Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Persistence.swift

352 lines12.1 KB

1import Foundation
2import Security
3​
4public protocol CredentialStore: Sendable {
5 func credential(for environmentID: String) async throws -> EnvironmentCredential?
6 func setCredential(_ credential: EnvironmentCredential, for environmentID: String) async throws
7 func swapCredential(
8 _ credential: EnvironmentCredential,
9 for environmentID: String
10 ) async throws -> EnvironmentCredential?
11 func replaceCredential(
12 _ credential: EnvironmentCredential,
13 ifMatching expected: EnvironmentCredential?,
14 for environmentID: String
15 ) async throws -> Bool
16 func removeCredential(for environmentID: String) async throws
17 func removeCredential(
18 ifMatching expected: EnvironmentCredential,
19 for environmentID: String
20 ) async throws -> Bool
22​
23protocol KeychainCredentialBackend: Sendable {
24 func credential(for environmentID: String) throws -> EnvironmentCredential?
25 func setCredential(_ credential: EnvironmentCredential, for environmentID: String) throws
26 func removeCredential(for environmentID: String) throws
28​
29public enum CredentialStoreError: LocalizedError, Sendable {
30 case keychain(OSStatus)
31 case invalidData
32​
33 public var errorDescription: String? {
34 switch self {
35 case let .keychain(status):
36 SecCopyErrorMessageString(status, nil) as String? ?? "Keychain error \(status)."
37 case .invalidData:
38 "The saved environment credential is invalid."
39 }
40 }
42​
43/// Access tokens are deliberately isolated from the environment catalog so
44/// catalog exports and backups never contain authentication material.
45public actor KeychainCredentialStore: CredentialStore {
46 private static let keychainLock = NSLock()
47 private let service: String
48 private let accessibility: CFString
49 private let backend: (any KeychainCredentialBackend)?
50​
51 public init(
52 service: String = "codes.t3.swift-ios.environment-credentials",
53 accessibility: CFString = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
54 ) {
55 self.service = service
56 self.accessibility = accessibility
57 backend = nil
58 }
59​
60 init(
61 service: String,
62 backend: any KeychainCredentialBackend,
63 accessibility: CFString = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
64 ) {
65 self.service = service
66 self.accessibility = accessibility
67 self.backend = backend
68 }
69​
70 public func credential(for environmentID: String) throws -> EnvironmentCredential? {
71 try Self.keychainLock.withLock {
72 try readCredential(for: environmentID)
73 }
74 }
75​
76 public func setCredential(
77 _ credential: EnvironmentCredential,
78 for environmentID: String
79 ) throws {
80 try Self.keychainLock.withLock {
81 try writeCredential(credential, for: environmentID)
82 }
83 }
84​
85 public func removeCredential(for environmentID: String) throws {
86 try Self.keychainLock.withLock {
87 try deleteCredential(for: environmentID)
88 }
89 }
90​
91 public func swapCredential(
92 _ credential: EnvironmentCredential,
93 for environmentID: String
94 ) throws -> EnvironmentCredential? {
95 try Self.keychainLock.withLock {
96 let previousCredential = try readCredential(for: environmentID)
97 try writeCredential(credential, for: environmentID)
98 return previousCredential
99 }
100 }
101​
102 public func replaceCredential(
103 _ credential: EnvironmentCredential,
104 ifMatching expected: EnvironmentCredential?,
105 for environmentID: String
106 ) throws -> Bool {
107 try Self.keychainLock.withLock {
108 guard try readCredential(for: environmentID) == expected else { return false }
109 try writeCredential(credential, for: environmentID)
110 return true
111 }
112 }
113​
114 public func removeCredential(
115 ifMatching expected: EnvironmentCredential,
116 for environmentID: String
117 ) throws -> Bool {
118 try Self.keychainLock.withLock {
119 guard try readCredential(for: environmentID) == expected else { return false }
120 try deleteCredential(for: environmentID)
121 return true
122 }
123 }
124​
125 private func readCredential(for environmentID: String) throws -> EnvironmentCredential? {
126 if let backend {
127 return try backend.credential(for: environmentID)
128 }
129 let query: [String: Any] = [
130 kSecClass as String: kSecClassGenericPassword,
131 kSecAttrService as String: service,
132 kSecAttrAccount as String: environmentID,
133 kSecReturnData as String: true,
134 kSecMatchLimit as String: kSecMatchLimitOne,
135 ]
136 var item: CFTypeRef?
137 let status = SecItemCopyMatching(query as CFDictionary, &item)
138 if status == errSecItemNotFound { return nil }
139 guard status == errSecSuccess else { throw CredentialStoreError.keychain(status) }
140 guard let data = item as? Data else { throw CredentialStoreError.invalidData }
141 do {
142 return try JSONDecoder.t3.decode(EnvironmentCredential.self, from: data)
143 } catch {
144 throw CredentialStoreError.invalidData
145 }
146 }
147​
148 private func writeCredential(
149 _ credential: EnvironmentCredential,
150 for environmentID: String
151 ) throws {
152 if let backend {
153 try backend.setCredential(credential, for: environmentID)
154 return
155 }
156 let data = try JSONEncoder.t3.encode(credential)
157 let lookup: [String: Any] = [
158 kSecClass as String: kSecClassGenericPassword,
159 kSecAttrService as String: service,
160 kSecAttrAccount as String: environmentID,
161 ]
162 let attributes: [String: Any] = [
163 kSecValueData as String: data,
164 kSecAttrAccessible as String: accessibility,
165 ]
166 let updateStatus = SecItemUpdate(lookup as CFDictionary, attributes as CFDictionary)
167 if updateStatus == errSecItemNotFound {
168 var insertion = lookup
169 attributes.forEach { insertion[$0.key] = $0.value }
170 let status = SecItemAdd(insertion as CFDictionary, nil)
171 guard status == errSecSuccess else { throw CredentialStoreError.keychain(status) }
172 } else if updateStatus != errSecSuccess {
173 throw CredentialStoreError.keychain(updateStatus)
174 }
175 }
176​
177 private func deleteCredential(for environmentID: String) throws {
178 if let backend {
179 try backend.removeCredential(for: environmentID)
180 return
181 }
182 let query: [String: Any] = [
183 kSecClass as String: kSecClassGenericPassword,
184 kSecAttrService as String: service,
185 kSecAttrAccount as String: environmentID,
186 ]
187 let status = SecItemDelete(query as CFDictionary)
188 guard status == errSecSuccess || status == errSecItemNotFound else {
189 throw CredentialStoreError.keychain(status)
190 }
191 }
193​
194public actor InMemoryCredentialStore: CredentialStore {
195 private var credentials: [String: EnvironmentCredential]
196​
197 public init(credentials: [String: EnvironmentCredential] = [:]) {
198 self.credentials = credentials
199 }
200​
201 public func credential(for environmentID: String) -> EnvironmentCredential? {
202 credentials[environmentID]
203 }
204​
205 public func setCredential(
206 _ credential: EnvironmentCredential,
207 for environmentID: String
208 ) {
209 credentials[environmentID] = credential
210 }
211​
212 public func removeCredential(for environmentID: String) {
213 credentials.removeValue(forKey: environmentID)
214 }
215​
216 public func swapCredential(
217 _ credential: EnvironmentCredential,
218 for environmentID: String
219 ) -> EnvironmentCredential? {
220 credentials.updateValue(credential, forKey: environmentID)
221 }
222​
223 public func replaceCredential(
224 _ credential: EnvironmentCredential,
225 ifMatching expected: EnvironmentCredential?,
226 for environmentID: String
227 ) -> Bool {
228 guard credentials[environmentID] == expected else { return false }
229 credentials[environmentID] = credential
230 return true
231 }
232​
233 public func removeCredential(
234 ifMatching expected: EnvironmentCredential,
235 for environmentID: String
236 ) -> Bool {
237 guard credentials[environmentID] == expected else { return false }
238 credentials.removeValue(forKey: environmentID)
239 return true
240 }
242​
243public actor EnvironmentStore {
244 private struct Document: Codable {
245 let version: Int
246 var environments: [Environment]
247 var activeEnvironmentID: String?
248 }
249​
250 public let fileURL: URL
251​
252 /// Snapshot publishes read the catalog several times a second, so the
253 /// decoded document is cached and invalidated by writes on this actor.
254 private var cached: Document?
255​
256 public init(fileURL: URL? = nil) {
257 if let fileURL {
258 self.fileURL = fileURL
259 } else {
260 let root = FileManager.default.urls(
261 for: .applicationSupportDirectory,
262 in: .userDomainMask
263 ).first!
264 self.fileURL = root
265 .appendingPathComponent("T3CodeSwift", isDirectory: true)
266 .appendingPathComponent("environments.json", isDirectory: false)
267 }
268 }
269​
270 public func load() throws -> [Environment] {
271 try loadDocument().environments
272 }
273​
274 public func activeEnvironmentID() throws -> String? {
275 try loadDocument().activeEnvironmentID
276 }
277​
278 public func setActiveEnvironment(id: String?) throws {
279 var document = try loadDocument()
280 document.activeEnvironmentID = id
281 try save(document)
282 }
283​
284 @discardableResult
285 public func setEnabled(id: String, enabled: Bool) throws -> [Environment] {
286 var document = try loadDocument()
287 guard let index = document.environments.firstIndex(where: { $0.id == id }) else {
288 return document.environments
289 }
290 document.environments[index].isEnabled = enabled
291 if !enabled, document.activeEnvironmentID == id {
292 document.activeEnvironmentID = document.environments.first {
293 $0.isEnabled && $0.id != id
294 }?.id
295 }
296 try save(document)
297 return document.environments
298 }
299​
300 public func save(_ environments: [Environment]) throws {
301 try FileManager.default.createDirectory(
302 at: fileURL.deletingLastPathComponent(),
303 withIntermediateDirectories: true
304 )
305 var document = try loadDocument()
306 document.environments = environments
307 try save(document)
308 }
309​
310 @discardableResult
311 public func upsert(_ environment: Environment) throws -> [Environment] {
312 var environments = try load()
313 if let index = environments.firstIndex(where: { $0.id == environment.id }) {
314 environments[index] = environment
315 } else {
316 environments.append(environment)
317 }
318 try save(environments)
319 return environments
320 }
321​
322 @discardableResult
323 public func remove(id: String) throws -> [Environment] {
324 var document = try loadDocument()
325 document.environments.removeAll { $0.id == id }
326 if document.activeEnvironmentID == id {
327 document.activeEnvironmentID = document.environments.first(where: \.isEnabled)?.id
328 }
329 try save(document)
330 return document.environments
331 }
332​
333 private func loadDocument() throws -> Document {
334 if let cached { return cached }
335 guard FileManager.default.fileExists(atPath: fileURL.path) else {
336 return Document(version: 1, environments: [], activeEnvironmentID: nil)
337 }
338 let data = try Data(contentsOf: fileURL)
339 let document = try JSONDecoder.t3.decode(Document.self, from: data)
340 cached = document
341 return document
342 }
343​
344 private func save(_ document: Document) throws {
345 try FileManager.default.createDirectory(
346 at: fileURL.deletingLastPathComponent(),
347 withIntermediateDirectories: true
348 )
349 try JSONEncoder.t3.encode(document).write(to: fileURL, options: .atomic)
350 cached = document
351 }