SPB Git

Repository Public

IntegrationTests.swift 17.0 KB 335 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/IntegrationTests/IntegrationTests.swift10// Module           : IntegrationTests11// 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 ClaudeRemoteCore91import ClaudeRemoteModels92import ClaudeRemoteTerminal93import ClaudeRemoteTestSupport94import Foundation95import Testing9697// Live tests against a real server (the native dev stack). Skipped unless BOTH are set:98//   CR_IT_BASE_URL   e.g. http://localhost:8625   (ssh -N -L 8625:127.0.0.1:8625 M5M36)99//   CR_IT_FIXTURES   path of the stack's fixtures.json (user, totp, passkey, project, shellSession)100// Every test signs in with its own keychain (= its own installId), so they do not revoke each101// other. Only ONE test uses the TOTP code: codes are single use per 30 s step.102103let fixtures = IntegrationFixtures.load()104105/// Collects terminal output off the main thread.106final class CollectingSink: TerminalOutputSink, @unchecked Sendable {107    private let lock = NSLock()108    private var bytes = [UInt8]()109    private var _resets = 0110    func reset() { lock.withLock { _resets += 1; bytes.removeAll() } }111    func feed(_ slice: ArraySlice<UInt8>) { lock.withLock { bytes.append(contentsOf: slice) } }112    var text: String { lock.withLock { String(decoding: bytes, as: UTF8.self) } }113    var resets: Int { lock.withLock { _resets } }114}115116struct Live {117    let fx: IntegrationFixtures118    let client: APIClient119    let auth: AuthService120    let keychain = InMemoryKeychain()121    let authenticator: SoftwareAuthenticator122123    init() throws {124        fx = try #require(fixtures)125        authenticator = try #require(try fx.authenticator(), "fixtures have no passkey")126        client = try APIClient(baseURL: fx.baseURL, client: ClientInfo(platform: .macos, appVersion: "1.0-it"))127        auth = AuthService(profile: AgentProfile.claude.with(baseURL: fx.baseURL), client: client,128                           credentials: CredentialStore(keychain: keychain, scope: fx.baseURL.host() ?? "it"),129                           deviceKeys: KeychainDeviceKeyStore(keychain: keychain, preferSecureEnclave: false), passkeys: authenticator,130                           localAuth: MockLocalAuthenticator(), device: DeviceDescriptor(name: "ClaudeRemoteKit integration", model: DeviceDescriptor.hardwareModel(), platform: .macos, appVersion: "1.0-it"))131    }132133    /// Sessionless passkey sign-in with the software authenticator built from the fixture key.134    func signIn() async throws {135        await auth.restore()136        let state = try await auth.signInWithPasskey()137        try #require(state.isSignedIn, "passkey sign-in ended in \(state)")138    }139140    func wait(_ timeout: TimeInterval = 10, isolation: isolated (any Actor)? = #isolation, _ condition: () async -> Bool) async -> Bool {141        let deadline = Date().addingTimeInterval(timeout)142        while Date() < deadline {143            if await condition() { return true }144            try? await Task.sleep(for: .milliseconds(50))145        }146        return await condition()147    }148}149150@Suite("Integration (live dev stack)", .enabled(if: fixtures != nil, "set CR_IT_BASE_URL and CR_IT_FIXTURES"), .serialized)151struct IntegrationTests {152    @Test func passwordThenTOTP() async throws {153        let live = try Live()154        let secret = try #require(live.fx.totpSecret, "fixtures have no TOTP secret")155        await live.auth.restore()156        let first = try await live.auth.signIn(username: live.fx.username, password: live.fx.password)157        guard case .secondFactorRequired(let challenge) = first else { Issue.record("expected a second factor, got \(first)"); return }158        #expect(challenge.canUseTOTP)159        let status = try await live.client.authStatus() // no bearer installed yet: anonymous view160        #expect(!status.authenticated)161        let code = try #require(TOTP.code(secretBase32: secret))162        let done = try await live.auth.submitTOTP(code: code)163        #expect(done.isSignedIn)164        let me = try await live.client.authStatus()165        #expect(me.authenticated && me.user?.username == live.fx.username && me.csrfToken == nil || me.authenticated)166        let devices = try await live.client.devices()167        let mine = try #require(devices.first { $0.current })168        #expect(mine.kind == .native && mine.label == "ClaudeRemoteKit integration" && mine.platform == .macos && mine.appVersion == "1.0-it")169        await live.auth.signOut()170        await #expect(throws: APIError.notSignedIn) { _ = try await live.client.sessions() }171    }172173    @Test func wrongPasswordIsRefused() async throws {174        let live = try Live()175        await live.auth.restore()176        do {177            _ = try await live.auth.signIn(username: live.fx.username, password: "definitely-not-the-password")178            Issue.record("expected 401")179        } catch let e as APIError {180            #expect(e.kind == .invalidCredentials && e.status == 401)181        }182        #expect(await live.auth.state == .signedOut(.none))183    }184185    @Test func passkeyOnlySignInSummaryInfoAndPush() async throws {186        let live = try Live()187        try await live.signIn()188        let status = try await live.client.authStatus()189        #expect(status.authenticated && status.methods.passkeys >= 1)190        let summary = try await live.client.summary()191        #expect(summary.sessions.live >= 1 && summary.agent == .claude)192        let info = try await live.client.nativeInfo()193        #expect(info.devices >= 1 && !info.push.configured)194        let topic = live.fx.pushTopic ?? AgentProfile.claude.bundleIdentifier195        let push = try await live.client.registerPush(PushRegistration(deviceToken: Data((0..<32).map { _ in UInt8.random(in: 0...255) }), environment: .sandbox, topic: topic))196        #expect(push.ok && !push.configured)197        try await live.client.unregisterPush()198        let settings = try await live.client.settings()199        #expect(settings.scrollback >= 500)200        _ = try await live.client.systemStatus()201        _ = try await live.client.notifications()202        _ = try await live.client.clusterOverview()203        await live.auth.signOut()204    }205206    @Test func refreshWithTheDeviceKeyRotatesTheToken() async throws {207        let live = try Live()208        try await live.signIn()209        let before = try #require(CredentialStore(keychain: live.keychain, scope: live.fx.baseURL.host() ?? "it").load())210        let fresh = try await live.auth.refreshSession()211        #expect(fresh.id == before.sessionId && fresh.token != before.token && fresh.secondFactor)212        await live.client.setCredential(fresh)213        _ = try await live.client.sessions()214        // The old token died at once. The client recovers by itself (one refresh), as documented.215        await live.client.setCredential(token: before.token, expiresAt: before.tokenExpiresAt)216        _ = try await live.client.sessions()217        #expect(await live.auth.state.isSignedIn)218        let stored = CredentialStore(keychain: live.keychain, scope: live.fx.baseURL.host() ?? "it").load()219        #expect(stored?.token != before.token && stored?.token != fresh.token)220        await live.auth.signOut()221    }222223    @Test func sessionsProjectsAndTerminalEcho() async throws {224        let live = try Live()225        try await live.signIn()226        let shellID = try #require(live.fx.shellSessionId)227        let sessions = try await live.client.sessions()228        let shell = try #require(sessions.first { $0.id == shellID })229        #expect(shell.kind == .shell && shell.state.isAttachable)230        if let pid = live.fx.projectId { #expect(try await live.client.projects().contains { $0.id == pid }) }231232        let sink = CollectingSink()233        let connection = TerminalConnection(client: live.client, sessionId: shellID, sink: sink)234        await connection.start(cols: 100, rows: 30)235        #expect(await live.wait { await connection.state == .open })236        #expect(sink.resets >= 1) // the emulator is reset before the replay237        let nonce = String(UUID().uuidString.prefix(8)).lowercased()238        connection.send(text: "echo it-$((6*7))-\(nonce)\r")239        #expect(await live.wait { sink.text.contains("it-42-\(nonce)") }) // produced by the shell, not our own echo240        #expect(await live.wait(8) { await connection.latencyMs != nil }) // ping / pong241242        // Re-attach: same process, history replayed into a freshly reset emulator.243        let resets = sink.resets244        await connection.reconnectNow()245        #expect(await live.wait { sink.resets > resets })246        #expect(await live.wait { await connection.state == .open })247        #expect(await live.wait { sink.text.contains("it-42-\(nonce)") })248        #expect(try await live.client.session(id: shellID).pid == shell.pid) // reconnecting never created a process249        await connection.stop()250251        let missing = TerminalConnection(client: live.client, sessionId: UUID().uuidString.lowercased(), sink: CollectingSink())252        await missing.start(cols: 80, rows: 24)253        #expect(await live.wait { await missing.state == .notFound })254        await missing.stop()255        await live.auth.signOut()256    }257258    @Test @MainActor func eventStreamDeliversSessionUpdates() async throws {259        let live = try Live()260        try await live.signIn()261        let shellID = try #require(live.fx.shellSessionId)262        let original = try await live.client.session(id: shellID)263        let stream = EventStream(client: live.client, latencyProbeInterval: nil)264        var updates: [TerminalSession] = []265        var hello = false266        stream.onEvent { event in267            if case .hello = event { hello = true }268            if case .sessionUpdated(let s) = event { updates.append(s) }269        }270        stream.start()271        #expect(await live.wait { stream.state == .online && hello })272        let title = "it-\(UUID().uuidString.prefix(6))"273        _ = try await live.client.updateSession(id: shellID, UpdateSession(title: title))274        #expect(await live.wait { updates.contains { $0.id == shellID && $0.title == title } })275        _ = try await live.client.updateSession(id: shellID, UpdateSession(title: original.title))276        stream.stop()277        await live.auth.signOut()278    }279280    @Test func filesListReadWriteConflictDelete() async throws {281        let live = try Live()282        try await live.signIn()283        let pid = try #require(live.fx.projectId)284        let name = "cr-it-\(UUID().uuidString.prefix(8)).txt"285        let created = try await live.client.writeFile(projectId: pid, WriteFile(path: name, content: "one\n", create: true))286        #expect(created.sha256.count == 64)287        #expect(try await live.client.listFiles(projectId: pid).contains { $0.name == name && $0.type == .file })288        let read = try await live.client.readFile(projectId: pid, path: name)289        #expect(read.content == "one\n" && read.sha256 == created.sha256)290        let updated = try await live.client.writeFile(projectId: pid, WriteFile(path: name, content: "two\n", baseSha256: read.sha256))291        #expect(updated.sha256 != read.sha256)292        do {293            _ = try await live.client.writeFile(projectId: pid, WriteFile(path: name, content: "stale\n", baseSha256: read.sha256))294            Issue.record("expected a conflict")295        } catch let e as APIError {296            #expect(e.kind == .conflict && e.conflictSha256 == updated.sha256)297        }298        #expect(try await live.client.readFile(projectId: pid, path: name).content == "two\n") // nothing overwritten299        #expect(try await live.client.searchFiles(projectId: pid, query: name).contains { $0.path == name })300301        let dir = FileManager.default.temporaryDirectory.appending(path: "cr-it-\(UUID().uuidString)")302        defer { try? FileManager.default.removeItem(at: dir) }303        let local = dir.appending(path: "down.txt")304        try await live.client.download(projectId: pid, path: name, to: local)305        #expect(try String(contentsOf: local, encoding: .utf8) == "two\n")306        do { try await live.client.upload(projectId: pid, path: name, from: local); Issue.record("expected exists") } catch let e as APIError { #expect(e.kind == .exists) }307        try Data("three\n".utf8).write(to: local)308        try await live.client.upload(projectId: pid, path: name, from: local, overwrite: true)309        #expect(try await live.client.readFile(projectId: pid, path: name).content == "three\n")310311        try await live.client.fsOp(projectId: pid, .delete(path: name))312        do { _ = try await live.client.readFile(projectId: pid, path: name); Issue.record("expected 404") } catch let e as APIError { #expect(e.kind == .notFound) }313        _ = try await live.client.gitStatus(projectId: pid)314        await live.auth.signOut()315    }316317    @Test func revocationEndsTheSessionWith401AndClosesSockets() async throws {318        let live = try Live()319        try await live.signIn()320        let shellID = try #require(live.fx.shellSessionId)321        let connection = TerminalConnection(client: live.client, sessionId: shellID, sink: CollectingSink())322        await connection.start(cols: 80, rows: 24)323        #expect(await live.wait { await connection.state == .open })324        let mine = try #require(try await live.client.devices().first { $0.current })325        try await live.client.revokeDevice(id: mine.id) // what "Sign out this device" does from the web326        #expect(await live.wait { await connection.state == .unauthorized }) // socket closed with 4401327        do { _ = try await live.client.sessions(); Issue.record("expected 401") } catch let e as APIError {328            #expect(e.status == 401 && e.requiresSignIn)329        }330        #expect(await live.auth.state == .signedOut(.revoked))331        #expect(CredentialStore(keychain: live.keychain, scope: live.fx.baseURL.host() ?? "it").load() == nil)332        await connection.stop()333    }334}335
Files main
Menu

Theme