Repository Public
1// SP Notes Core2// File: Tests/SPNotesAPITests/HTTPClientTests.swift3// Description: Transport rules checked against a URLProtocol stub: manual session cookie, ceremony cookie replay,4// rotation, single sign-out event, Origin, request id, idempotency key, transfers.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import XCTest10@testable import SPNotesAPI1112final class HTTPClientTests: XCTestCase {13 // MARK: configuration1415 func testConfigurationOriginAndUserAgent() {16 XCTAssertEqual(APIConfiguration.production.baseURL.absoluteString, "https://note.spboucher.ai")17 XCTAssertEqual(APIConfiguration.production.origin, "https://note.spboucher.ai")18 XCTAssertEqual(APIConfiguration.production.relyingPartyID, "note.spboucher.ai")19 XCTAssertEqual(APIConfiguration(baseURL: URL(string: "http://localhost:8482/")!).origin, "http://localhost:8482")20 XCTAssertEqual(APIConfiguration(baseURL: URL(string: "http://localhost:8482/")!).baseURL.absoluteString, "http://localhost:8482")21 XCTAssertEqual(APIConfiguration.origin(of: URL(string: "https://Example.com:443/x")!), "https://example.com")22 XCTAssertEqual(APIConfiguration.origin(of: URL(string: "http://example.com:80")!), "http://example.com")23 XCTAssertEqual(APIConfiguration.origin(of: URL(string: "https://example.com:8443")!), "https://example.com:8443")24 XCTAssertEqual(APIConfiguration.userAgent(appVersion: "1.2.3", device: .iPhone, osVersion: "iOS 18.1"), "SPNotes/1.2.3 (iPhone; iOS 18.1) native")25 XCTAssertEqual(APIConfiguration.userAgent(appVersion: "2.0.0", device: .iPad, osVersion: "iPadOS 18.2"), "SPNotes/2.0.0 (iPad; iPadOS 18.2) native")26 XCTAssertEqual(APIConfiguration.userAgent(appVersion: "2.0.0", device: .mac, osVersion: "macOS 15.1"), "SPNotes/2.0.0 (Macintosh; macOS 15.1) native")27 let automatic = APIConfiguration.userAgent(appVersion: "1.0.0")28 XCTAssertNotNil(automatic.range(of: #"^SPNotes/1\.0\.0 \((iPhone|iPad|Macintosh); (iOS|iPadOS|macOS) \d+\.\d+(\.\d+)?\) native$"#, options: .regularExpression), automatic)29 }3031 // MARK: headers3233 func testGetSendsCookieManuallyAndNoOrigin() async throws {34 StubServer.shared.reset { _ in .json("{\"ok\":true}") }35 let (client, _) = TestEnv.client()36 let response = try await client.send(.get("/api/health"))37 XCTAssertEqual(response.status, 200)38 let request = try XCTUnwrap(StubServer.shared.last)39 XCTAssertEqual(request.method, "GET")40 XCTAssertEqual(request.url.absoluteString, "https://notes.test/api/health")41 XCTAssertEqual(request.header("Cookie"), "__Host-note_session=\(TestEnv.token)")42 XCTAssertNil(request.header("Origin"))43 XCTAssertNil(request.header("Idempotency-Key"))44 XCTAssertEqual(request.header("Accept"), "application/json")45 XCTAssertEqual(request.header("User-Agent"), "SPNotes/1.2.3 (iPhone; iOS 18.1) native")46 let requestID = try XCTUnwrap(request.header("x-request-id"))47 XCTAssertNotNil(requestID.range(of: "^[A-Za-z0-9_-]{8,64}$", options: .regularExpression), requestID)48 }4950 func testNoCookieHeaderWithoutToken() async throws {51 StubServer.shared.reset { _ in .json("{}") }52 let (client, _) = TestEnv.client(token: nil)53 _ = try await client.send(.get("/api/health"))54 XCTAssertNil(StubServer.shared.last?.header("Cookie"))55 let has = await client.hasSession56 XCTAssertFalse(has)57 }5859 func testOriginOnlyOnMutatingMethods() async throws {60 StubServer.shared.reset { _ in .json("{}") }61 let (client, _) = TestEnv.client()62 for method in [HTTPMethod.get, .post, .patch, .put, .delete] {63 _ = try await client.send(HTTPRequest(method: method, path: "/api/x", idempotencyKey: "key-12345678"))64 let request = try XCTUnwrap(StubServer.shared.last)65 XCTAssertEqual(request.method, method.rawValue)66 if method == .get {67 XCTAssertNil(request.header("Origin"))68 XCTAssertNil(request.header("Idempotency-Key"), "an idempotency key has no meaning on a GET")69 } else {70 XCTAssertEqual(request.header("Origin"), "https://notes.test")71 XCTAssertEqual(request.header("Idempotency-Key"), "key-12345678")72 }73 }74 }7576 func testIdempotencyKeyRequestIDAndJSONBody() async throws {77 StubServer.shared.reset { _ in .json("{}", headers: ["x-request-id": "req-abcdefgh", "idempotent-replay": "true", "x-existing": "1"]) }78 let (client, _) = TestEnv.client()79 var request = try HTTPRequest.json(.post, "/api/capture", body: ["kind": "note"], idempotencyKey: "idem-00000001")80 request.requestID = "req-abcdefgh"81 let response = try await client.send(request)82 let seen = try XCTUnwrap(StubServer.shared.last)83 XCTAssertEqual(seen.header("Idempotency-Key"), "idem-00000001")84 XCTAssertEqual(seen.header("x-request-id"), "req-abcdefgh")85 XCTAssertEqual(seen.header("Content-Type"), "application/json")86 XCTAssertEqual(seen.bodyText, "{\"kind\":\"note\"}")87 XCTAssertEqual(response.requestID, "req-abcdefgh")88 XCTAssertTrue(response.isIdempotentReplay)89 XCTAssertTrue(response.isExisting)90 }9192 func testQueryEncoding() async throws {93 StubServer.shared.reset { _ in .json("[]") }94 let (client, _) = TestEnv.client()95 _ = try await client.send(.get("/api/search", query: [URLQueryItem(name: "q", value: "a+b & c=d é"), URLQueryItem(name: "mode", value: "quick")]))96 XCTAssertEqual(StubServer.shared.last?.url.absoluteString, "https://notes.test/api/search?q=a%2Bb%20%26%20c%3Dd%20%C3%A9&mode=quick")97 XCTAssertEqual(HTTPRequest.segment("a/b?c#d e"), "a%2Fb%3Fc%23d%20e")98 }99100 // MARK: cookies101102 func testSetCookieParsing() {103 let header = "__Host-note_wa=abc-123; Path=/; Max-Age=300; HttpOnly; SameSite=Strict; Secure, __Host-note_session=tok_1; Path=/; Expires=Wed, 16 Feb 2067 10:00:00 GMT; HttpOnly, other=; Max-Age=0"104 let cookies = SetCookie.parse(header)105 XCTAssertEqual(cookies.map(\.name), ["__Host-note_wa", "__Host-note_session", "other"])106 XCTAssertEqual(cookies[0].value, "abc-123")107 XCTAssertEqual(cookies[0].maxAge, 300)108 XCTAssertFalse(cookies[0].isCleared)109 XCTAssertEqual(cookies[1].value, "tok_1")110 XCTAssertEqual(cookies[1].expires, APIDate.parse("2067-02-16T10:00:00Z"))111 XCTAssertFalse(cookies[1].isCleared)112 XCTAssertTrue(cookies[2].isCleared)113 XCTAssertTrue(SetCookie.parse("s=x; Expires=Thu, 01 Jan 1970 00:00:00 GMT")[0].isCleared)114 XCTAssertTrue(SetCookie.parse("s=x; Max-Age=0")[0].isCleared)115 XCTAssertTrue(SetCookie.parse("s=; Path=/")[0].isCleared)116 XCTAssertEqual(SetCookie.parse(""), [])117 }118119 func testLoginStoresTokenAndRotationReplacesIt() async throws {120 StubServer.shared.reset { request in121 switch request.path {122 case "/login": return .json("{\"ok\":true}", headers: ["Set-Cookie": "__Host-note_session=tok_first; Path=/; HttpOnly; Secure; SameSite=Lax; Expires=Wed, 16 Feb 2067 10:00:00 GMT, __Host-note_wa=; Path=/; Max-Age=0"])123 case "/rotate": return .json("{\"ok\":true}", headers: ["Set-Cookie": "__Host-note_session=tok_second; Path=/; HttpOnly; Secure"])124 default: return .json("{}")125 }126 }127 let (client, store) = TestEnv.client(token: nil)128 var events = await client.sessionEvents().makeAsyncIterator()129130 let login = try await client.send(HTTPRequest(method: .post, path: "/login"))131 XCTAssertNil(login.header("Set-Cookie"), "cookies are never handed to callers")132 XCTAssertEqual(store.load(), "tok_first")133 let signedIn = await events.next()134 XCTAssertEqual(signedIn, .signedIn)135136 _ = try await client.send(.get("/after"))137 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), "__Host-note_session=tok_first")138139 _ = try await client.send(HTTPRequest(method: .post, path: "/rotate"))140 XCTAssertEqual(store.load(), "tok_second")141 let rotated = await events.next()142 XCTAssertEqual(rotated, .tokenRotated)143144 _ = try await client.send(.get("/after"))145 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), "__Host-note_session=tok_second")146 XCTAssertEqual(store.saveCount, 2)147148 // The same token again is not a rotation.149 StubServer.shared.reset { _ in .json("{}", headers: ["Set-Cookie": "__Host-note_session=tok_second; Path=/"]) }150 _ = try await client.send(.get("/again"))151 XCTAssertEqual(store.saveCount, 2)152 }153154 func testCeremonyCookieIsReplayedOnMatchingVerifyOnly() async throws {155 StubServer.shared.reset { request in156 switch request.path {157 case "/api/auth/reauth/options": return .json("{}", headers: ["Set-Cookie": "__Host-note_wa=ceremony-1; Path=/; Max-Age=300; HttpOnly; SameSite=Strict; Secure"])158 case "/api/auth/login/options": return .json("{}", headers: ["Set-Cookie": "__Host-note_wa=ceremony-login; Path=/; Max-Age=300"])159 case "/plain": return .json("{}", headers: ["Set-Cookie": "__Host-note_wa=stray; Path=/; Max-Age=300"])160 default: return .json("{}")161 }162 }163 let (client, _) = TestEnv.client()164 let session = "__Host-note_session=\(TestEnv.token)"165166 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/reauth/options", ceremony: .begin("reauth")))167 var held = await client.holdsCeremonyCookie("reauth")168 XCTAssertTrue(held)169170 // An unrelated request does not carry the ceremony cookie…171 _ = try await client.send(.get("/api/sync"))172 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), session)173 // …nor does the verify call of another ceremony.174 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/login/verify", ceremony: .complete("login")))175 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), session)176177 // The matching verify call carries it, once.178 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/reauth/verify", ceremony: .complete("reauth")))179 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), "\(session); __Host-note_wa=ceremony-1")180 held = await client.holdsCeremonyCookie("reauth")181 XCTAssertFalse(held)182 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/reauth/verify", ceremony: .complete("reauth")))183 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), session)184185 // A ceremony cookie on an answer that is not an options call is ignored.186 _ = try await client.send(.get("/plain"))187 for key in ["login", "reauth", "register"] {188 let stray = await client.holdsCeremonyCookie(key)189 XCTAssertFalse(stray)190 }191192 // Two ceremonies in flight keep separate cookies.193 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/login/options", ceremony: .begin("login")))194 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/reauth/options", ceremony: .begin("reauth")))195 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/login/verify", ceremony: .complete("login")))196 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), "\(session); __Host-note_wa=ceremony-login")197 }198199 func testUnauthorizedClearsTokenAndEmitsSignedOutExactlyOnce() async throws {200 StubServer.shared.reset { _ in .json("{\"error\":\"Sign-in required\",\"code\":\"unauthenticated\"}", status: 401) }201 let (client, store) = TestEnv.client()202 var events = await client.sessionEvents().makeAsyncIterator()203 var secondListener = await client.sessionEvents().makeAsyncIterator()204205 // Several requests fail at the same time: one event.206 async let a = captureAPIError { try await client.send(.get("/api/sync")) }207 async let b = captureAPIError { try await client.send(.get("/api/tags")) }208 async let c = captureAPIError { try await client.send(.get("/api/tasks")) }209 let errors = await [a, b, c]210 XCTAssertTrue(errors.allSatisfy { $0?.isUnauthenticated == true })211 XCTAssertNil(store.load())212 XCTAssertEqual(store.clearCount, 1)213 let has = await client.hasSession214 XCTAssertFalse(has)215216 // Later 401s (no token any more) add nothing.217 _ = await captureAPIError { try await client.send(.get("/api/sync")) }218 XCTAssertNil(StubServer.shared.last?.header("Cookie"))219 await client.clearSession()220221 // A marker event proves that exactly one sign-out was emitted before it.222 await client.setSessionToken("tok_new")223 let first = await events.next()224 let second = await events.next()225 XCTAssertEqual(first, .signedOut(.unauthorized))226 XCTAssertEqual(second, .signedIn)227 let otherFirst = await secondListener.next()228 XCTAssertEqual(otherFirst, .signedOut(.unauthorized))229 }230231 func testClearedCookieSignsOutOnce() async throws {232 StubServer.shared.reset { _ in .json("{\"ok\":true}", headers: ["Set-Cookie": "__Host-note_session=; Path=/; Max-Age=0; HttpOnly; Secure"]) }233 let (client, store) = TestEnv.client()234 var events = await client.sessionEvents().makeAsyncIterator()235 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/logout"))236 _ = try await client.send(HTTPRequest(method: .post, path: "/api/auth/logout"))237 XCTAssertNil(store.load())238 XCTAssertEqual(store.clearCount, 1)239 await client.setSessionToken("tok_marker")240 let first = await events.next()241 let second = await events.next()242 XCTAssertEqual(first, .signedOut(.cookieCleared))243 XCTAssertEqual(second, .signedIn)244 }245246 func testLocalClearEmitsOnceAndStaleUnauthorizedIsIgnored() async throws {247 let (client, store) = TestEnv.client()248 var events = await client.sessionEvents().makeAsyncIterator()249 await client.clearSession()250 await client.clearSession()251 let first = await events.next()252 XCTAssertEqual(first, .signedOut(.local))253 XCTAssertEqual(store.clearCount, 1)254255 // A 401 answering a request sent without a token never signs out.256 StubServer.shared.reset { _ in .json("{\"error\":\"x\",\"code\":\"unauthenticated\"}", status: 401) }257 _ = await captureAPIError { try await client.send(.get("/api/sync")) }258 await client.setSessionToken("tok_marker")259 let second = await events.next()260 XCTAssertEqual(second, .signedIn)261 }262263 func testUnauthorizedForAnOlderTokenDoesNotEndTheRotatedSession() async throws {264 // The answer rotates the token AND is a 401 for the token that was sent: the new token must survive.265 StubServer.shared.reset { _ in .json("{\"error\":\"x\",\"code\":\"unauthenticated\"}", status: 401, headers: ["Set-Cookie": "__Host-note_session=tok_rotated; Path=/"]) }266 let (client, store) = TestEnv.client()267 _ = await captureAPIError { try await client.send(.get("/api/sync")) }268 XCTAssertEqual(store.load(), "tok_rotated")269 XCTAssertEqual(store.clearCount, 0)270 }271272 // MARK: errors and transport273274 func testTransportErrorsAreTyped() async {275 let (client, _) = TestEnv.client()276 let cases: [(URLError.Code, APIError)] = [277 (.notConnectedToInternet, .offline), (.dataNotAllowed, .offline), (.timedOut, .timeout),278 (.networkConnectionLost, .transport(.networkConnectionLost)), (.cannotFindHost, .transport(.cannotFindHost)),279 (.secureConnectionFailed, .transport(.secureConnectionFailed)),280 ]281 for (code, expected) in cases {282 StubServer.shared.reset { _ in .failure(code) }283 let error = await captureAPIError { try await client.send(.get("/api/sync")) }284 XCTAssertEqual(error, expected)285 XCTAssertEqual(error?.isRetryable, true)286 XCTAssertNil(error?.status)287 }288 let has = await client.hasSession289 XCTAssertTrue(has, "a transport failure never ends the session")290 }291292 func testCancellationIsTyped() async {293 StubServer.shared.reset { _ in .json("{}") }294 let (client, _) = TestEnv.client()295 let task = Task { () -> APIError? in296 do { _ = try await client.send(.get("/api/sync")); return nil } catch { return error as? APIError }297 }298 task.cancel()299 let error = await task.value300 if let error { // the request may also have completed before the cancellation was seen301 XCTAssertEqual(error, .cancelled)302 XCTAssertFalse(error.isRetryable)303 }304 }305306 func testDecodingFailureIsTyped() async {307 StubServer.shared.reset { _ in .json("{\"ok\":\"yes\"}") }308 let (client, _) = TestEnv.client()309 let error = await captureAPIError { try await client.decode(OKResult.self, .get("/api/x")) }310 guard case .decoding(let detail) = error else { return XCTFail("\(String(describing: error))") }311 XCTAssertTrue(detail.contains("ok"), detail)312 }313314 // MARK: transfers315316 func testUploadFromFileSendsHeadersAndDecodesAnswer() async throws {317 StubServer.shared.reset { _ in .json("{\"id\":\"a1\"}", status: 201, headers: ["x-existing": "1"]) }318 let (client, _) = TestEnv.client()319 let file = FileManager.default.temporaryDirectory.appendingPathComponent("spn-upload-\(UUID().uuidString).bin")320 try Data(repeating: 0x41, count: 4096).write(to: file)321 defer { try? FileManager.default.removeItem(at: file) }322 let response = try await client.upload(HTTPRequest(method: .post, path: "/api/attachments", contentType: "multipart/form-data; boundary=b"), fromFile: file)323 XCTAssertEqual(response.status, 201)324 XCTAssertTrue(response.isExisting)325 let request = try XCTUnwrap(StubServer.shared.last)326 XCTAssertEqual(request.method, "POST")327 XCTAssertEqual(request.header("Content-Type"), "multipart/form-data; boundary=b")328 XCTAssertEqual(request.header("Origin"), "https://notes.test")329 XCTAssertEqual(request.header("Cookie"), "__Host-note_session=\(TestEnv.token)")330 if !request.body.isEmpty { XCTAssertEqual(request.body.count, 4096) }331 }332333 func testUploadErrorIsMapped() async throws {334 StubServer.shared.reset { _ in .json("{\"error\":\"File type not allowed\"}", status: 415) }335 let (client, _) = TestEnv.client()336 let file = FileManager.default.temporaryDirectory.appendingPathComponent("spn-upload-\(UUID().uuidString).bin")337 try Data("x".utf8).write(to: file)338 defer { try? FileManager.default.removeItem(at: file) }339 let error = await captureAPIError { try await client.upload(HTTPRequest(method: .post, path: "/api/attachments"), fromFile: file) }340 XCTAssertEqual(error?.status, 415)341 XCTAssertEqual(error?.message, "File type not allowed")342 }343344 func testDownloadWritesFileAndReplacesExisting() async throws {345 let payload = Data((0..<50_000).map { UInt8($0 % 251) })346 StubServer.shared.reset { _ in StubReply(status: 200, headers: ["Content-Type": "image/png", "Content-Length": "\(payload.count)"], body: payload) }347 let (client, _) = TestEnv.client()348 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spn-dl-\(UUID().uuidString)/nested")349 let destination = directory.appendingPathComponent("file.png")350 defer { try? FileManager.default.removeItem(at: directory.deletingLastPathComponent()) }351 for _ in 0..<2 { // the second pass replaces the file352 let response = try await client.download(.get("/api/files/abc"), to: destination)353 XCTAssertEqual(response.contentType, "image/png")354 XCTAssertEqual(try Data(contentsOf: destination), payload)355 }356 XCTAssertEqual(StubServer.shared.last?.header("Cookie"), "__Host-note_session=\(TestEnv.token)")357 XCTAssertNil(StubServer.shared.last?.header("Origin"))358 }359360 func testDownloadErrorLeavesNoFileAndIsMapped() async throws {361 StubServer.shared.reset { _ in .json("{\"error\":\"File not found\"}", status: 404) }362 let (client, _) = TestEnv.client()363 let destination = FileManager.default.temporaryDirectory.appendingPathComponent("spn-dl-\(UUID().uuidString).bin")364 let error = await captureAPIError { try await client.download(.get("/api/files/missing"), to: destination) }365 XCTAssertEqual(error?.status, 404)366 XCTAssertEqual(error?.message, "File not found")367 XCTAssertEqual(error?.isNotFound, true)368 XCTAssertFalse(FileManager.default.fileExists(atPath: destination.path))369 }370371 // MARK: token stores372373 func testInMemoryTokenStore() {374 let store = InMemoryTokenStore()375 XCTAssertNil(store.load())376 store.save("abc")377 XCTAssertEqual(store.load(), "abc")378 store.clear()379 XCTAssertNil(store.load())380 }381382 func testKeychainTokenStoreRoundTrip() throws {383 // The legacy file keychain is used here: the data-protection keychain needs a signed app with entitlements.384 let store = KeychainTokenStore(service: "ai.spboucher.spnotes.tests", account: "unit-\(UUID().uuidString)", useDataProtectionKeychain: false)385 do { try store.save("tok_keychain_1") } catch { throw XCTSkip("no usable keychain in this environment: \(error)") }386 defer { try? store.clear() }387 XCTAssertEqual(store.load(), "tok_keychain_1")388 try store.save("tok_keychain_2")389 XCTAssertEqual(store.load(), "tok_keychain_2")390 try store.clear()391 XCTAssertNil(store.load())392 try store.clear() // clearing twice is not an error393 }394}395