]> git.saurik.com Git - apple/security.git/blob - keychain/TrustedPeersHelper/ContainerMap.swift
Security-59306.101.1.tar.gz
[apple/security.git] / keychain / TrustedPeersHelper / ContainerMap.swift
1 /*
2 * Copyright (c) 2018 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 import CloudKit
25 import CloudKit_Private
26 import CloudKitCode
27 import CloudKitCodeProtobuf
28 import CoreData
29 import Foundation
30
31 // TODO: merge into CodeConnection
32
33 let CuttlefishPushTopicBundleIdentifier = "com.apple.security.cuttlefish"
34
35 struct CKInternalErrorMatcher {
36 let code: Int
37 let internalCode: Int
38 }
39
40 // Match a CKError/CKInternalError
41 func ~= (pattern: CKInternalErrorMatcher, value: Error?) -> Bool {
42 guard let value = value else {
43 return false
44 }
45 let error = value as NSError
46 guard let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError else {
47 return false
48 }
49 return error.domain == CKErrorDomain && error.code == pattern.code &&
50 underlyingError.domain == CKInternalErrorDomain && underlyingError.code == pattern.internalCode
51 }
52
53 struct CKErrorMatcher {
54 let code: Int
55 }
56
57 // Match a CKError
58 func ~= (pattern: CKErrorMatcher, value: Error?) -> Bool {
59 guard let value = value else {
60 return false
61 }
62 let error = value as NSError
63 return error.domain == CKErrorDomain && error.code == pattern.code
64 }
65
66 struct NSURLErrorMatcher {
67 let code: Int
68 }
69
70 // Match an NSURLError
71 func ~= (pattern: NSURLErrorMatcher, value: Error?) -> Bool {
72 guard let value = value else {
73 return false
74 }
75 let error = value as NSError
76 return error.domain == NSURLErrorDomain && error.code == pattern.code
77 }
78
79 public class RetryingInvocable: CloudKitCode.Invocable {
80 private let underlyingInvocable: CloudKitCode.Invocable
81
82 internal init(retry: CloudKitCode.Invocable) {
83 self.underlyingInvocable = retry
84 }
85
86 public class func retryableError(error: Error?) -> Bool {
87 switch error {
88 case NSURLErrorMatcher(code: NSURLErrorTimedOut):
89 return true
90 case CKErrorMatcher(code: CKError.networkFailure.rawValue):
91 return true
92 case CKInternalErrorMatcher(code: CKError.serverRejectedRequest.rawValue, internalCode: CKInternalErrorCode.errorInternalServerInternalError.rawValue):
93 return true
94 case CuttlefishErrorMatcher(code: CuttlefishErrorCode.retryableServerFailure):
95 return true
96 case CuttlefishErrorMatcher(code: CuttlefishErrorCode.transactionalFailure):
97 return true
98 default:
99 return false
100 }
101 }
102
103 public func invoke<RequestType, ResponseType>(function: String,
104 request: RequestType,
105 completion: @escaping (ResponseType?, Error?) -> Void) where RequestType: Message, ResponseType: Message {
106 let now = Date()
107 let deadline = Date(timeInterval: 30, since: now)
108 let delay = TimeInterval(5)
109
110 self.invokeRetry(function: function,
111 request: request,
112 deadline: deadline,
113 minimumDelay: delay,
114 completion: completion)
115 }
116
117 private func invokeRetry<RequestType: Message, ResponseType: Message>(
118 function: String,
119 request: RequestType,
120 deadline: Date,
121 minimumDelay: TimeInterval,
122 completion: @escaping (ResponseType?, Error?) -> Void) {
123
124 self.underlyingInvocable.invoke(function: function,
125 request: request) { (response: ResponseType?, error: Error?) in
126 if let error = error, RetryingInvocable.retryableError(error: error) {
127 let now = Date()
128
129 // Check cuttlefish and CKError retry afters.
130 let cuttlefishDelay = CuttlefishRetryAfter(error: error)
131 let ckDelay = CKRetryAfterSecondsForError(error)
132 let delay = max(minimumDelay, cuttlefishDelay, ckDelay)
133 let cutoff = Date(timeInterval: delay, since: now)
134
135 guard cutoff.compare(deadline) == ComparisonResult.orderedDescending else {
136 Thread.sleep(forTimeInterval: delay)
137 os_log("%{public}@ error: %{public}@ (retrying, now=%{public}@, deadline=%{public}@)", log: tplogDebug,
138 function,
139 "\(String(describing: error))",
140 "\(String(describing: now))",
141 "\(String(describing: deadline))")
142 self.invokeRetry(function: function,
143 request: request,
144 deadline: deadline,
145 minimumDelay: minimumDelay,
146 completion: completion)
147 return
148 }
149 }
150 completion(response, error)
151 }
152 }
153 }
154
155 public class MyCodeConnection: CloudKitCode.Invocable {
156 private let serviceName: String
157 private let container: CKContainer
158 private let databaseScope: CKDatabase.Scope
159 private let local: Bool
160 private let queue: DispatchQueue
161
162 internal init(service: String, container: CKContainer, databaseScope: CKDatabase.Scope, local: Bool) {
163 self.serviceName = service
164 self.container = container
165 self.databaseScope = databaseScope
166 self.local = local
167 self.queue = DispatchQueue(label: "MyCodeConnection", qos: .userInitiated)
168 }
169
170 /// Temporary stand-in until xcinverness moves to a swift-grpc plugin.
171 /// Intended to be used by protoc-generated code only
172 public func invoke<RequestType: Message, ResponseType: Message>(
173 function: String, request: RequestType,
174 completion: @escaping (ResponseType?, Error?) -> Void) {
175
176 // Hack to fool CloudKit, real solution is tracked in <rdar://problem/49086080>
177 self.queue.async {
178
179 let operation = CodeOperation<RequestType, ResponseType>(
180 service: self.serviceName,
181 functionName: function,
182 request: request,
183 destinationServer: self.local ? .local : .default)
184
185 // As each UUID finishes, log it.
186 let requestCompletion = { (requestInfo: CKRequestInfo?) -> Void in
187 if let requestUUID = requestInfo?.requestUUID {
188 os_log("ckoperation request finished: %{public}@ %{public}@", log: tplogDebug, function, requestUUID)
189 }
190 }
191 operation.requestCompletedBlock = requestCompletion
192
193 let loggingCompletion = { (response: ResponseType?, error: Error?) -> Void in
194 os_log("%{public}@(%{public}@): %{public}@, error: %{public}@",
195 log: tplogDebug,
196 function,
197 "\(String(describing: request))",
198 "\(String(describing: response))",
199 "\(String(describing: error))")
200 completion(response, error)
201 }
202 operation.codeOperationCompletionBlock = loggingCompletion
203
204 /* Same convenience API properties that we specify in CKContainer / CKDatabase */
205 operation.queuePriority = .low
206
207 // One alternative here would be to not set any QoS and trust the
208 // QoS propagation to do what's right. But there is also some benefit in
209 // just using a lower CPU QoS because it should be hard to measure for the
210 // casual adopter.
211 operation.qualityOfService = .userInitiated
212
213 operation.configuration.discretionaryNetworkBehavior = .nonDiscretionary
214 operation.configuration.automaticallyRetryNetworkFailures = false
215 operation.configuration.isCloudKitSupportOperation = true
216
217 operation.configuration.sourceApplicationBundleIdentifier = CuttlefishPushTopicBundleIdentifier
218
219 let database = self.container.database(with: self.databaseScope)
220
221 database.add(operation)
222 }
223 }
224 }
225
226 protocol ContainerNameToCuttlefishInvocable {
227 func client(container: String) -> CloudKitCode.Invocable
228 }
229
230 class CKCodeCuttlefishInvocableCreator: ContainerNameToCuttlefishInvocable {
231 func client(container: String) -> CloudKitCode.Invocable {
232 // Set up Cuttlefish client connection
233 let ckContainer = CKContainer(identifier: container)
234
235 // Cuttlefish is using its own push topic.
236 // To register for this push topic, we need to issue CK operations with a specific bundle identifier
237 ckContainer.sourceApplicationBundleIdentifier = CuttlefishPushTopicBundleIdentifier
238
239 let ckDatabase = ckContainer.privateCloudDatabase
240 return MyCodeConnection(service: "Cuttlefish", container: ckContainer,
241 databaseScope: ckDatabase.databaseScope, local: false)
242 }
243 }
244
245 // A collection of Containers.
246 // When a Container of a given name is requested, it is created if it did not already exist.
247 // Methods may be invoked concurrently.
248 class ContainerMap {
249 private let queue = DispatchQueue(label: "com.apple.security.TrustedPeersHelper.ContainerMap")
250
251 let invocableCreator: ContainerNameToCuttlefishInvocable
252
253 init(invocableCreator: ContainerNameToCuttlefishInvocable) {
254 self.invocableCreator = invocableCreator
255 }
256
257 // Only access containers while executing on queue
258 private var containers: [ContainerName: Container] = [:]
259
260 func findOrCreate(name: ContainerName) throws -> Container {
261 return try queue.sync {
262 if let container = self.containers[name] {
263 return container
264 } else {
265
266 // Set up Core Data stack
267 let persistentStoreURL = ContainerMap.urlForPersistentStore(name: name)
268 let description = NSPersistentStoreDescription(url: persistentStoreURL)
269
270 // Wrap whatever we're given in a magically-retrying layer
271 let cuttlefishInvocable = self.invocableCreator.client(container: name.container)
272 let retryingInvocable = RetryingInvocable(retry: cuttlefishInvocable)
273 let cuttlefish = CuttlefishAPIAsyncClient(invocable: retryingInvocable)
274
275 let container = try Container(name: name, persistentStoreDescription: description,
276 cuttlefish: cuttlefish)
277 self.containers[name] = container
278 return container
279 }
280 }
281 }
282
283 static func urlForPersistentStore(name: ContainerName) -> URL {
284 let filename = name.container + "-" + name.context + ".TrustedPeersHelper.db"
285 return SecCopyURLForFileInKeychainDirectory(filename as CFString) as URL
286 }
287
288 // To be called via test only
289 func removeAllContainers() {
290 queue.sync {
291 self.containers.removeAll()
292 }
293 }
294 }