summaryrefslogtreecommitdiff
path: root/octosentry/KeychainTokenStore.swift
diff options
context:
space:
mode:
Diffstat (limited to 'octosentry/KeychainTokenStore.swift')
-rw-r--r--octosentry/KeychainTokenStore.swift73
1 files changed, 73 insertions, 0 deletions
diff --git a/octosentry/KeychainTokenStore.swift b/octosentry/KeychainTokenStore.swift
new file mode 100644
index 0000000..c48c9f6
--- /dev/null
+++ b/octosentry/KeychainTokenStore.swift
@@ -0,0 +1,73 @@
+//
+// KeychainTokenStore.swift
+// octosentry
+//
+// Stores the GitHub OAuth token in the app's own Keychain item. Not
+// synced to iCloud Keychain by default (spec §6) — deliberate given the
+// token's access scope. No keychain-access-groups entitlement needed:
+// that's only required to share an item across multiple apps/extensions,
+// not for an app reading/writing its own item.
+//
+
+import Foundation
+import Security
+
+nonisolated enum KeychainTokenStore {
+ private static let service = "net.cleberg.octosentry.github-token"
+ private static let account = "github-oauth-token"
+
+ static func save(_ token: String) throws {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ ]
+ SecItemDelete(query as CFDictionary)
+
+ var attributes = query
+ attributes[kSecValueData as String] = Data(token.utf8)
+ attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
+ attributes[kSecAttrSynchronizable as String] = false
+
+ let status = SecItemAdd(attributes as CFDictionary, nil)
+ guard status == errSecSuccess else {
+ throw KeychainError.unhandled(status)
+ }
+ }
+
+ static func load() -> String? {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne,
+ ]
+
+ var result: AnyObject?
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+ guard status == errSecSuccess, let data = result as? Data else { return nil }
+ return String(data: data, encoding: .utf8)
+ }
+
+ static func delete() {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ ]
+ SecItemDelete(query as CFDictionary)
+ }
+
+ enum KeychainError: Error, LocalizedError {
+ case unhandled(OSStatus)
+
+ var errorDescription: String? {
+ switch self {
+ case .unhandled(let status):
+ let message = SecCopyErrorMessageString(status, nil) as String? ?? "unknown"
+ return "Keychain error \(status): \(message)"
+ }
+ }
+ }
+}