-
Notifications
You must be signed in to change notification settings - Fork 26
/
SecureVaultManager.swift
388 lines (319 loc) · 19.3 KB
/
SecureVaultManager.swift
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
//
// SecureVaultManager.swift
// DuckDuckGo
//
// Copyright © 2021 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import os
public enum AutofillType {
case password
case card
case identity
}
public struct AutofillData {
public let identity: SecureVaultModels.Identity?
public let credentials: SecureVaultModels.WebsiteCredentials?
public let creditCard: SecureVaultModels.CreditCard?
public let automaticallySavedCredentials: Bool
}
public protocol SecureVaultManagerDelegate: SecureVaultErrorReporting {
func secureVaultManagerIsEnabledStatus(_: SecureVaultManager) -> Bool
func secureVaultManager(_: SecureVaultManager, promptUserToStoreAutofillData data: AutofillData)
func secureVaultManager(_: SecureVaultManager,
promptUserToAutofillCredentialsForDomain domain: String,
withAccounts accounts: [SecureVaultModels.WebsiteAccount],
withTrigger trigger: AutofillUserScript.GetTriggerType,
completionHandler: @escaping (SecureVaultModels.WebsiteAccount?) -> Void)
func secureVaultManagerShouldAutomaticallyUpdateCredentialsWithoutUsername(_: SecureVaultManager) -> Bool
func secureVaultManager(_: SecureVaultManager, didAutofill type: AutofillType, withObjectId objectId: Int64)
// swiftlint:disable:next identifier_name
func secureVaultManager(_: SecureVaultManager, didRequestAuthenticationWithCompletionHandler: @escaping (Bool) -> Void)
}
public class SecureVaultManager {
public weak var delegate: SecureVaultManagerDelegate?
private let vault: SecureVault?
public init(vault: SecureVault? = nil) {
self.vault = vault
}
}
// Later these catches should check if it is an auth error and call the delegate to ask for user authentication.
extension SecureVaultManager: AutofillSecureVaultDelegate {
public func autofillUserScript(_: AutofillUserScript,
didRequestAutoFillInitDataForDomain domain: String,
completionHandler: @escaping ([SecureVaultModels.WebsiteAccount],
[SecureVaultModels.Identity],
[SecureVaultModels.CreditCard]) -> Void) {
do {
guard let delegate = delegate, delegate.secureVaultManagerIsEnabledStatus(self) else {
completionHandler([], [], [])
return
}
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
let accounts = try vault.accountsFor(domain: domain)
let identities = try vault.identities()
let cards = try vault.creditCards()
completionHandler(accounts, identities, cards)
} catch {
os_log(.error, "Error requesting autofill init data: %{public}@", error.localizedDescription)
completionHandler([], [], [])
}
}
public func autofillUserScript(_: AutofillUserScript, didRequestPasswordManagerForDomain domain: String) {
// no-op at this point
}
/// Receives each of the types of data that the Autofill script has detected, and determines whether the user should be prompted to save them.
/// This involves checking each proposed object to determine whether it already exists in the store.
/// Currently, only one new type of data is presented to the user, but that decision is handled client-side so that it's easier to adapt in the future when multiple types are presented at once.
public func autofillUserScript(_: AutofillUserScript,
didRequestStoreDataForDomain domain: String,
data: AutofillUserScript.DetectedAutofillData) {
do {
let automaticallySavedCredentials = try storeOrUpdateAutogeneratedCredentials(domain: domain, autofillData: data)
if delegate?.secureVaultManagerShouldAutomaticallyUpdateCredentialsWithoutUsername(self) ?? false {
try updateExistingCredentialsWithoutUsernameWithSubmittedValues(domain: domain, autofillData: data)
}
let dataToPrompt = try existingEntries(for: domain, autofillData: data, automaticallySavedCredentials: automaticallySavedCredentials)
delegate?.secureVaultManager(self, promptUserToStoreAutofillData: dataToPrompt)
} catch {
os_log(.error, "Error storing data: %{public}@", error.localizedDescription)
}
}
public func autofillUserScript(_: AutofillUserScript,
didRequestAccountsForDomain domain: String,
completionHandler: @escaping ([SecureVaultModels.WebsiteAccount]) -> Void) {
do {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
completionHandler(try vault.accountsFor(domain: domain))
} catch {
os_log(.error, "Error requesting accounts: %{public}@", error.localizedDescription)
completionHandler([])
}
}
public func autofillUserScript(_: AutofillUserScript,
didRequestCredentialsForDomain domain: String,
subType: AutofillUserScript.GetAutofillDataSubType,
trigger: AutofillUserScript.GetTriggerType,
completionHandler: @escaping (SecureVaultModels.WebsiteCredentials?, RequestVaultCredentialsAction) -> Void) {
do {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
let accounts = try vault
.accountsFor(domain: domain)
.filter {
// don't show accounts without usernames if the user interacted with the 'username' field
if subType == .username && $0.username.isEmpty {
return false
}
return true
}
if accounts.count == 0 {
os_log(.debug, "Not showing the modal, no suitable accounts found")
completionHandler(nil, .none)
return
}
delegate?.secureVaultManager(self, promptUserToAutofillCredentialsForDomain: domain, withAccounts: accounts, withTrigger: trigger) { account in
guard let accountID = account?.id else {
completionHandler(nil, .none)
return
}
do {
let credentials = try vault.websiteCredentialsFor(accountId: accountID)
completionHandler(credentials, .fill)
} catch {
os_log(.error, "Error requesting credentials: %{public}@", error.localizedDescription)
completionHandler(nil, .none)
}
}
} catch {
os_log(.error, "Error requesting accounts: %{public}@", error.localizedDescription)
completionHandler(nil, .none)
}
}
public func autofillUserScript(_: AutofillUserScript,
didRequestCredentialsForAccount accountId: Int64,
completionHandler: @escaping (SecureVaultModels.WebsiteCredentials?) -> Void) {
do {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
completionHandler(try vault.websiteCredentialsFor(accountId: accountId))
delegate?.secureVaultManager(self, didAutofill: .password, withObjectId: accountId)
} catch {
os_log(.error, "Error requesting credentials: %{public}@", error.localizedDescription)
completionHandler(nil)
}
}
public func autofillUserScript(_: AutofillUserScript,
didRequestCreditCardWithId creditCardId: Int64,
completionHandler: @escaping (SecureVaultModels.CreditCard?) -> Void) {
do {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
let card = try vault.creditCardFor(id: creditCardId)
delegate?.secureVaultManager(self, didRequestAuthenticationWithCompletionHandler: { authenticated in
if authenticated {
completionHandler(card)
} else {
completionHandler(nil)
}
})
delegate?.secureVaultManager(self, didAutofill: .card, withObjectId: creditCardId)
} catch {
os_log(.error, "Error requesting credit card: %{public}@", error.localizedDescription)
completionHandler(nil)
}
}
public func autofillUserScript(_: AutofillUserScript,
didRequestIdentityWithId identityId: Int64,
completionHandler: @escaping (SecureVaultModels.Identity?) -> Void) {
do {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
completionHandler(try vault.identityFor(id: identityId))
delegate?.secureVaultManager(self, didAutofill: .identity, withObjectId: identityId)
} catch {
os_log(.error, "Error requesting identity: %{public}@", error.localizedDescription)
completionHandler(nil)
}
}
/// Stores autogenerated credentials sent by the AutofillUserScript, or updates an existing row in the database if credentials already exist.
/// The Secure Vault only stores one generated password for a domain, which is updated any time the user selects a new generated password.
func storeOrUpdateAutogeneratedCredentials(domain: String, autofillData: AutofillUserScript.DetectedAutofillData) throws -> Bool {
guard autofillData.hasAutogeneratedPassword,
let autogeneratedCredentials = autofillData.credentials,
!(autogeneratedCredentials.username?.isEmpty ?? true),
let passwordData = autogeneratedCredentials.password.data(using: .utf8) else {
os_log("Did not meet conditions for silently saving autogenerated credentials, returning early", log: .passwordManager)
return false
}
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
let accounts = try vault.accountsFor(domain: domain)
if accounts.contains(where: { account in account.username == autogeneratedCredentials.username }) {
os_log("Tried to automatically save credentials for which an account already exists, returning early", log: .passwordManager)
return false
}
// As a precaution, check whether an account exists with the matching generated password _and_ a non-nil username.
// If so, then the user must have already saved the generated credentials and set a username.
for account in accounts where !account.username.isEmpty {
if let accountID = account.id,
let credentialsForAccount = try vault.websiteCredentialsFor(accountId: accountID),
credentialsForAccount.password == passwordData,
account.username == autogeneratedCredentials.username ?? "" {
os_log("Tried to save autogenerated password but it already exists, returning early", log: .passwordManager)
return false
}
}
let existingAccount = accounts.first(where: { $0.username == "" })
var account = existingAccount ?? SecureVaultModels.WebsiteAccount(username: "", domain: domain)
account.title = "Saved Password (\(domain))"
let generatedPassword = SecureVaultModels.WebsiteCredentials(account: account, password: passwordData)
os_log("Saving autogenerated password", log: .passwordManager)
try vault.storeWebsiteCredentials(generatedPassword)
return true
}
/// If credentials are sent via the AutofillUserScript, and there exists a credential row with empty username and matching password, then this function will update that credential row with the username.
/// This can happen if the user saves a form with only a password when signing up for a service, then enters their own username and submits the form.
func updateExistingCredentialsWithoutUsernameWithSubmittedValues(domain: String, autofillData: AutofillUserScript.DetectedAutofillData) throws {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
let accounts = try vault.accountsFor(domain: domain)
guard let autofillCredentials = autofillData.credentials,
let autofillCredentialsUsername = autofillCredentials.username,
var existingAccount = accounts.first(where: { $0.username == "" }),
let existingAccountID = existingAccount.id else {
return
}
if accounts.contains(where: { $0.username == autofillCredentials.username }) {
os_log("ERROR: Tried to save generated credentials with an existing username, prompt the user to update instead.", log: .passwordManager)
return
}
let existingCredentials = try vault.websiteCredentialsFor(accountId: existingAccountID)
guard let existingPasswordData = existingCredentials?.password,
let autofillPasswordData = autofillCredentials.password.data(using: .utf8) else {
return
}
// If true, then the existing generated password matches the credentials sent by the script, so update and save the difference.
if existingPasswordData == autofillPasswordData {
os_log("Found matching autogenerated credentials in Secure Vault, updating with username", log: .passwordManager)
existingAccount.username = autofillCredentialsUsername
existingAccount.title = nil // Remove the "Saved Password" title so that the UI uses the default title format
let credentialsToSave = SecureVaultModels.WebsiteCredentials(account: existingAccount, password: autofillPasswordData)
try vault.storeWebsiteCredentials(credentialsToSave)
}
}
func existingEntries(for domain: String,
autofillData: AutofillUserScript.DetectedAutofillData,
automaticallySavedCredentials: Bool) throws -> AutofillData {
let vault = try self.vault ?? SecureVaultFactory.default.makeVault(errorReporter: self.delegate)
let proposedIdentity = try existingIdentity(with: autofillData, vault: vault)
let proposedCredentials = try existingCredentials(with: autofillData,
domain: domain,
automaticallySavedCredentials: automaticallySavedCredentials,
vault: vault)
let proposedCard = try existingPaymentMethod(with: autofillData, vault: vault)
return AutofillData(identity: proposedIdentity,
credentials: proposedCredentials,
creditCard: proposedCard,
automaticallySavedCredentials: automaticallySavedCredentials)
}
private func existingIdentity(with autofillData: AutofillUserScript.DetectedAutofillData,
vault: SecureVault) throws -> SecureVaultModels.Identity? {
if let identity = autofillData.identity, try vault.existingIdentityForAutofill(matching: identity) == nil {
os_log("Got new identity/address to save", log: .passwordManager)
return identity
} else {
os_log("No new identity/address found, avoid prompting user", log: .passwordManager)
return nil
}
}
private func existingCredentials(with autofillData: AutofillUserScript.DetectedAutofillData,
domain: String,
automaticallySavedCredentials: Bool,
vault: SecureVault) throws -> SecureVaultModels.WebsiteCredentials? {
if let credentials = autofillData.credentials, let passwordData = credentials.password.data(using: .utf8) {
if let account = try vault
.accountsFor(domain: domain)
.first(where: { $0.username == credentials.username ?? "" }) {
if let existingAccountID = account.id,
let existingCredentials = try vault.websiteCredentialsFor(accountId: existingAccountID),
existingCredentials.password == passwordData {
if automaticallySavedCredentials {
os_log("Found duplicate credentials which were just saved, notifying user", log: .passwordManager)
return SecureVaultModels.WebsiteCredentials(account: account, password: passwordData)
} else {
os_log("Found duplicate credentials which were previously saved, avoid notifying user", log: .passwordManager)
return nil
}
} else {
os_log("Found existing credentials to update", log: .passwordManager)
return SecureVaultModels.WebsiteCredentials(account: account, password: passwordData)
}
} else {
os_log("Received new credentials to save", log: .passwordManager)
let account = SecureVaultModels.WebsiteAccount(username: credentials.username ?? "", domain: domain)
return SecureVaultModels.WebsiteCredentials(account: account, password: passwordData)
}
} else {
os_log("No new credentials found, avoid prompting user", log: .passwordManager)
}
return nil
}
private func existingPaymentMethod(with autofillData: AutofillUserScript.DetectedAutofillData,
vault: SecureVault) throws -> SecureVaultModels.CreditCard? {
if let card = autofillData.creditCard, try vault.existingCardForAutofill(matching: card) == nil {
os_log("Got new payment method to save", log: .passwordManager)
return card
} else {
os_log("No new payment method found, avoid prompting user", log: .passwordManager)
return nil
}
}
}