mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-11-29 10:43:47 +00:00
fix(menubar): migrate Claude/Codex caches to namespaced Keychain
Stop writing OAuth caches as Application Support JSON. Persist CodeBurn-owned items in Keychain, secure-read and migrate leftover 0644 files only after read-back verification, and keep Claude from storing a refresh token.
This commit is contained in:
parent
bb1974dab8
commit
cdaa5b7ed3
10 changed files with 1112 additions and 56 deletions
|
|
@ -1070,7 +1070,11 @@ final class AppStore {
|
|||
// result instead of re-populating the cleared state.
|
||||
claudeRefreshGen &+= 1
|
||||
subscription = nil
|
||||
subscriptionError = nil
|
||||
if let result = ClaudeCredentialStore.lastCacheDeleteResult, !result.isSuccess {
|
||||
subscriptionError = "Could not fully remove the local Claude credential cache."
|
||||
} else {
|
||||
subscriptionError = nil
|
||||
}
|
||||
subscriptionLoadState = .notBootstrapped
|
||||
capacityEstimates = [:]
|
||||
Task.detached { await SubscriptionSnapshotStore.clearAll() }
|
||||
|
|
@ -1134,7 +1138,11 @@ final class AppStore {
|
|||
CodexSubscriptionService.disconnect()
|
||||
codexRefreshGen &+= 1
|
||||
codexUsage = nil
|
||||
codexError = nil
|
||||
if let result = CodexCredentialStore.lastCacheDeleteResult, !result.isSuccess {
|
||||
codexError = "Could not fully remove the local Codex credential cache."
|
||||
} else {
|
||||
codexError = nil
|
||||
}
|
||||
codexLoadState = .notBootstrapped
|
||||
NotificationCenter.default.post(name: .codeBurnSubscriptionDisconnected, object: nil)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ import Security
|
|||
/// the refresh endpoint. If the CLI hasn't rotated yet we report a
|
||||
/// transient staleness (`sourceTokenStale`) and recover on its next use.
|
||||
///
|
||||
/// 3. **In-memory + file cache** so back-to-back reads in the same refresh
|
||||
/// 3. **In-memory + Keychain cache** so back-to-back reads in the same refresh
|
||||
/// cycle don't re-hit the source, and we keep serving the last good token
|
||||
/// across launches.
|
||||
/// across launches without a plaintext Application Support file.
|
||||
enum ClaudeCredentialStore {
|
||||
private static let bootstrapCompletedKey = "codeburn.claude.bootstrapCompleted"
|
||||
private static let inMemoryTTL: TimeInterval = 5 * 60
|
||||
|
|
@ -28,12 +28,45 @@ enum ClaudeCredentialStore {
|
|||
private static let credentialsRelativePath = ".claude/.credentials.json"
|
||||
private static let maxCredentialBytes = 64 * 1024
|
||||
|
||||
/// Legacy local cache file. New writes use the macOS Keychain; this path is
|
||||
/// Legacy local cache file under Application Support. Migration to the
|
||||
/// CodeBurn-namespaced Keychain item is staged behind an injectable seam.
|
||||
private static let cacheFilename = "claude-credentials.v1.json"
|
||||
|
||||
static let ourKeychainService = CodeBurnKeychainIdentity.claudeService
|
||||
static let ourKeychainAccount = CodeBurnKeychainIdentity.account
|
||||
|
||||
private static let lock = NSLock()
|
||||
private nonisolated(unsafe) static var memoryCache: CachedRecord?
|
||||
|
||||
// MARK: - Injectable seams (tests + staged Keychain migration)
|
||||
|
||||
/// Override Application Support root. Nil uses the real user domain.
|
||||
nonisolated(unsafe) static var applicationSupportDirectoryOverride: URL?
|
||||
/// Override home for Claude CLI credential discovery. Nil uses the real home.
|
||||
nonisolated(unsafe) static var homeDirectoryOverride: URL?
|
||||
/// Override defaults used for bootstrap flags.
|
||||
nonisolated(unsafe) static var userDefaultsOverride: UserDefaults?
|
||||
/// Keychain backend. Production uses Live; tests inject InMemory.
|
||||
nonisolated(unsafe) static var keychainCache: any KeychainCredentialCaching = LiveKeychainCredentialCache()
|
||||
|
||||
static func resetTestSeams() {
|
||||
applicationSupportDirectoryOverride = nil
|
||||
homeDirectoryOverride = nil
|
||||
userDefaultsOverride = nil
|
||||
keychainCache = LiveKeychainCredentialCache()
|
||||
lastCacheDeleteResult = nil
|
||||
lastLegacyCleanupFailed = false
|
||||
lock.withLock { memoryCache = nil }
|
||||
}
|
||||
|
||||
private static var defaults: UserDefaults {
|
||||
userDefaultsOverride ?? .standard
|
||||
}
|
||||
|
||||
private static var homeDirectory: URL {
|
||||
homeDirectoryOverride ?? FileManager.default.homeDirectoryForCurrentUser
|
||||
}
|
||||
|
||||
struct CachedRecord {
|
||||
let record: CredentialRecord
|
||||
let cachedAt: Date
|
||||
|
|
@ -88,18 +121,37 @@ enum ClaudeCredentialStore {
|
|||
/// True once the user has explicitly connected (clicked Connect in the Plan
|
||||
/// tab AND we successfully read their credentials). Persists across launches.
|
||||
static var isBootstrapCompleted: Bool {
|
||||
get { UserDefaults.standard.bool(forKey: bootstrapCompletedKey) }
|
||||
set { UserDefaults.standard.set(newValue, forKey: bootstrapCompletedKey) }
|
||||
get { defaults.bool(forKey: bootstrapCompletedKey) }
|
||||
set { defaults.set(newValue, forKey: bootstrapCompletedKey) }
|
||||
}
|
||||
|
||||
/// Reset bootstrap state. Used when the user explicitly wants to disconnect
|
||||
/// or when the refresh token has been revoked terminally.
|
||||
static func resetBootstrap() {
|
||||
/// or when the refresh token has been revoked terminally. Deletion failures
|
||||
/// are recorded on `lastCacheDeleteResult` — callers must not claim the
|
||||
/// local copy is gone when `isSuccess` is false.
|
||||
@discardableResult
|
||||
static func resetBootstrap() -> CacheDeleteResult {
|
||||
lock.withLock { memoryCache = nil }
|
||||
deleteOurCache()
|
||||
let result = deleteOurCache()
|
||||
lastCacheDeleteResult = result
|
||||
isBootstrapCompleted = false
|
||||
return result
|
||||
}
|
||||
|
||||
/// Outcome of deleting CodeBurn-owned Claude cache material.
|
||||
struct CacheDeleteResult: Equatable {
|
||||
var keychainDeletedOrAbsent: Bool
|
||||
var legacyDeletedOrAbsent: Bool
|
||||
var isSuccess: Bool { keychainDeletedOrAbsent && legacyDeletedOrAbsent }
|
||||
}
|
||||
|
||||
/// Last disconnect/cleanup result. Nil until the first delete attempt.
|
||||
nonisolated(unsafe) static var lastCacheDeleteResult: CacheDeleteResult?
|
||||
|
||||
/// Last legacy-unlink failure after a verified Keychain write (cleanup retry signal).
|
||||
nonisolated(unsafe) static var lastLegacyCleanupFailed = false
|
||||
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// User-initiated entry point. Reads from Claude's source (PROMPTS for the
|
||||
|
|
@ -190,7 +242,7 @@ enum ClaudeCredentialStore {
|
|||
}
|
||||
|
||||
private static func readClaudeFile() throws -> CredentialRecord? {
|
||||
let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(credentialsRelativePath)
|
||||
let url = homeDirectory.appendingPathComponent(credentialsRelativePath)
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
||||
let data = try SafeFile.read(from: url.path, maxBytes: maxCredentialBytes)
|
||||
return try parseClaudeBlob(data: sanitizeClaudeBlob(data))
|
||||
|
|
@ -305,37 +357,174 @@ enum ClaudeCredentialStore {
|
|||
}
|
||||
}
|
||||
|
||||
// MARK: - Local cache file (no keychain involvement)
|
||||
// MARK: - Local cache (injectable Application Support + Keychain seam)
|
||||
|
||||
private static func cacheFileURL() -> URL {
|
||||
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")
|
||||
static func cacheFileURL() -> URL {
|
||||
let support = applicationSupportDirectoryOverride
|
||||
?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? homeDirectory.appendingPathComponent("Library/Application Support")
|
||||
return support
|
||||
.appendingPathComponent("CodeBurn", isDirectory: true)
|
||||
.appendingPathComponent(cacheFilename)
|
||||
}
|
||||
|
||||
/// Production-used write path. Persists to the CodeBurn-namespaced Keychain
|
||||
/// item. Claude never stores a refresh token in this cache. After a verified
|
||||
/// Keychain read-back, any legacy JSON is unlinked (not "securely erased").
|
||||
static func writeOurCache(record: CredentialRecord) throws {
|
||||
let persisted = encodePersisted(record)
|
||||
let data = try JSONEncoder().encode(persisted)
|
||||
try keychainCache.upsert(
|
||||
service: ourKeychainService,
|
||||
account: ourKeychainAccount,
|
||||
data: data
|
||||
)
|
||||
try verifyKeychainMatches(persisted)
|
||||
tryUnlinkLegacyAfterVerifiedKeychain()
|
||||
}
|
||||
|
||||
/// Cache shape stored in Keychain — intentionally omits refreshToken.
|
||||
struct PersistedCacheRecord: Codable, Equatable {
|
||||
let accessToken: String
|
||||
let expiresAt: Date?
|
||||
let rateLimitTier: String?
|
||||
}
|
||||
|
||||
private static func encodePersisted(_ record: CredentialRecord) -> PersistedCacheRecord {
|
||||
PersistedCacheRecord(
|
||||
accessToken: record.accessToken,
|
||||
expiresAt: record.expiresAt,
|
||||
rateLimitTier: record.rateLimitTier
|
||||
)
|
||||
}
|
||||
|
||||
private static func decodePersisted(_ data: Data) -> CredentialRecord? {
|
||||
if let persisted = try? JSONDecoder().decode(PersistedCacheRecord.self, from: data) {
|
||||
return CredentialRecord(
|
||||
accessToken: persisted.accessToken,
|
||||
refreshToken: nil,
|
||||
expiresAt: persisted.expiresAt,
|
||||
rateLimitTier: persisted.rateLimitTier
|
||||
)
|
||||
}
|
||||
// Historical blobs may still include refreshToken; drop it on read.
|
||||
if let legacy = try? JSONDecoder().decode(CredentialRecord.self, from: data) {
|
||||
return CredentialRecord(
|
||||
accessToken: legacy.accessToken,
|
||||
refreshToken: nil,
|
||||
expiresAt: legacy.expiresAt,
|
||||
rateLimitTier: legacy.rateLimitTier
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func verifyKeychainMatches(_ expected: PersistedCacheRecord) throws {
|
||||
guard let data = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount),
|
||||
let roundTrip = decodePersisted(data),
|
||||
encodePersisted(roundTrip) == expected
|
||||
else {
|
||||
throw StoreError.keychainWriteFailed(-1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func readOurCache() throws -> CredentialRecord? {
|
||||
if let data = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount),
|
||||
let record = decodePersisted(data) {
|
||||
// Rewrite historical Claude blobs once without refreshToken.
|
||||
let sanitized = encodePersisted(record)
|
||||
if let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
object.keys.contains("refreshToken") {
|
||||
try? writeOurCache(record: record)
|
||||
} else {
|
||||
tryUnlinkLegacyAfterVerifiedKeychain()
|
||||
_ = sanitized
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
return try migrateLegacyFileIfPresent()
|
||||
}
|
||||
|
||||
/// Secure-read legacy JSON, upsert Keychain, verify read-back, then unlink.
|
||||
private static func migrateLegacyFileIfPresent() throws -> CredentialRecord? {
|
||||
let url = cacheFileURL()
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
||||
let data = try SafeFile.read(from: url.path, maxBytes: maxCredentialBytes)
|
||||
guard let record = try? JSONDecoder().decode(CredentialRecord.self, from: data) else { return nil }
|
||||
return record
|
||||
|
||||
let data: Data
|
||||
do {
|
||||
data = try SafeFile.readAfterSecuringPermissions(
|
||||
from: url.path,
|
||||
maxBytes: maxCredentialBytes
|
||||
)
|
||||
} catch {
|
||||
// Symlink / ownership / chmod failures: leave the file alone.
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let decoded = try? JSONDecoder().decode(CredentialRecord.self, from: data) else {
|
||||
// Invalid data stays in place at 0600; do not delete.
|
||||
return nil
|
||||
}
|
||||
let migrated = CredentialRecord(
|
||||
accessToken: decoded.accessToken,
|
||||
refreshToken: nil,
|
||||
expiresAt: decoded.expiresAt,
|
||||
rateLimitTier: decoded.rateLimitTier
|
||||
)
|
||||
|
||||
do {
|
||||
try writeOurCache(record: migrated)
|
||||
return migrated
|
||||
} catch {
|
||||
// Keychain write/read-back failure: leave repaired 0600 legacy file.
|
||||
lastLegacyCleanupFailed = false
|
||||
return migrated
|
||||
}
|
||||
}
|
||||
|
||||
private static func writeOurCache(record: CredentialRecord) throws {
|
||||
try writeOurFileCache(record: record)
|
||||
}
|
||||
|
||||
private static func writeOurFileCache(record: CredentialRecord) throws {
|
||||
private static func tryUnlinkLegacyAfterVerifiedKeychain() {
|
||||
let url = cacheFileURL()
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let data = try JSONEncoder().encode(record)
|
||||
try data.write(to: url, options: [.atomic, .completeFileProtection])
|
||||
guard FileManager.default.fileExists(atPath: url.path) else {
|
||||
lastLegacyCleanupFailed = false
|
||||
return
|
||||
}
|
||||
do {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
lastLegacyCleanupFailed = false
|
||||
} catch {
|
||||
// Retain valid Keychain item + 0600 file; surface for later retry.
|
||||
lastLegacyCleanupFailed = true
|
||||
}
|
||||
}
|
||||
|
||||
private static func deleteOurCache() {
|
||||
try? FileManager.default.removeItem(at: cacheFileURL())
|
||||
@discardableResult
|
||||
private static func deleteOurCache() -> CacheDeleteResult {
|
||||
var keychainOK = true
|
||||
do {
|
||||
try keychainCache.delete(service: ourKeychainService, account: ourKeychainAccount)
|
||||
} catch {
|
||||
keychainOK = false
|
||||
}
|
||||
|
||||
var legacyOK = true
|
||||
let url = cacheFileURL()
|
||||
if FileManager.default.fileExists(atPath: url.path) {
|
||||
do {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
} catch {
|
||||
legacyOK = false
|
||||
}
|
||||
}
|
||||
return CacheDeleteResult(
|
||||
keychainDeletedOrAbsent: keychainOK,
|
||||
legacyDeletedOrAbsent: legacyOK
|
||||
)
|
||||
}
|
||||
|
||||
/// Clears only the in-memory TTL cache (simulates process restart in tests).
|
||||
static func clearMemoryCacheForTesting() {
|
||||
lock.withLock { memoryCache = nil }
|
||||
}
|
||||
|
||||
private static func cacheInMemory(_ record: CredentialRecord) {
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ enum ClaudeSubscriptionService {
|
|||
|
||||
/// Reset everything — used on user-initiated disconnect.
|
||||
static func disconnect() {
|
||||
ClaudeCredentialStore.resetBootstrap()
|
||||
_ = ClaudeCredentialStore.resetBootstrap()
|
||||
clearUsageBlock()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import Security
|
|||
/// ClaudeCredentialStore but reads from ~/.codex/auth.json — Codex CLI
|
||||
/// already stores its tokens as plaintext JSON in the home directory, so
|
||||
/// no keychain prompt is involved on bootstrap. After the user clicks
|
||||
/// Connect we cache a copy under ~/Library/Application Support/CodeBurn so
|
||||
/// Connect we cache a CodeBurn-owned copy in the macOS Keychain so
|
||||
/// we keep using rotated tokens after refresh.
|
||||
enum CodexCredentialStore {
|
||||
private static let bootstrapCompletedKey = "codeburn.codex.bootstrapCompleted"
|
||||
|
|
@ -23,9 +23,37 @@ enum CodexCredentialStore {
|
|||
|
||||
private static let cacheFilename = "codex-credentials.v1.json"
|
||||
|
||||
static let ourKeychainService = CodeBurnKeychainIdentity.codexService
|
||||
static let ourKeychainAccount = CodeBurnKeychainIdentity.account
|
||||
|
||||
private static let lock = NSLock()
|
||||
private nonisolated(unsafe) static var memoryCache: CachedRecord?
|
||||
|
||||
// MARK: - Injectable seams (tests + staged Keychain migration)
|
||||
|
||||
nonisolated(unsafe) static var applicationSupportDirectoryOverride: URL?
|
||||
nonisolated(unsafe) static var homeDirectoryOverride: URL?
|
||||
nonisolated(unsafe) static var userDefaultsOverride: UserDefaults?
|
||||
nonisolated(unsafe) static var keychainCache: any KeychainCredentialCaching = LiveKeychainCredentialCache()
|
||||
|
||||
static func resetTestSeams() {
|
||||
applicationSupportDirectoryOverride = nil
|
||||
homeDirectoryOverride = nil
|
||||
userDefaultsOverride = nil
|
||||
keychainCache = LiveKeychainCredentialCache()
|
||||
lastCacheDeleteResult = nil
|
||||
lastLegacyCleanupFailed = false
|
||||
lock.withLock { memoryCache = nil }
|
||||
}
|
||||
|
||||
private static var defaults: UserDefaults {
|
||||
userDefaultsOverride ?? .standard
|
||||
}
|
||||
|
||||
private static var homeDirectory: URL {
|
||||
homeDirectoryOverride ?? FileManager.default.homeDirectoryForCurrentUser
|
||||
}
|
||||
|
||||
struct CachedRecord {
|
||||
let record: CredentialRecord
|
||||
let cachedAt: Date
|
||||
|
|
@ -97,16 +125,28 @@ enum CodexCredentialStore {
|
|||
// MARK: - Bootstrap state
|
||||
|
||||
static var isBootstrapCompleted: Bool {
|
||||
get { UserDefaults.standard.bool(forKey: bootstrapCompletedKey) }
|
||||
set { UserDefaults.standard.set(newValue, forKey: bootstrapCompletedKey) }
|
||||
get { defaults.bool(forKey: bootstrapCompletedKey) }
|
||||
set { defaults.set(newValue, forKey: bootstrapCompletedKey) }
|
||||
}
|
||||
|
||||
static func resetBootstrap() {
|
||||
static func resetBootstrap() -> CacheDeleteResult {
|
||||
lock.withLock { memoryCache = nil }
|
||||
deleteOurCache()
|
||||
let result = deleteOurCache()
|
||||
lastCacheDeleteResult = result
|
||||
isBootstrapCompleted = false
|
||||
return result
|
||||
}
|
||||
|
||||
struct CacheDeleteResult: Equatable {
|
||||
var keychainDeletedOrAbsent: Bool
|
||||
var legacyDeletedOrAbsent: Bool
|
||||
var isSuccess: Bool { keychainDeletedOrAbsent && legacyDeletedOrAbsent }
|
||||
}
|
||||
|
||||
nonisolated(unsafe) static var lastCacheDeleteResult: CacheDeleteResult?
|
||||
nonisolated(unsafe) static var lastLegacyCleanupFailed = false
|
||||
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
@discardableResult
|
||||
|
|
@ -170,7 +210,7 @@ enum CodexCredentialStore {
|
|||
// MARK: - Bootstrap source: ~/.codex/auth.json
|
||||
|
||||
private static func readCodexAuth() throws -> CredentialRecord {
|
||||
let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(codexAuthPath)
|
||||
let url = homeDirectory.appendingPathComponent(codexAuthPath)
|
||||
guard FileManager.default.fileExists(atPath: url.path) else {
|
||||
throw StoreError.bootstrapNoSource
|
||||
}
|
||||
|
|
@ -231,7 +271,7 @@ enum CodexCredentialStore {
|
|||
/// key (OPENAI_API_KEY, auth_mode, ...) and only rewrites the tokens dict and
|
||||
/// last_refresh. Keeps the CLI and the menubar on the same rotated grant.
|
||||
private static func writeBackToCodexAuth(record: CredentialRecord) {
|
||||
let url = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(codexAuthPath)
|
||||
let url = homeDirectory.appendingPathComponent(codexAuthPath)
|
||||
var json: [String: Any] = [:]
|
||||
if let data = try? SafeFile.read(from: url.path, maxBytes: maxCredentialBytes),
|
||||
let existing = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
||||
|
|
@ -250,40 +290,117 @@ enum CodexCredentialStore {
|
|||
guard let out = try? JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys]) else {
|
||||
return
|
||||
}
|
||||
try? out.write(to: url, options: .atomic)
|
||||
try? SafeFile.write(out, to: url.path, mode: 0o600)
|
||||
}
|
||||
|
||||
// MARK: - Local cache file
|
||||
// MARK: - Local cache (injectable Application Support + Keychain seam)
|
||||
|
||||
private static func cacheFileURL() -> URL {
|
||||
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support")
|
||||
static func cacheFileURL() -> URL {
|
||||
let support = applicationSupportDirectoryOverride
|
||||
?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? homeDirectory.appendingPathComponent("Library/Application Support")
|
||||
return support
|
||||
.appendingPathComponent("CodeBurn", isDirectory: true)
|
||||
.appendingPathComponent(cacheFilename)
|
||||
}
|
||||
|
||||
/// Production-used write path. Persists rotation fields to the CodeBurn
|
||||
/// Keychain item. After verified read-back, unlinks any legacy JSON.
|
||||
static func writeOurCache(record: CredentialRecord) throws {
|
||||
let data = try JSONEncoder().encode(record)
|
||||
try keychainCache.upsert(
|
||||
service: ourKeychainService,
|
||||
account: ourKeychainAccount,
|
||||
data: data
|
||||
)
|
||||
guard let readBack = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount),
|
||||
let roundTrip = try? JSONDecoder().decode(CredentialRecord.self, from: readBack),
|
||||
roundTrip.accessToken == record.accessToken,
|
||||
roundTrip.refreshToken == record.refreshToken,
|
||||
roundTrip.idToken == record.idToken,
|
||||
roundTrip.accountId == record.accountId
|
||||
else {
|
||||
throw StoreError.fileWriteFailed("keychain read-back mismatch")
|
||||
}
|
||||
tryUnlinkLegacyAfterVerifiedKeychain()
|
||||
}
|
||||
|
||||
private static func readOurCache() throws -> CredentialRecord? {
|
||||
if let data = try keychainCache.read(service: ourKeychainService, account: ourKeychainAccount),
|
||||
let record = try? JSONDecoder().decode(CredentialRecord.self, from: data) {
|
||||
tryUnlinkLegacyAfterVerifiedKeychain()
|
||||
return record
|
||||
}
|
||||
return try migrateLegacyFileIfPresent()
|
||||
}
|
||||
|
||||
private static func migrateLegacyFileIfPresent() throws -> CredentialRecord? {
|
||||
let url = cacheFileURL()
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
||||
let data = try SafeFile.read(from: url.path, maxBytes: maxCredentialBytes)
|
||||
guard let record = try? JSONDecoder().decode(CredentialRecord.self, from: data) else { return nil }
|
||||
return record
|
||||
|
||||
let data: Data
|
||||
do {
|
||||
data = try SafeFile.readAfterSecuringPermissions(
|
||||
from: url.path,
|
||||
maxBytes: maxCredentialBytes
|
||||
)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let decoded = try? JSONDecoder().decode(CredentialRecord.self, from: data) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
do {
|
||||
try writeOurCache(record: decoded)
|
||||
return decoded
|
||||
} catch {
|
||||
lastLegacyCleanupFailed = false
|
||||
return decoded
|
||||
}
|
||||
}
|
||||
|
||||
private static func writeOurCache(record: CredentialRecord) throws {
|
||||
try writeOurFileCache(record: record)
|
||||
}
|
||||
|
||||
private static func writeOurFileCache(record: CredentialRecord) throws {
|
||||
private static func tryUnlinkLegacyAfterVerifiedKeychain() {
|
||||
let url = cacheFileURL()
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let data = try JSONEncoder().encode(record)
|
||||
try data.write(to: url, options: [.atomic, .completeFileProtection])
|
||||
guard FileManager.default.fileExists(atPath: url.path) else {
|
||||
lastLegacyCleanupFailed = false
|
||||
return
|
||||
}
|
||||
do {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
lastLegacyCleanupFailed = false
|
||||
} catch {
|
||||
lastLegacyCleanupFailed = true
|
||||
}
|
||||
}
|
||||
|
||||
private static func deleteOurCache() {
|
||||
try? FileManager.default.removeItem(at: cacheFileURL())
|
||||
@discardableResult
|
||||
private static func deleteOurCache() -> CacheDeleteResult {
|
||||
var keychainOK = true
|
||||
do {
|
||||
try keychainCache.delete(service: ourKeychainService, account: ourKeychainAccount)
|
||||
} catch {
|
||||
keychainOK = false
|
||||
}
|
||||
|
||||
var legacyOK = true
|
||||
let url = cacheFileURL()
|
||||
if FileManager.default.fileExists(atPath: url.path) {
|
||||
do {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
} catch {
|
||||
legacyOK = false
|
||||
}
|
||||
}
|
||||
return CacheDeleteResult(
|
||||
keychainDeletedOrAbsent: keychainOK,
|
||||
legacyDeletedOrAbsent: legacyOK
|
||||
)
|
||||
}
|
||||
|
||||
static func clearMemoryCacheForTesting() {
|
||||
lock.withLock { memoryCache = nil }
|
||||
}
|
||||
|
||||
private static func cacheInMemory(_ record: CredentialRecord) {
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ enum CodexSubscriptionService {
|
|||
}
|
||||
|
||||
static func disconnect() {
|
||||
CodexCredentialStore.resetBootstrap()
|
||||
_ = CodexCredentialStore.resetBootstrap()
|
||||
clearUsageBlock()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
import Foundation
|
||||
import Security
|
||||
|
||||
/// Serializes credential-store test harnesses that mutate process-wide seams.
|
||||
enum CredentialStoreTestIsolation {
|
||||
static let lock = NSLock()
|
||||
}
|
||||
|
||||
/// Narrow CodeBurn-owned Keychain cache over exact service/account pairs.
|
||||
///
|
||||
/// Production uses `LiveKeychainCredentialCache`. Tests inject
|
||||
/// `InMemoryKeychainCredentialCache` so the suite never touches the login
|
||||
/// Keychain. Errors carry only operation, service, and OSStatus — never blob data.
|
||||
protocol KeychainCredentialCaching: Sendable {
|
||||
func read(service: String, account: String) throws -> Data?
|
||||
func upsert(service: String, account: String, data: Data) throws
|
||||
func delete(service: String, account: String) throws
|
||||
}
|
||||
|
||||
enum KeychainCredentialCacheError: Error, LocalizedError, Equatable {
|
||||
case readFailed(service: String, status: OSStatus)
|
||||
case writeFailed(service: String, status: OSStatus)
|
||||
case deleteFailed(service: String, status: OSStatus)
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case let .readFailed(service, status):
|
||||
return "Keychain read failed for \(service) (status \(status))."
|
||||
case let .writeFailed(service, status):
|
||||
return "Keychain write failed for \(service) (status \(status))."
|
||||
case let .deleteFailed(service, status):
|
||||
return "Keychain delete failed for \(service) (status \(status))."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Published CodeBurn Keychain identities. Keep these exact — Electron contracts
|
||||
/// on the Codex pair, and historical items use the same names.
|
||||
enum CodeBurnKeychainIdentity {
|
||||
static let claudeService = "org.agentseal.codeburn.menubar.claude.oauth.v1"
|
||||
static let codexService = "org.agentseal.codeburn.menubar.codex.oauth.v1"
|
||||
static let account = "default"
|
||||
}
|
||||
|
||||
struct LiveKeychainCredentialCache: KeychainCredentialCaching {
|
||||
func read(service: String, account: String) throws -> Data? {
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
kSecMatchLimit as String: kSecMatchLimitOne,
|
||||
kSecReturnData as String: true,
|
||||
]
|
||||
var result: CFTypeRef?
|
||||
let status = SecItemCopyMatching(query as CFDictionary, &result)
|
||||
if status == errSecItemNotFound { return nil }
|
||||
guard status == errSecSuccess, let data = result as? Data else {
|
||||
throw KeychainCredentialCacheError.readFailed(service: service, status: status)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func upsert(service: String, account: String, data: Data) throws {
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
]
|
||||
let attributes: [String: Any] = [
|
||||
kSecValueData as String: data,
|
||||
]
|
||||
let updateStatus = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
|
||||
if updateStatus == errSecSuccess { return }
|
||||
if updateStatus == errSecItemNotFound {
|
||||
var add = query
|
||||
add[kSecValueData as String] = data
|
||||
let addStatus = SecItemAdd(add as CFDictionary, nil)
|
||||
if addStatus == errSecSuccess { return }
|
||||
if addStatus == errSecDuplicateItem {
|
||||
let retry = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
|
||||
guard retry == errSecSuccess else {
|
||||
throw KeychainCredentialCacheError.writeFailed(service: service, status: retry)
|
||||
}
|
||||
return
|
||||
}
|
||||
throw KeychainCredentialCacheError.writeFailed(service: service, status: addStatus)
|
||||
}
|
||||
throw KeychainCredentialCacheError.writeFailed(service: service, status: updateStatus)
|
||||
}
|
||||
|
||||
func delete(service: String, account: String) throws {
|
||||
let query: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: service,
|
||||
kSecAttrAccount as String: account,
|
||||
]
|
||||
let status = SecItemDelete(query as CFDictionary)
|
||||
if status == errSecSuccess || status == errSecItemNotFound { return }
|
||||
throw KeychainCredentialCacheError.deleteFailed(service: service, status: status)
|
||||
}
|
||||
}
|
||||
|
||||
/// Process-local fake for tests. Never writes to the system Keychain.
|
||||
final class InMemoryKeychainCredentialCache: KeychainCredentialCaching, @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var items: [String: Data] = [:]
|
||||
private(set) var upsertCount = 0
|
||||
private(set) var readCount = 0
|
||||
private(set) var deleteCount = 0
|
||||
|
||||
private func key(_ service: String, _ account: String) -> String {
|
||||
"\(service)\u{1f}\(account)"
|
||||
}
|
||||
|
||||
func read(service: String, account: String) throws -> Data? {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
readCount += 1
|
||||
return items[key(service, account)]
|
||||
}
|
||||
|
||||
func upsert(service: String, account: String, data: Data) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
upsertCount += 1
|
||||
items[key(service, account)] = data
|
||||
}
|
||||
|
||||
func delete(service: String, account: String) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
deleteCount += 1
|
||||
items.removeValue(forKey: key(service, account))
|
||||
}
|
||||
|
||||
func storedJSONObject(service: String, account: String) -> [String: Any]? {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let data = items[key(service, account)] else { return nil }
|
||||
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
|
||||
}
|
||||
|
||||
func storedKeys(service: String, account: String) -> [String]? {
|
||||
storedJSONObject(service: service, account: account).map { Array($0.keys).sorted() }
|
||||
}
|
||||
|
||||
/// Snapshot for simulated process restart: keep Keychain bytes, drop nothing else.
|
||||
func cloneStorage() -> InMemoryKeychainCredentialCache {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
let copy = InMemoryKeychainCredentialCache()
|
||||
copy.items = items
|
||||
return copy
|
||||
}
|
||||
}
|
||||
|
||||
/// Test double that wraps another backend and can force upsert/read/delete failures.
|
||||
final class ControllableKeychainCredentialCache: KeychainCredentialCaching, @unchecked Sendable {
|
||||
private let inner: any KeychainCredentialCaching
|
||||
var failUpsert = false
|
||||
var failRead = false
|
||||
var failDelete = false
|
||||
var upsertStatus: OSStatus = -1
|
||||
var readStatus: OSStatus = -1
|
||||
var deleteStatus: OSStatus = -1
|
||||
|
||||
init(inner: any KeychainCredentialCaching) {
|
||||
self.inner = inner
|
||||
}
|
||||
|
||||
func read(service: String, account: String) throws -> Data? {
|
||||
if failRead {
|
||||
throw KeychainCredentialCacheError.readFailed(service: service, status: readStatus)
|
||||
}
|
||||
return try inner.read(service: service, account: account)
|
||||
}
|
||||
|
||||
func upsert(service: String, account: String, data: Data) throws {
|
||||
if failUpsert {
|
||||
throw KeychainCredentialCacheError.writeFailed(service: service, status: upsertStatus)
|
||||
}
|
||||
try inner.upsert(service: service, account: account, data: data)
|
||||
}
|
||||
|
||||
func delete(service: String, account: String) throws {
|
||||
if failDelete {
|
||||
throw KeychainCredentialCacheError.deleteFailed(service: service, status: deleteStatus)
|
||||
}
|
||||
try inner.delete(service: service, account: account)
|
||||
}
|
||||
}
|
||||
|
|
@ -101,6 +101,72 @@ enum SafeFile {
|
|||
return data
|
||||
}
|
||||
|
||||
enum SecureReadError: Swift.Error, Equatable {
|
||||
case notRegularFile(String)
|
||||
case wrongOwner(String)
|
||||
case chmodFailed(String, Int32)
|
||||
case modeVerifyFailed(String, mode_t)
|
||||
}
|
||||
|
||||
/// Legacy credential migration path: open with `O_NOFOLLOW`, refuse non-regular /
|
||||
/// non-owned files, `fchmod(0600)` and verify mode, then read bounded bytes from
|
||||
/// the same descriptor. Permissions are repaired before any secret byte is read.
|
||||
static func readAfterSecuringPermissions(
|
||||
from path: String,
|
||||
maxBytes: Int = defaultReadLimit,
|
||||
expectedOwner: uid_t = geteuid()
|
||||
) throws -> Data {
|
||||
var linkInfo = stat()
|
||||
guard lstat(path, &linkInfo) == 0 else {
|
||||
throw Error.readFailed(path, errno)
|
||||
}
|
||||
if (linkInfo.st_mode & S_IFMT) == S_IFLNK {
|
||||
throw Error.symlinkDetected(path)
|
||||
}
|
||||
guard (linkInfo.st_mode & S_IFMT) == S_IFREG else {
|
||||
throw SecureReadError.notRegularFile(path)
|
||||
}
|
||||
guard linkInfo.st_uid == expectedOwner else {
|
||||
throw SecureReadError.wrongOwner(path)
|
||||
}
|
||||
|
||||
let fd = Darwin.open(path, O_RDONLY | O_NOFOLLOW)
|
||||
guard fd >= 0 else {
|
||||
throw Error.readFailed(path, errno)
|
||||
}
|
||||
defer { Darwin.close(fd) }
|
||||
|
||||
if fchmod(fd, 0o600) != 0 {
|
||||
throw SecureReadError.chmodFailed(path, errno)
|
||||
}
|
||||
var verified = stat()
|
||||
guard fstat(fd, &verified) == 0 else {
|
||||
throw Error.readFailed(path, errno)
|
||||
}
|
||||
let mode = verified.st_mode & 0o777
|
||||
guard mode == 0o600 else {
|
||||
throw SecureReadError.modeVerifyFailed(path, mode)
|
||||
}
|
||||
|
||||
let size = Int(verified.st_size)
|
||||
if size > maxBytes {
|
||||
throw Error.sizeLimitExceeded(path, size)
|
||||
}
|
||||
|
||||
var data = Data(count: max(size, 0))
|
||||
let readBytes: Int = data.withUnsafeMutableBytes { buffer -> Int in
|
||||
guard let base = buffer.baseAddress else { return 0 }
|
||||
return Darwin.read(fd, base, buffer.count)
|
||||
}
|
||||
guard readBytes >= 0 else {
|
||||
throw Error.readFailed(path, errno)
|
||||
}
|
||||
if readBytes < data.count {
|
||||
data = data.prefix(readBytes)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
/// Runs `body` while holding an exclusive POSIX advisory lock on `path`. The lock file is
|
||||
/// created if missing (with 0o600 permissions) and released on scope exit, so other
|
||||
/// codeburn processes (the CLI running in a terminal, say) block on the same file instead
|
||||
|
|
|
|||
|
|
@ -508,7 +508,7 @@ private struct CodexSettingsTab: View {
|
|||
CodexConnectionRow()
|
||||
}
|
||||
Section {
|
||||
Text("Codex live-quota tracking reads `~/.codex/auth.json` once on Connect, then keeps a local copy under Application Support so subsequent quota fetches don't re-read the original. Only ChatGPT-mode auth (Plus / Pro / Team / Business / Edu / Enterprise) is supported. API-key users are billed per request and have a different reporting surface. Credit-metered workspaces report no rate-limit windows, so their monthly credit allowance is shown instead.")
|
||||
Text("Codex live-quota tracking reads `~/.codex/auth.json` once on Connect, then keeps a CodeBurn-owned copy in the macOS Keychain so subsequent quota fetches don't re-read the original. Only ChatGPT-mode auth (Plus / Pro / Team / Business / Edu / Enterprise) is supported. API-key users are billed per request and have a different reporting surface. Credit-metered workspaces report no rate-limit windows, so their monthly credit allowance is shown instead.")
|
||||
.font(.system(size: 11))
|
||||
.foregroundStyle(.secondary)
|
||||
} header: {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,149 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import CodeBurnMenubar
|
||||
|
||||
/// Red receipt for 0B: current plaintext writers must fail these assertions.
|
||||
/// Disposable sentinels only — never log or expect raw secret values in receipts.
|
||||
@Suite("Credential Keychain cache red", .serialized)
|
||||
struct CredentialKeychainCacheRedTests {
|
||||
private let accessSentinel = "cb-red-access-sentinel"
|
||||
private let refreshSentinel = "cb-red-refresh-sentinel"
|
||||
private let idSentinel = "cb-red-id-sentinel"
|
||||
private let accountSentinel = "cb-red-account-sentinel"
|
||||
|
||||
private func withIsolatedSeams(
|
||||
_ body: (URL, InMemoryKeychainCredentialCache) throws -> Void
|
||||
) throws {
|
||||
CredentialStoreTestIsolation.lock.lock()
|
||||
defer { CredentialStoreTestIsolation.lock.unlock() }
|
||||
|
||||
let root = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("codeburn-0b-red-\(UUID().uuidString)", isDirectory: true)
|
||||
let support = root.appendingPathComponent("Application Support", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true)
|
||||
let suiteName = "codeburn.0b.red.\(UUID().uuidString)"
|
||||
let defaults = UserDefaults(suiteName: suiteName)!
|
||||
defaults.removePersistentDomain(forName: suiteName)
|
||||
|
||||
let fakeKeychain = InMemoryKeychainCredentialCache()
|
||||
ClaudeCredentialStore.resetTestSeams()
|
||||
CodexCredentialStore.resetTestSeams()
|
||||
ClaudeCredentialStore.applicationSupportDirectoryOverride = support
|
||||
CodexCredentialStore.applicationSupportDirectoryOverride = support
|
||||
ClaudeCredentialStore.userDefaultsOverride = defaults
|
||||
CodexCredentialStore.userDefaultsOverride = defaults
|
||||
ClaudeCredentialStore.keychainCache = fakeKeychain
|
||||
CodexCredentialStore.keychainCache = fakeKeychain
|
||||
|
||||
defer {
|
||||
ClaudeCredentialStore.resetTestSeams()
|
||||
CodexCredentialStore.resetTestSeams()
|
||||
defaults.removePersistentDomain(forName: suiteName)
|
||||
try? FileManager.default.removeItem(at: root)
|
||||
}
|
||||
|
||||
try body(support, fakeKeychain)
|
||||
}
|
||||
|
||||
private func posixMode(at url: URL) -> mode_t? {
|
||||
var info = stat()
|
||||
guard lstat(url.path, &info) == 0 else { return nil }
|
||||
return info.st_mode & 0o777
|
||||
}
|
||||
|
||||
private func jsonKeys(at url: URL) throws -> [String] {
|
||||
let data = try Data(contentsOf: url)
|
||||
let object = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])
|
||||
return object.keys.sorted()
|
||||
}
|
||||
|
||||
@Test("Claude writeOurCache leaves no JSON and stores Keychain payload without refreshToken")
|
||||
func claudeWriteUsesKeychainWithoutRefreshToken() throws {
|
||||
try withIsolatedSeams { support, fakeKeychain in
|
||||
let record = ClaudeCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_000),
|
||||
rateLimitTier: "default"
|
||||
)
|
||||
|
||||
try ClaudeCredentialStore.writeOurCache(record: record)
|
||||
|
||||
let legacyURL = ClaudeCredentialStore.cacheFileURL()
|
||||
let legacyExists = FileManager.default.fileExists(atPath: legacyURL.path)
|
||||
let mode = legacyExists ? posixMode(at: legacyURL) : nil
|
||||
let fileKeys = legacyExists ? try jsonKeys(at: legacyURL) : []
|
||||
let keychainKeys = fakeKeychain.storedKeys(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount
|
||||
)
|
||||
let keychainObject = fakeKeychain.storedJSONObject(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount
|
||||
)
|
||||
let hasRefreshKey = keychainObject?.keys.contains("refreshToken") == true
|
||||
let refreshValueMatches = (keychainObject?["refreshToken"] as? String) == refreshSentinel
|
||||
|
||||
// Intended green behavior (must fail against current plaintext writer):
|
||||
#expect(!legacyExists, "legacy Claude JSON must not be created under Application Support")
|
||||
#expect(fakeKeychain.upsertCount >= 1, "fake Keychain must receive a Claude upsert")
|
||||
#expect(keychainKeys != nil, "Claude Keychain payload must exist")
|
||||
#expect(!(keychainKeys?.contains("refreshToken") ?? false), "Claude Keychain keys must omit refreshToken")
|
||||
#expect(!hasRefreshKey && !refreshValueMatches, "Claude Keychain must not persist refreshToken")
|
||||
|
||||
// Red diagnostic (keys + mode only; never fixture values):
|
||||
if legacyExists {
|
||||
Issue.record(
|
||||
Comment(rawValue: "RED Claude legacy present mode=\(String(mode.map { String($0, radix: 8) } ?? "nil")) keys=\(fileKeys.joined(separator: ","))")
|
||||
)
|
||||
}
|
||||
if fakeKeychain.upsertCount == 0 {
|
||||
Issue.record(Comment(rawValue: "RED Claude Keychain upsertCount=0"))
|
||||
}
|
||||
_ = support
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Codex writeOurCache leaves no JSON and stores Keychain rotation fields")
|
||||
func codexWriteUsesKeychainWithRotationFields() throws {
|
||||
try withIsolatedSeams { support, fakeKeychain in
|
||||
let record = CodexCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
idToken: idSentinel,
|
||||
accountId: accountSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_100),
|
||||
lastRefresh: Date(timeIntervalSince1970: 1_700_000_000)
|
||||
)
|
||||
|
||||
try CodexCredentialStore.writeOurCache(record: record)
|
||||
|
||||
let legacyURL = CodexCredentialStore.cacheFileURL()
|
||||
let legacyExists = FileManager.default.fileExists(atPath: legacyURL.path)
|
||||
let mode = legacyExists ? posixMode(at: legacyURL) : nil
|
||||
let fileKeys = legacyExists ? try jsonKeys(at: legacyURL) : []
|
||||
let keychainKeys = fakeKeychain.storedKeys(
|
||||
service: CodexCredentialStore.ourKeychainService,
|
||||
account: CodexCredentialStore.ourKeychainAccount
|
||||
)
|
||||
|
||||
let required = ["accessToken", "refreshToken", "idToken", "accountId", "lastRefresh"]
|
||||
let missingRequired = required.filter { !(keychainKeys?.contains($0) ?? false) }
|
||||
|
||||
#expect(!legacyExists, "legacy Codex JSON must not be created under Application Support")
|
||||
#expect(fakeKeychain.upsertCount >= 1, "fake Keychain must receive a Codex upsert")
|
||||
#expect(keychainKeys != nil, "Codex Keychain payload must exist")
|
||||
#expect(missingRequired.isEmpty, "Codex Keychain must retain rotation fields")
|
||||
|
||||
if legacyExists {
|
||||
Issue.record(
|
||||
Comment(rawValue: "RED Codex legacy present mode=\(String(mode.map { String($0, radix: 8) } ?? "nil")) keys=\(fileKeys.joined(separator: ","))")
|
||||
)
|
||||
}
|
||||
if fakeKeychain.upsertCount == 0 {
|
||||
Issue.record(Comment(rawValue: "RED Codex Keychain upsertCount=0"))
|
||||
}
|
||||
_ = support
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,341 @@
|
|||
import Foundation
|
||||
import Testing
|
||||
@testable import CodeBurnMenubar
|
||||
|
||||
/// Implementation-continuity tests for option-3 evidence bar.
|
||||
/// Uses only InMemory/Controllable Keychain backends and temp Application Support —
|
||||
/// never the operator login Keychain or live credential files.
|
||||
@Suite("Credential Keychain implementation continuity", .serialized)
|
||||
struct CredentialKeychainContinuityTests {
|
||||
private let accessSentinel = "cb-cont-access-sentinel"
|
||||
private let refreshSentinel = "cb-cont-refresh-sentinel"
|
||||
private let idSentinel = "cb-cont-id-sentinel"
|
||||
private let accountSentinel = "cb-cont-account-sentinel"
|
||||
|
||||
private struct Harness {
|
||||
let root: URL
|
||||
let support: URL
|
||||
let defaults: UserDefaults
|
||||
let suiteName: String
|
||||
let fakeKeychain: InMemoryKeychainCredentialCache
|
||||
}
|
||||
|
||||
private func withHarness(
|
||||
_ body: (Harness) throws -> Void
|
||||
) throws {
|
||||
CredentialStoreTestIsolation.lock.lock()
|
||||
defer { CredentialStoreTestIsolation.lock.unlock() }
|
||||
|
||||
let root = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("codeburn-0b-cont-\(UUID().uuidString)", isDirectory: true)
|
||||
let support = root.appendingPathComponent("Application Support", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: support, withIntermediateDirectories: true)
|
||||
let suiteName = "codeburn.0b.cont.\(UUID().uuidString)"
|
||||
let defaults = UserDefaults(suiteName: suiteName)!
|
||||
defaults.removePersistentDomain(forName: suiteName)
|
||||
let fake = InMemoryKeychainCredentialCache()
|
||||
|
||||
ClaudeCredentialStore.resetTestSeams()
|
||||
CodexCredentialStore.resetTestSeams()
|
||||
ClaudeCredentialStore.applicationSupportDirectoryOverride = support
|
||||
CodexCredentialStore.applicationSupportDirectoryOverride = support
|
||||
ClaudeCredentialStore.homeDirectoryOverride = root
|
||||
CodexCredentialStore.homeDirectoryOverride = root
|
||||
ClaudeCredentialStore.userDefaultsOverride = defaults
|
||||
CodexCredentialStore.userDefaultsOverride = defaults
|
||||
ClaudeCredentialStore.keychainCache = fake
|
||||
CodexCredentialStore.keychainCache = fake
|
||||
|
||||
defer {
|
||||
ClaudeCredentialStore.resetTestSeams()
|
||||
CodexCredentialStore.resetTestSeams()
|
||||
defaults.removePersistentDomain(forName: suiteName)
|
||||
try? FileManager.default.removeItem(at: root)
|
||||
}
|
||||
|
||||
try body(Harness(root: root, support: support, defaults: defaults, suiteName: suiteName, fakeKeychain: fake))
|
||||
}
|
||||
|
||||
private func posixMode(at url: URL) -> mode_t? {
|
||||
var info = stat()
|
||||
guard lstat(url.path, &info) == 0 else { return nil }
|
||||
return info.st_mode & 0o777
|
||||
}
|
||||
|
||||
private func writeLegacyClaude0644(record: ClaudeCredentialStore.CredentialRecord) throws {
|
||||
let url = ClaudeCredentialStore.cacheFileURL()
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let data = try JSONEncoder().encode(record)
|
||||
try data.write(to: url)
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path)
|
||||
}
|
||||
|
||||
private func writeLegacyCodex0644(record: CodexCredentialStore.CredentialRecord) throws {
|
||||
let url = CodexCredentialStore.cacheFileURL()
|
||||
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let data = try JSONEncoder().encode(record)
|
||||
try data.write(to: url)
|
||||
try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path)
|
||||
}
|
||||
|
||||
// MARK: - Continuity lifecycle
|
||||
|
||||
@Test("Claude write → simulated restart → read → update → delete")
|
||||
func claudeWriteRestartReadUpdateDelete() throws {
|
||||
try withHarness { harness in
|
||||
let initial = ClaudeCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_000),
|
||||
rateLimitTier: "default"
|
||||
)
|
||||
try ClaudeCredentialStore.writeOurCache(record: initial)
|
||||
ClaudeCredentialStore.isBootstrapCompleted = true
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path))
|
||||
let keys = harness.fakeKeychain.storedKeys(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount
|
||||
)
|
||||
#expect(keys?.contains("refreshToken") != true)
|
||||
#expect(keys?.contains("accessToken") == true)
|
||||
|
||||
// Simulated process restart: drop memory, keep Keychain bytes.
|
||||
ClaudeCredentialStore.clearMemoryCacheForTesting()
|
||||
let afterRestart = try #require(try ClaudeCredentialStore.currentRecord())
|
||||
#expect(afterRestart.accessToken == accessSentinel)
|
||||
#expect(afterRestart.refreshToken == nil)
|
||||
|
||||
let updated = ClaudeCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel + "-rotated",
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_100),
|
||||
rateLimitTier: "default"
|
||||
)
|
||||
try ClaudeCredentialStore.writeOurCache(record: updated)
|
||||
ClaudeCredentialStore.clearMemoryCacheForTesting()
|
||||
let afterUpdate = try #require(try ClaudeCredentialStore.currentRecord())
|
||||
#expect(afterUpdate.accessToken == accessSentinel + "-rotated")
|
||||
|
||||
let deleteResult = ClaudeCredentialStore.resetBootstrap()
|
||||
#expect(deleteResult.isSuccess)
|
||||
let afterDelete = try harness.fakeKeychain.read(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount
|
||||
)
|
||||
#expect(afterDelete == nil)
|
||||
let afterDisconnect = try ClaudeCredentialStore.currentRecord()
|
||||
#expect(afterDisconnect == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Codex write → simulated restart → read → update → delete")
|
||||
func codexWriteRestartReadUpdateDelete() throws {
|
||||
try withHarness { harness in
|
||||
let initial = CodexCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
idToken: idSentinel,
|
||||
accountId: accountSentinel,
|
||||
expiresAt: nil,
|
||||
lastRefresh: Date(timeIntervalSince1970: 1_700_000_000)
|
||||
)
|
||||
try CodexCredentialStore.writeOurCache(record: initial)
|
||||
CodexCredentialStore.isBootstrapCompleted = true
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: CodexCredentialStore.cacheFileURL().path))
|
||||
let keys = harness.fakeKeychain.storedKeys(
|
||||
service: CodexCredentialStore.ourKeychainService,
|
||||
account: CodexCredentialStore.ourKeychainAccount
|
||||
)
|
||||
for required in ["accessToken", "refreshToken", "idToken", "accountId", "lastRefresh"] {
|
||||
#expect(keys?.contains(required) == true)
|
||||
}
|
||||
|
||||
CodexCredentialStore.clearMemoryCacheForTesting()
|
||||
// Without ~/.codex/auth.json, currentRecord falls through to Keychain cache.
|
||||
let afterRestart = try #require(try CodexCredentialStore.currentRecord())
|
||||
#expect(afterRestart.accessToken == accessSentinel)
|
||||
#expect(afterRestart.refreshToken == refreshSentinel)
|
||||
|
||||
let updated = CodexCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel + "-rotated",
|
||||
refreshToken: refreshSentinel + "-rotated",
|
||||
idToken: idSentinel,
|
||||
accountId: accountSentinel,
|
||||
expiresAt: nil,
|
||||
lastRefresh: Date(timeIntervalSince1970: 1_700_000_800)
|
||||
)
|
||||
try CodexCredentialStore.writeOurCache(record: updated)
|
||||
CodexCredentialStore.clearMemoryCacheForTesting()
|
||||
let afterUpdate = try #require(try CodexCredentialStore.currentRecord())
|
||||
#expect(afterUpdate.accessToken == accessSentinel + "-rotated")
|
||||
#expect(afterUpdate.refreshToken == refreshSentinel + "-rotated")
|
||||
|
||||
let deleteResult = CodexCredentialStore.resetBootstrap()
|
||||
#expect(deleteResult.isSuccess)
|
||||
let afterDisconnect = try CodexCredentialStore.currentRecord()
|
||||
#expect(afterDisconnect == nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Migration
|
||||
|
||||
@Test("successful Claude legacy 0644 migration unlinks JSON and omits refreshToken")
|
||||
func claudeSuccessfulLegacyMigration() throws {
|
||||
try withHarness { harness in
|
||||
let legacy = ClaudeCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_000),
|
||||
rateLimitTier: "default"
|
||||
)
|
||||
try writeLegacyClaude0644(record: legacy)
|
||||
#expect(posixMode(at: ClaudeCredentialStore.cacheFileURL()) == 0o644)
|
||||
|
||||
ClaudeCredentialStore.isBootstrapCompleted = true
|
||||
let migrated = try #require(try ClaudeCredentialStore.currentRecord())
|
||||
#expect(migrated.accessToken == accessSentinel)
|
||||
#expect(migrated.refreshToken == nil)
|
||||
#expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path))
|
||||
#expect(harness.fakeKeychain.upsertCount >= 1)
|
||||
let keys = harness.fakeKeychain.storedKeys(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount
|
||||
)
|
||||
#expect(keys?.contains("refreshToken") != true)
|
||||
#expect(ClaudeCredentialStore.lastLegacyCleanupFailed == false)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("failed Claude Keychain upsert leaves secured legacy file")
|
||||
func claudeFailedMigrationKeepsLegacy() throws {
|
||||
try withHarness { harness in
|
||||
let controllable = ControllableKeychainCredentialCache(inner: harness.fakeKeychain)
|
||||
controllable.failUpsert = true
|
||||
ClaudeCredentialStore.keychainCache = controllable
|
||||
|
||||
let legacy = ClaudeCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_000),
|
||||
rateLimitTier: "default"
|
||||
)
|
||||
try writeLegacyClaude0644(record: legacy)
|
||||
ClaudeCredentialStore.isBootstrapCompleted = true
|
||||
|
||||
let record = try #require(try ClaudeCredentialStore.currentRecord())
|
||||
#expect(record.accessToken == accessSentinel)
|
||||
#expect(FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path))
|
||||
#expect(posixMode(at: ClaudeCredentialStore.cacheFileURL()) == 0o600)
|
||||
#expect(harness.fakeKeychain.upsertCount == 0)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("successful Codex legacy migration unlinks JSON and keeps rotation fields")
|
||||
func codexSuccessfulLegacyMigration() throws {
|
||||
try withHarness { harness in
|
||||
let legacy = CodexCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
idToken: idSentinel,
|
||||
accountId: accountSentinel,
|
||||
expiresAt: nil,
|
||||
lastRefresh: Date(timeIntervalSince1970: 1_700_000_000)
|
||||
)
|
||||
try writeLegacyCodex0644(record: legacy)
|
||||
CodexCredentialStore.isBootstrapCompleted = true
|
||||
|
||||
let migrated = try #require(try CodexCredentialStore.currentRecord())
|
||||
#expect(migrated.refreshToken == refreshSentinel)
|
||||
#expect(!FileManager.default.fileExists(atPath: CodexCredentialStore.cacheFileURL().path))
|
||||
let keys = harness.fakeKeychain.storedKeys(
|
||||
service: CodexCredentialStore.ourKeychainService,
|
||||
account: CodexCredentialStore.ourKeychainAccount
|
||||
)
|
||||
#expect(keys?.contains("refreshToken") == true)
|
||||
#expect(keys?.contains("lastRefresh") == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("symlink legacy Claude file is refused and left in place")
|
||||
func claudeSymlinkLegacyRefused() throws {
|
||||
try withHarness { _ in
|
||||
let codeburnDir = ClaudeCredentialStore.cacheFileURL().deletingLastPathComponent()
|
||||
try FileManager.default.createDirectory(at: codeburnDir, withIntermediateDirectories: true)
|
||||
let target = codeburnDir.appendingPathComponent("not-a-cred.txt")
|
||||
try Data("x".utf8).write(to: target)
|
||||
let link = ClaudeCredentialStore.cacheFileURL()
|
||||
try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target)
|
||||
|
||||
ClaudeCredentialStore.isBootstrapCompleted = true
|
||||
let afterSymlink = try ClaudeCredentialStore.currentRecord()
|
||||
#expect(afterSymlink == nil)
|
||||
#expect(FileManager.default.fileExists(atPath: link.path))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Disconnect / reinstall
|
||||
|
||||
@Test("disconnect not-found is success; delete failure is observable")
|
||||
func disconnectIdempotentAndPartialFailure() throws {
|
||||
try withHarness { harness in
|
||||
let empty = ClaudeCredentialStore.resetBootstrap()
|
||||
#expect(empty.isSuccess)
|
||||
|
||||
try ClaudeCredentialStore.writeOurCache(record: .init(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: nil,
|
||||
rateLimitTier: nil
|
||||
))
|
||||
let controllable = ControllableKeychainCredentialCache(inner: harness.fakeKeychain)
|
||||
controllable.failDelete = true
|
||||
ClaudeCredentialStore.keychainCache = controllable
|
||||
|
||||
let failed = ClaudeCredentialStore.resetBootstrap()
|
||||
#expect(!failed.isSuccess)
|
||||
#expect(failed.keychainDeletedOrAbsent == false)
|
||||
#expect(ClaudeCredentialStore.lastCacheDeleteResult?.isSuccess == false)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("reinstall with empty Keychain and no legacy clears bootstrap on read")
|
||||
func reinstallMissingCacheClearsBootstrap() throws {
|
||||
try withHarness { _ in
|
||||
ClaudeCredentialStore.isBootstrapCompleted = true
|
||||
let missing = try ClaudeCredentialStore.currentRecord()
|
||||
#expect(missing == nil)
|
||||
#expect(ClaudeCredentialStore.isBootstrapCompleted == false)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("corrupt Keychain plus valid legacy repairs the CodeBurn item")
|
||||
func corruptKeychainRepairedFromLegacy() throws {
|
||||
try withHarness { harness in
|
||||
try harness.fakeKeychain.upsert(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount,
|
||||
data: Data("%not-json%".utf8)
|
||||
)
|
||||
let legacy = ClaudeCredentialStore.CredentialRecord(
|
||||
accessToken: accessSentinel,
|
||||
refreshToken: refreshSentinel,
|
||||
expiresAt: Date(timeIntervalSince1970: 1_900_000_000),
|
||||
rateLimitTier: "default"
|
||||
)
|
||||
try writeLegacyClaude0644(record: legacy)
|
||||
ClaudeCredentialStore.isBootstrapCompleted = true
|
||||
|
||||
let repaired = try #require(try ClaudeCredentialStore.currentRecord())
|
||||
#expect(repaired.accessToken == accessSentinel)
|
||||
#expect(repaired.refreshToken == nil)
|
||||
#expect(!FileManager.default.fileExists(atPath: ClaudeCredentialStore.cacheFileURL().path))
|
||||
let object = harness.fakeKeychain.storedJSONObject(
|
||||
service: ClaudeCredentialStore.ourKeychainService,
|
||||
account: ClaudeCredentialStore.ourKeychainAccount
|
||||
)
|
||||
#expect(object?.keys.contains("refreshToken") != true)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue