CI / ci (push) Canceled after 0s
A piece's assets/ ink-sketch images publish with it: Send as Draft first uploads every referenced image to Micro.blog's media endpoint (q=config discovery, one multipart file POST per FILE — duplicate refs share an upload), then each  ref REWRITES IN PLACE with its uploaded URL in the wire content. The image renders exactly where the writer placed it and the alt rides the markdown; the piece on disk never changes. The first shape attached uploads as a Micropub photo property with mp-photo-alt — live dogfood (2026-11-01) showed the theme renders properties at the bottom of the post, losing position. No property ships at all now; inline refs are the only transport, which also makes the parsed body ref the only way an image ships — the alt floor at the illustration rail is therefore the only gate a photo needs (G12: a whitespace-empty alt refuses naming the file before anything touches the wire; the mentor is never consulted). Pre-flight gates every payload: the endpoint's exact formats (PNG/JPEG/GIF/WebP/SVG), path containment resolved through symlinks (a planted link never uploads outside-file bytes under the writer's token), all-or-nothing uploads. A URL carrying markdown-active characters rides the angle form  — a plain-paren destination would close at the first ) and smuggle a live link into the published post; the frontmatter trust gate does not cover markdown's grammar. Finish-audit (three reviewers) drove the angle form, the symlink containment, the per-file upload dedup, and four pins; all four behavior guards flip-verified in one batch cycle. Suite 546 passed / 0 failed; swiftformat + swiftlint clean. Ingest UX (drop image onto the editor) is #141, blocked by this issue.
296 lines
12 KiB
Swift
296 lines
12 KiB
Swift
//
|
|
// MicropubMediaTests.swift
|
|
// MuseionTests
|
|
//
|
|
// #34 (S6.2): illustrations travel with it. Scenario:
|
|
//
|
|
// Given a saved Post whose body references ink-sketch PNGs from its
|
|
// assets/ with alt text
|
|
// When the writer sends the piece as a draft and publishes
|
|
// Then each PNG uploads once via the media endpoint (q=config →
|
|
// multipart → 202 + Location) and its ref REWRITES IN PLACE with
|
|
// the uploaded URL — the image renders exactly where the writer
|
|
// placed it, alt travels in the markdown — and a photo without
|
|
// alt text never ships: the send refuses naming the illustration
|
|
// before anything touches the wire.
|
|
// The mentor never assesses images (G12) — the flow consults no
|
|
// engine anywhere.
|
|
//
|
|
// Wire facts (microblog.dev/api/posting, book.micro.blog/micropub):
|
|
// `q=config` names the media endpoint; `POST /micropub/media`
|
|
// multipart → 202 + Location = the upload URL. No photo property:
|
|
// it renders wherever the THEME decides, not where placed
|
|
// (live-verified 2026-11-01 — bottom of the post, position lost).
|
|
//
|
|
|
|
import Foundation
|
|
@testable import Museion
|
|
import Testing
|
|
|
|
// MARK: Shared helpers (shared-helper convention)
|
|
|
|
/// A tiny deterministic PNG payload — the client never inspects the
|
|
/// bytes (the server does); tests only need recognizable ones.
|
|
nonisolated func micropubPNG() -> Data {
|
|
Data([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x01, 0x02, 0x03])
|
|
}
|
|
|
|
/// A transport that routes the #34 three-step flow by target:
|
|
/// q=config → media upload → create. Records every request it served.
|
|
nonisolated func micropubMediaScripted(log: MicropubRequestLog) -> Micropub.Transport {
|
|
{ request in
|
|
log.append(request)
|
|
let target = request.url?.absoluteString ?? ""
|
|
if target.contains("q=config") {
|
|
return (Data(#"{"media-endpoint":"https://micro.blog/micropub/media"}"#.utf8), micropubHTTP(200))
|
|
}
|
|
if target.contains("/micropub/media") {
|
|
return (Data("{}".utf8), micropubHTTP(202, headers: ["Location": "https://micro.blog/uploads/2026/ink.png"]))
|
|
}
|
|
return (Data("{}".utf8), micropubHTTP(201, headers: ["Location": "https://example.micro.blog/inked"]))
|
|
}
|
|
}
|
|
|
|
@Suite("MicropubMediaTests")
|
|
struct MicropubMediaTests {
|
|
// MARK: Parsing the body's illustration refs (G12: plain refs into assets/)
|
|
|
|
@Test func `illustrations finds asset refs and leaves foreign images alone`() {
|
|
let body = """
|
|
# Title
|
|
|
|
Prose with  inside.
|
|
|
|

|
|
|
|

|
|
|
|

|
|
|
|

|
|
"""
|
|
let found = Micropub.illustrations(in: body)
|
|
// Honest parse: every assets/ ref, alt captured verbatim (the
|
|
// floor judges trimmed emptiness — the parse never hides one).
|
|
#expect(found == [
|
|
.init(alt: "an inline ref", destination: "assets/inline.png"),
|
|
.init(alt: "A winding path.", destination: "assets/path.png"),
|
|
.init(alt: "", destination: "assets/blank.png"),
|
|
])
|
|
}
|
|
|
|
@Test func `rewriting swaps each ref for its uploaded url in place`() {
|
|
let body = """
|
|
# Title
|
|
|
|
Prose with  inside.
|
|
|
|

|
|
|
|

|
|
|
|

|
|
|
|

|
|
"""
|
|
let wire = Micropub.rewritingIllustrations(body, uploaded: [
|
|
"assets/inline.png": "https://micro.blog/uploads/a.png",
|
|
"assets/path.png": "https://micro.blog/uploads/b.png",
|
|
])
|
|
// Position is the writer's: each ref rewrites exactly where it
|
|
// stands, alt + surrounding text verbatim; foreign images and
|
|
// refs without an upload stay put; a quoted title drops.
|
|
#expect(wire.contains("Prose with  inside."))
|
|
#expect(wire.contains(""))
|
|
#expect(wire.contains(""))
|
|
#expect(wire.contains(""))
|
|
#expect(wire.contains(""))
|
|
#expect(wire.hasPrefix("# Title"))
|
|
// Only the uploaded refs' assets/ destinations leave.
|
|
#expect(!wire.contains("assets/inline.png"))
|
|
#expect(!wire.contains("assets/path.png"))
|
|
}
|
|
|
|
@Test func `mime types cover the media endpoint's formats and refuse the rest`() {
|
|
#expect(Micropub.mimeType(forDestination: "assets/ink.png") == "image/png")
|
|
#expect(Micropub.mimeType(forDestination: "assets/ink.PNG") == "image/png")
|
|
#expect(Micropub.mimeType(forDestination: "assets/photo.jpeg") == "image/jpeg")
|
|
#expect(Micropub.mimeType(forDestination: "assets/anim.gif") == "image/gif")
|
|
#expect(Micropub.mimeType(forDestination: "assets/modern.webp") == "image/webp")
|
|
#expect(Micropub.mimeType(forDestination: "assets/vector.svg") == "image/svg+xml")
|
|
#expect(Micropub.mimeType(forDestination: "assets/note.md") == nil)
|
|
}
|
|
|
|
@Test func `a url carrying markdown-active characters rides the angle form`() {
|
|
// The uploaded URL is server-controlled data landing in the
|
|
// wire body as markdown — a `)` in a plain-paren destination
|
|
// would close the image early and smuggle a live attacker
|
|
// link into the post (the trustworthyURL gate was built for
|
|
// frontmatter, not this sink). Angle form caps the worst
|
|
// case at broken rendering.
|
|
let wire = Micropub.rewritingIllustrations(
|
|
"",
|
|
uploaded: ["assets/a.png": "https://x.example/x)[evil](https://evil.example"],
|
|
)
|
|
#expect(wire == "[evil](https://evil.example>)")
|
|
// A clean URL keeps the plain form (pinned by the rewrite test).
|
|
}
|
|
|
|
@Test func `rewriting passes through untouched bodies and handles boundary refs`() {
|
|
// Empty map (and all-matches-skipped — same guard) returns the
|
|
// body verbatim; adjacent refs at string start/end rewrite
|
|
// with clean cursor math.
|
|
let adjacent = ""
|
|
#expect(Micropub.rewritingIllustrations(adjacent, uploaded: [:]) == adjacent)
|
|
let one = Micropub.rewritingIllustrations(adjacent, uploaded: ["assets/a.png": "https://micro.blog/uploads/a.png"])
|
|
#expect(one == "")
|
|
}
|
|
|
|
@Test func `a multi-line alt never parses so both passes agree`() {
|
|
// A ref whose alt spans lines must NOT parse — if it parsed but
|
|
// didn't rewrite, the local assets/ ref would ride the wire as
|
|
// a broken relative link. It rides as prose, never uploaded.
|
|
let body = "# Title\n\n\n\n"
|
|
#expect(Micropub.illustrations(in: body) == [.init(alt: "fine", destination: "assets/ok.png")])
|
|
let wire = Micropub.rewritingIllustrations(body, uploaded: [
|
|
"assets/path.png": "https://micro.blog/uploads/a.png",
|
|
"assets/ok.png": "https://micro.blog/uploads/b.png",
|
|
])
|
|
#expect(wire.contains("")) // untouched
|
|
#expect(wire.contains("")) // the well-formed ref still rewrites
|
|
}
|
|
|
|
// MARK: q=config (hop 1)
|
|
|
|
@Test func `config request asks the endpoint for its media endpoint`() {
|
|
let request = Micropub.makeConfigRequest(token: "tok")
|
|
let components = URLComponents(url: request.url ?? Micropub.endpoint, resolvingAgainstBaseURL: false)
|
|
#expect(components?.queryItems?.contains(URLQueryItem(name: "q", value: "config")) == true)
|
|
#expect(request.httpMethod == nil || request.httpMethod == "GET") // GET is the default
|
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
|
}
|
|
|
|
@Test func `mediaEndpoint decodes the discovered endpoint and refuses honestly`() async {
|
|
let log = MicropubRequestLog()
|
|
// The named endpoint, trust-gated.
|
|
let named = await Micropub.mediaEndpoint(
|
|
token: "tok",
|
|
transport: micropubCanned(200, body: #"{"media-endpoint":"https://micro.blog/micropub/media"}"#, log: log),
|
|
)
|
|
#expect(named == .url("https://micro.blog/micropub/media"))
|
|
|
|
// A config that names nothing usable is a failed request, never
|
|
// a silent default.
|
|
let bare = await Micropub.mediaEndpoint(token: "tok", transport: micropubCanned(200, body: "{}", log: log))
|
|
guard case .failed(.requestFailed) = bare else {
|
|
Issue.record("expected requestFailed, got \(bare)")
|
|
return
|
|
}
|
|
|
|
// An injection-carrying endpoint is refused (the writer's PNG
|
|
// and token would POST to it) — the trustworthyURL gate.
|
|
let hostile = await Micropub.mediaEndpoint(
|
|
token: "tok",
|
|
transport: micropubCanned(200, body: "{\"media-endpoint\":\"https://x.example/a\\n---\\ninjected\"}", log: log),
|
|
)
|
|
guard case .failed(.requestFailed) = hostile else {
|
|
Issue.record("expected requestFailed for the injected endpoint, got \(hostile)")
|
|
return
|
|
}
|
|
|
|
let denied = await Micropub.mediaEndpoint(
|
|
token: "tok",
|
|
transport: micropubCanned(401, body: #"{"error_description":"bad token"}"#, log: log),
|
|
)
|
|
guard case .failed(.authFailed) = denied else {
|
|
Issue.record("expected authFailed, got \(denied)")
|
|
return
|
|
}
|
|
}
|
|
|
|
// MARK: The multipart upload (hop 2)
|
|
|
|
@Test func `media upload request is a multipart file post to the discovered endpoint`() {
|
|
let request = Micropub.makeMediaUploadRequest(
|
|
mediaEndpoint: "https://micro.blog/micropub/media",
|
|
filename: "ink.png",
|
|
mimeType: "image/png",
|
|
data: micropubPNG(),
|
|
token: "tok",
|
|
)
|
|
#expect(request.url?.absoluteString == "https://micro.blog/micropub/media")
|
|
#expect(request.httpMethod == "POST")
|
|
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok")
|
|
let contentType = request.value(forHTTPHeaderField: "Content-Type") ?? ""
|
|
#expect(contentType.hasPrefix("multipart/form-data; boundary="))
|
|
let boundary = contentType.components(separatedBy: "boundary=").last ?? ""
|
|
|
|
// The multipart shape, asserted over bytes: part head, payload,
|
|
// closing delimiter.
|
|
let body = request.httpBody ?? Data()
|
|
let head = Data((
|
|
"--\(boundary)\r\n"
|
|
+ "Content-Disposition: form-data; name=\"file\"; filename=\"ink.png\"\r\n"
|
|
+ "Content-Type: image/png\r\n\r\n"
|
|
).utf8)
|
|
#expect(body.firstRange(of: head) != nil)
|
|
#expect(body.firstRange(of: micropubPNG()) != nil) // the bytes ride intact
|
|
#expect(body.suffix(Data("--\(boundary)--\r\n".utf8).count) == Data("--\(boundary)--\r\n".utf8))
|
|
}
|
|
|
|
@Test func `uploadMedia reads Location then body url and gates the url`() async {
|
|
let log = MicropubRequestLog()
|
|
// Location wins; body url is the fallback.
|
|
let located = await Micropub.uploadMedia(
|
|
mediaEndpoint: "https://micro.blog/micropub/media",
|
|
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
|
|
transport: micropubCanned(
|
|
202, body: #"{"url":"https://ignored.example/should-not-win"}"#,
|
|
headers: ["Location": "https://micro.blog/uploads/ink.png"], log: log,
|
|
),
|
|
)
|
|
#expect(located == .url("https://micro.blog/uploads/ink.png"))
|
|
|
|
let fallback = await Micropub.uploadMedia(
|
|
mediaEndpoint: "https://micro.blog/micropub/media",
|
|
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
|
|
transport: micropubCanned(202, body: #"{"url":"https://micro.blog/uploads/from-body"}"#, log: log),
|
|
)
|
|
#expect(fallback == .url("https://micro.blog/uploads/from-body"))
|
|
|
|
// No URL anywhere → request failure, never a silent success.
|
|
let bare = await Micropub.uploadMedia(
|
|
mediaEndpoint: "https://micro.blog/micropub/media",
|
|
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
|
|
transport: micropubCanned(202, body: "{}", log: log),
|
|
)
|
|
guard case .failed(.requestFailed) = bare else {
|
|
Issue.record("expected requestFailed, got \(bare)")
|
|
return
|
|
}
|
|
|
|
let denied = await Micropub.uploadMedia(
|
|
mediaEndpoint: "https://micro.blog/micropub/media",
|
|
filename: "ink.png", mimeType: "image/png", data: micropubPNG(), token: "tok",
|
|
transport: micropubCanned(403, body: "{}", log: log),
|
|
)
|
|
guard case .failed(.authFailed) = denied else {
|
|
Issue.record("expected authFailed, got \(denied)")
|
|
return
|
|
}
|
|
}
|
|
|
|
// MARK: The create (hop 3)
|
|
|
|
@Test func `draft request carries no photo keys ever`() {
|
|
// #34 amendment (2026-11-01): images travel INLINE — the rail
|
|
// rewrites each asset ref to its uploaded URL inside content.
|
|
// A photo property would render wherever the theme decides.
|
|
let request = Micropub.makeDraftRequest(title: "T", body: "", token: "tok")
|
|
let props = micropubJSON(request)["properties"] as? [String: Any]
|
|
#expect(props?["photo"] == nil)
|
|
#expect(props?["mp-photo-alt"] == nil)
|
|
#expect(props?["content"] as? [String] == [""])
|
|
}
|
|
}
|