CI / ci (push) Canceled after 0s
Two-step publish to Micro.blog over Micropub: Send as Draft (JSON h=entry create — name = the Title, markdown content verbatim, post-status draft), review via the preview link, then Publish (the action=update post-status flip). The piece remembers its draft URL as a frontmatter micropub_url stamp — in-place, body and foreign keys byte-identical — so a draft survives a reopen; Send Again re-drafts after edits. The app token lives in the Keychain (login keychain; entered once in the sheet, re-offered only on auth failure — ADR-0014's no-Keychain rule covers only provider keys hermes reads from .env). Frontmatter category: is permitted but never sent in v1 — pinned on the wire. The draft URL is trust-boundary data landing in frontmatter, so every URL passes a format gate (https + host, no line/control characters) at BOTH ends: the response decode (Location header → body url; the preview link is display-only, never the publish target) and Post.scan's read-back — imported frontmatter rides verbatim, and a newline--- rider would otherwise close the block and reparse as attacker markdown in the writer's piece. Twenty tests pin the wire contract, decode matrix, own-slot keychain round-trip, stamp/scan, and the model flow (flush-first, refusal guards, the category AC); all four audit guards are flip-verified. Full suite 529 passed / 0 failed. Live end-to-end on a real post (needs the owner's app token) remains open on the ticket.
322 lines
12 KiB
Swift
322 lines
12 KiB
Swift
//
|
|
// MicropubTests.swift
|
|
// MuseionTests
|
|
//
|
|
// #33 (S6.1): Micropub draft → publish. Scenario:
|
|
//
|
|
// Given a saved Post open in the editor and a Micro.blog app token
|
|
// entered once (Keychain)
|
|
// When the writer sends the piece as a draft, reviews it, then
|
|
// confirms publish
|
|
// Then Micro.blog receives an h=entry create (markdown content, name,
|
|
// post-status=draft) followed by an update flipping post-status to
|
|
// published — the piece's frontmatter `category:` never travels, and
|
|
// the draft URL is remembered on the piece.
|
|
//
|
|
// Wire facts live-verified against microblog.dev/api/posting and
|
|
// Micro.blog's Micropub docs (2026-10-31): JSON create reads
|
|
// type/properties; `post-status: draft` creates a draft whose final
|
|
// URL arrives in the Location header (body carries url + preview);
|
|
// publishing the draft is `action=update` + `replace.post-status
|
|
// published` (JSON only).
|
|
//
|
|
|
|
import Foundation
|
|
@testable import Museion
|
|
import Testing
|
|
|
|
// MARK: Shared helpers (shared-helper convention)
|
|
|
|
/// Records every request a canned transport saw, thread-safely.
|
|
final class MicropubRequestLog: @unchecked Sendable {
|
|
private let lock = NSLock()
|
|
private var items: [URLRequest] = []
|
|
|
|
func append(_ request: URLRequest) {
|
|
lock.lock()
|
|
items.append(request)
|
|
lock.unlock()
|
|
}
|
|
|
|
var requests: [URLRequest] {
|
|
lock.lock()
|
|
defer { lock.unlock() }
|
|
return items
|
|
}
|
|
}
|
|
|
|
nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse {
|
|
HTTPURLResponse(
|
|
url: Micropub.endpoint,
|
|
statusCode: status,
|
|
httpVersion: "HTTP/1.1",
|
|
headerFields: headers,
|
|
)!
|
|
}
|
|
|
|
/// A canned transport that always answers `(status, body, headers)` and
|
|
/// logs the requests it served.
|
|
nonisolated func micropubCanned(
|
|
_ status: Int,
|
|
body: String = "{}",
|
|
headers: [String: String]? = nil,
|
|
log: MicropubRequestLog,
|
|
) -> Micropub.Transport {
|
|
{ request in
|
|
log.append(request)
|
|
return (Data(body.utf8), micropubHTTP(status, headers: headers))
|
|
}
|
|
}
|
|
|
|
nonisolated func micropubJSON(_ request: URLRequest) -> [String: Any] {
|
|
guard let data = request.httpBody else { return [:] }
|
|
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
|
|
}
|
|
|
|
@Suite("MicropubTests")
|
|
struct MicropubTests {
|
|
// MARK: Request shapes (the wire contract)
|
|
|
|
@Test func `draft request is an h-entry create with name content and post-status draft`() {
|
|
let request = Micropub.makeDraftRequest(title: "The Title", body: "The body.", token: "tok")
|
|
|
|
#expect(request.url == Micropub.endpoint)
|
|
#expect(request.httpMethod == "POST")
|
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
|
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
|
|
|
|
let root = micropubJSON(request)
|
|
#expect(root["type"] as? [String] == ["h-entry"])
|
|
let props = root["properties"] as? [String: Any]
|
|
#expect(props?["name"] as? [String] == ["The Title"])
|
|
#expect(props?["content"] as? [String] == ["The body."])
|
|
#expect(props?["post-status"] as? [String] == ["draft"])
|
|
}
|
|
|
|
@Test func `publish request is the post-status update against the draft url`() {
|
|
let request = Micropub.makePublishRequest(url: "https://example.micro.blog/hello.html", token: "tok")
|
|
|
|
#expect(request.url == Micropub.endpoint)
|
|
#expect(request.httpMethod == "POST")
|
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
|
|
|
let root = micropubJSON(request)
|
|
#expect(root["action"] as? String == "update")
|
|
#expect(root["url"] as? String == "https://example.micro.blog/hello.html")
|
|
let replace = root["replace"] as? [String: Any]
|
|
#expect(replace?["post-status"] as? [String] == ["published"])
|
|
}
|
|
|
|
// MARK: Outcome decoding over canned transports
|
|
|
|
@Test func `sendDraft reads Location then body url and carries the preview`() async {
|
|
let log = MicropubRequestLog()
|
|
let headers = ["Location": "https://example.micro.blog/hello.html"]
|
|
let body = #"{"url":"https://ignored.example/should-not-win","preview":"https://micro.blog/account/posts/1/preview/2"}"#
|
|
let outcome = await Micropub.sendDraft(
|
|
title: "T", body: "B", token: "tok",
|
|
transport: micropubCanned(201, body: body, headers: headers, log: log),
|
|
)
|
|
#expect(outcome == .drafted(url: "https://example.micro.blog/hello.html", preview: "https://micro.blog/account/posts/1/preview/2"))
|
|
|
|
// No Location header → the body's url is the fallback.
|
|
let fallback = await Micropub.sendDraft(
|
|
title: "T", body: "B", token: "tok",
|
|
transport: micropubCanned(200, body: #"{"url":"https://example.micro.blog/from-body"}"#, log: log),
|
|
)
|
|
#expect(fallback == .drafted(url: "https://example.micro.blog/from-body", preview: nil))
|
|
}
|
|
|
|
@Test func `a create with no url anywhere is a request failure not a silent success`() async {
|
|
let log = MicropubRequestLog()
|
|
let outcome = await Micropub.sendDraft(
|
|
title: "T", body: "B", token: "tok",
|
|
transport: micropubCanned(200, body: "{}", log: log),
|
|
)
|
|
guard case let .requestFailed(status, _) = outcome else {
|
|
Issue.record("expected requestFailed, got \(outcome)")
|
|
return
|
|
}
|
|
#expect(status == 200)
|
|
}
|
|
|
|
@Test func `a draft url carrying injection characters is refused not stamped`() async {
|
|
// #33 audit: the URL is trust-boundary data — a `\n---` riding
|
|
// it would close the frontmatter block on the next parse and
|
|
// re-parse as BODY. The JSON carries the ESCAPED form (valid
|
|
// JSON); the decode yields real newlines at the guard — the
|
|
// refusal is the guard's, not a parse failure's.
|
|
let log = MicropubRequestLog()
|
|
let outcome = await Micropub.sendDraft(
|
|
title: "T", body: "# B\n\nBody.", token: "tok",
|
|
transport: micropubCanned(201, body: "{\"url\":\"https://x.example/a\\n---\\ninjected\"}", log: log),
|
|
)
|
|
guard case .requestFailed = outcome else {
|
|
Issue.record("expected requestFailed for the injected URL, got \(outcome)")
|
|
return
|
|
}
|
|
}
|
|
|
|
@Test func `preview never becomes the publish target`() async {
|
|
let log = MicropubRequestLog()
|
|
// Location AND body url absent — only a preview URL rides the
|
|
// body. Display-only: the outcome must not adopt it.
|
|
let outcome = await Micropub.sendDraft(
|
|
title: "T", body: "B", token: "tok",
|
|
transport: micropubCanned(200, body: #"{"preview":"https://micro.blog/account/posts/1/preview/2"}"#, log: log),
|
|
)
|
|
guard case .requestFailed = outcome else {
|
|
Issue.record("expected requestFailed, got \(outcome)")
|
|
return
|
|
}
|
|
}
|
|
|
|
@Test func `auth failures decode with the error description`() async {
|
|
let log = MicropubRequestLog()
|
|
let body = #"{"error":"forbidden","error_description":"token not authorized"}"#
|
|
let outcome = await Micropub.sendDraft(
|
|
title: "T", body: "B", token: "tok",
|
|
transport: micropubCanned(401, body: body, log: log),
|
|
)
|
|
guard case let .authFailed(detail) = outcome else {
|
|
Issue.record("expected authFailed, got \(outcome)")
|
|
return
|
|
}
|
|
#expect(detail.contains("token not authorized"))
|
|
|
|
let update = await Micropub.publish(
|
|
url: "https://example.micro.blog/hello.html", token: "tok",
|
|
transport: micropubCanned(403, body: body, log: log),
|
|
)
|
|
guard case .authFailed = update else {
|
|
Issue.record("expected authFailed, got \(update)")
|
|
return
|
|
}
|
|
}
|
|
|
|
@Test func `non-2xx maps to requestFailed and transport errors to unreachable`() async {
|
|
let log = MicropubRequestLog()
|
|
let outcome = await Micropub.sendDraft(
|
|
title: "T", body: "B", token: "tok",
|
|
transport: micropubCanned(500, body: "{}", log: log),
|
|
)
|
|
guard case let .requestFailed(status, _) = outcome else {
|
|
Issue.record("expected requestFailed, got \(outcome)")
|
|
return
|
|
}
|
|
#expect(status == 500)
|
|
|
|
let dead: Micropub.Transport = { _ in throw URLError(.notConnectedToInternet) }
|
|
let unreachable = await Micropub.publish(url: "https://x.example/", token: "tok", transport: dead)
|
|
guard case .unreachable = unreachable else {
|
|
Issue.record("expected unreachable, got \(unreachable)")
|
|
return
|
|
}
|
|
}
|
|
|
|
@Test func `publish outcome is published on 2xx`() async {
|
|
let log = MicropubRequestLog()
|
|
let outcome = await Micropub.publish(
|
|
url: "https://example.micro.blog/hello.html", token: "tok",
|
|
transport: micropubCanned(200, body: "", log: log),
|
|
)
|
|
#expect(outcome == .published)
|
|
}
|
|
|
|
// MARK: Keychain token store (entered once)
|
|
|
|
@Test func `token store round-trips through the login keychain`() {
|
|
// #33 audit: the suite runs against its OWN slot — a real live
|
|
// token in the production account is never read, replaced, or
|
|
// (on a locked keychain's nil read) deleted by cleanup.
|
|
let slot = "museion-tests-\(UUID().uuidString)"
|
|
defer { MicropubTokenStore.delete(account: slot) }
|
|
|
|
#expect(MicropubTokenStore.read(account: slot) == nil)
|
|
|
|
MicropubTokenStore.save("test-token-abc", account: slot)
|
|
#expect(MicropubTokenStore.read(account: slot) == "test-token-abc")
|
|
|
|
// Re-save replaces (rotation), never duplicates.
|
|
MicropubTokenStore.save("test-token-xyz", account: slot)
|
|
#expect(MicropubTokenStore.read(account: slot) == "test-token-xyz")
|
|
|
|
MicropubTokenStore.delete(account: slot)
|
|
#expect(MicropubTokenStore.read(account: slot) == nil)
|
|
}
|
|
|
|
// MARK: The stamp + scan (the remembered draft URL)
|
|
|
|
@Test func `stampMicropubURL stamps in place and scan reads it back`() throws {
|
|
let home = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
|
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: home) }
|
|
|
|
let post = try PostStore.writeNew(
|
|
body: "# Kept Title\n\nBody byte-preserved.",
|
|
home: home,
|
|
)
|
|
// A foreign key rides along — the stamp must not disturb it.
|
|
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
|
try [
|
|
"---",
|
|
"type: post",
|
|
"pass_state: First Draft",
|
|
"origin: writer",
|
|
"category: Essays",
|
|
"---",
|
|
"",
|
|
"# Kept Title",
|
|
"",
|
|
"Body byte-preserved.",
|
|
].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8)
|
|
let before = try String(contentsOf: fileURL, encoding: .utf8)
|
|
|
|
try PostStore.stampMicropubURL(id: post.id, url: "https://example.micro.blog/hello.html", home: home)
|
|
|
|
let after = try String(contentsOf: fileURL, encoding: .utf8)
|
|
#expect(after.contains("micropub_url: https://example.micro.blog/hello.html"))
|
|
#expect(after.contains("category: Essays")) // foreign keys survive
|
|
// The BODY is byte-identical — only the frontmatter block grew a line.
|
|
#expect(after.components(separatedBy: "---\n").last == before.components(separatedBy: "---\n").last)
|
|
|
|
let scanned = Post.scan(home: home).first
|
|
#expect(scanned?.micropubURL == "https://example.micro.blog/hello.html")
|
|
#expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else
|
|
}
|
|
|
|
@Test func `stampMicropubURL throws on a vanished piece`() throws {
|
|
let home = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
|
#expect(throws: (any Error).self) {
|
|
try PostStore.stampMicropubURL(id: "ghost", url: "https://x.example/", home: home)
|
|
}
|
|
}
|
|
|
|
@Test func `scan reads an untrustworthy micropub_url as nil`() throws {
|
|
let home = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
|
|
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
|
|
defer { try? FileManager.default.removeItem(at: home) }
|
|
|
|
let post = try PostStore.writeNew(body: "# Imported\n\nBody.", home: home)
|
|
let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md"))
|
|
let raw = try String(contentsOf: fileURL, encoding: .utf8)
|
|
// #33 audit: imported frontmatter rides verbatim — a hostile
|
|
// value must never pre-arm the publish sheet. The scan parse is
|
|
// line-bounded (a newline can't ride one value); the vectors
|
|
// here are a non-URL value and a control character.
|
|
try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\nmicropub_url: not a url\n")
|
|
.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
|
|
#expect(Post.scan(home: home).first?.micropubURL == nil)
|
|
|
|
// A clean hand-edited value still reads back (format-only gate).
|
|
let clean = try String(contentsOf: fileURL, encoding: .utf8)
|
|
try clean.replacingOccurrences(of: "micropub_url: not a url\n", with: "micropub_url: https://example.micro.blog/imported\n")
|
|
.write(to: fileURL, atomically: true, encoding: .utf8)
|
|
#expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/imported")
|
|
}
|
|
}
|