Allow after first unlock accessibility (#871)

* Allow after first unlock

* Fix tests

* Fix tests
This commit is contained in:
Max Goedjen authored and GitHub committed 2026-11-17 20:28:30 -08:00
1 parent 0d1ca5e744
commit c0562ba50a
14 files changed
+50 -13

No files matched your search

@@ -6720,6 +6720,28 @@
} }
} }
}, },
"create_secret_allow_while_locked_description" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Consider enabling this if you run scripts while your Mac is locked."
}
}
}
},
"create_secret_allow_while_locked_label" : {
"extractionState" : "manual",
"localizations" : {
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Allow While Locked"
}
}
}
},
"create_secret_biometry_current_warning" : { "create_secret_biometry_current_warning" : {
"extractionState" : "manual", "extractionState" : "manual",
"localizations" : { "localizations" : {
@@ -39,7 +39,8 @@ import SecretKit
kSecAttrService: Constants.keyTag, kSecAttrService: Constants.keyTag,
kSecAttrAccount: certificate.id, kSecAttrAccount: certificate.id,
kSecUseDataProtectionKeychain: true, kSecUseDataProtectionKeychain: true,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, // Note: Previous versions used kSecAttrAccessibleWhenUnlockedThisDeviceOnly
kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
kSecValueData: certificate.rawData, kSecValueData: certificate.rawData,
kSecAttrGeneric: attributes kSecAttrGeneric: attributes
]) ])
@@ -8,6 +8,9 @@ public struct Attributes: Sendable, Codable, Hashable {
/// The authentication requirements for the key. This is simply a description of the option recorded at creation – modifying it doers not modify the key's authentication requirements. /// The authentication requirements for the key. This is simply a description of the option recorded at creation – modifying it doers not modify the key's authentication requirements.
public let authentication: AuthenticationRequirement public let authentication: AuthenticationRequirement
/// Whether the key can be used while unlocked. This is only applicable to keys with `notRequired` authentication requirements.
public let allowWhileLocked: Bool
/// The string appended to the end of the SSH Public Key. /// The string appended to the end of the SSH Public Key.
/// If nil, a default value will be used. /// If nil, a default value will be used.
public var publicKeyAttribution: String? public var publicKeyAttribution: String?
@@ -15,10 +18,12 @@ public struct Attributes: Sendable, Codable, Hashable {
public init( public init(
keyType: KeyType, keyType: KeyType,
authentication: AuthenticationRequirement, authentication: AuthenticationRequirement,
allowWhileLocked: Bool,
publicKeyAttribution: String? = nil publicKeyAttribution: String? = nil
) { ) {
self.keyType = keyType self.keyType = keyType
self.authentication = authentication self.authentication = authentication
self.allowWhileLocked = allowWhileLocked
self.publicKeyAttribution = publicKeyAttribution self.publicKeyAttribution = publicKeyAttribution
} }
@@ -47,7 +47,7 @@ extension SecureEnclave {
.contains("DeviceOwnerAuthentication") ? .presenceRequired : .unknown .contains("DeviceOwnerAuthentication") ? .presenceRequired : .unknown
do { do {
let parsed = try CryptoKit.SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: tokenObjectID) let parsed = try CryptoKit.SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: tokenObjectID)
let secret = Secret(id: UUID().uuidString, name: name, publicKey: parsed.publicKey.x963Representation, attributes: Attributes(keyType: .init(algorithm: .ecdsa, size: 256), authentication: auth)) let secret = Secret(id: UUID().uuidString, name: name, publicKey: parsed.publicKey.x963Representation, attributes: Attributes(keyType: .init(algorithm: .ecdsa, size: 256), authentication: auth, allowWhileLocked: false))
guard !migratedPublicKeys.contains(parsed.publicKey.x963Representation) else { guard !migratedPublicKeys.contains(parsed.publicKey.x963Representation) else {
logger.log("Skipping \(name), public key already present. Marking as migrated.") logger.log("Skipping \(name), public key already present. Marking as migrated.")
markMigrated(secret: secret, oldID: id) markMigrated(secret: secret, oldID: id)
@@ -244,17 +244,17 @@ extension SecureEnclave.Store {
/// - Note: Despite the name, the "Data" of the key is _not_ actual key material. This is an opaque data representation that the SEP can manipulate. /// - Note: Despite the name, the "Data" of the key is _not_ actual key material. This is an opaque data representation that the SEP can manipulate.
@discardableResult @discardableResult
func saveKey(_ key: Data, name: String, attributes: Attributes) throws -> String { func saveKey(_ key: Data, name: String, attributes: Attributes) throws -> String {
let attributes = try JSONEncoder().encode(attributes) let encodedAttributes = try JSONEncoder().encode(attributes)
let id = UUID().uuidString let id = UUID().uuidString
let keychainAttributes = KeychainDictionary([ let keychainAttributes = KeychainDictionary([
kSecClass: Constants.keyClass, kSecClass: Constants.keyClass,
kSecAttrService: Constants.keyTag, kSecAttrService: Constants.keyTag,
kSecUseDataProtectionKeychain: true, kSecUseDataProtectionKeychain: true,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAttrAccessible: attributes.allowWhileLocked ? kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly : kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
kSecAttrAccount: id, kSecAttrAccount: id,
kSecValueData: key, kSecValueData: key,
kSecAttrLabel: name, kSecAttrLabel: name,
kSecAttrGeneric: attributes kSecAttrGeneric: encodedAttributes
]) ])
let status = SecItemAdd(keychainAttributes, nil) let status = SecItemAdd(keychainAttributes, nil)
if status != errSecSuccess { if status != errSecSuccess {
@@ -40,7 +40,7 @@ import OSLog
kSecAttrService: Constants.keyTag, kSecAttrService: Constants.keyTag,
kSecAttrAccount: String(describing: SettingsKeyType.self), kSecAttrAccount: String(describing: SettingsKeyType.self),
kSecUseDataProtectionKeychain: true, kSecUseDataProtectionKeychain: true,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
kSecValueData: data, kSecValueData: data,
]) ])
let status = SecItemAdd(keychainAttributes, nil) let status = SecItemAdd(keychainAttributes, nil)
@@ -156,7 +156,7 @@ extension SmartCard.Store {
let publicKeySecRef = SecKeyCopyPublicKey(publicKeyRef)! let publicKeySecRef = SecKeyCopyPublicKey(publicKeyRef)!
let publicKeyAttributes = SecKeyCopyAttributes(publicKeySecRef) as! [CFString: Any] let publicKeyAttributes = SecKeyCopyAttributes(publicKeySecRef) as! [CFString: Any]
let publicKey = publicKeyAttributes[kSecValueData] as! Data let publicKey = publicKeyAttributes[kSecValueData] as! Data
let attributes = Attributes(keyType: KeyType(secAttr: algorithmSecAttr, size: keySize)!, authentication: .presenceRequired) let attributes = Attributes(keyType: KeyType(secAttr: algorithmSecAttr, size: keySize)!, authentication: .presenceRequired, allowWhileLocked: false)
let secret = SmartCard.Secret(id: tokenID, name: name, publicKey: publicKey, attributes: attributes) let secret = SmartCard.Secret(id: tokenID, name: name, publicKey: publicKey, attributes: attributes)
guard signatureAlgorithm(for: secret) != nil else { return nil } guard signatureAlgorithm(for: secret) != nil else { return nil }
return secret return secret
@@ -46,8 +46,8 @@ import SSHProtocolKit
extension OpenSSHPublicKeyWriterTests { extension OpenSSHPublicKeyWriterTests {
enum Constants { enum Constants {
static let ecdsa256Secret = TestSecret(id: Data(), name: "Test Key (ECDSA 256)", publicKey: Data(base64Encoded: "BOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")!, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 256), authentication: .notRequired, publicKeyAttribution: "test@example.com")) static let ecdsa256Secret = TestSecret(id: Data(), name: "Test Key (ECDSA 256)", publicKey: Data(base64Encoded: "BOVEjgAA5PHqRgwykjN5qM21uWCHFSY/Sqo5gkHAkn+e1MMQKHOLga7ucB9b3mif33MBid59GRK9GEPVlMiSQwo=")!, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 256), authentication: .notRequired, allowWhileLocked: true, publicKeyAttribution: "test@example.com"))
static let ecdsa384Secret = TestSecret(id: Data(), name: "Test Key (ECDSA 384)", publicKey: Data(base64Encoded: "BG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")!, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 384), authentication: .notRequired, publicKeyAttribution: "test@example.com")) static let ecdsa384Secret = TestSecret(id: Data(), name: "Test Key (ECDSA 384)", publicKey: Data(base64Encoded: "BG2MNc/C5OTHFE2tBvbZCVcpOGa8vBMquiTLkH4lwkeqOPxhi+PyYUfQZMTRJNPiTyWPoMBqNiCIFRVv60yPN/AHufHaOgbdTP42EgMlMMImkAjYUEv9DESHTVIs2PW1yQ==")!, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 384), authentication: .notRequired, allowWhileLocked: true, publicKeyAttribution: "test@example.com"))
} }
@@ -51,7 +51,7 @@ private extension OpenSSHSignatureWriterTests {
publicKey: Data(repeating: 0x01, count: 65), publicKey: Data(repeating: 0x01, count: 65),
attributes: Attributes( attributes: Attributes(
keyType: KeyType(algorithm: .ecdsa, size: 256), keyType: KeyType(algorithm: .ecdsa, size: 256),
authentication: .notRequired, authentication: .notRequired, allowWhileLocked: true,
publicKeyAttribution: "test@example.com" publicKeyAttribution: "test@example.com"
) )
) )
@@ -34,7 +34,7 @@ public struct TestSecret: Secret {
init(authenticationRequirement: AuthenticationRequirement, testEvaluationResult: Bool, approval: ApprovalMode = .manual) { init(authenticationRequirement: AuthenticationRequirement, testEvaluationResult: Bool, approval: ApprovalMode = .manual) {
self.canceled = false self.canceled = false
self.testEvaluationResult = testEvaluationResult self.testEvaluationResult = testEvaluationResult
self.secret = AnySecret(TestSecret(attributes: .init(keyType: .ecdsa256, authentication: authenticationRequirement))) self.secret = AnySecret(TestSecret(attributes: .init(keyType: .ecdsa256, authentication: authenticationRequirement, allowWhileLocked: false)))
self.approval = approval self.approval = approval
} }
@@ -77,7 +77,7 @@ extension Stub {
let privateKey: Data let privateKey: Data
init(keySize: Int, publicKey: Data, privateKey: Data) { init(keySize: Int, publicKey: Data, privateKey: Data) {
self.attributes = Attributes(keyType: .init(algorithm: .ecdsa, size: keySize), authentication: .notRequired, publicKeyAttribution: "ecdsa-\(keySize)@example.com") self.attributes = Attributes(keyType: .init(algorithm: .ecdsa, size: keySize), authentication: .notRequired, allowWhileLocked: false, publicKeyAttribution: "ecdsa-\(keySize)@example.com")
self.publicKey = publicKey self.publicKey = publicKey
self.privateKey = privateKey self.privateKey = privateKey
} }
@@ -9,7 +9,7 @@ import Testing
@Test func eraser() { @Test func eraser() {
let data = Data(UUID().uuidString.utf8) let data = Data(UUID().uuidString.utf8)
let secret = SmartCard.Secret(id: data, name: "Name", publicKey: data, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 256), authentication: .notRequired)) let secret = SmartCard.Secret(id: data, name: "Name", publicKey: data, attributes: Attributes(keyType: KeyType(algorithm: .ecdsa, size: 256), authentication: .notRequired, allowWhileLocked: true))
let erased = AnySecret(secret) let erased = AnySecret(secret)
#expect(erased.id == secret.id as AnyHashable) #expect(erased.id == secret.id as AnyHashable)
#expect(erased.name == secret.name) #expect(erased.name == secret.name)
@@ -15,6 +15,7 @@ extension Preview {
Attributes( Attributes(
keyType: .init(algorithm: .ecdsa, size: 256), keyType: .init(algorithm: .ecdsa, size: 256),
authentication: .presenceRequired, authentication: .presenceRequired,
allowWhileLocked: true,
) )
} }
} }
@@ -10,6 +10,7 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
@State private var name = "" @State private var name = ""
@State private var keyAttribution = "" @State private var keyAttribution = ""
@State private var authenticationRequirement: AuthenticationRequirement = .presenceRequired @State private var authenticationRequirement: AuthenticationRequirement = .presenceRequired
@State private var allowWhileLocked = false
@State private var keyType: KeyType? @State private var keyType: KeyType?
@State var advanced = false @State var advanced = false
@State var errorText: String? @State var errorText: String?
@@ -73,6 +74,12 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
} }
if advanced { if advanced {
Section { Section {
Toggle(isOn: $allowWhileLocked) {
Text(.createSecretAllowWhileLockedLabel)
Text(.createSecretAllowWhileLockedDescription)
.font(.subheadline)
.foregroundStyle(.secondary)
}
VStack { VStack {
Picker(.createSecretKeyTypeLabel, selection: $keyType) { Picker(.createSecretKeyTypeLabel, selection: $keyType) {
ForEach(store.supportedKeyTypes.available, id: \.self) { option in ForEach(store.supportedKeyTypes.available, id: \.self) { option in
@@ -146,6 +153,7 @@ struct CreateSecretView<StoreType: SecretStoreModifiable>: View {
attributes: .init( attributes: .init(
keyType: keyType!, keyType: keyType!,
authentication: authenticationRequirement, authentication: authenticationRequirement,
allowWhileLocked: allowWhileLocked,
publicKeyAttribution: attribution publicKeyAttribution: attribution
) )
) )