|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import Foundation |
| 6 | + |
| 7 | +public class OhttpManager { |
| 8 | + // The OhttpManager communicates with the relay and key server using |
| 9 | + // URLSession.shared.data unless an alternative networking method is |
| 10 | + // provided with this signature. |
| 11 | + public typealias NetworkFunction = (_: URLRequest) async throws -> (Data, URLResponse) |
| 12 | + |
| 13 | + // Global cache to caching Gateway encryption keys. Stale entries are |
| 14 | + // ignored and on Gateway errors the key used should be purged and retrieved |
| 15 | + // again next at next network attempt. |
| 16 | + static var keyCache = [URL: ([UInt8], Date)]() |
| 17 | + |
| 18 | + private var configUrl: URL |
| 19 | + private var relayUrl: URL |
| 20 | + private var network: NetworkFunction |
| 21 | + |
| 22 | + public init(configUrl: URL, |
| 23 | + relayUrl: URL, |
| 24 | + network: @escaping NetworkFunction = URLSession.shared.data) |
| 25 | + { |
| 26 | + self.configUrl = configUrl |
| 27 | + self.relayUrl = relayUrl |
| 28 | + self.network = network |
| 29 | + } |
| 30 | + |
| 31 | + private func fetchKey(url: URL) async throws -> [UInt8] { |
| 32 | + let request = URLRequest(url: url) |
| 33 | + if let (data, response) = try? await network(request), |
| 34 | + let httpResponse = response as? HTTPURLResponse, |
| 35 | + httpResponse.statusCode == 200 |
| 36 | + { |
| 37 | + return [UInt8](data) |
| 38 | + } |
| 39 | + |
| 40 | + throw OhttpError.KeyFetchFailed(message: "Failed to fetch encryption key") |
| 41 | + } |
| 42 | + |
| 43 | + private func keyForGateway(gatewayConfigUrl: URL, ttl: TimeInterval) async throws -> [UInt8] { |
| 44 | + if let (data, timestamp) = Self.keyCache[gatewayConfigUrl] { |
| 45 | + if Date() < timestamp + ttl { |
| 46 | + // Cache Hit! |
| 47 | + return data |
| 48 | + } |
| 49 | + |
| 50 | + Self.keyCache.removeValue(forKey: gatewayConfigUrl) |
| 51 | + } |
| 52 | + |
| 53 | + let data = try await fetchKey(url: gatewayConfigUrl) |
| 54 | + Self.keyCache[gatewayConfigUrl] = (data, Date()) |
| 55 | + |
| 56 | + return data |
| 57 | + } |
| 58 | + |
| 59 | + private func invalidateKey() { |
| 60 | + Self.keyCache.removeValue(forKey: configUrl) |
| 61 | + } |
| 62 | + |
| 63 | + public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) { |
| 64 | + // Get the encryption keys for Gateway |
| 65 | + let config = try await keyForGateway(gatewayConfigUrl: configUrl, |
| 66 | + ttl: TimeInterval(3600)) |
| 67 | + |
| 68 | + // Create an encryption session for a request-response round-trip |
| 69 | + let session = try OhttpSession(config: config) |
| 70 | + |
| 71 | + // Encapsulate the URLRequest for the Target |
| 72 | + let encoded = try session.encapsulate(method: request.httpMethod ?? "GET", |
| 73 | + scheme: request.url!.scheme!, |
| 74 | + server: request.url!.host!, |
| 75 | + endpoint: request.url!.path, |
| 76 | + headers: request.allHTTPHeaderFields ?? [:], |
| 77 | + payload: [UInt8](request.httpBody ?? Data())) |
| 78 | + |
| 79 | + // Request from Client to Relay |
| 80 | + var request = URLRequest(url: relayUrl) |
| 81 | + request.httpMethod = "POST" |
| 82 | + request.setValue("message/ohttp-req", forHTTPHeaderField: "Content-Type") |
| 83 | + request.httpBody = Data(encoded) |
| 84 | + |
| 85 | + let (data, response) = try await network(request) |
| 86 | + |
| 87 | + // Decapsulation failures have these codes, so invalidate any cached |
| 88 | + // keys in case the gateway has changed them. |
| 89 | + if let httpResponse = response as? HTTPURLResponse, |
| 90 | + httpResponse.statusCode == 400 || |
| 91 | + httpResponse.statusCode == 401 |
| 92 | + { |
| 93 | + invalidateKey() |
| 94 | + } |
| 95 | + |
| 96 | + guard let httpResponse = response as? HTTPURLResponse, |
| 97 | + httpResponse.statusCode == 200 |
| 98 | + else { |
| 99 | + throw OhttpError.RelayFailed(message: "Network errors communicating with Relay / Gateway") |
| 100 | + } |
| 101 | + |
| 102 | + // Decapsulate the Target response into a HTTPURLResponse |
| 103 | + let message = try session.decapsulate(encoded: [UInt8](data)) |
| 104 | + return (Data(message.payload), |
| 105 | + HTTPURLResponse(url: request.url!, |
| 106 | + statusCode: Int(message.statusCode), |
| 107 | + httpVersion: "HTTP/1.1", |
| 108 | + headerFields: message.headers)!) |
| 109 | + } |
| 110 | +} |
0 commit comments