Files
yattee/Yattee/Services/Credentials/KeychainProvenanceReport.swift
Arkadiusz Fal 9fd0a71035 Add identity-scoped, account-keyed credential storage
Yattee 2 keys credentials by instance UUID with no notion of which Apple
account they belong to, and reads them back with SynchronizableAny. Apple
documents that Keychain data may stay on device when a user signs out and
chooses to keep it, so whoever signs in next would be served the previous
user's credential - guaranteed for migrated accounts, since local instances
survive the switch and the migrated account UUID is deterministically the
instance UUID.

Credentials are now keyed "<identityScope>|<accountID>", where the scope is
the CloudKit user record (identical across a user's devices, so iCloud
Keychain sync still works). Usernames get the same scope and live beside the
credential, keeping login identifiers out of synced metadata.

The legacy unscoped item is never adopted automatically. A strict
kSecAttrSynchronizable == true query was the candidate discriminator for
"this secret belongs to the current Apple account", but measured on iPadOS
27.0 a retained item keeps the attribute and still matches that query with
no Apple account signed in at all - the flag records what was once requested,
not live iCloud Keychain membership. Reads therefore never fall back to the
legacy key; adoption is an explicit user action that copies the item,
verifies the scoped read-back, then records a marker bound to the identity
and a salted fingerprint of the secret. The legacy item is retained, because
deleting a synchronizable item propagates and would log out devices still on
the previous release mid-rollout. Deleting it later needs all three of: a
marker on this device, matching identity, and the item still holding the
adopted secret.

The instance-keyed path is untouched, so no shipping call site changes
behavior. BasicAuthCredentialsManager stays instance-keyed - proxy auth
belongs to the instance, not to a user account.

While the scope is unresolved (first launch under a new Apple account,
CloudKit unreachable) reads report "can't tell yet" via isScopeResolved
rather than "signed out", and writes are refused rather than guessing a
scope. Login state is cached per scope so one identity's cache can never
answer for another.

Also adds the debug-only harness the measurement was taken with, under
Advanced > Developer > Experiments.
2026-08-23 21:20:30 +02:00

151 lines
5.7 KiB
Swift

//
// KeychainProvenanceReport.swift
// Yattee
//
// Captures and persists the output of KeychainProvenanceProbe so results
// survive the Apple-account sign-out/sign-in steps of the experiment.
//
#if DEBUG
import Foundation
#if canImport(UIKit)
import UIKit
#endif
/// One captured run of the experiment.
///
/// Reports are persisted because the protocol spans an Apple-account sign-out
/// and sign-in: the reading taken *before* the switch is half the evidence, and
/// it must still be readable after it.
struct KeychainProvenanceReport: Codable, Identifiable, Sendable {
let id: UUID
let capturedAt: Date
let label: String
let text: String
init(id: UUID = UUID(), capturedAt: Date = Date(), label: String, text: String) {
self.id = id
self.capturedAt = capturedAt
self.label = label
self.text = text
}
}
/// UserDefaults-backed store for captured reports.
///
/// Deliberately not synced anywhere — the whole point is a per-device record.
enum KeychainProvenanceReportStore {
private static let defaultsKey = "debug.keychainProvenanceReports"
static func load() -> [KeychainProvenanceReport] {
guard let data = UserDefaults.standard.data(forKey: defaultsKey),
let reports = try? JSONDecoder().decode([KeychainProvenanceReport].self, from: data)
else { return [] }
return reports
}
static func append(_ report: KeychainProvenanceReport) -> [KeychainProvenanceReport] {
let reports = load() + [report]
save(reports)
return reports
}
static func clear() {
UserDefaults.standard.removeObject(forKey: defaultsKey)
}
private static func save(_ reports: [KeychainProvenanceReport]) {
guard let data = try? JSONEncoder().encode(reports) else { return }
UserDefaults.standard.set(data, forKey: defaultsKey)
}
}
// MARK: - Report text
enum KeychainProvenanceReportBuilder {
/// Builds the full plain-text report for the current device state.
///
/// - Parameters:
/// - label: free-form run label, e.g. "iPhone 15 — signed in as identity B".
/// - userRecordID: resolved asynchronously by the caller (network), `nil`
/// when unavailable.
static func build(label: String, userRecordID: String?) -> String {
let results = KeychainProvenanceProbe.queryAll()
var lines: [String] = []
lines.append("=== Yattee Keychain provenance experiment ===")
lines.append("Label: \(label.isEmpty ? "<unlabelled>" : label)")
lines.append("Captured: \(iso(Date()))")
lines.append("Platform: \(platformDescription)")
lines.append("")
lines.append("--- Identity ---")
lines.append("CloudKit entitlement: \(CloudKitAvailability.isAvailable ? "available" : "missing (sideload)")")
lines.append("ubiquityIdentityToken: \(CloudKitIdentity.ubiquityFingerprint.map { "present, fp=\($0)" } ?? "none — no Apple account signed in")")
lines.append("CloudKit user record: \(userRecordID ?? "unresolved")")
lines.append("")
lines.append("--- Keychain queries (service \(KeychainProvenanceProbe.service)) ---")
for result in results {
lines.append("")
lines.append("[\(result.match.label)]")
lines.append(" status: \(KeychainProvenanceProbe.describe(result.status)), \(result.items.count) item(s)")
for item in result.items {
lines.append(" • account=\(item.account)")
lines.append(" stored synchronizable: \(item.synchronizable.map(String.init(describing:)) ?? "absent")")
lines.append(" accessible: \(item.accessible ?? "absent")")
lines.append(" created: \(item.creationDate.map(iso) ?? "absent")")
lines.append(" modified: \(item.modificationDate.map(iso) ?? "absent")")
lines.append(" payload: \(item.payload ?? "<not utf8>")")
}
}
lines.append("")
lines.append("--- Discriminator check ---")
lines.append(contentsOf: discriminatorLines(results))
return lines.joined(separator: "\n")
}
/// Compares what the candidate discriminator matched against what Yattee's
/// current `SynchronizableAny` query matches — the difference is exactly
/// what auto-adoption would refuse to adopt.
private static func discriminatorLines(
_ results: [KeychainProvenanceProbe.QueryResult]
) -> [String] {
let strict = Set(results.first { $0.match == .synchronizableTrue }?.items.map(\.account) ?? [])
let any = Set(results.first { $0.match == .any }?.items.map(\.account) ?? [])
var lines: [String] = []
lines.append("matched by strict `== true`: \(format(strict))")
lines.append("matched by `Any` (today): \(format(any))")
lines.append("visible to Yattee but NOT provenance-backed: \(format(any.subtracting(strict)))")
return lines
}
private static func format(_ accounts: Set<String>) -> String {
accounts.isEmpty ? "none" : accounts.sorted().joined(separator: ", ")
}
// MARK: - Environment
private static var platformDescription: String {
let version = ProcessInfo.processInfo.operatingSystemVersionString
#if os(iOS)
return "iOS — \(UIDevice.current.model) — \(version)"
#elseif os(tvOS)
return "tvOS — \(UIDevice.current.model) — \(version)"
#elseif os(macOS)
return "macOS — \(version)"
#else
return version
#endif
}
private static func iso(_ date: Date) -> String {
date.formatted(.iso8601)
}
}
#endif