SPB Git

Repository Public License

KeychainStoreTests.swift 5.8 KB 120 lines swift

1// ORIX OS Automation2// File: Packages/ORIXSecurity/Tests/ORIXSecurityTests/KeychainStoreTests.swift3// Description: Keychain tests. Naming/masking are unit tests; item tests are integration tests on the real Keychain under a unique test-only service, cleaned up afterwards.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import ORIXCore9import Security10import Testing11@testable import ORIXSecurity1213@Suite("KeychainStore naming and masking (unit)")14struct KeychainNamingTests {15    @Test func accountNames() {16        #expect(KeychainStore.providerAccount(.anthropic) == "provider.anthropic")17        #expect(KeychainStore.providerAccount(ProviderID(rawValue: "custom")) == "provider.custom")18        #expect(KeychainStore.secretAccount("github-token") == "secret.github-token")19        #expect(KeychainStore().service == "ai.spboucher.orix.automation")20    }2122    @Test func maskingNeverRevealsMoreThanFourTrailingCharacters() {23        #expect(KeychainStore.masked("sk-ant-api03-ABCDEFGHIJKLMNOPa1b2") == "sk-…a1b2")24        #expect(KeychainStore.masked("xai-0123456789abcdefWXYZ") == "xai-…WXYZ")25        #expect(KeychainStore.masked("0123456789abcdefghijklmnop") == "…mnop")26        #expect(KeychainStore.masked("12345678-abcdefghijklmnop") == "…mnop")27        #expect(KeychainStore.masked("short") == "••••")28        #expect(KeychainStore.masked("") == "••••")29        #expect(KeychainStore.masked("twelve-chars") == "…rs")30        #expect(KeychainStore().masked("sk-proj-0000000000000000zzzz") == "sk-…zzzz")31        for value in ["sk-ant-api03-ABCDEFGHIJKLMNOPa1b2", "ghp_abcdefghijklmnopqrstuvwxyz0123456789"] {32            let masked = KeychainStore.masked(value)33            let middle = String(value.dropFirst(4).dropLast(4))34            #expect(!masked.contains(middle))35            #expect(masked.count <= 12)36        }37    }3839    @Test func errorsAreReadable() {40        let missing = KeychainError.missingSecret(reference: "github").errorDescription ?? ""41        #expect(missing.contains("github") && missing.contains("Keychain"))42        let status = KeychainError.status(errSecItemNotFound, operation: "read")43        #expect(status.osStatus == errSecItemNotFound)44        #expect(status.errorDescription?.contains("-25300") == true)45        #expect(throws: KeychainError.invalidAccount) { try KeychainStore(service: "ai.spboucher.orix.automation.tests.unused").set("x", account: "") }46    }47}4849@Suite("KeychainStore (integration, real Keychain, unique test-only service)", .serialized)50struct KeychainIntegrationTests {51    /// A store under a service nobody else uses. Returns nil, after printing why, when this session has no usable Keychain.52    private func makeStore() -> KeychainStore? {53        let store = KeychainStore(service: "ai.spboucher.orix.automation.tests.\(UUID().uuidString)")54        do {55            try store.set("probe-value", account: "probe")56            try store.delete(account: "probe")57            return store58        } catch {59            print("SKIPPED(Keychain is not usable in this session: \(error.localizedDescription))")60            return nil61        }62    }6364    private func cleanUp(_ store: KeychainStore) {65        for account in (try? store.accounts()) ?? [] { try? store.delete(account: account) }66    }6768    @Test func setGetUpdateDeleteAndList() throws {69        guard let store = makeStore() else {70            withKnownIssue("Keychain unavailable in this session") { Issue.record("SKIPPED(Keychain unavailable)") }71            return72        }73        defer { cleanUp(store) }74        #expect(try store.accounts().isEmpty)75        #expect(try store.get(account: "provider.anthropic") == nil)76        #expect(!store.exists(account: "provider.anthropic"))7778        try store.set("first-value-0001", account: KeychainStore.providerAccount(.anthropic))79        try store.set("other-value-0002", account: KeychainStore.secretAccount("github"))80        #expect(try store.get(account: "provider.anthropic") == "first-value-0001")81        #expect(store.exists(account: "provider.anthropic"))82        #expect(try store.accounts() == ["provider.anthropic", "secret.github"])8384        try store.set("second-value-0003 ünïcödé", account: "provider.anthropic")85        #expect(try store.get(account: "provider.anthropic") == "second-value-0003 ünïcödé")86        #expect(try store.accounts().count == 2)8788        try store.delete(account: "provider.anthropic")89        try store.delete(account: "provider.anthropic")90        #expect(try store.get(account: "provider.anthropic") == nil)91        #expect(try store.accounts() == ["secret.github"])9293        // Another service does not see these items.94        let other = KeychainStore(service: store.service + ".other")95        #expect(try other.get(account: "secret.github") == nil)96        #expect(try other.accounts().isEmpty)9798        cleanUp(store)99        #expect(try store.accounts().isEmpty)100    }101102    @Test func resolverReadsRegistersAndReportsMissing() async throws {103        guard let store = makeStore() else {104            withKnownIssue("Keychain unavailable in this session") { Issue.record("SKIPPED(Keychain unavailable)") }105            return106        }107        defer { cleanUp(store) }108        let value = "orix-resolver-\(UUID().uuidString)"109        defer { Redactor.shared.unregister(secret: value) }110        try store.set(value, account: KeychainStore.secretAccount("deploy"))111        let resolver = KeychainSecretResolver(store: store)112        #expect(Redactor.shared.redact("value is \(value)").contains(value))113        #expect(try await resolver.secret(reference: "deploy") == value)114        #expect(Redactor.shared.redact("value is \(value)") == "value is \(Redactor.placeholder)")115        await #expect(throws: KeychainError.missingSecret(reference: "absent")) {116            _ = try await resolver.secret(reference: "absent")117        }118    }119}120
Files main
Menu

Theme