-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathOWSRequestMaker.swift
229 lines (200 loc) · 8.29 KB
/
OWSRequestMaker.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
//
// Copyright 2018 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
//
import Foundation
import LibSignalClient
@objc
public enum RequestMakerUDAuthError: Int, Error, IsRetryableProvider {
case udAuthFailure
// MARK: - IsRetryableProvider
public var isRetryableProvider: Bool {
switch self {
case .udAuthFailure:
return true
}
}
}
// MARK: -
public struct RequestMakerResult {
public let response: HTTPResponse
public let wasSentByUD: Bool
public var responseJson: Any? {
response.responseBodyJson
}
}
/// A utility class that handles:
///
/// - Sending via Web Socket or REST, depending on the process (main app vs.
/// NSE) & whether or not we're connected.
///
/// - Retrying UD requests that fail due to 401/403 errors.
final class RequestMaker {
struct Options: OptionSet {
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
/// If the initial request is unidentified and that fails, send the request
/// again as an identified request.
static let allowIdentifiedFallback = Options(rawValue: 1 << 0)
/// This RequestMaker is used when fetching profiles, so it shouldn't kick
/// off additional profile fetches when errors occur.
static let isProfileFetch = Options(rawValue: 1 << 1)
/// This Request can *always* use the web socket and should never fall back
/// to REST.
static let waitForWebSocketToOpen = Options(rawValue: 1 << 2)
}
private let label: String
private let serviceId: ServiceId
private let address: SignalServiceAddress
private let canUseStoryAuth: Bool
private let accessKey: OWSUDAccess?
private let endorsement: GroupSendFullTokenBuilder?
private let authedAccount: AuthedAccount
private let options: Options
init(
label: String,
serviceId: ServiceId,
canUseStoryAuth: Bool,
accessKey: OWSUDAccess?,
endorsement: GroupSendFullTokenBuilder?,
authedAccount: AuthedAccount,
options: Options
) {
self.label = label
self.serviceId = serviceId
self.address = SignalServiceAddress(serviceId)
self.canUseStoryAuth = canUseStoryAuth
self.accessKey = accessKey
self.endorsement = endorsement
self.authedAccount = authedAccount
self.options = options
}
private enum SealedSenderAuth {
case story
case accessKey(OWSUDAccess)
case endorsement(GroupSendFullToken)
func toRequestAuth() -> TSRequest.SealedSenderAuth {
switch self {
case .story: .story
case .accessKey(let udAccess): .accessKey(udAccess.key)
case .endorsement(let endorsement): .endorsement(endorsement)
}
}
}
/// Invokes `block` with each available authentication mechanism.
///
/// The `block` is always invoked at least once, and it may be invoked
/// multiple times when Sealed Sender auth errors occur.
private func forEachAuthMechanism<T>(block: (SealedSenderAuth?) async throws -> T) async throws -> T {
var authMechanisms: [() -> SealedSenderAuth?]
if canUseStoryAuth {
authMechanisms = [{ .story }]
owsAssertDebug(!self.options.contains(.allowIdentifiedFallback))
} else {
authMechanisms = [
accessKey.map({ accessKey in { .accessKey(accessKey) } }),
endorsement.map({ endorsement in { .endorsement(endorsement.build()) } }),
].compacted()
if authMechanisms.isEmpty || self.options.contains(.allowIdentifiedFallback) {
authMechanisms.append({ nil })
}
}
var mostRecentError: (any Error)?
for authMechanism in authMechanisms {
do {
return try await block(authMechanism())
} catch {
mostRecentError = error
switch error {
case RequestMakerUDAuthError.udAuthFailure:
continue
default:
throw error
}
}
}
// We must run the loop at least once, and we either exit successfully or
// set `mostRecentError` to some value.
owsPrecondition(!authMechanisms.isEmpty)
throw mostRecentError!
}
func makeRequest(requestBlock: (TSRequest.SealedSenderAuth?) throws -> TSRequest) async throws -> RequestMakerResult {
return try await self.forEachAuthMechanism { sealedSenderAuth in
do {
let request = try requestBlock(sealedSenderAuth?.toRequestAuth())
let isUDRequest = sealedSenderAuth != nil
owsPrecondition(isUDRequest == request.isUDRequest)
let result = try await self._makeRequest(request: request)
await requestSucceeded(sealedSenderAuth: sealedSenderAuth)
return result
} catch {
try await requestFailed(error: error, sealedSenderAuth: sealedSenderAuth)
}
}
}
private func _makeRequest(request: TSRequest) async throws -> RequestMakerResult {
let connectionType: OWSChatConnectionType = (request.isUDRequest ? .unidentified : .identified)
let shouldUseWebsocket: Bool = (
OWSChatConnection.canAppUseSocketsToMakeRequests
&& (self.options.contains(.waitForWebSocketToOpen) || DependenciesBridge.shared.chatConnectionManager.canMakeRequests(connectionType: connectionType))
)
let response: HTTPResponse
if shouldUseWebsocket {
response = try await DependenciesBridge.shared.chatConnectionManager.makeRequest(request)
} else {
response = try await SSKEnvironment.shared.networkManagerRef.asyncRequest(request, canUseWebSocket: false)
}
return RequestMakerResult(response: response, wasSentByUD: request.isUDRequest)
}
private func requestFailed(error: Error, sealedSenderAuth: SealedSenderAuth?) async throws -> Never {
if let sealedSenderAuth, (error.httpStatusCode == 401 || error.httpStatusCode == 403) {
// If an Access Key-authenticated request fails because of a 401/403, we
// assume the Access Key is wrong.
if case .accessKey(let udAccess) = sealedSenderAuth {
await updateUdAccessMode({
switch udAccess.mode {
case .unrestricted:
// If it was unrestricted, we *might* have the right profile key.
return .unknown
case .unknown, .enabled:
// If it was unknown, we may have tried the real key (if we had it) or a
// random key. In either of these cases, we don't want to try again because
// it won't work.
return .disabled
}
}())
}
throw RequestMakerUDAuthError.udAuthFailure
}
throw error
}
private func requestSucceeded(sealedSenderAuth: SealedSenderAuth?) async {
// If this was an Access Key-authed request for an "unknown" user...
if case .accessKey(let udAccess) = sealedSenderAuth, udAccess.mode == .unknown {
// ...fetch their profile since we know udAccessMode is out of date.
fetchProfileIfNeeded()
}
}
private func updateUdAccessMode(_ newValue: UnidentifiedAccessMode) async {
await SSKEnvironment.shared.databaseStorageRef.awaitableWrite { tx in
SSKEnvironment.shared.udManagerRef.setUnidentifiedAccessMode(newValue, for: self.serviceId, tx: tx)
}
fetchProfileIfNeeded()
}
private func fetchProfileIfNeeded() {
// If this request isn't a profile fetch, kick off a profile fetch. If it
// is a profile fetch, don't bother fetching it *again*.
if self.options.contains(.isProfileFetch) {
return
}
Task { [serviceId, authedAccount] in
let profileFetcher = SSKEnvironment.shared.profileFetcherRef
_ = try? await profileFetcher.fetchProfile(
for: serviceId,
authedAccount: authedAccount
)
}
}
}