SPB Git

Repository Public

AuthTests.swift 18.5 KB 294 lines swift

1import CryptoKit2import Foundation3import Testing4@testable import MCCCore56/// Minimal CBOR reader for the tests (maps, byte/text strings, integers) — independent of the encoder under test.7struct CBORReader {8    indirect enum Item: Equatable {9        case int(Int64), bytes(Data), text(String), map([(Item, Item)]), array([Item])10        static func == (l: Item, r: Item) -> Bool { String(describing: l) == String(describing: r) }11        subscript(_ key: String) -> Item? { if case .map(let m) = self { return m.first { $0.0 == .text(key) }?.1 }; return nil }12        subscript(_ key: Int64) -> Item? { if case .map(let m) = self { return m.first { $0.0 == .int(key) }?.1 }; return nil }13        var data: Data? { if case .bytes(let d) = self { return d }; return nil }14        var string: String? { if case .text(let s) = self { return s }; return nil }15        var integer: Int64? { if case .int(let i) = self { return i }; return nil }16    }17    var bytes: [UInt8]18    var i = 019    init(_ d: Data) { bytes = [UInt8](d) }20    mutating func length(_ info: UInt8) -> UInt64 {21        switch info {22        case 0..<24: return UInt64(info)23        case 24: defer { i += 1 }; return UInt64(bytes[i])24        case 25: defer { i += 2 }; return UInt64(bytes[i]) << 8 | UInt64(bytes[i + 1])25        case 26: defer { i += 4 }; return (0..<4).reduce(0) { $0 << 8 | UInt64(bytes[i + $1]) }26        default: defer { i += 8 }; return (0..<8).reduce(0) { $0 << 8 | UInt64(bytes[i + $1]) }27        }28    }29    mutating func read() -> Item {30        let head = bytes[i]; i += 131        let n = length(head & 0x1f)32        switch head >> 5 {33        case 0: return .int(Int64(n))34        case 1: return .int(-1 - Int64(n))35        case 2: defer { i += Int(n) }; return .bytes(Data(bytes[i..<i + Int(n)]))36        case 3: defer { i += Int(n) }; return .text(String(decoding: bytes[i..<i + Int(n)], as: UTF8.self))37        case 4: return .array((0..<n).map { _ in read() })38        default: return .map((0..<n).map { _ in (read(), read()) })39        }40    }41}4243@Suite("WebAuthn")44struct AuthTests {45    static let rp = "localhost"46    static let origin = "http://localhost:8760"4748    static func registrationRequest(challenge: Data = Data(repeating: 7, count: 32)) -> PasskeyRegistrationRequest {49        PasskeyRegistrationRequest(relyingPartyID: rp, relyingPartyName: "MCC", userID: Data("user-handle".utf8), userName: "spb",50                                   userDisplayName: "Simon-Pierre", challenge: challenge, excludedCredentialIDs: [], algorithms: [-7, -257],51                                   userVerification: "required", attestation: "none", timeoutMilliseconds: 300_000)52    }5354    @Test("server options (base64url JSON) → ceremony requests")55    func optionsParsing() throws {56        let get = Fixture.json(#"{"challenge":"3q2-7wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","rpId":"clustr.spboucher.ai","timeout":300000,"userVerification":"required","allowCredentials":[{"type":"public-key","id":"AQIDBA"}]}"#)57        let a = try WebAuthnJSON.assertionRequest(from: get)58        #expect(a.relyingPartyID == "clustr.spboucher.ai")59        #expect(a.challenge.count == 32)60        #expect(a.challenge.prefix(4) == Data([0xde, 0xad, 0xbe, 0xef]))61        #expect(a.allowedCredentialIDs == [Data([1, 2, 3, 4])])62        #expect(a.userVerification == "required")63        #expect(a.timeoutMilliseconds == 300_000)6465        let create = Fixture.json(#"{"rp":{"name":"MacLustr Command Center","id":"clustr.spboucher.ai"},"user":{"name":"spb","displayName":"Simon-Pierre","id":"dXNlci1oYW5kbGU"},"challenge":"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc","pubKeyCredParams":[{"type":"public-key","alg":-7},{"type":"public-key","alg":-257}],"timeout":300000,"excludeCredentials":[{"type":"public-key","id":"_-7d"}],"authenticatorSelection":{"requireResidentKey":true,"residentKey":"required","userVerification":"required"},"attestation":"none"}"#)66        let r = try WebAuthnJSON.registrationRequest(from: create)67        #expect(r.relyingPartyID == "clustr.spboucher.ai")68        #expect(r.userID == Data("user-handle".utf8))69        #expect(r.userName == "spb")70        #expect(r.userDisplayName == "Simon-Pierre")71        #expect(r.challenge == Data(repeating: 7, count: 32))72        #expect(r.algorithms == [-7, -257])73        #expect(r.excludedCredentialIDs == [Data([0xff, 0xee, 0xdd])])74        #expect(r.attestation == "none")7576        #expect(throws: PasskeyError.self) { try WebAuthnJSON.assertionRequest(from: Fixture.json(#"{"rpId":"x"}"#)) }77        #expect(throws: PasskeyError.self) { try WebAuthnJSON.assertionRequest(from: Fixture.json(#"{"challenge":"AQ"}"#)) }78        #expect(throws: PasskeyError.self) { try WebAuthnJSON.registrationRequest(from: Fixture.json(#"{"challenge":"AQ","rp":{"id":"x"}}"#)) }79    }8081    @Test("ceremony results → exactly the JSON of PublicKeyCredential.toJSON()")82    func credentialJSON() throws {83        let a = PasskeyAssertion(credentialID: Data([0xfb, 0xff, 0xfe]), clientDataJSON: Data("{}".utf8), authenticatorData: Data([1, 2, 3]),84                                 signature: Data([9, 9]), userHandle: Data("user-handle".utf8))85        let j = WebAuthnJSON.credential(a)86        #expect(Set(j.objectValue!.keys) == ["id", "rawId", "type", "response", "clientExtensionResults", "authenticatorAttachment"])87        #expect(j["id"]?.stringValue == "-__-")                 // base64url, no padding88        #expect(j["rawId"]?.stringValue == "-__-")89        #expect(j["type"]?.stringValue == "public-key")90        #expect(j["clientExtensionResults"] == .object([:]))91        #expect(Set(j["response"]!.objectValue!.keys) == ["clientDataJSON", "authenticatorData", "signature", "userHandle"])92        #expect(j["response"]?["clientDataJSON"]?.stringValue == "e30")93        #expect(j["response"]?["authenticatorData"]?.stringValue == "AQID")94        #expect(j["response"]?["signature"]?.stringValue == "CQk")95        #expect(j["response"]?["userHandle"]?.stringValue == "dXNlci1oYW5kbGU")96        // No user handle (non-discoverable): the key is absent, not null.97        var noHandle = a; noHandle.userHandle = nil98        #expect(WebAuthnJSON.credential(noHandle)["response"]?["userHandle"] == nil)99100        let r = PasskeyRegistration(credentialID: Data([1, 2]), clientDataJSON: Data("{}".utf8), attestationObject: Data([0xa0]))101        let rj = WebAuthnJSON.credential(r)102        #expect(Set(rj.objectValue!.keys) == ["id", "rawId", "type", "response", "clientExtensionResults", "authenticatorAttachment"])103        #expect(Set(rj["response"]!.objectValue!.keys) == ["clientDataJSON", "attestationObject", "transports"])104        #expect(rj["response"]?["attestationObject"]?.stringValue == "oA")105        #expect(rj["response"]?["transports"] == .array([.string("internal"), .string("hybrid")]))106        // The generated request payload carries it unchanged.107        let payload = try rj.decode(API.RegistrationFinishRequest.CredentialPayload.self)108        #expect(try JSONValue(encoding: payload) == rj)109    }110111    @Test("software authenticator: registration vector (attestation none, flags, COSE key)")112    func registrationVector() async throws {113        let auth = SoftwareAuthenticator(origin: Self.origin)114        let reg = try await auth.registration(Self.registrationRequest())115        let client = try JSONValue.parse(reg.clientDataJSON)116        #expect(client["type"]?.stringValue == "webauthn.create")117        #expect(client["origin"]?.stringValue == Self.origin)118        #expect(client["challenge"]?.stringValue == Base64URL.encode(Data(repeating: 7, count: 32)))119        #expect(client["crossOrigin"]?.boolValue == false)120121        var reader = CBORReader(reg.attestationObject)122        let att = reader.read()123        #expect(att["fmt"]?.string == "none")124        #expect(att["attStmt"] == .map([]))125        let authData = try #require(att["authData"]?.data)126        #expect(authData.prefix(32) == Data(SHA256.hash(data: Data(Self.rp.utf8))))127        let flags = authData[32]128        #expect(flags == 0x5d)                                   // UP | UV | BE | BS | AT129        #expect(flags & 0x01 != 0 && flags & 0x04 != 0 && flags & 0x08 != 0 && flags & 0x10 != 0 && flags & 0x40 != 0)130        #expect(authData[33..<37] == Data([0, 0, 0, 0]))         // signature counter 0131        #expect(authData[37..<53] == Data(count: 16))            // AAGUID zero132        let idLen = Int(authData[53]) << 8 | Int(authData[54])133        #expect(authData[55..<55 + idLen] == reg.credentialID)134        var coseReader = CBORReader(Data(authData[(55 + idLen)...]))135        let cose = coseReader.read()136        #expect(cose[1]?.integer == 2)      // kty EC2137        #expect(cose[3]?.integer == -7)     // ES256138        #expect(cose[-1]?.integer == 1)     // P-256139        let x = try #require(cose[-2]?.data), y = try #require(cose[-3]?.data)140        #expect(x.count == 32 && y.count == 32)141        #expect(coseReader.i == coseReader.bytes.count)          // nothing after the key (no extensions)142143        // The assertion verifies against the registered public key.144        let pub = try P256.Signing.PublicKey(x963Representation: Data([4]) + x + y)145        let assertion = try await auth.assertion(PasskeyAssertionRequest(relyingPartyID: Self.rp, challenge: Data(repeating: 9, count: 32),146                                                                         allowedCredentialIDs: [], userVerification: "required"))147        #expect(assertion.credentialID == reg.credentialID)148        #expect(assertion.userHandle == Data("user-handle".utf8))149        #expect(assertion.authenticatorData.count == 37)150        #expect(assertion.authenticatorData[32] == 0x1d)         // UP | UV | BE | BS151        let signed = assertion.authenticatorData + Data(SHA256.hash(data: assertion.clientDataJSON))152        #expect(pub.isValidSignature(try P256.Signing.ECDSASignature(derRepresentation: assertion.signature), for: signed))153        #expect(try JSONValue.parse(assertion.clientDataJSON)["type"]?.stringValue == "webauthn.get")154    }155156    @Test("software authenticator: selection, exclusion, cancellation, persistence")157    func authenticatorBehaviour() async throws {158        let file = FileManager.default.temporaryDirectory.appendingPathComponent("mcc-auth-\(UUID().uuidString).json")159        defer { try? FileManager.default.removeItem(at: file) }160        let auth = SoftwareAuthenticator(origin: Self.origin, storageURL: file)161        await #expect(throws: PasskeyError.noCredential) {162            try await auth.assertion(PasskeyAssertionRequest(relyingPartyID: Self.rp, challenge: Data([1]), allowedCredentialIDs: [], userVerification: "required"))163        }164        let reg = try await auth.registration(Self.registrationRequest())165        // Same authenticator, excluded credential → refused like a platform authenticator.166        var again = Self.registrationRequest()167        again.excludedCredentialIDs = [reg.credentialID]168        await #expect(throws: PasskeyError.self) { try await auth.registration(again) }169        // Another relying party does not see the credential.170        await #expect(throws: PasskeyError.noCredential) {171            try await auth.assertion(PasskeyAssertionRequest(relyingPartyID: "other.example", challenge: Data([1]), allowedCredentialIDs: [], userVerification: "required"))172        }173        auth.behaviour = .cancel174        await #expect(throws: PasskeyError.cancelled) {175            try await auth.assertion(PasskeyAssertionRequest(relyingPartyID: Self.rp, challenge: Data([1]), allowedCredentialIDs: [], userVerification: "required"))176        }177        #expect(PasskeyError.cancelled.apiError.isPasskeyCancelled)178        // A new instance on the same file finds the credential again.179        let reloaded = SoftwareAuthenticator(origin: Self.origin, storageURL: file)180        #expect(reloaded.storedCredentials.map(\.id) == [reg.credentialID])181        _ = try await reloaded.assertion(PasskeyAssertionRequest(relyingPartyID: Self.rp, challenge: Data([1]), allowedCredentialIDs: [reg.credentialID], userVerification: "required"))182    }183184    /// Stub of the step-up endpoints + one protected operation.185    private func stepUpServer(freshAfterCeremony: Bool) -> (StubServer, Box<[String]>) {186        let server = StubServer()187        let log = Box<[String]>([])188        let stepped = Box(false)189        server.handle { r in190            log.update { $0.append("\(r.method) \(r.path)") }191            switch (r.method, r.path) {192            case ("POST", "/api/v1/auth/stepup/begin"):193                return .json(200, Fixture.json(#"{"challenge_id":"0199aaaa-0000-7000-8000-0000000000f1","expires_at":"2026-11-18T21:05:00Z","public_key":{"challenge":"BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc","rpId":"localhost","timeout":300000,"userVerification":"required"}}"#))194            case ("POST", "/api/v1/auth/stepup/finish"):195                guard r.json?["challenge_id"]?.stringValue == "0199aaaa-0000-7000-8000-0000000000f1",196                      r.json?["credential"]?["response"]?["signature"]?.stringValue != nil else { return .error(400, code: "validation_failed") }197                stepped.value = freshAfterCeremony198                return .json(200, Fixture.json(#"{"authenticated_at":"2026-11-18T21:00:00Z","step_up_valid_until":"2026-11-18T21:05:00Z"}"#))199            case ("DELETE", _):200                return stepped.value ? .http(status: 204) : .error(403, code: "step_up_required", message: "A recent passkey verification is required.")201            default: return .http(status: 404)202            }203        }204        return (server, log)205    }206207    @Test("403 step_up_required → ceremony → the original call is retried exactly once")208    func stepUpRetry() async throws {209        let (server, log) = stepUpServer(freshAfterCeremony: true)210        let api = makeAPI(server, store: Fixture.signedInStore(for: server))211        let key = SoftwareAuthenticator(origin: "http://localhost")212        _ = try await key.registration(Self.registrationRequest())213        let auth = AuthService(api: api, passkeys: key)214        try await auth.withStepUp {215            try await api.call { _ = try await $0.deleteMyPasskey(path: .init(id: Fixture.nodeID)).noContent }216        }217        #expect(log.value == ["DELETE /api/v1/me/passkeys/\(Fixture.nodeID)", "POST /api/v1/auth/stepup/begin", "POST /api/v1/auth/stepup/finish",218                              "DELETE /api/v1/me/passkeys/\(Fixture.nodeID)"])219        #expect(await auth.stepUpCount == 1)220        #expect(key.assertionCount == 1)221    }222223    @Test("a second step_up_required after the ceremony is returned to the caller (no loop)")224    func stepUpDoesNotLoop() async throws {225        let (server, log) = stepUpServer(freshAfterCeremony: false)226        let api = makeAPI(server, store: Fixture.signedInStore(for: server))227        let key = SoftwareAuthenticator(origin: "http://localhost")228        _ = try await key.registration(Self.registrationRequest())229        let auth = AuthService(api: api, passkeys: key)230        do {231            try await auth.withStepUp { try await api.call { _ = try await $0.deleteMyPasskey(path: .init(id: Fixture.nodeID)).noContent } }232            Issue.record("must throw")233        } catch {234            #expect(APIError.from(error).isStepUpRequired)235        }236        #expect(log.value.filter { $0.hasPrefix("DELETE") }.count == 2)237        #expect(await auth.stepUpCount == 1)238    }239240    @Test("a cancelled passkey sheet cancels the operation and is reported as such")241    func stepUpCancelled() async throws {242        let (server, log) = stepUpServer(freshAfterCeremony: true)243        let api = makeAPI(server, store: Fixture.signedInStore(for: server))244        let key = SoftwareAuthenticator(origin: "http://localhost")245        _ = try await key.registration(Self.registrationRequest())246        key.behaviour = .cancel247        let auth = AuthService(api: api, passkeys: key)248        do {249            try await auth.withStepUp { try await api.call { _ = try await $0.deleteMyPasskey(path: .init(id: Fixture.nodeID)).noContent } }250            Issue.record("must throw")251        } catch {252            #expect(APIError.from(error).isPasskeyCancelled)253        }254        #expect(log.value.filter { $0.hasPrefix("DELETE") }.count == 1)   // not retried255    }256257    @Test("the setup transaction token travels in X-MCC-Setup-Transaction, without bearer, and only in memory")258    func setupTransactionHeader() async throws {259        let server = StubServer()260        server.handle { r in261            switch (r.method, r.path) {262            case ("POST", "/api/v1/invitations/exchange"):263                return .json(200, Fixture.json(#"{"purpose":"new_account","role":"viewer","requires_existing_account":false,"profile_required":true,"expires_at":"2026-11-18T21:10:00Z","inviter_display_name":"Owner","transaction_token":"setup-tx-secret"}"#))264            case ("POST", "/api/v1/invitations/transaction/profile"):265                return .json(200, Fixture.json(#"{"purpose":"new_account","role":"viewer","handle":"new","display_name":"New","requires_existing_account":false,"profile_required":false,"expires_at":"2026-11-18T21:10:00Z","inviter_display_name":"Owner"}"#))266            case ("DELETE", "/api/v1/invitations/transaction"): return .http(status: 204)267            default: return .http(status: 404)268            }269        }270        // A session exists on this device: the setup calls must still not carry its bearer.271        let store = Fixture.signedInStore(for: server)272        let api = makeAPI(server, store: store)273        let auth = AuthService(api: api, passkeys: SoftwareAuthenticator(origin: "http://localhost"))274        let tx = try await auth.exchangeInvitation(token: "invitation-secret")275        #expect(tx.profileRequired)276        #expect(await auth.hasPendingInvitation)277        _ = try await auth.setInvitationProfile(handle: "new", displayName: "New")278        let profile = try #require(server.requests("POST", "/api/v1/invitations/transaction/profile").first)279        #expect(profile.header("X-MCC-Setup-Transaction") == "setup-tx-secret")280        #expect(profile.header("Authorization") == nil)281        let exchange = try #require(server.requests("POST", "/api/v1/invitations/exchange").first)282        #expect(exchange.json?["token"]?.stringValue == "invitation-secret")283        #expect(exchange.json?["client"]?["kind"]?.stringValue == "macos")284        #expect(exchange.header("Authorization") == nil)285        await auth.abandonInvitation()286        #expect(await auth.hasPendingInvitation == false)287        // Neither secret was written to the secure store.288        for account in store.accounts {289            let text = String(decoding: try #require(try store.read(account)), as: UTF8.self)290            #expect(!text.contains("setup-tx-secret") && !text.contains("invitation-secret"))291        }292    }293}294
Files main
Menu

Theme