SPB Git

Repository Public

AuthTests.swift 36.2 KB 665 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Tests/AuthTests/AuthTests.swift10// Module           : AuthTests11// 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 ClaudeRemoteAuth90import ClaudeRemoteModels91import ClaudeRemoteTestSupport92import CryptoKit93import Foundation94import Testing9596/// AuthService wired to the in-memory contract implementation.97struct Harness {98    let server = StubServer()99    let backend: StubNativeAuth100    let keychain = InMemoryKeychain()101    let authenticator: SoftwareAuthenticator102    let localAuth = MockLocalAuthenticator()103    let client: APIClient104    let auth: AuthService105    let deviceKeys: KeychainDeviceKeyStore106107    init(factor: StubNativeAuth.SecondFactor = .totp) throws {108        authenticator = SoftwareAuthenticator(userHandle: Data("user-1".utf8), origin: "https://stub.test")109        backend = StubNativeAuth(server: server, secondFactor: factor, passkey: authenticator)110        client = try APIClient(baseURL: server.baseURL, client: .test, configuration: server.configuration)111        deviceKeys = KeychainDeviceKeyStore(keychain: keychain, preferSecureEnclave: false)112        auth = AuthService(113            profile: AgentProfile.claude.with(baseURL: server.baseURL), client: client,114            credentials: CredentialStore(keychain: keychain, scope: "stub.test"), deviceKeys: deviceKeys, passkeys: authenticator,115            localAuth: localAuth, device: DeviceDescriptor(name: "Test Mac", model: "Mac16,5", platform: .macos, appVersion: "1.0-test"))116        server.on("GET", "/api/v1/sessions", backend.guarded { _ in .json("[]") })117    }118119    var stored: StoredCredential? { CredentialStore(keychain: keychain, scope: "stub.test").load() }120}121122@Suite("Auth state machine")123struct AuthStateMachineTests {124    @Test func restoreWithNothingStoredIsSignedOut() async throws {125        let h = try Harness()126        #expect(await h.auth.state == .unknown)127        #expect(await h.auth.restore() == .signedOut(.none))128        #expect(await h.client.hasCredential == false)129    }130131    @Test func passwordOnlyAccountSignsInDirectly() async throws {132        let h = try Harness(factor: .none)133        await h.auth.restore()134        let state = try await h.auth.signIn(username: "admin", password: h.backend.password)135        guard case .signedIn(let info) = state else { Issue.record("expected signedIn, got \(state)"); return }136        #expect(info.sessionId == h.backend.sessionID && info.username == "admin")137        #expect(h.stored?.token == h.backend.currentToken && h.stored?.username == "admin")138        _ = try await h.client.sessions() // the bearer is installed139        // The device declared at sign-in carries the install id and the device public key.140        let device = try #require(h.backend.device)141        #expect(device.installId == h.auth.installID && device.platform == .macos && device.name == "Test Mac" && device.model == "Mac16,5")142        #expect(Data(base64Encoded: device.publicKey) == (try h.deviceKeys.loadOrCreate().publicKeyX963))143    }144145    @Test func totpBranch() async throws {146        let h = try Harness(factor: .totp)147        await h.auth.restore()148        let state = try await h.auth.signIn(username: "admin", password: h.backend.password)149        guard case .secondFactorRequired(let challenge) = state else { Issue.record("expected second factor, got \(state)"); return }150        #expect(challenge.preferred == .totp && challenge.canUseTOTP && !challenge.canUsePasskey)151        #expect(h.stored == nil) // a restricted session is never persisted152        #expect(await h.client.hasCredential == false)153        // Wrong code: error, the challenge stays.154        do { _ = try await h.auth.submitTOTP(code: "000000"); Issue.record("expected invalid code") } catch let e as APIError { #expect(e.kind == .invalidCredentials) }155        #expect(await h.auth.state == state)156        let done = try await h.auth.submitTOTP(code: h.backend.totpCode)157        #expect(done.isSignedIn && h.stored?.token == h.backend.currentToken)158        // The token was rotated by the TOTP step: the restricted one is gone.159        _ = try await h.client.sessions()160        #expect(h.server.requests.last?.bearer == h.backend.currentToken)161    }162163    @Test func totpInTheSameRequest() async throws {164        let h = try Harness(factor: .totp)165        await h.auth.restore()166        #expect(try await h.auth.signIn(username: "admin", password: h.backend.password, totp: h.backend.totpCode).isSignedIn)167        #expect(h.server.requests("POST", "/api/v1/native/auth/login").first?.json?["totp"]?.stringValue == h.backend.totpCode)168    }169170    @Test func passkeySecondStep() async throws {171        let h = try Harness(factor: .passkey)172        await h.auth.restore()173        let state = try await h.auth.signIn(username: "admin", password: h.backend.password)174        guard case .secondFactorRequired(let challenge) = state else { Issue.record("expected second factor"); return }175        #expect(challenge.preferred == .passkey && challenge.canUsePasskey && !challenge.canUseTOTP)176        // TOTP is not offered: the server refuses the code.177        #expect(try await h.auth.completeSecondFactorWithPasskey().isSignedIn)178        let request = try #require(h.authenticator.requests.first)179        #expect(request.relyingParty == "stub.test" && request.allowCredentials == [h.authenticator.credentialID])180        let verify = try #require(h.server.requests("POST", "/api/v1/native/auth/passkey/verify").first)181        #expect(verify.bearer != nil && verify.json?["challengeToken"] == nil && verify.json?["device"] == nil)182        #expect(verify.json?["credential"]?["type"] == "public-key" && verify.json?["credential"]?["clientExtensionResults"] == [:])183    }184185    @Test func passkeyOnlySignIn() async throws {186        let h = try Harness(factor: .both)187        await h.auth.restore()188        let state = try await h.auth.signInWithPasskey()189        #expect(state.isSignedIn && h.stored != nil)190        let options = try #require(h.server.requests("POST", "/api/v1/native/auth/passkey/options").first)191        #expect(options.bearer == nil)192        let verify = try #require(h.server.requests("POST", "/api/v1/native/auth/passkey/verify").first)193        #expect(verify.bearer == nil && verify.json?["challengeToken"]?.stringValue?.hasPrefix("pct_") == true)194        #expect(verify.json?["device"]?["installId"]?.stringValue == h.auth.installID)195        #expect(verify.json?["credential"]?["response"]?["userHandle"]?.stringValue == Base64URL.encode(Data("user-1".utf8)))196        #expect(h.authenticator.requests.first?.allowCredentials.isEmpty == true) // discoverable credential197        #expect(h.server.requests("POST", "/api/v1/native/auth/login").isEmpty) // no password involved198    }199200    @Test func cancelledPasskeySheetLeavesTheStateAlone() async throws {201        let h = try Harness(factor: .passkey)202        await h.auth.restore()203        h.authenticator.failure = PasskeyError(.cancelled, "Verification cancelled.")204        await #expect(throws: PasskeyError.self) { _ = try await h.auth.signInWithPasskey() }205        #expect(await h.auth.state == .signedOut(.none))206        let pending = try await h.auth.signIn(username: "admin", password: h.backend.password)207        await #expect(throws: PasskeyError.self) { _ = try await h.auth.completeSecondFactorWithPasskey() }208        #expect(await h.auth.state == pending)209        h.authenticator.failure = nil210        #expect(try await h.auth.completeSecondFactorWithPasskey().isSignedIn)211    }212213    @Test func enrollmentBranchWithTOTP() async throws {214        let h = try Harness(factor: .mustEnroll)215        await h.auth.restore()216        let state = try await h.auth.signIn(username: "admin", password: h.backend.password)217        guard case .enrollmentRequired = state else { Issue.record("expected enrollment, got \(state)"); return }218        #expect(h.stored == nil)219        let start = try await h.auth.startTOTPEnrollment()220        #expect(start.secret == "JBSWY3DPEHPK3PXP" && start.otpauthUrl.hasPrefix("otpauth://totp/"))221        do { _ = try await h.auth.finishTOTPEnrollment(code: "111111"); Issue.record("expected invalid code") } catch let e as APIError { #expect(e.kind == .invalidCredentials) }222        #expect(try await h.auth.finishTOTPEnrollment(code: h.backend.totpCode).isSignedIn)223        #expect(h.stored?.username == "admin")224        #expect(h.stored?.token == h.backend.currentToken) // the ROTATED session from the answer was stored225        #expect(h.server.requests("GET", "/api/v1/auth/status").isEmpty)226        _ = try await h.client.sessions()227    }228229    @Test func enrollmentOnAServerThatUpgradesInPlace() async throws {230        let h = try Harness(factor: .mustEnroll)231        h.backend.returnsSessionOnEnrolment = false232        await h.auth.restore()233        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)234        #expect(try await h.auth.finishTOTPEnrollment(code: h.backend.totpCode).isSignedIn)235        #expect(h.server.requests("GET", "/api/v1/auth/status").count == 1) // confirmed before persisting236        _ = try await h.client.sessions()237    }238239    @Test func enrollmentBranchWithPasskeyRegistration() async throws {240        let h = try Harness(factor: .mustEnroll)241        await h.auth.restore()242        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)243        #expect(try await h.auth.registerPasskey(label: "My Mac").isSignedIn)244        let verify = try #require(h.server.requests("POST", "/api/v1/auth/passkey/register/verify").first)245        #expect(verify.json?["label"] == "My Mac" && verify.json?["credential"]?["response"]?["attestationObject"]?.stringValue?.isEmpty == false)246        #expect(h.authenticator.requests.last?.relyingParty == "claude.spboucher.ai") // rp.id from the server's options247    }248249    @Test func addingAPasskeyWhileSignedInKeepsTheSession() async throws {250        let h = try Harness(factor: .none)251        await h.auth.restore()252        let before = try await h.auth.signIn(username: "admin", password: h.backend.password)253        #expect(try await h.auth.registerPasskey() == before)254        #expect(h.server.requests("POST", "/api/v1/auth/passkey/register/verify").first?.json?["label"] == "Test Mac")255        #expect(h.server.requests("GET", "/api/v1/auth/status").isEmpty)256    }257258    @Test func wrongPasswordThenLockoutWithRetryAfter() async throws {259        let h = try Harness()260        await h.auth.restore()261        for _ in 0..<3 {262            do { _ = try await h.auth.signIn(username: "admin", password: "nope"); Issue.record("expected 401") } catch let e as APIError {263                #expect(e.kind == .invalidCredentials && e.status == 401)264            }265        }266        do { _ = try await h.auth.signIn(username: "admin", password: h.backend.password); Issue.record("expected lockout") } catch let e as APIError {267            #expect(e.kind == .locked && e.retryAfter == 90)268        }269        #expect(await h.auth.state == .signedOut(.none) && h.stored == nil)270    }271272    @Test func unknownNextStepIsReportedNotCrashed() async throws {273        let h = try Harness()274        await h.auth.restore()275        h.server.on("POST", "/api/v1/native/auth/login") { _ in .json(Fixtures.loginResponse(next: "sms")) }276        await #expect(throws: AuthFlowError.unsupportedStep("sms")) { _ = try await h.auth.signIn(username: "admin", password: "x") }277        #expect(await h.auth.state == .signedOut(.none))278    }279280    @Test func secondFactorWindowExpiry() async throws {281        let h = try Harness(factor: .totp)282        await h.auth.restore()283        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)284        h.server.on("POST", "/api/v1/native/auth/totp") { _ in .error(401, "unauthenticated", "authentication required") }285        do { _ = try await h.auth.submitTOTP(code: "123456"); Issue.record("expected failure") } catch let e as APIError { #expect(e.kind == .unauthenticated) }286        #expect(await h.auth.state == .signedOut(.secondFactorTimedOut))287        await #expect(throws: AuthFlowError.invalidState) { _ = try await h.auth.submitTOTP(code: "123456") }288    }289290    @Test func cancelSignInRevokesTheRestrictedSession() async throws {291        let h = try Harness(factor: .totp)292        await h.auth.restore()293        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)294        await h.auth.cancelSignIn()295        #expect(await h.auth.state == .signedOut(.none))296        #expect(h.server.requests("POST", "/api/v1/auth/logout").first?.bearer != nil)297    }298299    @Test func restoreAcrossLaunchesAndExpiredStoredSession() async throws {300        let h = try Harness(factor: .none)301        await h.auth.restore()302        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)303        // "Relaunch": a new service over the same keychain.304        let client2 = try APIClient(baseURL: h.server.baseURL, client: .test, configuration: h.server.configuration)305        func relaunch(now: Date) -> AuthService {306            AuthService(profile: AgentProfile.claude.with(baseURL: h.server.baseURL), client: client2,307                        credentials: CredentialStore(keychain: h.keychain, scope: "stub.test"), deviceKeys: h.deviceKeys, passkeys: h.authenticator,308                        localAuth: h.localAuth, device: DeviceDescriptor(name: "Test Mac", model: "Mac16,5", platform: .macos, appVersion: "1.0-test"), now: { now })309        }310        let restored = await relaunch(now: Date()).restore()311        #expect(restored.isSignedIn)312        _ = try await client2.sessions()313        #expect(h.server.requests.count { $0.path.hasSuffix("/login") } == 1) // no new sign-in314        // Past the absolute expiry (fixture: 2099-01-31): wiped.315        let late = await relaunch(now: Date(timeIntervalSince1970: 4_100_000_000)).restore()316        #expect(late == .signedOut(.none) && h.stored == nil)317    }318319    @Test func stateUpdatesAreVersionedAndObservable() async throws {320        let h = try Harness(factor: .totp)321        let updates = await h.auth.updates()322        await h.auth.restore()323        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)324        _ = try await h.auth.submitTOTP(code: h.backend.totpCode)325        await h.auth.signOut()326        var seen: [AuthStateUpdate] = []327        for await update in updates {328            seen.append(update)329            if update.state == .signedOut(.userSignedOut) { break }330        }331        #expect(seen.map(\.version) == seen.map(\.version).sorted() && Set(seen.map(\.version)).count == seen.count)332        #expect(seen.first?.state == .unknown && seen.contains { $0.state.isSignedIn })333        #expect(seen.contains { if case .secondFactorRequired = $0.state { true } else { false } })334        #expect(await h.auth.snapshot == seen.last)335    }336}337338@Suite("Refresh, revocation, sign-out")339struct SessionLifecycleTests {340    func signedIn() async throws -> Harness {341        let h = try Harness(factor: .none)342        await h.auth.restore()343        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)344        return h345    }346347    @Test func expiredTokenIsRefreshedWithTheDeviceKeyAndTheRequestRetried() async throws {348        let h = try await signedIn()349        let first = try #require(h.backend.currentToken)350        h.backend.expireToken()351        _ = try await h.client.sessions() // 401 token_expired → challenge → signature → refresh → retry352        let rotated = try #require(h.backend.currentToken)353        #expect(rotated != first && h.backend.refreshCount == 1)354        #expect(h.stored?.token == rotated) // persisted355        #expect(await h.auth.state.isSignedIn)356        let refresh = try #require(h.server.requests("POST", "/api/v1/native/auth/refresh").first)357        #expect(refresh.bearer == nil && refresh.json?["sessionId"]?.stringValue == h.backend.sessionID)358        // The signature is base64 DER over the exact contract string, valid for the device key.359        let challenge = try #require(h.server.requests("POST", "/api/v1/native/auth/refresh/challenge").first)360        #expect(challenge.bearer == nil && challenge.json == ["sessionId": .string(h.backend.sessionID)])361        let signature = try #require(refresh.json?["signature"]?.stringValue)362        #expect(Data(base64Encoded: signature)?.first == 0x30) // DER SEQUENCE363    }364365    @Test func concurrentRequestsTriggerASingleRefresh() async throws {366        let h = try await signedIn()367        h.backend.expireToken()368        try await withThrowingTaskGroup(of: Void.self) { group in369            for _ in 0..<10 { group.addTask { _ = try await h.client.sessions() } }370            try await group.waitForAll()371        }372        #expect(h.backend.refreshCount == 1)373    }374375    @Test func revocationWipesTheCredentialAndEmitsSignedOut() async throws {376        let h = try await signedIn()377        h.backend.revoke()378        do { _ = try await h.client.sessions(); Issue.record("expected 401") } catch let e as APIError { #expect(e.requiresSignIn) }379        #expect(await h.auth.state == .signedOut(.revoked))380        #expect(h.stored == nil)381        #expect((await h.client.hasCredential) == false)382        // The device key and the install id survive, so the device is recognised next time.383        #expect(h.keychain.accounts.contains("device-key.sw") && h.keychain.accounts.contains("install-id"))384    }385386    @Test func refreshRefusedMeansRevoked() async throws {387        let h = try await signedIn()388        h.backend.expireToken()389        h.server.on("POST", "/api/v1/native/auth/refresh") { _ in .error(401, "unauthenticated", "authentication required") }390        do { _ = try await h.client.sessions(); Issue.record("expected 401") } catch let e as APIError { #expect(e.requiresSignIn) }391        #expect(await h.auth.state == .signedOut(.revoked) && h.stored == nil)392    }393394    @Test func refreshWithAnotherDeviceKeyIsRefusedByTheServer() async throws {395        let h = try await signedIn()396        h.deviceKeys.delete() // a different key is generated on next use: the signature no longer verifies397        h.backend.expireToken()398        do { _ = try await h.client.sessions(); Issue.record("expected 401") } catch let e as APIError { #expect(e.requiresSignIn) }399        #expect(h.backend.refreshCount == 0)400        #expect(await h.auth.state == .signedOut(.revoked))401    }402403    @Test func networkFailureDuringRefreshKeepsTheSession() async throws {404        let h = try await signedIn()405        h.backend.expireToken()406        h.server.on("POST", "/api/v1/native/auth/refresh/challenge") { _ in .transportFailure(.notConnectedToInternet) }407        do { _ = try await h.client.sessions(); Issue.record("expected network error") } catch let e as APIError { #expect(e.kind == .network) }408        #expect(await h.auth.state.isSignedIn && h.stored != nil)409    }410411    @Test func remoteExpiryEventSignsOut() async throws {412        let h = try await signedIn()413        await h.auth.sessionExpiredRemotely()414        #expect(await h.auth.state == .signedOut(.revoked) && h.stored == nil)415    }416417    @Test func signOutRevokesOnTheServerAndWipesLocally() async throws {418        let h = try await signedIn()419        let token = h.backend.currentToken420        await h.auth.signOut()421        #expect(await h.auth.state == .signedOut(.userSignedOut))422        #expect(h.server.requests("POST", "/api/v1/auth/logout").first?.bearer == token && h.backend.currentToken == nil)423        #expect(h.stored == nil)424        #expect((await h.client.hasCredential) == false)425        await #expect(throws: APIError.notSignedIn) { _ = try await h.client.sessions() }426    }427428    @Test func signOutWorksOffline() async throws {429        let h = try await signedIn()430        h.server.on("POST", "/api/v1/auth/logout") { _ in .transportFailure(.notConnectedToInternet) }431        await h.auth.signOut()432        #expect(await h.auth.state == .signedOut(.userSignedOut) && h.stored == nil)433    }434435    @Test func localWipeRemovesEverything() async throws {436        let h = try await signedIn()437        let install = h.auth.installID438        await h.auth.wipeLocalData()439        #expect(h.keychain.accounts.isEmpty)440        #expect(h.auth.installID != install)441        #expect(h.server.requests("POST", "/api/v1/auth/logout").isEmpty) // no network involved442    }443444    @Test func reauthenticationGate() async throws {445        let h = try await signedIn()446        try await h.auth.reauthenticate(reason: "Terminate the session")447        #expect(h.localAuth.reasons == ["Terminate the session"] && h.auth.canReauthenticate)448        h.localAuth.result = .failure(.cancelled)449        await #expect(throws: LocalAuthError.cancelled) { try await h.auth.reauthenticate(reason: "Delete") }450        h.localAuth.available = false451        #expect(!h.auth.canReauthenticate)452        await #expect(throws: LocalAuthError.unavailable) { try await h.auth.reauthenticate(reason: "Delete") }453        #expect(await h.auth.state.isSignedIn) // local verification never touches the server session454    }455456    @Test func keychainWriteFailureDoesNotPretendToBeSignedIn() async throws {457        let h = try Harness(factor: .none)458        await h.auth.restore()459        _ = h.auth.installID460        _ = try await h.auth.nativeDevice()461        h.keychain.failWritesWith = errSecInteractionNotAllowed462        await #expect(throws: KeychainError.self) { _ = try await h.auth.signIn(username: "admin", password: h.backend.password) }463        #expect(await h.auth.state == .signedOut(.none))464    }465}466467@Suite("Device key, keychain, credential store")468struct DeviceKeyTests {469    @Test func signatureFormatIsDEROverTheContractString() throws {470        let key = SoftwareDeviceKey()471        #expect(key.publicKeyX963.count == 65 && key.publicKeyX963.first == 0x04 && !key.isHardwareBacked)472        #expect(Data(base64Encoded: key.publicKeyBase64) == key.publicKeyX963)473        let message = RefreshSignature.message(sessionId: "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", challenge: "q83vEjRWeJCrze8SNFZ4kA")474        #expect(String(decoding: message, as: UTF8.self) == "cr-native-refresh:v1:9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d:q83vEjRWeJCrze8SNFZ4kA")475        let b64 = try RefreshSignature.make(sessionId: "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", challenge: "q83vEjRWeJCrze8SNFZ4kA", key: key)476        let der = try #require(Data(base64Encoded: b64)) // standard base64, not base64url477        #expect(der[0] == 0x30 && Int(der[1]) == der.count - 2 && der[2] == 0x02) // SEQUENCE { INTEGER r, INTEGER s }478        // An independent verifier (what the server does): ECDSA P-256 / SHA-256 over the UTF-8 bytes.479        let signature = try P256.Signing.ECDSASignature(derRepresentation: der)480        let publicKey = try P256.Signing.PublicKey(x963Representation: key.publicKeyX963)481        #expect(publicKey.isValidSignature(signature, for: SHA256.hash(data: message)))482        #expect(RefreshSignature.verify(b64, sessionId: "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", challenge: "q83vEjRWeJCrze8SNFZ4kA", publicKeyX963: key.publicKeyX963))483        #expect(!RefreshSignature.verify(b64, sessionId: "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d", challenge: "other", publicKeyX963: key.publicKeyX963))484        #expect(!RefreshSignature.verify(b64, sessionId: "x", challenge: "q83vEjRWeJCrze8SNFZ4kA", publicKeyX963: SoftwareDeviceKey().publicKeyX963))485        #expect(!RefreshSignature.verify("not base64", sessionId: "x", challenge: "y", publicKeyX963: key.publicKeyX963))486    }487488    @Test func softwareKeyIsPersistedAndStable() throws {489        let keychain = InMemoryKeychain()490        let store = KeychainDeviceKeyStore(keychain: keychain, preferSecureEnclave: false)491        let a = try store.loadOrCreate(), b = try store.loadOrCreate()492        #expect(a.publicKeyX963 == b.publicKeyX963 && keychain.accounts == ["device-key.sw"])493        let again = try KeychainDeviceKeyStore(keychain: keychain, preferSecureEnclave: false).loadOrCreate()494        #expect(again.publicKeyX963 == a.publicKeyX963)495        store.delete()496        #expect(keychain.accounts.isEmpty)497        #expect(try store.loadOrCreate().publicKeyX963 != a.publicKeyX963)498    }499500    @Test func secureEnclavePathWhenAvailable() throws {501        // On a Mac with a Secure Enclave the key is created there even in an unsigned test process;502        // elsewhere (CI VMs) the store falls back to a software key. Both must produce valid signatures.503        let keychain = InMemoryKeychain()504        let store = KeychainDeviceKeyStore(keychain: keychain)505        let key = try store.loadOrCreate()506        #expect(keychain.accounts == [key.isHardwareBacked ? "device-key.se" : "device-key.sw"])507        let b64 = try RefreshSignature.make(sessionId: "s", challenge: "c", key: key)508        #expect(RefreshSignature.verify(b64, sessionId: "s", challenge: "c", publicKeyX963: key.publicKeyX963))509        #expect(try store.loadOrCreate().publicKeyX963 == key.publicKeyX963) // reloaded from its handle510        if key.isHardwareBacked {511            // What is stored is the enclave's opaque handle, not key material usable elsewhere.512            let blob = try #require(try keychain.read("device-key.se"))513            #expect((try? P256.Signing.PrivateKey(rawRepresentation: blob)) == nil)514        }515    }516517    @Test func credentialStoreRoundTripAndScoping() throws {518        let keychain = InMemoryKeychain()519        let store = CredentialStore(keychain: keychain, scope: "claude.spboucher.ai")520        #expect(store.load() == nil)521        let session = NativeSession(id: "sid", token: "crn_secret", tokenExpiresAt: Date(timeIntervalSince1970: 2_000_000_000.5),522                                    expiresAt: Date(timeIntervalSince1970: 2_002_000_000), secondFactor: true)523        try store.save(StoredCredential(session: session, username: "admin"))524        let loaded = try #require(store.load())525        #expect(loaded.session == session && loaded.username == "admin")526        #expect(CredentialStore(keychain: keychain, scope: "codex.spboucher.ai").load() == nil) // per instance527        let id = store.installID()528        #expect(UUID(uuidString: id) != nil && store.installID() == id && CredentialStore(keychain: keychain, scope: "other").installID() == id)529        store.clear()530        #expect(store.load() == nil && store.installID() == id) // sign-out keeps the install id531        #expect(CredentialStore.service(for: .claude) == "ai.spboucher.clauderemote.session" && CredentialStore.service(for: .codex, debug: true) == "ai.spboucher.codexremote.dev.session")532        // Garbage in the keychain is treated as "no credential", never a crash.533        try keychain.write(Data("garbage".utf8), account: "credential@claude.spboucher.ai")534        #expect(store.load() == nil)535    }536537    @Test func nothingSecretReachesUserDefaults() async throws {538        let h = try Harness(factor: .none)539        await h.auth.restore()540        _ = try await h.auth.signIn(username: "admin", password: h.backend.password)541        let token = try #require(h.backend.currentToken)542        let dump = UserDefaults.standard.dictionaryRepresentation().description543        #expect(!dump.contains(token) && !dump.contains(h.backend.password))544    }545546    @Test(.enabled(if: ProcessInfo.processInfo.environment["CR_TEST_REAL_KEYCHAIN"] == "1"))547    func realKeychainRoundTrip() throws {548        // Opt-in: writes to the login keychain of the machine running the tests.549        let keychain = SystemKeychain(service: "ai.spboucher.clauderemote.kit-tests", useDataProtectionKeychain: false)550        defer { try? keychain.delete("probe") }551        try keychain.write(Data("one".utf8), account: "probe")552        try keychain.write(Data("two".utf8), account: "probe")553        #expect(try keychain.read("probe") == Data("two".utf8))554        try keychain.delete("probe")555        #expect(try keychain.read("probe") == nil)556    }557558    @Test func softwareAuthenticatorProducesVerifiableAssertions() async throws {559        let authenticator = SoftwareAuthenticator(userHandle: Data("u".utf8), origin: "https://claude.spboucher.ai")560        let challenge = Data("challenge-bytes".utf8)561        let credential = try await authenticator.assertion(relyingParty: "claude.spboucher.ai", challenge: challenge, allowCredentials: [])562        let clientData = try #require(Base64URL.decode(credential.response.clientDataJSON))563        let parsed = try JSONDecoder().decode(JSONValue.self, from: clientData)564        #expect(parsed["type"] == "webauthn.get" && parsed["origin"] == "https://claude.spboucher.ai" && parsed["challenge"]?.stringValue == Base64URL.encode(challenge))565        let authData = try #require(Base64URL.decode(credential.response.authenticatorData))566        #expect(authData.count == 37 && authData.prefix(32) == Data(SHA256.hash(data: Data("claude.spboucher.ai".utf8))) && authData[32] == 0x05)567        let signature = try P256.Signing.ECDSASignature(derRepresentation: try #require(Base64URL.decode(credential.response.signature)))568        #expect(authenticator.privateKey.publicKey.isValidSignature(signature, for: authData + Data(SHA256.hash(data: clientData))))569        #expect(credential.id == Base64URL.encode(authenticator.credentialID) && credential.rawId == credential.id && credential.type == "public-key")570        await #expect(throws: PasskeyError.self) { _ = try await authenticator.assertion(relyingParty: "x", challenge: challenge, allowCredentials: [Data("other".utf8)]) }571        let registration = try await authenticator.registration(relyingParty: "claude.spboucher.ai", challenge: challenge, userName: "admin", userID: Data("u".utf8), excludeCredentials: [])572        let attestation = try #require(Base64URL.decode(registration.response.attestationObject))573        #expect(attestation.first == 0xA3 && attestation.count > 100)574        #expect(TOTP.code(secretBase32: "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", at: Date(timeIntervalSince1970: 59)) == "287082") // RFC 6238 vector575    }576}577578@Suite("Biometric lock")579@MainActor580struct BiometricLockTests {581    final class Clock: @unchecked Sendable {582        var now = Date(timeIntervalSince1970: 1_800_000_000)583    }584585    func make(enabled: Bool, timeout: TimeInterval = 300, auth: MockLocalAuthenticator = MockLocalAuthenticator()) -> (BiometricLock, Clock, UserDefaults) {586        let suite = "cr-lock-tests-\(UUID().uuidString)"587        let defaults = UserDefaults(suiteName: suite)!588        defaults.set(enabled, forKey: "cr.lock.enabled")589        defaults.set(timeout, forKey: "cr.lock.timeout")590        let clock = Clock()591        return (BiometricLock(authenticator: auth, defaults: defaults, now: { clock.now }), clock, defaults)592    }593594    @Test func disabledLockNeverLocks() {595        let (lock, clock, _) = make(enabled: false)596        #expect(!lock.isLocked && !lock.isEnabled)597        lock.appDidEnterBackground()598        clock.now += 86400599        lock.appWillEnterForeground()600        lock.lock()601        #expect(!lock.isLocked)602    }603604    @Test func coldStartIsLockedAndUnlocksWithBiometrics() async {605        let auth = MockLocalAuthenticator(biometry: .faceID)606        let (lock, _, _) = make(enabled: true, auth: auth)607        #expect(lock.isLocked && lock.biometry == .faceID && lock.isAvailable)608        auth.result = .failure(.cancelled)609        #expect(await lock.unlock() == false && lock.isLocked)610        auth.result = .success(())611        #expect(await lock.unlock(reason: "Unlock Claude Remote") && !lock.isLocked)612        #expect(auth.reasons.last == "Unlock Claude Remote")613        #expect(await lock.unlock()) // already unlocked: no prompt614        #expect(auth.reasons.count == 2)615    }616617    @Test func autoLockAfterInactivity() async {618        let (lock, clock, _) = make(enabled: true, timeout: 300)619        await lock.unlock()620        lock.appDidEnterBackground()621        clock.now += 299622        lock.appWillEnterForeground()623        #expect(!lock.isLocked)624        lock.appDidEnterBackground()625        clock.now += 300626        lock.appWillEnterForeground()627        #expect(lock.isLocked)628        await lock.unlock()629        // Foreground inactivity: activity pushes the deadline.630        clock.now += 200631        lock.noteActivity()632        clock.now += 200633        lock.lockIfExpired()634        #expect(!lock.isLocked)635        clock.now += 100636        lock.lockIfExpired()637        #expect(lock.isLocked)638    }639640    @Test func zeroTimeoutLocksAsSoonAsTheAppLeaves() async {641        let (lock, _, _) = make(enabled: true, timeout: 0)642        await lock.unlock()643        lock.appDidEnterBackground()644        #expect(lock.isLocked)645    }646647    @Test func enablingAndDisablingRequireVerificationAndPersist() async throws {648        let auth = MockLocalAuthenticator(result: .failure(.failed))649        let (lock, _, defaults) = make(enabled: false, auth: auth)650        await #expect(throws: LocalAuthError.failed) { try await lock.enable() }651        #expect(!lock.isEnabled)652        auth.result = .success(())653        try await lock.enable()654        #expect(lock.isEnabled && !lock.isLocked && defaults.bool(forKey: "cr.lock.enabled"))655        lock.timeout = 60656        #expect(defaults.double(forKey: "cr.lock.timeout") == 60)657        auth.result = .failure(.cancelled)658        await #expect(throws: LocalAuthError.cancelled) { try await lock.disable() }659        #expect(lock.isEnabled)660        auth.result = .success(())661        try await lock.disable()662        #expect(!lock.isEnabled && !defaults.bool(forKey: "cr.lock.enabled"))663    }664}665
Files main
Menu

Theme