Repository Public
1// SP Notes Core2// File: Tests/SPNotesAPITests/LiveBackendTests.swift3// Description: Integration tests against the TEST backend only (never production). Skipped unless SPN_LIVE_URL and4// SPN_LIVE_TOKEN are set; everything they create is trashed or purged at the end.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9// Run:10// ssh -f -N -L 8482:localhost:8482 M4M64c11// SPN_LIVE_URL=http://localhost:8482 SPN_LIVE_TOKEN=<dev token> \12// [SPN_LIVE_TOKEN_DISPOSABLE=<2nd token> SPN_LIVE_TOKEN_DISPOSABLE2=<3rd token>] \13// SPN_ONLY=API swift test --scratch-path .build-api --filter LiveBackendTests14import CryptoKit15import Foundation16import XCTest17@testable import SPNotesAPI1819final class LiveBackendTests: XCTestCase {20 // MARK: environment2122 private struct Live {23 var api: NotesAPI24 var client: HTTPClient25 var store: InMemoryTokenStore26 var configuration: APIConfiguration27 }2829 private func environment(_ name: String) -> String? {30 guard let value = ProcessInfo.processInfo.environment[name], !value.isEmpty else { return nil }31 return value32 }3334 private func live(tokenVariable: String = "SPN_LIVE_TOKEN", token override: String? = nil) throws -> Live {35 guard let base = environment("SPN_LIVE_URL"), let url = URL(string: base) else { throw XCTSkip("SPN_LIVE_URL is not set") }36 guard let host = url.host, !host.hasSuffix("spboucher.ai") else {37 XCTFail("The live tests never run against production")38 throw XCTSkip("refusing to use \(base)")39 }40 guard let token = override ?? environment(tokenVariable) else { throw XCTSkip("\(tokenVariable) is not set") }41 let configuration = APIConfiguration(baseURL: url, userAgent: APIConfiguration.userAgent(appVersion: "0.0.1"))42 let store = InMemoryTokenStore(token: token)43 let client = HTTPClient(configuration: configuration, tokenStore: store)44 return Live(api: NotesAPI(client: client), client: client, store: store, configuration: configuration)45 }4647 /// Trashes (and purges when the session is fresh enough) a page at the end of the test.48 private func cleanUp(_ api: NotesAPI, page id: String) {49 addTeardownBlock {50 _ = try? await api.trashPage(id: id)51 _ = try? await api.purgePage(id: id)52 }53 }5455 private func document(_ text: String, blockID: String = "spnliveblk") -> RawJSON {56 RawJSON(string: #"{"type":"doc","content":[{"type":"paragraph","attrs":{"id":"\#(blockID)"},"content":[{"type":"text","text":"\#(text)"}]}]}"#)57 }5859 private struct FeedWalk {60 var pages: [Page] = []61 var attachments: [SyncAttachment] = []62 var tombstones: [Tombstone] = []63 var cursor: Int64 = 064 var head: Int64 = 065 var calls = 066 }6768 /// Follows the feed from `since` until `more` is false, checking the invariants of every answer.69 private func walk(_ api: NotesAPI, since: Int64, limit: Int? = nil) async throws -> FeedWalk {70 var result = FeedWalk(cursor: since)71 while true {72 let page = try await api.sync(since: result.cursor, limit: limit)73 result.calls += 174 XCTAssertFalse(page.reset)75 XCTAssertGreaterThanOrEqual(page.cursor, result.cursor)76 XCTAssertLessThanOrEqual(page.cursor, page.head)77 for revs in [page.pages.compactMap(\.rev), page.attachments.map(\.rev), page.tombstones.map(\.rev)] {78 XCTAssertEqual(revs, revs.sorted(), "revisions are ascending inside an answer")79 XCTAssertTrue(revs.allSatisfy { $0 > result.cursor && $0 <= page.cursor }, "revisions lie in (since, cursor]")80 }81 if let limit { XCTAssertLessThanOrEqual(page.pages.count + page.attachments.count + page.tombstones.count, limit * 3) }82 result.pages += page.pages83 result.attachments += page.attachments84 result.tombstones += page.tombstones85 result.head = page.head86 if page.more { XCTAssertGreaterThan(page.cursor, result.cursor, "a page with more must advance") }87 result.cursor = page.cursor88 if !page.more { break }89 if result.calls > 5_000 { XCTFail("the feed does not terminate"); break }90 }91 return result92 }9394 // MARK: tests9596 func testHealthStateAndSessions() async throws {97 let live = try live()98 let health = try await live.api.health()99 XCTAssertTrue(health.ok)100 XCTAssertEqual(health.db, true)101 XCTAssertNotNil(health.version)102103 let state = try await live.api.authState()104 XCTAssertFalse(state.sessionId.isEmpty)105 XCTAssertEqual(state.rpId, live.configuration.relyingPartyID)106 XCTAssertEqual(state.origins?.contains(live.configuration.origin), true)107 XCTAssertEqual(state.freshWindowMs, 300_000)108109 let sessions = try await live.api.sessions()110 XCTAssertEqual(sessions.filter(\.current).map(\.id), [state.sessionId])111 _ = try await live.api.passkeys()112 _ = try await live.api.tags()113 let has = await live.client.hasSession114 XCTAssertTrue(has)115 }116117 func testFeedFromZeroWithPaging() async throws {118 let live = try live()119 let first = try await live.api.sync(since: 0, limit: 1)120 XCTAssertFalse(first.workspace.id.isEmpty)121 XCTAssertFalse(first.workspace.name.isEmpty)122 XCTAssertLessThan(abs(first.serverTime.timeIntervalSinceNow), 300, "serverTime is a real date")123124 let paged = try await walk(live.api, since: 0, limit: 3)125 let whole = try await walk(live.api, since: 0, limit: 500)126 XCTAssertGreaterThan(paged.calls, 1, "the test database holds more than 3 changes")127 XCTAssertGreaterThanOrEqual(paged.calls, whole.calls)128 XCTAssertEqual(paged.cursor, paged.head)129 // Unless somebody wrote in between, both walks describe the same state.130 if paged.head == whole.head {131 XCTAssertEqual(paged.pages.map(\.id), whole.pages.map(\.id))132 XCTAssertEqual(paged.pages.compactMap(\.rev), whole.pages.compactMap(\.rev))133 XCTAssertEqual(paged.attachments.map(\.id), whole.attachments.map(\.id))134 XCTAssertEqual(paged.tombstones, whole.tombstones)135 }136 XCTAssertEqual(Set(whole.pages.map(\.id)).count, whole.pages.count, "a full copy lists each page once")137 XCTAssertTrue(Set(whole.pages.map(\.id)).isDisjoint(with: whole.tombstones.filter { $0.kind == Tombstone.pageKind }.map(\.id)))138139 // Nothing new after the head; a cursor ahead of the server asks for a reset.140 let idle = try await live.api.sync(since: whole.head)141 if idle.head == whole.head {142 XCTAssertTrue(idle.pages.isEmpty && idle.attachments.isEmpty && idle.tombstones.isEmpty)143 XCTAssertFalse(idle.more)144 XCTAssertEqual(idle.cursor, whole.head)145 }146 let ahead = try await live.api.sync(since: whole.head + 1_000_000)147 XCTAssertTrue(ahead.reset)148 XCTAssertEqual(ahead.cursor, 0, "a reset answer sends the client back to 0")149 XCTAssertTrue(ahead.pages.isEmpty)150 let badCursor = await captureAPIError { try await live.api.sync(since: -1) }151 XCTAssertEqual(badCursor?.status, 400)152 XCTAssertEqual(badCursor?.code, "bad_cursor")153 }154155 func testPageLifecycleConflictAndFeed() async throws {156 let live = try live()157 let api = live.api158 let head0 = try await api.sync(since: 0, limit: 1).head159 let marker = "spnlive" + UUID().uuidString.prefix(8).lowercased()160 let id = NotesAPI.newID()161 cleanUp(api, page: id)162163 // Create with a client id, twice.164 let created = try await api.createPage(PageDraft(id: id, title: "\(marker) one", section: .notes, content: document("first"), properties: RawJSON(string: #"{"favorite":true}"#)))165 XCTAssertFalse(created.existing)166 XCTAssertEqual(created.value.id, id)167 XCTAssertEqual(created.value.version, 1)168 XCTAssertEqual(created.value.content, document("first"))169 XCTAssertEqual(created.value.properties, RawJSON(string: #"{"favorite":true}"#))170 let rev1 = try XCTUnwrap(created.value.rev)171 XCTAssertGreaterThan(rev1, head0)172 let again = try await api.createPage(PageDraft(id: id, title: "must be ignored"))173 XCTAssertTrue(again.existing)174 XCTAssertEqual(again.value.title, "\(marker) one")175 XCTAssertEqual(again.value.rev, rev1)176177 // Read.178 let detail = try await api.page(id: id)179 XCTAssertEqual(detail.page.title, "\(marker) one")180 XCTAssertEqual(detail.breadcrumb.last?.id, id)181 let head = try await api.pageHead(id: id)182 XCTAssertEqual(head.version, 1)183 XCTAssertNil(head.deletedAt)184185 // Guarded write, then a stale one.186 let patched = try await api.patchPage(id: id, PagePatch(title: "\(marker) two", content: document("second"), versionReason: "live-test", baseVersion: 1))187 XCTAssertEqual(patched.version, 2)188 XCTAssertEqual(patched.title, "\(marker) two")189 XCTAssertEqual(patched.wordCount, 1)190 let stale = await captureAPIError { try await api.patchPage(id: id, PagePatch(title: "stale", baseVersion: 1)) }191 guard case .conflict(let server, _) = stale else { return XCTFail("expected a typed conflict, got \(String(describing: stale))") }192 XCTAssertEqual(server.version, 2)193 XCTAssertEqual(server.title, "\(marker) two")194 XCTAssertEqual(server.content, document("second"))195 XCTAssertEqual(server.properties, RawJSON(string: #"{"favorite":true}"#))196 XCTAssertEqual(server.updatedAt.timeIntervalSince1970, patched.updatedAt.timeIntervalSince1970, accuracy: 0.001)197 let unchanged = try await api.pageHead(id: id)198 XCTAssertEqual(unchanged.version, 2, "a refused write changes nothing")199200 // Fields that are not version-guarded; null versus absent.201 let decorated = try await api.patchPage(id: id, PagePatch(icon: .value("📝"), pinned: true))202 XCTAssertEqual(decorated.version, 2, "icon and pinned are not versioned")203 var current = try await api.page(id: id).page204 XCTAssertEqual(current.icon, "📝")205 XCTAssertTrue(current.pinned)206 _ = try await api.patchPage(id: id, PagePatch(icon: .null))207 current = try await api.page(id: id).page208 XCTAssertNil(current.icon)209 XCTAssertTrue(current.pinned, "an absent field is left alone")210211 // Resolve: mine, then both (creates a copy), then with a stale server version.212 let mine = try await api.resolveConflict(pageID: id, choice: .mine, serverVersion: 2, mine: ConflictMine(title: "\(marker) three", content: document("third")))213 XCTAssertEqual(mine.title, "\(marker) three")214 XCTAssertEqual(mine.content, document("third"))215 XCTAssertGreaterThan(mine.version, 2)216 XCTAssertNil(mine.copyId)217 let both = try await api.resolveConflict(pageID: id, choice: .both, serverVersion: mine.version, mine: ConflictMine(title: "\(marker) mine", content: document("local copy")))218 let copyID = try XCTUnwrap(both.copyId)219 cleanUp(api, page: copyID)220 XCTAssertEqual(both.title, "\(marker) three")221 let copy = try await api.page(id: copyID).page222 XCTAssertEqual(copy.content, document("local copy"))223 let staleResolve = await captureAPIError { try await api.resolveConflict(pageID: id, choice: .mine, serverVersion: 1, mine: ConflictMine(title: "x")) }224 XCTAssertEqual(staleResolve?.isConflict, true, "\(String(describing: staleResolve))")225226 // Tags.227 let normalised = try await api.setPageTags(pageID: id, tags: ["#Alpha ", " beta"])228 XCTAssertEqual(normalised, ["alpha", "beta"])229 let tags = try await api.pageTags(pageID: id)230 XCTAssertEqual(tags, ["alpha", "beta"])231 let allTags = try await api.tags()232 XCTAssertTrue(Set(allTags.map(\.name)).isSuperset(of: ["alpha", "beta"]))233234 // Versions.235 let versions = try await api.pageVersions(pageID: id)236 XCTAssertFalse(versions.isEmpty)237 XCTAssertTrue(versions.contains { $0.version == 1 })238 XCTAssertTrue(versions.contains { $0.reason == "live-test" } || versions.contains { $0.reason != nil })239 let snapshot = try await api.pageVersion(pageID: id, version: 1)240 XCTAssertEqual(snapshot.title, "\(marker) one")241 XCTAssertEqual(snapshot.content, document("first"))242 let before = try await api.pageHead(id: id).version243 let restoredVersion = try await api.restorePageVersion(pageID: id, version: 1)244 XCTAssertTrue(restoredVersion.ok)245 XCTAssertGreaterThan(restoredVersion.version, before)246 current = try await api.page(id: id).page247 XCTAssertEqual(current.title, "\(marker) one")248 XCTAssertEqual(current.content, document("first"))249250 // Duplicate and search.251 let duplicate = try await api.duplicatePage(id: id)252 cleanUp(api, page: duplicate.id)253 XCTAssertNotEqual(duplicate.id, id)254 XCTAssertEqual(duplicate.title, "\(marker) one (copy)")255 let hits = try await api.search(SearchQuery(marker, mode: .quick, limit: 10))256 XCTAssertTrue(hits.contains { $0.targetPageID == id }, "quick search finds the page by its title")257 XCTAssertTrue(hits.allSatisfy { $0.updatedAt != nil }, "the PostgreSQL date form of /api/search is parsed")258259 // Trash and restore.260 let trashed = try await api.trashPage(id: id)261 XCTAssertTrue(trashed.ok)262 XCTAssertEqual(trashed.trashed, 1)263 let inTrash = try await api.pageHead(id: id)264 XCTAssertNotNil(inTrash.deletedAt)265 let restored = try await api.restorePage(id: id)266 XCTAssertTrue(restored.ok)267 let outOfTrash = try await api.pageHead(id: id)268 XCTAssertNil(outOfTrash.deletedAt)269270 // The feed reports all of it.271 var feed = try await walk(api, since: head0)272 let row = try XCTUnwrap(feed.pages.last { $0.id == id })273 XCTAssertGreaterThan(try XCTUnwrap(row.rev), rev1, "every write bumps the revision")274 XCTAssertEqual(row.tags, ["alpha", "beta"])275 XCTAssertEqual(row.version, restoredVersion.version)276 XCTAssertEqual(row.title, "\(marker) one")277 XCTAssertTrue(row.pinned)278 XCTAssertNil(row.deletedAt)279 XCTAssertEqual(row.content, document("first"))280 XCTAssertTrue(feed.pages.contains { $0.id == copyID })281 XCTAssertTrue(feed.pages.contains { $0.id == duplicate.id })282 XCTAssertTrue(Set(feed.pages.compactMap(\.rev)).count == feed.pages.count)283284 // Trash again: the feed shows the trashed state; purge: a tombstone (or the typed step-up request).285 _ = try await api.trashPage(id: id)286 let cursorBeforePurge = feed.cursor287 feed = try await walk(api, since: cursorBeforePurge)288 XCTAssertNotNil(feed.pages.last { $0.id == id }?.deletedAt)289 do {290 let purged = try await api.purgePage(id: id)291 XCTAssertTrue(purged.ok)292 let after = try await walk(api, since: feed.cursor)293 let tombstone = try XCTUnwrap(after.tombstones.first { $0.id == id })294 XCTAssertEqual(tombstone.kind, Tombstone.pageKind)295 XCTAssertGreaterThan(tombstone.rev, feed.cursor)296 XCTAssertFalse(after.pages.contains { $0.id == id })297 let gone = await captureAPIError { try await api.page(id: id) }298 XCTAssertEqual(gone?.isNotFound, true)299 let full = try await walk(api, since: 0, limit: 500)300 XCTAssertFalse(full.pages.contains { $0.id == id }, "a purged page is absent from a full copy")301 XCTAssertTrue(full.tombstones.contains { $0.id == id })302 } catch let error as APIError {303 XCTAssertTrue(error.needsReauth, "purge without a fresh verification must be the typed reauth_required, got \(error)")304 XCTAssertEqual(error.status, 403)305 }306 }307308 func testAttachmentRoundTripAndFeed() async throws {309 let live = try live()310 let api = live.api311 let head0 = try await api.sync(since: 0, limit: 1).head312 let pageID = NotesAPI.newID()313 cleanUp(api, page: pageID)314 _ = try await api.createPage(PageDraft(id: pageID, title: "spnlive attachment host"))315316 var generator = SystemRandomNumberGenerator()317 let bytes = Data((0..<300_000).map { _ in UInt8.random(in: 0...255, using: &generator) })318 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spn-live-\(UUID().uuidString)")319 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)320 addTeardownBlock { try? FileManager.default.removeItem(at: directory) }321 let source = directory.appendingPathComponent("spn live é \"file\".bin")322 try bytes.write(to: source)323324 let attachmentID = NotesAPI.newID()325 addTeardownBlock { _ = try? await api.deleteAttachment(id: attachmentID) }326 let uploadProgress = ProgressLog()327 let uploaded = try await api.uploadAttachment(fileURL: source, id: attachmentID, pageID: pageID, mimeType: "application/octet-stream") { uploadProgress.add($0) }328 XCTAssertFalse(uploaded.existing)329 XCTAssertEqual(uploaded.value.id, attachmentID)330 XCTAssertEqual(uploaded.value.size, 300_000)331 XCTAssertEqual(uploaded.value.url, NotesAPI.filePath(id: attachmentID))332 XCTAssertEqual(uploaded.value.name, "spn live é \"file\".bin", "the file name survives the multipart escaping")333 XCTAssertGreaterThan(uploadProgress.values.last?.completedBytes ?? 0, 300_000, "progress covers the whole multipart body")334 XCTAssertEqual(uploadProgress.values.last?.fraction, 1)335 XCTAssertEqual(uploadProgress.values.map(\.completedBytes), uploadProgress.values.map(\.completedBytes).sorted())336337 // The same client id again: nothing new.338 let second = try await api.uploadAttachment(fileURL: source, id: attachmentID, pageID: pageID)339 XCTAssertTrue(second.existing)340 XCTAssertEqual(second.value.id, attachmentID)341342 let listed = try await api.attachments(pageID: pageID)343 XCTAssertEqual(listed.map(\.id), [attachmentID])344 XCTAssertEqual(listed.first?.size, 300_000)345 XCTAssertEqual(listed.first?.pageId, pageID)346347 // Download and compare.348 let destination = directory.appendingPathComponent("downloaded.bin")349 let downloadProgress = ProgressLog()350 let file = try await api.downloadFile(id: attachmentID, to: destination) { downloadProgress.add($0) }351 XCTAssertEqual(try Data(contentsOf: destination), bytes)352 XCTAssertEqual(file.expectedSize, 300_000)353 XCTAssertEqual(file.suggestedFilename, "spn live é \"file\".bin")354 XCTAssertEqual(downloadProgress.values.last?.completedBytes, 300_000, "download progress is reported")355356 let missing = await captureAPIError { try await api.downloadFile(id: NotesAPI.newID(), to: directory.appendingPathComponent("missing.bin")) }357 XCTAssertEqual(missing?.isNotFound, true)358 XCTAssertFalse(FileManager.default.fileExists(atPath: directory.appendingPathComponent("missing.bin").path))359360 // Delete; the feed reports the attachment with its hash and its deletion.361 let before = try await walk(api, since: head0)362 let alive = try XCTUnwrap(before.attachments.last { $0.id == attachmentID })363 XCTAssertNil(alive.deletedAt)364 XCTAssertEqual(alive.sha256, SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())365 XCTAssertEqual(alive.pageId, pageID)366 XCTAssertEqual(alive.size, 300_000)367 let deleted = try await api.deleteAttachment(id: attachmentID)368 XCTAssertTrue(deleted.ok)369 let after = try await walk(api, since: before.cursor)370 let dead = try XCTUnwrap(after.attachments.last { $0.id == attachmentID })371 XCTAssertNotNil(dead.deletedAt)372 XCTAssertGreaterThan(dead.rev, alive.rev)373 let remaining = try await api.attachments(pageID: pageID)374 XCTAssertTrue(remaining.isEmpty)375 }376377 func testTasksCRUD() async throws {378 let live = try live()379 let api = live.api380 let title = "spnlive task \(UUID().uuidString.prefix(8))"381 let due = Date(timeIntervalSince1970: 1_800_000_000.123)382 let task = try await api.createTask(TaskDraft(title: title, dueAt: due, priority: .high, project: "spnlive"), idempotencyKey: NotesAPI.newIdempotencyKey())383 addTeardownBlock { _ = try? await api.deleteTask(id: task.id) }384 XCTAssertEqual(task.title, title)385 XCTAssertEqual(task.status, "todo")386 XCTAssertEqual(task.priority, "high")387 XCTAssertEqual(task.project, "spnlive")388 XCTAssertEqual(try XCTUnwrap(task.dueAt).timeIntervalSince1970, due.timeIntervalSince1970, accuracy: 0.001)389390 var open = try await api.tasks()391 XCTAssertTrue(open.contains { $0.id == task.id })392393 let done = try await api.updateTask(TaskPatch(id: task.id, title: title + " done", dueAt: .null, status: .done, priority: .low))394 XCTAssertTrue(done.isDone)395 XCTAssertNil(done.dueAt)396 XCTAssertNotNil(done.completedAt)397 XCTAssertEqual(done.priority, "low")398 XCTAssertEqual(done.title, title + " done")399 XCTAssertEqual(done.project, "spnlive", "an absent field is left alone")400401 open = try await api.tasks()402 XCTAssertFalse(open.contains { $0.id == task.id })403 var all = try await api.tasks(includeDone: true)404 XCTAssertTrue(all.contains { $0.id == task.id })405406 let deleted = try await api.deleteTask(id: task.id)407 XCTAssertTrue(deleted.ok)408 all = try await api.tasks(includeDone: true)409 XCTAssertFalse(all.contains { $0.id == task.id })410 let missing = await captureAPIError { try await api.updateTask(TaskPatch(id: NotesAPI.newID(), status: .done)) }411 XCTAssertEqual(missing?.isNotFound, true)412 }413414 func testCaptureInboxTriageAndIdempotency() async throws {415 let live = try live()416 let api = live.api417 let text = "spnlive capture \(UUID().uuidString.prefix(8))"418 let key = NotesAPI.newIdempotencyKey()419 let captured = try await api.capture(CaptureRequest(kind: .note, text: text), idempotencyKey: key)420 cleanUp(api, page: captured.id)421 XCTAssertEqual(captured.kind, "note")422 XCTAssertNotNil(captured.inboxAt)423424 // The same key again: the stored answer, no second page.425 let replay = try await api.capture(CaptureRequest(kind: .note, text: text), idempotencyKey: key)426 XCTAssertEqual(replay.id, captured.id)427 let response = try await live.client.send(.json(.post, "/api/capture", body: CaptureRequest(kind: .note, text: text), idempotencyKey: key))428 XCTAssertTrue(response.isIdempotentReplay)429 XCTAssertNotNil(response.requestID)430 var inbox = try await api.inbox()431 XCTAssertEqual(inbox.filter { $0.title == captured.title }.count, 1)432 XCTAssertTrue(inbox.contains { $0.id == captured.id })433434 let badKey = await captureAPIError { try await api.capture(CaptureRequest(kind: .note, text: text), idempotencyKey: "short") }435 XCTAssertEqual(badKey?.code, APIError.Code.badIdempotencyKey)436 XCTAssertEqual(badKey?.status, 400)437438 let archived = try await api.triageInboxItem(id: captured.id, .archive)439 XCTAssertFalse(archived.actionId.isEmpty)440 inbox = try await api.inbox()441 XCTAssertFalse(inbox.contains { $0.id == captured.id })442 let undone = try await api.undoInboxAction(actionID: archived.actionId)443 XCTAssertTrue(undone.ok)444 inbox = try await api.inbox()445 XCTAssertTrue(inbox.contains { $0.id == captured.id })446 let trashed = try await api.triageInboxItem(id: captured.id, .trash)447 XCTAssertFalse(trashed.actionId.isEmpty)448 let head = try await api.pageHead(id: captured.id)449 XCTAssertNotNil(head.deletedAt)450 }451452 /// Only the paths that cost nothing: the server answers before calling any provider.453 func testAIErrorPathsOnly() async throws {454 let live = try live()455 let noInstruction = await captureAPIError { try await live.api.aiAction(AIActionRequest(action: .custom, text: "some text")) }456 XCTAssertEqual(noInstruction?.status, 400)457 XCTAssertEqual(noInstruction?.code, "no_instruction")458 let noLanguage = await captureAPIError { try await live.api.aiAction(AIActionRequest(action: .translate, text: "some text")) }459 XCTAssertEqual(noLanguage?.status, 400)460 XCTAssertEqual(noLanguage?.code, "bad_language")461 let emptyMessage = await captureAPIError { try await live.api.aiChat(AIChatRequest(message: " ")) }462 XCTAssertEqual(emptyMessage?.status, 400)463 let has = await live.client.hasSession464 XCTAssertTrue(has)465 }466467 func testTypedErrorsFromTheRealServer() async throws {468 let live = try live()469 let missing = await captureAPIError { try await live.api.page(id: NotesAPI.newID()) }470 XCTAssertEqual(missing?.isNotFound, true)471 XCTAssertEqual(missing?.message, "Page not found")472 let badDocument = await captureAPIError { try await live.api.createPage(PageDraft(title: "spnlive bad", content: RawJSON(string: #"{"type":"nope"}"#))) }473 XCTAssertEqual(badDocument?.code, APIError.Code.badDocument, "\(String(describing: badDocument))")474 }475476 func testInvalidTokenIsRefusedAndSignsOutOnce() async throws {477 let live = try live(token: "invalid" + String(repeating: "A", count: 36))478 var events = await live.client.sessionEvents().makeAsyncIterator()479 let error = await captureAPIError { try await live.api.sync(since: 0, limit: 1) }480 guard error?.isUnauthenticated == true else { return XCTFail("expected a 401, got \(String(describing: error))") }481 XCTAssertEqual(error?.code, APIError.Code.unauthenticated)482 XCTAssertNil(live.store.load())483 _ = await captureAPIError { try await live.api.tags() }484 await live.client.setSessionToken("marker")485 let first = await events.next()486 let second = await events.next()487 XCTAssertEqual(first, .signedOut(.unauthorized))488 XCTAssertEqual(second, .signedIn)489 // Public routes still answer.490 await live.client.clearSession()491 let health = try await live.api.health()492 XCTAssertTrue(health.ok)493 }494495 /// The real server sets `__Host-note_wa` on an options call: the client must capture it from `Set-Cookie`496 /// (no cookie storage) and replay it on the verify call only.497 func testCeremonyCookieWithTheRealServer() async throws {498 let live = try live()499 let options = try await live.api.reauthOptions()500 XCTAssertEqual(options.rpId, live.configuration.relyingPartyID)501 XCTAssertEqual(options.challenge.count, 32)502 XCTAssertEqual(options.userVerification, "required")503 var held = await live.client.holdsCeremonyCookie(PasskeyCeremony.Kind.reauth.rawValue)504 XCTAssertTrue(held, "the ceremony cookie was read from Set-Cookie")505506 // A made-up assertion: the server finds its challenge (the cookie was replayed) and refuses the credential.507 let forged = PasskeyCeremony.assertionCredential(credentialID: Data(repeating: 7, count: 16), clientDataJSON: Data("{}".utf8), authenticatorData: Data(repeating: 1, count: 37), signature: Data(repeating: 2, count: 70), userHandle: nil)508 let refused = await captureAPIError { try await live.api.reauthVerify(forged) }509 XCTAssertEqual(refused?.status, 400)510 XCTAssertNotEqual(refused?.code, "challenge_missing", "the verify call carried the ceremony cookie")511 held = await live.client.holdsCeremonyCookie(PasskeyCeremony.Kind.reauth.rawValue)512 XCTAssertFalse(held, "the ceremony cookie is single-use")513 // Without a pending ceremony the server says so.514 let noCeremony = await captureAPIError { try await live.api.reauthVerify(forged) }515 XCTAssertEqual(noCeremony?.code, "challenge_missing")516517 // The session survived, and the registration options decode (or ask for a fresh verification).518 _ = try await live.api.authState()519 do {520 let creation = try await live.api.passkeyRegistrationOptions()521 XCTAssertEqual(creation.rp.id, live.configuration.relyingPartyID)522 XCTAssertFalse(creation.user.id.isEmpty)523 XCTAssertEqual(creation.challenge.count, 32)524 } catch let error as APIError {525 XCTAssertTrue(error.needsReauth, "\(error)")526 }527 // Sign-in options: the test account may have no passkey at all.528 do {529 let login = try await live.api.loginOptions()530 XCTAssertEqual(login.challenge.count, 32)531 } catch let error as APIError {532 XCTAssertEqual(error.code, APIError.Code.notEnrolled, "\(error)")533 }534 }535536 /// Needs two extra throw-away tokens: one is revoked from the main session, the other signs out.537 func testRevocationAndLogoutWithDisposableSessions() async throws {538 let main = try live()539 let victim = try live(tokenVariable: "SPN_LIVE_TOKEN_DISPOSABLE")540 let leaver = try live(tokenVariable: "SPN_LIVE_TOKEN_DISPOSABLE2")541542 // Revoked from another session → the next call is a 401 and the client signs out. Revoking needs a fresh543 // passkey verification: a main token older than 5 minutes gets the typed step-up request instead.544 let victimSession = try await victim.api.authState().sessionId545 var victimEvents = await victim.client.sessionEvents().makeAsyncIterator()546 do {547 let revoked = try await main.api.revokeSession(id: victimSession)548 XCTAssertTrue(revoked.ok)549 let refused = await captureAPIError { try await victim.api.authState() }550 guard refused?.isUnauthenticated == true else { return XCTFail("expected a 401, got \(String(describing: refused))") }551 let victimEvent = await victimEvents.next()552 XCTAssertEqual(victimEvent, .signedOut(.unauthorized))553 XCTAssertNil(victim.store.load())554 let sessions = try await main.api.sessions()555 XCTAssertFalse(sessions.contains { $0.id == victimSession })556 } catch let error as APIError {557 XCTAssertTrue(error.needsReauth, "\(error)")558 let stillValid = try await victim.api.authState()559 XCTAssertEqual(stillValid.sessionId, victimSession)560 }561562 // Logout → the server clears the cookie; the token is dead afterwards.563 let leaverToken = try XCTUnwrap(leaver.store.load())564 var leaverEvents = await leaver.client.sessionEvents().makeAsyncIterator()565 let auth = AuthService(api: leaver.api, authorizer: FakeAuthorizer())566 await auth.signOut()567 XCTAssertNil(leaver.store.load())568 let leaverEvent = await leaverEvents.next()569 XCTAssertEqual(leaverEvent, .signedOut(.cookieCleared))570 let dead = try live(token: leaverToken)571 let afterLogout = await captureAPIError { try await dead.api.authState() }572 XCTAssertEqual(afterLogout?.isUnauthenticated, true)573 }574}575576/// Collects progress callbacks (they arrive on a background queue).577private final class ProgressLog: @unchecked Sendable {578 private let lock = NSLock()579 private var log: [TransferProgress] = []580 func add(_ progress: TransferProgress) { lock.withLock { log.append(progress) } }581 var values: [TransferProgress] { lock.withLock { log } }582}583