forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeychain.swift
More file actions
210 lines (175 loc) · 5.98 KB
/
Keychain.swift
File metadata and controls
210 lines (175 loc) · 5.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import Configs
import Foundation
import Preferences
import Security
public protocol KeychainType {
func getAll() throws -> [String: String]
func update(_ value: String, key: String) throws
func get(_ key: String) throws -> String?
func remove(_ key: String) throws
}
public final class FakeKeyChain: KeychainType {
var values: [String: String] = [:]
public init() {}
public func getAll() throws -> [String: String] {
values
}
public func update(_ value: String, key: String) throws {
values[key] = value
}
public func get(_ key: String) throws -> String? {
values[key]
}
public func remove(_ key: String) throws {
values[key] = nil
}
}
public final class UserDefaultsBaseAPIKeychain: KeychainType {
let defaults = UserDefaults.shared
let scope: String
var key: String {
"UserDefaultsBaseAPIKeychain-\(scope)"
}
init(scope: String) {
self.scope = scope
}
public func getAll() throws -> [String : String] {
defaults.dictionary(forKey: key) as? [String: String] ?? [:]
}
public func update(_ value: String, key: String) throws {
var dict = try getAll()
dict[key] = value
defaults.set(dict, forKey: self.key)
}
public func get(_ key: String) throws -> String? {
try getAll()[key]
}
public func remove(_ key: String) throws {
var dict = try getAll()
dict[key] = nil
defaults.set(dict, forKey: self.key)
}
}
public struct Keychain: KeychainType {
let service = keychainService
let accessGroup = keychainAccessGroup
let scope: String
public static var apiKey: KeychainType {
if UserDefaults.shared.value(for: \.useUserDefaultsBaseAPIKeychain) {
return UserDefaultsBaseAPIKeychain(scope: "apiKey")
}
return Keychain(scope: "apiKey")
}
public enum Error: Swift.Error {
case failedToDeleteFromKeyChain
case failedToUpdateOrSetItem
}
public init(scope: String = "") {
self.scope = scope
}
func query(_ key: String) -> [String: Any] {
let key = scopeKey(key)
return [
kSecClass as String: kSecClassGenericPassword as String,
kSecAttrService as String: service,
kSecAttrAccessGroup as String: accessGroup,
kSecAttrAccount as String: key,
kSecUseDataProtectionKeychain as String: true,
]
}
func set(_ value: String, key: String) throws {
let query = query(key).merging([
kSecValueData as String: value.data(using: .utf8) ?? Data(),
], uniquingKeysWith: { _, b in b })
let result = SecItemAdd(query as CFDictionary, nil)
switch result {
case noErr:
return
default:
throw Error.failedToUpdateOrSetItem
}
}
func scopeKey(_ key: String) -> String {
if scope.isEmpty {
return key
}
return "\(scope)::\(key)"
}
func escapeScope(_ key: String) -> String? {
if scope.isEmpty {
return key
}
if !key.hasPrefix("\(scope)::") { return nil }
return key.replacingOccurrences(of: "\(scope)::", with: "")
}
public func getAll() throws -> [String: String] {
let query = [
kSecClass as String: kSecClassGenericPassword as String,
kSecAttrService as String: service,
kSecAttrAccessGroup as String: accessGroup,
kSecReturnAttributes as String: true,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitAll,
] as [String: Any]
var result: AnyObject?
if SecItemCopyMatching(query as CFDictionary, &result) == noErr {
guard let items = result as? [[String: Any]] else {
return [:]
}
var dict = [String: String]()
for item in items {
guard let key = item[kSecAttrAccount as String] as? String,
let escapedKey = escapeScope(key)
else { continue }
guard let valueData = item[kSecValueData as String] as? Data,
let value = String(data: valueData, encoding: .utf8)
else { continue }
dict[escapedKey] = value
}
return dict
}
return [:]
}
public func update(_ value: String, key: String) throws {
let query = query(key).merging([
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnData as String: true,
], uniquingKeysWith: { _, b in b })
let attributes: [String: Any] =
[kSecValueData as String: value.data(using: .utf8) ?? Data()]
let result = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
switch result {
case noErr:
return
case errSecItemNotFound:
try set(value, key: key)
default:
throw Error.failedToUpdateOrSetItem
}
}
public func get(_ key: String) throws -> String? {
let query = query(key).merging([
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnData as String: true,
kSecReturnAttributes as String: true,
], uniquingKeysWith: { _, b in b })
var item: CFTypeRef?
if SecItemCopyMatching(query as CFDictionary, &item) == noErr {
if let existingItem = item as? [String: Any],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: .utf8)
{
return password
}
return nil
} else {
return nil
}
}
public func remove(_ key: String) throws {
if SecItemDelete(query(key) as CFDictionary) == noErr {
return
}
throw Error.failedToDeleteFromKeyChain
}
}