-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathIDXClient+V1ResponseConstructors.swift
More file actions
678 lines (590 loc) · 25.7 KB
/
Copy pathIDXClient+V1ResponseConstructors.swift
File metadata and controls
678 lines (590 loc) · 25.7 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//
// Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 AuthFoundation
#if !COCOAPODS
import JSON
#endif
protocol ReferencesParent: AnyObject {
func assign<ParentType>(parent: ParentType?)
}
struct IonRemediationContext {
let webAuthnAutofillUIChallenge: IonObject<IonChallengeData>?
let authenticatorCollection: Authenticator.Collection?
}
extension Response {
internal convenience init(flow: any InteractionCodeFlowAPI, ion response: IonResponse) throws {
let authenticators = try Authenticator.Collection(flow: flow, ion: response)
let remediations = Remediation.Collection(flow: flow, ion: response, authenticatorCollection: authenticators)
let successRemediationOption = Remediation(flow: flow, ion: response.successWithInteractionCode)
let messages = Response.Message.Collection(response.messages?.value.compactMap { Response.Message(flow: flow, ion: $0) },
nestedMessages: remediations.nestedMessages())
self.init(flow: flow,
expiresAt: response.expiresAt,
intent: Intent(string: response.intent),
authenticators: authenticators,
remediations: remediations,
successRemediationOption: successRemediationOption,
messages: messages,
app: Response.Application(ion: response.app?.value),
user: Response.User(ion: response.user?.value))
try loadRelatedObjects()
}
}
extension Response.Message {
internal convenience init?(flow: any InteractionCodeFlowAPI, ion object: IonMessage?) {
guard let object = object else { return nil }
self.init(type: object.type,
localizationKey: object.i18n?.key,
message: object.message)
}
}
extension Response.Application {
internal init?(ion object: IonApp?) {
guard let object = object else { return nil }
self.init(id: object.id,
label: object.label,
name: object.name)
}
}
extension Response.User {
internal init?(ion object: IonUser?) {
guard let object = object,
let userId = object.id
else { return nil }
self.init(id: userId,
username: object.identifier,
profile: .init(ion: object.profile?.compactMapValues({ $0 })))
}
}
extension Response.User.Profile {
internal init?(ion object: [String: String]?) {
guard let object = object else { return nil }
var timeZone: TimeZone?
if let string = object["timeZone"] {
timeZone = TimeZone(identifier: string)
}
var locale: Locale?
if let string = object["locale"] {
locale = Locale(identifier: string)
}
self.init(firstName: object["firstName"],
lastName: object["lastName"],
timeZone: timeZone,
locale: locale)
}
}
extension IonResponse {
struct AuthenticatorMapping {
let jsonPath: String
let authenticator: IonAuthenticator
}
func authenticatorState(for authenticators: [IonAuthenticator],
in jsonPaths: [String]) -> Authenticator.State
{
var state = [Authenticator.State]()
state = jsonPaths.reduce(into: state, { state, jsonPath in
switch jsonPath {
case "$.currentAuthenticatorEnrollment":
state.append(.enrolling)
case "$.currentAuthenticator":
state.append(.authenticating)
case "$.recoveryAuthenticator":
state.append(.recovery)
default:
if jsonPath.hasPrefix("$.authenticatorEnrollments") {
state.append(.enrolled)
}
else if jsonPath.hasPrefix("$.authenticators") {
state.append(.normal)
}
}
})
return state.sorted(by: { $0 > $1 }).first ?? .normal
}
func allAuthenticators() -> [AuthenticatorMapping] {
var allAuthenticators: [AuthenticatorMapping] = []
if let authenticator = currentAuthenticatorEnrollment?.value {
allAuthenticators.append(.init(jsonPath: "$.currentAuthenticatorEnrollment",
authenticator: authenticator))
}
if let authenticator = currentAuthenticator?.value {
allAuthenticators.append(.init(jsonPath: "$.currentAuthenticator",
authenticator: authenticator))
}
if let authenticator = recoveryAuthenticator?.value {
allAuthenticators.append(.init(jsonPath: "$.recoveryAuthenticator",
authenticator: authenticator))
}
if let authenticators = authenticatorEnrollments?.value,
!authenticators.isEmpty
{
for index in 0 ... authenticators.count - 1 {
allAuthenticators.append(.init(jsonPath: "$.authenticatorEnrollments.value[\(index)]",
authenticator: authenticators[index]))
}
}
if let authenticators = authenticators?.value,
!authenticators.isEmpty
{
for index in 0 ... authenticators.count - 1 {
allAuthenticators.append(.init(jsonPath: "$.authenticators.value[\(index)]",
authenticator: authenticators[index]))
}
}
return allAuthenticators
}
}
extension PasswordSettingsCapability {
init?(with settings: JSON?) {
guard case let .object(settings) = settings,
let complexity = settings["complexity"]?.anyValue as? [String: Any]
else { return nil }
var daysToExpiry: Int?
if case let .number(daysToExpiryValue) = settings["daysToExpiry"] {
daysToExpiry = daysToExpiryValue.intValue
}
self.init(daysToExpiry: daysToExpiry ?? 0,
minLength: complexity["minLength"] as? Int ?? 0,
minLowerCase: complexity["minLowerCase"] as? Int ?? 0,
minUpperCase: complexity["minUpperCase"] as? Int ?? 0,
minNumber: complexity["minNumber"] as? Int ?? 0,
minSymbol: complexity["minSymbol"] as? Int ?? 0,
maxConsecutiveRepeatingCharacters: complexity["maxConsecutiveRepeatingCharacters"] as? Int ?? 0,
excludeUsername: complexity["excludeUsername"] as? Bool ?? false,
excludeAttributes: complexity["excludeAttributes"] as? [String] ?? [])
}
}
extension Authenticator.Collection {
convenience init(flow: any InteractionCodeFlowAPI, ion object: IonResponse) throws {
let authenticatorMapping: [String: [IonResponse.AuthenticatorMapping]]
authenticatorMapping = object
.allAuthenticators()
.reduce(into: [:]) { (result, mapping) in
let authenticatorType = "\(mapping.authenticator.type):\(mapping.authenticator.id ?? "-")"
var collection: [IonResponse.AuthenticatorMapping] = result[authenticatorType] ?? []
collection.append(mapping)
result[authenticatorType] = collection
}
let authenticators: [Authenticator] = try authenticatorMapping
.values
.compactMap({ (mappingArray) in
return try Authenticator.makeAuthenticator(flow: flow,
ion: mappingArray.map(\.authenticator),
jsonPaths: mappingArray.map(\.jsonPath),
in: object)
})
self.init(authenticators)
}
}
extension Remediation.Collection {
convenience init(flow: any InteractionCodeFlowAPI,
ion object: IonResponse?,
authenticatorCollection: Authenticator.Collection)
{
let remediationContext = IonRemediationContext(
webAuthnAutofillUIChallenge: object?.webauthnAutofillUIChallenge,
authenticatorCollection: authenticatorCollection)
var remediations: [Remediation] = object?.remediation?.value.compactMap { (value) in
Remediation.makeRemediation(flow: flow,
ion: value,
context: remediationContext)
} ?? []
if let cancelResponse = Remediation.makeRemediation(flow: flow, ion: object?.cancel) {
remediations.append(cancelResponse)
}
if let successResponse = Remediation.makeRemediation(flow: flow, ion: object?.successWithInteractionCode) {
remediations.append(successResponse)
}
self.init(remediations: remediations)
}
}
extension SendCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let authenticator = authenticators.compactMap(\.send).first,
let remediation = Remediation.makeRemediation(flow: flow, ion: authenticator)
else {
return nil
}
self.init(remediation: remediation)
}
}
extension ResendCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let authenticator = authenticators.compactMap(\.resend).first,
let remediation = Remediation.makeRemediation(flow: flow, ion: authenticator)
else {
return nil
}
self.init(remediation: remediation)
}
}
extension RecoverCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let authenticator = authenticators.compactMap(\.recover).first,
let remediation = Remediation.makeRemediation(flow: flow, ion: authenticator)
else {
return nil
}
self.init(remediation: remediation)
}
}
extension PollCapability {
convenience init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let type = authenticators.first?.type,
let authenticator = authenticators.compactMap(\.poll).first,
let remediation = Remediation.makeRemediation(flow: flow, ion: authenticator)
else {
return nil
}
self.init(flow: flow,
authenticatorType: type,
remediation: remediation)
}
convenience init?(flow: any InteractionCodeFlowAPI, ion form: IonForm) {
guard form.name == "enroll-poll" ||
form.name == "challenge-poll"
else {
return nil
}
guard let remediation = Remediation.makeRemediation(flow: flow,
ion: form,
createCapabilities: false)
else {
return nil
}
self.init(flow: flow,
authenticatorType: .app,
remediation: remediation)
}
}
extension NumberChallengeCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let answerJson = authenticators.compactMap(\.contextualData?["correctAnswer"]).first,
case let .string(answer) = answerJson
else {
return nil
}
self.init(correctAnswer: answer)
}
}
extension ProfileCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let profile = authenticators.compactMap(\.profile).first
else {
return nil
}
self.init(profile: profile)
}
}
extension PasswordSettingsCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
guard let type = authenticators.first?.type,
type == .password,
let settings = authenticators.compactMap(\.settings).first
else {
return nil
}
self.init(with: settings)
}
}
extension OTPCapability {
init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
let methods = methodTypes(from: authenticators)
guard methods.contains(.otp) || methods.contains(.totp)
else {
return nil
}
guard let authenticator = authenticators.first(where: { $0.type == .app })
else {
return nil
}
guard let contextualData = authenticator.contextualData,
case let .object(qrcode) = contextualData["qrcode"],
case let .string(method) = qrcode["method"],
method == "embedded",
case let .string(mimeType) = qrcode["type"],
case let .string(href) = qrcode["href"],
let imageData = href.base64ImageData
else {
return nil
}
var sharedSecret: String?
if case let .string(value) = contextualData["sharedSecret"] {
sharedSecret = value
}
self.init(mimeType: mimeType,
imageData: imageData,
sharedSecret: sharedSecret)
}
}
extension DuoCapability {
convenience init?(flow: any InteractionCodeFlowAPI, ion authenticators: [IonAuthenticator]) {
// Exit early if none of the authenticators have a "duo" method
let methods = methodTypes(from: authenticators)
guard methods.contains(.duo) else {
return nil
}
// Extract the duo authenticator data
let duoAuthenticators = authenticators.filter({ $0.type == .app && $0.key == "duo" })
guard let authenticator = duoAuthenticators.first(where: { $0.contextualData != nil }),
let contextualData = authenticator.contextualData,
case let .string(host) = contextualData["host"],
case let .string(signedToken) = contextualData["signedToken"],
case let .string(script) = contextualData["script"]
else {
return nil
}
self.init(host: host, signedToken: signedToken, script: script)
}
}
extension SocialIDPCapability {
init?(flow: any InteractionCodeFlowAPI, ion object: IonForm) {
let type = Remediation.RemediationType(string: object.name)
guard type == .redirectIdp,
let idpObject = object.idp,
let idpId = idpObject["id"],
let idpName = idpObject["name"],
let idpType = object.type
else {
return nil
}
self.init(redirectUrl: object.href,
id: idpId,
idpName: idpName,
idpType: idpType,
service: .init(string: idpType))
}
}
extension WebAuthnRegistrationCapability {
convenience init?(flow: any InteractionCodeFlowAPI,
ion object: IonForm?,
context: IonRemediationContext?) throws
{
// WebAuthn registration information is listed on the currentAuthenticator,
// but is actionable by the Remediation. So we need to enure this capability
// can access the authenticator contextualData information, and that the
// registration capability is only bound to the remediation capable of
// carrying out the operation.
guard let authenticatorCollection = context?.authenticatorCollection,
object?.relatesTo != nil
else { return nil }
let webAuthnAuthenticators = authenticatorCollection.filter { authenticator in
authenticator.type == .securityKey && authenticator.key == "webauthn"
}
guard let contextualData = webAuthnAuthenticators.compactMap(\.context).first,
let activationData = contextualData["activationData"]
else {
return nil
}
try self.init(issuerURL: flow.client.configuration.issuerURL,
rawActivationJSON: activationData)
}
}
extension WebAuthnAuthenticationCapability {
convenience init?(flow: any InteractionCodeFlowAPI,
ion object: IonForm?,
context: IonRemediationContext?) throws
{
if let challengeData = context?.webAuthnAutofillUIChallenge {
try self.init(flow: flow,
ion: object,
challengeData: challengeData.value)
} else if let authenticatorCollection = context?.authenticatorCollection {
try self.init(flow: flow,
ion: object,
authenticatorCollection: authenticatorCollection)
} else {
return nil
}
}
convenience init?(flow: any InteractionCodeFlowAPI,
ion object: IonForm?,
authenticatorCollection: Authenticator.Collection) throws
{
guard object?.relatesTo != nil
else { return nil }
let webAuthnAuthenticators = authenticatorCollection.filter { authenticator in
authenticator.type == .securityKey && authenticator.key == "webauthn"
}
guard let contextualData = webAuthnAuthenticators.compactMap(\.context).first,
let challengeData = contextualData["challengeData"]
else {
return nil
}
try self.init(issuerURL: flow.client.configuration.issuerURL,
rawChallengeJSON: challengeData)
}
convenience init?(flow: any InteractionCodeFlowAPI,
ion object: IonForm?,
challengeData: IonChallengeData) throws
{
guard let object,
let relatesTo = object.relatesTo,
object.name == "challenge-webauthn-autofillui-authenticator",
relatesTo.contains("webauthnAutofillUIChallenge")
else {
return nil
}
try self.init(issuerURL: flow.client.configuration.issuerURL,
rawChallengeJSON: challengeData.challengeData)
}
}
private func methodTypes(from authenticators: [IonAuthenticator]) -> [Authenticator.Method]
{
let methods = authenticators
.compactMap(\.methods)
.reduce(into: [String: String]()) { (partialResult, items: [[String: String]]) in
items.forEach { item in
item.forEach { (key: String, value: String) in
partialResult[key] = value
}
}
}
let methodTypes: [Authenticator.Method] = methods
.filter { (key, value) in
key == "type"
}
.map { (key, value) in
return Authenticator.Method(rawValue: value)
}
return methodTypes
}
extension Authenticator {
static func makeAuthenticator(flow: any InteractionCodeFlowAPI,
ion authenticators: [IonAuthenticator],
jsonPaths: [String],
in response: IonResponse) throws -> Authenticator?
{
guard let first = authenticators.first else { return nil }
let filteredTypes = Set(authenticators.map(\.type))
guard filteredTypes.count == 1 else {
throw InteractionCodeFlowError.responseValidationFailed("Some mapped authenticators have differing types: \(filteredTypes.map(\.rawValue).joined(separator: ", "))")
}
let state = response.authenticatorState(for: authenticators, in: jsonPaths)
let key = authenticators.compactMap(\.key).first
let methods = authenticators.compactMap(\.methods).first
let contextualData = authenticators.compactMap(\.contextualData).first
let capabilities: [(any Capability)?] = [
ProfileCapability(flow: flow, ion: authenticators),
SendCapability(flow: flow, ion: authenticators),
ResendCapability(flow: flow, ion: authenticators),
PollCapability(flow: flow, ion: authenticators),
RecoverCapability(flow: flow, ion: authenticators),
PasswordSettingsCapability(flow: flow, ion: authenticators),
NumberChallengeCapability(flow: flow, ion: authenticators),
OTPCapability(flow: flow, ion: authenticators),
DuoCapability(flow: flow, ion: authenticators)
]
return Authenticator(flow: flow,
v1JsonPaths: jsonPaths,
state: state,
id: first.id,
displayName: first.displayName,
type: first.type,
key: key,
methods: methods,
contextualData: contextualData,
capabilities: capabilities.compactMap { $0 })
}
}
extension Remediation {
static func makeRemediation(flow: any InteractionCodeFlowAPI,
ion object: IonForm?,
context: IonRemediationContext? = nil,
createCapabilities: Bool = true) -> Remediation?
{
guard let object = object else { return nil }
// swiftlint:disable force_unwrapping
let form = Form(fields: object.value?.map({ (value) in
.init(flow: flow, ion: value)
})) ?? Form(fields: [])!
let refresh = (object.refresh != nil) ? Double(object.refresh!) / 1000.0 : nil
// swiftlint:enable force_unwrapping
let capabilities: [(any Capability)?] = createCapabilities ? [
SocialIDPCapability(flow: flow, ion: object),
PollCapability(flow: flow, ion: object),
try? WebAuthnRegistrationCapability(flow: flow,
ion: object,
context: context),
try? WebAuthnAuthenticationCapability(flow: flow,
ion: object,
context: context),
] : []
let remediation = Remediation(flow: flow,
name: object.name,
method: object.method,
href: object.href,
accepts: object.accepts,
form: form,
refresh: refresh,
relatesTo: object.relatesTo,
capabilities: capabilities.compactMap { $0 })
remediation?
.capabilities
.compactMap { $0.capabilityValue as? any ReferencesParent }
.forEach {
$0.assign(parent: remediation)
}
return remediation
}
internal convenience init?(flow: any InteractionCodeFlowAPI, ion object: IonForm?) {
guard let object = object,
let form = Form(fields: object.value?.map({ (value) in
.init(flow: flow, ion: value)
}))
else { return nil }
// swiftlint:disable force_unwrapping
self.init(flow: flow,
name: object.name,
method: object.method,
href: object.href,
accepts: object.accepts,
form: form,
refresh: (object.refresh != nil) ? Double(object.refresh!) / 1000.0 : nil,
relatesTo: object.relatesTo,
capabilities: [])
// swiftlint:enable force_unwrapping
}
}
extension Remediation.Form.Field {
internal convenience init(flow: any InteractionCodeFlowAPI, ion object: IonFormValue) {
// Fields default to visible, except there are circumstances where
// fields (such as `id`) don't properly include a `visible: false`. As a result,
// we need to infer visibility from other values.
var visible = object.visible ?? true
if let isMutable = object.mutable,
!isMutable && object.value != .null
{
visible = false
}
self.init(name: object.name,
label: object.label,
type: object.type,
value: object.value,
visible: visible,
mutable: object.mutable ?? true,
required: object.required ?? false,
secret: object.secret ?? false,
relatesTo: object.relatesTo,
form: Remediation.Form(fields: object.form?.value.map({ (value) in
.init(flow: flow, ion: value)
})),
options: object.options?.map { (value) in
.init(flow: flow, ion: value)
},
messages: .init(object.messages?.value.compactMap {
Response.Message(flow: flow, ion: $0)
}))
self.messages.allMessages.forEach { $0.field = self }
}
}