This repository was archived by the owner on Feb 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathPasswordManagerCoordinator.swift
332 lines (273 loc) · 11.1 KB
/
PasswordManagerCoordinator.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
//
// PasswordManagerCoordinator.swift
//
// Copyright © 2022 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 BrowserServicesKit
import Combine
import Common
import PixelKit
import os.log
protocol PasswordManagerCoordinating: BrowserServicesKit.PasswordManager {
var displayName: String { get }
func reportPasswordAutofill()
func reportPasswordSave()
}
// Encapsulation of third party password managers
final class PasswordManagerCoordinator: PasswordManagerCoordinating {
static let shared = PasswordManagerCoordinator()
enum PasswordManagerCoordinatorError: Error {
case makingOfUrlFailed
}
let bitwardenManagement: BWManagement = BWManager.shared
var isEnabled: Bool {
return bitwardenManagement.status != .disabled
}
var name: String {
return "bitwarden"
}
var displayName: String {
return "Bitwarden"
}
var username: String? {
if case let .connected(vault: vault) = bitwardenManagement.status {
return vault.email
}
return nil
}
var isLocked: Bool {
switch bitwardenManagement.status {
case .connected(vault: let vault): return vault.status == .locked
case .disabled: return false
default: return true
}
}
var activeVaultEmail: String? {
switch bitwardenManagement.status {
case .connected(vault: let vault): return vault.email
default: return nil
}
}
var statusCancellable: AnyCancellable?
#if !APPSTORE
func setEnabled(_ enabled: Bool) {
if enabled {
if !bitwardenManagement.status.isConnected {
bitwardenManagement.initCommunication()
}
} else {
BWManager.shared.cancelCommunication()
}
}
func askToUnlock(completionHandler: @escaping () -> Void) {
switch bitwardenManagement.status {
case .disabled, .notInstalled, .oldVersion, .incompatible, .missingHandshake, .handshakeNotApproved, .error, .accessToContainersNotApproved:
Task {
await WindowControllersManager.shared.showPreferencesTab(withSelectedPane: .autofill)
}
return
default:
break
}
bitwardenManagement.openBitwarden()
statusCancellable = bitwardenManagement.statusPublisher
.receive(on: DispatchQueue.main)
.removeDuplicates()
.sink { [weak self] status in
guard let self = self else {
self?.statusCancellable?.cancel()
return
}
if case let .connected(vault: vault) = status,
vault.status == .unlocked {
self.statusCancellable?.cancel()
self.statusCancellable = nil
completionHandler()
}
}
}
func openPasswordManager() {
bitwardenManagement.openBitwarden()
}
func accountsFor(domain: String, completion: @escaping ([BrowserServicesKit.SecureVaultModels.WebsiteAccount], Error?) -> Void) {
guard !isLocked else {
completion([], nil)
return
}
guard let url = URL(string: "https://\(domain)") else {
completion([], PasswordManagerCoordinatorError.makingOfUrlFailed)
return
}
bitwardenManagement.retrieveCredentials(for: url) { [weak self] credentials, error in
if let error = error {
completion([], error)
return
} else {
let accounts = credentials.compactMap { return BrowserServicesKit.SecureVaultModels.WebsiteAccount(from: $0) }
self?.cache(credentials: credentials, for: url)
completion(accounts, nil)
}
}
}
func cachedAccountsFor(domain: String) -> [BrowserServicesKit.SecureVaultModels.WebsiteAccount] {
return cache
.filter { (_, credential) in
credential.domain == domain
}
.compactMap {
SecureVaultModels.WebsiteAccount(from: $0.value)
}
}
func cachedWebsiteCredentialsFor(domain: String, username: String) -> BrowserServicesKit.SecureVaultModels.WebsiteCredentials? {
if let credential: BWCredential = cache.values.first(where: { credential in
credential.domain == domain && credential.username == username
}) {
return SecureVaultModels.WebsiteCredentials(from: credential)
}
return nil
}
func websiteCredentialsFor(accountId: String, completion: @escaping (BrowserServicesKit.SecureVaultModels.WebsiteCredentials?, Error?) -> Void) {
guard !isLocked else {
completion(nil, nil)
return
}
if let credential = cache[accountId] {
completion(BrowserServicesKit.SecureVaultModels.WebsiteCredentials(from: credential), nil)
} else {
assertionFailure("Credentials not cached")
completion(nil, nil)
}
}
func websiteCredentialsFor(domain: String, completion: @escaping ([BrowserServicesKit.SecureVaultModels.WebsiteCredentials], Error?) -> Void) {
guard !isLocked else {
completion([], nil)
return
}
guard let url = URL(string: "https://\(domain)") else {
completion([], PasswordManagerCoordinatorError.makingOfUrlFailed)
return
}
bitwardenManagement.retrieveCredentials(for: url) { [weak self] credentials, error in
if let error = error {
completion([], error)
return
} else {
self?.cache(credentials: credentials, for: url)
let credentials = credentials.compactMap { BrowserServicesKit.SecureVaultModels.WebsiteCredentials(from: $0) }
completion(credentials, nil)
}
}
}
func storeWebsiteCredentials(_ credentials: SecureVaultModels.WebsiteCredentials,
completion: @escaping (Error?) -> Void) {
guard case let .connected(vault) = bitwardenManagement.status,
let bitwardenCredential = BWCredential(from: credentials, vault: vault) else {
Logger.general.fault("Failed to store credentials: Bitwarden is not connected or bad credential")
assertionFailure("Bitwarden is not connected or bad credential")
return
}
if bitwardenCredential.credentialId == nil {
bitwardenManagement.create(credential: bitwardenCredential) { [weak self] error in
self?.websiteCredentialsFor(domain: credentials.account.domain ?? "") { _, _ in
completion(error)
}
}
} else {
bitwardenManagement.update(credential: bitwardenCredential) { [weak self] error in
self?.websiteCredentialsFor(domain: credentials.account.domain ?? "") { _, _ in
completion(error)
}
}
}
}
#else
func setEnabled(_ enabled: Bool) {}
func askToUnlock(completionHandler: @escaping () -> Void) {}
func openPasswordManager() {}
func accountsFor(domain: String, completion: @escaping ([BrowserServicesKit.SecureVaultModels.WebsiteAccount], Error?) -> Void) {}
func cachedAccountsFor(domain: String) -> [BrowserServicesKit.SecureVaultModels.WebsiteAccount] { return [] }
func cachedWebsiteCredentialsFor(domain: String, username: String) -> BrowserServicesKit.SecureVaultModels.WebsiteCredentials? { return nil }
func websiteCredentialsFor(accountId: String, completion: @escaping (BrowserServicesKit.SecureVaultModels.WebsiteCredentials?, Error?) -> Void) {}
func websiteCredentialsFor(domain: String, completion: @escaping ([BrowserServicesKit.SecureVaultModels.WebsiteCredentials], Error?) -> Void) {}
func storeWebsiteCredentials(_ credentials: SecureVaultModels.WebsiteCredentials,
completion: @escaping (Error?) -> Void) {}
#endif
func reportPasswordAutofill() {
guard isEnabled else {
return
}
PixelKit.fire(GeneralPixel.bitwardenPasswordAutofilled)
}
func reportPasswordSave() {
guard isEnabled else {
return
}
PixelKit.fire(GeneralPixel.bitwardenPasswordSaved)
}
// MARK: - Cache
private func cache(credentials: [BWCredential], for url: URL) {
cache.forEach { key, value in
if value.domain == url.host {
cache.removeValue(forKey: key)
}
}
credentials.forEach { credential in
if let credentialId = credential.credentialId {
cache[credentialId] = credential
}
}
}
private var cache = [String: BWCredential]()
}
extension BrowserServicesKit.SecureVaultModels.WebsiteAccount {
init?(from bitwardenCredential: BWCredential) {
guard let credentialId = bitwardenCredential.credentialId else {
return nil
}
self.init(id: credentialId,
username: bitwardenCredential.username ?? "",
domain: bitwardenCredential.domain,
created: Date(),
lastUpdated: Date())
}
}
extension BrowserServicesKit.SecureVaultModels.WebsiteCredentials {
init?(from bitwardenCredential: BWCredential, emptyPasswordAllowed: Bool = true) {
guard let account = BrowserServicesKit.SecureVaultModels.WebsiteAccount(from: bitwardenCredential) else {
assertionFailure("Failed to init account from BitwardenCredential")
return nil
}
let passwordString = emptyPasswordAllowed ? bitwardenCredential.password ?? "" : bitwardenCredential.password
guard let password = passwordString?.data(using: .utf8) else {
assertionFailure("Failed to init account from BitwardenCredential")
return nil
}
self.init(account: account, password: password)
}
}
extension BWCredential {
init?(from websiteCredentials: BrowserServicesKit.SecureVaultModels.WebsiteCredentials, vault: BWVault) {
guard let domain = websiteCredentials.account.domain else {
return nil
}
self.init(userId: vault.id,
credentialId: websiteCredentials.account.id,
credentialName: domain,
username: websiteCredentials.account.username,
password: websiteCredentials.password?.utf8String() ?? "",
domain: domain)
}
}