// // MicropubStatusTests.swift // MuseionTests // // #206: the Micro.blog publish record. Scenario: // // Given a saved Post the writer sent to Micro.blog (the piece // remembers its post URL) // When the writer publishes it, sends it again, or Micro.blog has // lost the post // Then the piece remembers the publish (frontmatter // `micropub_published`, healing a link the send could not stamp) // and the library row can say // "published "; a re-send UPDATES the remembered post in // place — same URL, no second post, no second upload for an // unchanged image — and leaves the publish date alone; a 404 (the // post deleted on Micro.blog) clears the link so the piece can go // out as a fresh draft. Nothing is stamped on any failure, and a forget that // cannot land says so — never a "cleared" the disk contradicts. // // Wire facts (microblog.dev/api/posting, 2026-12-04): // `action=update` with `replace` sets name and content; updates // answer 200 with an empty body and 404 when `url` is not on the // blog. The media listing carries no content hash, so upload dedup // is a local memo keyed by the asset's bytes. // // A file from outside brings none of this: the import boundary drops // Museion's micropub keys, so a foreign `micropub_url` can never aim // a send at one of the writer's posts. // import Foundation @testable import Museion import Testing @Suite("MicropubStatusTests") struct MicropubStatusTests { /// A fresh piece with extra frontmatter lines planted after the /// owned keys; returns its id. private func piece(_ home: URL, frontmatter: String = "") throws -> String { let post = try PostStore.writeNew(body: "# Titled\n\nBody.", home: home) if !frontmatter.isEmpty { let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md")) let raw = try String(contentsOf: fileURL, encoding: .utf8) try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\n" + frontmatter) .write(to: fileURL, atomically: true, encoding: .utf8) } return post.id } // MARK: The record on disk @Test func `row status reads nil draft or published from the frontmatter`() throws { let home = try storeHome() defer { try? FileManager.default.removeItem(at: home) } let live = try piece( home, frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2026-12-04T15:02:00\n", ) let draft = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/draft\n") let untouched = try piece(home) // A stamp that isn't the stamp shape never reads as a publish. let broken = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/broken\nmicropub_published: yesterday\n") let posts = Post.scan(home: home) #expect(posts.first { $0.id == live }?.micropubStatus == "published Dec 4, 2026") #expect(posts.first { $0.id == draft }?.micropubStatus == "draft on Micro.blog") #expect(posts.first { $0.id == untouched }?.micropubStatus == nil) #expect(posts.first { $0.id == broken }?.micropubStatus == "draft on Micro.blog") } @Test func `an imported piece brings no micro.blog memory`() throws { let home = try storeHome() defer { try? FileManager.default.removeItem(at: home) } let source = home.appendingPathComponent("guest.md") try """ --- title: Guest micropub_url: https://example.micro.blog/someone-elses-live-post micropub_published: 2026-01-01T00:00:00 --- # Guest Body. """.write(to: source, atomically: true, encoding: .utf8) // A foreign file's remembered URL would aim the next send's // content replace at whatever post it names, under the writer's // token — so Museion's bookkeeping is ours to set, never theirs // to carry in (the way a foreign `origin` loses). let post = try PostStore.importFile(at: source, origin: .writer, home: home) let scanned = try #require(Post.scan(home: home).first { $0.id == post.id }) #expect(scanned.micropubURL == nil) #expect(scanned.micropubPublished == nil) #expect(scanned.micropubStatus == nil) let matter = try PostFrontmatter.parse(readPost(home, post.id)) #expect(matter["title"] == "Guest") // every other external key still rides verbatim #expect(matter["micropub_url"] == nil) // the line is gone, not merely emptied } @Test @MainActor func `publish remembers the date on the piece`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Stamped\n\nBody.", home: home) model.select(post.id) let url = "https://example.micro.blog/stamped" _ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog())) #expect(Post.scan(home: home).first?.micropubPublished == nil) // a draft is not a publish let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog())) #expect(outcome == .published) let scanned = try #require(Post.scan(home: home).first) let published = try #require(scanned.micropubPublished) #expect(abs(published.timeIntervalSinceNow) < 60) // stamped now, local time #expect(scanned.micropubURL == url) #expect(scanned.micropubStatus?.hasPrefix("published ") == true) } @Test @MainActor func `publish remembers a post whose send could not stamp it`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Unstamped\n\nBody.", home: home) model.select(post.id) let url = "https://example.micro.blog/unstamped" // The send lands, but its stamp cannot: the piece folder is // read-only for the moment (the sheet still holds the URL for // this session; the piece remembers nothing on disk). let dir = try #require(PostStore.folder(of: post.id, home: home)) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) } try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path) let sent = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog())) #expect(sent == .drafted(url: url, preview: nil)) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) #expect(Post.scan(home: home).first?.micropubURL == nil) // Publish writes the record AND heals the link the send couldn't. _ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog())) let scanned = try #require(Post.scan(home: home).first) #expect(scanned.micropubURL == url) #expect(scanned.micropubPublished != nil) } @Test @MainActor func `a failed publish stamps nothing`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Refused\n\nBody.", home: home) model.select(post.id) let outcome = await model.micropubPublish( url: "https://example.micro.blog/refused", token: "tok", transport: micropubCanned(500, log: MicropubRequestLog()), ) guard case let .requestFailed(status, _) = outcome else { Issue.record("expected requestFailed, got \(outcome)") return } #expect(status == 500) #expect(Post.scan(home: home).first?.micropubPublished == nil) } @Test @MainActor func `publish refuses a post address that is not a clean url`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Injected\n\nBody.", home: home) model.select(post.id) let log = MicropubRequestLog() // A newline in the address would close the frontmatter block on // the heal write — so nothing travels and nothing is remembered. let outcome = await model.micropubPublish( url: "https://example.micro.blog/live\nmicropub_published: 2020-01-01T00:00:00", token: "tok", transport: micropubCanned(200, log: log), ) guard case .refused = outcome else { Issue.record("expected refused, got \(outcome)") return } #expect(log.requests.isEmpty) let scanned = try #require(Post.scan(home: home).first) #expect(scanned.micropubURL == nil) #expect(scanned.micropubPublished == nil) } // MARK: A re-send updates the remembered post in place @Test func `update request is the in-place replace against the remembered url`() { let request = Micropub.makeUpdateRequest( url: "https://example.micro.blog/hello.html", title: "The Title", body: "The body.", 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?["name"] as? [String] == ["The Title"]) #expect(replace?["content"] as? [String] == ["The body."]) // Never a status flip — a draft stays a draft, a live post stays live. #expect(replace?["post-status"] == nil) } @Test @MainActor func `a re-send updates the remembered post and never creates a second`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Again\n\nFirst body.", home: home) model.select(post.id) let url = "https://example.micro.blog/again" _ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog())) model.session?.edit("# Again\n\nSecond body.") let log = MicropubRequestLog() let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log)) #expect(outcome == .updated(url: url)) let request = try #require(log.requests.first) let root = micropubJSON(request) #expect(root["action"] as? String == "update") // the create's `type`/`properties` never ride #expect(root["type"] == nil) #expect(root["url"] as? String == url) let replace = try #require(root["replace"] as? [String: Any]) #expect(replace["content"] as? [String] == ["# Again\n\nSecond body."]) #expect(Post.scan(home: home).first?.micropubURL == url) // the remembered URL never moves } @Test @MainActor func `a live update leaves the publish date alone`() async throws { let (model, home) = try makeModelHome() let live = try piece(home, frontmatter: "micropub_url: https://example.micro.blog/live\nmicropub_published: 2025-01-15T08:00:00\n") model.select(live) let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: MicropubRequestLog())) #expect(outcome == .updated(url: "https://example.micro.blog/live")) #expect(Post.scan(home: home).first?.micropubStatus == "published Jan 15, 2025") } // MARK: A re-send never re-uploads an unchanged image /// An illustrated piece, opened in the model; returns its folder /// (`MicropubModelTests` owns the planting — shared-helper convention). @MainActor private func illustratedPiece(_ model: PostsModel, _ home: URL) throws -> URL { try MicropubModelTests() .plantIllustratedPiece(model, home, body: "# Inked\n\n![A winding path.](assets/path.png)\n\nProse.") .deletingLastPathComponent() } @Test @MainActor func `an unchanged illustration rides its earlier upload`() async throws { let (model, home) = try makeModelHome() _ = try illustratedPiece(model, home) _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // config + upload + create let log = MicropubRequestLog() let outcome = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log)) // ONE request — the in-place update. No q=config, no upload. #expect(outcome == .updated(url: "https://example.micro.blog/inked")) #expect(log.requests.count == 1) let resent = try #require(log.request(0)) let replace = try #require(micropubJSON(resent)["replace"] as? [String: Any]) #expect((replace["content"] as? [String])?.first?.contains("![A winding path.](https://micro.blog/uploads/2026/ink.png)") == true) } @Test @MainActor func `a changed illustration uploads again`() async throws { let (model, home) = try makeModelHome() let dir = try illustratedPiece(model, home) _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // The writer replaces the image — same name, new bytes. let fresh = micropubPNG() + Data([0x7F]) try fresh.write(to: dir.appendingPathComponent("assets/path.png")) let log = MicropubRequestLog() _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log)) // config → upload → update, and the upload carries the NEW bytes. #expect(log.requests.count == 3) #expect(log.request(1)?.httpBody?.firstRange(of: fresh) != nil) } @Test @MainActor func `an untrustworthy memo url never rides the wire`() async throws { let (model, home) = try makeModelHome() let dir = try illustratedPiece(model, home) _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // The sidecar is disk, so external data: a planted http URL is // no memory at all. let memoURL = dir.appendingPathComponent(".museion-uploads.json") var memo = try JSONDecoder().decode([String: String].self, from: Data(contentsOf: memoURL)) let key = try #require(memo.keys.first) memo[key] = "http://evil.example/swap.png" try JSONEncoder().encode(memo).write(to: memoURL, options: .atomic) let log = MicropubRequestLog() _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log)) #expect(log.requests.count == 3) // re-uploaded rather than trusted let last = try #require(log.request(2)) let replace = try #require(micropubJSON(last)["replace"] as? [String: Any]) let content = try #require((replace["content"] as? [String])?.first) #expect(!content.contains("evil.example")) #expect(content.contains("https://micro.blog/uploads/2026/ink.png")) } @Test @MainActor func `a symlinked upload memo is no memory at all`() async throws { let (model, home) = try makeModelHome() let dir = try illustratedPiece(model, home) _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: MicropubRequestLog())) // the real memo lands // Planted: the sidecar becomes a link to a memo OUTSIDE the piece // that names this image's bytes with an attacker-chosen URL. let memoURL = dir.appendingPathComponent(".museion-uploads.json") try FileManager.default.removeItem(at: memoURL) let outside = home.appendingPathComponent("planted-memo.json") let planted = [Micropub.uploadKey(micropubPNG()): "https://micro.blog/uploads/2026/planted.png"] try JSONEncoder().encode(planted).write(to: outside, options: .atomic) try FileManager.default.createSymbolicLink(at: memoURL, withDestinationURL: outside) let log = MicropubRequestLog() _ = await model.micropubSend(token: "tok", transport: micropubMediaScripted(log: log)) #expect(log.requests.count == 3) // config → a fresh upload → the update let last = try #require(log.request(2)) let replace = try #require(micropubJSON(last)["replace"] as? [String: Any]) let content = try #require((replace["content"] as? [String])?.first) #expect(!content.contains("planted.png")) } // MARK: A post Micro.blog lost @Test @MainActor func `a post micro.blog lost is forgotten named and sendable again`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Gone\n\nBody.", home: home) model.select(post.id) let url = "https://example.micro.blog/gone" _ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog())) // The writer deleted the draft on Micro.blog; the next send hears 404. let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog())) guard case let .forgotten(reason) = outcome else { Issue.record("expected forgotten, got \(outcome)") return } #expect(reason.contains("deleted")) let forgotten = try #require(Post.scan(home: home).first) #expect(forgotten.micropubURL == nil) // no dead link left on the piece #expect(forgotten.micropubStatus == nil) // Recovery: with nothing remembered, the next send is a fresh draft. let log = MicropubRequestLog() _ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: log)) let created = try #require(log.request(0)) #expect(micropubJSON(created)["action"] == nil) // a create, not an update #expect(Post.scan(home: home).first?.micropubURL == url) } @Test @MainActor func `a lost live post takes the publish record with it`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Vanish\n\nBody.", home: home) model.select(post.id) let url = "https://example.micro.blog/vanish" _ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog())) _ = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(200, log: MicropubRequestLog())) #expect(Post.scan(home: home).first?.micropubPublished != nil) // the record exists // The post is deleted on Micro.blog; the next word there is 404. let outcome = await model.micropubPublish(url: url, token: "tok", transport: micropubCanned(404, log: MicropubRequestLog())) guard case .forgotten = outcome else { Issue.record("expected forgotten, got \(outcome)") return } #expect(Post.scan(home: home).first?.micropubURL == nil) #expect(Post.scan(home: home).first?.micropubPublished == nil) } @Test @MainActor func `publish refuses a piece that is not the open one`() async throws { let (model, home) = try makeModelHome() _ = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never selected let log = MicropubRequestLog() let outcome = await model.micropubPublish( url: "https://example.micro.blog/unopened", token: "tok", transport: micropubCanned(200, log: log), ) guard case .refused = outcome else { Issue.record("expected refused, got \(outcome)") return } #expect(log.requests.isEmpty) // nothing went out #expect(Post.scan(home: home).first?.micropubPublished == nil) // and nothing was remembered for it } @Test @MainActor func `a forget that cannot write says so instead of claiming the link is cleared`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Stuck\n\nBody.", home: home) model.select(post.id) let url = "https://example.micro.blog/stuck" _ = await model.micropubSend(token: "tok", transport: micropubCanned(201, headers: ["Location": url], log: MicropubRequestLog())) // The piece folder goes read-only: the forget cannot land. let dir = try #require(PostStore.folder(of: post.id, home: home)) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) } try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path) let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(404, log: MicropubRequestLog())) guard case let .refused(reason) = outcome else { Issue.record("expected refused, got \(outcome)") return } #expect(reason.contains("couldn't be cleared")) #expect(Post.scan(home: home).first?.micropubURL == url) // still on the piece — and said to be } }