-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathMSALNativeAuthEndToEndBaseTestCase.swift
More file actions
213 lines (184 loc) · 9.65 KB
/
Copy pathMSALNativeAuthEndToEndBaseTestCase.swift
File metadata and controls
213 lines (184 loc) · 9.65 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
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import MSAL
class MSALNativeAuthEndToEndBaseTestCase: XCTestCase {
private class Constants {
static let nativeAuthKey = "native_auth"
static let clientIdEmailPasswordKey = "email_password_client_id"
static let clientIdEmailCodeKey = "email_code_client_id"
static let clientIdEmailPasswordAttributesKey = "email_password_attributes_client_id"
static let clientIdEmailCodeAttributesKey = "email_code_attributes_client_id"
static let tenantSubdomainKey = "tenant_subdomain"
static let tenantIdKey = "tenant_id"
static let signInEmailPasswordUsernameKey = "sign_in_email_password_username"
static let signInEmailPasswordMFAUsernameKey = "sign_in_email_password_mfa_username"
static let signInEmailPasswordMFANoDefaultAuthMethodUsernameKey = "sign_in_email_password_mfa_no_default_username"
static let signInEmailCodeUsernameKey = "sign_in_email_code_username"
#if !os(macOS)
static let resetPasswordUsernameKey = "reset_password_username"
#else
static let resetPasswordUsernameKey = "reset_password_username_macos"
#endif
static let emailProviderPasswordKey = "email_provider_password"
}
let correlationId = UUID()
static var confFileContent: [String: Any]? = nil
static var nativeAuthConfFileContent: [String: String]? = nil
// Per-test-case instance so mail.tm state (token, checkpoint) is isolated to a single test's
// lifecycle. markCheckpoint() and the subsequent readOtpCode() run on the same instance within
// a test, while parallel test runs never share mutable state.
private let codeRetriever = MSALNativeAuthEmailCodeRetriever()
override class func setUp() {
super.setUp()
guard let confURL = Bundle(for: Self.self).url(forResource: "conf", withExtension: "json"), let configurationData = try? Data(contentsOf: confURL) else {
XCTFail("conf.json file not found")
return
}
guard let confFile = try? JSONSerialization.jsonObject(with: configurationData, options: []) as? [String: Any] else {
XCTFail("conf.json file can't be parsed.")
return
}
confFileContent = confFile
if let configurationFileContent = confFile[Constants.nativeAuthKey] as? [String: String] {
nativeAuthConfFileContent = configurationFileContent
} else {
XCTFail("native_auth section in conf.json file not found")
}
}
func initialisePublicClientApplication(
clientIdType: ClientIdType = .password,
challengeTypes: MSALNativeAuthChallengeTypes = [.OOB, .password],
capabilities: MSALNativeAuthCapabilities = [.mfaRequired, .registrationRequired],
customAuthorityURLFormat: AuthorityURLFormat? = nil
) -> MSALNativeAuthPublicClientApplication? {
let clientIdKey = getClientIdKey(type: clientIdType)
guard let clientId = MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[clientIdKey] as? String else {
XCTFail("ClientId not found in conf.json")
return nil
}
guard let tenantSubdomain = MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.tenantSubdomainKey] as? String else {
XCTFail("TenantSubdomain not found in conf.json")
return nil
}
guard let tenantId = MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.tenantIdKey] as? String else {
XCTFail("TenantId not found in conf.json")
return nil
}
if let customAuthorityURLFormat = customAuthorityURLFormat {
let customSubdomain = getAuthorityURLString(
tenantSubdomain: tenantSubdomain,
tenantId: tenantId,
format: customAuthorityURLFormat
)
let authority = try! MSALCIAMAuthority(
url: URL(string: customSubdomain)!,
validateFormat: false
)
let configuration = MSALNativeAuthPublicClientApplicationConfig(clientId: clientId, authority: authority, challengeTypes: challengeTypes)
configuration.capabilities = capabilities
return try? MSALNativeAuthPublicClientApplication(
nativeAuthConfiguration: configuration
)
} else if let configuration = try? MSALNativeAuthPublicClientApplicationConfig(clientId: clientId, tenantSubdomain: tenantSubdomain, challengeTypes: challengeTypes) {
configuration.capabilities = capabilities
return try? MSALNativeAuthPublicClientApplication(nativeAuthConfiguration: configuration)
} else {
return nil
}
}
func createEmailProviderAccount(password: String) async -> String {
guard let address = await codeRetriever.createAuthenticatedAccount(password: password) else {
XCTFail("Failed to create/authenticate email provider account")
return ""
}
return address
}
func generateSignUpRandomEmail() -> String {
return codeRetriever.generateRandomEmailAddress()
}
func generateRandomPassword() -> String {
return "password.\(Date().timeIntervalSince1970)"
}
func retrieveCodeFor(email: String, password: String? = nil) async -> String? {
guard let password = password ?? retrieveEmailProviderPassword() else {
XCTFail("email_provider_password not found in conf.json")
return nil
}
let connected = await codeRetriever.connectToExistingAccount(address: email, password: password)
guard connected else {
XCTFail("Could not authenticate with mail.tm for the email specified")
return nil
}
return await codeRetriever.readOtpCode()
}
/// Records a checkpoint on the test-case's mail.tm client. Call this immediately before triggering
/// an action that sends an OTP email so `retrieveCodeFor` ignores older messages.
func markEmailCheckpoint() {
codeRetriever.markCheckpoint()
}
func retrieveEmailProviderPassword() -> String? {
return MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.emailProviderPasswordKey]
}
func retrieveUsernameForSignInCode() -> String? {
return MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.signInEmailCodeUsernameKey]
}
func retrieveUsernameForSignInUsernameAndPassword() -> String? {
return MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.signInEmailPasswordUsernameKey]
}
func retrieveUsernameForSignInUsernamePasswordAndMFA() -> String? {
return MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.signInEmailPasswordMFAUsernameKey]
}
func retrieveUsernameForSignInUsernamePasswordAndMFANoDefaultAuthMethod() -> String? {
return MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.signInEmailPasswordMFANoDefaultAuthMethodUsernameKey]
}
func retrieveUsernameForResetPassword() -> String? {
return MSALNativeAuthEndToEndBaseTestCase.nativeAuthConfFileContent?[Constants.resetPasswordUsernameKey]
}
func fulfillment(of expectations: [XCTestExpectation], timeout seconds: TimeInterval = 40) async {
await fulfillment(of: expectations, timeout: seconds, enforceOrder: false)
}
private func getClientIdKey(type: ClientIdType) -> String {
switch type {
case .password:
return Constants.clientIdEmailPasswordKey
case .passwordAndAttributes:
return Constants.clientIdEmailPasswordAttributesKey
case .code:
return Constants.clientIdEmailCodeKey
case .codeAndAttributes:
return Constants.clientIdEmailCodeAttributesKey
}
}
private func getAuthorityURLString(tenantSubdomain: String, tenantId: String, format: AuthorityURLFormat) -> String {
switch format {
case .tenantSubdomainShortVersion:
return String(format: "https://%@.ciamlogin.com/", tenantSubdomain)
case .tenantSubdomainLongVersion:
return String(format: "https://%@.ciamlogin.com/%@.onmicrosoft.com", tenantSubdomain, tenantSubdomain)
case .tenantSubdomainTenantId:
return String(format: "https://%@.ciamlogin.com/%@", tenantSubdomain, tenantId)
}
}
}