Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Claude Remote / Codex Remote9// File : Packages/ClaudeRemoteKit/Tests/APITests/APIClientTests.swift10// Module : APITests11// Repository : https://git.spboucher.ai/claude-remote-apple12// Project Website : https://claude.spboucher.ai13// Created : 2026-11-2914// Last Modified : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteAPI89import ClaudeRemoteModels90import ClaudeRemoteTestSupport91import Foundation92import Testing9394/// Scripted `SessionAuthority`.95final class FakeAuthority: SessionAuthority, @unchecked Sendable {96 private let lock = NSLock()97 private var _refreshes = 098 private var _rejected: [String] = []99 var result: Result<NativeSession, APIError>100 var delay: Duration = .zero101102 init(result: Result<NativeSession, APIError>) { self.result = result }103 var refreshes: Int { lock.withLock { _refreshes } }104 var rejected: [String] { lock.withLock { _rejected } }105106 func refreshSession() async throws -> NativeSession {107 lock.withLock { _refreshes += 1 }108 if delay > .zero { try await Task.sleep(for: delay) }109 return try result.get()110 }111 func sessionWasRejected(token: String) async { lock.withLock { _rejected.append(token) } }112}113114func freshSession(_ token: String = Fixtures.token2) -> NativeSession {115 NativeSession(id: Fixtures.authSessionID, token: token, tokenExpiresAt: Date().addingTimeInterval(3600), expiresAt: Date().addingTimeInterval(86400), secondFactor: true)116}117118func makeClient(_ server: StubServer, sockets: FakeWebSocketTransport? = nil, token: String? = Fixtures.token) async throws -> APIClient {119 let client = try APIClient(baseURL: server.baseURL, client: .test, configuration: server.configuration, webSocketTransport: sockets)120 if let token { await client.setCredential(token: token, expiresAt: Date().addingTimeInterval(3600)) }121 return client122}123124@Suite("APIClient: requests, headers, typed endpoints")125struct APIClientRequestTests {126 @Test func refusesInsecureBaseURLs() throws {127 #expect(throws: APIError.self) { try APIClient(baseURL: URL(string: "http://claude.spboucher.ai")!, client: .test) }128 #expect(throws: APIError.self) { try APIClient(baseURL: URL(string: "ftp://localhost")!, client: .test) }129 #expect(throws: APIError.self) { try APIClient(baseURL: URL(string: "http://localhost.evil.example")!, client: .test) }130 _ = try APIClient(baseURL: URL(string: "https://claude.spboucher.ai")!, client: .test)131 _ = try APIClient(baseURL: URL(string: "http://localhost:8625")!, client: .test)132 _ = try APIClient(baseURL: URL(string: "http://127.0.0.1:8625/")!, client: .test)133 do { try APIClient.validate(URL(string: "http://example.com")!) } catch let e as APIError { #expect(e.code == "insecure_url" && e.kind == .client) }134 }135136 @Test func bearerAndClientHeadersOnSessionRequests() async throws {137 let server = StubServer()138 server.on("GET", "/api/v1/sessions") { _ in .json("[\(Fixtures.session()),\(Fixtures.sessionStopped)]") }139 let client = try await makeClient(server)140 let sessions = try await client.sessions(archived: true)141 #expect(sessions.count == 2)142 let request = try #require(server.requests.first)143 #expect(request.bearer == Fixtures.token)144 #expect(request.header("X-CR-Client") == "native/macos/1.0-test")145 #expect(request.query == ["archived": "1"])146 #expect(request.header("Cookie") == nil && request.header("Origin") == nil && request.header("X-CSRF-Token") == nil)147 }148149 @Test func preauthPostsCarryJSONContentTypeAndNoBearer() async throws {150 let server = StubServer()151 server.on("POST", "/api/v1/native/auth/passkey/options") { _ in .json(Fixtures.passkeyDiscoverableOptions) }152 server.on("POST", "/api/v1/native/auth/refresh/challenge") { _ in .json(#"{"challenge":"abc","expiresAt":"2026-11-20T02:26:00.000Z"}"#) }153 let client = try await makeClient(server)154 _ = try await client.nativePasskeyOptions()155 _ = try await client.nativeRefreshChallenge(sessionId: Fixtures.authSessionID)156 for request in server.requests {157 #expect(request.bearer == nil)158 #expect(request.header("Content-Type") == "application/json")159 #expect(request.header("X-CR-Client") == "native/macos/1.0-test")160 }161 #expect(server.requests[0].json == [:]) // never an empty body with a JSON content type162 #expect(server.requests[1].json == ["sessionId": .string(Fixtures.authSessionID)])163 }164165 @Test func sessionRequestWithoutCredentialFailsLocally() async throws {166 let server = StubServer()167 let client = try await makeClient(server, token: nil)168 await #expect(throws: APIError.notSignedIn) { _ = try await client.projects() }169 #expect(server.requests.isEmpty)170 }171172 @Test func typedEndpointsUseTheDocumentedRoutes() async throws {173 let server = StubServer()174 let pid = Fixtures.projectID, sid = Fixtures.sessionID, tid = Fixtures.taskID175 server.on("POST", "/api/v1/sessions") { _ in .json(Fixtures.session(), status: 201) }176 server.on("PATCH", "/api/v1/sessions/\(sid)") { _ in .json(Fixtures.session(pinned: true)) }177 server.on("POST", "/api/v1/sessions/\(sid)/terminate") { _ in .json(Fixtures.session(state: "STOPPING")) }178 server.on("POST", "/api/v1/sessions/\(sid)/reconnect") { _ in .json(Fixtures.session(state: "STARTING")) }179 server.on("GET", "/api/v1/sessions/\(sid)/snapshot") { _ in .json(#"{"text":"hi"}"#) }180 server.on("GET", "/api/v1/projects/\(pid)/conversations") { _ in .json(Fixtures.conversations) }181 server.on("GET", "/api/v1/projects/\(pid)/files") { _ in .json(Fixtures.fileEntries) }182 server.on("GET", "/api/v1/projects/\(pid)/file") { _ in .json(Fixtures.fileContent) }183 server.on("POST", "/api/v1/projects/\(pid)/fs") { _ in .json(#"{"ok":true}"#) }184 server.on("GET", "/api/v1/projects/\(pid)/search") { _ in .json(Fixtures.searchHits) }185 server.on("GET", "/api/v1/projects/\(pid)/git/status") { _ in .json(Fixtures.gitStatus) }186 server.on("GET", "/api/v1/projects/\(pid)/git/diff") { _ in .json(#"{"diff":"","truncated":false}"#) }187 server.on("GET", "/api/v1/tasks") { _ in .json("[\(Fixtures.task())]") }188 server.on("POST", "/api/v1/tasks/\(tid)/cancel") { _ in .json(Fixtures.task(state: "CANCELLING")) }189 server.on("POST", "/api/v1/tasks/\(tid)/retry") { _ in .json(Fixtures.task(state: "QUEUED"), status: 201) }190 server.on("GET", "/api/v1/tasks/\(tid)/log") { _ in .bytes(Data("line 1\nline 2\n".utf8), headers: ["X-Log-Size": "4096"]) }191 server.on("GET", "/api/v1/cluster/nodes") { _ in .json(Fixtures.clusterOverview) }192 server.on("GET", "/api/v1/cluster/nodes/M5M36") { _ in .json(Fixtures.clusterNodeDetail) }193 server.on("GET", "/api/v1/cluster/metrics") { _ in .json(Fixtures.clusterMetrics) }194 server.on("GET", "/api/v1/cluster/apps") { _ in .json(Fixtures.clusterApps) }195 server.on("GET", "/api/v1/cluster/incidents") { _ in .json(Fixtures.clusterIncidents) }196 server.on("GET", "/api/v1/cluster/trend") { _ in .json(Fixtures.clusterTrend) }197 server.on("GET", "/api/v1/cluster/models") { _ in .json(Fixtures.localModels) }198 server.on("POST", "/api/v1/cluster/models/qwen3-30b/test") { _ in .json(Fixtures.modelTest) }199 server.on("GET", "/api/v1/skills") { _ in .json(Fixtures.skills) }200 server.on("POST", "/api/v1/skills/op") { _ in .json(#"{"ok":true}"#) }201 server.on("GET", "/api/v1/mcp") { _ in .json(Fixtures.mcpServers) }202 server.on("POST", "/api/v1/mcp") { _ in .json(#"{"ok":true}"#, status: 201) }203 server.on("DELETE", "/api/v1/mcp/notion") { _ in .json(#"{"ok":true}"#) }204 server.on("POST", "/api/v1/mcp/notion/test") { _ in .json(#"{"name":"notion","scope":"project","transport":"http","target":"https://mcp.notion.com/mcp","envKeys":[],"status":"connected","lastError":null,"checkedAt":"2026-11-20T02:25:00.000Z"}"#) }205 server.on("GET", "/api/v1/system/status") { _ in .json(Fixtures.systemStatus) }206 server.on("GET", "/api/v1/system/audit") { _ in .json(Fixtures.audit) }207 server.on("GET", "/api/v1/notifications") { _ in .json("[\(Fixtures.notification())]") }208 server.on("POST", "/api/v1/notifications/read") { _ in .json(#"{"ok":true,"updated":1}"#) }209 server.on("GET", "/api/v1/settings") { _ in .json(Fixtures.settings) }210 server.on("PUT", "/api/v1/settings") { r in StubResponse(status: 200, headers: ["Content-Type": "application/json"], body: r.body) }211 server.on("GET", "/api/v1/native/summary") { _ in .json(Fixtures.summary) }212 server.on("PUT", "/api/v1/native/push") { _ in .json(#"{"ok":true,"configured":true}"#) }213 server.on("DELETE", "/api/v1/native/push") { _ in .json(#"{"ok":true}"#) }214 server.on("GET", "/api/v1/auth/devices") { _ in .json(Fixtures.devices) }215 server.on("DELETE", "/api/v1/auth/devices/\(Fixtures.authSessionID)") { _ in .json(#"{"ok":true}"#) }216 server.on("GET", "/api/v1/workspace/roots") { _ in .json(#"[{"label":"workspace"}]"#) }217 server.on("GET", "/api/v1/health") { _ in .json(#"{"ok":true,"version":"1.4.0"}"#) }218 let client = try await makeClient(server)219220 #expect(try await client.createSession(CreateSession(projectId: pid, kind: .shell)).id == sid)221 #expect(server.requests.last?.json?["kind"] == "shell")222 #expect(try await client.updateSession(id: sid, UpdateSession(pinned: true)).pinned)223 #expect(try await client.terminateSession(id: sid).state == .stopping)224 #expect(try await client.reconnectSession(id: sid, restart: true).state == .starting)225 #expect(server.requests.last?.json == ["restart": true])226 #expect(try await client.sessionSnapshot(id: sid).text == "hi")227 #expect(try await client.conversations(projectId: pid).count == 1)228 #expect(try await client.listFiles(projectId: pid, path: "src/a b").count == 5)229 #expect(server.requests.last?.query == ["path": "src/a b"])230 #expect(try await client.readFile(projectId: pid, path: "a+b&c=d/é.md").path == "README.md")231 #expect(server.requests.last?.query["path"] == "a+b&c=d/é.md") // "+" and "&" survive the query encoding232 try await client.fsOp(projectId: pid, .delete(path: "tmp"))233 #expect(server.requests.last?.json == ["op": "delete", "path": "tmp", "confirm": true])234 #expect(try await client.searchFiles(projectId: pid, query: "hello", mode: .content, path: "src", limit: 20).count == 2)235 #expect(server.requests.last?.query == ["q": "hello", "mode": "content", "path": "src", "limit": "20"])236 #expect(try await client.gitStatus(projectId: pid).isRepo)237 _ = try await client.gitDiff(projectId: pid, path: "README.md", staged: true)238 #expect(server.requests.last?.query == ["path": "README.md", "staged": "1"])239 #expect(try await client.tasks(limit: 10, projectId: pid).count == 1)240 #expect(server.requests.last?.query == ["limit": "10", "projectId": pid])241 #expect(try await client.cancelTask(id: tid).state == .cancelling)242 #expect(try await client.retryTask(id: tid).state == .queued)243 let log = try await client.taskLog(id: tid, offset: 100, limit: 2048)244 #expect(log.text == "line 1\nline 2\n" && log.totalSize == 4096 && log.nextOffset == 114 && !log.isAtEnd)245 #expect(server.requests.last?.query == ["offset": "100", "limit": "2048"])246 #expect(try await client.clusterOverview().nodes.count == 2)247 #expect(try await client.clusterNode(id: "M5M36").history.count == 2)248 _ = try await client.clusterMetrics(node: "M5M36", minutes: 120)249 #expect(server.requests.last?.query == ["node": "M5M36", "minutes": "120"])250 #expect(try await client.clusterApps().apps.count == 2)251 #expect(try await client.clusterIncidents().count == 2)252 #expect(try await client.clusterTrend().points.count == 2)253 #expect(try await client.localModels().count == 2)254 #expect(try await client.testLocalModel(id: "qwen3-30b").ok)255 #expect(try await client.skills(projectId: pid).count == 3)256 try await client.skillOp(.enable(name: "deploy", kind: .command, scope: .project, projectId: pid))257 _ = try await client.mcpServers(live: true, refresh: true)258 #expect(server.requests.last?.query == ["live": "1", "refresh": "1"])259 try await client.addMcpServer(AddMcpServer(name: "notion", transport: .http, target: "https://mcp.notion.com/mcp", headers: ["Authorization": "Bearer secret"]))260 try await client.removeMcpServer(name: "notion", scope: .project, projectId: pid)261 #expect(server.requests.last?.query == ["scope": "project", "projectId": pid])262 #expect(try await client.testMcpServer(name: "notion", scope: .project, projectId: pid).status == .connected)263 #expect(try await client.systemStatus().version == "1.4.0")264 _ = try await client.audit(limit: 50, before: "1041", action: "fs.op")265 #expect(server.requests.last?.query == ["limit": "50", "before": "1041", "action": "fs.op"])266 _ = try await client.notifications(limit: 20, unreadOnly: true)267 #expect(server.requests.last?.query == ["limit": "20", "unread": "1"])268 #expect(try await client.markNotificationsRead(ids: ["a"]).updated == 1)269 #expect(server.requests.last?.json == ["ids": ["a"]])270 try await client.markAllNotificationsRead()271 #expect(server.requests.last?.json == ["all": true])272 var settings = try await client.settings()273 settings.theme = .dark274 #expect(try await client.saveSettings(settings).theme == .dark)275 #expect(try await client.summary().notificationsUnread == 4)276 #expect(try await client.registerPush(PushRegistration(apnsToken: "ab", environment: .production, topic: "ai.spboucher.clauderemote")).configured)277 try await client.unregisterPush()278 #expect(try await client.devices().count == 4)279 try await client.revokeDevice(id: Fixtures.authSessionID)280 #expect(try await client.workspaceRoots().first?.label == "workspace")281 #expect(try await client.health().ok)282 #expect(server.requests.last?.bearer == nil) // /health is public: no credential sent283 // DELETE requests carry neither a body nor a JSON content type.284 let deletes = server.requests.filter { $0.method == "DELETE" }285 #expect(deletes.count == 3 && deletes.allSatisfy { $0.body.isEmpty && $0.header("Content-Type") == nil })286 }287288 @Test func uploadStreamsTheFileAndDownloadWritesTheDestination() async throws {289 let server = StubServer()290 let pid = Fixtures.projectID291 let payload = Data((0..<200_000).map { UInt8($0 % 251) })292 server.on("POST", "/api/v1/projects/\(pid)/upload") { r in r.query["overwrite"] == "1" ? .json(#"{"ok":true}"#, status: 201) : .error(409, "exists", "destination exists") }293 server.on("GET", "/api/v1/projects/\(pid)/download") { _ in .bytes(payload, headers: ["Content-Length": String(payload.count)]) }294 server.on("GET", "/api/v1/tasks/\(Fixtures.taskID)/artifacts/art") { _ in .error(404, "not_found", "artifact") }295 let client = try await makeClient(server)296 let dir = FileManager.default.temporaryDirectory.appending(path: "cr-tests-\(UUID().uuidString)")297 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)298 defer { try? FileManager.default.removeItem(at: dir) }299 let source = dir.appending(path: "data.bin")300 try payload.write(to: source)301302 do {303 try await client.upload(projectId: pid, path: "up/data.bin", from: source)304 Issue.record("expected 409 exists")305 } catch let e as APIError {306 #expect(e.kind == .exists)307 }308 try await client.upload(projectId: pid, path: "up/data.bin", from: source, overwrite: true)309 let upload = try #require(server.requests.last)310 #expect(upload.body == payload && upload.header("Content-Type") == "application/octet-stream" && upload.query == ["path": "up/data.bin", "overwrite": "1"] && upload.bearer == Fixtures.token)311312 let destination = dir.appending(path: "nested/out.bin")313 try await client.download(projectId: pid, path: "up/data.bin", to: destination)314 #expect(try Data(contentsOf: destination) == payload)315 try await client.download(projectId: pid, path: "up/data.bin", to: destination) // replaces an existing file316 #expect(try Data(contentsOf: destination) == payload)317318 let missing = dir.appending(path: "artifact.bin")319 do {320 try await client.downloadArtifact(taskId: Fixtures.taskID, artifactId: "art", to: missing)321 Issue.record("expected 404")322 } catch let e as APIError {323 #expect(e.kind == .notFound && e.code == "not_found")324 }325 #expect(!FileManager.default.fileExists(atPath: missing.path))326 }327}328329@Suite("APIError mapping")330struct APIErrorTests {331 @Test func mapsTheServerEnvelope() {332 func make(_ status: Int, _ code: String, details: String? = nil, headers: [String: String] = [:]) -> APIError {333 APIError.from(status: status, data: StubResponse.error(status, code, "msg", details: details).body, headers: headers)334 }335 #expect(make(401, "unauthenticated").kind == .unauthenticated && make(401, "unauthenticated").requiresSignIn)336 #expect(make(401, "token_expired").kind == .tokenExpired && !make(401, "token_expired").requiresSignIn)337 #expect(make(401, "invalid_credentials").kind == .invalidCredentials && make(401, "invalid_code").kind == .invalidCredentials)338 #expect(make(403, "second_factor_required").kind == .secondFactorRequired)339 #expect(make(403, "bad_client").kind == .forbidden && make(403, "bad_origin").kind == .forbidden && make(403, "host_not_allowed").kind == .forbidden)340 #expect(make(404, "not_found").kind == .notFound)341 #expect(make(409, "exists").kind == .exists && make(409, "invalid_state").kind == .invalidState && make(409, "session_live").kind == .invalidState)342 #expect(make(413, "payload_too_large").kind == .payloadTooLarge && make(415, "binary").kind == .binary)343 #expect(make(429, "rate_limited").kind == .rateLimited && make(429, "too_many_sessions").kind == .tooManySessions)344 #expect(make(400, "invalid_request").kind == .invalidRequest && make(501, "not_implemented").kind == .notImplemented)345 #expect(make(503, "runtime_unavailable").kind == .runtimeUnavailable && make(503, "runtime_unavailable").isTransient)346 #expect(make(502, "runtime_error").kind == .server && make(502, "runtime_error").isTransient && make(500, "internal").kind == .server)347348 let conflict = make(409, "conflict", details: #"{"sha256":"abc123","mtimeMs":1795000000000}"#)349 #expect(conflict.kind == .conflict && conflict.conflictSha256 == "abc123")350 let deleted = make(409, "conflict", details: #"{"sha256":null,"mtimeMs":null}"#)351 #expect(deleted.kind == .conflict && deleted.conflictSha256 == nil)352353 let locked = make(429, "locked", details: #"{"retryAfterSec":42}"#)354 #expect(locked.kind == .locked && locked.retryAfter == 42)355 let lockedHeader = make(429, "locked", details: #"{"retryAfterSec":42}"#, headers: ["Retry-After": "17"])356 #expect(lockedHeader.retryAfter == 17) // the header wins357358 let invalid = make(400, "invalid_request", details: #"[{"path":"cols","message":"Too small"},{"path":["device","name"],"message":"Required"}]"#)359 #expect(invalid.validationIssues.map(\.path) == ["cols", "device.name"] && invalid.validationIssues[0].message == "Too small")360 #expect(invalid.errorDescription == "msg")361 }362363 @Test func toleratesNonJSONBodiesAndTransportFailures() {364 let html = APIError.from(status: 502, data: Data("<html>Bad Gateway</html>".utf8))365 #expect(html.code == "bad_gateway" && html.kind == .server && html.isTransient)366 #expect(APIError.from(status: 401, data: Data()).kind == .unauthenticated)367 #expect(APIError.from(status: 429, data: Data(), headers: ["retry-after": "5"]).retryAfter == 5)368 #expect(APIError.wrap(URLError(.notConnectedToInternet)).kind == .network && APIError.wrap(URLError(.notConnectedToInternet)).isTransient)369 #expect(APIError.wrap(URLError(.cancelled)).kind == .cancelled && APIError.wrap(CancellationError()).kind == .cancelled)370 #expect(APIError.wrap(APIError.notSignedIn) == APIError.notSignedIn)371 #expect(APIError.wrap(DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: ""))).kind == .decoding)372 }373374 @Test func surfacesServerErrorsFromRequests() async throws {375 let server = StubServer()376 server.on("GET", "/api/v1/projects") { _ in .error(503, "runtime_unavailable", "the runtime daemon is not reachable") }377 server.on("GET", "/api/v1/tasks") { _ in .transportFailure(.timedOut) }378 server.on("GET", "/api/v1/settings") { _ in .json(#"{"theme":42}"#) }379 server.on("POST", "/api/v1/native/auth/login") { _ in .error(429, "locked", "too many failed attempts, try again later", details: #"{"retryAfterSec":120}"#, headers: ["Retry-After": "120"]) }380 let client = try await makeClient(server)381 await #expect(throws: APIError(status: 503, code: "runtime_unavailable", message: "the runtime daemon is not reachable")) { _ = try await client.projects() }382 do { _ = try await client.tasks(); Issue.record("expected a network error") } catch let e as APIError { #expect(e.kind == .network) }383 do { _ = try await client.settings(); Issue.record("expected a decoding error") } catch let e as APIError { #expect(e.kind == .decoding) }384 let device = NativeDevice(installId: "i", name: "n", platform: .macos, model: "m", appVersion: "1", publicKey: "k")385 do {386 _ = try await client.nativeLogin(NativeLoginRequest(username: "admin", password: "wrong", device: device))387 Issue.record("expected 429")388 } catch let e as APIError {389 #expect(e.kind == .locked && e.retryAfter == 120)390 }391 }392}393394@Suite("APIClient: token refresh")395struct TokenRefreshTests {396 /// Server that accepts only `valid` and answers 401 `token_expired` otherwise.397 func server(valid: String) -> StubServer {398 let server = StubServer()399 server.onUnmatched { request in400 guard request.bearer == valid else { return .error(401, "token_expired", "access token expired") }401 return request.path.hasSuffix("/sessions") ? .json("[]") : .json(Fixtures.summary)402 }403 return server404 }405406 @Test func refreshesOnceForConcurrentRequestsAndRetriesEach() async throws {407 let server = server(valid: Fixtures.token2)408 let client = try await makeClient(server)409 let authority = FakeAuthority(result: .success(freshSession()))410 authority.delay = .milliseconds(80)411 await client.setAuthority(authority)412413 try await withThrowingTaskGroup(of: Void.self) { group in414 for i in 0..<12 {415 group.addTask {416 if i % 2 == 0 { _ = try await client.sessions() } else { _ = try await client.summary() }417 }418 }419 try await group.waitForAll()420 }421 #expect(authority.refreshes == 1) // single flight422 #expect(authority.rejected.isEmpty)423 let withNew = server.requests.filter { $0.bearer == Fixtures.token2 }.count424 #expect(withNew == 12 && server.requests.count >= 13 && server.requests.count <= 24)425 // The rotated token is used directly afterwards.426 let before = server.requests.count427 _ = try await client.sessions()428 #expect(server.requests.count == before + 1 && authority.refreshes == 1)429 }430431 @Test func refreshesBeforeTheRequestWhenTheTokenIsAboutToExpire() async throws {432 let server = server(valid: Fixtures.token2)433 let client = try APIClient(baseURL: server.baseURL, client: .test, configuration: server.configuration)434 await client.setCredential(token: Fixtures.token, expiresAt: Date().addingTimeInterval(5)) // inside the 30 s margin435 let authority = FakeAuthority(result: .success(freshSession()))436 await client.setAuthority(authority)437 _ = try await client.sessions()438 #expect(authority.refreshes == 1 && server.requests.count == 1 && server.requests[0].bearer == Fixtures.token2)439 }440441 @Test func refreshFailureWith401SurfacesUnauthenticated() async throws {442 let server = server(valid: "never")443 let client = try await makeClient(server)444 let authority = FakeAuthority(result: .failure(APIError(status: 401, code: "unauthenticated", message: "authentication required")))445 await client.setAuthority(authority)446 do { _ = try await client.sessions(); Issue.record("expected failure") } catch let e as APIError {447 #expect(e.kind == .unauthenticated && e.requiresSignIn)448 }449 #expect(authority.refreshes == 1 && server.requests.count == 1) // no retry after a failed refresh450 }451452 @Test func refreshFailureFromTheNetworkKeepsTheCredential() async throws {453 let server = server(valid: "never")454 let client = try await makeClient(server)455 let authority = FakeAuthority(result: .failure(.network()))456 await client.setAuthority(authority)457 do { _ = try await client.sessions(); Issue.record("expected failure") } catch let e as APIError { #expect(e.kind == .network) }458 #expect(await client.hasCredential && authority.rejected.isEmpty)459 }460461 @Test func aSecondTokenExpiredAfterRefreshIsNotRetriedForever() async throws {462 let server = server(valid: "never")463 let client = try await makeClient(server)464 let authority = FakeAuthority(result: .success(freshSession()))465 await client.setAuthority(authority)466 do { _ = try await client.sessions(); Issue.record("expected failure") } catch let e as APIError { #expect(e.kind == .tokenExpired) }467 #expect(authority.refreshes == 1 && server.requests.count == 2)468 #expect(authority.rejected == [Fixtures.token2]) // still expired after a fresh token: treated as a dead session469 }470471 @Test func unauthenticatedIsReportedToTheAuthorityAndClearsTheCredential() async throws {472 let server = StubServer()473 server.on("GET", "/api/v1/sessions") { _ in .error(401, "unauthenticated", "authentication required") }474 let client = try await makeClient(server)475 let authority = FakeAuthority(result: .success(freshSession()))476 await client.setAuthority(authority)477 do { _ = try await client.sessions(); Issue.record("expected failure") } catch let e as APIError { #expect(e.requiresSignIn) }478 // One refresh is attempted (a rotated-away token also answers `unauthenticated`); the479 // fresh token is refused too, so the session is reported dead.480 #expect(authority.refreshes == 1 && authority.rejected == [Fixtures.token2])481 #expect(await client.hasCredential == false)482 }483484 @Test func aRotatedAwayTokenRecoversThroughOneRefresh() async throws {485 let server = StubServer()486 server.on("GET", "/api/v1/sessions") { r in r.bearer == Fixtures.token2 ? .json("[]") : .error(401, "unauthenticated", "authentication required") }487 let client = try await makeClient(server)488 let authority = FakeAuthority(result: .success(freshSession()))489 await client.setAuthority(authority)490 _ = try await client.sessions()491 #expect(authority.refreshes == 1 && authority.rejected.isEmpty && server.requests.count == 2)492 }493494 @Test func explicitTokenRequestsNeverRefreshNorInvalidate() async throws {495 let server = StubServer()496 server.on("POST", "/api/v1/native/auth/totp") { _ in .error(401, "invalid_code", "invalid code") }497 let client = try await makeClient(server)498 let authority = FakeAuthority(result: .success(freshSession()))499 await client.setAuthority(authority)500 do { _ = try await client.nativeTotp(code: "000000", token: "crn_restricted"); Issue.record("expected failure") } catch let e as APIError {501 #expect(e.kind == .invalidCredentials)502 }503 #expect(server.requests[0].bearer == "crn_restricted" && authority.refreshes == 0 && authority.rejected.isEmpty)504 #expect(await client.hasCredential)505 }506}507508@Suite("APIClient: WebSockets")509struct WebSocketOpenTests {510 @Test func upgradesWithBearerOnTheWSSURL() async throws {511 let server = StubServer()512 let sockets = FakeWebSocketTransport()513 let client = try await makeClient(server, sockets: sockets)514 _ = try await client.openTerminalStream(sessionId: Fixtures.sessionID, cols: 5, rows: 999)515 _ = try await client.openEventStream()516 _ = try await client.openTaskLogStream(taskId: Fixtures.taskID, offset: 1234)517 let urls = sockets.requests.compactMap { $0.url?.absoluteString }518 #expect(urls == ["wss://stub.test/api/v1/sessions/\(Fixtures.sessionID)/stream?cols=20&rows=200",519 "wss://stub.test/api/v1/events",520 "wss://stub.test/api/v1/tasks/\(Fixtures.taskID)/log/stream?offset=1234"])521 for request in sockets.requests {522 #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(Fixtures.token)")523 #expect(request.value(forHTTPHeaderField: "X-CR-Client") == "native/macos/1.0-test")524 #expect(request.value(forHTTPHeaderField: "Origin") == nil)525 }526 }527528 @Test func localhostUsesPlainWS() async throws {529 let sockets = FakeWebSocketTransport()530 let client = try APIClient(baseURL: URL(string: "http://localhost:8625")!, client: .test, webSocketTransport: sockets)531 await client.setCredential(token: Fixtures.token, expiresAt: .distantFuture)532 _ = try await client.openEventStream()533 #expect(sockets.requests.first?.url?.absoluteString == "ws://localhost:8625/api/v1/events")534 }535536 @Test func refusedUpgradesBecomeAPIErrors() async throws {537 let sockets = FakeWebSocketTransport()538 let client = try await makeClient(StubServer(), sockets: sockets)539 for (status, kind) in [(403, APIError.Kind.forbidden), (404, .notFound), (410, .server), (503, .runtimeUnavailable)] {540 sockets.enqueue(.refuse(status: status))541 do { _ = try await client.openEventStream(); Issue.record("expected \(status)") } catch let e as APIError {542 #expect(e.status == status && e.kind == kind)543 }544 }545 sockets.enqueue(.unreachable)546 do { _ = try await client.openEventStream(); Issue.record("expected network") } catch let e as APIError { #expect(e.kind == .network) }547 }548549 @Test func a401UpgradeRefreshesOnceThenRetries() async throws {550 let sockets = FakeWebSocketTransport()551 let client = try await makeClient(StubServer(), sockets: sockets)552 let authority = FakeAuthority(result: .success(freshSession()))553 await client.setAuthority(authority)554 sockets.enqueue(.refuse(status: 401))555 _ = try await client.openEventStream()556 #expect(authority.refreshes == 1 && sockets.requests.count == 2)557 #expect(sockets.requests[1].value(forHTTPHeaderField: "Authorization") == "Bearer \(Fixtures.token2)")558559 // Still 401 with a fresh token: the session is dead.560 sockets.enqueue(.refuse(status: 401), .refuse(status: 401))561 await client.setCredential(token: Fixtures.token, expiresAt: .distantFuture)562 do { _ = try await client.openEventStream(); Issue.record("expected 401") } catch let e as APIError { #expect(e.status == 401) }563 #expect(authority.rejected == [Fixtures.token2])564 }565}566567@Suite("Reconnect policy")568struct ReconnectPolicyTests {569 @Test func exponentialWithJitterAndCap() {570 let low = ReconnectPolicy(random: { 0 }), high = ReconnectPolicy(random: { 0.999999 }), mid = ReconnectPolicy(random: { 0.5 })571 #expect((0..<7).map { mid.delay(attempt: $0) } == [0.5, 1, 2, 4, 8, 10, 10])572 #expect(low.delay(attempt: 0) == 0.375 && abs(high.delay(attempt: 0) - 0.625) < 0.001)573 #expect(low.delay(attempt: 20) == 7.5 && high.delay(attempt: 1000) < 12.5001)574 #expect(ReconnectPolicy(base: 1, maximum: 30, random: { 0.5 }).delay(attempt: 10) == 30)575 for attempt in 0..<12 {576 let d = ReconnectPolicy.standard.delay(attempt: attempt)577 #expect(d >= 0.375 && d <= 12.5)578 }579 }580581 @Test func manualSleeperOnlyMovesWhenAdvanced() async throws {582 let sleeper = ManualSleeper()583 let start = sleeper.now()584 let task = Task { try await sleeper.sleep(seconds: 10); return sleeper.now() }585 #expect(await sleeper.waitForPending())586 sleeper.advance(by: 9.9)587 #expect(sleeper.pendingCount == 1)588 sleeper.advance(by: 0.2)589 #expect(abs(try await task.value - start - 10.1) < 0.0001 && sleeper.requested == [10])590 let cancelled = Task { try await sleeper.sleep(seconds: 5) }591 #expect(await sleeper.waitForPending())592 cancelled.cancel()593 await #expect(throws: CancellationError.self) { try await cancelled.value }594 }595}596