Files
museion/MuseionTests/MicropubTests.swift
T
AlexKucera 6aa31a419a feat(microblog): show Micro.blog publish status
The publish sheet flipped a draft live and remembered nothing, so
nothing on disk said a piece was out and the library could not show
it. A successful Publish now stamps `micropub_published` in the
piece's frontmatter; the row and the sheet read `published <date>`
or `draft on Micro.blog`, and a published piece's menu opens the
live post.

Sending a piece again no longer creates a second post: a piece that
remembers its post updates it in place (name and content only, so
categories set on Micro.blog survive). An image whose bytes are
unchanged rides its earlier upload through a per-piece memo. When
Micro.blog answers 404 the piece forgets both keys and the sheet
offers a fresh draft; a clear that cannot land says so instead of
claiming the link is gone.

Museion's micropub keys are dropped at the import boundary. An
imported `micropub_url` passes the format gate and would aim the
in-place update at one of the writer's own posts under their token,
so the keys are treated like `origin`: ours to set, never a foreign
file's to carry in. Publish is model-owned and trust-gates its URL
before anything is stamped.

Tests read recorded requests through an optional accessor: an
out-of-range subscript after a failed count expectation trapped the
hosted runner and reported every queued test as crashed.

+16 tests net (17 new pins in MicropubStatusTests, one retired whose
premise the in-place design voids); every new pin was watched fail
on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean.
Reviews: standards + spec during the build, then a three-reviewer
finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY
terms, CHANGELOG [Unreleased], README, and the devlog.

Closes #206
2026-12-04 17:45:35 +01:00

353 lines
14 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
}
/// The request at `index`, nil when fewer traveled. Read recorded
/// requests through here, never `requests[index]`: an out-of-range
/// subscript TRAPS, one trap kills the hosted runner, and every
/// queued test reports `Crash:` beside it (#206 flip cycle). A nil
/// here fails the pin's OWN expectation — `#require` it when the
/// value feeds a non-optional parameter.
func request(_ index: Int) -> URLRequest? {
lock.lock()
defer { lock.unlock() }
return index < items.count ? items[index] : nil
}
}
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 `a 5xx names micro.blog's outage not a bare status`() {
// Their errors arrive as HTML pages, so the JSON decode finds
// nothing — a 503 over that body names their side; a 4xx keeps
// the bare status; a described 5xx keeps the description.
let html = Data("<html><body>503 Service Unavailable</body></html>".utf8)
let outage = Micropub.decodeFailure(status: 503, body: html)
guard case let .requestFailed(status, detail) = outage else {
Issue.record("expected requestFailed, got \(outage)")
return
}
#expect(status == 503)
#expect(detail.contains("their side"))
let bare = Micropub.decodeFailure(status: 422, body: html)
#expect(bare == .requestFailed(status: 422, detail: "HTTP 422"))
let described = Micropub.decodeFailure(status: 502, body: Data(#"{"error_description":"upstream timeout"}"#.utf8))
#expect(described == .requestFailed(status: 502, detail: "upstream timeout"))
}
@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 `stampMicropub 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.stampMicropub(post.id, home: home, [("micropub_url", "https://example.micro.blog/hello.html")])
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 `stampMicropub throws on a vanished piece`() throws {
let home = FileManager.default.temporaryDirectory
.appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true)
#expect(throws: (any Error).self) {
try PostStore.stampMicropub("ghost", home: home, [("micropub_url", "https://x.example/")])
}
}
@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")
}
}