Repository Public
1import Foundation2import Testing3@testable import MCCCore45/// Identity flows against the REAL local control-api (no server-side test hook: the software authenticator produces6/// genuine WebAuthn attestations and assertions that the server verifies).7extension Integration {8@Suite("identity")9struct IdentityIntegrationTests {10 @Test("invitation setup opens a session; software-authenticator attestation accepted by the server")11 func invitationSetup() async throws {12 _ = try await IT.owner.authenticator()13 let seat = try #require(await IT.owner.firstSeat)14 let reg = try #require(await IT.owner.firstRegistration)15 let tx = try #require(await IT.owner.transaction)16 #expect(tx.role == .owner)17 #expect(tx.requiresExistingAccount == false)18 #expect(reg.auth?.user.handle == "owner-it")19 #expect(reg.passkey.backupEligible && reg.passkey.backupState) // BE|BS flags of the software authenticator2021 let me = try await seat.api.call { try await $0.getMe().ok.body.json }22 #expect(me.user.role == .owner)23 #expect(me.permissions.contains("actions.run.critical"))24 #expect(me.session.kind == .bearer)25 // Tokens and device id are in the secure store, namespaced by server.26 #expect(seat.store.accounts.contains { $0.hasPrefix("tokens@localhost") })27 #expect(seat.store.accounts.contains { $0.hasPrefix("device@localhost") })28 let devices = try await seat.api.call { try await $0.listMyDevices().ok.body.json }29 let current = try #require(devices.items.first { $0.current })30 #expect(current.kind == .macos)31 #expect(current.label == "Owner Mac")32 #expect(current.model == "Mac16,9")33 #expect(current.appVersion == "1.0.0 (test)")34 #expect(await seat.auth.hasPendingInvitation == false)35 }3637 @Test("passkey sign-in on a new device; software-authenticator assertion accepted by the server")38 func signIn() async throws {39 let seat = try await IT.sharedOwner.seat()40 let me = try await seat.api.call { try await $0.getMe().ok.body.json }41 #expect(me.user.handle == "owner-it")42 #expect(me.session.current)43 #expect(await seat.api.tokens.hasSession)44 }4546 @Test("a tampered assertion is rejected by the server (no backdoor)")47 func tamperedAssertionRejected() async throws {48 let key = try await IT.owner.authenticator()49 let seat = IT.seat(authenticator: key)50 key.behaviour = .wrongSignature51 defer { key.behaviour = .normal }52 do {53 _ = try await IT.patiently { try await seat.auth.signIn() }54 Issue.record("a forged signature must not open a session")55 } catch {56 let e = APIError.from(error)57 #expect(e.status == 401)58 #expect(e.correlationID != nil)59 #expect(await seat.api.tokens.hasSession == false)60 }61 }6263 @Test("a wrong origin in clientDataJSON is rejected by the server")64 func wrongOriginRejected() async throws {65 let foreign = SoftwareAuthenticator(origin: "http://evil.example")66 let token = try await ownerInvitation(role: .viewer, handle: "wrong-origin", name: "Wrong Origin")67 let seat = IT.seat(authenticator: foreign)68 _ = try await IT.patiently { try await seat.auth.exchangeInvitation(token: token) }69 do {70 _ = try await IT.patiently { try await seat.auth.completeInvitation(passkeyLabel: nil) }71 Issue.record("registration from another origin must fail")72 } catch {73 let status = APIError.from(error).status ?? 074 #expect(status >= 400 && status != 429)75 }76 }7778 @Test("20 concurrent requests with an expired access token trigger exactly one refresh")79 func singleFlightRefresh() async throws {80 let seat = try await IT.sharedOwner.seat()81 let refreshesBefore = await seat.api.tokens.refreshRequestCount82 let me = try await seat.api.call { try await $0.getMe().ok.body.json }83 let before = try IT.psql("select count(*) from refresh_tokens where session_id='\(me.session.id)'")84 let rotationsBefore = try #require(Int(before))85 // The server now considers the access token expired while the client still believes it is valid.86 try IT.psql("update sessions set access_expires_at = now() - interval '1 second' where id='\(me.session.id)'")87 let results = await withTaskGroup(of: Result<String, APIError>.self) { group in88 for _ in 0..<20 {89 group.addTask {90 do { return .success(try await seat.api.call { try await $0.getMe().ok.body.json }.user.handle) }91 catch { return .failure(APIError.from(error)) }92 }93 }94 var out: [Result<String, APIError>] = []95 for await r in group { out.append(r) }96 return out97 }98 #expect(results.count == 20)99 #expect(results.allSatisfy { (try? $0.get()) == "owner-it" })100 #expect(await seat.api.tokens.refreshRequestCount == refreshesBefore + 1)101 let after = try IT.psql("select count(*) from refresh_tokens where session_id='\(me.session.id)'")102 #expect(Int(after) == rotationsBefore + 1) // exactly one rotation happened server-side103 }104105 @Test("presenting a rotated refresh token revokes the session: both holders end signed out")106 func refreshReuse() async throws {107 let key = try await IT.owner.authenticator()108 let seat = try await IT.signedIn(as: key)109 let me = try await seat.api.call { try await $0.getMe().ok.body.json }110 // A copy of the secure store taken BEFORE the rotation = a leaked refresh token.111 let leaked = InMemorySecureStore()112 for account in seat.store.accounts { try leaked.write(try #require(try seat.store.read(account)), account: account) }113 try IT.psql("update sessions set access_expires_at = now() - interval '1 second' where id='\(me.session.id)'")114 _ = try await IT.patiently { try await seat.api.call { try await $0.getMe().ok.body.json } } // legitimate rotation115 #expect(await seat.api.tokens.refreshRequestCount == 1)116117 let thief = IT.seat(authenticator: key, store: leaked)118 let ended = Task { () -> SessionEndReason? in119 for await r in await thief.api.tokens.sessionEnds() { return r }120 return nil121 }122 try await Task.sleep(for: .milliseconds(100))123 do {124 _ = try await IT.patiently { try await thief.api.call { try await $0.getMe().ok.body.json } }125 Issue.record("the leaked token must not work")126 } catch {127 #expect(APIError.from(error).isSignedOut)128 }129 if case .refreshRejected(let e)? = await ended.value { #expect(e.code == "refresh_rejected") } else { Issue.record("no session end emitted") }130 #expect(leaked.accounts.isEmpty) // wiped131 #expect(await thief.api.tokens.hasSession == false)132 #expect(try IT.psql("select revoked_reason from sessions where id='\(me.session.id)'") == "refresh_reuse")133134 // The legitimate holder is signed out too: the server revoked the whole session.135 do {136 _ = try await IT.patiently { try await seat.api.call { try await $0.getMe().ok.body.json } }137 Issue.record("the revoked session must not work")138 } catch {139 #expect(APIError.from(error).isSignedOut)140 }141 #expect(seat.store.accounts.isEmpty)142 }143144 @Test("a revoked device is signed out at its next request")145 func revokedDevice() async throws {146 let key = try await IT.owner.authenticator()147 let a = try await IT.sharedOwner.seat()148 let b = try await IT.signedIn(as: key, label: "To revoke")149 let bDevice = try #require(await b.api.tokens.deviceID)150 _ = try await a.api.call { try await $0.revokeMyDevice(path: .init(id: bDevice)).noContent }151 do {152 _ = try await IT.patiently { try await b.api.call { try await $0.getMe().ok.body.json } }153 Issue.record("a revoked device must not keep working")154 } catch {155 #expect(APIError.from(error).isSignedOut)156 }157 #expect(await b.api.tokens.hasSession == false)158 #expect(b.store.accounts.isEmpty)159 _ = try await a.api.call { try await $0.getMe().ok.body.json } // the other device is unaffected160 }161162 @Test("403 step_up_required → passkey ceremony → the original call is retried once")163 func stepUpRetry() async throws {164 let key = try await IT.owner.authenticator()165 let seat = try await IT.sharedOwner.seat()166 let stepUpsBefore = await seat.auth.stepUpCount167 let me = try await seat.api.call { try await $0.getMe().ok.body.json }168 try IT.psql("update sessions set authenticated_at = now() - interval '10 minutes' where id='\(me.session.id)'")169 // Without the helper the server refuses.170 do {171 _ = try await seat.api.call { try await $0.createInvitation(body: .json(.init(role: .viewer, handle: "stepup-a", displayName: "A"))).created.body.json }172 Issue.record("step-up must be required")173 } catch {174 let e = APIError.from(error)175 #expect(e.isStepUpRequired)176 #expect(e.correlationID != nil)177 }178 let assertionsBefore = key.assertionCount179 let created = try await seat.auth.withStepUp {180 try await seat.api.call { try await $0.createInvitation(body: .json(.init(role: .viewer, handle: "stepup-b", displayName: "B"))).created.body.json }181 }182 #expect(created.invitation.role == .viewer)183 #expect(created.setupUrl.contains("/setup#"))184 #expect(await seat.auth.stepUpCount == stepUpsBefore + 1)185 #expect(key.assertionCount == assertionsBefore + 1)186 // Within the 5-minute window no new ceremony is needed.187 _ = try await seat.auth.withStepUp {188 try await seat.api.call { try await $0.createInvitation(body: .json(.init(role: .viewer, handle: "stepup-c", displayName: "C"))).created.body.json }189 }190 #expect(await seat.auth.stepUpCount == stepUpsBefore + 1)191 }192193 private func ownerInvitation(role: API.UserRole, handle: String? = nil, name: String? = nil, target: String? = nil) async throws -> String {194 let seat = try await IT.sharedOwner.seat()195 let created = try await seat.auth.withStepUp {196 try await seat.api.call {197 try await $0.createInvitation(body: .json(.init(role: role, handle: handle, displayName: name, targetUserId: target))).created.body.json198 }199 }200 return created.token201 }202203 @Test("invited operator: profile step, passkey creation, server-side role; a used invitation is a dead end")204 func invitedOperatorAndLink() async throws {205 let token = try await ownerInvitation(role: ._operator)206 let seat = IT.seat(label: "Operator Mac")207 let tx = try await IT.patiently { try await seat.auth.exchangeInvitation(token: token) }208 #expect(tx.role == ._operator)209 #expect(tx.profileRequired)210 #expect(tx.inviterDisplayName == "Owner IT")211 // The passkey cannot be created before the profile is chosen.212 do { _ = try await IT.patiently { try await seat.auth.completeInvitation(passkeyLabel: nil) }; Issue.record("profile must be required") }213 catch { #expect(APIError.from(error).code == "profile_required") }214 let tx2 = try await IT.patiently { try await seat.auth.setInvitationProfile(handle: "operator-it", displayName: "Operator IT") }215 #expect(tx2.profileRequired == false)216 #expect(tx2.handle == "operator-it")217 _ = try await IT.patiently { try await seat.auth.completeInvitation(passkeyLabel: "Op key") }218 let me = try await seat.api.call { try await $0.getMe().ok.body.json }219 #expect(me.user.role == ._operator)220 #expect(me.permissions.contains("maintenance.write"))221 #expect(!me.permissions.contains("users.manage"))222 // The server, not the client, enforces permissions.223 do { _ = try await seat.api.call { try await $0.listUsers().ok.body.json }; Issue.record("operators cannot list users") }224 catch { #expect(APIError.from(error).isForbidden) }225226 // Used invitation → 410, dead end.227 let again = IT.seat()228 do { _ = try await IT.patiently { try await again.auth.exchangeInvitation(token: token) }; Issue.record("single use") }229 catch {230 let e = APIError.from(error)231 #expect(e.isGone)232 #expect(e.correlationID != nil)233 }234235 // Link flow: an invitation aimed at the existing operator account raises its role after sign-in + step-up +236 // explicit confirmation.237 let link = try await ownerInvitation(role: .admin, target: me.user.id)238 let linkSeat = IT.seat(authenticator: seat.authenticator, label: "Operator Mac 2")239 let ltx = try await IT.patiently { try await linkSeat.auth.exchangeInvitation(token: link) }240 #expect(ltx.requiresExistingAccount)241 #expect(ltx.purpose == .link)242 do { _ = try await linkSeat.auth.linkInvitation(confirmed: false); Issue.record("confirmation is mandatory") }243 catch { #expect(APIError.from(error).code == "validation_failed") }244 _ = try await IT.patiently { try await linkSeat.auth.signIn() }245 try IT.psql("update sessions set authenticated_at = now() - interval '10 minutes' where user_id='\(me.user.id)'")246 let linked = try await linkSeat.auth.linkInvitation(confirmed: true)247 #expect(linked.user.id == me.user.id)248 #expect(linked.user.role == .admin)249 #expect(await linkSeat.auth.stepUpCount == 1)250 #expect(await linkSeat.auth.hasPendingInvitation == false)251252 // An invitation for another account cannot be linked by the wrong user.253 let ownerKey = try await IT.owner.authenticator()254 let foreign = try await ownerInvitation(role: .viewer, target: me.user.id)255 let wrong = IT.seat(authenticator: ownerKey)256 _ = try await IT.patiently { try await wrong.auth.exchangeInvitation(token: foreign) }257 _ = try await IT.patiently { try await wrong.auth.signIn() }258 do { _ = try await wrong.auth.linkInvitation(confirmed: true); Issue.record("wrong account must be refused") }259 catch { #expect(APIError.from(error).code == "wrong_account") }260 }261262 @Test("passkeys: add (step-up), rename, delete; the last passkey cannot be removed")263 func passkeyManagement() async throws {264 let token = try await ownerInvitation(role: .viewer, handle: "passkeys-it", name: "Passkeys IT")265 let seat = IT.seat()266 _ = try await IT.patiently { try await seat.auth.exchangeInvitation(token: token) }267 let reg = try await IT.patiently { try await seat.auth.completeInvitation(passkeyLabel: "First") }268 // A second authenticator (another device) for the same account.269 let second = SoftwareAuthenticator(origin: IT.origin!.absoluteString)270 let auth2 = AuthService(api: seat.api, passkeys: second) { DeviceInfo(kind: .macos, label: "x", model: "x", osVersion: "x", appVersion: "x") }271 let added = try await auth2.addPasskey(label: "Second")272 #expect(added.label == "Second")273 var list = try await seat.api.call { try await $0.listMyPasskeys().ok.body.json }274 #expect(list.items.count == 2)275 let renamed = try await seat.api.call { try await $0.updateMyPasskey(path: .init(id: added.id), body: .json(.init(label: "Renamed"))).ok.body.json }276 #expect(renamed.label == "Renamed")277 _ = try await seat.auth.withStepUp { try await seat.api.call { _ = try await $0.deleteMyPasskey(path: .init(id: added.id)).noContent } }278 list = try await seat.api.call { try await $0.listMyPasskeys().ok.body.json }279 #expect(list.items.filter { $0.revokedAt == nil }.count == 1)280 do {281 _ = try await seat.auth.withStepUp { try await seat.api.call { _ = try await $0.deleteMyPasskey(path: .init(id: reg.passkey.id)).noContent } }282 Issue.record("the last passkey must stay")283 } catch {284 #expect(APIError.from(error).code == "last_passkey")285 }286 }287288 @Test("sign-out revokes the server session and wipes the tokens; push token registration")289 func signOutAndPushToken() async throws {290 let key = try await IT.owner.authenticator()291 let seat = try await IT.signedIn(as: key)292 let device = try await seat.api.call {293 try await $0.putMyPushToken(body: .json(.init(token: String(repeating: "ab", count: 32), environment: .development))).ok.body.json294 }295 #expect(device.pushEnabled)296 let me = try await seat.api.call { try await $0.getMe().ok.body.json }297 await seat.auth.signOut()298 #expect(await seat.api.tokens.hasSession == false)299 #expect(!seat.store.accounts.contains { $0.hasPrefix("tokens@") })300 #expect(seat.store.accounts.contains { $0.hasPrefix("device@") }) // the device identity is kept for the next sign-in301 #expect(try IT.psql("select revoked_at is not null from sessions where id='\(me.session.id)'") == "t")302 }303}304}305