diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift index cdf1f9b8d0..f68d08e7c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFAppInfo.swift @@ -14,7 +14,7 @@ struct ASFAppInfo: ASFAppInfoBehavior { } var targetSDK: String { - var targetSDK: String = "" + var targetSDK = "" #if os(iOS) || os(watchOS) || os(tvOS) targetSDK = "\(__IPHONE_OS_VERSION_MIN_REQUIRED)" #elseif os(macOS) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift index ddb5d61259..e48933a824 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/ASFDeviceInfo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @MainActor struct ASFDeviceInfo: ASFDeviceBehavior { @@ -28,9 +28,13 @@ struct ASFDeviceInfo: ASFDeviceBehavior { var type: String { var systemInfo = utsname() uname(&systemInfo) - return String(bytes: Data(bytes: &systemInfo.machine, - count: Int(_SYS_NAMELEN)), - encoding: .utf8) ?? DeviceInfo.current.hostName + return String( + bytes: Data( + bytes: &systemInfo.machine, + count: Int(_SYS_NAMELEN) + ), + encoding: .utf8 + ) ?? DeviceInfo.current.hostName } var platform: String { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift index c5c688972b..c499d5b35c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/AdvancedSecurityBehavior.swift @@ -9,10 +9,12 @@ import Foundation protocol AdvancedSecurityBehavior { - func userContextData(for username: String, - deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior, - configuration: UserPoolConfigurationData) throws -> String + func userContextData( + for username: String, + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior, + configuration: UserPoolConfigurationData + ) throws -> String } protocol ASFDeviceBehavior: Sendable { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift index 8949aee102..89bd152bd8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF+KeyChain.swift @@ -11,7 +11,8 @@ extension CognitoUserPoolASF { static func asfDeviceID( for username: String, - credentialStoreClient: CredentialStoreStateBehavior) async throws -> String { + credentialStoreClient: CredentialStoreStateBehavior + ) async throws -> String { let deviceMetaDataType = CredentialStoreDataType.deviceMetadata(username: username) let data = try? await credentialStoreClient.fetchData(type: deviceMetaDataType) if case .deviceMetadata(let metadata, _) = data, @@ -29,10 +30,12 @@ extension CognitoUserPoolASF { return uuid } - static func encodedContext(username: String, - asfDeviceId: String, - asfClient: AdvancedSecurityBehavior, - userPoolConfiguration: UserPoolConfigurationData) async -> String? { + static func encodedContext( + username: String, + asfDeviceId: String, + asfClient: AdvancedSecurityBehavior, + userPoolConfiguration: UserPoolConfigurationData + ) async -> String? { let deviceInfo: ASFDeviceBehavior = await ASFDeviceInfo(id: asfDeviceId) let appInfo: ASFAppInfoBehavior = ASFAppInfo() @@ -41,7 +44,8 @@ extension CognitoUserPoolASF { for: username, deviceInfo: deviceInfo, appInfo: appInfo, - configuration: userPoolConfiguration) + configuration: userPoolConfiguration + ) } catch { // Ignore the error and add nil as context data return nil diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift index 4d9568f270..a6cc64bc7e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation struct CognitoUserPoolASF: AdvancedSecurityBehavior { @@ -27,23 +27,31 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { static let phoneTypeKey = "PhoneType" static let asfVersion = "IOS20171114" - func userContextData(for username: String = "unknown", - deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior, - configuration: UserPoolConfigurationData) throws -> String { + func userContextData( + for username: String = "unknown", + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior, + configuration: UserPoolConfigurationData + ) throws -> String { let contextData = prepareUserContextData(deviceInfo: deviceInfo, appInfo: appInfo) - let payload = try prepareJsonPayload(username: username, - contextData: contextData, - userPoolId: configuration.poolId) - let signature = try calculateSecretHash(contextJson: payload, - clientId: configuration.clientId) + let payload = try prepareJsonPayload( + username: username, + contextData: contextData, + userPoolId: configuration.poolId + ) + let signature = try calculateSecretHash( + contextJson: payload, + clientId: configuration.clientId + ) let result = try prepareJsonResult(payload: payload, signature: signature) return result } - func prepareUserContextData(deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior) -> [String: String] { + func prepareUserContextData( + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior + ) -> [String: String] { var build = "release" #if DEBUG build = "debug" @@ -73,10 +81,12 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { return contextData } - func prepareJsonPayload(username: String, - contextData: [String: String], - userPoolId: String) throws -> String { - let timestamp = String(format: "%lli", floor(Date().timeIntervalSince1970 * 1000)) + func prepareJsonPayload( + username: String, + contextData: [String: String], + userPoolId: String + ) throws -> String { + let timestamp = String(format: "%lli", floor(Date().timeIntervalSince1970 * 1_000)) let payload = [ "contextData": contextData, "username": username, @@ -92,8 +102,8 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { func timeZoneOffet(seconds: Int = TimeZone.current.secondsFromGMT()) -> String { - let hours = seconds/3600 - let minutes = abs(seconds/60) % 60 + let hours = seconds / 3_600 + let minutes = abs(seconds / 60) % 60 return String(format: "%+.2d:%.2d", hours, minutes) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift index fdcfbf9385..6e85d86f1f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift @@ -7,11 +7,11 @@ import Foundation @_spi(InternalAmplifyConfiguration) import Amplify +import AWSClientRuntime import AWSCognitoIdentity import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSClientRuntime @_spi(PluginHTTPClientEngine) import InternalAmplifyCredentials @_spi(InternalHttpEngineProxy) import AWSPluginsCore @@ -33,13 +33,16 @@ extension AWSCognitoAuthPlugin { } else { throw PluginError.pluginConfigurationError( AuthPluginErrorConstants.decodeConfigurationError.errorDescription, - AuthPluginErrorConstants.decodeConfigurationError.recoverySuggestion) + AuthPluginErrorConstants.decodeConfigurationError.recoverySuggestion + ) } let credentialStoreResolver = CredentialStoreState.Resolver().eraseToAnyResolver() let credentialEnvironment = credentialStoreEnvironment(authConfiguration: authConfiguration) - let credentialStoreMachine = StateMachine(resolver: credentialStoreResolver, - environment: credentialEnvironment) + let credentialStoreMachine = StateMachine( + resolver: credentialStoreResolver, + environment: credentialEnvironment + ) let credentialsClient = CredentialStoreOperationClient( credentialStoreStateMachine: credentialStoreMachine) @@ -54,23 +57,28 @@ extension AWSCognitoAuthPlugin { let hubEventHandler = AuthHubEventHandler() let analyticsHandler = try UserPoolAnalytics( authConfiguration.getUserPoolConfiguration(), - credentialStoreEnvironment: credentialEnvironment.credentialStoreEnvironment) - - configure(authConfiguration: authConfiguration, - authEnvironment: authEnvironment, - authStateMachine: authStateMachine, - credentialStoreStateMachine: credentialStoreMachine, - hubEventHandler: hubEventHandler, - analyticsHandler: analyticsHandler) + credentialStoreEnvironment: credentialEnvironment.credentialStoreEnvironment + ) + + configure( + authConfiguration: authConfiguration, + authEnvironment: authEnvironment, + authStateMachine: authStateMachine, + credentialStoreStateMachine: credentialStoreMachine, + hubEventHandler: hubEventHandler, + analyticsHandler: analyticsHandler + ) } - func configure(authConfiguration: AuthConfiguration, - authEnvironment: AuthEnvironment, - authStateMachine: AuthStateMachine, - credentialStoreStateMachine: CredentialStoreStateMachine, - hubEventHandler: AuthHubEventBehavior, - analyticsHandler: UserPoolAnalyticsBehavior, - queue: OperationQueue = OperationQueue()) { + func configure( + authConfiguration: AuthConfiguration, + authEnvironment: AuthEnvironment, + authStateMachine: AuthStateMachine, + credentialStoreStateMachine: CredentialStoreStateMachine, + hubEventHandler: AuthHubEventBehavior, + analyticsHandler: UserPoolAnalyticsBehavior, + queue: OperationQueue = OperationQueue() + ) { self.authConfiguration = authConfiguration self.queue = queue @@ -78,11 +86,11 @@ extension AWSCognitoAuthPlugin { self.authEnvironment = authEnvironment self.authStateMachine = authStateMachine self.credentialStoreStateMachine = credentialStoreStateMachine - self.internalConfigure() - self.listenToStateMachineChanges() + internalConfigure() + listenToStateMachineChanges() self.hubEventHandler = hubEventHandler self.analyticsHandler = analyticsHandler - self.taskQueue = TaskQueue() + taskQueue = TaskQueue() } // MARK: - Configure Helpers @@ -94,7 +102,7 @@ extension AWSCognitoAuthPlugin { serviceSpecific: .init(endpointResolver: userPoolConfig.endpoint?.resolver) ) - if var httpClientEngineProxy = httpClientEngineProxy { + if var httpClientEngineProxy { httpClientEngineProxy.target = baseClientEngine(for: configuration) configuration.httpClientEngine = UserAgentSettingClientEngine( target: httpClientEngineProxy @@ -201,7 +209,8 @@ extension AWSCognitoAuthPlugin { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: nil, credentialsClient: credentialsClient, - logger: log) + logger: log + ) case .identityPools(let identityPoolConfigurationData): let authorizationEnvironment = authorizationEnvironment( @@ -213,10 +222,13 @@ extension AWSCognitoAuthPlugin { authenticationEnvironment: nil, authorizationEnvironment: authorizationEnvironment, credentialsClient: credentialsClient, - logger: log) + logger: log + ) - case .userPoolsAndIdentityPools(let userPoolConfigurationData, - let identityPoolConfigurationData): + case .userPoolsAndIdentityPools( + let userPoolConfigurationData, + let identityPoolConfigurationData + ): let authenticationEnvironment = authenticationEnvironment( userPoolConfigData: userPoolConfigurationData) let authorizationEnvironment = authorizationEnvironment( @@ -228,39 +240,49 @@ extension AWSCognitoAuthPlugin { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: authorizationEnvironment, credentialsClient: credentialsClient, - logger: log) + logger: log + ) } } private func authenticationEnvironment(userPoolConfigData: UserPoolConfigurationData) -> AuthenticationEnvironment { - let srpAuthEnvironment = BasicSRPAuthEnvironment(userPoolConfiguration: userPoolConfigData, - cognitoUserPoolFactory: makeUserPool) + let srpAuthEnvironment = BasicSRPAuthEnvironment( + userPoolConfiguration: userPoolConfigData, + cognitoUserPoolFactory: makeUserPool + ) let srpSignInEnvironment = BasicSRPSignInEnvironment(srpAuthEnvironment: srpAuthEnvironment) let userPoolEnvironment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfigData, cognitoUserPoolFactory: makeUserPool, cognitoUserPoolASFFactory: makeCognitoASF, - cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics + ) let hostedUIEnvironment = hostedUIEnvironment(userPoolConfigData) - return BasicAuthenticationEnvironment(srpSignInEnvironment: srpSignInEnvironment, - userPoolEnvironment: userPoolEnvironment, - hostedUIEnvironment: hostedUIEnvironment) + return BasicAuthenticationEnvironment( + srpSignInEnvironment: srpSignInEnvironment, + userPoolEnvironment: userPoolEnvironment, + hostedUIEnvironment: hostedUIEnvironment + ) } private func hostedUIEnvironment(_ configuration: UserPoolConfigurationData) -> HostedUIEnvironment? { guard let hostedUIConfig = configuration.hostedUIConfig else { return nil } - return BasicHostedUIEnvironment(configuration: hostedUIConfig, - hostedUISessionFactory: makeHostedUISession, - urlSessionFactory: makeURLSession, - randomStringFactory: makeRandomString) + return BasicHostedUIEnvironment( + configuration: hostedUIConfig, + hostedUISessionFactory: makeHostedUISession, + urlSessionFactory: makeURLSession, + randomStringFactory: makeRandomString + ) } private func authorizationEnvironment(identityPoolConfigData: IdentityPoolConfigurationData) -> AuthorizationEnvironment { - BasicAuthorizationEnvironment(identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: makeIdentityClient) + BasicAuthorizationEnvironment( + identityPoolConfiguration: identityPoolConfigData, + cognitoIdentityFactory: makeIdentityClient + ) } private func credentialStoreEnvironment(authConfiguration: AuthConfiguration) -> CredentialEnvironment { @@ -278,8 +300,9 @@ extension AWSCognitoAuthPlugin { let operation = AuthConfigureOperation( request: request, authStateMachine: authStateMachine, - credentialStoreStateMachine: credentialStoreStateMachine) - self.queue.addOperation(operation) + credentialStoreStateMachine: credentialStoreStateMachine + ) + queue.addOperation(operation) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift index 37bbb02b0c..4876c75bde 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+EscapeHatch.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentity import AWSCognitoIdentityProvider +import Foundation public extension AWSCognitoAuthPlugin { @@ -37,13 +37,15 @@ public extension AWSCognitoAuthPlugin { let identityPoolClient = identityPoolClient as? CognitoIdentityClient { - service = .userPoolAndIdentityPool(userPoolClient, - identityPoolClient) + service = .userPoolAndIdentityPool( + userPoolClient, + identityPoolClient + ) } case .none: service = nil } - guard let service = service else { + guard let service else { fatalError(""" Could not find any escape hatch, invoke Amplify configuration before accessing the escape hatch. diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift index e617062e5c..8d7a214b41 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginExtension.swift @@ -5,15 +5,15 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials -import Foundation import ClientRuntime +import Foundation +@_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials -extension AWSCognitoAuthPlugin { +public extension AWSCognitoAuthPlugin { @_spi(InternalAmplifyPluginExtension) - public func add(pluginExtension: AWSPluginExtension) { + func add(pluginExtension: AWSPluginExtension) { if let customHttpEngine = pluginExtension as? HttpClientEngineProxy { - self.httpClientEngineProxy = customHttpEngine + httpClientEngineProxy = customHttpEngine } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift index 6155f93d27..cc31fd7e2c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+PluginSpecificAPI.swift @@ -36,7 +36,8 @@ public extension AWSCognitoAuthPlugin { func fetchMFAPreference() async throws -> UserMFAPreference { let task = FetchMFAPreferenceTask( authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await task.value } @@ -48,7 +49,8 @@ public extension AWSCognitoAuthPlugin { smsPreference: sms, totpPreference: totp, authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await task.value } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift index f32209ba9c..858b848202 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation public final class AWSCognitoAuthPlugin: AWSCognitoAuthPluginBehavior { @@ -36,7 +36,7 @@ public final class AWSCognitoAuthPlugin: AWSCognitoAuthPluginBehavior { let networkPreferences: AWSCognitoNetworkPreferences? @_spi(InternalAmplifyConfiguration) - internal(set) public var jsonConfiguration: JSONValue? + public internal(set) var jsonConfiguration: JSONValue? /// The unique key of the plugin within the auth category. public var key: PluginKey { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift index ffc07ce349..be382f8a52 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPluginBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AWSCognitoAuthPluginBehavior: AuthCategoryPlugin { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift index e56295b478..2e4bc9508e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Authentication/SignInComplete.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify import Foundation diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift index 4d1388d7ef..e2264e3c29 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthConfiguration.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct InitializeAuthConfiguration: Action { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift index 4b5574ddc6..a5f47425f5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthenticationConfiguration.swift @@ -14,8 +14,10 @@ struct InitializeAuthenticationConfiguration: Action { let configuration: AuthConfiguration let storedCredentials: AmplifyCredentials - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let event = AuthenticationEvent(eventType: .configure(configuration, storedCredentials)) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift index 4fd3208bc9..20aacc9ac6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/InitializeAuthorizationConfiguration.swift @@ -13,16 +13,17 @@ struct InitializeAuthorizationConfiguration: Action { let storedCredentials: AmplifyCredentials - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { // ATM this is a no-op action logVerbose("\(#fileID) Starting execution", environment: environment) - var event: AuthorizationEvent - switch storedCredentials { + var event = switch storedCredentials { case .noCredentials: - event = AuthorizationEvent(eventType: .configure) + AuthorizationEvent(eventType: .configure) default: - event = AuthorizationEvent(eventType: .cachedCredentialsAvailable(storedCredentials)) + AuthorizationEvent(eventType: .cachedCredentialsAvailable(storedCredentials)) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift index 9d4f8085df..4b1af4c2ae 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Configuration/ValidateCredentialsAndConfiguration.swift @@ -21,11 +21,15 @@ struct ValidateCredentialsAndConfiguration: Action { var event: StateMachineEvent switch authConfiguration { case .identityPools: - event = AuthEvent(eventType: .configureAuthorization(authConfiguration, - cachedCredentials)) + event = AuthEvent(eventType: .configureAuthorization( + authConfiguration, + cachedCredentials + )) default: - event = AuthEvent(eventType: .configureAuthentication(authConfiguration, - cachedCredentials)) + event = AuthEvent(eventType: .configureAuthentication( + authConfiguration, + cachedCredentials + )) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift index 3be32348bf..9890df37af 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/ClearCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct ClearCredentialStore: Action { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift index 40fad5f103..cac9300138 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/LoadCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct LoadCredentialStore: Action { @@ -27,8 +27,10 @@ struct LoadCredentialStore: Action { return } - logVerbose("\(#fileID) Retreiving credential \(credentialStoreType)", - environment: environment) + logVerbose( + "\(#fileID) Retreiving credential \(credentialStoreType)", + environment: environment + ) let credentialStoreEnvironment = credentialEnvironment.credentialStoreEnvironment let amplifyCredentialStore = credentialStoreEnvironment.amplifyCredentialStoreFactory() diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift index 6017f71215..311f8e22c5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/MigrateLegacyCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @_spi(KeychainStore) import AWSPluginsCore // swiftlint:disable identifier_name @@ -57,25 +57,34 @@ struct MigrateLegacyCredentialStore: Action { var identityId: String? var awsCredentials: AuthAWSCognitoCredentials? - migrateDeviceDetails(from: credentialStoreEnvironment, - with: authConfiguration) - let userPoolTokens = try? getUserPoolTokens(from: credentialStoreEnvironment, - with: authConfiguration) + migrateDeviceDetails( + from: credentialStoreEnvironment, + with: authConfiguration + ) + let userPoolTokens = try? getUserPoolTokens( + from: credentialStoreEnvironment, + with: authConfiguration + ) // IdentityId and AWSCredentials should exist together - if let (storedIdentityId, - storedAWSCredentials) = try? getIdentityIdAndAWSCredentials( - from: credentialStoreEnvironment, - with: authConfiguration) { + if let ( + storedIdentityId, + storedAWSCredentials + ) = try? getIdentityIdAndAWSCredentials( + from: credentialStoreEnvironment, + with: authConfiguration + ) { identityId = storedIdentityId awsCredentials = storedAWSCredentials } let loginsMap = getCachedLoginMaps(from: credentialStoreEnvironment) - let signInMethod = (try? getSignInMethod(from: credentialStoreEnvironment, - with: authConfiguration)) ?? .apiBased(.userSRP) + let signInMethod = (try? getSignInMethod( + from: credentialStoreEnvironment, + with: authConfiguration + )) ?? .apiBased(.userSRP) do { - if let identityId = identityId, - let awsCredentials = awsCredentials, + if let identityId, + let awsCredentials, userPoolTokens == nil { if !loginsMap.isEmpty, @@ -86,37 +95,42 @@ struct MigrateLegacyCredentialStore: Action { let credentials = AmplifyCredentials.identityPoolWithFederation( federatedToken: .init(token: providerToken, provider: provider), identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) try amplifyCredentialStore.saveCredential(credentials) } else { logVerbose("\(#fileID) Guest user", environment: environment) let credentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) try amplifyCredentialStore.saveCredential(credentials) } - } else if let identityId = identityId, - let awsCredentials = awsCredentials, - let userPoolTokens = userPoolTokens { + } else if let identityId, + let awsCredentials, + let userPoolTokens { logVerbose("\(#fileID) User pool with identity pool", environment: environment) let signedInData = SignedInData( signedInDate: Date.distantPast, signInMethod: signInMethod, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) let credentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) try amplifyCredentialStore.saveCredential(credentials) - } else if let userPoolTokens = userPoolTokens { + } else if let userPoolTokens { logVerbose("\(#fileID) Only user pool", environment: environment) let signedInData = SignedInData( signedInDate: Date.distantPast, signInMethod: signInMethod, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) let credentials = AmplifyCredentials.userPoolOnly(signedInData: signedInData) try amplifyCredentialStore.saveCredential(credentials) } @@ -139,7 +153,8 @@ struct MigrateLegacyCredentialStore: Action { private func migrateDeviceDetails( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) { + with authConfiguration: AuthConfiguration + ) { guard let bundleIdentifier = Bundle.main.bundleIdentifier, let userPoolConfig = authConfiguration.getUserPoolConfiguration() else { @@ -187,23 +202,26 @@ struct MigrateLegacyCredentialStore: Action { ) let amplifyCredentialStore = credentialStoreEnvironment.amplifyCredentialStoreFactory() - if let deviceId = deviceId, - let deviceSecret = deviceSecret, - let deviceGroup = deviceGroup { - let deviceMetaData = DeviceMetadata.metadata(.init(deviceKey: deviceId, - deviceGroupKey: deviceGroup, - deviceSecret: deviceSecret)) + if let deviceId, + let deviceSecret, + let deviceGroup { + let deviceMetaData = DeviceMetadata.metadata(.init( + deviceKey: deviceId, + deviceGroupKey: deviceGroup, + deviceSecret: deviceSecret + )) try? amplifyCredentialStore.saveDevice(deviceMetaData, for: currentUsername) } - if let asfDeviceId = asfDeviceId { + if let asfDeviceId { try? amplifyCredentialStore.saveASFDevice(asfDeviceId, for: currentUsername) } } private func getUserPoolTokens( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) throws -> AWSCognitoUserPoolTokens { + with authConfiguration: AuthConfiguration + ) throws -> AWSCognitoUserPoolTokens { guard let bundleIdentifier = Bundle.main.bundleIdentifier, let userPoolConfig = authConfiguration.getUserPoolConfiguration() @@ -251,10 +269,12 @@ struct MigrateLegacyCredentialStore: Action { // If the token expiration can't be converted to a date, chose a date in the past let pastDate = Date.init(timeIntervalSince1970: 0) let tokenExpiration = dateFormatter().date(from: tokenExpirationString) ?? pastDate - return AWSCognitoUserPoolTokens(idToken: idToken, - accessToken: accessToken, - refreshToken: refreshToken, - expiration: tokenExpiration) + return AWSCognitoUserPoolTokens( + idToken: idToken, + accessToken: accessToken, + refreshToken: refreshToken, + expiration: tokenExpiration + ) } private func getCachedLoginMaps( @@ -276,7 +296,8 @@ struct MigrateLegacyCredentialStore: Action { private func getSignInMethod( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) throws -> SignInMethod { + with authConfiguration: AuthConfiguration + ) throws -> SignInMethod { let serviceKey = "\(String.init(describing: Bundle.main.bundleIdentifier)).AWSMobileClient" let legacyKeychainStore = credentialStoreEnvironment.legacyKeychainStoreFactory(serviceKey) @@ -287,32 +308,41 @@ struct MigrateLegacyCredentialStore: Action { case "hostedUI": let userPoolConfig = authConfiguration.getUserPoolConfiguration() let scopes = userPoolConfig?.hostedUIConfig?.oauth.scopes - let provider = HostedUIProviderInfo(authProvider: nil, - idpIdentifier: nil) - return .hostedUI(.init(scopes: scopes ?? [], - providerInfo: provider, - presentationAnchor: nil, - preferPrivateSession: false)) + let provider = HostedUIProviderInfo( + authProvider: nil, + idpIdentifier: nil + ) + return .hostedUI(.init( + scopes: scopes ?? [], + providerInfo: provider, + presentationAnchor: nil, + preferPrivateSession: false + )) default: return .apiBased(.userSRP) } } - private func userPoolNamespace(userPoolConfig: UserPoolConfigurationData, - for key: String) -> String { + private func userPoolNamespace( + userPoolConfig: UserPoolConfigurationData, + for key: String + ) -> String { return "\(userPoolConfig.clientId).\(key)" } - private func userPoolNamespace(withUser userName: String, - userPoolConfig: UserPoolConfigurationData, - for key: String) -> String { + private func userPoolNamespace( + withUser userName: String, + userPoolConfig: UserPoolConfigurationData, + for key: String + ) -> String { return "\(userPoolConfig.poolId).\(userName).\(key)" } private func getIdentityIdAndAWSCredentials( from credentialStoreEnvironment: CredentialStoreEnvironment, - with authConfiguration: AuthConfiguration) throws + with authConfiguration: AuthConfiguration + ) throws -> (identityId: String, awsCredentials: AuthAWSCognitoCredentials) { guard let bundleIdentifier = Bundle.main.bundleIdentifier, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift index 2b8f856743..dcc28465e3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/CredentialStore/StoreCredentials.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation struct StoreCredentials: Action { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift index c51bc24770..87bdb58834 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/DeleteUser.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct DeleteUser: Action { @@ -50,11 +50,12 @@ struct DeleteUser: Action { } catch let error as AuthErrorConvertible { event = DeleteUserEvent(eventType: .throwError(error.authError)) logVerbose("\(#fileID) Delete User failed \(error)", environment: environment) - } catch let error { + } catch { let authError = AuthError.service( "Delete user failed with service error", AmplifyErrorMessages.reportBugToAWS(), - error) + error + ) event = DeleteUserEvent(eventType: .throwError(authError)) logVerbose("\(#fileID) Delete user failed \(error)", environment: environment) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift index a604270478..2bb868a626 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/DeleteUser/InformUserDeletedAndSignedOut.swift @@ -19,12 +19,11 @@ struct InformUserDeletedAndSignedOut: Action { logVerbose("\(#fileID) Starting execution", environment: environment) - let event: DeleteUserEvent - switch result { + let event = switch result { case .success(let signedOutData): - event = DeleteUserEvent(eventType: .userSignedOutAndDeleted(signedOutData)) + DeleteUserEvent(eventType: .userSignedOutAndDeleted(signedOutData)) case .failure(let error): - event = DeleteUserEvent(eventType: .throwError(error)) + DeleteUserEvent(eventType: .throwError(error)) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift index 1624c9083c..425d1d7c41 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Federation/InitializeFederationToIdentityPool.swift @@ -19,11 +19,12 @@ struct InitializeFederationToIdentityPool: Action { let authProviderLoginsMap = AuthProviderLoginsMap(federatedToken: federatedToken) let event: FetchAuthSessionEvent - if let developerProvidedIdentityId = developerProvidedIdentityId { + if let developerProvidedIdentityId { event = FetchAuthSessionEvent.init( eventType: .fetchAWSCredentials( developerProvidedIdentityId, - authProviderLoginsMap)) + authProviderLoginsMap + )) } else { event = FetchAuthSessionEvent.init( eventType: .fetchAuthenticatedIdentityID(authProviderLoginsMap)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift index 898806c1e4..d9927aed9d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/AWSCredentials/FetchAuthAWSCredentials.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentity -import Foundation import Amplify +import AWSCognitoIdentity import ClientRuntime +import Foundation struct FetchAuthAWSCredentials: Action { @@ -32,8 +32,10 @@ struct FetchAuthAWSCredentials: Action { return } - let getCredentialsInput = GetCredentialsForIdentityInput(identityId: identityID, - logins: loginsMap) + let getCredentialsInput = GetCredentialsForIdentityInput( + identityId: identityID, + logins: loginsMap + ) do { let response = try await client.getCredentialsForIdentity(input: getCredentialsInput) @@ -54,10 +56,12 @@ struct FetchAuthAWSCredentials: Action { logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) return } - let awsCognitoCredentials = AuthAWSCognitoCredentials(accessKeyId: accessKey, - secretAccessKey: secretKey, - sessionToken: sessionKey, - expiration: expiration) + let awsCognitoCredentials = AuthAWSCognitoCredentials( + accessKeyId: accessKey, + secretAccessKey: secretKey, + sessionToken: sessionKey, + expiration: expiration + ) let event = FetchAuthSessionEvent( eventType: .fetchedAWSCredentials(identityId, awsCognitoCredentials)) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift index 97ffabda08..bf21a6cd88 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift @@ -6,8 +6,8 @@ // import AWSCognitoIdentity -import Foundation import ClientRuntime +import Foundation struct FetchAuthIdentityId: Action { @@ -19,8 +19,10 @@ struct FetchAuthIdentityId: Action { self.loginsMap = loginsMap } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) @@ -37,7 +39,8 @@ struct FetchAuthIdentityId: Action { let getIdInput = GetIdInput( identityPoolId: authZEnvironment.identityPoolConfiguration.poolId, - logins: loginsMap) + logins: loginsMap + ) do { let response = try await client.getId(input: getIdInput) @@ -52,14 +55,15 @@ struct FetchAuthIdentityId: Action { await dispatcher.send(event) } catch { - let event: FetchAuthSessionEvent - if isNotAuthorizedError(error) { - event = FetchAuthSessionEvent(eventType: .throwError(.notAuthorized)) + let event = if isNotAuthorizedError(error) { + FetchAuthSessionEvent(eventType: .throwError(.notAuthorized)) } else { - event = FetchAuthSessionEvent(eventType: .throwError(.service(error))) + FetchAuthSessionEvent(eventType: .throwError(.service(error))) } - logVerbose("\(#fileID) Sending event \(event.type)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event.type)", + environment: environment + ) await dispatcher.send(event) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift index bca1e5e6d0..a4a1bead9e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import Foundation struct InformSessionError: Action { @@ -19,17 +19,16 @@ struct InformSessionError: Action { func execute(withDispatcher dispatcher: EventDispatcher, environment: Environment) async { logVerbose("\(#fileID) Starting execution", environment: environment) - var event: AuthorizationEvent - switch error { + var event: AuthorizationEvent = switch error { case .service(let serviceError): if isNotAuthorizedError(serviceError) { - event = .init(eventType: .throwError( + .init(eventType: .throwError( .sessionExpired(error: serviceError))) } else { - event = .init(eventType: .receivedSessionError(error)) + .init(eventType: .receivedSessionError(error)) } default: - event = .init(eventType: .receivedSessionError(error)) + .init(eventType: .receivedSessionError(error)) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift index 09ecfed4b2..83b57a5ff8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchAuthSessionWithUserPool.swift @@ -27,9 +27,11 @@ struct InitializeFetchAuthSessionWithUserPool: Action { case .userPoolsAndIdentityPools(let userPoolData, _): let region = userPoolData.region let poolId = userPoolData.poolId - let loginsMapProvider = CognitoUserPoolLoginsMap(idToken: tokens.idToken, - region: region, - poolId: poolId) + let loginsMapProvider = CognitoUserPoolLoginsMap( + idToken: tokens.idToken, + region: region, + poolId: poolId + ) event = .init(eventType: .fetchAuthenticatedIdentityID(loginsMapProvider)) default: event = .init(eventType: .throwError(.noUserPool)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift index 619e2586ff..e9e34495f2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InitializeFetchUnAuthSession.swift @@ -17,13 +17,12 @@ struct InitializeFetchUnAuthSession: Action { logVerbose("\(#fileID) Starting execution", environment: environment) let configuration = (environment as? AuthEnvironment)?.configuration - let event: FetchAuthSessionEvent - switch configuration { + let event: FetchAuthSessionEvent = switch configuration { case .userPools: // If only user pool is configured then we do not have any unauthsession - event = .init(eventType: .throwError(.noIdentityPool)) + .init(eventType: .throwError(.noIdentityPool)) default: - event = .init(eventType: .fetchUnAuthIdentityID) + .init(eventType: .fetchUnAuthIdentityID) } logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift index df971f223f..3f9fdda072 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/Persistence/ConfigureAuthentication.swift @@ -32,8 +32,10 @@ struct ConfigureAuthentication: Action { logVerbose("\(#fileID) Sending event \(authenticationEvent.type)", environment: environment) await dispatcher.send(authenticationEvent) - let authStateEvent = AuthEvent(eventType: .authenticationConfigured(configuration, - storedCredentials)) + let authStateEvent = AuthEvent(eventType: .authenticationConfigured( + configuration, + storedCredentials + )) logVerbose("\(#fileID) Sending event \(authStateEvent.type)", environment: environment) await dispatcher.send(authStateEvent) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift index 43c36c2cb9..10dba6ba59 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/InitializeRefreshSession.swift @@ -40,16 +40,20 @@ struct InitializeRefreshSession: Action { return } let tokens = signedInData.cognitoUserPoolTokens - let provider = CognitoUserPoolLoginsMap(idToken: tokens.idToken, - region: config.region, - poolId: config.poolId) + let provider = CognitoUserPoolLoginsMap( + idToken: tokens.idToken, + region: config.region, + poolId: config.poolId + ) if isForceRefresh || tokens.doesExpire(in: AmplifyCredentials.expiryBufferInSeconds) { event = .init(eventType: .refreshCognitoUserPoolWithIdentityId(signedInData, identityID)) } else { - event = .init(eventType: .refreshAWSCredentialsWithUserPool(identityID, - signedInData, - provider)) + event = .init(eventType: .refreshAWSCredentialsWithUserPool( + identityID, + signedInData, + provider + )) } case .noCredentials: event = .init(eventType: .throwError(.noCredentialsToRefresh)) @@ -74,7 +78,7 @@ extension InitializeRefreshSession: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { [ "identifier": identifier, - "isForceRefresh": isForceRefresh ? "true": "false", + "isForceRefresh": isForceRefresh ? "true" : "false", "existingCredentials": existingCredentials.debugDescription ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift index a5d180b876..382b7b0fca 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/RefreshAuthorizationSession/UserPool/RefreshUserPoolTokens.swift @@ -6,10 +6,10 @@ // import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider -import Foundation +import AWSPluginsCore import ClientRuntime +import Foundation struct RefreshUserPoolTokens: Action { @@ -35,11 +35,13 @@ struct RefreshUserPoolTokens: Action { let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: existingSignedIndata.username, - with: environment) + with: environment + ) let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: existingSignedIndata.username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let input = await InitiateAuthInput.refreshAuthInput( username: existingSignedIndata.username, @@ -47,7 +49,8 @@ struct RefreshUserPoolTokens: Action { clientMetadata: [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) logVerbose("\(#fileID) Starting initiate auth refresh token", environment: environment) @@ -75,14 +78,16 @@ struct RefreshUserPoolTokens: Action { let signedInData = SignedInData( signedInDate: existingSignedIndata.signedInDate, signInMethod: existingSignedIndata.signInMethod, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) let event: RefreshSessionEvent if ((environment as? AuthEnvironment)?.identityPoolConfigData) != nil { let provider = CognitoUserPoolLoginsMap( idToken: idToken, region: config.region, - poolId: config.poolId) + poolId: config.poolId + ) event = .init(eventType: .refreshIdentityInfo(signedInData, provider)) } else { event = .init(eventType: .refreshedCognitoUserPool(signedInData)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift index 22da95affb..04232dc18f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/ConfirmDevice.swift @@ -34,7 +34,8 @@ struct ConfirmDevice: Action { let passwordVerifier = srpClient.generateDevicePasswordVerifier( deviceGroupKey: deviceMetadata.deviceGroupKey, deviceKey: deviceMetadata.deviceKey, - password: deviceMetadata.deviceSecret) + password: deviceMetadata.deviceSecret + ) let deviceName = await DeviceInfo.current.name @@ -42,26 +43,34 @@ struct ConfirmDevice: Action { let base64EncodedSalt = passwordVerifier.salt.base64EncodedString() let verifier = CognitoIdentityProviderClientTypes.DeviceSecretVerifierConfigType( passwordVerifier: base64EncodedVerifier, - salt: base64EncodedSalt) + salt: base64EncodedSalt + ) let input = ConfirmDeviceInput( accessToken: signedInData.cognitoUserPoolTokens.accessToken, deviceKey: deviceMetadata.deviceKey, deviceName: deviceName, - deviceSecretVerifierConfig: verifier) + deviceSecretVerifierConfig: verifier + ) let response = try await client.confirmDevice(input: input) - logVerbose("Successfully completed device confirmation with result \(response)", - environment: environment) + logVerbose( + "Successfully completed device confirmation with result \(response)", + environment: environment + ) // Save the device metadata to keychain let credentialStoreClient = (environment as? AuthEnvironment)?.credentialsClient _ = try await credentialStoreClient?.storeData( data: .deviceMetadata(signedInData.deviceMetadata, signedInData.username)) - logVerbose("Successfully stored the device metadata in the keychain ", - environment: environment) + logVerbose( + "Successfully stored the device metadata in the keychain ", + environment: environment + ) } catch { - logError("Failed to confirm the device \(error)", - environment: environment) + logError( + "Failed to confirm the device \(error)", + environment: environment + ) } let event = SignInEvent(eventType: .finalizeSignIn(signedInData)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift index ff1c572f06..239aec3d95 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/CustomSignIn/InitiateCustomAuth.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct InitiateCustomAuth: Action { let identifier = "InitiateCustomAuth" @@ -16,32 +16,40 @@ struct InitiateCustomAuth: Action { let clientMetadata: [String: String] let deviceMetadata: DeviceMetadata - init(username: String, - clientMetadata: [String: String], - deviceMetadata: DeviceMetadata) { + init( + username: String, + clientMetadata: [String: String], + deviceMetadata: DeviceMetadata + ) { self.username = username self.clientMetadata = clientMetadata self.deviceMetadata = deviceMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { let userPoolEnv = try environment.userPoolEnvironment() let authEnv = try environment.authEnvironment() let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let request = await InitiateAuthInput.customAuth( username: username, clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: userPoolEnv) + environment: userPoolEnv + ) - let responseEvent = try await sendRequest(request: request, - environment: userPoolEnv) + let responseEvent = try await sendRequest( + request: request, + environment: userPoolEnv + ) logVerbose("\(#fileID) Sending event \(responseEvent)", environment: environment) await dispatcher.send(responseEvent) @@ -60,16 +68,20 @@ struct InitiateCustomAuth: Action { } - private func sendRequest(request: InitiateAuthInput, - environment: UserPoolEnvironment) async throws -> StateMachineEvent { + private func sendRequest( + request: InitiateAuthInput, + environment: UserPoolEnvironment + ) async throws -> StateMachineEvent { let cognitoClient = try environment.cognitoUserPoolFactory() logVerbose("\(#fileID) Starting execution", environment: environment) let response = try await cognitoClient.initiateAuth(input: request) - return try UserPoolSignInHelper.parseResponse(response, - for: username, - signInMethod: .apiBased(.customWithoutSRP)) + return try UserPoolSignInHelper.parseResponse( + response, + for: username, + signInMethod: .apiBased(.customWithoutSRP) + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift index fde6beec31..182989f480 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/InitiateAuthDeviceSRP.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation -import CryptoKit import AWSCognitoIdentityProvider +import CryptoKit +import Foundation struct InitiateAuthDeviceSRP: Action { let identifier = "InitiateAuthDeviceSRP" @@ -16,8 +16,10 @@ struct InitiateAuthDeviceSRP: Action { let username: String let authResponse: SignInResponseBehavior - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { @@ -31,11 +33,13 @@ struct InitiateAuthDeviceSRP: Action { // Get device metadata let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) let srpStateData = SRPStateData( username: username, @@ -43,7 +47,8 @@ struct InitiateAuthDeviceSRP: Action { NHexValue: nHexValue, gHexValue: gHexValue, srpKeyPair: srpKeyPair, - clientTimestamp: Date()) + clientTimestamp: Date() + ) let request = await RespondToAuthChallengeInput.deviceSRP( username: username, @@ -51,7 +56,8 @@ struct InitiateAuthDeviceSRP: Action { deviceMetadata: deviceMetadata, asfDeviceId: asfDeviceId, session: authResponse.session, - publicHexValue: srpKeyPair.publicKeyHexValue) + publicHexValue: srpKeyPair.publicKeyHexValue + ) let client = try userPoolEnv.cognitoUserPoolFactory() @@ -84,7 +90,8 @@ struct InitiateAuthDeviceSRP: Action { func parseResponse( _ response: SignInResponseBehavior, - with stateData: SRPStateData) -> StateMachineEvent { + with stateData: SRPStateData + ) -> StateMachineEvent { guard case .devicePasswordVerifier = response.challengeName else { let message = """ Unsupported challenge response during DeviceSRPAuth diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift index b797c0b24b..bdbe90675e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/StartDeviceSRPFlow.swift @@ -17,7 +17,8 @@ struct StartDeviceSRPFlow: Action { func execute(withDispatcher dispatcher: EventDispatcher, environment: Environment) async { logVerbose("\(#fileID) Start execution", environment: environment) let event = SignInEvent(id: UUID().uuidString, eventType: .respondDeviceSRPChallenge( - username, authResponse)) + username, authResponse + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift index d1846ff20d..c7099a0673 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift @@ -5,26 +5,29 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation extension VerifyDevicePasswordSRP { // swiftlint:disable:next function_parameter_count identifier_name - func signature(deviceGroupKey: String, - deviceKey: String, - deviceSecret: String, - saltHex: String, - secretBlock: Data, - serverPublicBHexString: String, - srpClient: SRPClientBehavior) throws -> String { + func signature( + deviceGroupKey: String, + deviceKey: String, + deviceSecret: String, + saltHex: String, + secretBlock: Data, + serverPublicBHexString: String, + srpClient: SRPClientBehavior + ) throws -> String { let sharedSecret = try sharedSecret( username: "\(deviceGroupKey)\(deviceKey)", password: deviceSecret, saltHex: saltHex, serverPublicBHexString: serverPublicBHexString, - srpClient: srpClient) + srpClient: srpClient + ) do { let dateStr = stateData.clientTimestamp.utcString @@ -32,11 +35,13 @@ extension VerifyDevicePasswordSRP { // swiftlint:disable:next identifier_name let u = try clientClass.calculateUHexValue( clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) // HKDF let authenticationKey = try clientClass.generateAuthenticationKey( sharedSecretHexValue: sharedSecret, - uHexValue: u) + uHexValue: u + ) // Signature let signature = generateSignature( @@ -44,7 +49,8 @@ extension VerifyDevicePasswordSRP { authenticationKey: authenticationKey, deviceKey: deviceKey, deviceGroupKey: deviceGroupKey, - serviceSecretBlock: secretBlock) + serviceSecretBlock: secretBlock + ) return signature.base64EncodedString() } catch let error as SRPError { @@ -57,11 +63,13 @@ extension VerifyDevicePasswordSRP { } } - func sharedSecret(username: String, - password: String, - saltHex: String, - serverPublicBHexString: String, - srpClient: SRPClientBehavior) throws -> String { + func sharedSecret( + username: String, + password: String, + saltHex: String, + serverPublicBHexString: String, + srpClient: SRPClientBehavior + ) throws -> String { do { let srpKeyPair = stateData.srpKeyPair return try srpClient.calculateSharedSecret( @@ -70,7 +78,8 @@ extension VerifyDevicePasswordSRP { saltHexValue: saltHex, clientPrivateKeyHexValue: srpKeyPair.privateKeyHexValue, clientPublicKeyHexValue: srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) } catch let error as SRPError { let authError = SignInError.calculation(error) throw authError @@ -81,11 +90,13 @@ extension VerifyDevicePasswordSRP { } } - func generateSignature(srpTimeStamp: String, - authenticationKey: Data, - deviceKey: String, - deviceGroupKey: String, - serviceSecretBlock: Data) -> Data { + func generateSignature( + srpTimeStamp: String, + authenticationKey: Data, + deviceKey: String, + deviceGroupKey: String, + serviceSecretBlock: Data + ) -> Data { let key = SymmetricKey(data: authenticationKey) var hmac = HMAC.init(key: key) hmac.update(data: Data(deviceGroupKey.utf8)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift index 4bfa1397de..58eff84d00 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifyDevicePasswordSRP: Action { let identifier = "VerifyDevicePasswordSRP" @@ -15,8 +15,10 @@ struct VerifyDevicePasswordSRP: Action { let stateData: SRPStateData let authResponse: SignInResponseBehavior - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { @@ -35,11 +37,13 @@ struct VerifyDevicePasswordSRP: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) guard case .metadata(let deviceData) = deviceMetadata else { @@ -57,7 +61,8 @@ struct VerifyDevicePasswordSRP: Action { saltHex: saltHex, secretBlock: secretBlock, serverPublicBHexString: serverPublicB, - srpClient: srpClient) + srpClient: srpClient + ) let request = await RespondToAuthChallengeInput.devicePasswordVerifier( username: username, @@ -67,15 +72,19 @@ struct VerifyDevicePasswordSRP: Action { signature: signature, deviceMetadata: deviceMetadata, asfDeviceId: asfDeviceId, - environment: userPoolEnv) + environment: userPoolEnv + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: request, for: username, signInMethod: .apiBased(.userSRP), - environment: userPoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userPoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift index 870a41f72a..59990d9a04 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/FetchHostedUISignInToken.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import CryptoKit +import Foundation struct FetchHostedUISignInToken: Action { @@ -32,16 +32,17 @@ struct FetchHostedUISignInToken: Action { do { let request = try HostedUIRequestHelper.createTokenRequest( configuration: hostedUIConfig, - result: result) + result: result + ) let data = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in let task = hostedUIEnvironment.urlSessionFactory().dataTask(with: request) { data, _, error in - if let error = error { + if let error { continuation.resume(with: .failure(SignInError.service(error: error))) - } else if let data = data { + } else if let data { continuation.resume(with: .success(data)) } else { continuation.resume(with: .failure(SignInError.hostedUI(.tokenParsing))) @@ -71,7 +72,8 @@ struct FetchHostedUISignInToken: Action { func handleData(_ data: Data) async throws -> SignedInData { guard let json = try JSONSerialization.jsonObject( with: data, - options: []) as? [String: Any] else { + options: [] + ) as? [String: Any] else { throw HostedUIError.tokenParsing } @@ -86,11 +88,13 @@ struct FetchHostedUISignInToken: Action { idToken: idToken, accessToken: accessToken, refreshToken: refreshToken, - expiresIn: json["expires_in"] as? Int) + expiresIn: json["expires_in"] as? Int + ) let signedInData = SignedInData( signedInDate: Date(), signInMethod: .hostedUI(result.options), - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) return signedInData } else { throw HostedUIError.tokenParsing diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift index ca0de00abe..9ba084b2ef 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/InitializeHostedUISignIn.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import CryptoKit +import Foundation struct InitializeHostedUISignIn: Action { @@ -19,7 +19,8 @@ struct InitializeHostedUISignIn: Action { logVerbose("\(#fileID) Starting execution", environment: environment) guard let environment = environment as? AuthEnvironment, - let hostedUIEnvironment = environment.hostedUIEnvironment else { + let hostedUIEnvironment = environment.hostedUIEnvironment + else { let message = AuthPluginErrorConstants.configurationError let error = AuthenticationError.configuration(message: message) let event = AuthenticationEvent(eventType: .error(error)) @@ -32,13 +33,16 @@ struct InitializeHostedUISignIn: Action { presentationAnchor: options.presentationAnchor, environment: environment, hostedUIEnvironment: hostedUIEnvironment, - dispatcher: dispatcher) + dispatcher: dispatcher + ) } - func initializeHostedUI(presentationAnchor: AuthUIPresentationAnchor?, - environment: AuthEnvironment, - hostedUIEnvironment: HostedUIEnvironment, - dispatcher: EventDispatcher) async { + func initializeHostedUI( + presentationAnchor: AuthUIPresentationAnchor?, + environment: AuthEnvironment, + hostedUIEnvironment: HostedUIEnvironment, + dispatcher: EventDispatcher + ) async { let username = "unknown" let hostedUIConfig = hostedUIEnvironment.configuration let randomGenerator = hostedUIEnvironment.randomStringFactory() @@ -53,23 +57,29 @@ struct InitializeHostedUISignIn: Action { do { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) + userPoolConfiguration: environment.userPoolConfiguration + ) - let url = try HostedUIRequestHelper.createSignInURL(state: state, - proofKey: proofKey, - userContextData: encodedData, - configuration: hostedUIConfig, - options: options) - let signInData = HostedUISigningInState(signInURL: url, - state: state, - codeChallenge: proofKey, - presentationAnchor: presentationAnchor, - options: options) + let url = try HostedUIRequestHelper.createSignInURL( + state: state, + proofKey: proofKey, + userContextData: encodedData, + configuration: hostedUIConfig, + options: options + ) + let signInData = HostedUISigningInState( + signInURL: url, + state: state, + codeChallenge: proofKey, + presentationAnchor: presentationAnchor, + options: options + ) let event = HostedUIEvent(eventType: .showHostedUI(signInData)) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift index 02f3c992b8..c019099b01 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/HostedUI/ShowHostedUISignIn.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AuthenticationServices +import Foundation class ShowHostedUISignIn: NSObject, Action { @@ -43,7 +43,7 @@ class ShowHostedUISignIn: NSObject, Action { } let url = signingInData.signInURL - self.logVerbose("\(#fileID) Showing url \(url.absoluteString)", environment: environment) + logVerbose("\(#fileID) Showing url \(url.absoluteString)", environment: environment) do { let sessionAdapter = hostedUIEnvironment.hostedUISessionFactory() @@ -51,24 +51,27 @@ class ShowHostedUISignIn: NSObject, Action { url: url, callbackScheme: callbackURLScheme, inPrivate: signingInData.options.preferPrivateSession, - presentationAnchor: signingInData.presentationAnchor) + presentationAnchor: signingInData.presentationAnchor + ) guard let code = queryItems.first(where: { $0.name == "code" })?.value, let state = queryItems.first(where: { $0.name == "state" })?.value, - self.signingInData.state == state else { + signingInData.state == state else { let event = HostedUIEvent(eventType: .throwError(.hostedUI(.codeValidation))) - self.logVerbose("\(#fileID) Sending event \(event)", environment: environment) + logVerbose("\(#fileID) Sending event \(event)", environment: environment) await dispatcher.send(event) return } - let result = HostedUIResult(code: code, - state: state, - codeVerifier: self.signingInData.codeChallenge, - options: self.signingInData.options) + let result = HostedUIResult( + code: code, + state: state, + codeVerifier: signingInData.codeChallenge, + options: signingInData.options + ) let event = HostedUIEvent(eventType: .fetchToken(result)) - self.logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) + logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } catch let error as HostedUIError { self.logVerbose("\(#fileID) Received error \(error)", environment: environment) @@ -76,9 +79,9 @@ class ShowHostedUISignIn: NSObject, Action { self.logVerbose("\(#fileID) Sending event \(event)", environment: environment) await dispatcher.send(event) } catch { - self.logVerbose("\(#fileID) Received error \(error)", environment: environment) + logVerbose("\(#fileID) Received error \(error)", environment: environment) let event = HostedUIEvent(eventType: .throwError(.service(error: error))) - self.logVerbose("\(#fileID) Sending event \(event)", environment: environment) + logVerbose("\(#fileID) Sending event \(event)", environment: environment) await dispatcher.send(event) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift index 8ea604a1ff..dc1741b4a7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/IntializeSignInFlow.swift @@ -25,7 +25,8 @@ struct InitializeSignInFlow: Action { func createSignInEvent(from environment: Environment) async -> SignInEvent { guard let authEnvironment = environment as? AuthEnvironment, - authEnvironment.configuration.getUserPoolConfiguration() != nil else { + authEnvironment.configuration.getUserPoolConfiguration() != nil + else { let message = AuthPluginErrorConstants.configurationError let event = SignInEvent(eventType: .throwAuthError(.configuration(message: message))) return event @@ -35,23 +36,25 @@ struct InitializeSignInFlow: Action { if let username = signInEventData.username { deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) } - let event: SignInEvent - switch signInEventData.signInMethod { + let event: SignInEvent = switch signInEventData.signInMethod { case .apiBased(let authflowType): - event = signInEvent(for: authflowType, with: deviceMetadata) + signInEvent(for: authflowType, with: deviceMetadata) case .hostedUI(let hostedUIOptions): - event = .init(eventType: .initiateHostedUISignIn(hostedUIOptions)) + .init(eventType: .initiateHostedUISignIn(hostedUIOptions)) } return event } - func signInEvent(for authflow: AuthFlowType, - with deviceMetadata: DeviceMetadata) -> SignInEvent { + func signInEvent( + for authflow: AuthFlowType, + with deviceMetadata: DeviceMetadata + ) -> SignInEvent { switch authflow { case .userSRP: return .init(eventType: .initiateSignInWithSRP(signInEventData, deviceMetadata)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift index 34cf4ece9d..3ecca4b345 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/MigrateAuth/InitiateMigrateAuth.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct InitiateMigrateAuth: Action { let identifier = "InitiateMigrateAuth" @@ -17,35 +17,43 @@ struct InitiateMigrateAuth: Action { let clientMetadata: [String: String] let deviceMetadata: DeviceMetadata - init(username: String, - password: String, - clientMetadata: [String: String], - deviceMetadata: DeviceMetadata) { + init( + username: String, + password: String, + clientMetadata: [String: String], + deviceMetadata: DeviceMetadata + ) { self.username = username self.password = password self.clientMetadata = clientMetadata self.deviceMetadata = deviceMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { let userPoolEnv = try environment.userPoolEnvironment() let authEnv = try environment.authEnvironment() let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let request = await InitiateAuthInput.migrateAuth( username: username, password: password, clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: userPoolEnv) + environment: userPoolEnv + ) - let responseEvent = try await sendRequest(request: request, - environment: userPoolEnv) + let responseEvent = try await sendRequest( + request: request, + environment: userPoolEnv + ) logVerbose("\(#fileID) Sending event \(responseEvent)", environment: environment) await dispatcher.send(responseEvent) @@ -64,16 +72,20 @@ struct InitiateMigrateAuth: Action { } - private func sendRequest(request: InitiateAuthInput, - environment: UserPoolEnvironment) async throws -> StateMachineEvent { + private func sendRequest( + request: InitiateAuthInput, + environment: UserPoolEnvironment + ) async throws -> StateMachineEvent { let cognitoClient = try environment.cognitoUserPoolFactory() logVerbose("\(#fileID) Starting execution", environment: environment) let response = try await cognitoClient.initiateAuth(input: request) - return try UserPoolSignInHelper.parseResponse(response, - for: username, - signInMethod: .apiBased(.userPassword)) + return try UserPoolSignInHelper.parseResponse( + response, + for: username, + signInMethod: .apiBased(.userPassword) + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift index eb5832ac4a..cf4be25834 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/CancelSignIn.swift @@ -11,8 +11,10 @@ import Foundation struct CancelSignIn: Action { let identifier = "CancelSignIn" - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let event = AuthenticationEvent(eventType: .cancelSignIn) logVerbose("\(#fileID) Sending event \(event)", environment: environment) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift index b1645d0ee1..47556a1758 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/InitiateAuthSRP.swift @@ -6,9 +6,9 @@ // import Amplify -import Foundation -import CryptoKit import AWSCognitoIdentityProvider +import CryptoKit +import Foundation struct InitiateAuthSRP: Action { let identifier = "InitiateAuthSRP" @@ -19,11 +19,13 @@ struct InitiateAuthSRP: Action { let deviceMetadata: DeviceMetadata let clientMetadata: [String: String] - init(username: String, - password: String, - authFlowType: AuthFlowType = .userSRP, - deviceMetadata: DeviceMetadata = .noData, - clientMetadata: [String: String] = [:]) { + init( + username: String, + password: String, + authFlowType: AuthFlowType = .userSRP, + deviceMetadata: DeviceMetadata = .noData, + clientMetadata: [String: String] = [:] + ) { self.username = username self.password = password self.authFlowType = authFlowType @@ -31,8 +33,10 @@ struct InitiateAuthSRP: Action { self.clientMetadata = clientMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) do { let authEnv = try environment.authEnvironment() @@ -50,11 +54,13 @@ struct InitiateAuthSRP: Action { NHexValue: nHexValue, gHexValue: gHexValue, srpKeyPair: srpKeyPair, - clientTimestamp: Date()) + clientTimestamp: Date() + ) let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) let request = await InitiateAuthInput.srpInput( username: username, @@ -63,11 +69,14 @@ struct InitiateAuthSRP: Action { clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: userPoolEnv) + environment: userPoolEnv + ) - let responseEvent = try await sendRequest(request: request, - environment: userPoolEnv, - srpStateData: srpStateData) + let responseEvent = try await sendRequest( + request: request, + environment: userPoolEnv, + srpStateData: srpStateData + ) logVerbose("\(#fileID) Sending event \(responseEvent)", environment: srpEnv) await dispatcher.send(responseEvent) @@ -86,9 +95,11 @@ struct InitiateAuthSRP: Action { } - private func sendRequest(request: InitiateAuthInput, - environment: UserPoolEnvironment, - srpStateData: SRPStateData) async throws -> SignInEvent { + private func sendRequest( + request: InitiateAuthInput, + environment: UserPoolEnvironment, + srpStateData: SRPStateData + ) async throws -> SignInEvent { let cognitoClient = try environment.cognitoUserPoolFactory() logVerbose("\(#fileID) Starting execution", environment: environment) @@ -101,7 +112,8 @@ struct InitiateAuthSRP: Action { challenge: .customChallenge, username: username, session: response.session, - parameters: parameters) + parameters: parameters + ) return SignInEvent(eventType: .receivedChallenge(respondToAuthChallenge)) } return SignInEvent(eventType: .respondPasswordVerifier(srpStateData, response, clientMetadata)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift index 3b113da329..c5b239fcfd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/SRPSignInHelper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation -struct SRPSignInHelper { +enum SRPSignInHelper { static func srpClient(_ environment: SRPAuthEnvironment) throws -> SRPClientBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift index 80222157e2..a3bfe98f60 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/ThrowSignInError.swift @@ -13,8 +13,10 @@ struct ThrowSignInError: Action { let error: Error - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let event = AuthenticationEvent( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift index cab2fbc412..f6a9eafe61 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift @@ -5,25 +5,28 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation extension VerifyPasswordSRP { // swiftlint:disable:next function_parameter_count - func signature(userIdForSRP: String, - saltHex: String, - secretBlock: Data, - serverPublicBHexString: String, - srpClient: SRPClientBehavior, - poolId: String) throws -> String { + func signature( + userIdForSRP: String, + saltHex: String, + secretBlock: Data, + serverPublicBHexString: String, + srpClient: SRPClientBehavior, + poolId: String + ) throws -> String { let sharedSecret = try sharedSecret( userIdForSRP: userIdForSRP, saltHex: saltHex, serverPublicBHexString: serverPublicBHexString, srpClient: srpClient, - poolId: poolId) + poolId: poolId + ) do { let strippedPoolId = strippedPoolId(poolId) @@ -32,11 +35,13 @@ extension VerifyPasswordSRP { // swiftlint:disable:next identifier_name let u = try clientClass.calculateUHexValue( clientPublicKeyHexValue: stateData.srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) // HKDF let authenticationkey = try clientClass.generateAuthenticationKey( sharedSecretHexValue: sharedSecret, - uHexValue: u) + uHexValue: u + ) // Signature let signature = generateSignature( @@ -44,7 +49,8 @@ extension VerifyPasswordSRP { authenticationKey: authenticationkey, srpUserName: userIdForSRP, poolName: strippedPoolId, - serviceSecretBlock: secretBlock) + serviceSecretBlock: secretBlock + ) return signature.base64EncodedString() } catch let error as SRPError { @@ -57,11 +63,13 @@ extension VerifyPasswordSRP { } } - func sharedSecret(userIdForSRP: String, - saltHex: String, - serverPublicBHexString: String, - srpClient: SRPClientBehavior, - poolId: String) throws -> String { + func sharedSecret( + userIdForSRP: String, + saltHex: String, + serverPublicBHexString: String, + srpClient: SRPClientBehavior, + poolId: String + ) throws -> String { let strippedPoolId = strippedPoolId(poolId) let usernameForS = "\(strippedPoolId)\(userIdForSRP)" do { @@ -72,7 +80,8 @@ extension VerifyPasswordSRP { saltHexValue: saltHex, clientPrivateKeyHexValue: srpKeyPair.privateKeyHexValue, clientPublicKeyHexValue: srpKeyPair.publicKeyHexValue, - serverPublicKeyHexValue: serverPublicBHexString) + serverPublicKeyHexValue: serverPublicBHexString + ) } catch let error as SRPError { let authError = SignInError.calculation(error) throw authError @@ -88,11 +97,13 @@ extension VerifyPasswordSRP { return String(poolId[poolId.index(index, offsetBy: 1)...]) } - func generateSignature(srpTimeStamp: String, - authenticationKey: Data, - srpUserName: String, - poolName: String, - serviceSecretBlock: Data) -> Data { + func generateSignature( + srpTimeStamp: String, + authenticationKey: Data, + srpUserName: String, + poolName: String, + serviceSecretBlock: Data + ) -> Data { let key = SymmetricKey(data: authenticationKey) var hmac = HMAC.init(key: key) hmac.update(data: Data(poolName.utf8)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift index d6687065a7..03e84f157b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifyPasswordSRP: Action { let identifier = "VerifyPasswordSRP" @@ -16,16 +16,20 @@ struct VerifyPasswordSRP: Action { let authResponse: InitiateAuthOutput let clientMetadata: ClientMetadata - init(stateData: SRPStateData, - authResponse: InitiateAuthOutput, - clientMetadata: ClientMetadata) { + init( + stateData: SRPStateData, + authResponse: InitiateAuthOutput, + clientMetadata: ClientMetadata + ) { self.stateData = stateData self.authResponse = authResponse self.clientMetadata = clientMetadata } - func execute(withDispatcher dispatcher: EventDispatcher, - environment: Environment) async { + func execute( + withDispatcher dispatcher: EventDispatcher, + environment: Environment + ) async { logVerbose("\(#fileID) Starting execution", environment: environment) let inputUsername = stateData.username @@ -46,17 +50,21 @@ struct VerifyPasswordSRP: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) - let signature = try signature(userIdForSRP: userIdForSRP, - saltHex: saltHex, - secretBlock: secretBlock, - serverPublicBHexString: serverPublicB, - srpClient: srpClient, - poolId: userPoolEnv.userPoolConfiguration.poolId) + with: environment + ) + let signature = try signature( + userIdForSRP: userIdForSRP, + saltHex: saltHex, + secretBlock: secretBlock, + serverPublicBHexString: serverPublicB, + srpClient: srpClient, + poolId: userPoolEnv.userPoolConfiguration.poolId + ) let request = await RespondToAuthChallengeInput.passwordVerifier( username: username, stateData: stateData, @@ -66,30 +74,38 @@ struct VerifyPasswordSRP: Action { clientMetadata: clientMetadata, deviceMetadata: deviceMetadata, asfDeviceId: asfDeviceId, - environment: userPoolEnv) + environment: userPoolEnv + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: request, for: username, signInMethod: .apiBased(.userSRP), - environment: userPoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userPoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logVerbose("\(#fileID) SRPSignInError \(error)", environment: environment) let event = SignInEvent( eventType: .throwPasswordVerifierError(error) ) - logVerbose("\(#fileID) Sending event \(event)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event)", + environment: environment + ) await dispatcher.send(event) } catch let error where deviceNotFound(error: error, deviceMetadata: deviceMetadata) { logVerbose("\(#fileID) Received device not found \(error)", environment: environment) // Remove the saved device details and retry password verify await DeviceMetadataHelper.removeDeviceMetaData(for: username, with: environment) let event = SignInEvent(eventType: .retryRespondPasswordVerifier(stateData, authResponse, clientMetadata)) - logVerbose("\(#fileID) Sending event \(event)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event)", + environment: environment + ) await dispatcher.send(event) } catch { logVerbose("\(#fileID) SRPSignInError Generic \(error)", environment: environment) @@ -97,8 +113,10 @@ struct VerifyPasswordSRP: Action { let event = SignInEvent( eventType: .throwAuthError(authError) ) - logVerbose("\(#fileID) Sending event \(event)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(event)", + environment: environment + ) await dispatcher.send(event) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift index ef4a63e26a..48b5ef7096 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/CompleteTOTPSetup.swift @@ -28,7 +28,8 @@ struct CompleteTOTPSetup: Action { deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) var challengeResponses = [ "USERNAME": username @@ -50,14 +51,16 @@ struct CompleteTOTPSetup: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: authEnv.credentialsClient) + credentialStoreClient: authEnv.credentialsClient + ) var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? if let encodedData = await CognitoUserPoolASF.encodedContext( username: username, asfDeviceId: asfDeviceId, asfClient: userpoolEnv.cognitoUserPoolASFFactory(), - userPoolConfiguration: userpoolEnv.userPoolConfiguration) { + userPoolConfiguration: userpoolEnv.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } @@ -71,29 +74,37 @@ struct CompleteTOTPSetup: Action { challengeResponses: challengeResponses, clientId: userPoolClientId, session: userSession, - userContextData: userContextData) + userContextData: userContextData + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: input, for: username, signInMethod: signInEventData.signInMethod, - environment: userpoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userpoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logError(error.authError.errorDescription, environment: environment) let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) logError(error.authError.errorDescription, environment: environment) let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift index 8fd033dae4..69d20c863c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/InitializeTOTPSetup.swift @@ -16,7 +16,8 @@ struct InitializeTOTPSetup: Action { logVerbose("\(#fileID) Start execution", environment: environment) let event = SetUpTOTPEvent( id: UUID().uuidString, - eventType: .setUpTOTP(authResponse)) + eventType: .setUpTOTP(authResponse) + ) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift index ff9f8633ac..291f6cf305 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/SetUpTOTP.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct SetUpTOTP: Action { @@ -31,7 +31,8 @@ struct SetUpTOTP: Action { } guard let session = result.session, - let secretCode = result.secretCode else { + let secretCode = result.secretCode + else { throw SignInError.unknown(message: "Error unwrapping result associateSoftwareToken result") } @@ -39,22 +40,29 @@ struct SetUpTOTP: Action { .waitForAnswer(.init( secretCode: secretCode, session: session, - username: username))) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + username: username + ))) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift index dd1b37450d..c415cae27e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SoftwareTokenSetup/VerifyTOTPSetup.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifyTOTPSetup: Action { @@ -25,7 +25,8 @@ struct VerifyTOTPSetup: Action { let input = VerifySoftwareTokenInput( friendlyDeviceName: friendlyDeviceName, session: session, - userCode: totpCode) + userCode: totpCode + ) // Initiate TOTP verification let result = try await client.verifySoftwareToken(input: input) @@ -36,21 +37,27 @@ struct VerifyTOTPSetup: Action { let responseEvent = SetUpTOTPEvent(eventType: .respondToAuthChallenge(session)) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error as SignInError { logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) logError(error.authError.errorDescription, environment: environment) let errorEvent = SetUpTOTPEvent(eventType: .throwError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift index 45c6556ce2..f94aa2c7da 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation struct VerifySignInChallenge: Action { @@ -33,11 +33,13 @@ struct VerifySignInChallenge: Action { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: username, - credentialStoreClient: environment.authEnvironment().credentialsClient) + credentialStoreClient: environment.authEnvironment().credentialsClient + ) deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( - for: username, - with: environment) + for: username, + with: environment + ) let input = await RespondToAuthChallengeInput.verifyChallenge( username: username, @@ -49,15 +51,19 @@ struct VerifySignInChallenge: Action { asfDeviceId: asfDeviceId, attributes: confirmSignEventData.attributes, deviceMetadata: deviceMetadata, - environment: userpoolEnv) + environment: userpoolEnv + ) let responseEvent = try await UserPoolSignInHelper.sendRespondToAuth( request: input, for: username, signInMethod: signInMethod, - environment: userpoolEnv) - logVerbose("\(#fileID) Sending event \(responseEvent)", - environment: environment) + environment: userpoolEnv + ) + logVerbose( + "\(#fileID) Sending event \(responseEvent)", + environment: environment + ) await dispatcher.send(responseEvent) } catch let error where deviceNotFound(error: error, deviceMetadata: deviceMetadata) { logVerbose("\(#fileID) Received device not found \(error)", environment: environment) @@ -70,14 +76,18 @@ struct VerifySignInChallenge: Action { await dispatcher.send(event) } catch let error as SignInError { let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } catch { let error = SignInError.service(error: error) let errorEvent = SignInEvent(eventType: .throwAuthError(error)) - logVerbose("\(#fileID) Sending event \(errorEvent)", - environment: environment) + logVerbose( + "\(#fileID) Sending event \(errorEvent)", + environment: environment + ) await dispatcher.send(errorEvent) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift index d4a3d5f429..3eb250552e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/BuildRevokeTokenError.swift @@ -20,12 +20,14 @@ struct BuildRevokeTokenError: Action { logVerbose("\(#fileID) Starting execution", environment: environment) let revokeTokenError = AWSCognitoRevokeTokenError( refreshToken: signedInData.cognitoUserPoolTokens.refreshToken, - error: .service("", "", nil)) + error: .service("", "", nil) + ) let event = SignOutEvent(eventType: .signOutLocally( signedInData, hostedUIError: hostedUIError, globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError)) + revokeTokenError: revokeTokenError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift index dddb53bd49..bd89225197 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/InitiateSignOut.swift @@ -21,8 +21,10 @@ struct InitiateSignOut: Action { let event: SignOutEvent if case .hostedUI(let options) = signedInData.signInMethod, options.preferPrivateSession == false { - event = SignOutEvent(eventType: .invokeHostedUISignOut(signOutEventData, - signedInData)) + event = SignOutEvent(eventType: .invokeHostedUISignOut( + signOutEventData, + signedInData + )) } else if signOutEventData.globalSignOut { event = SignOutEvent(eventType: .signOutGlobally(signedInData)) } else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift index 642db164f2..8d0804b8c4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/RevokeToken.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import Foundation struct RevokeToken: Action { @@ -59,19 +59,22 @@ struct RevokeToken: Action { let internalError = authErrorConvertible.authError revokeTokenError = AWSCognitoRevokeTokenError( refreshToken: signedInData.cognitoUserPoolTokens.refreshToken, - error: internalError) - } else if let error = error { + error: internalError + ) + } else if let error { let internalError = AuthError.service("", "", error) revokeTokenError = AWSCognitoRevokeTokenError( refreshToken: signedInData.cognitoUserPoolTokens.refreshToken, - error: internalError) + error: internalError + ) } let event = SignOutEvent(eventType: .signOutLocally( signedInData, hostedUIError: hostedUIError, globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError)) + revokeTokenError: revokeTokenError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift index 4ff593f96d..0d00a4b44a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/ShowHostedUISignOut.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AuthenticationServices +import Foundation class ShowHostedUISignOut: NSObject, Action { @@ -25,14 +25,16 @@ class ShowHostedUISignOut: NSObject, Action { logVerbose("\(#fileID) Starting execution", environment: environment) guard let environment = environment as? AuthEnvironment, - let hostedUIEnvironment = environment.hostedUIEnvironment else { + let hostedUIEnvironment = environment.hostedUIEnvironment + else { let error = HostedUIError.pluginConfiguration(AuthPluginErrorConstants.configurationError) await sendEvent(with: error, dispatcher: dispatcher, environment: environment) return } let hostedUIConfig = hostedUIEnvironment.configuration guard let callbackURL = URL(string: hostedUIConfig.oauth.signOutRedirectURI), - let callbackURLScheme = callbackURL.scheme else { + let callbackURLScheme = callbackURL.scheme + else { await sendEvent(with: HostedUIError.signOutRedirectURI, dispatcher: dispatcher, environment: environment) return } @@ -44,44 +46,51 @@ class ShowHostedUISignOut: NSObject, Action { url: logoutURL, callbackScheme: callbackURLScheme, inPrivate: false, - presentationAnchor: signOutEvent.presentationAnchor) + presentationAnchor: signOutEvent.presentationAnchor + ) await sendEvent(with: nil, dispatcher: dispatcher, environment: environment) } catch { - self.logVerbose("\(#fileID) Received error \(error)", environment: environment) + logVerbose("\(#fileID) Received error \(error)", environment: environment) await sendEvent(with: error, dispatcher: dispatcher, environment: environment) } } - func sendEvent(with error: Error?, - dispatcher: EventDispatcher, - environment: Environment) async { + func sendEvent( + with error: Error?, + dispatcher: EventDispatcher, + environment: Environment + ) async { let event: SignOutEvent if let hostedUIInternalError = error as? HostedUIError { event = SignOutEvent(eventType: .hostedUISignOutError(hostedUIInternalError)) } else if let error = error as? AuthErrorConvertible { event = getEvent(for: AWSCognitoHostedUIError(error: error.authError)) - } else if let error = error { + } else if let error { let serviceError = AuthError.service( - "HostedUI failed with error", - "", + "HostedUI failed with error", + "", error ) event = getEvent(for: AWSCognitoHostedUIError(error: serviceError)) } else { event = getEvent(for: nil) } - self.logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) + logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } private func getEvent(for hostedUIError: AWSCognitoHostedUIError?) -> SignOutEvent { - if self.signOutEvent.globalSignOut { - return SignOutEvent(eventType: .signOutGlobally(self.signInData, - hostedUIError: hostedUIError)) + if signOutEvent.globalSignOut { + return SignOutEvent(eventType: .signOutGlobally( + signInData, + hostedUIError: hostedUIError + )) } else { - return SignOutEvent(eventType: .revokeToken(self.signInData, - hostedUIError: hostedUIError)) + return SignOutEvent(eventType: .revokeToken( + signInData, + hostedUIError: hostedUIError + )) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift index 778f32fd46..526595c056 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutGlobally.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import Foundation struct SignOutGlobally: Action { @@ -55,19 +55,22 @@ struct SignOutGlobally: Action { let internalError = authErrorConvertible.authError globalSignOutError = AWSCognitoGlobalSignOutError( accessToken: signedInData.cognitoUserPoolTokens.accessToken, - error: internalError) - } else if let error = error { + error: internalError + ) + } else if let error { let internalError = AuthError.service("", "", error) globalSignOutError = AWSCognitoGlobalSignOutError( accessToken: signedInData.cognitoUserPoolTokens.accessToken, - error: internalError) + error: internalError + ) } - if let globalSignOutError = globalSignOutError { + if let globalSignOutError { let event = SignOutEvent(eventType: .globalSignOutError( signedInData, globalSignOutError: globalSignOutError, - hostedUIError: hostedUIError)) + hostedUIError: hostedUIError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) return @@ -75,7 +78,8 @@ struct SignOutGlobally: Action { let event = SignOutEvent(eventType: .revokeToken( signedInData, - hostedUIError: hostedUIError)) + hostedUIError: hostedUIError + )) logVerbose("\(#fileID) Sending event \(event.type)", environment: environment) await dispatcher.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift index cc9be1abea..f73b0a867c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignOut/SignOutLocally.swift @@ -25,7 +25,8 @@ struct SignOutLocally: Action { event = SignOutEvent(eventType: .signedOutSuccess( hostedUIError: hostedUIError, globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError)) + revokeTokenError: revokeTokenError + )) } catch { let signOutError = AuthenticationError.unknown( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift index 75bed80e89..65d46128f8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+ClientBehavior.swift @@ -5,34 +5,42 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AuthenticationServices +import Foundation // swiftlint:disable force_cast extension AWSCognitoAuthPlugin: AuthCategoryBehavior { - public func signUp(username: String, - password: String?, - options: AuthSignUpRequest.Options?) async throws -> AuthSignUpResult { + public func signUp( + username: String, + password: String?, + options: AuthSignUpRequest.Options? + ) async throws -> AuthSignUpResult { let options = options ?? AuthSignUpRequest.Options() - let request = AuthSignUpRequest(username: username, - password: password, - options: options) + let request = AuthSignUpRequest( + username: username, + password: password, + options: options + ) let task = AWSAuthSignUpTask(request, authEnvironment: authEnvironment) return try await taskQueue.sync { return try await task.value } as! AuthSignUpResult } - public func confirmSignUp(for username: String, - confirmationCode: String, - options: AuthConfirmSignUpRequest.Options?) + public func confirmSignUp( + for username: String, + confirmationCode: String, + options: AuthConfirmSignUpRequest.Options? + ) async throws -> AuthSignUpResult { let options = options ?? AuthConfirmSignUpRequest.Options() - let request = AuthConfirmSignUpRequest(username: username, - code: confirmationCode, - options: options) + let request = AuthConfirmSignUpRequest( + username: username, + code: confirmationCode, + options: options + ) let task = AWSAuthConfirmSignUpTask(request, authEnvironment: authEnvironment) return try await taskQueue.sync { return try await task.value @@ -49,11 +57,15 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } #if os(iOS) || os(macOS) - public func signInWithWebUI(presentationAnchor: AuthUIPresentationAnchor? = nil, - options: AuthWebUISignInRequest.Options?) async throws -> AuthSignInResult { + public func signInWithWebUI( + presentationAnchor: AuthUIPresentationAnchor? = nil, + options: AuthWebUISignInRequest.Options? + ) async throws -> AuthSignInResult { let options = options ?? AuthWebUISignInRequest.Options() - let request = AuthWebUISignInRequest(presentationAnchor: presentationAnchor, - options: options) + let request = AuthWebUISignInRequest( + presentationAnchor: presentationAnchor, + options: options + ) let task = AWSAuthWebUISignInTask( request, authConfiguration: authConfiguration, @@ -65,13 +77,17 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } as! AuthSignInResult } - public func signInWithWebUI(for authProvider: AuthProvider, - presentationAnchor: AuthUIPresentationAnchor? = nil, - options: AuthWebUISignInRequest.Options?) async throws -> AuthSignInResult { + public func signInWithWebUI( + for authProvider: AuthProvider, + presentationAnchor: AuthUIPresentationAnchor? = nil, + options: AuthWebUISignInRequest.Options? + ) async throws -> AuthSignInResult { let options = options ?? AuthWebUISignInRequest.Options() - let request = AuthWebUISignInRequest(presentationAnchor: presentationAnchor, - authProvider: authProvider, - options: options) + let request = AuthWebUISignInRequest( + presentationAnchor: presentationAnchor, + authProvider: authProvider, + options: options + ) let task = AWSAuthWebUISignInTask( request, authConfiguration: authConfiguration, @@ -84,15 +100,21 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } #endif - public func confirmSignIn(challengeResponse: String, - options: AuthConfirmSignInRequest.Options? = nil) async throws -> AuthSignInResult { + public func confirmSignIn( + challengeResponse: String, + options: AuthConfirmSignInRequest.Options? = nil + ) async throws -> AuthSignInResult { let options = options ?? AuthConfirmSignInRequest.Options() - let request = AuthConfirmSignInRequest(challengeResponse: challengeResponse, - options: options) - let task = AWSAuthConfirmSignInTask(request, - stateMachine: authStateMachine, - configuration: authConfiguration) + let request = AuthConfirmSignInRequest( + challengeResponse: challengeResponse, + options: options + ) + let task = AWSAuthConfirmSignInTask( + request, + stateMachine: authStateMachine, + configuration: authConfiguration + ) return try await taskQueue.sync { return try await task.value } as! AuthSignInResult @@ -129,31 +151,41 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { } as! AuthResetPasswordResult } - public func confirmResetPassword(for username: String, - with newPassword: String, - confirmationCode: String, - options: AuthConfirmResetPasswordRequest.Options?) async throws { + public func confirmResetPassword( + for username: String, + with newPassword: String, + confirmationCode: String, + options: AuthConfirmResetPasswordRequest.Options? + ) async throws { let options = options ?? AuthConfirmResetPasswordRequest.Options() - let request = AuthConfirmResetPasswordRequest(username: username, - newPassword: newPassword, - confirmationCode: confirmationCode, - options: options) + let request = AuthConfirmResetPasswordRequest( + username: username, + newPassword: newPassword, + confirmationCode: confirmationCode, + options: options + ) let task = AWSAuthConfirmResetPasswordTask(request, environment: authEnvironment, authConfiguration: authConfiguration) _ = try await taskQueue.sync { return try await task.value } } - public func signIn(username: String?, - password: String?, - options: AuthSignInRequest.Options?) async throws -> AuthSignInResult { + public func signIn( + username: String?, + password: String?, + options: AuthSignInRequest.Options? + ) async throws -> AuthSignInResult { let options = options ?? AuthSignInRequest.Options() - let request = AuthSignInRequest(username: username, - password: password, - options: options) - let task = AWSAuthSignInTask(request, - authStateMachine: self.authStateMachine, - configuration: authConfiguration) + let request = AuthSignInRequest( + username: username, + password: password, + options: options + ) + let task = AWSAuthSignInTask( + request, + authStateMachine: authStateMachine, + configuration: authConfiguration + ) return try await taskQueue.sync { return try await task.value } as! AuthSignInResult @@ -161,8 +193,9 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { public func deleteUser() async throws { let task = AWSAuthDeleteUserTask( - authStateMachine: self.authStateMachine, - authConfiguraiton: authConfiguration) + authStateMachine: authStateMachine, + authConfiguraiton: authConfiguration + ) _ = try await taskQueue.sync { return try await task.value } @@ -171,7 +204,8 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { public func setUpTOTP() async throws -> TOTPSetupDetails { let task = SetUpTOTPTask( authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! TOTPSetupDetails @@ -184,11 +218,13 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior { let options = options ?? VerifyTOTPSetupRequest.Options() let request = VerifyTOTPSetupRequest( code: code, - options: options) + options: options + ) let task = VerifyTOTPSetupTask( request, authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) _ = try await taskQueue.sync { return try await task.value } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift index 4dc7c9c348..1e7e909dde 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+DeviceBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { @@ -14,9 +14,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { -> [AuthDevice] { let options = options ?? AuthFetchDevicesRequest.Options() let request = AuthFetchDevicesRequest(options: options) - let task = AWSAuthFetchDevicesTask(request, - authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + let task = AWSAuthFetchDevicesTask( + request, + authStateMachine: authStateMachine, + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! [AuthDevice] // swiftlint:disable:this force_cast @@ -28,9 +30,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { ) async throws { let options = options ?? AuthForgetDeviceRequest.Options() let request = AuthForgetDeviceRequest(device: device, options: options) - let task = AWSAuthForgetDeviceTask(request, - authStateMachine: authStateMachine, - environment: authEnvironment) + let task = AWSAuthForgetDeviceTask( + request, + authStateMachine: authStateMachine, + environment: authEnvironment + ) _ = try await taskQueue.sync { return try await task.value } @@ -39,9 +43,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryDeviceBehavior { public func rememberDevice( options: AuthRememberDeviceRequest.Options? = nil) async throws { let options = options ?? AuthRememberDeviceRequest.Options() let request = AuthRememberDeviceRequest(options: options) - let task = AWSAuthRememberDeviceTask(request, - authStateMachine: authStateMachine, - environment: authEnvironment) + let task = AWSAuthRememberDeviceTask( + request, + authStateMachine: authStateMachine, + environment: authEnvironment + ) _ = try await taskQueue.sync { return try await task.value } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift index 21df88d96b..770bbb1b55 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ClientBehavior/AWSCognitoAuthPlugin+UserBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation // swiftlint:disable force_cast public extension AWSCognitoAuthPlugin { @@ -30,8 +30,10 @@ public extension AWSCognitoAuthPlugin { } as! AuthUpdateAttributeResult } - func update(userAttributes: [AuthUserAttribute], - options: AuthUpdateUserAttributesRequest.Options? = nil) + func update( + userAttributes: [AuthUserAttribute], + options: AuthUpdateUserAttributesRequest.Options? = nil + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { let options = options ?? AuthUpdateUserAttributesRequest.Options() @@ -50,7 +52,8 @@ public extension AWSCognitoAuthPlugin { let options = options ?? AuthAttributeResendConfirmationCodeRequest.Options() let request = AuthAttributeResendConfirmationCodeRequest( - attributeKey: userAttributeKey, options: options) + attributeKey: userAttributeKey, options: options + ) let task = AWSAuthAttributeResendConfirmationCodeTask( request, authStateMachine: authStateMachine, @@ -68,10 +71,12 @@ public extension AWSCognitoAuthPlugin { ) async throws -> AuthCodeDeliveryDetails { let options = options ?? AuthSendUserAttributeVerificationCodeRequest.Options() let request = AuthSendUserAttributeVerificationCodeRequest( - attributeKey: userAttributeKey, options: options) + attributeKey: userAttributeKey, options: options + ) let task = AWSAuthSendUserAttributeVerificationCodeTask( request, authStateMachine: authStateMachine, - userPoolFactory: authEnvironment.cognitoUserPoolFactory) + userPoolFactory: authEnvironment.cognitoUserPoolFactory + ) return try await taskQueue.sync { return try await task.value } as! AuthCodeDeliveryDetails @@ -82,7 +87,8 @@ public extension AWSCognitoAuthPlugin { let request = AuthConfirmUserAttributeRequest( attributeKey: userAttribute, confirmationCode: confirmationCode, - options: options) + options: options + ) let task = AWSAuthConfirmUserAttributeTask(request, authStateMachine: authStateMachine, userPoolFactory: authEnvironment.cognitoUserPoolFactory) _ = try await taskQueue.sync { return try await task.value diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift index 3bb2a2e1bb..1af4db5b7d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AWSCognitoAuthCredentialStore.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation @_spi(KeychainStore) import AWSPluginsCore struct AWSCognitoAuthCredentialStore { @@ -63,8 +63,7 @@ struct AWSCognitoAuthCredentialStore { /// - Old Identity Pool Config == New Identity Pool Config if oldUserPoolConfiguration == nil && newIdentityConfigData != nil && - oldIdentityPoolConfiguration == newIdentityConfigData - { + oldIdentityPoolConfiguration == newIdentityConfigData { // retrieve data from the old namespace and save with the new namespace if let oldCognitoCredentialsData = try? keychain._getData(oldNameSpace) { @@ -98,13 +97,15 @@ struct AWSCognitoAuthCredentialStore { private func generateDeviceMetadataKey( for username: String, - with configuration: AuthConfiguration) -> String { + with configuration: AuthConfiguration + ) -> String { return "\(storeKey(for: authConfiguration)).\(username).\(deviceMetadataKey)" } private func generateASFDeviceKey( for username: String, - with configuration: AuthConfiguration) -> String { + with configuration: AuthConfiguration + ) -> String { return "\(storeKey(for: authConfiguration)).\(username).\(deviceASFKey)" } @@ -188,7 +189,7 @@ extension AWSCognitoAuthCredentialStore: AmplifyAuthCredentialStoreBehavior { /// Helpers for encode and decoding private extension AWSCognitoAuthCredentialStore { - func encode(object: T) throws -> Data { + func encode(object: some Codable) throws -> Data { do { return try JSONEncoder().encode(object) } catch { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift index 326c8e19cb..54ee20a6d5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials+CognitoSession.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AmplifyCredentials { static let expiryBufferInSeconds = TimeInterval.seconds(2 * 60) @@ -20,11 +20,13 @@ extension AmplifyCredentials { isSignedIn: true, identityIdResult: .failure(identityError), awsCredentialsResult: .failure(credentialsError), - cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens)) + cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens) + ) case .identityPoolOnly(let identityID, let credentials): return AuthCognitoSignedOutSessionHelper.makeSignedOutSession( identityId: identityID, - awsCredentials: credentials) + awsCredentials: credentials + ) case .identityPoolWithFederation(_, let identityId, let awsCredentials): return AWSAuthCognitoSession( isSignedIn: true, @@ -43,7 +45,8 @@ extension AmplifyCredentials { isSignedIn: true, identityIdResult: .success(identityID), awsCredentialsResult: .success(credentials), - cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens)) + cognitoTokensResult: .success(signedInData.cognitoUserPoolTokens) + ) case .noCredentials: return AuthCognitoSignedOutSessionHelper.makeSessionWithNoGuestAccess() } @@ -64,9 +67,11 @@ extension AmplifyCredentials { case .identityPoolOnly(identityID: _, credentials: let awsCredentials): doesExpire = awsCredentials.doesExpire(in: expiryBuffer) - case .userPoolAndIdentityPool(signedInData: let data, - identityID: _, - credentials: let awsCredentials): + case .userPoolAndIdentityPool( + signedInData: let data, + identityID: _, + credentials: let awsCredentials + ): doesExpire = ( data.cognitoUserPoolTokens.doesExpire(in: expiryBuffer) || awsCredentials.doesExpire(in: expiryBuffer) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift index 3d93d21d79..1ce0b9f8a6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/CredentialStorage/AmplifyCredentials.swift @@ -5,24 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// Internal representation of Credentials Auth category maintain. enum AmplifyCredentials { case userPoolOnly(signedInData: SignedInData) - case identityPoolOnly(identityID: String, - credentials: AuthAWSCognitoCredentials) - - case identityPoolWithFederation(federatedToken: FederatedToken, - identityID: String, - credentials: AuthAWSCognitoCredentials) - - case userPoolAndIdentityPool(signedInData: SignedInData, - identityID: String, - credentials: AuthAWSCognitoCredentials) + case identityPoolOnly( + identityID: String, + credentials: AuthAWSCognitoCredentials + ) + + case identityPoolWithFederation( + federatedToken: FederatedToken, + identityID: String, + credentials: AuthAWSCognitoCredentials + ) + + case userPoolAndIdentityPool( + signedInData: SignedInData, + identityID: String, + credentials: AuthAWSCognitoCredentials + ) case noCredentials } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift index b8dd44df29..f6afd000c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthEnvironment.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct AuthEnvironment: Environment, LoggerProvider { let configuration: AuthConfiguration diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift index 8337c3fb76..33b8676e5d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/AuthorizationEnvironment.swift @@ -41,14 +41,14 @@ struct BasicAuthorizationEnvironment: AuthorizationEnvironment { extension AuthEnvironment: AuthorizationEnvironment { var identityPoolConfiguration: IdentityPoolConfigurationData { - guard let authorizationEnvironment = authorizationEnvironment else { + guard let authorizationEnvironment else { fatalError("Could not find authorization environment") } return authorizationEnvironment.identityPoolConfiguration } var cognitoIdentityFactory: CognitoIdentityFactory { - guard let authorizationEnvironment = authorizationEnvironment else { + guard let authorizationEnvironment else { fatalError("Could not find authorization environment") } return authorizationEnvironment.cognitoIdentityFactory diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift index a7a54a7039..13cff87751 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/CredentialStoreEnvironment.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSPluginsCore import Amplify +import AWSPluginsCore struct CredentialEnvironment: Environment, LoggerProvider { let authConfiguration: AuthConfiguration @@ -35,9 +35,11 @@ struct BasicCredentialStoreEnvironment: CredentialStoreEnvironment { // Optional let eventIDFactory: EventIDFactory - init(amplifyCredentialStoreFactory: @escaping AmplifyAuthCredentialStoreFactory, - legacyKeychainStoreFactory: @escaping KeychainStoreFactory, - eventIDFactory: @escaping EventIDFactory = UUIDFactory.factory) { + init( + amplifyCredentialStoreFactory: @escaping AmplifyAuthCredentialStoreFactory, + legacyKeychainStoreFactory: @escaping KeychainStoreFactory, + eventIDFactory: @escaping EventIDFactory = UUIDFactory.factory + ) { self.amplifyCredentialStoreFactory = amplifyCredentialStoreFactory self.legacyKeychainStoreFactory = legacyKeychainStoreFactory self.eventIDFactory = eventIDFactory diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift index 822a9e37f3..a012c706ea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Environment/SRPAuthEnvironment.swift @@ -24,8 +24,10 @@ struct BasicSRPAuthEnvironment: SRPAuthEnvironment { cognitoUserPoolFactory: @escaping CognitoUserPoolFactory, eventIDFactory: @escaping EventIDFactory = UUIDFactory.factory, srpClientFactory: @escaping SRPClientFactory = AmplifySRPClient.init(NHexValue:gHexValue:), - srpConfiguration: (nHexValue: String, gHexValue: String) = (nHexValue: SRPCommonConfig.nHexValue, - gHexValue: SRPCommonConfig.gHexValue) + srpConfiguration: (nHexValue: String, gHexValue: String) = ( + nHexValue: SRPCommonConfig.nHexValue, + gHexValue: SRPCommonConfig.gHexValue + ) ) { self.userPoolConfiguration = userPoolConfiguration self.cognitoUserPoolFactory = cognitoUserPoolFactory diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift index c8248e156f..c70e9637e4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/HubEvents/AuthHubEventHandler.swift @@ -40,14 +40,16 @@ class AuthHubEventHandler: AuthHubEventBehavior { case HubPayload.EventName.Auth.signInAPI: guard let event = payload.data as? AWSAuthSignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) case HubPayload.EventName.Auth.confirmSignInAPI: guard let event = payload.data as? AWSAuthConfirmSignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) @@ -55,14 +57,16 @@ class AuthHubEventHandler: AuthHubEventBehavior { #if os(iOS) || os(macOS) case HubPayload.EventName.Auth.webUISignInAPI: guard let event = payload.data as? AWSAuthWebUISignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) case HubPayload.EventName.Auth.socialWebUISignInAPI: guard let event = payload.data as? AWSAuthWebUISignInTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSignInEvent(result) @@ -70,7 +74,8 @@ class AuthHubEventHandler: AuthHubEventBehavior { case HubPayload.EventName.Auth.deleteUserAPI: guard let event = payload.data as? AWSAuthDeleteUserTask.AmplifyAuthTaskResult, - case .success = event else { + case .success = event + else { return } self?.sendUserDeletedEvent() @@ -89,7 +94,8 @@ class AuthHubEventHandler: AuthHubEventBehavior { case HubPayload.EventName.Auth.fetchSessionAPI: guard let event = payload.data as? AWSAuthFetchSessionTask.AmplifyAuthTaskResult, - case let .success(result) = event else { + case let .success(result) = event + else { return } self?.handleSessionEvent(result) @@ -109,7 +115,8 @@ class AuthHubEventHandler: AuthHubEventBehavior { private func handleSessionEvent(_ sessionResult: AuthSession) { guard let tokensProvider = sessionResult as? AuthCognitoTokensProvider, - case let .failure(authError) = tokensProvider.getCognitoTokens() else { + case let .failure(authError) = tokensProvider.getCognitoTokens() + else { return } guard case .sessionExpired = authError else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift index 59d799e963..8dc177cd86 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthCognitoSession.swift @@ -27,10 +27,12 @@ public struct AWSAuthCognitoSession: AuthSession, public let userPoolTokensResult: Result - init(isSignedIn: Bool, - identityIdResult: Result, - awsCredentialsResult: Result, - cognitoTokensResult: Result) { + init( + isSignedIn: Bool, + identityIdResult: Result, + awsCredentialsResult: Result, + cognitoTokensResult: Result + ) { self.isSignedIn = isSignedIn self.identityIdResult = identityIdResult self.awsCredentialsResult = awsCredentialsResult @@ -62,8 +64,9 @@ public struct AWSAuthCognitoSession: AuthSession, return .success(userSub) } catch AuthError.signedOut { return .failure(AuthError.signedOut( - AuthPluginErrorConstants.userSubSignOutError.errorDescription, - AuthPluginErrorConstants.userSubSignOutError.recoverySuggestion)) + AuthPluginErrorConstants.userSubSignOutError.errorDescription, + AuthPluginErrorConstants.userSubSignOutError.recoverySuggestion + )) } catch let error as AuthError { return .failure(error) } catch { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift index b2ad2fbedd..310251820f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthDevice.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation public struct AWSAuthDevice: AuthDevice { @@ -28,12 +28,14 @@ public struct AWSAuthDevice: AuthDevice { /// The date this device was last updated. public let lastModifiedDate: Date? - public init(id: String, - name: String, - attributes: [String: String]?, - createdDate: Date?, - lastAuthenticatedDate: Date?, - lastModifiedDate: Date?) { + public init( + id: String, + name: String, + attributes: [String: String]?, + createdDate: Date?, + lastAuthenticatedDate: Date?, + lastModifiedDate: Date? + ) { self.id = id self.name = name self.attributes = attributes diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift index 07172c8da2..7cbd2c56e8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSAuthUser.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify public struct AWSAuthUser: AuthUser { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift index f61bd5ca52..a7b98bc275 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoAuthService.swift @@ -20,6 +20,8 @@ public enum AWSCognitoAuthService { /// Both AWS Cognito User Pool and AWS Identity Pool auth services are configured. The associated /// value contains the underlying low level clients. - case userPoolAndIdentityPool(CognitoIdentityProviderClient, - CognitoIdentityClient) + case userPoolAndIdentityPool( + CognitoIdentityProviderClient, + CognitoIdentityClient + ) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift index 2be4f3279b..3d9d6d65ef 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoNetworkPreferences.swift @@ -16,14 +16,16 @@ public struct AWSCognitoNetworkPreferences { public let timeoutIntervalForRequest: TimeInterval /// The maximum amount of time that a resource request should be allowed to take. - /// + /// /// NOTE: This value is only applicable to HostedUI because the underlying Swift SDK does /// not support resource timeouts public let timeoutIntervalForResource: TimeInterval? - public init(maxRetryCount: UInt32, - timeoutIntervalForRequest: TimeInterval, - timeoutIntervalForResource: TimeInterval? = nil) { + public init( + maxRetryCount: UInt32, + timeoutIntervalForRequest: TimeInterval, + timeoutIntervalForResource: TimeInterval? = nil + ) { self.maxRetryCount = maxRetryCount self.timeoutIntervalForRequest = timeoutIntervalForRequest self.timeoutIntervalForResource = timeoutIntervalForResource diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift index f8786e6353..0bb2bc4512 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoSignOutResult.swift @@ -19,9 +19,11 @@ public enum AWSCognitoSignOutResult: AuthSignOutResult { case complete - case partial(revokeTokenError: AWSCognitoRevokeTokenError?, - globalSignOutError: AWSCognitoGlobalSignOutError?, - hostedUIError: AWSCognitoHostedUIError?) + case partial( + revokeTokenError: AWSCognitoRevokeTokenError?, + globalSignOutError: AWSCognitoGlobalSignOutError?, + hostedUIError: AWSCognitoHostedUIError? + ) case failed(AuthError) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift index 38d34ba4d9..1aec9b7f6c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AWSCognitoUserPoolTokens.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { @@ -21,10 +21,12 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { // swiftlint:disable:next line_length @available(*, deprecated, message: "Use of `init(idToken,accessToken,refreshToken:expiresIn)` is deprecated, use `exp` claim in the `idToken` or `accessToken` instead") - public init(idToken: String, - accessToken: String, - refreshToken: String, - expiresIn: Int) { + public init( + idToken: String, + accessToken: String, + refreshToken: String, + expiresIn: Int + ) { self.idToken = idToken self.accessToken = accessToken self.refreshToken = refreshToken @@ -33,26 +35,30 @@ public struct AWSCognitoUserPoolTokens: AuthCognitoTokens { // swiftlint:disable:next line_length @available(*, deprecated, message: "Use of `init(idToken,accessToken,refreshToken:expiration)` is deprecated, use `exp` claim in the `idToken` or `accessToken` instead") - public init(idToken: String, - accessToken: String, - refreshToken: String, - expiration: Date) { + public init( + idToken: String, + accessToken: String, + refreshToken: String, + expiration: Date + ) { self.idToken = idToken self.accessToken = accessToken self.refreshToken = refreshToken self.expiration = expiration } - init(idToken: String, - accessToken: String, - refreshToken: String, - expiresIn: Int? = nil) { + init( + idToken: String, + accessToken: String, + refreshToken: String, + expiresIn: Int? = nil + ) { self.idToken = idToken self.accessToken = accessToken self.refreshToken = refreshToken - if let expiresIn = expiresIn { + if let expiresIn { self.expiration = Date().addingTimeInterval(TimeInterval(expiresIn)) } else { let expirationDoubleValue: Double diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift index c3bcb015f5..19082e8f0f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthAWSCognitoCredentials.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation public struct AuthAWSCognitoCredentials: AWSTemporaryCredentials { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift index 499aa62175..ecba5d432e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthChallengeType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation enum AuthChallengeType { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift index 7320fe6bef..d7a9c364dd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/AuthFlowType.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation public enum AuthFlowType: String { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift index afeedeb0c3..6614194fe5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/MFATypeExtension.swift @@ -10,7 +10,7 @@ import Foundation extension MFAType: DefaultLogger { - internal init?(rawValue: String) { + init?(rawValue: String) { if rawValue.caseInsensitiveCompare("SMS_MFA") == .orderedSame { self = .sms } else if rawValue.caseInsensitiveCompare("SOFTWARE_TOKEN_MFA") == .orderedSame { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift index ce54b5a908..bca07f4deb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignInOptions.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify public struct AWSAuthConfirmSignInOptions { @@ -19,7 +20,8 @@ public struct AWSAuthConfirmSignInOptions { public init( userAttributes: [AuthUserAttribute]? = nil, metadata: [String: String]? = nil, - friendlyDeviceName: String? = nil) { + friendlyDeviceName: String? = nil + ) { self.userAttributes = userAttributes self.metadata = metadata self.friendlyDeviceName = friendlyDeviceName diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift index c661c54855..4f2ff6bca1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthConfirmSignUpOptions.swift @@ -13,8 +13,10 @@ public struct AWSAuthConfirmSignUpOptions { public let forceAliasCreation: Bool? - public init(metadata: [String: String]? = nil, - forceAliasCreation: Bool? = nil) { + public init( + metadata: [String: String]? = nil, + forceAliasCreation: Bool? = nil + ) { self.metadata = metadata self.forceAliasCreation = forceAliasCreation } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift index e73ab0759a..3aecf5e584 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthResetPasswordOptions.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation public struct AWSAuthResetPasswordOptions { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift index 6b6a0ee6d4..3b747fdd84 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthSignInOptions.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import AWSCognitoIdentityProvider +import Foundation public struct AWSAuthSignInOptions { @@ -26,9 +27,11 @@ public struct AWSAuthSignInOptions { public var validationData: [String: String]? @available(*, deprecated, renamed: "init(metadata:authFlowType:)") - public init(validationData: [String: String]? = nil, - metadata: [String: String]? = nil, - authFlowType: AuthFlowType? = nil) { + public init( + validationData: [String: String]? = nil, + metadata: [String: String]? = nil, + authFlowType: AuthFlowType? = nil + ) { self.validationData = validationData self.metadata = metadata self.authFlowType = authFlowType diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift index 64bedd43c4..5619d882b8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Models/Options/AWSAuthWebUISignInOptions.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) -import Foundation import Amplify +import Foundation public struct AWSAuthWebUISignInOptions { @@ -27,16 +27,18 @@ public struct AWSAuthWebUISignInOptions { /// Safari always honors the request. public let preferPrivateSession: Bool - public init(idpIdentifier: String? = nil, - preferPrivateSession: Bool = false) { + public init( + idpIdentifier: String? = nil, + preferPrivateSession: Bool = false + ) { self.idpIdentifier = idpIdentifier self.preferPrivateSession = preferPrivateSession } } -extension AuthWebUISignInRequest.Options { +public extension AuthWebUISignInRequest.Options { - public static func preferPrivateSession() -> AuthWebUISignInRequest.Options { + static func preferPrivateSession() -> AuthWebUISignInRequest.Options { let pluginOptions = AWSAuthWebUISignInOptions(preferPrivateSession: true) let options = AuthWebUISignInRequest.Options(pluginOptions: pluginOptions) return options diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift index 49ca97e23a..5e4fddf0a4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/AuthConfigureOperation.swift @@ -5,16 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation -import ClientRuntime import AWSCognitoIdentityProvider +import ClientRuntime typealias ConfigureOperation = AmplifyOperation< AuthConfigureRequest, Void, - AuthError> + AuthError +> class AuthConfigureOperation: ConfigureOperation { @@ -22,16 +23,20 @@ class AuthConfigureOperation: ConfigureOperation { let authStateMachine: AuthStateMachine let credentialStoreStateMachine: CredentialStoreStateMachine - init(request: AuthConfigureRequest, - authStateMachine: AuthStateMachine, - credentialStoreStateMachine: CredentialStoreStateMachine) { + init( + request: AuthConfigureRequest, + authStateMachine: AuthStateMachine, + credentialStoreStateMachine: CredentialStoreStateMachine + ) { self.authConfiguration = request.authConfiguration self.authStateMachine = authStateMachine self.credentialStoreStateMachine = credentialStoreStateMachine - super.init(categoryType: .auth, - eventName: "InternalConfigureAuth", - request: request) + super.init( + categoryType: .auth, + eventName: "InternalConfigureAuth", + request: request + ) } override public func main() { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift index 3e4e761629..e96fab68f3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/AmplifyOperationHelper.swift @@ -9,7 +9,9 @@ import Foundation typealias AuthStateMachine = StateMachine< AuthState, - AuthEnvironment> + AuthEnvironment +> typealias CredentialStoreStateMachine = StateMachine< CredentialStoreState, - CredentialEnvironment> + CredentialEnvironment +> diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift index df5c6d46fe..0593cfc6e5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/ClearFederationOperationHelper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct ClearFederationOperationHelper { @@ -17,7 +17,8 @@ struct ClearFederationOperationHelper { guard case .configured(let authNState, let authZState) = currentState else { let authError = AuthError.invalidState( "Clearing of federation failed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) throw authError } @@ -28,7 +29,8 @@ struct ClearFederationOperationHelper { default: let authError = AuthError.invalidState( "Clearing of federation failed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) throw authError } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift index b4a7aa9d4a..aa2f9412e3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/FetchAuthSessionOperationHelper.swift @@ -5,15 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class FetchAuthSessionOperationHelper: DefaultLogger { typealias FetchAuthSessionCompletion = (Result) -> Void - func fetch(_ authStateMachine: AuthStateMachine, - forceRefresh: Bool = false) async throws -> AuthSession { + func fetch( + _ authStateMachine: AuthStateMachine, + forceRefresh: Bool = false + ) async throws -> AuthSession { let state = await authStateMachine.currentState guard case .configured(_, let authorizationState) = state else { let message = "Auth state machine not in configured state: \(state)" @@ -36,7 +38,8 @@ class FetchAuthSessionOperationHelper: DefaultLogger { return try await refreshIfRequired( existingCredentials: credentials, authStateMachine: authStateMachine, - forceRefresh: forceRefresh) + forceRefresh: forceRefresh + ) case .error(let error): if case .sessionExpired(let error) = error { @@ -48,7 +51,8 @@ class FetchAuthSessionOperationHelper: DefaultLogger { return try await refreshIfRequired( existingCredentials: credentials, authStateMachine: authStateMachine, - forceRefresh: forceRefresh) + forceRefresh: forceRefresh + ) } else { log.verbose("Session is in error state \(error)") let event = AuthorizationEvent(eventType: .fetchUnAuthSession) @@ -64,17 +68,17 @@ class FetchAuthSessionOperationHelper: DefaultLogger { func refreshIfRequired( existingCredentials credentials: AmplifyCredentials, authStateMachine: AuthStateMachine, - forceRefresh: Bool) async throws -> AuthSession { + forceRefresh: Bool + ) async throws -> AuthSession { if forceRefresh || !credentials.areValid() { - var event: AuthorizationEvent - switch credentials { + var event = switch credentials { case .identityPoolWithFederation(let federatedToken, let identityId, _): - event = AuthorizationEvent(eventType: .startFederationToIdentityPool(federatedToken, identityId)) + AuthorizationEvent(eventType: .startFederationToIdentityPool(federatedToken, identityId)) case .noCredentials: - event = AuthorizationEvent(eventType: .fetchUnAuthSession) + AuthorizationEvent(eventType: .fetchUnAuthSession) case .userPoolOnly, .identityPoolOnly, .userPoolAndIdentityPool: - event = AuthorizationEvent(eventType: .refreshSession(forceRefresh)) + AuthorizationEvent(eventType: .refreshSession(forceRefresh)) } await authStateMachine.send(event) return try await listenForSession(authStateMachine: authStateMachine) @@ -100,16 +104,21 @@ class FetchAuthSessionOperationHelper: DefaultLogger { case .error(let authorizationError): return try sessionResultWithError( authorizationError, - authenticationState: authenticationState) + authenticationState: authenticationState + ) default: continue } } - throw AuthError.invalidState("Could not fetch session due to internal error", - "Auth plugin is in an invalid state") + throw AuthError.invalidState( + "Could not fetch session due to internal error", + "Auth plugin is in an invalid state" + ) } - func sessionResultWithError(_ error: AuthorizationError, - authenticationState: AuthenticationState) + func sessionResultWithError( + _ error: AuthorizationError, + authenticationState: AuthenticationState + ) throws -> AuthSession { log.verbose("Received error - \(error)") @@ -119,9 +128,11 @@ class FetchAuthSessionOperationHelper: DefaultLogger { } switch error { case .sessionError(let fetchError, let credentials): - return try sessionResultWithFetchError(fetchError, - authenticationState: authenticationState, - existingCredentials: credentials) + return try sessionResultWithFetchError( + fetchError, + authenticationState: authenticationState, + existingCredentials: credentials + ) case .sessionExpired(let error): let session = AuthCognitoSignedInSessionHelper.makeExpiredSignedInSession( underlyingError: error) @@ -129,17 +140,21 @@ class FetchAuthSessionOperationHelper: DefaultLogger { default: let message = "Unknown error occurred" let error = AuthError.unknown(message) - let session = AWSAuthCognitoSession(isSignedIn: isSignedIn, - identityIdResult: .failure(error), - awsCredentialsResult: .failure(error), - cognitoTokensResult: .failure(error)) + let session = AWSAuthCognitoSession( + isSignedIn: isSignedIn, + identityIdResult: .failure(error), + awsCredentialsResult: .failure(error), + cognitoTokensResult: .failure(error) + ) return session } } - func sessionResultWithFetchError(_ error: FetchSessionError, - authenticationState: AuthenticationState, - existingCredentials: AmplifyCredentials) + func sessionResultWithFetchError( + _ error: FetchSessionError, + authenticationState: AuthenticationState, + existingCredentials: AmplifyCredentials + ) throws -> AuthSession { var isSignedIn = false @@ -155,30 +170,33 @@ class FetchAuthSessionOperationHelper: DefaultLogger { } case .service(let error): - var authError: AuthError - if let convertedAuthError = (error as? AuthErrorConvertible)?.authError { - authError = convertedAuthError + var authError: AuthError = if let convertedAuthError = (error as? AuthErrorConvertible)?.authError { + convertedAuthError } else { - authError = AuthError.service( + AuthError.service( "Unknown service error occurred", "See the attached error for more details", - error) + error + ) } let session = AWSAuthCognitoSession( isSignedIn: isSignedIn, identityIdResult: .failure(authError), awsCredentialsResult: .failure(authError), - cognitoTokensResult: .failure(authError)) + cognitoTokensResult: .failure(authError) + ) return session default: break } let message = "Unknown error occurred" let error = AuthError.unknown(message) - let session = AWSAuthCognitoSession(isSignedIn: isSignedIn, - identityIdResult: .failure(error), - awsCredentialsResult: .failure(error), - cognitoTokensResult: .failure(error)) + let session = AWSAuthCognitoSession( + isSignedIn: isSignedIn, + identityIdResult: .failure(error), + awsCredentialsResult: .failure(error), + cognitoTokensResult: .failure(error) + ) return session } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift index 375216c8d5..d25b417ee3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/HostedUISignInHelper.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) -import Foundation import Amplify +import Foundation struct HostedUISignInHelper: DefaultLogger { @@ -17,9 +17,11 @@ struct HostedUISignInHelper: DefaultLogger { let configuration: AuthConfiguration - init(request: AuthWebUISignInRequest, - authstateMachine: AuthStateMachine, - configuration: AuthConfiguration) { + init( + request: AuthWebUISignInRequest, + authstateMachine: AuthStateMachine, + configuration: AuthConfiguration + ) { self.request = request self.authStateMachine = authstateMachine self.configuration = configuration @@ -51,7 +53,8 @@ struct HostedUISignInHelper: DefaultLogger { case .signedIn: throw AuthError.invalidState( "There is already a user in signedIn state. SignOut the user first before calling signIn", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) case .signedOut: return default: continue @@ -81,8 +84,10 @@ struct HostedUISignInHelper: DefaultLogger { await sendSignInEvent(oauthConfiguration: oauthConfiguration) log.verbose("Wait for signIn to complete") for await state in stateSequences { - guard case .configured(let authNState, - let authZState) = state else { continue } + guard case .configured( + let authNState, + let authZState + ) = state else { continue } switch authNState { case .signedIn: @@ -115,16 +120,22 @@ struct HostedUISignInHelper: DefaultLogger { let privateSession = pluginOptions?.preferPrivateSession ?? false let idpIdentifier = pluginOptions?.idpIdentifier - let providerInfo = HostedUIProviderInfo(authProvider: request.authProvider, - idpIdentifier: idpIdentifier) + let providerInfo = HostedUIProviderInfo( + authProvider: request.authProvider, + idpIdentifier: idpIdentifier + ) let scopeFromConfig = oauthConfiguration.scopes - let hostedUIOptions = HostedUIOptions(scopes: request.options.scopes ?? scopeFromConfig, - providerInfo: providerInfo, - presentationAnchor: request.presentationAnchor, - preferPrivateSession: privateSession) - let signInData = SignInEventData(username: nil, - password: nil, - signInMethod: .hostedUI(hostedUIOptions)) + let hostedUIOptions = HostedUIOptions( + scopes: request.options.scopes ?? scopeFromConfig, + providerInfo: providerInfo, + presentationAnchor: request.presentationAnchor, + preferPrivateSession: privateSession + ) + let signInData = SignInEventData( + username: nil, + password: nil, + signInMethod: .hostedUI(hostedUIOptions) + ) let event = AuthenticationEvent.init(eventType: .signInRequested(signInData)) await authStateMachine.send(event) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift index 269cf048e8..4239b0c7e7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Operations/Helpers/UpdateAttributesOperationHelper.swift @@ -6,10 +6,10 @@ // import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore -struct UpdateAttributesOperationHelper { +enum UpdateAttributesOperationHelper { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -17,13 +17,16 @@ struct UpdateAttributesOperationHelper { attributes: [AuthUserAttribute], accessToken: String, userPoolFactory: @escaping CognitoUserPoolFactory, - clientMetaData: [String: String]) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { + clientMetaData: [String: String] + ) async throws -> [AuthUserAttributeKey: AuthUpdateAttributeResult] { let userPoolService = try userPoolFactory() - let input = UpdateUserAttributesInput(accessToken: accessToken, - clientMetadata: clientMetaData, - userAttributes: attributes.map({ $0.sdkClientAttributeType() })) + let input = UpdateUserAttributesInput( + accessToken: accessToken, + clientMetadata: clientMetaData, + userAttributes: attributes.map { $0.sdkClientAttributeType() } + ) let result = try await userPoolService.updateUserAttributes(input: input) @@ -32,8 +35,10 @@ struct UpdateAttributesOperationHelper { if let attribute = item.attributeName { let authCodeDeliveryDetails = item.toAuthCodeDeliveryDetails() let nextStep = AuthUpdateAttributeStep.confirmAttributeWithCode(authCodeDeliveryDetails, nil) - let updateAttributeResult = AuthUpdateAttributeResult(isUpdated: false, - nextStep: nextStep) + let updateAttributeResult = AuthUpdateAttributeResult( + isUpdated: false, + nextStep: nextStep + ) finalResult[AuthUserAttributeKey(rawValue: attribute)] = updateAttributeResult } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift index 2ab68e1c01..571932f115 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Request/AuthFederateToIdentityPoolRequest.swift @@ -18,9 +18,11 @@ public struct AuthFederateToIdentityPoolRequest: AmplifyOperationRequest { /// Extra request options defined in `FederateToIdentityPoolRequest.Options` public var options: Options - public init(token: String, - provider: AuthProvider, - options: Options) { + public init( + token: String, + provider: AuthProvider, + options: Options + ) { self.token = token self.provider = provider self.options = options diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift index de41eead55..c81306db5e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/AmplifySRPClient.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AmplifySRP import AmplifyBigInteger +import AmplifySRP +import Foundation struct AmplifySRPClient: SRPClientBehavior { @@ -31,18 +31,22 @@ struct AmplifySRPClient: SRPClientBehavior { func generateClientKeyPair() -> SRPKeys { let publicHexValue = client.publicA.asString(radix: 16) let privateHexValue = client.privateA.asString(radix: 16) - let srpKeys = SRPKeys(publicKeyHexValue: publicHexValue, - privateKeyHexValue: privateHexValue) + let srpKeys = SRPKeys( + publicKeyHexValue: publicHexValue, + privateKeyHexValue: privateHexValue + ) return srpKeys } // swiftlint:disable:next function_parameter_count - func calculateSharedSecret(username: String, - password: String, - saltHexValue: String, - clientPrivateKeyHexValue: String, - clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String { + func calculateSharedSecret( + username: String, + password: String, + saltHexValue: String, + clientPrivateKeyHexValue: String, + clientPublicKeyHexValue: String, + serverPublicKeyHexValue: String + ) throws -> String { guard let clientPublicNum = BigInt(clientPublicKeyHexValue, radix: 16) else { throw SRPError.numberConversion } @@ -58,18 +62,22 @@ struct AmplifySRPClient: SRPClientBehavior { guard serverPublicKeyNum % commonState.prime != BigInt(0) else { throw SRPError.illegalParameter } - let sharedSecret = SRPClientState.calculateSessionKey(username: username, - password: password, - publicClientKey: clientPublicNum, - privateClientKey: clientPrivateNum, - publicServerKey: serverPublicKeyNum, - salt: saltNum, - commonState: commonState) + let sharedSecret = SRPClientState.calculateSessionKey( + username: username, + password: password, + publicClientKey: clientPublicNum, + privateClientKey: clientPrivateNum, + publicServerKey: serverPublicKeyNum, + salt: saltNum, + commonState: commonState + ) return sharedSecret.asString(radix: 16) } - static func calculateUHexValue(clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String { + static func calculateUHexValue( + clientPublicKeyHexValue: String, + serverPublicKeyHexValue: String + ) throws -> String { guard let clientPublicNum = BigInt(clientPublicKeyHexValue, radix: 16) else { throw SRPError.numberConversion } @@ -79,8 +87,10 @@ struct AmplifySRPClient: SRPClientBehavior { let signedClientPublicKey = AmplifyBigIntHelper.getSignedData(num: clientPublicNum) let signedServerPublicKey = AmplifyBigIntHelper.getSignedData(num: serverPublicNum) - let u = SRPClientState.calculcateU(publicClientKey: signedClientPublicKey, - publicServerKey: signedServerPublicKey) + let u = SRPClientState.calculcateU( + publicClientKey: signedClientPublicKey, + publicServerKey: signedServerPublicKey + ) return u.asString(radix: 16) } @@ -99,20 +109,23 @@ struct AmplifySRPClient: SRPClientBehavior { keyingMaterial: Data(keyingMaterial), salt: Data(salt), info: "Caldera Derived Key", - outputLength: 16) + outputLength: 16 + ) return authenticationkey } func generateDevicePasswordVerifier( deviceGroupKey: String, deviceKey: String, - password: String) -> (salt: Data, passwordVerifier: Data) { + password: String + ) -> (salt: Data, passwordVerifier: Data) { let passwordVerifier = SRPClientState.calculateDevicePasswordVerifier( deviceGroupKey: deviceGroupKey, deviceKey: deviceKey, password: password, - commonState: commonState) + commonState: commonState + ) let verifierData = Data(AmplifyBigIntHelper.getSignedData( num: passwordVerifier.passwordVerifier)) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift index 2b1c549df6..ed7d5a5a1c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/SRP/SRPClientBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AmplifySRP +import Foundation protocol SRPClientBehavior { @@ -14,24 +14,29 @@ protocol SRPClientBehavior { func generateClientKeyPair() -> SRPKeys - func calculateSharedSecret(username: String, - password: String, - saltHexValue: String, - clientPrivateKeyHexValue: String, - clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String + func calculateSharedSecret( + username: String, + password: String, + saltHexValue: String, + clientPrivateKeyHexValue: String, + clientPublicKeyHexValue: String, + serverPublicKeyHexValue: String + ) throws -> String static func calculateUHexValue( clientPublicKeyHexValue: String, - serverPublicKeyHexValue: String) throws -> String + serverPublicKeyHexValue: String + ) throws -> String static func generateAuthenticationKey( - sharedSecretHexValue: String, uHexValue: String) throws -> Data + sharedSecretHexValue: String, uHexValue: String + ) throws -> Data func generateDevicePasswordVerifier( deviceGroupKey: String, deviceKey: String, - password: String) -> (salt: Data, passwordVerifier: Data) + password: String + ) -> (salt: Data, passwordVerifier: Data) } enum SRPError: Error { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift index dbe795e4fc..7a0610bbfa 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSCognitoIdentity import AWSClientRuntime +import AWSCognitoIdentity +import Foundation // AWSCognitoIdentity extension AWSCognitoIdentity.ExternalServiceException: AuthErrorConvertible { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift index 0b3f3c2fa4..aa9ae2d341 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSCognitoIdentityProvider import AWSClientRuntime +import AWSCognitoIdentityProvider +import Foundation extension ForbiddenException: AuthErrorConvertible { var fallbackDescription: String { "Access to the requested resource is forbidden" } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift index e811b761d9..6221452a2f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation /// A type that can be represented as an AuthError /// diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift index 942c410f70..56f7a22932 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import ClientRuntime +import Foundation extension ClientError: AuthErrorConvertible { var fallbackDescription: String { "Client Error" } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift index 8244b277a5..2bdff43b41 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AwsCommonRuntimeKit -import AwsCIo import AwsCHttp +import AwsCIo +import AwsCommonRuntimeKit +import Foundation private let connectivityErrorCodes: Set = [ AWS_ERROR_HTTP_CONNECTION_CLOSED.rawValue, @@ -30,8 +30,7 @@ private let connectivityErrorCodes: Set = [ extension CommonRunTimeError: AuthErrorConvertible { var authError: AuthError { - let error: CRTError - switch self { case .crtError(let crtError): error = crtError } + let error: CRTError = switch self { case .crtError(let crtError): crtError } if connectivityErrorCodes.contains(UInt32(error.code)) { return .service(error.name, error.message, AWSCognitoAuthError.network) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift index 532cd251aa..4b811ad4dd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/AuthUserAttribute+Helper.swift @@ -6,8 +6,8 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation extension AuthUserAttribute { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift index 570f5bfb5d..b68e4a435c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/ListDevicesOutputResponse+Helper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider import AWSPluginsCore +import Foundation extension CognitoIdentityProviderClientTypes.DeviceType { @@ -27,6 +27,7 @@ extension CognitoIdentityProviderClientTypes.DeviceType { attributes: attributes, createdDate: deviceCreateDate, lastAuthenticatedDate: deviceLastAuthenticatedDate, - lastModifiedDate: deviceLastModifiedDate) + lastModifiedDate: deviceLastModifiedDate + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift index df971aef31..a416c46163 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/Helpers/SignUpOutputResponse+Helper.swift @@ -6,13 +6,13 @@ // import Amplify -import Foundation import AWSCognitoIdentityProvider +import Foundation extension SignUpOutput { var authResponse: AuthSignUpResult { - if self.userConfirmed { + if userConfirmed { return .init(.done, userID: userSub) } return AuthSignUpResult( @@ -46,7 +46,8 @@ extension CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType { } return AuthCodeDeliveryDetails( destination: destination, - attributeKey: AuthUserAttributeKey(rawValue: attributeToVerify)) + attributeKey: AuthUserAttributeKey(rawValue: attributeToVerify) + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift index c4328aac58..92317a612b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSClientRuntime import ClientRuntime +import Foundation public typealias NetworkResult = (Result) -> Void diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift index 8c3a6972be..ad8c591910 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalytics.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation @_spi(KeychainStore) import AWSPluginsCore struct UserPoolAnalytics: UserPoolAnalyticsBehavior { @@ -15,14 +15,16 @@ struct UserPoolAnalytics: UserPoolAnalyticsBehavior { static let AWSPinpointContextKeychainUniqueIdKey = "com.amazonaws.AWSPinpointContextKeychainUniqueIdKey" let pinpointEndpoint: String? - init(_ configuration: UserPoolConfigurationData?, - credentialStoreEnvironment: CredentialStoreEnvironment) throws { + init( + _ configuration: UserPoolConfigurationData?, + credentialStoreEnvironment: CredentialStoreEnvironment + ) throws { if let pinpointId = configuration?.pinpointAppId, !pinpointId.isEmpty { - pinpointEndpoint = try UserPoolAnalytics.getInternalPinpointEndpoint( + self.pinpointEndpoint = try UserPoolAnalytics.getInternalPinpointEndpoint( credentialStoreEnvironment) } else { - pinpointEndpoint = nil + self.pinpointEndpoint = nil } } @@ -37,15 +39,17 @@ struct UserPoolAnalytics: UserPoolAnalyticsBehavior { AWSPinpointContextKeychainUniqueIdKey) else { let uniqueValue = UUID().uuidString.lowercased() - try legacyKeychainStore._set(AWSPinpointContextKeychainUniqueIdKey, - key: uniqueValue) + try legacyKeychainStore._set( + AWSPinpointContextKeychainUniqueIdKey, + key: uniqueValue + ) return uniqueValue } return value } func analyticsMetadata() -> CognitoIdentityProviderClientTypes.AnalyticsMetadataType? { - if let pinpointEndpoint = pinpointEndpoint { + if let pinpointEndpoint { return .init(analyticsEndpointId: pinpointEndpoint) } return nil diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift index c8ceddf5a0..53a6d68006 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/UserPoolAnalytics/UserPoolAnalyticsBehavior.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation protocol UserPoolAnalyticsBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift index ce3d08e37d..4775198989 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/AuthConfiguration.swift @@ -43,8 +43,10 @@ extension AuthConfiguration: Codable { guard userConfigData != nil || idpConfigData != nil else { throw DecodingError.dataCorrupted( - DecodingError.Context(codingPath: values.codingPath, - debugDescription: "Unable to decode") + DecodingError.Context( + codingPath: values.codingPath, + debugDescription: "Unable to decode" + ) ) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift index 42ac10651c..56141cfebc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/DeviceMetadata.swift @@ -19,9 +19,11 @@ enum DeviceMetadata { let deviceGroupKey: String let deviceSecret: String - init(deviceKey: String, - deviceGroupKey: String, - deviceSecret: String = UUID().uuidString) { + init( + deviceKey: String, + deviceGroupKey: String, + deviceSecret: String = UUID().uuidString + ) { self.deviceKey = deviceKey self.deviceGroupKey = deviceGroupKey self.deviceSecret = deviceSecret @@ -59,13 +61,14 @@ extension DeviceMetadata: CustomDebugStringConvertible { extension CognitoIdentityProviderClientTypes.AuthenticationResultType { var deviceMetadata: DeviceMetadata { - if let newDeviceMetadata = newDeviceMetadata, + if let newDeviceMetadata, let deviceKey = newDeviceMetadata.deviceKey, let deviceGroupKey = newDeviceMetadata.deviceGroupKey { let data = DeviceMetadata.Data( deviceKey: deviceKey, - deviceGroupKey: deviceGroupKey) + deviceGroupKey: deviceGroupKey + ) return .metadata(data) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift index 03d15cb9f2..fd75c7a9ab 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/FederatedToken.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct FederatedToken { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift index 4c62415442..c342ca8dca 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIConfigurationData.swift @@ -18,9 +18,11 @@ struct HostedUIConfigurationData: Equatable { // OAuth related information let oauth: OAuthConfigurationData - init(clientId: String, - oauth: OAuthConfigurationData, - clientSecret: String? = nil) { + init( + clientId: String, + oauth: OAuthConfigurationData, + clientSecret: String? = nil + ) { self.clientId = clientId self.oauth = oauth self.clientSecret = clientSecret diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift index 9f0d0b3f28..7ef648ebdf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIOptions.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct HostedUIOptions { @@ -32,10 +32,10 @@ extension HostedUIOptions: Codable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - scopes = try values.decode(Array.self, forKey: .scopes) - providerInfo = try values.decode(HostedUIProviderInfo.self, forKey: .providerInfo) - preferPrivateSession = try values.decode(Bool.self, forKey: .preferPrivateSession) - presentationAnchor = nil + self.scopes = try values.decode(Array.self, forKey: .scopes) + self.providerInfo = try values.decode(HostedUIProviderInfo.self, forKey: .providerInfo) + self.preferPrivateSession = try values.decode(Bool.self, forKey: .preferPrivateSession) + self.presentationAnchor = nil } func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift index 799be98f7b..ba4bc4db20 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/HostedUIProviderInfo.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation struct HostedUIProviderInfo: Equatable { @@ -24,8 +24,8 @@ extension HostedUIProviderInfo: Codable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - idpIdentifier = try values.decodeIfPresent(String.self, forKey: .idpIdentifier) - authProvider = nil + self.idpIdentifier = try values.decodeIfPresent(String.self, forKey: .idpIdentifier) + self.authProvider = nil } func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift index c8a5297f86..71bfc036eb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation struct RespondToAuthChallenge: Equatable { @@ -24,10 +24,12 @@ struct RespondToAuthChallenge: Equatable { extension RespondToAuthChallenge { var codeDeliveryDetails: AuthCodeDeliveryDetails { - guard let parameters = parameters, + guard let parameters, let medium = parameters["CODE_DELIVERY_DELIVERY_MEDIUM"] else { - return AuthCodeDeliveryDetails(destination: .unknown(nil), - attributeKey: nil) + return AuthCodeDeliveryDetails( + destination: .unknown(nil), + attributeKey: nil + ) } var deliveryDestination = DeliveryDestination.unknown(nil) @@ -35,8 +37,10 @@ extension RespondToAuthChallenge { if medium == "SMS" { deliveryDestination = .sms(destination) } - return AuthCodeDeliveryDetails(destination: deliveryDestination, - attributeKey: nil) + return AuthCodeDeliveryDetails( + destination: deliveryDestination, + attributeKey: nil + ) } var getAllowedMFATypesForSelection: Set { @@ -51,8 +55,8 @@ extension RespondToAuthChallenge { private func getMFATypes(forKey key: String) -> Set { guard let mfaTypeParameters = parameters?[key], let mfaTypesArray = try? JSONDecoder().decode( - [String].self, - from: Data(mfaTypeParameters.utf8) + [String].self, + from: Data(mfaTypeParameters.utf8) ) else { return .init() } @@ -61,8 +65,10 @@ extension RespondToAuthChallenge { } var debugDictionary: [String: Any] { - return ["challenge": challenge, - "username": username.masked()] + return [ + "challenge": challenge, + "username": username.masked() + ] } func getChallengeKey() throws -> String { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift index dad365c91d..505e6fe033 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignInEventData.swift @@ -15,10 +15,12 @@ struct SignInEventData { let signInMethod: SignInMethod - init(username: String?, - password: String?, - clientMetadata: [String: String] = [:], - signInMethod: SignInMethod) { + init( + username: String?, + password: String?, + clientMetadata: [String: String] = [:], + signInMethod: SignInMethod + ) { self.username = username self.password = password self.clientMetadata = clientMetadata diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift index af5d436284..e4dc0770c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignOutEventData.swift @@ -43,8 +43,8 @@ extension SignOutEventData: Codable { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - globalSignOut = try values.decode(Bool.self, forKey: .globalSignOut) - presentationAnchor = nil + self.globalSignOut = try values.decode(Bool.self, forKey: .globalSignOut) + self.presentationAnchor = nil } func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift index da3dc0bf02..b75f93085e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/SignedInData.swift @@ -15,10 +15,11 @@ struct SignedInData { let deviceMetadata: DeviceMetadata let cognitoUserPoolTokens: AWSCognitoUserPoolTokens - init(signedInDate: Date, - signInMethod: SignInMethod, - deviceMetadata: DeviceMetadata = .noData, - cognitoUserPoolTokens: AWSCognitoUserPoolTokens + init( + signedInDate: Date, + signInMethod: SignInMethod, + deviceMetadata: DeviceMetadata = .noData, + cognitoUserPoolTokens: AWSCognitoUserPoolTokens ) { let user = try? TokenParserHelper.getAuthUser(accessToken: cognitoUserPoolTokens.accessToken) self.userId = user?.userId ?? "unknown" diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift index 249c189781..b65b7af350 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/AuthorizationError.swift @@ -25,7 +25,8 @@ extension AuthorizationError: AuthErrorConvertible { return .sessionExpired( "Session expired", "Invoke Auth.signIn to re-authenticate the user", - error) + error + ) case .configuration(let message): return .configuration(message, "") case .service(let error): @@ -35,7 +36,8 @@ extension AuthorizationError: AuthErrorConvertible { return .service( "Service error occurred", AmplifyErrorMessages.reportBugToAWS(), - error) + error + ) } case .invalidState(let message): return .invalidState(message, AuthPluginErrorConstants.invalidStateError, nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift index 72e3857a8a..692ff4a4e8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/FetchSessionError.swift @@ -55,18 +55,21 @@ extension FetchSessionError: AuthErrorConvertible { case .noIdentityPool: return .configuration( "No identity pool configuration found", - AuthPluginErrorConstants.configurationError) + AuthPluginErrorConstants.configurationError + ) case .noUserPool: return .configuration( "No user pool configuration found", - AuthPluginErrorConstants.configurationError) + AuthPluginErrorConstants.configurationError + ) case .invalidTokens: return .unknown( "Invalid tokens received when refreshing session") case .notAuthorized: return .notAuthorized( "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) + AuthPluginErrorConstants.notAuthorizedError + ) case .invalidIdentityID: return .unknown("Invalid identity id received when fetching session") case .invalidAWSCredentials: @@ -74,7 +77,8 @@ extension FetchSessionError: AuthErrorConvertible { case .noCredentialsToRefresh: return .service( "No credentials found to refresh", - AmplifyErrorMessages.reportBugToAWS()) + AmplifyErrorMessages.reportBugToAWS() + ) case .federationNotSupportedDuringRefresh: return .unknown( "Refreshing credentials from federationToIdentityPool is not supported \(AmplifyErrorMessages.reportBugToAWS())") @@ -85,7 +89,8 @@ extension FetchSessionError: AuthErrorConvertible { return .service( "Service error occurred", AmplifyErrorMessages.reportBugToAWS(), - error) + error + ) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift index 7aaff48375..b3ece1f910 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Errors/SignOutError.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation enum SignOutError: Error { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift index ac3b2bb595..6350703e76 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/AuthEvents.swift @@ -44,9 +44,11 @@ struct AuthEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = Date()) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = Date() + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift index 28522a3b3a..323f142dd7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/CredentialStoreEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation enum CredentialStoreData: Codable, Equatable { case amplifyCredentials(AmplifyCredentials) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift index 728deb5c30..2187054962 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/DeleteUserEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation typealias AccessToken = String @@ -41,9 +41,11 @@ struct DeleteUserEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift index 387262e785..186454befc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SetUpTOTPEvent.swift @@ -43,9 +43,11 @@ struct SetUpTOTPEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift index c85b03bf22..b45e12b3e1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInChallengeEvent.swift @@ -34,9 +34,11 @@ struct SignInChallengeEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift index 6733421a1f..97faac9dd8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignInEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation typealias Username = String typealias Password = String @@ -82,9 +82,11 @@ struct SignInEvent: StateMachineEvent { } } - init(id: String = UUID().uuidString, - eventType: EventType, - time: Date? = nil) { + init( + id: String = UUID().uuidString, + eventType: EventType, + time: Date? = nil + ) { self.id = id self.eventType = eventType self.time = time diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift index 3d223e5a7a..85475dc293 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Events/SignOutEvent.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation struct SignOutEvent: StateMachineEvent { var data: Any? @@ -14,30 +14,37 @@ struct SignOutEvent: StateMachineEvent { enum EventType { case signOutGlobally( SignedInData, - hostedUIError: AWSCognitoHostedUIError? = nil) + hostedUIError: AWSCognitoHostedUIError? = nil + ) case revokeToken( SignedInData, hostedUIError: AWSCognitoHostedUIError? = nil, - globalSignOutError: AWSCognitoGlobalSignOutError? = nil) + globalSignOutError: AWSCognitoGlobalSignOutError? = nil + ) case signOutLocally( SignedInData, hostedUIError: AWSCognitoHostedUIError? = nil, globalSignOutError: AWSCognitoGlobalSignOutError? = nil, - revokeTokenError: AWSCognitoRevokeTokenError? = nil) + revokeTokenError: AWSCognitoRevokeTokenError? = nil + ) case signOutGuest case invokeHostedUISignOut(SignOutEventData, SignedInData) - case signedOutSuccess(hostedUIError: AWSCognitoHostedUIError? = nil, - globalSignOutError: AWSCognitoGlobalSignOutError? = nil, - revokeTokenError: AWSCognitoRevokeTokenError? = nil) + case signedOutSuccess( + hostedUIError: AWSCognitoHostedUIError? = nil, + globalSignOutError: AWSCognitoGlobalSignOutError? = nil, + revokeTokenError: AWSCognitoRevokeTokenError? = nil + ) - case globalSignOutError(SignedInData, - globalSignOutError: AWSCognitoGlobalSignOutError, - hostedUIError: AWSCognitoHostedUIError? = nil) + case globalSignOutError( + SignedInData, + globalSignOutError: AWSCognitoGlobalSignOutError, + hostedUIError: AWSCognitoHostedUIError? = nil + ) case signedOutFailure(AuthenticationError) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift index e68f8fbce1..7dc4b5bf32 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/AuthorizationState.swift @@ -20,12 +20,15 @@ enum AuthorizationState: State { case federatingToIdentityPool( FetchAuthSessionState, FederatedToken, - existingCredentials: AmplifyCredentials) + existingCredentials: AmplifyCredentials + ) case fetchingUnAuthSession(FetchAuthSessionState) - case fetchingAuthSessionWithUserPool(FetchAuthSessionState, - SignedInData) + case fetchingAuthSessionWithUserPool( + FetchAuthSessionState, + SignedInData + ) case refreshingSession(existingCredentials: AmplifyCredentials, RefreshSessionState) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift index febd203c0b..fb6847a8cc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/CredentialStoreState.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation enum CredentialStoreState: State { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift index 56a8c92f92..3235f0cdf3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthState+Debug.swift @@ -11,23 +11,21 @@ extension AuthState: CustomDebugStringConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notConfigured: - additionalMetadataDictionary = [:] + [:] case .configuringAuth: - additionalMetadataDictionary = [:] + [:] case .configuringAuthentication(let authenticationState): - additionalMetadataDictionary = authenticationState.debugDictionary + authenticationState.debugDictionary case .validatingCredentialsAndConfiguration: - additionalMetadataDictionary = [:] + [:] case .configuringAuthorization(let authenticationState, let authorizationState): - additionalMetadataDictionary = authenticationState.debugDictionary.merging( + authenticationState.debugDictionary.merging( authorizationState.debugDictionary, uniquingKeysWith: {$1} ) case .configured(let authenticationState, let authorizationState): - additionalMetadataDictionary = authenticationState.debugDictionary.merging( + authenticationState.debugDictionary.merging( authorizationState.debugDictionary, uniquingKeysWith: {$1} ) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift index 451f8e36b5..37737259e0 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthenticationState+Debug.swift @@ -8,34 +8,33 @@ extension AuthenticationState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notConfigured: - additionalMetadataDictionary = [:] + [:] case .configured: - additionalMetadataDictionary = [:] + [:] case .signingOut(let signOutState): - additionalMetadataDictionary = signOutState.debugDictionary + signOutState.debugDictionary case .signedOut(let signedOutData): - additionalMetadataDictionary = signedOutData.debugDictionary + signedOutData.debugDictionary case .signingIn(let signInState): - additionalMetadataDictionary = signInState.debugDictionary + signInState.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .federatedToIdentityPool, .clearingFederation, .federatingToIdentityPool: - additionalMetadataDictionary = [:] + [:] case .deletingUser(_, let deleteUserState): - additionalMetadataDictionary = deleteUserState.debugDictionary + deleteUserState.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift index d66207a120..5a298c0c5a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/AuthorizationState+Debug.swift @@ -19,8 +19,10 @@ extension AuthorizationState: CustomDebugDictionaryConvertible { .deletingUser: additionalMetadataDictionary = [:] case .refreshingSession(existingCredentials: let credentials, let state): - additionalMetadataDictionary = ["existing": credentials.debugDescription, - "refreshState": state.debugDictionary] + additionalMetadataDictionary = [ + "existing": credentials.debugDescription, + "refreshState": state.debugDictionary + ] case .fetchingUnAuthSession(let state), .fetchingAuthSessionWithUserPool(let state, _), .federatingToIdentityPool(let state, _, _): diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift index 4b9eb908af..b4a63e689e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CredentialStoreState+Debug.swift @@ -9,26 +9,24 @@ import Foundation extension CredentialStoreState: CustomDebugStringConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notConfigured, .migratingLegacyStore, .loadingStoredCredentials, .storingCredentials, .clearingCredentials, .idle: - additionalMetadataDictionary = [:] + [:] case .clearedCredential(let dataType): - additionalMetadataDictionary = [ + [ "clearedDataType": dataType ] case .success(let data): - additionalMetadataDictionary = [ + [ "savedData": data ] case .error(let error): - additionalMetadataDictionary = [ + [ "errorType": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift index 316bf2daa2..6267589485 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/CustomSignInState+Debug.swift @@ -11,16 +11,15 @@ extension CustomSignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .initiating(let signInEventData): - additionalMetadataDictionary = signInEventData.debugDictionary + signInEventData.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift index f2a0c1dc88..5a983348da 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeleteUserState+Debug.swift @@ -8,18 +8,17 @@ extension DeleteUserState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .deletingUser: - additionalMetadataDictionary = [:] + [:] case .signingOut(let signedOutState): - additionalMetadataDictionary = signedOutState.debugDictionary + signedOutState.debugDictionary case .userDeleted: - additionalMetadataDictionary = [:] + [:] case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift index 3b0e80913d..4adb72c240 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/DeviceSRPState+Debug.swift @@ -11,20 +11,19 @@ extension DeviceSRPState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .initiatingDeviceSRP: - additionalMetadataDictionary = [:] + [:] case .cancelling: - additionalMetadataDictionary = [:] + [:] case .respondingDevicePasswordVerifier(let srpStateData): - additionalMetadataDictionary = srpStateData.debugDictionary + srpStateData.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift index 57c7f9646a..415d478e80 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/FetchAuthSessionState+Debug.swift @@ -10,18 +10,17 @@ import Foundation extension FetchAuthSessionState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .fetchingIdentityID: - additionalMetadataDictionary = [:] + [:] case .fetchingAWSCredentials: - additionalMetadataDictionary = [:] + [:] case .fetched: - additionalMetadataDictionary = [:] + [:] case .error(let error): - additionalMetadataDictionary = ["error": error] + ["error": error] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift index 82b14798f7..b5bdd699ec 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/HostedUISignInState+Debug.swift @@ -8,14 +8,13 @@ extension HostedUISignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .error(let error): - additionalMetadataDictionary = ["error": error] + ["error": error] default: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift index a0df091306..df1c70da71 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/MigrateSignInState+Debug.swift @@ -11,18 +11,16 @@ extension MigrateSignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .signingIn: - additionalMetadataDictionary = [:] + [:] case .signedIn(let signedInData): - additionalMetadataDictionary = ["SignedInData": signedInData.debugDictionary] + ["SignedInData": signedInData.debugDictionary] case .error: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift index fedc330c46..59a4c79383 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/RefreshSessionState+Debug.swift @@ -10,14 +10,13 @@ import Foundation extension RefreshSessionState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .fetchingAuthSessionWithUserPool(let state, _): - additionalMetadataDictionary = ["fetchingSession": state.debugDictionary] + ["fetchingSession": state.debugDictionary] case .error(let error): - additionalMetadataDictionary = ["error": error] + ["error": error] default: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift index f61b26644b..df3cc457c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SRPSignInState+Debug.swift @@ -11,20 +11,19 @@ extension SRPSignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .notStarted: - additionalMetadataDictionary = [:] + [:] case .initiatingSRPA(let signInEventData): - additionalMetadataDictionary = signInEventData.debugDictionary + signInEventData.debugDictionary case .cancelling: - additionalMetadataDictionary = [:] + [:] case .respondingPasswordVerifier(let srpStateData): - additionalMetadataDictionary = srpStateData.debugDictionary + srpStateData.debugDictionary case .signedIn(let signedInData): - additionalMetadataDictionary = signedInData.debugDictionary + signedInData.debugDictionary case .error(let error): - additionalMetadataDictionary = [ + [ "Error": error ] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift index 7ded00a585..e8480bdfbd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInChallengeState+Debug.swift @@ -21,7 +21,8 @@ extension SignInChallengeState: CustomDebugDictionaryConvertible { [ "error": error ], - uniquingKeysWith: {$1}) + uniquingKeysWith: {$1} + ) default: additionalMetadataDictionary = [:] } return [type: additionalMetadataDictionary] diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift index 1cba475ba8..05fb240464 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInState+Debug.swift @@ -11,45 +11,45 @@ extension SignInState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .signingInWithSRP(let srpSignInState, let signInEventData): - additionalMetadataDictionary = srpSignInState.debugDictionary.merging( + srpSignInState.debugDictionary.merging( signInEventData.debugDictionary, uniquingKeysWith: {$1} ) case .signingInWithHostedUI(let substate): - additionalMetadataDictionary = substate.debugDictionary + substate.debugDictionary case .resolvingChallenge(let challengeState, let challengeType, let signInMethod): - additionalMetadataDictionary = challengeState.debugDictionary.merging( + challengeState.debugDictionary.merging( [ "challengeType": challengeType, "signInMethod": signInMethod ], - uniquingKeysWith: {$1}) + uniquingKeysWith: {$1} + ) case .notStarted: - additionalMetadataDictionary = [:] + [:] case .signingInWithSRPCustom(let srpstate, _): - additionalMetadataDictionary = ["SRPSignInStaet": srpstate.debugDictionary] + ["SRPSignInStaet": srpstate.debugDictionary] case .signingInWithCustom(let customSignIn, _): - additionalMetadataDictionary = ["CustomSignInState": customSignIn.debugDictionary] + ["CustomSignInState": customSignIn.debugDictionary] case .signingInViaMigrateAuth(let migrateSignInState, _): - additionalMetadataDictionary = ["MigrateSignInState": migrateSignInState.debugDictionary] + ["MigrateSignInState": migrateSignInState.debugDictionary] case .confirmingDevice: - additionalMetadataDictionary = [:] + [:] case .resolvingDeviceSrpa(let deviceSRPState): - additionalMetadataDictionary = ["DeviceSRPState": deviceSRPState.debugDictionary] + ["DeviceSRPState": deviceSRPState.debugDictionary] case .signedIn(let data): - additionalMetadataDictionary = ["SignedInData": data.debugDictionary] + ["SignedInData": data.debugDictionary] case .resolvingTOTPSetup(let signInTOTPSetupState, let signInEventData): - additionalMetadataDictionary = [ + [ "SignInTOTPSetupState": signInTOTPSetupState.debugDictionary, - "SignInEventData": signInEventData.debugDictionary] + "SignInEventData": signInEventData.debugDictionary + ] case .error: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift index 53b796378f..7adc148cfb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignInTOTPSetupState+Debug.swift @@ -10,20 +10,20 @@ import Foundation extension SignInTOTPSetupState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .waitingForAnswer(let signInTOTPSetupData): - additionalMetadataDictionary = signInTOTPSetupData.debugDictionary + signInTOTPSetupData.debugDictionary case .verifying(let signInSetupData, let confirmSignInEventData): - additionalMetadataDictionary = confirmSignInEventData.debugDictionary.merging( + confirmSignInEventData.debugDictionary.merging( signInSetupData.debugDictionary, - uniquingKeysWith: {$1}) + uniquingKeysWith: {$1} + ) case .error(let data, let error): - additionalMetadataDictionary = [ + [ "totpSetupData": data ?? "Nil", "error": error ] - default: additionalMetadataDictionary = [:] + default: [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift index f8805e88c5..9bffe49222 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/DebugInfo/SignOutState+Debug.swift @@ -11,13 +11,11 @@ extension SignOutState: CustomDebugDictionaryConvertible { var debugDictionary: [String: Any] { - let additionalMetadataDictionary: [String: Any] - - switch self { + let additionalMetadataDictionary: [String: Any] = switch self { case .error(let error): - additionalMetadataDictionary = ["Error": error] + ["Error": error] default: - additionalMetadataDictionary = [:] + [:] } return [type: additionalMetadataDictionary] } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift index 81cea4671c..b76c2fcac7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/HostedUISignInState.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation enum HostedUISignInState: State { case notStarted diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift index 48e816f8fc..dffbe0df61 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/States/RefreshSessionState.swift @@ -39,8 +39,10 @@ extension RefreshSessionState: Equatable { (.refreshed, .refreshed), (.error, .error): return true - case (.fetchingAuthSessionWithUserPool(let lhsFetchState, _), - .fetchingAuthSessionWithUserPool(let rhsFetchState, _)): + case ( + .fetchingAuthSessionWithUserPool(let lhsFetchState, _), + .fetchingAuthSessionWithUserPool(let rhsFetchState, _) + ): return lhsFetchState == rhsFetchState default: return false diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift index 1a37569191..c65f88ff6c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/KeychainStoreError+AuthConvertible.swift @@ -5,26 +5,26 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSPluginsCore import Amplify +import AWSPluginsCore +import Foundation extension KeychainStoreError: AuthErrorConvertible { var authError: AuthError { switch self { case .configuration(let message): - return .configuration(message, self.recoverySuggestion) + return .configuration(message, recoverySuggestion) case .unknown(let errorDescription, let error): return .unknown(errorDescription, error) case .conversionError(let errorDescription, let error): - return .configuration(errorDescription, self.recoverySuggestion, error) + return .configuration(errorDescription, recoverySuggestion, error) case .codingError(let errorDescription, let error): - return .configuration(errorDescription, self.recoverySuggestion, error) + return .configuration(errorDescription, recoverySuggestion, error) case .itemNotFound: - return .service(self.errorDescription, self.recoverySuggestion) + return .service(errorDescription, recoverySuggestion) case .securityError: - return .service(self.errorDescription, self.recoverySuggestion) + return .service(errorDescription, recoverySuggestion) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift index a6e21bced9..6812413bd6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import ClientRuntime import AWSCognitoIdentityProvider +import ClientRuntime +import Foundation extension SignInError { @@ -50,7 +50,8 @@ extension SignInError: AuthErrorConvertible { return AuthError.validation( field, AuthPluginErrorConstants.signInUsernameError.errorDescription, - AuthPluginErrorConstants.signInUsernameError.recoverySuggestion) + AuthPluginErrorConstants.signInUsernameError.recoverySuggestion + ) case .unknown(let message): return .unknown(message, nil) case .hostedUI(let error): @@ -66,54 +67,64 @@ extension HostedUIError: AuthErrorConvertible { case .signInURI: return .configuration( AuthPluginErrorConstants.hostedUISignInURI.errorDescription, - AuthPluginErrorConstants.hostedUISignInURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUISignInURI.recoverySuggestion + ) case .tokenURI: return .configuration( AuthPluginErrorConstants.hostedUITokenURI.errorDescription, - AuthPluginErrorConstants.hostedUITokenURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUITokenURI.recoverySuggestion + ) case .signOutURI: return .configuration( AuthPluginErrorConstants.hostedUISignOutURI.errorDescription, - AuthPluginErrorConstants.hostedUISignOutURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUISignOutURI.recoverySuggestion + ) case .signOutRedirectURI: return .configuration( AuthPluginErrorConstants.hostedUISignOutRedirectURI.errorDescription, - AuthPluginErrorConstants.hostedUISignOutRedirectURI.recoverySuggestion) + AuthPluginErrorConstants.hostedUISignOutRedirectURI.recoverySuggestion + ) case .proofCalculation: return .invalidState( AuthPluginErrorConstants.hostedUIProofCalculation.errorDescription, - AuthPluginErrorConstants.hostedUIProofCalculation.recoverySuggestion) + AuthPluginErrorConstants.hostedUIProofCalculation.recoverySuggestion + ) case .codeValidation: return .service( AuthPluginErrorConstants.hostedUISecurityFailedError.errorDescription, - AuthPluginErrorConstants.hostedUISecurityFailedError.recoverySuggestion) + AuthPluginErrorConstants.hostedUISecurityFailedError.recoverySuggestion + ) case .tokenParsing: return .service( AuthPluginErrorConstants.tokenParsingError.errorDescription, - AuthPluginErrorConstants.tokenParsingError.recoverySuggestion) + AuthPluginErrorConstants.tokenParsingError.recoverySuggestion + ) case .cancelled: return .service( AuthPluginErrorConstants.hostedUIUserCancelledError.errorDescription, AuthPluginErrorConstants.hostedUIUserCancelledError.recoverySuggestion, - AWSCognitoAuthError.userCancelled) + AWSCognitoAuthError.userCancelled + ) case .invalidContext: return .invalidState( AuthPluginErrorConstants.hostedUIInvalidPresentation.errorDescription, - AuthPluginErrorConstants.hostedUIInvalidPresentation.recoverySuggestion) + AuthPluginErrorConstants.hostedUIInvalidPresentation.recoverySuggestion + ) case .unableToStartASWebAuthenticationSession: return .service( AuthPluginErrorConstants.hostedUIUnableToStartASWebAuthenticationSession.errorDescription, AuthPluginErrorConstants.hostedUIUnableToStartASWebAuthenticationSession.recoverySuggestion, - AWSCognitoAuthError.errorLoadingUI) + AWSCognitoAuthError.errorLoadingUI + ) case .serviceMessage(let message): return .service(message, AuthPluginErrorConstants.serviceError) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift index 56a1644467..9868d0f4b1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignUpError+Helper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension SignUpError: AuthErrorConvertible { var authError: AuthError { @@ -17,12 +17,14 @@ extension SignUpError: AuthErrorConvertible { return AuthError.validation( AuthPluginErrorConstants.signUpUsernameError.field, AuthPluginErrorConstants.signUpUsernameError.errorDescription, - AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil + ) case .invalidPassword: return AuthError.validation( AuthPluginErrorConstants.signUpPasswordError.field, AuthPluginErrorConstants.signUpPasswordError.errorDescription, - AuthPluginErrorConstants.signUpPasswordError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpPasswordError.recoverySuggestion, nil + ) case .invalidConfirmationCode(message: let message): fatalError("Fix me \(message)") case .service(error: let error): diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift index d4f9e98c6c..d263dde4f4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/AuthState/AuthState+Resolver.swift @@ -32,7 +32,8 @@ extension AuthState { case .validateCredentialAndConfiguration(let authConfiguration, let credentials): let action = ValidateCredentialsAndConfiguration( authConfiguration: authConfiguration, - cachedCredentials: credentials) + cachedCredentials: credentials + ) let newState = AuthState.validatingCredentialsAndConfiguration return .init(newState: newState, actions: [action]) default: @@ -44,7 +45,8 @@ extension AuthState { let newState = AuthState.configuringAuthentication(.notConfigured) let action = InitializeAuthenticationConfiguration( configuration: authConfiguration, - storedCredentials: storedCredentials) + storedCredentials: storedCredentials + ) return .init(newState: newState, actions: [action]) case .configureAuthorization(_, let storedCredentials): let newState = AuthState.configuringAuthorization(.notConfigured, .notConfigured) @@ -71,8 +73,10 @@ extension AuthState { let authNresolution = authenticationResolver.resolve(oldState: authenticationState, byApplying: event) let authZresolution = authorizationResolver.resolve(oldState: authorizationState, byApplying: event) guard case .authorizationConfigured = isAuthEvent(event)?.eventType else { - let newState = AuthState.configuringAuthorization(authNresolution.newState, - authZresolution.newState) + let newState = AuthState.configuringAuthorization( + authNresolution.newState, + authZresolution.newState + ) return .init(newState: newState, actions: authNresolution.actions + authZresolution.actions) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift index d7703d9482..b9f7c77b2c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authentication/AuthenticationState+Resolver.swift @@ -36,8 +36,10 @@ extension AuthenticationState { return .from(oldState) } case .signingOut(let signOutState): - return resolveSigningOutState(byApplying: event, - to: signOutState) + return resolveSigningOutState( + byApplying: event, + to: signOutState + ) case .signedOut(let signedOutData): if let authEvent = event as? AuthenticationEvent { return resolveSignedOut( byApplying: authEvent, to: signedOutData) @@ -56,7 +58,8 @@ extension AuthenticationState { return resolveDeleteUser( byApplying: deleteUserEvent, to: .notStarted, - with: signedInData) + with: signedInData + ) } else { return .from(oldState) } @@ -68,7 +71,8 @@ extension AuthenticationState { newState: .clearingFederation, actions: [ ClearFederationToIdentityPool() - ]) + ] + ) } else if let authZEvent = event.isAuthorizationEvent, case .startFederationToIdentityPool = authZEvent { return .init(newState: .federatingToIdentityPool) @@ -114,7 +118,8 @@ extension AuthenticationState { return resolveDeleteUser( byApplying: event, to: deleteUserState, - with: signedInData) + with: signedInData + ) } case .error: @@ -130,7 +135,8 @@ extension AuthenticationState { newState: .clearingFederation, actions: [ ClearFederationToIdentityPool() - ]) + ] + ) } else { return .from(oldState) } @@ -195,8 +201,10 @@ extension AuthenticationState { ) -> StateResolution { switch authEvent.eventType { case .signOutRequested(let signOutEventData): - let action = InitiateSignOut(signedInData: currentSignedInData, - signOutEventData: signOutEventData) + let action = InitiateSignOut( + signedInData: currentSignedInData, + signOutEventData: signOutEventData + ) let signOutState = SignOutState.notStarted let resolution = StateResolution( newState: AuthenticationState.signingOut(signOutState), @@ -207,7 +215,8 @@ extension AuthenticationState { case .cancelSignIn: let action = InitiateSignOut( signedInData: currentSignedInData, - signOutEventData: .init(globalSignOut: false)) + signOutEventData: .init(globalSignOut: false) + ) let signOutState = SignOutState.notStarted let resolution = StateResolution( newState: AuthenticationState.signingOut(signOutState), @@ -222,15 +231,18 @@ extension AuthenticationState { private func resolveDeleteUser( byApplying deleteUserEvent: StateMachineEvent, to oldState: DeleteUserState, - with signedInData: SignedInData) -> StateResolution { + with signedInData: SignedInData + ) -> StateResolution { let resolver = DeleteUserState.Resolver(signedInData: signedInData) let resolution = resolver.resolve(oldState: oldState, byApplying: deleteUserEvent) let newState = AuthenticationState.deletingUser(signedInData, resolution.newState) return .init(newState: newState, actions: resolution.actions) } - private func resolveSigningInState(oldState: AuthenticationState, - event: StateMachineEvent) -> StateResolution { + private func resolveSigningInState( + oldState: AuthenticationState, + event: StateMachineEvent + ) -> StateResolution { if let authEvent = event as? AuthenticationEvent, case .error(let error) = authEvent.eventType { return .init(newState: .error(error)) @@ -252,8 +264,10 @@ extension AuthenticationState { return .init(newState: .signedIn(signedInData)) } - let resolution = SignInState.Resolver().resolve(oldState: signInState, - byApplying: event) + let resolution = SignInState.Resolver().resolve( + oldState: signInState, + byApplying: event + ) return .init(newState: .signingIn(resolution.newState), actions: resolution.actions) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift index 51be1d9500..d7ca1f27ea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/Authorization/AuthorizationState+Resolver.swift @@ -29,7 +29,8 @@ extension AuthorizationState { signedInData: signedInData) return .init( newState: .fetchingAuthSessionWithUserPool(.notStarted, signedInData), - actions: [action]) + actions: [action] + ) case .error(let error): return .init(newState: .error(AuthorizationError.service(error: error))) case .cancelSignIn: @@ -53,17 +54,21 @@ extension AuthorizationState { } if case .startFederationToIdentityPool( - let federatedToken, let identityId) = event.isAuthorizationEvent { + let federatedToken, let identityId + ) = event.isAuthorizationEvent { let action = InitializeFederationToIdentityPool( federatedToken: federatedToken, - developerProvidedIdentityId: identityId) + developerProvidedIdentityId: identityId + ) return .init( newState: .federatingToIdentityPool( .notStarted, federatedToken, - existingCredentials: .noCredentials), - actions: [action]) + existingCredentials: .noCredentials + ), + actions: [action] + ) } return .from(oldState) @@ -81,23 +86,28 @@ extension AuthorizationState { let action = InitializeFederationToIdentityPool( federatedToken: federatedToken, - developerProvidedIdentityId: identityId) + developerProvidedIdentityId: identityId + ) return .init( newState: .federatingToIdentityPool( .notStarted, federatedToken, - existingCredentials: credentials), - actions: [action]) + existingCredentials: credentials + ), + actions: [action] + ) } if case .refreshSession(let forceRefresh) = event.isAuthorizationEvent { let action = InitializeRefreshSession( existingCredentials: credentials, - isForceRefresh: forceRefresh) + isForceRefresh: forceRefresh + ) let subState = RefreshSessionState.notStarted return .init(newState: .refreshingSession( existingCredentials: credentials, - subState), actions: [action]) + subState + ), actions: [action]) } if case .deleteUser = event.isDeleteUserEvent { @@ -107,17 +117,23 @@ extension AuthorizationState { return .from(oldState) case .federatingToIdentityPool( - let fetchSessionState, let federatedToken, let credentials): + let fetchSessionState, let federatedToken, let credentials + ): - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.identityPoolWithFederation( federatedToken: federatedToken, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } if case .receivedSessionError(let error) = event.isAuthorizationEvent { @@ -134,8 +150,10 @@ extension AuthorizationState { newState: .federatingToIdentityPool( resolution.newState, federatedToken, - existingCredentials: credentials), - actions: resolution.actions) + existingCredentials: credentials + ), + actions: resolution.actions + ) case .signingOut(let credentials): if let signOutEvent = event.isSignOutEvent, @@ -144,7 +162,7 @@ extension AuthorizationState { } if let authenEvent = event.isAuthenticationEvent, case .cancelSignOut = authenEvent { - if let credentials = credentials { + if let credentials { return .init(newState: .sessionEstablished(credentials)) } else { return .init(newState: .configured) @@ -164,14 +182,19 @@ extension AuthorizationState { case .fetchingUnAuthSession(let fetchSessionState): - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } if case .receivedSessionError(let error) = event.isAuthorizationEvent { @@ -184,31 +207,41 @@ extension AuthorizationState { let resolver = FetchAuthSessionState.Resolver() let resolution = resolver.resolve(oldState: fetchSessionState, byApplying: event) - return .init(newState: .fetchingUnAuthSession(resolution.newState), - actions: resolution.actions) + return .init( + newState: .fetchingUnAuthSession(resolution.newState), + actions: resolution.actions + ) case .fetchingAuthSessionWithUserPool(let fetchSessionState, let signedInData): - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } else if case .receivedSessionError(let fetchError) = event.isAuthorizationEvent { let amplifyCredentials = AmplifyCredentials.userPoolOnly( signedInData: signedInData) if case .noIdentityPool = fetchError { let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } let authorizationError = AuthorizationError.sessionError( fetchError, - amplifyCredentials) + amplifyCredentials + ) return .init(newState: .error(authorizationError)) } else if case .throwError(let error) = event.isAuthorizationEvent { @@ -216,20 +249,25 @@ extension AuthorizationState { signedInData: signedInData) let authorizationError = AuthorizationError.sessionError( .service(error), - amplifyCredentials) + amplifyCredentials + ) return .init(newState: .error(authorizationError)) } let resolver = FetchAuthSessionState.Resolver() let resolution = resolver.resolve(oldState: fetchSessionState, byApplying: event) - return .init(newState: .fetchingAuthSessionWithUserPool(resolution.newState, signedInData), - actions: resolution.actions) + return .init( + newState: .fetchingAuthSessionWithUserPool(resolution.newState, signedInData), + actions: resolution.actions + ) case .refreshingSession(let existingCredentials, let refreshState): if case .refreshed(let amplifyCredentials) = event.isAuthorizationEvent { let action = PersistCredentials(credentials: amplifyCredentials) - return .init(newState: .storingCredentials(amplifyCredentials), - actions: [action]) + return .init( + newState: .storingCredentials(amplifyCredentials), + actions: [action] + ) } if case .receivedSessionError(let error) = event.isAuthorizationEvent { @@ -243,7 +281,8 @@ extension AuthorizationState { let resolution = resolver.resolve(oldState: refreshState, byApplying: event) return .init(newState: .refreshingSession( existingCredentials: existingCredentials, - resolution.newState), actions: resolution.actions) + resolution.newState + ), actions: resolution.actions) case .storingCredentials: if case .sessionEstablished(let credentials) = event.isAuthorizationEvent { @@ -287,13 +326,16 @@ extension AuthorizationState { let action = InitializeFederationToIdentityPool( federatedToken: federatedToken, - developerProvidedIdentityId: identityId) + developerProvidedIdentityId: identityId + ) return .init( newState: .federatingToIdentityPool( .notStarted, federatedToken, - existingCredentials: existingCredentials), - actions: [action]) + existingCredentials: existingCredentials + ), + actions: [action] + ) } // If authorization is under session error, we try to refresh it again to see if @@ -302,11 +344,13 @@ extension AuthorizationState { case .sessionError(_, let credentials) = error { let action = InitializeRefreshSession( existingCredentials: credentials, - isForceRefresh: forceRefresh) + isForceRefresh: forceRefresh + ) let subState = RefreshSessionState.notStarted return .init(newState: .refreshingSession( existingCredentials: credentials, - subState), actions: [action]) + subState + ), actions: [action]) } return .from(oldState) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift index 370524c44f..827a677e8b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/CustomAuth/CustomSignInState+Resolver.swift @@ -50,7 +50,8 @@ extension CustomSignInState { let action = InitiateCustomAuth( username: username, clientMetadata: signInEventData.clientMetadata, - deviceMetadata: deviceMetadata) + deviceMetadata: deviceMetadata + ) return StateResolution( newState: CustomSignInState.initiating(signInEventData), actions: [action] @@ -62,11 +63,14 @@ extension CustomSignInState { private func resolveInitiating( from oldState: CustomSignInState, - byApplying signInEvent: SignInEvent) -> StateResolution { + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) default: return .from(oldState) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift index 34e5ad0f7b..e27ca8e1ac 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/DeleteUser/DeleteUserState+Resolver.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension DeleteUserState { @@ -16,8 +16,10 @@ extension DeleteUserState { let signedInData: SignedInData - func resolve(oldState: DeleteUserState, - byApplying event: StateMachineEvent) -> StateResolution { + func resolve( + oldState: DeleteUserState, + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -70,7 +72,7 @@ extension DeleteUserState { let resolution = resolver.resolve(oldState: signOutState, byApplying: event) switch resolution.newState { case .signedOut(let signedOutData): - let action = InformUserDeletedAndSignedOut(result: .success((signedOutData))) + let action = InformUserDeletedAndSignedOut(result: .success(signedOutData)) let newState = DeleteUserState.userDeleted(signedOutData) var resolutionActions = resolution.actions resolutionActions.append(action) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift index f0d2ddeba9..6956202404 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/FetchAuthSession/FetchAuthSessionState+Resolver.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSPluginsCore import Amplify +import AWSPluginsCore +import Foundation extension FetchAuthSessionState { @@ -15,8 +15,10 @@ extension FetchAuthSessionState { var defaultState: FetchAuthSessionState = .notStarted - func resolve(oldState: FetchAuthSessionState, - byApplying event: StateMachineEvent) + func resolve( + oldState: FetchAuthSessionState, + byApplying event: StateMachineEvent + ) -> StateResolution { guard let eventType = isFetchAuthSessionEvent(event)?.eventType else { @@ -28,22 +30,31 @@ extension FetchAuthSessionState { switch eventType { case .fetchUnAuthIdentityID: - return .init(newState: .fetchingIdentityID(UnAuthLoginsMapProvider()), - actions: [FetchAuthIdentityId()]) + return .init( + newState: .fetchingIdentityID(UnAuthLoginsMapProvider()), + actions: [FetchAuthIdentityId()] + ) case .fetchAuthenticatedIdentityID(let provider): - return .init(newState: .fetchingIdentityID(provider), - actions: [FetchAuthIdentityId(loginsMap: provider.loginsMap)]) + return .init( + newState: .fetchingIdentityID(provider), + actions: [FetchAuthIdentityId(loginsMap: provider.loginsMap)] + ) case .fetchAWSCredentials(let identityId, let loginsMapProvider): let action = FetchAuthAWSCredentials( loginsMap: loginsMapProvider.loginsMap, - identityID: identityId) - return .init(newState: .fetchingAWSCredentials(identityId, loginsMapProvider), - actions: [action]) + identityID: identityId + ) + return .init( + newState: .fetchingAWSCredentials(identityId, loginsMapProvider), + actions: [action] + ) case .throwError(let error): - return .init(newState: .error(error), - actions: [InformSessionError(error: error)]) + return .init( + newState: .error(error), + actions: [InformSessionError(error: error)] + ) default: return .from(oldState) } @@ -54,9 +65,12 @@ extension FetchAuthSessionState { case .fetchedIdentityID(let identityID): let action = FetchAuthAWSCredentials( loginsMap: loginsMapProvider.loginsMap, - identityID: identityID) - return .init(newState: .fetchingAWSCredentials(identityID, loginsMapProvider), - actions: [action]) + identityID: identityID + ) + return .init( + newState: .fetchingAWSCredentials(identityID, loginsMapProvider), + actions: [action] + ) case .throwError(let error): let action = InformSessionError(error: error) return .init(newState: .error(error), actions: [action]) @@ -70,7 +84,8 @@ extension FetchAuthSessionState { case .fetchedAWSCredentials(let identityID, let credentials): let action = InformSessionFetched( identityID: identityID, - credentials: credentials) + credentials: credentials + ) return .init(newState: .fetched(identityID, credentials), actions: [action]) case .throwError(let error): let action = InformSessionError(error: error) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift index 21e4ef5f70..ac4ec340b8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/MigrateAuth/MigrateSignInState+Resolver.swift @@ -49,7 +49,8 @@ extension MigrateSignInState { return errorStateWithCancelSignIn(error) } guard let password = signInEventData.password, - !password.isEmpty else { + !password.isEmpty + else { let error = SignInError.inputValidation( field: AuthPluginErrorConstants.signInPasswordError.field ) @@ -59,7 +60,8 @@ extension MigrateSignInState { username: username, password: password, clientMetadata: signInEventData.clientMetadata, - deviceMetadata: deviceMetadata) + deviceMetadata: deviceMetadata + ) return StateResolution( newState: MigrateSignInState.signingIn(signInEventData), actions: [action] @@ -71,11 +73,14 @@ extension MigrateSignInState { private func resolveInitiating( from oldState: MigrateSignInState, - byApplying signInEvent: SignInEvent) -> StateResolution { + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) default: return .from(oldState) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift index 3a0828f867..d64ad5f745 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/RefreshSession/RefreshSessionState+Resolver.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension RefreshSessionState { @@ -15,8 +15,10 @@ extension RefreshSessionState { var defaultState: RefreshSessionState = .notStarted // swiftlint:disable:next cyclomatic_complexity - func resolve(oldState: RefreshSessionState, - byApplying event: StateMachineEvent) -> StateResolution { + func resolve( + oldState: RefreshSessionState, + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -24,34 +26,46 @@ extension RefreshSessionState { if case .refreshCognitoUserPool(let signedInData) = event.isRefreshSessionEvent { let action = RefreshUserPoolTokens(existingSignedIndata: signedInData) - return .init(newState: .refreshingUserPoolToken(signedInData), - actions: [action]) + return .init( + newState: .refreshingUserPoolToken(signedInData), + actions: [action] + ) } if case .refreshCognitoUserPoolWithIdentityId( let signedInData, - let identityID) = event.isRefreshSessionEvent { + let identityID + ) = event.isRefreshSessionEvent { let action = RefreshUserPoolTokens(existingSignedIndata: signedInData) - return .init(newState: + return .init( + newState: .refreshingUserPoolTokenWithIdentity(signedInData, identityID), - actions: [action]) + actions: [action] + ) } if case .refreshUnAuthAWSCredentials(let identityID) = event.isRefreshSessionEvent { let provider = UnAuthLoginsMapProvider() - let action = FetchAuthAWSCredentials(loginsMap: provider.loginsMap, - identityID: identityID) - return .init(newState: .refreshingUnAuthAWSCredentials(identityID), - actions: [action]) + let action = FetchAuthAWSCredentials( + loginsMap: provider.loginsMap, + identityID: identityID + ) + return .init( + newState: .refreshingUnAuthAWSCredentials(identityID), + actions: [action] + ) } if case .refreshAWSCredentialsWithUserPool( let identityID, let signedInData, - let provider) = event.isRefreshSessionEvent { - let action = FetchAuthAWSCredentials(loginsMap: provider.loginsMap, - identityID: identityID) + let provider + ) = event.isRefreshSessionEvent { + let action = FetchAuthAWSCredentials( + loginsMap: provider.loginsMap, + identityID: identityID + ) return .init(newState: .refreshingAWSCredentialsWithUserPoolTokens( signedInData, identityID @@ -78,8 +92,10 @@ extension RefreshSessionState { if case .refreshIdentityInfo(let signedInData, _) = event.isRefreshSessionEvent { let action = InitializeFetchAuthSessionWithUserPool(signedInData: signedInData) - return .init(newState: .fetchingAuthSessionWithUserPool(.notStarted, signedInData), - actions: [action]) + return .init( + newState: .fetchingAuthSessionWithUserPool(.notStarted, signedInData), + actions: [action] + ) } return .from(oldState) @@ -95,11 +111,14 @@ extension RefreshSessionState { return .init(newState: .refreshed(credentials), actions: [action]) } if case .refreshIdentityInfo(let signedInData, let provider) = event.isRefreshSessionEvent { - let action = FetchAuthAWSCredentials(loginsMap: provider.loginsMap, - identityID: identityID) + let action = FetchAuthAWSCredentials( + loginsMap: provider.loginsMap, + identityID: identityID + ) return .init(newState: .refreshingAWSCredentialsWithUserPoolTokens( signedInData, - identityID), actions: [action]) + identityID + ), actions: [action]) } return .from(oldState) @@ -109,21 +128,27 @@ extension RefreshSessionState { let action = InformSessionError(error: error) return .init(newState: .error(error), actions: [action]) } - if case .fetched(let identityID, - let credentials) = event.isAuthorizationEvent { + if case .fetched( + let identityID, + let credentials + ) = event.isAuthorizationEvent { let credentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = InformSessionRefreshed(credentials: credentials) return .init(newState: .refreshed(credentials), actions: [action]) } let resolver = FetchAuthSessionState.Resolver() - let resolution = resolver.resolve(oldState: fetchSessionState, - byApplying: event) + let resolution = resolver.resolve( + oldState: fetchSessionState, + byApplying: event + ) return .init(newState: .fetchingAuthSessionWithUserPool( resolution.newState, - signedInData), actions: resolution.actions) + signedInData + ), actions: resolution.actions) case .refreshingUnAuthAWSCredentials: @@ -133,10 +158,12 @@ extension RefreshSessionState { } if case .fetchedAWSCredentials( let identityID, - let credentials) = event.isFetchSessionEvent { + let credentials + ) = event.isFetchSessionEvent { let amplifyCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = InformSessionRefreshed(credentials: amplifyCredentials) return .init(newState: .refreshed(amplifyCredentials), actions: [action]) } @@ -150,11 +177,13 @@ extension RefreshSessionState { } if case .fetchedAWSCredentials( let identityID, - let credentials) = event.isFetchSessionEvent { + let credentials + ) = event.isFetchSessionEvent { let amplifyCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: credentials) + credentials: credentials + ) let action = InformSessionRefreshed(credentials: amplifyCredentials) return .init(newState: .refreshed(amplifyCredentials), actions: [action]) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift index a95a2aa06d..2bcff08926 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/DeviceSRPState+Resolver.swift @@ -35,11 +35,13 @@ extension DeviceSRPState { case .initiatingDeviceSRP: return resolveRespondingDeviceSRPA( byApplying: deviceSrpSignInEvent, - from: oldState) + from: oldState + ) case .respondingDevicePasswordVerifier(let srpStateData): return resolveRespondingVerifyPassword( srpStateData: srpStateData, - byApplying: deviceSrpSignInEvent) + byApplying: deviceSrpSignInEvent + ) case .signedIn, .error: return .from(oldState) case .cancelling: @@ -53,7 +55,8 @@ extension DeviceSRPState { case .respondDeviceSRPChallenge(let username, let authResponse): let action = InitiateAuthDeviceSRP( username: username, - authResponse: authResponse) + authResponse: authResponse + ) return StateResolution( newState: DeviceSRPState.initiatingDeviceSRP, actions: [action] @@ -65,13 +68,15 @@ extension DeviceSRPState { private func resolveRespondingDeviceSRPA( byApplying signInEvent: SignInEvent, - from oldState: DeviceSRPState) + from oldState: DeviceSRPState + ) -> StateResolution { switch signInEvent.eventType { case .respondDevicePasswordVerifier(let srpStateData, let authResponse): let action = VerifyDevicePasswordSRP( stateData: srpStateData, - authResponse: authResponse) + authResponse: authResponse + ) return StateResolution( newState: DeviceSRPState.respondingDevicePasswordVerifier(srpStateData), actions: [action] @@ -85,12 +90,15 @@ extension DeviceSRPState { private func resolveRespondingVerifyPassword( srpStateData: SRPStateData, - byApplying signInEvent: SignInEvent) + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) case .cancelSRPSignIn: return .from(.cancelling) default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift index 7336e0ad58..756ca5c5bb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SRP/SRPSignInState+Resolver.swift @@ -35,11 +35,13 @@ extension SRPSignInState { case .initiatingSRPA(let signInEventData): return resolveInitiatingSRPA( byApplying: srpSignInEvent, - from: oldState) + from: oldState + ) case .respondingPasswordVerifier(let srpStateData): return resolveRespondingVerifyPassword( srpStateData: srpStateData, - byApplying: srpSignInEvent) + byApplying: srpSignInEvent + ) case .signedIn, .error: return .from(oldState) case .cancelling: @@ -72,7 +74,8 @@ extension SRPSignInState { password: password, authFlowType: authFlowType, deviceMetadata: deviceMetadata, - clientMetadata: signInEventData.clientMetadata) + clientMetadata: signInEventData.clientMetadata + ) return StateResolution( newState: SRPSignInState.initiatingSRPA(signInEventData), actions: [action] @@ -84,14 +87,16 @@ extension SRPSignInState { private func resolveInitiatingSRPA( byApplying signInEvent: SignInEvent, - from oldState: SRPSignInState) + from oldState: SRPSignInState + ) -> StateResolution { switch signInEvent.eventType { case .respondPasswordVerifier(let srpStateData, let authResponse, let clientMetadata): let action = VerifyPasswordSRP( stateData: srpStateData, authResponse: authResponse, - clientMetadata: clientMetadata) + clientMetadata: clientMetadata + ) return StateResolution( newState: SRPSignInState.respondingPasswordVerifier(srpStateData), actions: [action] @@ -105,21 +110,25 @@ extension SRPSignInState { private func resolveRespondingVerifyPassword( srpStateData: SRPStateData, - byApplying signInEvent: SignInEvent) + byApplying signInEvent: SignInEvent + ) -> StateResolution { switch signInEvent.eventType { case .retryRespondPasswordVerifier(let srpStateData, let authResponse, let clientMetadata): let action = VerifyPasswordSRP( stateData: srpStateData, authResponse: authResponse, - clientMetadata: clientMetadata) + clientMetadata: clientMetadata + ) return StateResolution( newState: SRPSignInState.respondingPasswordVerifier(srpStateData), actions: [action] ) case .finalizeSignIn(let signedInData): - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) case .cancelSRPSignIn: return .from(.cancelling) default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift index 8c50307e8f..9873db5fe7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/HostedUISignInState+Resolver.swift @@ -16,7 +16,8 @@ extension HostedUISignInState { func resolve( oldState: HostedUISignInState, - byApplying event: StateMachineEvent) + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -48,8 +49,10 @@ extension HostedUISignInState { return .init(newState: .error(error), actions: [action]) } if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .done, - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .done, + actions: [SignInComplete(signedInData: signedInData)] + ) } return .from(oldState) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift index bff26db8a3..000c031eea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInChallengeState+Resolver.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation extension SignInChallengeState { @@ -15,7 +16,8 @@ extension SignInChallengeState { func resolve( oldState: SignInChallengeState, - byApplying event: StateMachineEvent) + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -32,7 +34,8 @@ extension SignInChallengeState { let action = VerifySignInChallenge( challenge: challenge, confirmSignEventData: answerEventData, - signInMethod: signInMethod) + signInMethod: signInMethod + ) return .init( newState: .verifying(challenge, signInMethod, answerEventData.answer), actions: [action] @@ -46,7 +49,8 @@ extension SignInChallengeState { let action = VerifySignInChallenge( challenge: challenge, confirmSignEventData: answerEventData, - signInMethod: signInMethod) + signInMethod: signInMethod + ) return .init( newState: .verifying(challenge, signInMethod, answerEventData.answer), actions: [action] @@ -54,8 +58,10 @@ extension SignInChallengeState { } if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .verified, - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .verified, + actions: [SignInComplete(signedInData: signedInData)] + ) } if case .throwAuthError(let error) = event.isSignInEvent { @@ -70,7 +76,8 @@ extension SignInChallengeState { let action = VerifySignInChallenge( challenge: challenge, confirmSignEventData: answerEventData, - signInMethod: signInMethod) + signInMethod: signInMethod + ) return .init( newState: .verifying(challenge, signInMethod, answerEventData.answer), actions: [action] diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift index d95da1588c..dc819cc3a1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignIn/SignInState+Resolver.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation extension SignInState { @@ -17,7 +18,8 @@ extension SignInState { // swiftlint:disable:next cyclomatic_complexity function_body_length func resolve( oldState: SignInState, - byApplying event: StateMachineEvent) + byApplying event: StateMachineEvent + ) -> StateResolution { switch oldState { @@ -25,24 +27,32 @@ extension SignInState { if case .initiateSignInWithSRP(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartSRPFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) - return .init(newState: .signingInWithSRP(.notStarted, signInEventData), - actions: [action]) + deviceMetadata: deviceMetadata + ) + return .init( + newState: .signingInWithSRP(.notStarted, signInEventData), + actions: [action] + ) } if case .initiateCustomSignIn(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartCustomSignInFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) + deviceMetadata: deviceMetadata + ) return .init( newState: .signingInWithCustom(.notStarted, signInEventData), - actions: [action]) + actions: [action] + ) } if case .initiateCustomSignInWithSRP(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartSRPFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) - return .init(newState: .signingInWithSRPCustom(.notStarted, signInEventData), - actions: [action]) + deviceMetadata: deviceMetadata + ) + return .init( + newState: .signingInWithSRPCustom(.notStarted, signInEventData), + actions: [action] + ) } if case .initiateHostedUISignIn(let options) = event.isSignInEvent { let action = InitializeHostedUISignIn(options: options) @@ -51,9 +61,12 @@ extension SignInState { if case .initiateMigrateAuth(let signInEventData, let deviceMetadata) = event.isSignInEvent { let action = StartMigrateAuthFlow( signInEventData: signInEventData, - deviceMetadata: deviceMetadata) - return .init(newState: .signingInViaMigrateAuth(.notStarted, signInEventData), - actions: [action]) + deviceMetadata: deviceMetadata + ) + return .init( + newState: .signingInViaMigrateAuth(.notStarted, signInEventData), + actions: [action] + ) } return .from(oldState) @@ -63,8 +76,10 @@ extension SignInState { return .init(newState: .signedIn(signedInData)) } - let resolution = HostedUISignInState.Resolver().resolve(oldState: hostedUIState, - byApplying: event) + let resolution = HostedUISignInState.Resolver().resolve( + oldState: hostedUIState, + byApplying: event + ) let newState = SignInState.signingInWithHostedUI(resolution.newState) return .init(newState: newState, actions: resolution.actions) @@ -72,22 +87,29 @@ extension SignInState { let signInMethod = SignInMethod.apiBased(.userSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted - return .init(newState: + return .init( + newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, signInMethod - ), actions: [action]) + ), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, @@ -95,31 +117,42 @@ extension SignInState { case .respondingPasswordVerifier = srpSignInState { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } - let resolution = SRPSignInState.Resolver().resolve(oldState: srpSignInState, - byApplying: event) - let signingInWithSRP = SignInState.signingInWithSRP(resolution.newState, - signInEventData) + let resolution = SRPSignInState.Resolver().resolve( + oldState: srpSignInState, + byApplying: event + ) + let signingInWithSRP = SignInState.signingInWithSRP( + resolution.newState, + signInEventData + ) return .init(newState: signingInWithSRP, actions: resolution.actions) case .signingInWithCustom(let customSignInState, let signInEventData): let signInMethod = SignInMethod.apiBased(.customWithoutSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, @@ -131,51 +164,65 @@ extension SignInState { if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } let resolution = CustomSignInState.Resolver().resolve( - oldState: customSignInState, byApplying: event) + oldState: customSignInState, byApplying: event + ) let signingInWithCustom = SignInState.signingInWithCustom( - resolution.newState, signInEventData) + resolution.newState, signInEventData + ) return .init(newState: signingInWithCustom, actions: resolution.actions) case .signingInViaMigrateAuth(let migrateSignInState, let signInEventData): let signInMethod = SignInMethod.apiBased(.userPassword) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, - signInMethod), actions: [action]) + signInMethod + ), actions: [action]) } if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, @@ -183,23 +230,30 @@ extension SignInState { case .signingIn = migrateSignInState { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } let resolution = MigrateSignInState.Resolver().resolve( - oldState: migrateSignInState, byApplying: event) + oldState: migrateSignInState, byApplying: event + ) let signingInWithMigration = SignInState.signingInViaMigrateAuth( - resolution.newState, signInEventData) + resolution.newState, signInEventData + ) return .init(newState: signingInWithMigration, actions: resolution.actions) case .resolvingChallenge(let challengeState, let challengeType, let signInMethod): @@ -207,30 +261,38 @@ extension SignInState { if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } // This could when we have nested challenges // Example newPasswordRequired -> sms_mfa if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, - signInMethod), actions: [action]) + signInMethod + ), actions: [action]) } if let signInEvent = event as? SignInEvent, @@ -240,26 +302,34 @@ extension SignInState { return .init( newState: .resolvingTOTPSetup( .notStarted, - .init(username: username, - password: nil, - signInMethod: signInMethod)), - actions: [action]) + .init( + username: username, + password: nil, + signInMethod: signInMethod + ) + ), + actions: [action] + ) } let resolution = SignInChallengeState.Resolver().resolve( oldState: challengeState, - byApplying: event) + byApplying: event + ) return .init(newState: .resolvingChallenge( resolution.newState, challengeType, - signInMethod), actions: resolution.actions) + signInMethod + ), actions: resolution.actions) case .signingInWithSRPCustom(let srpSignInState, let signInEventData): let signInMethod = SignInMethod.apiBased(.customWithSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, @@ -272,43 +342,58 @@ extension SignInState { case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(_, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: .resolvingTOTPSetup(.notStarted, signInEventData), - actions: [action]) + return .init( + newState: .resolvingTOTPSetup(.notStarted, signInEventData), + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } - let resolution = SRPSignInState.Resolver().resolve(oldState: srpSignInState, - byApplying: event) - let signingInWithSRP = SignInState.signingInWithSRPCustom(resolution.newState, - signInEventData) + let resolution = SRPSignInState.Resolver().resolve( + oldState: srpSignInState, + byApplying: event + ) + let signingInWithSRP = SignInState.signingInWithSRPCustom( + resolution.newState, + signInEventData + ) return .init(newState: signingInWithSRP, actions: resolution.actions) case .resolvingTOTPSetup(let setUpTOTPState, let signInEventData): if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) } if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInEventData.signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInEventData.signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, @@ -320,64 +405,83 @@ extension SignInState { if let signInEvent = event as? SignInEvent, case .confirmDevice(let signedInData) = signInEvent.eventType { let action = ConfirmDevice(signedInData: signedInData) - return .init(newState: .confirmingDevice, - actions: [action]) + return .init( + newState: .confirmingDevice, + actions: [action] + ) } if let signInEvent = event as? SignInEvent, case .initiateDeviceSRP(let username, let challengeResponse) = signInEvent.eventType { let action = StartDeviceSRPFlow( username: username, - authResponse: challengeResponse) - return .init(newState: .resolvingDeviceSrpa(.notStarted), - actions: [action]) + authResponse: challengeResponse + ) + return .init( + newState: .resolvingDeviceSrpa(.notStarted), + actions: [action] + ) } let resolution = SignInTOTPSetupState.Resolver( signInEventData: signInEventData).resolve( oldState: setUpTOTPState, - byApplying: event) + byApplying: event + ) let settingUpTOTPState = SignInState.resolvingTOTPSetup( resolution.newState, - signInEventData) + signInEventData + ) return .init(newState: settingUpTOTPState, actions: resolution.actions) case .resolvingDeviceSrpa(let deviceSrpState): let signInMethod = SignInMethod.apiBased(.userSRP) if let signInEvent = event as? SignInEvent, case .receivedChallenge(let challenge) = signInEvent.eventType { - let action = InitializeResolveChallenge(challenge: challenge, - signInMethod: signInMethod) + let action = InitializeResolveChallenge( + challenge: challenge, + signInMethod: signInMethod + ) let subState = SignInChallengeState.notStarted return .init(newState: .resolvingChallenge( subState, challenge.challenge.authChallengeType, - signInMethod), actions: [action]) + signInMethod + ), actions: [action]) } if let signInEvent = event as? SignInEvent, case .initiateTOTPSetup(let username, let challengeResponse) = signInEvent.eventType { let action = InitializeTOTPSetup( authResponse: challengeResponse) - return .init(newState: + return .init( + newState: .resolvingTOTPSetup( .notStarted, - .init(username: username, - password: nil, - signInMethod: signInMethod)), - actions: [action]) - } - - let resolution = DeviceSRPState.Resolver().resolve(oldState: deviceSrpState, - byApplying: event) + .init( + username: username, + password: nil, + signInMethod: signInMethod + ) + ), + actions: [action] + ) + } + + let resolution = DeviceSRPState.Resolver().resolve( + oldState: deviceSrpState, + byApplying: event + ) let resolvingDeviceSrpa = SignInState.resolvingDeviceSrpa(resolution.newState) return .init(newState: resolvingDeviceSrpa, actions: resolution.actions) case .confirmingDevice: if case .finalizeSignIn(let signedInData) = event.isSignInEvent { - return .init(newState: .signedIn(signedInData), - actions: [SignInComplete(signedInData: signedInData)]) + return .init( + newState: .signedIn(signedInData), + actions: [SignInComplete(signedInData: signedInData)] + ) } return .from(oldState) case .signedIn, .error: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift index 17523862b4..239e632d70 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/SignOut/SignOutState+Resolver.swift @@ -37,16 +37,20 @@ extension SignOutState { guard let signOutEvent = event as? SignOutEvent else { return .from(oldState) } - return resolveSigningOutLocally(byApplying: signOutEvent, - from: oldState, - signedInData: signedInData) + return resolveSigningOutLocally( + byApplying: signOutEvent, + from: oldState, + signedInData: signedInData + ) case .signingOutHostedUI(let signedInData): guard let signOutEvent = event as? SignOutEvent else { return .from(oldState) } - return resolveHostedUISignOut(byApplying: signOutEvent, - signedInData: signedInData, - from: oldState) + return resolveHostedUISignOut( + byApplying: signOutEvent, + signedInData: signedInData, + from: oldState + ) case .buildingRevokeTokenError: guard let signOutEvent = event as? SignOutEvent else { return .from(oldState) @@ -61,58 +65,79 @@ extension SignOutState { private func resolveNotStarted( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { case .signOutGlobally(let signedInData, hostedUIError: let hostedUIError): - let action = SignOutGlobally(signedInData: signedInData, - hostedUIError: hostedUIError) + let action = SignOutGlobally( + signedInData: signedInData, + hostedUIError: hostedUIError + ) return StateResolution( newState: SignOutState.signingOutGlobally, actions: [action] ) - case .revokeToken(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError): - let action = RevokeToken(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) + case .revokeToken( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError + ): + let action = RevokeToken( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) return StateResolution( newState: SignOutState.revokingToken, actions: [action] ) case .invokeHostedUISignOut(let signOutEventData, let signedInData): - let action = ShowHostedUISignOut(signOutEvent: signOutEventData, - signInData: signedInData) + let action = ShowHostedUISignOut( + signOutEvent: signOutEventData, + signInData: signedInData + ) return .init(newState: .signingOutHostedUI(signedInData), actions: [action]) case .signOutGuest: - let action = SignOutLocally(hostedUIError: nil, - globalSignOutError: nil, - revokeTokenError: nil) - return .init(newState: .signingOutLocally(nil), - actions: [action]) + let action = SignOutLocally( + hostedUIError: nil, + globalSignOutError: nil, + revokeTokenError: nil + ) + return .init( + newState: .signingOutLocally(nil), + actions: [action] + ) default: return .from(oldState) } } - private func resolveHostedUISignOut(byApplying signOutEvent: SignOutEvent, - signedInData: SignedInData, - from oldState: SignOutState) + private func resolveHostedUISignOut( + byApplying signOutEvent: SignOutEvent, + signedInData: SignedInData, + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { case .signOutGlobally(let signedInData, hostedUIError: let hostedUIError): - let action = SignOutGlobally(signedInData: signedInData, - hostedUIError: hostedUIError) + let action = SignOutGlobally( + signedInData: signedInData, + hostedUIError: hostedUIError + ) return StateResolution( newState: SignOutState.signingOutGlobally, actions: [action] ) - case .revokeToken(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError): - let action = RevokeToken(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) + case .revokeToken( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError + ): + let action = RevokeToken( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) return StateResolution( newState: SignOutState.revokingToken, actions: [action] @@ -127,26 +152,37 @@ extension SignOutState { private func resolveSigningOutGlobally( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { - case .revokeToken(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError): - let action = RevokeToken(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) + case .revokeToken( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError + ): + let action = RevokeToken( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) return StateResolution( newState: SignOutState.revokingToken, actions: [action] ) - case .globalSignOutError(let signedInData, - globalSignOutError: let globalSignOutError, - hostedUIError: let hostedUIError): - let action = BuildRevokeTokenError(signedInData: signedInData, - hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError) - return .init(newState: .buildingRevokeTokenError, - actions: [action]) + case .globalSignOutError( + let signedInData, + globalSignOutError: let globalSignOutError, + hostedUIError: let hostedUIError + ): + let action = BuildRevokeTokenError( + signedInData: signedInData, + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError + ) + return .init( + newState: .buildingRevokeTokenError, + actions: [action] + ) default: return .from(oldState) @@ -155,35 +191,49 @@ extension SignOutState { private func resolveRevokingToken( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { - case .signOutLocally(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError, - revokeTokenError: let revokeTokenError): - let action = SignOutLocally(hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError) - return .init(newState: .signingOutLocally(signedInData), - actions: [action]) + case .signOutLocally( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError, + revokeTokenError: let revokeTokenError + ): + let action = SignOutLocally( + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError, + revokeTokenError: revokeTokenError + ) + return .init( + newState: .signingOutLocally(signedInData), + actions: [action] + ) default: return .from(oldState) } } - private func resolveBuildingRevokeTokenError ( + private func resolveBuildingRevokeTokenError( byApplying signOutEvent: SignOutEvent, - from oldState: SignOutState) -> StateResolution { + from oldState: SignOutState + ) -> StateResolution { switch signOutEvent.eventType { - case .signOutLocally(let signedInData, - hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError, - revokeTokenError: let revokeTokenError): - let action = SignOutLocally(hostedUIError: hostedUIError, - globalSignOutError: globalSignOutError, - revokeTokenError: revokeTokenError) - return .init(newState: .signingOutLocally(signedInData), - actions: [action]) + case .signOutLocally( + let signedInData, + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError, + revokeTokenError: let revokeTokenError + ): + let action = SignOutLocally( + hostedUIError: hostedUIError, + globalSignOutError: globalSignOutError, + revokeTokenError: revokeTokenError + ) + return .init( + newState: .signingOutLocally(signedInData), + actions: [action] + ) default: return .from(oldState) } @@ -192,12 +242,15 @@ extension SignOutState { private func resolveSigningOutLocally( byApplying event: SignOutEvent, from oldState: SignOutState, - signedInData: SignedInData?) + signedInData: SignedInData? + ) -> StateResolution { switch event.eventType { - case .signedOutSuccess(hostedUIError: let hostedUIError, - globalSignOutError: let globalSignOutError, - revokeTokenError: let revokeTokenError): + case .signedOutSuccess( + hostedUIError: let hostedUIError, + globalSignOutError: let globalSignOutError, + revokeTokenError: let revokeTokenError + ): let signedOutData = SignedOutData( lastKnownUserName: signedInData?.username, hostedUIError: hostedUIError, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift index d9ac9e2dee..ea0c0ea1ee 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/Resolvers/TOTPSetup/SignInTOTPSetupState+Resolver.swift @@ -31,13 +31,17 @@ extension SignInTOTPSetupState { case .waitingForAnswer(let signInTOTPSetupData): return resolveWaitForAnswer( byApplying: setupTOTPEvent, - with: signInTOTPSetupData) + with: signInTOTPSetupData + ) case .verifying(let signInTOTPSetupData, _): return resolveVerifyingState( - byApplying: setupTOTPEvent, with: signInTOTPSetupData) + byApplying: setupTOTPEvent, with: signInTOTPSetupData + ) case .error(let signInTOTPSetupData, _): - return resolveErrorState(byApplying: setupTOTPEvent, - with: signInTOTPSetupData) + return resolveErrorState( + byApplying: setupTOTPEvent, + with: signInTOTPSetupData + ) default: return .from(.notStarted) } @@ -49,7 +53,8 @@ extension SignInTOTPSetupState { case .setUpTOTP(let authResponse): let action = SetUpTOTP( authResponse: authResponse, - signInEventData: signInEventData) + signInEventData: signInEventData + ) return StateResolution( newState: SignInTOTPSetupState.setUpTOTP, actions: [action] @@ -78,17 +83,20 @@ extension SignInTOTPSetupState { private func resolveWaitForAnswer( byApplying signInEvent: SetUpTOTPEvent, - with signInTOTPSetupData: SignInTOTPSetupData) -> StateResolution { + with signInTOTPSetupData: SignInTOTPSetupData + ) -> StateResolution { switch signInEvent.eventType { case .verifyChallengeAnswer(let confirmSignInEventData): let action = VerifyTOTPSetup( session: signInTOTPSetupData.session, totpCode: confirmSignInEventData.answer, - friendlyDeviceName: confirmSignInEventData.friendlyDeviceName) + friendlyDeviceName: confirmSignInEventData.friendlyDeviceName + ) return StateResolution( newState: SignInTOTPSetupState.verifying( signInTOTPSetupData, - confirmSignInEventData), + confirmSignInEventData + ), actions: [action] ) case .throwError(let error): @@ -100,12 +108,14 @@ extension SignInTOTPSetupState { private func resolveVerifyingState( byApplying signInEvent: SetUpTOTPEvent, - with signInTOTPSetupData: SignInTOTPSetupData) -> StateResolution { + with signInTOTPSetupData: SignInTOTPSetupData + ) -> StateResolution { switch signInEvent.eventType { case .respondToAuthChallenge(let session): let action = CompleteTOTPSetup( userSession: session, - signInEventData: signInEventData) + signInEventData: signInEventData + ) return StateResolution( newState: SignInTOTPSetupState.respondingToAuthChallenge, actions: [action] @@ -119,21 +129,24 @@ extension SignInTOTPSetupState { private func resolveErrorState( byApplying signInEvent: SetUpTOTPEvent, - with signInTOTPSetupData: SignInTOTPSetupData?) -> StateResolution { + with signInTOTPSetupData: SignInTOTPSetupData? + ) -> StateResolution { switch signInEvent.eventType { case .verifyChallengeAnswer(let confirmSignInEventData): - guard let signInTOTPSetupData = signInTOTPSetupData else { + guard let signInTOTPSetupData else { return .from(.notStarted) } let action = VerifyTOTPSetup( session: signInTOTPSetupData.session, totpCode: confirmSignInEventData.answer, - friendlyDeviceName: confirmSignInEventData.friendlyDeviceName) + friendlyDeviceName: confirmSignInEventData.friendlyDeviceName + ) return StateResolution( newState: SignInTOTPSetupState.verifying( signInTOTPSetupData, - confirmSignInEventData), + confirmSignInEventData + ), actions: [action] ) default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift index 216c9bbde5..5f84a2f0db 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/hierarchical-state-machine-swift/ConcurrentEffectExecutor.swift @@ -12,8 +12,9 @@ enum ConcurrentEffectExecutor: EffectExecutor { static func execute( _ actions: [Action], dispatchingTo eventDispatcher: EventDispatcher, - environment: Environment) { - actions.forEach { action in + environment: Environment + ) { + for action in actions { Task.detached { await action.execute(withDispatcher: eventDispatcher, environment: environment) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift index 4edddb6d18..fe69142592 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginConstants.swift @@ -7,7 +7,7 @@ import Foundation -struct AuthPluginConstants { +enum AuthPluginConstants { /// The time interval under which the refresh of UserPool or awsCredentials tokens will happen static let sessionRefreshInterval: TimeInterval = 2 * 60 diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift index ab899e5682..cef09da5bc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Constants/AuthPluginErrorConstants.swift @@ -5,172 +5,213 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation typealias AuthPluginErrorString = (errorDescription: ErrorDescription, recoverySuggestion: RecoverySuggestion) -typealias AuthPluginValidationErrorString = (field: Field, +typealias AuthPluginValidationErrorString = ( + field: Field, errorDescription: ErrorDescription, - recoverySuggestion: RecoverySuggestion) + recoverySuggestion: RecoverySuggestion +) enum AuthPluginErrorConstants { static let decodeConfigurationError: AuthPluginErrorString = ( "Unable to decode configuration", - "Make sure the plugin configuration is JSONValue") + "Make sure the plugin configuration is JSONValue" + ) static let configurationObjectExpected: AuthPluginErrorString = ( "Configuration was not a dictionary literal", - "Make sure the value for the plugin is a dictionary literal") + "Make sure the value for the plugin is a dictionary literal" + ) static let hostedUISecurityFailedError: AuthPluginErrorString = ( "Found invalid parameter while parsing the webUI redirect URL", - "Make sure that the signIn URL has not been modified during the signIn flow") + "Make sure that the signIn URL has not been modified during the signIn flow" + ) static let hostedUIUserCancelledError: AuthPluginErrorString = ( "User cancelled the signIn flow and could not be completed.", - "Present the signIn UI again for the user to sign in") + "Present the signIn UI again for the user to sign in" + ) static let hostedUIUserCancelledSignOutError: AuthPluginErrorString = ( "User cancelled the signOut flow and could not be completed.", - "Present the signOut UI again for the user to sign out") + "Present the signOut UI again for the user to sign out" + ) static let hostedUIInvalidPresentation: AuthPluginErrorString = ( "Presentation context provided is invalid or not present", - "Retry by providing a presentation context to present the webUI") + "Retry by providing a presentation context to present the webUI" + ) static let hostedUIUnableToStartASWebAuthenticationSession: AuthPluginErrorString = ( "Unable to start a ASWebAuthenticationSession", - "Make sure that the app can present an ASWebAuthenticationSession") + "Make sure that the app can present an ASWebAuthenticationSession" + ) static let hostedUISignInURI: AuthPluginErrorString = ( "SignIn URI could not be created", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUITokenURI: AuthPluginErrorString = ( "Token URI could not be created", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUISignOutURI: AuthPluginErrorString = ( "SignOut URI could not be created", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUISignOutRedirectURI: AuthPluginErrorString = ( "Callback URL could not be retrieved", - "Check the configuration to make sure that HostedUI related information are present") + "Check the configuration to make sure that HostedUI related information are present" + ) static let hostedUIProofCalculation: AuthPluginErrorString = ( "Proof calculation failed", - "Reach out with amplify team via github to raise an issue") + "Reach out with amplify team via github to raise an issue" + ) static let tokenParsingError: AuthPluginErrorString = ( "Token returned by service could not be parsed", - "Check if the the configuration provided are correct") + "Check if the the configuration provided are correct" + ) static let userInvalidError: AuthPluginErrorString = ( "Could not validate the user", - "Get the current user Auth.getCurrentUser() and make the request") - + "Get the current user Auth.getCurrentUser() and make the request" + ) + static let identityIdSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive identity id", - "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool") + "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool" + ) static let awsCredentialsSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive AWS credentials", - "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool") + "Call Auth.signIn to sign in a user or enable unauthenticated access in AWS Cognito Identity Pool" + ) static let cognitoTokensSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive cognito tokens", - "Call Auth.signIn to sign in a user and then call Auth.fetchSession") + "Call Auth.signIn to sign in a user and then call Auth.fetchSession" + ) static let userSubSignOutError: AuthPluginErrorString = ( "There is no user signed in to retreive user sub", - "Call Auth.signIn to sign in a user and then call Auth.fetchSession") + "Call Auth.signIn to sign in a user and then call Auth.fetchSession" + ) static let identityIdOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch identity id", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let awsCredentialsOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch AWS credentials", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let usersubOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch user sub", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let cognitoTokenOfflineError: AuthPluginErrorString = ( "A network error occured while trying to fetch AWS Cognito Tokens", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let identityIdServiceError: AuthPluginErrorString = ( "A serivce error occured while trying to fetch identity id", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let awsCredentialsServiceError: AuthPluginErrorString = ( "A service error occured while trying to fetch AWS credentials", - "Try again with exponential backoff") + "Try again with exponential backoff" + ) static let identityIdSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch identity id", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let awsCredentialsSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch AWS Credentials", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let usersubSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch user sub", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let cognitoTokensSessionExpiredError: AuthPluginErrorString = ( "Session expired could not fetch cognito tokens", - "Invoke Auth.signIn to re-authenticate the user") + "Invoke Auth.signIn to re-authenticate the user" + ) static let cognitoTokenSignedInThroughCIDPError: AuthPluginErrorString = ( "User is not signed in through Cognito User pool", - "Tokens are not valid with user signed in through AWS Cognito Identity Pool") + "Tokens are not valid with user signed in through AWS Cognito Identity Pool" + ) static let userSubSignedInThroughCIDPError: AuthPluginErrorString = ( "User is not signed in through Cognito User pool", - "User sub are not valid with user signed in through AWS Cognito Identity Pool") + "User sub are not valid with user signed in through AWS Cognito Identity Pool" + ) static let signedInIdentityIdWithNoCIDPError: AuthPluginErrorString = ( "Could not fetch identity Id, AWS Cognito Identity Pool is not configured", - "Follow the steps to configure AWS Cognito Identity Pool and try again") + "Follow the steps to configure AWS Cognito Identity Pool and try again" + ) static let signedInAWSCredentialsWithNoCIDPError: AuthPluginErrorString = ( "Could not fetch AWS Credentials, AWS Cognito Identity Pool is not configured", - "Follow the steps to configure AWS Cognito Identity Pool and try again") + "Follow the steps to configure AWS Cognito Identity Pool and try again" + ) static let fetchAttributeSignedOutError: AuthPluginErrorString = ( - "Could not fetch attributes, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not fetch attributes, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let updateAttributeSignedOutError: AuthPluginErrorString = ( - "Could not update attributes, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not update attributes, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let resendAttributeCodeSignedOutError: AuthPluginErrorString = ( - "Could not resend attribute confirmation code, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not resend attribute confirmation code, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let confirmAttributeSignedOutError: AuthPluginErrorString = ( - "Could not confirm attribute, there is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then call user attributes apis") + "Could not confirm attribute, there is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then call user attributes apis" + ) static let changePasswordSignedOutError: AuthPluginErrorString = ( - "Could not change password, there is no user signed in to the Auth category", - "Change password require a user signed in to Auth category, use one of the signIn apis to signIn") + "Could not change password, there is no user signed in to the Auth category", + "Change password require a user signed in to Auth category, use one of the signIn apis to signIn" + ) static let changePasswordUnableToSignInError: AuthPluginErrorString = ( - "Could not change password, the user session is expired", - "Re-authenticate the user by using one of the signIn apis") + "Could not change password, the user session is expired", + "Re-authenticate the user by using one of the signIn apis" + ) static let userSignedOutError: AuthPluginErrorString = ( - "There is no user signed in to the Auth category", - "SignIn to Auth category by using one of the sign in methods and then try again") + "There is no user signed in to the Auth category", + "SignIn to Auth category by using one of the sign in methods and then try again" + ) } // Field validation errors diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/AWSEndpointResolving.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/AWSEndpointResolving.swift index 47c6a89c63..1abe8bdeb2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/AWSEndpointResolving.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/AWSEndpointResolving.swift @@ -6,8 +6,8 @@ // import AWSClientRuntime -import ClientRuntime import AWSCognitoIdentityProvider +import ClientRuntime struct AWSEndpointResolving: AWSCognitoIdentityProvider.EndpointResolver { func resolve(params: AWSCognitoIdentityProvider.EndpointParams) throws -> ClientRuntime.Endpoint { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift index 7f4f1c9de4..d8f02f1b63 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving+ValidationStep.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension EndpointResolving { struct ValidationStep { @@ -43,7 +43,7 @@ extension EndpointResolving.ValidationStep { /// Validate that the input `URLComponents` don't contain a path. static func pathIsEmpty() -> Self where Input == (URLComponents, String), Output == Void { - .init { (components, endpoint) in + .init { components, endpoint in guard components.path.isEmpty else { throw AuthError.invalidPath( endpoint: endpoint, @@ -55,8 +55,8 @@ extension EndpointResolving.ValidationStep { } // MARK: Fileprivate AuthError extensions thrown on invalid `Endpoint` input. -extension AuthError { - fileprivate static func invalidURL(_ endpoint: String) -> AuthError { +private extension AuthError { + static func invalidURL(_ endpoint: String) -> AuthError { .configuration( "Error configuring AWSCognitoAuthPlugin", """ @@ -67,7 +67,7 @@ extension AuthError { ) } - fileprivate static func invalidScheme(_ endpoint: String) -> AuthError { + static func invalidScheme(_ endpoint: String) -> AuthError { .configuration( "Error configuring AWSCognitoAuthPlugin", """ @@ -80,7 +80,7 @@ extension AuthError { ) } - fileprivate static func invalidPath( + static func invalidPath( endpoint: String, components: URLComponents ) -> AuthError { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving.swift index 3b4dab259c..212baad006 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/CustomEndpoint/EndpointResolving.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import ClientRuntime +import Foundation struct EndpointResolving { let run: (String) throws -> ClientRuntime.Endpoint diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift index 2db23e0ce7..674331157d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedInSessionHelper.swift @@ -7,28 +7,33 @@ import Amplify -struct AuthCognitoSignedInSessionHelper { +enum AuthCognitoSignedInSessionHelper { static func makeOfflineSignedInSession() -> AWSAuthCognitoSession { let identityIdError = AuthError.service( AuthPluginErrorConstants.identityIdOfflineError.errorDescription, AuthPluginErrorConstants.identityIdOfflineError.recoverySuggestion, - AWSCognitoAuthError.network) + AWSCognitoAuthError.network + ) let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.awsCredentialsOfflineError.errorDescription, AuthPluginErrorConstants.awsCredentialsOfflineError.recoverySuggestion, - AWSCognitoAuthError.network) + AWSCognitoAuthError.network + ) let tokensError = AuthError.service( AuthPluginErrorConstants.cognitoTokenOfflineError.errorDescription, AuthPluginErrorConstants.cognitoTokenOfflineError.recoverySuggestion, - AWSCognitoAuthError.network) + AWSCognitoAuthError.network + ) - let authSession = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -36,22 +41,27 @@ struct AuthCognitoSignedInSessionHelper { let identityIdError = AuthError.sessionExpired( AuthPluginErrorConstants.identityIdSessionExpiredError.errorDescription, AuthPluginErrorConstants.identityIdSessionExpiredError.recoverySuggestion, - underlyingError) + underlyingError + ) let awsCredentialsError = AuthError.sessionExpired( AuthPluginErrorConstants.awsCredentialsSessionExpiredError.errorDescription, AuthPluginErrorConstants.awsCredentialsSessionExpiredError.recoverySuggestion, - underlyingError) + underlyingError + ) let tokensError = AuthError.sessionExpired( AuthPluginErrorConstants.cognitoTokensSessionExpiredError.errorDescription, AuthPluginErrorConstants.cognitoTokensSessionExpiredError.recoverySuggestion, - underlyingError) + underlyingError + ) - let authSession = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -59,7 +69,8 @@ struct AuthCognitoSignedInSessionHelper { let userSubError = AuthError.service( AuthPluginErrorConstants.userSubSignedInThroughCIDPError.errorDescription, AuthPluginErrorConstants.userSubSignedInThroughCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return userSubError } @@ -67,7 +78,8 @@ struct AuthCognitoSignedInSessionHelper { let tokensError = AuthError.service( AuthPluginErrorConstants.cognitoTokenSignedInThroughCIDPError.errorDescription, AuthPluginErrorConstants.cognitoTokenSignedInThroughCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return tokensError } @@ -75,7 +87,8 @@ struct AuthCognitoSignedInSessionHelper { let identityIdError = AuthError.service( AuthPluginErrorConstants.signedInIdentityIdWithNoCIDPError.errorDescription, AuthPluginErrorConstants.signedInIdentityIdWithNoCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return identityIdError } @@ -83,7 +96,8 @@ struct AuthCognitoSignedInSessionHelper { let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.signedInAWSCredentialsWithNoCIDPError.errorDescription, AuthPluginErrorConstants.signedInAWSCredentialsWithNoCIDPError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) return awsCredentialsError } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift index 8e391355e5..ee923133c3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoSignedOutSessionHelper.swift @@ -8,20 +8,24 @@ import Amplify import AWSPluginsCore -struct AuthCognitoSignedOutSessionHelper { +enum AuthCognitoSignedOutSessionHelper { /// Creates a signedOut session information with valid identityId and aws credentials. /// - Parameters: /// - identityId: Valid identity id for the current signedOut session /// - awsCredentials: Valid AWS Credentials for the current signedOut session /// - Returns: Returns a valid signedOut session - static func makeSignedOutSession(identityId: String, - awsCredentials: AWSCredentials) -> AWSAuthCognitoSession { + static func makeSignedOutSession( + identityId: String, + awsCredentials: AWSCredentials + ) -> AWSAuthCognitoSession { let tokensError = makeCognitoTokensSignedOutError() - let authSession = AWSAuthCognitoSession(isSignedIn: false, - identityIdResult: .success(identityId), - awsCredentialsResult: .success(awsCredentials), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: false, + identityIdResult: .success(identityId), + awsCredentialsResult: .success(awsCredentials), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -31,19 +35,23 @@ struct AuthCognitoSignedOutSessionHelper { let identityIdError = AuthError.service( AuthPluginErrorConstants.identityIdSignOutError.errorDescription, AuthPluginErrorConstants.identityIdSignOutError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.awsCredentialsSignOutError.errorDescription, AuthPluginErrorConstants.awsCredentialsSignOutError.recoverySuggestion, - AWSCognitoAuthError.invalidAccountTypeException) + AWSCognitoAuthError.invalidAccountTypeException + ) let tokensError = makeCognitoTokensSignedOutError() - let authSession = AWSAuthCognitoSession(isSignedIn: false, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: false, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } @@ -53,25 +61,30 @@ struct AuthCognitoSignedOutSessionHelper { let identityIdError = AuthError.service( AuthPluginErrorConstants.identityIdServiceError.errorDescription, - AuthPluginErrorConstants.identityIdServiceError.recoverySuggestion) + AuthPluginErrorConstants.identityIdServiceError.recoverySuggestion + ) let awsCredentialsError = AuthError.service( AuthPluginErrorConstants.awsCredentialsServiceError.errorDescription, - AuthPluginErrorConstants.awsCredentialsServiceError.recoverySuggestion) + AuthPluginErrorConstants.awsCredentialsServiceError.recoverySuggestion + ) let tokensError = makeCognitoTokensSignedOutError() - let authSession = AWSAuthCognitoSession(isSignedIn: false, - identityIdResult: .failure(identityIdError), - awsCredentialsResult: .failure(awsCredentialsError), - cognitoTokensResult: .failure(tokensError)) + let authSession = AWSAuthCognitoSession( + isSignedIn: false, + identityIdResult: .failure(identityIdError), + awsCredentialsResult: .failure(awsCredentialsError), + cognitoTokensResult: .failure(tokensError) + ) return authSession } private static func makeCognitoTokensSignedOutError() -> AuthError { let tokensError = AuthError.signedOut( AuthPluginErrorConstants.cognitoTokensSignOutError.errorDescription, - AuthPluginErrorConstants.cognitoTokensSignOutError.recoverySuggestion) + AuthPluginErrorConstants.cognitoTokensSignOutError.recoverySuggestion + ) return tokensError } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift index 9dde721c31..2879bc27d1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthCognitoTokens+Validation.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSPluginsCore +import Foundation /// Internal Helpers for managing session tokens extension AWSCognitoUserPoolTokens { @@ -17,7 +17,8 @@ extension AWSCognitoUserPoolTokens { guard let idTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: idToken).get(), let accessTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: accessToken).get(), let idTokenExpiration = idTokenClaims["exp"]?.doubleValue, - let accessTokenExpiration = accessTokenClaims["exp"]?.doubleValue else { + let accessTokenExpiration = accessTokenClaims["exp"]?.doubleValue + else { return currentTime > expiration } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift index 2efe44d5fc..23abb97de5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/AuthProvider+Cognito.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation extension AuthProvider { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift index 341ac58617..28eb37ac2b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation enum ClientSecretHelper { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift index ae6d367070..ffd36adf36 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ConfigurationHelper.swift @@ -46,16 +46,15 @@ struct ConfigurationHelper { }() // parse `authFlowType` - var authFlowType: AuthFlowType - if case .boolean(let isMigrationEnabled) = cognitoUserPoolJSON.value(at: "MigrationEnabled"), + var authFlowType: AuthFlowType = if case .boolean(let isMigrationEnabled) = cognitoUserPoolJSON.value(at: "MigrationEnabled"), isMigrationEnabled == true { - authFlowType = .userPassword + .userPassword } else if let authJson = config.value(at: "Auth.Default"), case .string(let authFlowTypeJSON) = authJson.value(at: "authenticationFlowType"), authFlowTypeJSON == "CUSTOM_AUTH" { - authFlowType = .customWithSRP + .customWithSRP } else { - authFlowType = .userSRP + .userSRP } // parse `clientSecret` @@ -68,25 +67,27 @@ struct ConfigurationHelper { let hostedUIConfig = parseHostedConfiguration( configuration: config.value(at: "Auth.Default.OAuth")) - return UserPoolConfigurationData(poolId: poolId, - clientId: appClientId, - region: region, - endpoint: endpoint, - clientSecret: clientSecret, - pinpointAppId: pinpointId, - authFlowType: authFlowType, - hostedUIConfig: hostedUIConfig, - passwordProtectionSettings: nil, - usernameAttributes: [], - signUpAttributes: [], - verificationMechanisms: []) + return UserPoolConfigurationData( + poolId: poolId, + clientId: appClientId, + region: region, + endpoint: endpoint, + clientSecret: clientSecret, + pinpointAppId: pinpointId, + authFlowType: authFlowType, + hostedUIConfig: hostedUIConfig, + passwordProtectionSettings: nil, + usernameAttributes: [], + signUpAttributes: [], + verificationMechanisms: [] + ) } static func parseUserPoolData(_ config: AmplifyOutputsData.Auth) -> UserPoolConfigurationData? { let hostedUIConfig = parseHostedConfiguration(configuration: config) // parse `passwordProtectionSettings` - var passwordProtectionSettings: UserPoolConfigurationData.PasswordProtectionSettings? = nil + var passwordProtectionSettings: UserPoolConfigurationData.PasswordProtectionSettings? if let passwordPolicy = config.passwordPolicy { passwordProtectionSettings = .init(from: passwordPolicy) } @@ -106,18 +107,20 @@ struct ConfigurationHelper { .userVerificationTypes? .compactMap { .init(from: $0) } ?? [] - return UserPoolConfigurationData(poolId: config.userPoolId, - clientId: config.userPoolClientId, - region: config.awsRegion, - endpoint: nil, // Gen2 does not support this field - clientSecret: nil, // Gen2 does not support this field - pinpointAppId: nil, // Gen2 does not support this field - authFlowType: .userSRP, - hostedUIConfig: hostedUIConfig, - passwordProtectionSettings: passwordProtectionSettings, - usernameAttributes: usernameAttributes, - signUpAttributes: signUpAttributes, - verificationMechanisms: verificationMechanisms) + return UserPoolConfigurationData( + poolId: config.userPoolId, + clientId: config.userPoolClientId, + region: config.awsRegion, + endpoint: nil, // Gen2 does not support this field + clientSecret: nil, // Gen2 does not support this field + pinpointAppId: nil, // Gen2 does not support this field + authFlowType: .userSRP, + hostedUIConfig: hostedUIConfig, + passwordProtectionSettings: passwordProtectionSettings, + usernameAttributes: usernameAttributes, + signUpAttributes: signUpAttributes, + verificationMechanisms: verificationMechanisms + ) } static func parseHostedConfiguration(configuration: JSONValue?) -> HostedUIConfigurationData? { @@ -142,44 +145,55 @@ struct ConfigurationHelper { clientSecret = appClientSecret } - return createHostedConfiguration(appClientId: appClientId, - clientSecret: clientSecret, - domain: domain, - scopes: scopesArray, - signInRedirectURI: signInRedirectURI, - signOutRedirectURI: signOutRedirectURI) + return createHostedConfiguration( + appClientId: appClientId, + clientSecret: clientSecret, + domain: domain, + scopes: scopesArray, + signInRedirectURI: signInRedirectURI, + signOutRedirectURI: signOutRedirectURI + ) } static func parseHostedConfiguration(configuration: AmplifyOutputsData.Auth) -> HostedUIConfigurationData? { guard let oauth = configuration.oauth, let signInRedirectURI = oauth.redirectSignInUri.first, - let signOutRedirectURI = oauth.redirectSignOutUri.first else { + let signOutRedirectURI = oauth.redirectSignOutUri.first + else { return nil } - return createHostedConfiguration(appClientId: configuration.userPoolClientId, - clientSecret: nil, - domain: oauth.domain, - scopes: oauth.scopes, - signInRedirectURI: signInRedirectURI, - signOutRedirectURI: signOutRedirectURI) + return createHostedConfiguration( + appClientId: configuration.userPoolClientId, + clientSecret: nil, + domain: oauth.domain, + scopes: oauth.scopes, + signInRedirectURI: signInRedirectURI, + signOutRedirectURI: signOutRedirectURI + ) } - static func createHostedConfiguration(appClientId: String, - clientSecret: String?, - domain: String, - scopes: [String], - signInRedirectURI: String, - signOutRedirectURI: String) -> HostedUIConfigurationData { - - let oauth = OAuthConfigurationData(domain: domain, - scopes: scopes, - signInRedirectURI: signInRedirectURI, - signOutRedirectURI: signOutRedirectURI) - - return HostedUIConfigurationData(clientId: appClientId, - oauth: oauth, - clientSecret: clientSecret) + static func createHostedConfiguration( + appClientId: String, + clientSecret: String?, + domain: String, + scopes: [String], + signInRedirectURI: String, + signOutRedirectURI: String + ) -> HostedUIConfigurationData { + + let oauth = OAuthConfigurationData( + domain: domain, + scopes: scopes, + signInRedirectURI: signInRedirectURI, + signOutRedirectURI: signOutRedirectURI + ) + + return HostedUIConfigurationData( + clientId: appClientId, + oauth: oauth, + clientSecret: clientSecret + ) } static func parseIdentityPoolData(_ config: JSONValue) -> IdentityPoolConfigurationData? { @@ -198,8 +212,10 @@ struct ConfigurationHelper { static func parseIdentityPoolData(_ config: AmplifyOutputsData.Auth) -> IdentityPoolConfigurationData? { if let identityPoolId = config.identityPoolId { - return IdentityPoolConfigurationData(poolId: identityPoolId, - region: config.awsRegion) + return IdentityPoolConfigurationData( + poolId: identityPoolId, + region: config.awsRegion + ) } else { return nil } @@ -209,8 +225,10 @@ struct ConfigurationHelper { let userPoolConfig = try parseUserPoolData(config) let identityPoolConfig = parseIdentityPoolData(config) - return try createAuthConfiguration(userPoolConfig: userPoolConfig, - identityPoolConfig: identityPoolConfig) + return try createAuthConfiguration( + userPoolConfig: userPoolConfig, + identityPoolConfig: identityPoolConfig + ) } static func authConfiguration(_ config: AmplifyOutputsData) throws -> AuthConfiguration { @@ -223,13 +241,17 @@ struct ConfigurationHelper { let userPoolConfig = parseUserPoolData(config) let identityPoolConfig = parseIdentityPoolData(config) - return try createAuthConfiguration(userPoolConfig: userPoolConfig, - identityPoolConfig: identityPoolConfig) + return try createAuthConfiguration( + userPoolConfig: userPoolConfig, + identityPoolConfig: identityPoolConfig + ) } - static func createAuthConfiguration(userPoolConfig: UserPoolConfigurationData?, - identityPoolConfig: IdentityPoolConfigurationData?) throws -> AuthConfiguration { + static func createAuthConfiguration( + userPoolConfig: UserPoolConfigurationData?, + identityPoolConfig: IdentityPoolConfigurationData? + ) throws -> AuthConfiguration { if let userPoolConfigNonNil = userPoolConfig, let identityPoolConfigNonNil = identityPoolConfig { return .userPoolsAndIdentityPools(userPoolConfigNonNil, identityPoolConfigNonNil) } @@ -268,17 +290,23 @@ struct ConfigurationHelper { let characterPolicy: [JSONValue] = passwordProtectionSettings.characterPolicy.map { .string($0.rawValue) } authConfigObject = .object( - ["usernameAttributes": .array(usernameAttributes), - "signupAttributes": .array(signUpAttributes), - "verificationMechanism": .array(verificationMechanisms), - "passwordProtectionSettings": .object( - ["passwordPolicyMinLength": .number(Double(minLength)), - "passwordPolicyCharacters": .array(characterPolicy)])]) + [ + "usernameAttributes": .array(usernameAttributes), + "signupAttributes": .array(signUpAttributes), + "verificationMechanism": .array(verificationMechanisms), + "passwordProtectionSettings": .object( + [ + "passwordPolicyMinLength": .number(Double(minLength)), + "passwordPolicyCharacters": .array(characterPolicy) + ]) + ]) } else { authConfigObject = .object( - ["usernameAttributes": .array(usernameAttributes), - "signupAttributes": .array(signUpAttributes), - "verificationMechanism": .array(verificationMechanisms)]) + [ + "usernameAttributes": .array(usernameAttributes), + "signupAttributes": .array(signUpAttributes), + "verificationMechanism": .array(verificationMechanisms) + ]) } return JSONValue.object([ diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift index f53ae871c3..e85996927e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/DeviceMetadataHelper.swift @@ -7,11 +7,12 @@ import AWSPluginsCore -struct DeviceMetadataHelper { +enum DeviceMetadataHelper { static func getDeviceMetadata( for username: String, - with environment: Environment) async -> DeviceMetadata { + with environment: Environment + ) async -> DeviceMetadata { let credentialStoreClient = (environment as? AuthEnvironment)?.credentialsClient do { let data = try await credentialStoreClient?.fetchData( @@ -32,7 +33,8 @@ struct DeviceMetadataHelper { static func removeDeviceMetaData( for username: String, - with environment: Environment) async { + with environment: Environment + ) async { let credentialStoreClient = (environment as? AuthEnvironment)?.credentialsClient do { try await credentialStoreClient?.deleteData( diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift index 7ecbadb633..a95fef66df 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/String+Mask.swift @@ -42,7 +42,7 @@ public extension String { } } -public extension Optional where Wrapped == String { +public extension String? { func masked( using character: Character = "*", interiorCount: Int = .max, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift index a35478741c..af861154f1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/TokenParserHelper.swift @@ -7,7 +7,7 @@ import Foundation -struct TokenParserHelper { +enum TokenParserHelper { static func getAuthUser(accessToken: String) throws -> AWSAuthUser { let tokenSplit = accessToken.split(separator: ".") @@ -20,11 +20,14 @@ struct TokenParserHelper { let paddedLength = base64.count + (4 - (base64.count % 4)) % 4 let base64Padding = base64.padding(toLength: paddedLength, withPad: "=", startingAt: 0) - guard let encodedData = Data(base64Encoded: base64Padding, - options: .ignoreUnknownCharacters), + guard let encodedData = Data( + base64Encoded: base64Padding, + options: .ignoreUnknownCharacters + ), let jsonObject = try? JSONSerialization.jsonObject( - with: encodedData, - options: []) as? [String: Any] + with: encodedData, + options: [] + ) as? [String: Any] else { throw SignInError.hostedUI(.tokenParsing) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift index 02a2d74f62..9f54c75924 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/UserPoolSignInHelper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation struct UserPoolSignInHelper: DefaultLogger { @@ -56,8 +56,10 @@ struct UserPoolSignInHelper: DefaultLogger { return nil } - private static func validateResult(for challengeType: AuthChallengeType, - with challenge: RespondToAuthChallenge) + private static func validateResult( + for challengeType: AuthChallengeType, + with challenge: RespondToAuthChallenge + ) throws -> AuthSignInResult { switch challengeType { case .smsMfa: @@ -92,33 +94,38 @@ struct UserPoolSignInHelper: DefaultLogger { request: RespondToAuthChallengeInput, for username: String, signInMethod: SignInMethod, - environment: UserPoolEnvironment) async throws -> StateMachineEvent { + environment: UserPoolEnvironment + ) async throws -> StateMachineEvent { let client = try environment.cognitoUserPoolFactory() let response = try await client.respondToAuthChallenge(input: request) - let event = self.parseResponse(response, for: username, signInMethod: signInMethod) + let event = parseResponse(response, for: username, signInMethod: signInMethod) return event } static func parseResponse( _ response: SignInResponseBehavior, for username: String, - signInMethod: SignInMethod) -> StateMachineEvent { + signInMethod: SignInMethod + ) -> StateMachineEvent { if let authenticationResult = response.authenticationResult, let idToken = authenticationResult.idToken, let accessToken = authenticationResult.accessToken, let refreshToken = authenticationResult.refreshToken { - let userPoolTokens = AWSCognitoUserPoolTokens(idToken: idToken, - accessToken: accessToken, - refreshToken: refreshToken, - expiresIn: authenticationResult.expiresIn) + let userPoolTokens = AWSCognitoUserPoolTokens( + idToken: idToken, + accessToken: accessToken, + refreshToken: refreshToken, + expiresIn: authenticationResult.expiresIn + ) let signedInData = SignedInData( signedInDate: Date(), signInMethod: signInMethod, deviceMetadata: authenticationResult.deviceMetadata, - cognitoUserPoolTokens: userPoolTokens) + cognitoUserPoolTokens: userPoolTokens + ) switch signedInData.deviceMetadata { case .noData: @@ -133,7 +140,8 @@ struct UserPoolSignInHelper: DefaultLogger { challenge: challengeName, username: username, session: response.session, - parameters: parameters) + parameters: parameters + ) switch challengeName { case .smsMfa, .customChallenge, .newPasswordRequired, .softwareTokenMfa, .selectMfaType: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift index c15d072b39..11eda7f1bb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/AuthUIPresentationAnchorPlaceholder.swift @@ -18,8 +18,10 @@ class AuthUIPresentationAnchorPlaceholder: Equatable { private init() {} - public static func == (lhs: AuthUIPresentationAnchorPlaceholder, - rhs: AuthUIPresentationAnchorPlaceholder) -> Bool { + public static func == ( + lhs: AuthUIPresentationAnchorPlaceholder, + rhs: AuthUIPresentationAnchorPlaceholder + ) -> Bool { true } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift index 75f6e44e19..9ef0565678 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIASWebAuthenticationSession.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation #if os(iOS) || os(macOS) import AuthenticationServices #endif @@ -19,10 +19,11 @@ class HostedUIASWebAuthenticationSession: NSObject, HostedUISessionBehavior { url: URL, callbackScheme: String, inPrivate: Bool, - presentationAnchor: AuthUIPresentationAnchor?) async throws -> [URLQueryItem] { + presentationAnchor: AuthUIPresentationAnchor? + ) async throws -> [URLQueryItem] { #if os(iOS) || os(macOS) - self.webPresentation = presentationAnchor + webPresentation = presentationAnchor return try await withCheckedThrowingContinuation { [weak self] (continuation: CheckedContinuation<[URLQueryItem], Error>) in @@ -33,7 +34,7 @@ class HostedUIASWebAuthenticationSession: NSObject, HostedUISessionBehavior { callbackURLScheme: callbackScheme, completionHandler: { [weak self] url, error in guard let self else { return } - if let url = url { + if let url { let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) let queryItems = urlComponents?.queryItems ?? [] @@ -49,14 +50,15 @@ class HostedUIASWebAuthenticationSession: NSObject, HostedUISessionBehavior { return continuation.resume( returning: queryItems) } - } else if let error = error { + } else if let error { return continuation.resume( - throwing: self.convertHostedUIError(error)) + throwing: convertHostedUIError(error)) } else { return continuation.resume( throwing: HostedUIError.unknown) } - }) + } + ) aswebAuthenticationSession.presentationContextProvider = self aswebAuthenticationSession.prefersEphemeralWebBrowserSession = inPrivate diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift index 8976659779..aef9ae9671 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift @@ -5,16 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CryptoKit +import Foundation -struct HostedUIRequestHelper { +enum HostedUIRequestHelper { - static func createSignInURL(state: String, - proofKey: String, - userContextData: String?, - configuration: HostedUIConfigurationData, - options: HostedUIOptions) throws -> URL { + static func createSignInURL( + state: String, + proofKey: String, + userContextData: String?, + configuration: HostedUIConfigurationData, + options: HostedUIOptions + ) throws -> URL { guard let proofData = proofKey.data(using: .ascii) else { throw HostedUIError.proofCalculation @@ -45,7 +47,7 @@ struct HostedUIRequestHelper { .init(name: "code_challenge", value: codeChallenge) ] - if let userContextData = userContextData { + if let userContextData { components.queryItems?.append( .init(name: "userContextData", value: userContextData)) } @@ -83,12 +85,15 @@ struct HostedUIRequestHelper { return logoutURL } - static func createTokenRequest(configuration: HostedUIConfigurationData, - result: HostedUIResult) throws -> URLRequest { + static func createTokenRequest( + configuration: HostedUIConfigurationData, + result: HostedUIResult + ) throws -> URLRequest { guard let signInRedirectURI = configuration.oauth .signInRedirectURI - .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { + .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) + else { throw HostedUIError.tokenURI } @@ -107,7 +112,8 @@ struct HostedUIRequestHelper { .init(name: "client_id", value: configuration.clientId), .init(name: "code", value: result.code), .init(name: "redirect_uri", value: signInRedirectURI), - .init(name: "code_verifier", value: result.codeVerifier)] + .init(name: "code_verifier", value: result.codeVerifier) + ] guard let body = queryComponents.query else { throw HostedUIError.tokenURI diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift index 016dd21038..5e08c75301 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUISessionBehavior.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AuthenticationServices import Amplify +import AuthenticationServices +import Foundation protocol HostedUISessionBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift index 259b464c87..9ff9f5adf6 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/RandomStringBehavior.swift @@ -1,3 +1,10 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + import Foundation protocol RandomStringBehavior { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift index 946b5a4bfe..e3a49c1000 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmResetPasswordRequest+Validation.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthConfirmResetPasswordRequest { @@ -13,19 +14,22 @@ extension AuthConfirmResetPasswordRequest { return AuthError.validation( AuthPluginErrorConstants.confirmResetPasswordUsernameError.field, AuthPluginErrorConstants.confirmResetPasswordUsernameError.errorDescription, - AuthPluginErrorConstants.confirmResetPasswordUsernameError.recoverySuggestion) + AuthPluginErrorConstants.confirmResetPasswordUsernameError.recoverySuggestion + ) } guard !newPassword.isEmpty else { return AuthError.validation( AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.field, AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.errorDescription, - AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.recoverySuggestion) + AuthPluginErrorConstants.confirmResetPasswordNewPasswordError.recoverySuggestion + ) } guard !confirmationCode.isEmpty else { return AuthError.validation( AuthPluginErrorConstants.confirmResetPasswordCodeError.field, AuthPluginErrorConstants.confirmResetPasswordCodeError.errorDescription, - AuthPluginErrorConstants.confirmResetPasswordCodeError.recoverySuggestion) + AuthPluginErrorConstants.confirmResetPasswordCodeError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift index c310f51bcc..ab032ff029 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignInRequest+Validation.swift @@ -4,15 +4,18 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthConfirmSignInRequest { func hasError() -> AuthError? { guard !challengeResponse.isEmpty else { - return AuthError.validation(AuthPluginErrorConstants.confirmSignInChallengeResponseError.field, - AuthPluginErrorConstants.confirmSignInChallengeResponseError.errorDescription, - AuthPluginErrorConstants.confirmSignInChallengeResponseError.recoverySuggestion) + return AuthError.validation( + AuthPluginErrorConstants.confirmSignInChallengeResponseError.field, + AuthPluginErrorConstants.confirmSignInChallengeResponseError.errorDescription, + AuthPluginErrorConstants.confirmSignInChallengeResponseError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift index d53fe6c0f3..8a06538a7b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthConfirmSignUpRequest+Validation.swift @@ -15,15 +15,17 @@ extension AuthConfirmSignUpRequest { let error = AuthError.validation( AuthPluginErrorConstants.signUpUsernameError.field, AuthPluginErrorConstants.signUpUsernameError.errorDescription, - AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil + ) throw error } guard !code.isEmpty else { let error = AuthError.validation( - AuthPluginErrorConstants.confirmSignUpCodeError.field, - AuthPluginErrorConstants.confirmSignUpCodeError.errorDescription, - AuthPluginErrorConstants.confirmSignUpCodeError.recoverySuggestion, nil) + AuthPluginErrorConstants.confirmSignUpCodeError.field, + AuthPluginErrorConstants.confirmSignUpCodeError.errorDescription, + AuthPluginErrorConstants.confirmSignUpCodeError.recoverySuggestion, nil + ) throw error } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift index 01f61e1f78..d476cf6b0a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResendSignUpCodeRequest+Validation.swift @@ -4,15 +4,18 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthResendSignUpCodeRequest { func hasError() -> AuthError? { guard !username.isEmpty else { - return AuthError.validation(AuthPluginErrorConstants.resendSignUpCodeUsernameError.field, - AuthPluginErrorConstants.resendSignUpCodeUsernameError.errorDescription, - AuthPluginErrorConstants.resendSignUpCodeUsernameError.recoverySuggestion) + return AuthError.validation( + AuthPluginErrorConstants.resendSignUpCodeUsernameError.field, + AuthPluginErrorConstants.resendSignUpCodeUsernameError.errorDescription, + AuthPluginErrorConstants.resendSignUpCodeUsernameError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift index 817d16c4fc..7ce3c9dfdc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthResetPasswordRequest+Validation.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify extension AuthResetPasswordRequest { @@ -13,7 +14,8 @@ extension AuthResetPasswordRequest { return AuthError.validation( AuthPluginErrorConstants.resetPasswordUsernameError.field, AuthPluginErrorConstants.resetPasswordUsernameError.errorDescription, - AuthPluginErrorConstants.resetPasswordUsernameError.recoverySuggestion) + AuthPluginErrorConstants.resetPasswordUsernameError.recoverySuggestion + ) } return nil } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift index 4ca839b39b..a9e57830b2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Request/AuthSignUpRequest+Validation.swift @@ -14,7 +14,8 @@ extension AuthSignUpRequest { let error = AuthError.validation( AuthPluginErrorConstants.signUpUsernameError.field, AuthPluginErrorConstants.signUpUsernameError.errorDescription, - AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil) + AuthPluginErrorConstants.signUpUsernameError.recoverySuggestion, nil + ) throw error } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift index 6d3fea6612..3db5c1d858 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/ConfirmSignUpInput+Amplify.swift @@ -5,29 +5,32 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension ConfirmSignUpInput { - init(username: String, - confirmationCode: String, - clientMetadata: [String: String]?, - asfDeviceId: String?, - forceAliasCreation: Bool?, - environment: UserPoolEnvironment + init( + username: String, + confirmationCode: String, + clientMetadata: [String: String]?, + asfDeviceId: String?, + forceAliasCreation: Bool?, + environment: UserPoolEnvironment ) async { let configuration = environment.userPoolConfiguration let secretHash = ClientSecretHelper.calculateSecretHash( username: username, - userPoolConfiguration: configuration) + userPoolConfiguration: configuration + ) var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } let analyticsMetadata = environment @@ -41,6 +44,7 @@ extension ConfirmSignUpInput { forceAliasCreation: forceAliasCreation, secretHash: secretHash, userContextData: userContextData, - username: username) + username: username + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift index b3a5edf8d2..df2a371788 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/HttpClientEngineProxy.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@_spi(InternalHttpEngineProxy) @_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials import ClientRuntime import Foundation +@_spi(InternalHttpEngineProxy) @_spi(InternalAmplifyPluginExtension) import InternalAmplifyCredentials protocol HttpClientEngineProxy: HTTPClient { var target: HTTPClient? { get set } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift index fbda1ffbc0..daf5077e44 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/InitiateAuthInput+Amplify.swift @@ -5,18 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension InitiateAuthInput { - static func srpInput(username: String, - publicSRPAHexValue: String, - authFlowType: AuthFlowType, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func srpInput( + username: String, + publicSRPAHexValue: String, + authFlowType: AuthFlowType, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { var authParameters = [ "USERNAME": username, "SRP_A": publicSRPAHexValue @@ -28,81 +30,97 @@ extension InitiateAuthInput { authParameters["CHALLENGE_NAME"] = "SRP_A" } - return await buildInput(username: username, - authFlowType: authFlowType.getClientFlowType(), - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: authFlowType.getClientFlowType(), + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func customAuth(username: String, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func customAuth( + username: String, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { let authParameters = [ "USERNAME": username ] - return await buildInput(username: username, - authFlowType: .customAuth, - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: .customAuth, + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func migrateAuth(username: String, - password: String, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func migrateAuth( + username: String, + password: String, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { let authParameters = [ "USERNAME": username, "PASSWORD": password ] - return await buildInput(username: username, - authFlowType: .userPasswordAuth, - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: .userPasswordAuth, + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func refreshAuthInput(username: String, - refreshToken: String, - clientMetadata: [String: String], - asfDeviceId: String, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func refreshAuthInput( + username: String, + refreshToken: String, + clientMetadata: [String: String], + asfDeviceId: String, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { let authParameters = [ "REFRESH_TOKEN": refreshToken ] - return await buildInput(username: username, - authFlowType: .refreshTokenAuth, - authParameters: authParameters, - clientMetadata: clientMetadata, - asfDeviceId: asfDeviceId, - deviceMetadata: deviceMetadata, - environment: environment) + return await buildInput( + username: username, + authFlowType: .refreshTokenAuth, + authParameters: authParameters, + clientMetadata: clientMetadata, + asfDeviceId: asfDeviceId, + deviceMetadata: deviceMetadata, + environment: environment + ) } - static func buildInput(username: String, - authFlowType: CognitoIdentityProviderClientTypes.AuthFlowType, - authParameters: [String: String], - clientMetadata: [String: String], - asfDeviceId: String?, - deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> InitiateAuthInput { + static func buildInput( + username: String, + authFlowType: CognitoIdentityProviderClientTypes.AuthFlowType, + authParameters: [String: String], + clientMetadata: [String: String], + asfDeviceId: String?, + deviceMetadata: DeviceMetadata, + environment: UserPoolEnvironment + ) async -> InitiateAuthInput { var authParameters = authParameters let configuration = environment.userPoolConfiguration @@ -122,12 +140,13 @@ extension InitiateAuthInput { } var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } let analyticsMetadata = environment @@ -140,6 +159,7 @@ extension InitiateAuthInput { authParameters: authParameters, clientId: userPoolClientId, clientMetadata: clientMetadata, - userContextData: userContextData) + userContextData: userContextData + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift index 8132c97e28..d7fbea05ed 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/RespondToAuthChallengeInput+Amplify.swift @@ -5,27 +5,30 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension RespondToAuthChallengeInput { // swiftlint:disable:next function_parameter_count - static func passwordVerifier(username: String, - stateData: SRPStateData, - session: String?, - secretBlock: String, - signature: String, - clientMetadata: ClientMetadata, - deviceMetadata: DeviceMetadata, - asfDeviceId: String?, - environment: UserPoolEnvironment) async -> RespondToAuthChallengeInput { + static func passwordVerifier( + username: String, + stateData: SRPStateData, + session: String?, + secretBlock: String, + signature: String, + clientMetadata: ClientMetadata, + deviceMetadata: DeviceMetadata, + asfDeviceId: String?, + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { let dateStr = stateData.clientTimestamp.utcString let challengeResponses = [ "USERNAME": username, "TIMESTAMP": dateStr, "PASSWORD_CLAIM_SECRET_BLOCK": secretBlock, - "PASSWORD_CLAIM_SIGNATURE": signature] + "PASSWORD_CLAIM_SIGNATURE": signature + ] return await buildInput( username: username, challengeType: .passwordVerifier, @@ -34,16 +37,19 @@ extension RespondToAuthChallengeInput { clientMetadata: clientMetadata, asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } // swiftlint:disable:next function_parameter_count - static func deviceSRP(username: String, - environment: UserPoolEnvironment, - deviceMetadata: DeviceMetadata, - asfDeviceId: String?, - session: String?, - publicHexValue: String) async -> RespondToAuthChallengeInput { + static func deviceSRP( + username: String, + environment: UserPoolEnvironment, + deviceMetadata: DeviceMetadata, + asfDeviceId: String?, + session: String?, + publicHexValue: String + ) async -> RespondToAuthChallengeInput { let challengeResponses = [ "USERNAME": username, "SRP_A": publicHexValue @@ -56,24 +62,28 @@ extension RespondToAuthChallengeInput { clientMetadata: [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } - static func devicePasswordVerifier(username: String, - stateData: SRPStateData, - session: String?, - secretBlock: String, - signature: String, - deviceMetadata: DeviceMetadata, - asfDeviceId: String?, - environment: UserPoolEnvironment) async + static func devicePasswordVerifier( + username: String, + stateData: SRPStateData, + session: String?, + secretBlock: String, + signature: String, + deviceMetadata: DeviceMetadata, + asfDeviceId: String?, + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { let dateStr = stateData.clientTimestamp.utcString let challengeResponses = [ "USERNAME": username, "TIMESTAMP": dateStr, "PASSWORD_CLAIM_SECRET_BLOCK": secretBlock, - "PASSWORD_CLAIM_SIGNATURE": signature] + "PASSWORD_CLAIM_SIGNATURE": signature + ] return await buildInput( username: username, challengeType: .devicePasswordVerifier, @@ -82,7 +92,8 @@ extension RespondToAuthChallengeInput { clientMetadata: [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } // swiftlint:disable:next function_parameter_count @@ -96,7 +107,8 @@ extension RespondToAuthChallengeInput { asfDeviceId: String?, attributes: [String: String], deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> RespondToAuthChallengeInput { + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { var challengeResponses = [ "USERNAME": username, @@ -104,8 +116,8 @@ extension RespondToAuthChallengeInput { ] // Add the attributes to the challenge response - attributes.forEach { - challengeResponses[$0.key] = $0.value + for attribute in attributes { + challengeResponses[attribute.key] = attribute.value } return await buildInput( username: username, @@ -115,7 +127,8 @@ extension RespondToAuthChallengeInput { clientMetadata: clientMetadata ?? [:], asfDeviceId: asfDeviceId, deviceMetadata: deviceMetadata, - environment: environment) + environment: environment + ) } static func buildInput( @@ -126,7 +139,8 @@ extension RespondToAuthChallengeInput { clientMetadata: ClientMetadata, asfDeviceId: String?, deviceMetadata: DeviceMetadata, - environment: UserPoolEnvironment) async -> RespondToAuthChallengeInput { + environment: UserPoolEnvironment + ) async -> RespondToAuthChallengeInput { var challengeResponses = challengeResponses let userPoolClientId = environment.userPoolConfiguration.clientId if let clientSecret = environment.userPoolConfiguration.clientSecret { @@ -144,12 +158,13 @@ extension RespondToAuthChallengeInput { } var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } @@ -164,7 +179,8 @@ extension RespondToAuthChallengeInput { clientId: userPoolClientId, clientMetadata: clientMetadata, session: session, - userContextData: userContextData) + userContextData: userContextData + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift index bec03bab9b..a0f90a991c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Utils/SignUpInput+Amplify.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation #if canImport(WatchKit) import WatchKit #elseif canImport(UIKit) @@ -15,50 +15,59 @@ import UIKit extension SignUpInput { typealias CognitoAttributeType = CognitoIdentityProviderClientTypes.AttributeType - init(username: String, - password: String, - clientMetadata: [String: String]?, - validationData: [String: String]?, - attributes: [String: String], - asfDeviceId: String?, - environment: UserPoolEnvironment) async { + init( + username: String, + password: String, + clientMetadata: [String: String]?, + validationData: [String: String]?, + attributes: [String: String], + asfDeviceId: String?, + environment: UserPoolEnvironment + ) async { let configuration = environment.userPoolConfiguration - let secretHash = ClientSecretHelper.calculateSecretHash(username: username, - userPoolConfiguration: configuration) + let secretHash = ClientSecretHelper.calculateSecretHash( + username: username, + userPoolConfiguration: configuration + ) let validationData = await Self.getValidationData(with: validationData) let convertedAttributes = Self.convertAttributes(attributes) var userContextData: CognitoIdentityProviderClientTypes.UserContextDataType? - if let asfDeviceId = asfDeviceId, + if let asfDeviceId, let encodedData = await CognitoUserPoolASF.encodedContext( - username: username, - asfDeviceId: asfDeviceId, - asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: environment.userPoolConfiguration) { + username: username, + asfDeviceId: asfDeviceId, + asfClient: environment.cognitoUserPoolASFFactory(), + userPoolConfiguration: environment.userPoolConfiguration + ) { userContextData = .init(encodedData: encodedData) } let analyticsMetadata = environment .cognitoUserPoolAnalyticsHandlerFactory() .analyticsMetadata() - self.init(analyticsMetadata: analyticsMetadata, - clientId: configuration.clientId, - clientMetadata: clientMetadata, - password: password, - secretHash: secretHash, - userAttributes: convertedAttributes, - userContextData: userContextData, - username: username, - validationData: validationData) + self.init( + analyticsMetadata: analyticsMetadata, + clientId: configuration.clientId, + clientMetadata: clientMetadata, + password: password, + secretHash: secretHash, + userAttributes: convertedAttributes, + userContextData: userContextData, + username: username, + validationData: validationData + ) } private static func getValidationData(with devProvidedData: [String: String]?) async -> [CognitoIdentityProviderClientTypes.AttributeType]? { - if let devProvidedData = devProvidedData { - return devProvidedData.compactMap { (key, value) in + // swiftformat:disable all + if let devProvidedData { + return devProvidedData.compactMap { key, value in return CognitoIdentityProviderClientTypes.AttributeType(name: key, value: value) } + (await cognitoValidationData ?? []) } + // swiftformat:enable all return await cognitoValidationData } @@ -98,8 +107,10 @@ extension SignUpInput { private static func convertAttributes(_ attributes: [String: String]) -> [CognitoIdentityProviderClientTypes.AttributeType] { return attributes.reduce(into: [CognitoIdentityProviderClientTypes.AttributeType]()) { - $0.append(CognitoIdentityProviderClientTypes.AttributeType(name: $1.key, - value: $1.value)) + $0.append(CognitoIdentityProviderClientTypes.AttributeType( + name: $1.key, + value: $1.value + )) } } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift index 0fb50718c1..4bca9db65d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -22,9 +22,10 @@ class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { HubPayload.EventName.Auth.changePasswordAPI } - init(_ request: AuthChangePasswordRequest, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory + init( + _ request: AuthChangePasswordRequest, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory ) { self.request = request self.authStateMachine = authStateMachine @@ -52,9 +53,11 @@ class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { func changePassword(with accessToken: String) async throws { let userPoolService = try userPoolFactory() - let input = ChangePasswordInput(accessToken: accessToken, - previousPassword: request.oldPassword, - proposedPassword: request.newPassword) + let input = ChangePasswordInput( + accessToken: accessToken, + previousPassword: request.oldPassword, + proposedPassword: request.newPassword + ) _ = try await userPoolService.changePassword(input: input) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift index 293ae92b2f..92b4e3aa1a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthClearFederationToIdentityPoolTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthClearFederationToIdentityPoolTask: AmplifyAuthTask where Request == AuthClearFederationToIdentityPoolRequest, Success == Void, diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift index ceabc14ed2..11f24f5acf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogger { private let request: AuthConfirmResetPasswordRequest @@ -61,12 +61,14 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: request.username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: userPoolConfigurationData) + userPoolConfiguration: userPoolConfigurationData + ) let userContextData = CognitoIdentityProviderClientTypes.UserContextDataType( encodedData: encodedData) let analyticsMetadata = userPoolEnvironment @@ -84,7 +86,8 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg password: request.newPassword, secretHash: secretHash, userContextData: userContextData, - username: request.username) + username: request.username + ) _ = try await userPoolService.confirmForgotPassword(input: input) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift index 3c19a16d61..578be91ebe 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignInTask.swift @@ -4,9 +4,10 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify import AWSPluginsCore +import Foundation class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { @@ -19,9 +20,11 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { HubPayload.EventName.Auth.confirmSignInAPI } - init(_ request: AuthConfirmSignInRequest, - stateMachine: AuthStateMachine, - configuration: AuthConfiguration) { + init( + _ request: AuthConfirmSignInRequest, + stateMachine: AuthStateMachine, + configuration: AuthConfiguration + ) { self.request = request self.authStateMachine = stateMachine self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -37,7 +40,8 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { let message = AuthPluginErrorConstants.configurationError let authError = AuthError.configuration( "Could not find user pool configuration", - message) + message + ) throw authError } @@ -46,10 +50,12 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { } let invalidStateError = AuthError.invalidState( "User is not attempting signIn operation", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) guard case .configured(let authNState, _) = await authStateMachine.currentState, - case .signingIn(let signInState) = authNState else { + case .signingIn(let signInState) = authNState + else { throw invalidStateError } @@ -100,8 +106,9 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { return result case .notConfigured: throw AuthError.configuration( - "UserPool configuration is missing", - AuthPluginErrorConstants.configurationError) + "UserPool configuration is missing", + AuthPluginErrorConstants.configurationError + ) default: throw invalidStateError } @@ -116,7 +123,8 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { throw AuthError.validation( AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.field, AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.errorDescription, - AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.recoverySuggestion) + AuthPluginErrorConstants.confirmSignInMFASelectionResponseError.recoverySuggestion + ) } } @@ -142,10 +150,11 @@ class AWSAuthConfirmSignInTask: AuthConfirmSignInTask, DefaultLogger { $0[attributePrefix + $1.key.rawValue] = $1.value } ?? [:] return ConfirmSignInEventData( - answer: self.request.challengeResponse, + answer: request.challengeResponse, attributes: attributes, metadata: pluginOptions?.metadata, - friendlyDeviceName: pluginOptions?.friendlyDeviceName) + friendlyDeviceName: pluginOptions?.friendlyDeviceName + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift index dbbb086118..f296c25454 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoIdentityProvider +import Foundation class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { @@ -31,16 +31,19 @@ class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: authEnvironment.credentialsClient) + credentialStoreClient: authEnvironment.credentialsClient + ) let metadata = (request.options.pluginOptions as? AWSAuthConfirmSignUpOptions)?.metadata let forceAliasCreation = (request.options.pluginOptions as? AWSAuthConfirmSignUpOptions)?.forceAliasCreation let client = try userPoolEnvironment.cognitoUserPoolFactory() - let input = await ConfirmSignUpInput(username: request.username, - confirmationCode: request.code, - clientMetadata: metadata, - asfDeviceId: asfDeviceId, - forceAliasCreation: forceAliasCreation, - environment: userPoolEnvironment) + let input = await ConfirmSignUpInput( + username: request.username, + confirmationCode: request.code, + clientMetadata: metadata, + asfDeviceId: asfDeviceId, + forceAliasCreation: forceAliasCreation, + environment: userPoolEnvironment + ) _ = try await client.confirmSignUp(input: input) log.verbose("Received success") return AuthSignUpResult(.done, userID: nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift index 4539bcecba..3296024e7d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthDeleteUserTask.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSPluginsCore +import Foundation class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { private let authStateMachine: AuthStateMachine @@ -18,8 +18,10 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { HubPayload.EventName.Auth.deleteUserAPI } - init(authStateMachine: AuthStateMachine, - authConfiguraiton: AuthConfiguration) { + init( + authStateMachine: AuthStateMachine, + authConfiguraiton: AuthConfiguration + ) { self.authStateMachine = authStateMachine self.configuration = authConfiguraiton self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -51,7 +53,8 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { let error = AuthError.invalidState( "Auth state should be in configured state and authentication state should be in deleting user state", AuthPluginErrorConstants.invalidStateError, - nil) + nil + ) throw error } @@ -72,7 +75,8 @@ class AWSAuthDeleteUserTask: AuthDeleteUserTask, DefaultLogger { private func signOutIfUserWasNotFound(with error: Error) async { guard case AuthError.service(_, _, let underlyingError) = error, - case .userNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .userNotFound = (underlyingError as? AWSCognitoAuthError) + else { return } log.verbose("User not found, signing out") diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift index 9f3151a63f..6e7164ab5c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFederateToIdentityPoolTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthFederateToIdentityPoolTask: AmplifyAuthTask where Request == AuthFederateToIdentityPoolRequest, Success == FederateToIdentityPoolResult, @@ -40,7 +40,8 @@ public class AWSAuthFederateToIdentityPoolTask: AuthFederateToIdentityPoolTask, guard case .configured(let authNState, let authZState) = state else { throw AuthError.invalidState( "Federation could not be completed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) } if isValidAuthNStateToStart(authNState) && isValidAuthZStateToStart(authZState) { @@ -48,7 +49,8 @@ public class AWSAuthFederateToIdentityPoolTask: AuthFederateToIdentityPoolTask, } else { throw AuthError.invalidState( "Federation could not be completed.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) } } @@ -106,7 +108,8 @@ public class AWSAuthFederateToIdentityPoolTask: AuthFederateToIdentityPoolTask, case .identityPoolWithFederation(_, let identityId, let awsCredentials): let federatedResult = FederateToIdentityPoolResult( credentials: awsCredentials, - identityId: identityId) + identityId: identityId + ) return federatedResult default: throw AuthError.unknown("Unable to parse credentials to expected output", nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift index 7a00941ad9..e6ee1f6ce2 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthFetchSessionTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class AWSAuthFetchSessionTask: AuthFetchSessionTask, DefaultLogger { private let request: AuthFetchSessionRequest @@ -29,8 +29,10 @@ class AWSAuthFetchSessionTask: AuthFetchSessionTask, DefaultLogger { log.verbose("Starting execution") await taskHelper.didStateMachineConfigured() let doesNeedForceRefresh = request.options.forceRefresh - return try await fetchAuthSessionHelper.fetch(authStateMachine, - forceRefresh: doesNeedForceRefresh) + return try await fetchAuthSessionHelper.fetch( + authStateMachine, + forceRefresh: doesNeedForceRefresh + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift index 527b796585..f83fd9a18c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { private let request: AuthResendSignUpCodeRequest @@ -61,12 +61,14 @@ class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: request.username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: userPoolConfigurationData) + userPoolConfiguration: userPoolConfigurationData + ) let userContextData = CognitoIdentityProviderClientTypes.UserContextDataType( encodedData: encodedData) let analyticsMetadata = userPoolEnvironment @@ -82,7 +84,8 @@ class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { clientMetadata: clientMetaData, secretHash: secretHash, userContextData: userContextData, - username: request.username) + username: request.username + ) let result = try await userPoolService.resendConfirmationCode(input: input) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift index 823b0178e1..07d04ffdfe 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { @@ -61,12 +61,14 @@ class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { } let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: environment.credentialsClient) + credentialStoreClient: environment.credentialsClient + ) let encodedData = await CognitoUserPoolASF.encodedContext( username: request.username, asfDeviceId: asfDeviceId, asfClient: environment.cognitoUserPoolASFFactory(), - userPoolConfiguration: userPoolConfigurationData) + userPoolConfiguration: userPoolConfigurationData + ) let userContextData = CognitoIdentityProviderClientTypes.UserContextDataType( encodedData: encodedData) let analyticsMetadata = userPoolEnvironment @@ -82,7 +84,8 @@ class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { clientMetadata: clientMetaData, secretHash: secretHash, userContextData: userContextData, - username: request.username) + username: request.username + ) let result = try await userPoolService.forgotPassword(input: input) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift index 3a68e3aeff..d906899d70 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignInTask.swift @@ -4,9 +4,10 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify import AWSPluginsCore +import Foundation class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { @@ -19,9 +20,11 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { HubPayload.EventName.Auth.signInAPI } - init(_ request: AuthSignInRequest, - authStateMachine: AuthStateMachine, - configuration: AuthConfiguration) { + init( + _ request: AuthSignInRequest, + authStateMachine: AuthStateMachine, + configuration: AuthConfiguration + ) { self.request = request self.authStateMachine = authStateMachine self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -36,7 +39,8 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { let message = AuthPluginErrorConstants.configurationError let authError = AuthError.configuration( "Could not find user pool configuration", - message) + message + ) throw authError } @@ -67,7 +71,8 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { case .signedIn: let error = AuthError.invalidState( "There is already a user in signedIn state. SignOut the user first before calling signIn", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) throw error case .signingIn: log.verbose("Cancelling existing signIn flow") @@ -85,8 +90,10 @@ class AWSAuthSignInTask: AuthSignInTask, DefaultLogger { await sendSignInEvent(authflowType: authflowType) log.verbose("Waiting for signin to complete") for await state in stateSequences { - guard case .configured(let authNState, - let authZState) = state else { continue } + guard case .configured( + let authNState, + let authZState + ) = state else { continue } switch authNState { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift index f5de608577..b412b1400a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignOutTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class AWSAuthSignOutTask: AuthSignOutTask, DefaultLogger { @@ -39,7 +39,8 @@ class AWSAuthSignOutTask: AuthSignOutTask, DefaultLogger { } else if case .federatedToIdentityPool = authNState { let invalidStateError = AuthError.invalidState( "The user is currently federated to identity pool. You must call clearFederationToIdentityPool to clear credentials.", - AuthPluginErrorConstants.invalidStateError, nil) + AuthPluginErrorConstants.invalidStateError, nil + ) return AWSCognitoSignOutResult.failed(invalidStateError) } else { return invalidStateResult() diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift index 9e86b68daf..e6513525d5 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import Foundation class AWSAuthSignUpTask: AuthSignUpTask, DefaultLogger { @@ -36,18 +36,21 @@ class AWSAuthSignUpTask: AuthSignUpTask, DefaultLogger { let client = try userPoolEnvironment.cognitoUserPoolFactory() let asfDeviceId = try await CognitoUserPoolASF.asfDeviceID( for: request.username, - credentialStoreClient: authEnvironment.credentialsClient) + credentialStoreClient: authEnvironment.credentialsClient + ) let attributes = request.options.userAttributes?.reduce( into: [String: String]()) { $0[$1.key.rawValue] = $1.value } ?? [:] - let input = await SignUpInput(username: request.username, - password: request.password!, - clientMetadata: metaData, - validationData: validationData, - attributes: attributes, - asfDeviceId: asfDeviceId, - environment: userPoolEnvironment) + let input = await SignUpInput( + username: request.username, + password: request.password!, + clientMetadata: metaData, + validationData: validationData, + attributes: attributes, + asfDeviceId: asfDeviceId, + environment: userPoolEnvironment + ) let response = try await client.signUp(input: input) log.verbose("Received result") diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift index 564b5c177e..cc14416733 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift @@ -6,9 +6,9 @@ // #if os(iOS) || os(macOS) -import Foundation import Amplify import AWSPluginsCore +import Foundation class AWSAuthWebUISignInTask: AuthWebUISignInTask, DefaultLogger { @@ -18,16 +18,19 @@ class AWSAuthWebUISignInTask: AuthWebUISignInTask, DefaultLogger { private let taskHelper: AWSAuthTaskHelper let eventName: HubPayloadEventName - init(_ request: AuthWebUISignInRequest, - authConfiguration: AuthConfiguration, - authStateMachine: AuthStateMachine, - eventName: String + init( + _ request: AuthWebUISignInRequest, + authConfiguration: AuthConfiguration, + authStateMachine: AuthStateMachine, + eventName: String ) { self.request = request self.authStateMachine = authStateMachine - self.helper = HostedUISignInHelper(request: request, - authstateMachine: authStateMachine, - configuration: authConfiguration) + self.helper = HostedUISignInHelper( + request: request, + authstateMachine: authStateMachine, + configuration: authConfiguration + ) self.eventName = eventName self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift index 5ba804b989..a041023091 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthFetchDevicesTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthFetchDevicesTask: AuthFetchDevicesTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -40,7 +40,7 @@ class AWSAuthFetchDevicesTask: AuthFetchDevicesTask, DefaultLogger { throw error.authError } catch let error as AuthError { throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift index 239b4f9eac..62a08cd75f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthForgetDeviceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { @@ -22,9 +22,11 @@ class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { HubPayload.EventName.Auth.forgetDeviceAPI } - init(_ request: AuthForgetDeviceRequest, - authStateMachine: AuthStateMachine, - environment: AuthEnvironment) { + init( + _ request: AuthForgetDeviceRequest, + authStateMachine: AuthStateMachine, + environment: AuthEnvironment + ) { self.request = request self.authStateMachine = authStateMachine @@ -42,7 +44,7 @@ class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { throw error.authError } catch let error as AuthError { throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } @@ -61,7 +63,8 @@ class AWSAuthForgetDeviceTask: AuthForgetDeviceTask, DefaultLogger { guard let device = request.device else { let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) if case .metadata(let data) = deviceMetadata { let input = ForgetDeviceInput(accessToken: accessToken, deviceKey: data.deviceKey) _ = try await userPoolService.forgetDevice(input: input) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift index 71eb26f3f7..15794bec58 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/DeviceTasks/AWSAuthRememberDeviceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { @@ -22,9 +22,11 @@ class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { HubPayload.EventName.Auth.rememberDeviceAPI } - init(_ request: AuthRememberDeviceRequest, - authStateMachine: AuthStateMachine, - environment: AuthEnvironment) { + init( + _ request: AuthRememberDeviceRequest, + authStateMachine: AuthStateMachine, + environment: AuthEnvironment + ) { self.request = request self.authStateMachine = authStateMachine self.environment = environment @@ -41,7 +43,7 @@ class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { throw error.authError } catch let error as AuthError { throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } @@ -59,11 +61,14 @@ class AWSAuthRememberDeviceTask: AuthRememberDeviceTask, DefaultLogger { let userPoolService = try environment.cognitoUserPoolFactory() let deviceMetadata = await DeviceMetadataHelper.getDeviceMetadata( for: username, - with: environment) + with: environment + ) if case .metadata(let data) = deviceMetadata { - let input = UpdateDeviceStatusInput(accessToken: accessToken, - deviceKey: data.deviceKey, - deviceRememberedStatus: .remembered) + let input = UpdateDeviceStatusInput( + accessToken: accessToken, + deviceKey: data.deviceKey, + deviceRememberedStatus: .remembered + ) _ = try await userPoolService.updateDeviceStatus(input: input) } else { throw AuthError.unknown("Unable to get device metadata") diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift index acb63eacec..1ed501d21b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation protocol AuthFetchMFAPreferenceTask: AmplifyAuthTask where Request == Never, Success == UserMFAPreference, @@ -32,8 +32,10 @@ class FetchMFAPreferenceTask: AuthFetchMFAPreferenceTask, DefaultLogger { HubPayload.EventName.Auth.fetchMFAPreferenceAPI } - init(authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift index 44267909b1..2d58205262 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Helpers/AWSAuthTaskHelper.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthTaskHelper: DefaultLogger { @@ -48,7 +48,8 @@ class AWSAuthTaskHelper: DefaultLogger { return AWSCognitoSignOutResult.partial( revokeTokenError: data.revokeTokenError, globalSignOutError: data.globalSignOutError, - hostedUIError: data.hostedUIError) + hostedUIError: data.hostedUIError + ) } return AWSCognitoSignOutResult.complete case .signingIn: @@ -89,7 +90,8 @@ class AWSAuthTaskHelper: DefaultLogger { guard case .configured(let authenticationState, _) = authState else { throw AuthError.configuration( "Plugin not configured", - AuthPluginErrorConstants.configurationError) + AuthPluginErrorConstants.configurationError + ) } switch authenticationState { @@ -101,7 +103,8 @@ class AWSAuthTaskHelper: DefaultLogger { case .signedOut, .configured: throw AuthError.signedOut( "There is no user signed in to retrieve current user", - "Call Auth.signIn to sign in a user and then call Auth.getCurrentUser", nil) + "Call Auth.signIn to sign in a user and then call Auth.getCurrentUser", nil + ) case .error(let authNError): throw authNError.authError default: diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift index de7fec46ff..e08fbdf630 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AmplifyAuthTask { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift index aecfd2cd7e..15e1069f46 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AmplifyAuthTaskNonThrowing.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AmplifyAuthTaskNonThrowing { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift index c0067e6521..ca67519d4c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthChangePasswordTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthChangePasswordTask: AmplifyAuthTask where Request == AuthChangePasswordRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift index 4ae4b60d3e..d2c3541027 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmResetPasswordTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthConfirmResetPasswordTask: AmplifyAuthTask where Request == AuthConfirmResetPasswordRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift index 3f61b154d8..ea5df579f0 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignInTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthConfirmSignInTask: AmplifyAuthTask where Request == AuthConfirmSignInRequest, Success == AuthSignInResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift index 65014f85f2..8466dd55d1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthConfirmSignUpTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthConfirmSignUpTask: AmplifyAuthTask where Request == AuthConfirmSignUpRequest, Success == AuthSignUpResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift index 942873e618..c74e84f621 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthDeleteUserTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthDeleteUserTask: AmplifyAuthTask where Request == Never, Success == Void, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift index 670da24571..46efd03a36 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthFetchSessionTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthFetchSessionTask: AmplifyAuthTask where Request == AuthFetchSessionRequest, Success == AuthSession, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift index c6cd79a0a1..ffeeb80265 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResendSignUpCodeTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify protocol AuthResendSignUpCodeTask: AmplifyAuthTask where Request == AuthResendSignUpCodeRequest, Success == AuthCodeDeliveryDetails, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift index abb6c54632..f9302bbacf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthResetPasswordTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthResetPasswordTask: AmplifyAuthTask where Request == AuthResetPasswordRequest, Success == AuthResetPasswordResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift index 9a71406bbe..06c4f95282 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSetUpTOTPTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthSetUpTOTPTask: AmplifyAuthTask where Request == Never, Success == TOTPSetupDetails, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift index 509bae225f..c26824239c 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignInTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthSignInTask: AmplifyAuthTask where Request == AuthSignInRequest, Success == AuthSignInResult, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift index bcdd99ec77..c9a8136163 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignOutTask.swift @@ -4,8 +4,9 @@ // // SPDX-License-Identifier: Apache-2.0 // -import Foundation + import Amplify +import Foundation protocol AuthSignOutTask: AmplifyAuthTaskNonThrowing where Request == AuthSignOutRequest, Success == AuthSignOutResult { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift index 6ba40aeb49..12fd6e473f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSignUpTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthSignUpTask: AmplifyAuthTask where Request == AuthSignUpRequest, Success == AuthSignUpResult, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift index 430b072692..b5eec730cb 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthSocialWebUISignInTask.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) -import Foundation import Amplify +import Foundation protocol AuthSocialWebUISignInTask: AmplifyAuthTask where Request == AuthWebUISignInRequest, Success == AuthSignInResult, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift index f0b54d5bcb..00505d7da7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthVerifyTOTPSetupTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthVerifyTOTPSetupTask: AmplifyAuthTask where Request == VerifyTOTPSetupRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift index c68ae5bc56..718a65e45b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/AuthWebUISignInTask.swift @@ -6,8 +6,8 @@ // #if os(iOS) || os(macOS) -import Foundation import Amplify +import Foundation protocol AuthWebUISignInTask: AmplifyAuthTask where Request == AuthWebUISignInRequest, Success == AuthSignInResult, Failure == AuthError { } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift index 19efd6e384..9801f0283b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthFetchDevicesTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthFetchDevicesTask: AmplifyAuthTask where Request == AuthFetchDevicesRequest, Success == [AuthDevice], Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift index af27c94c79..27c537a977 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthForgetDeviceTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthForgetDeviceTask: AmplifyAuthTask where Request == AuthForgetDeviceRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift index f4365c8797..6091dda8e4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/DeviceTasks/AuthRememberDeviceTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthRememberDeviceTask: AmplifyAuthTask where Request == AuthRememberDeviceRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift index 22bd3525c0..561f84b127 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthConfirmUserAttributeTask.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation protocol AuthConfirmUserAttributeTask: AmplifyAuthTask where Request == AuthConfirmUserAttributeRequest, Success == Void, Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift index 49dd81815b..6bff56f037 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthFetchUserAttributeTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify protocol AuthFetchUserAttributeTask: AmplifyAuthTask where Request == AuthFetchUserAttributesRequest, Success == [AuthUserAttribute], Failure == AuthError {} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift index eaadcd9e78..f444ef5dd8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributeTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify // swiftlint:disable:next line_length diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift index b16def3182..3678a251f7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/Protocols/UserTasks/AuthUpdateUserAttributesTask.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Amplify // swiftlint:disable:next line_length diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift index 6a7ab2b6ea..23f9ac8973 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { @@ -23,8 +23,10 @@ class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { HubPayload.EventName.Auth.setUpTOTPAPI } - init(authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine) @@ -62,10 +64,13 @@ class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { throw AuthError.invalidState( "Auth State not in a valid state for the user", AuthPluginErrorConstants.invalidStateError, - nil) + nil + ) } - return .init(sharedSecret: secretCode, - username: authUser.username) + return .init( + sharedSecret: secretCode, + username: authUser.username + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift index b9bedf4fe8..cbc42e7ba1 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation protocol AuthUpdateMFAPreferenceTask: AmplifyAuthTask where Request == Never, Success == Void, @@ -34,10 +34,12 @@ class UpdateMFAPreferenceTask: AuthUpdateMFAPreferenceTask, DefaultLogger { HubPayload.EventName.Auth.updateMFAPreferenceAPI } - init(smsPreference: MFAPreference?, - totpPreference: MFAPreference?, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + smsPreference: MFAPreference?, + totpPreference: MFAPreference?, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.smsPreference = smsPreference self.totpPreference = totpPreference self.authStateMachine = authStateMachine @@ -64,7 +66,8 @@ class UpdateMFAPreferenceTask: AuthUpdateMFAPreferenceTask, DefaultLogger { let input = SetUserMFAPreferenceInput( accessToken: accessToken, smsMfaSettings: smsPreference?.smsSetting(isCurrentlyPreferred: preferredMFAType == .sms), - softwareTokenMfaSettings: totpPreference?.softwareTokenSetting(isCurrentlyPreferred: preferredMFAType == .totp)) + softwareTokenMfaSettings: totpPreference?.softwareTokenSetting(isCurrentlyPreferred: preferredMFAType == .totp) + ) _ = try await userPoolService.setUserMFAPreference(input: input) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift index 763af3e80c..cfe2a2dac7 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthAttributeResendConfirmationCodeTask: AuthAttributeResendConfirmationCodeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -53,7 +53,8 @@ class AWSAuthAttributeResendConfirmationCodeTask: AuthAttributeResendConfirmatio let input = GetUserAttributeVerificationCodeInput( accessToken: accessToken, attributeName: request.attributeKey.rawValue, - clientMetadata: clientMetaData) + clientMetadata: clientMetaData + ) let result = try await userPoolService.getUserAttributeVerificationCode(input: input) guard let deliveryDetails = result.codeDeliveryDetails?.toAuthCodeDeliveryDetails() else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift index b9b6574201..b7f0e147dc 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthConfirmUserAttributeTask: AuthConfirmUserAttributeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -48,7 +48,8 @@ class AWSAuthConfirmUserAttributeTask: AuthConfirmUserAttributeTask, DefaultLogg let input = VerifyUserAttributeInput( accessToken: accessToken, attributeName: request.attributeKey.rawValue, - code: request.confirmationCode) + code: request.confirmationCode + ) _ = try await userPoolService.verifyUserAttribute(input: input) } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift index c9e7a07727..5d5b3e70de 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class AWSAuthFetchUserAttributeTask: AuthFetchUserAttributeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -54,11 +54,14 @@ class AWSAuthFetchUserAttributeTask: AuthFetchUserAttributeTask, DefaultLogger { let mappedAttributes: [AuthUserAttribute] = attributes.compactMap { oldAttribute in guard let attributeName = oldAttribute.name, - let attributeValue = oldAttribute.value else { + let attributeValue = oldAttribute.value + else { return nil } - return AuthUserAttribute(AuthUserAttributeKey(rawValue: attributeName), - value: attributeValue) + return AuthUserAttribute( + AuthUserAttributeKey(rawValue: attributeName), + value: attributeValue + ) } return mappedAttributes } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift index 0d8d09f435..007887c6d3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthSendUserAttributeVerificationCodeTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerificationCodeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -22,9 +22,11 @@ class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerific HubPayload.EventName.Auth.sendUserAttributeVerificationCodeAPI } - init(_ request: AuthSendUserAttributeVerificationCodeRequest, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + _ request: AuthSendUserAttributeVerificationCodeRequest, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.request = request self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory @@ -55,7 +57,8 @@ class AWSAuthSendUserAttributeVerificationCodeTask: AuthSendUserAttributeVerific let input = GetUserAttributeVerificationCodeInput( accessToken: accessToken, attributeName: request.attributeKey.rawValue, - clientMetadata: clientMetaData) + clientMetadata: clientMetaData + ) let result = try await userPoolService.getUserAttributeVerificationCode(input: input) guard let deliveryDetails = result.codeDeliveryDetails?.toAuthCodeDeliveryDetails() else { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift index b6f318ddfd..eb4fbf7a23 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthUpdateUserAttributeTask: AuthUpdateUserAttributeTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -48,7 +48,8 @@ class AWSAuthUpdateUserAttributeTask: AuthUpdateUserAttributeTask, DefaultLogger attributes: [request.userAttribute], accessToken: accessToken, userPoolFactory: userPoolFactory, - clientMetaData: clientMetaData) + clientMetaData: clientMetaData + ) guard let attributeResult = finalResult[request.userAttribute.key] else { let authError = AuthError.unknown("Attribute to be updated does not exist in the result", nil) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift index 187791614a..481567447b 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import Foundation class AWSAuthUpdateUserAttributesTask: AuthUpdateUserAttributesTask, DefaultLogger { typealias CognitoUserPoolFactory = () throws -> CognitoUserPoolBehavior @@ -47,7 +47,8 @@ class AWSAuthUpdateUserAttributesTask: AuthUpdateUserAttributesTask, DefaultLogg attributes: request.userAttributes, accessToken: accessToken, userPoolFactory: userPoolFactory, - clientMetaData: clientMetaData) + clientMetaData: clientMetaData + ) return finalResult } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift index f5cf58d112..395a496ced 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSCognitoIdentityProvider +import Foundation class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { @@ -24,9 +24,11 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { HubPayload.EventName.Auth.verifyTOTPSetupAPI } - init(_ request: VerifyTOTPSetupRequest, - authStateMachine: AuthStateMachine, - userPoolFactory: @escaping CognitoUserPoolFactory) { + init( + _ request: VerifyTOTPSetupRequest, + authStateMachine: AuthStateMachine, + userPoolFactory: @escaping CognitoUserPoolFactory + ) { self.request = request self.authStateMachine = authStateMachine self.userPoolFactory = userPoolFactory @@ -38,7 +40,8 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { await taskHelper.didStateMachineConfigured() let accessToken = try await taskHelper.getAccessToken() try await verifyTOTPSetup( - with: accessToken, userCode: request.code) + with: accessToken, userCode: request.code + ) } catch let error as AuthErrorConvertible { throw error.authError } catch { @@ -52,7 +55,8 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { let input = VerifySoftwareTokenInput( accessToken: accessToken, friendlyDeviceName: friendlyDeviceName, - userCode: userCode) + userCode: userCode + ) let result = try await userPoolService.verifySoftwareToken(input: input) guard let output = result.status else { @@ -61,14 +65,17 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { switch output { case .error: - throw AuthError.service("Unknown service error occurred", - AmplifyErrorMessages.reportBugToAWS()) + throw AuthError.service( + "Unknown service error occurred", + AmplifyErrorMessages.reportBugToAWS() + ) case .success: return case .sdkUnknown(let error): throw AuthError.service( error, - AmplifyErrorMessages.reportBugToAWS()) + AmplifyErrorMessages.reportBugToAWS() + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift index f28509ce8e..c9c14d017f 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Bytes.swift @@ -15,7 +15,7 @@ public extension AmplifyBigInt { } var byteArray: [UInt8] { - let bytesCount = self.bytesCount + let bytesCount = bytesCount var buffer = [UInt8](repeating: 0, count: bytesCount) var written = size_t() let error = amplify_mp_to_sbin(&value, &buffer, bytesCount, &written) diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift index d53b1884b4..1a0dca0fb0 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Comparable.swift @@ -11,23 +11,23 @@ import libtommathAmplify extension AmplifyBigInt: Equatable, Comparable { public static func == (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) == .orderedSame) + return lhs.compare(rhs) == .orderedSame } public static func <= (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) != .orderedAscending) + return lhs.compare(rhs) != .orderedAscending } public static func >= (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) != .orderedDescending) + return lhs.compare(rhs) != .orderedDescending } public static func > (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) == .orderedAscending) + return lhs.compare(rhs) == .orderedAscending } public static func < (lhs: AmplifyBigInt, rhs: AmplifyBigInt) -> Bool { - return (lhs.compare(rhs) == .orderedDescending) + return lhs.compare(rhs) == .orderedDescending } func compare(_ againstValue: AmplifyBigInt) -> ComparisonResult { diff --git a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift index 5995ac75c8..dbdaa63dba 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifyBigInteger/AmplifyBigInt+Operations.swift @@ -118,8 +118,10 @@ public extension AmplifyBigInt { // MARK: - Exponentional - func pow(_ power: AmplifyBigInt, - modulus: AmplifyBigInt) -> AmplifyBigInt { + func pow( + _ power: AmplifyBigInt, + modulus: AmplifyBigInt + ) -> AmplifyBigInt { let exponentialModulus = AmplifyBigInt() let result = amplify_mp_exptmod(&value, &power.value, &modulus.value, &exponentialModulus.value) guard result == AMPLIFY_MP_OKAY else { diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift index 26aebf4545..905c2fb8d3 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift @@ -5,23 +5,27 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import CommonCrypto import CryptoKit +import Foundation // swiftlint:disable identifier_name // https://tools.ietf.org/html/rfc5869 public enum HMACKeyDerivationFunction { - public static func generateDerivedKey(keyingMaterial: Data, - salt: Data, - info: String?, - outputLength: Int) -> Data { + public static func generateDerivedKey( + keyingMaterial: Data, + salt: Data, + info: String?, + outputLength: Int + ) -> Data { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { - return generateHKDF(keyingMaterial: keyingMaterial, - salt: salt, - info: info, - outputLength: outputLength) + return generateHKDF( + keyingMaterial: keyingMaterial, + salt: salt, + info: info, + outputLength: outputLength + ) } else { let pseudoRandomKey = extractPseudoRandomKey(salt: salt, inputKeyMaterial: keyingMaterial) return expand(pseudoRandomKey: pseudoRandomKey, info: info.map { Data($0.utf8) }, outputLength: outputLength) @@ -38,13 +42,18 @@ public enum HMACKeyDerivationFunction { let key = SymmetricKey(data: keyingMaterial) var hkdf: SymmetricKey if let info { - hkdf = HKDF.deriveKey(inputKeyMaterial: key, - salt: salt, info: Data(info.utf8), - outputByteCount: outputLength) + hkdf = HKDF.deriveKey( + inputKeyMaterial: key, + salt: salt, + info: Data(info.utf8), + outputByteCount: outputLength + ) } else { - hkdf = HKDF.deriveKey(inputKeyMaterial: key, - salt: salt, - outputByteCount: outputLength) + hkdf = HKDF.deriveKey( + inputKeyMaterial: key, + salt: salt, + outputByteCount: outputLength + ) } return hkdf.withUnsafeBytes { buffPointer in return Data(Array(buffPointer)) @@ -63,10 +72,12 @@ public enum HMACKeyDerivationFunction { var outputKeyMaterial = Data() var previousT = Data() for index in 1 ... n { - let t = calculateT(pseudoRandomKey: pseudoRandomKey, - previousT: previousT, - info: info, - i: UInt8(index)) + let t = calculateT( + pseudoRandomKey: pseudoRandomKey, + previousT: previousT, + info: info, + i: UInt8(index) + ) outputKeyMaterial.append(t) previousT = t } diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift index 2bc92a7583..33a3ed5d10 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPClientState.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import CryptoKit import AmplifyBigInteger +import CryptoKit +import Foundation public typealias BigInt = AmplifyBigInt @@ -19,9 +19,11 @@ public struct SRPClientState { public init(commonState: SRPCommonState) { self.privateA = SRPClientState.calculatePrivateA(prime: commonState.prime) - self.publicA = SRPClientState.calculatePublicA(privateA: privateA, - generator: commonState.generator, - prime: commonState.prime) + self.publicA = SRPClientState.calculatePublicA( + privateA: privateA, + generator: commonState.generator, + prime: commonState.prime + ) } private static func calculatePrivateA(prime N: BigInt) -> BigInt { @@ -29,13 +31,15 @@ public struct SRPClientState { var randomInt: BigInt repeat { randomInt = generateRandomUnsigned(of: byteSize) - } while (randomInt >= N) + } while randomInt >= N return randomInt } - private static func calculatePublicA(privateA: BigInt, - generator: BigInt, - prime: BigInt) -> BigInt { + private static func calculatePublicA( + privateA: BigInt, + generator: BigInt, + prime: BigInt + ) -> BigInt { return generator.pow(privateA, modulus: prime) } @@ -56,13 +60,15 @@ public struct SRPClientState { return BigInt(unsignedData: hashBytes) } - public static func calculateSessionKey(username: String, - password: String, - publicClientKey: BigInt, - privateClientKey: BigInt, - publicServerKey: BigInt, - salt: BigInt, - commonState: SRPCommonState) -> BigInt { + public static func calculateSessionKey( + username: String, + password: String, + publicClientKey: BigInt, + privateClientKey: BigInt, + publicServerKey: BigInt, + salt: BigInt, + commonState: SRPCommonState + ) -> BigInt { // Calculations are detailed in RFC - https://datatracker.ietf.org/doc/html/rfc2945 // Calculate x = SHA( | SHA( | ":" | )) @@ -88,7 +94,8 @@ public struct SRPClientState { deviceGroupKey: String, deviceKey: String, password: String, - commonState: SRPCommonState) -> (salt: BigInt, passwordVerifier: BigInt) { + commonState: SRPCommonState + ) -> (salt: BigInt, passwordVerifier: BigInt) { // Salt (16 random bytes) let salt = generateRandomUnsigned(of: 16) diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift index 524e96106a..1430cab4f6 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPCommonState.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -import CryptoKit import AmplifyBigInteger +import CryptoKit +import Foundation // swiftlint:disable identifier_name public struct SRPCommonState { diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift index 15ec075974..e99530be9e 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/SRPServerResponse.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AmplifyBigInteger +import Foundation struct SRPServerResponse { let publicKey: BigInt diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift index 8f3f2a6899..9720713aa6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/ClearCredentialsTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSPluginsCore import Amplify +import AWSPluginsCore +import XCTest @testable import AWSCognitoAuthPlugin class ClearCredentialsTests: XCTestCase { @@ -35,20 +35,27 @@ class ClearCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = ClearCredentialStore(dataStoreType: .amplifyCredentials) - await action.execute(withDispatcher: MockDispatcher { _ in }, - environment: environment) + await action.execute( + withDispatcher: MockDispatcher { _ in }, + environment: environment + ) await fulfillment( of: [expectation], @@ -116,16 +123,21 @@ class ClearCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = ClearCredentialStore(dataStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in @@ -174,16 +186,21 @@ class ClearCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = ClearCredentialStore(dataStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift index 2375daf8a6..9c783bdd41 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/LoadCredentialsTests.swift @@ -7,9 +7,9 @@ import XCTest -@testable import AWSCognitoAuthPlugin -import AWSPluginsCore import Amplify +import AWSPluginsCore +@testable import AWSCognitoAuthPlugin class LoadCredentialsTests: XCTestCase { @@ -37,16 +37,21 @@ class LoadCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = LoadCredentialStore(credentialStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in @@ -133,16 +138,21 @@ class LoadCredentialsTests: XCTestCase { let amplifyCredentialStoreFactory: BasicCredentialStoreEnvironment.AmplifyAuthCredentialStoreFactory = { return mockAmplifyCredentialStoreBehavior } - let authConfig = AuthConfiguration.userPoolsAndIdentityPools(Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + let authConfig = AuthConfiguration.userPoolsAndIdentityPools( + Defaults.makeDefaultUserPoolConfigData(), + Defaults.makeIdentityConfigData() + ) - let credentialStoreEnv = BasicCredentialStoreEnvironment(amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + let credentialStoreEnv = BasicCredentialStoreEnvironment( + amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = LoadCredentialStore(credentialStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in @@ -193,16 +203,19 @@ class LoadCredentialsTests: XCTestCase { } let authConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStoreEnv = BasicCredentialStoreEnvironment( amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = LoadCredentialStore(credentialStoreType: .amplifyCredentials) await action.execute(withDispatcher: MockDispatcher { event in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift index 1252888632..20538cf4a9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MigrateLegacyCredentialStoreTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSCognitoAuthPlugin class MigrateLegacyCredentialStoreTests: XCTestCase { @@ -31,9 +31,10 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { saveCredentialHandler: { codableCredentials in guard let credentials = codableCredentials as? AmplifyCredentials, case .userPoolAndIdentityPool( - signedInData: let signedInData, - identityID: let identityID, - credentials: let awsCredentials) = credentials else { + signedInData: let signedInData, + identityID: let identityID, + credentials: let awsCredentials + ) = credentials else { XCTFail("The credentials saved should be of type AmplifyCredentials") return } @@ -58,16 +59,19 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { } let authConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStoreEnv = BasicCredentialStoreEnvironment( amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = MigrateLegacyCredentialStore() await action.execute(withDispatcher: MockDispatcher { _ in }, environment: environment) @@ -105,23 +109,26 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { } let authConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStoreEnv = BasicCredentialStoreEnvironment( amplifyCredentialStoreFactory: amplifyCredentialStoreFactory, - legacyKeychainStoreFactory: legacyKeychainStoreFactory) + legacyKeychainStoreFactory: legacyKeychainStoreFactory + ) let environment = CredentialEnvironment( authConfiguration: authConfig, credentialStoreEnvironment: credentialStoreEnv, - logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest")) + logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") + ) let action = MigrateLegacyCredentialStore() await action.execute(withDispatcher: MockDispatcher { _ in }, environment: environment) await fulfillment( of: [migrationCompletionInvoked], - + timeout: 0.1 ) } @@ -147,10 +154,10 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { ) await fulfillment(of: [expectation], timeout: 1) } - + /// - Given: A credential store with an environment that only has identity pool /// - When: The migration legacy store action is executed - /// - Then: + /// - Then: /// - A .loadCredentialStore event with type .amplifyCredentials is dispatched /// - An .identityPoolOnly credential is saved func testExecute_withoutUserPool_andWithoutLoginsTokens_shouldDispatchLoadEvent() async { @@ -184,13 +191,14 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { }, legacyKeychainStoreFactory: { _ in MockKeychainStoreBehavior(data: "hostedUI") - }), + } + ), logger: MigrateLegacyCredentialStore.log ) ) await fulfillment(of: [expectation], timeout: 1) } - + /// - Given: A credential store with an environment that only has identity pool /// - When: The migration legacy store action is executed /// - A .loadCredentialStore event with type .amplifyCredentials is dispatched @@ -233,7 +241,8 @@ class MigrateLegacyCredentialStoreTests: XCTestCase { return MockKeychainStoreBehavior( data: String(decoding: data, as: UTF8.self) ) - }), + } + ), logger: action.log ) ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift index 06e5fe9f25..9b11427816 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockAmplifyCredentialStoreBehavior.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSPluginsCore +@testable import AWSCognitoAuthPlugin class MockAmplifyCredentialStoreBehavior: AmplifyAuthCredentialStoreBehavior { @@ -22,10 +22,12 @@ class MockAmplifyCredentialStoreBehavior: AmplifyAuthCredentialStoreBehavior { let getCredentialHandler: GetCredentialHandler? let clearCredentialHandler: ClearCredentialHandler? - init(migrationCompleteHandler: Migrationhandler? = nil, - saveCredentialHandler: SaveCredentialHandler? = nil, - getCredentialHandler: GetCredentialHandler? = nil, - clearCredentialHandler: ClearCredentialHandler? = nil) { + init( + migrationCompleteHandler: Migrationhandler? = nil, + saveCredentialHandler: SaveCredentialHandler? = nil, + getCredentialHandler: GetCredentialHandler? = nil, + clearCredentialHandler: ClearCredentialHandler? = nil + ) { self.migrationCompleteHandler = migrationCompleteHandler self.saveCredentialHandler = saveCredentialHandler self.getCredentialHandler = getCredentialHandler diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift index 97b9201818..a0ec266dfa 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSPluginsCore +@testable import AWSCognitoAuthPlugin class MockKeychainStoreBehavior: KeychainStoreBehavior { @@ -17,8 +17,10 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior { let data: String let removeAllHandler: VoidHandler? - init(data: String, - removeAllHandler: VoidHandler? = nil) { + init( + data: String, + removeAllHandler: VoidHandler? = nil + ) { self.data = data self.removeAllHandler = removeAllHandler } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift index bb05912e17..b16f91ea2b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchAWSCredentials/FetchAuthAWSCredentialsTests.swift @@ -7,8 +7,8 @@ import XCTest -import AWSCognitoIdentity import Amplify +import AWSCognitoIdentity @testable import AWSCognitoAuthPlugin @@ -47,7 +47,8 @@ class FetchAuthAWSCredentialsTests: XCTestCase { } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) @@ -80,7 +81,8 @@ class FetchAuthAWSCredentialsTests: XCTestCase { } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) @@ -122,13 +124,16 @@ class FetchAuthAWSCredentialsTests: XCTestCase { accessKeyId: expectedAccessKey, expiration: Date(), secretKey: expectedSecretKey, - sessionToken: expectedSessionToken), - identityId: expectedIdentityId) + sessionToken: expectedSessionToken + ), + identityId: expectedIdentityId + ) }) } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) @@ -162,7 +167,8 @@ class FetchAuthAWSCredentialsTests: XCTestCase { } let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: IdentityPoolConfigurationData.testData, - cognitoIdentityFactory: identityProviderFactory) + cognitoIdentityFactory: identityProviderFactory + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( authZEnvironment: authorizationEnvironment) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift index 1dbc164dff..668fe71bd0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/FetchUserPoolTokens/RefreshUserPoolTokensTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify -import AWSPluginsCore import AWSCognitoIdentityProvider +import AWSPluginsCore +import XCTest @testable import AWSCognitoAuthPlugin @@ -20,7 +20,8 @@ class RefreshUserPoolTokensTests: XCTestCase { let action = RefreshUserPoolTokens(existingSignedIndata: .testData) - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in guard let event = event as? RefreshSessionEvent else { return @@ -31,7 +32,8 @@ class RefreshUserPoolTokensTests: XCTestCase { XCTAssertEqual(error, .noUserPool) expectation.fulfill() } - }, environment: MockInvalidEnvironment() + }, + environment: MockInvalidEnvironment() ) await fulfillment( @@ -53,7 +55,8 @@ class RefreshUserPoolTokensTests: XCTestCase { let action = RefreshUserPoolTokens(existingSignedIndata: .testData) - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in guard let event = event as? RefreshSessionEvent else { return } @@ -62,7 +65,8 @@ class RefreshUserPoolTokensTests: XCTestCase { XCTAssertEqual(error, .invalidTokens) expectation.fulfill() } - }, environment: Defaults.makeDefaultAuthEnvironment( + }, + environment: Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) ) @@ -83,20 +87,23 @@ class RefreshUserPoolTokensTests: XCTestCase { accessToken: "accessTokenNew", expiresIn: 100, idToken: "idTokenNew", - refreshToken: "refreshTokenNew")) + refreshToken: "refreshTokenNew" + )) } ) } let action = RefreshUserPoolTokens(existingSignedIndata: .testData) - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in if let userPoolEvent = event as? RefreshSessionEvent, case .refreshIdentityInfo = userPoolEvent.eventType { expectation.fulfill() } - }, environment: Defaults.makeDefaultAuthEnvironment( + }, + environment: Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) ) @@ -124,7 +131,8 @@ class RefreshUserPoolTokensTests: XCTestCase { userPoolConfiguration: UserPoolConfigurationData.testData, cognitoUserPoolFactory: identityProviderFactory, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let action = RefreshUserPoolTokens(existingSignedIndata: .testData) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift index 4976285b0e..6799a9032b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/FetchAuthSession/InitializeFetchAuthSessionTests.swift @@ -17,7 +17,8 @@ class InitializeFetchAuthSessionTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment() - await action.execute(withDispatcher: MockDispatcher { event in + await action.execute( + withDispatcher: MockDispatcher { event in guard let event = event as? FetchAuthSessionEvent else { XCTFail("Expected event to be FetchAuthSessionEvent") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift index c3ef575d95..e536300655 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/InitiateAuthSRPTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest @testable import AWSCognitoAuthPlugin diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift index d33a7f05c0..1ad44ac2b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider -@testable import AWSPluginsTestCommon import XCTest +@testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class VerifyDevicePasswordSRPSignatureTests: XCTestCase { private var srpClient: MockSRPClientBehavior! - + override func setUp() async throws { MockSRPClientBehavior.reset() srpClient = MockSRPClientBehavior() } - + override func tearDown() { MockSRPClientBehavior.reset() srpClient = nil @@ -34,7 +34,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTFail("Should not throw error: \(error)") } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws an SRPError error when generating a shared secret /// Then: a .calculation error is thrown @@ -52,7 +52,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(srpError, .numberConversion) } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws a non-SRPError error when generating a shared secret /// Then: a .configuration error is thrown @@ -70,7 +70,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(message, "Could not calculate shared secret") } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws a SRPError error when generating an authentication key /// Then: a .calculation error is thrown @@ -88,7 +88,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(srpError, .numberConversion) } } - + /// Given: A VerifyDevicePasswordSRP /// When: signature is invoked and the srpClient throws a non-SRPError error when generating an authentication key /// Then: a .configuration error is thrown @@ -106,7 +106,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { XCTAssertEqual(message, "Could not calculate signature") } } - + @discardableResult private func signature() throws -> String { let action = VerifyDevicePasswordSRP( @@ -128,7 +128,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { private class MockSRPClientBehavior: SRPClientBehavior { var kHexValue: String = "kHexValue" - + static func calculateUHexValue( clientPublicKeyHexValue: String, serverPublicKeyHexValue: String @@ -143,18 +143,18 @@ private class MockSRPClientBehavior: SRPClientBehavior { ) throws -> Data { return try authenticationKey.get() } - + static func reset() { authenticationKey = .success(Data("AuthenticationKey".utf8)) } - + func generateClientKeyPair() -> SRPKeys { return .init( publicKeyHexValue: "publicKeyHexValue", privateKeyHexValue: "privateKeyHexValue" ) } - + var sharedSecret: Result = .success("SharedSecret") func calculateSharedSecret( username: String, @@ -166,7 +166,7 @@ private class MockSRPClientBehavior: SRPClientBehavior { ) throws -> String { return try sharedSecret.get() } - + func generateDevicePasswordVerifier( deviceGroupKey: String, deviceKey: String, diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift index 7628638339..4ffb5777f1 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSCognitoIdentityProvider import AWSClientRuntime -@testable import AWSPluginsTestCommon +import AWSCognitoIdentityProvider +import XCTest @testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class VerifyPasswordSRPTests: XCTestCase { @@ -39,9 +39,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) await action.execute( withDispatcher: MockDispatcher { _ in }, @@ -75,9 +77,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation(description: "passwordVerifierError") @@ -126,9 +130,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidChallenge - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -177,9 +183,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataWithNoSalt - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -228,9 +236,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataWithNoSecretBlock - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -279,9 +289,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataWithNoSRPB - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -330,9 +342,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.invalidTestDataForException - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -380,9 +394,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierCompletion = expectation( description: "passwordVerifierCompletion" @@ -433,9 +449,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -484,9 +502,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierError = expectation(description: "passwordVerifierError") @@ -532,9 +552,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierCompletion = expectation( description: "passwordVerifierCompletion") @@ -578,9 +600,11 @@ class VerifyPasswordSRPTests: XCTestCase { userPoolFactory: identityProviderFactory) let data = InitiateAuthOutput.validTestData - let action = VerifyPasswordSRP(stateData: SRPStateData.testData, - authResponse: data, - clientMetadata: [:]) + let action = VerifyPasswordSRP( + stateData: SRPStateData.testData, + authResponse: data, + clientMetadata: [:] + ) let passwordVerifierCompletion = expectation( description: "passwordVerifierCompletion") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift index f69a2e7fec..d7fc8a2c69 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider -@testable import AWSPluginsTestCommon +import XCTest @testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class RevokeTokenTests: XCTestCase { @@ -29,9 +29,11 @@ class RevokeTokenTests: XCTestCase { cognitoUserPoolASFFactory: Defaults.makeDefaultASF, cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics ) - let action = RevokeToken(signedInData: .testData, - hostedUIError: nil, - globalSignOutError: nil) + let action = RevokeToken( + signedInData: .testData, + hostedUIError: nil, + globalSignOutError: nil + ) await action.execute( withDispatcher: MockDispatcher { _ in }, @@ -60,9 +62,11 @@ class RevokeTokenTests: XCTestCase { cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics ) - let action = RevokeToken(signedInData: .testData, - hostedUIError: nil, - globalSignOutError: nil) + let action = RevokeToken( + signedInData: .testData, + hostedUIError: nil, + globalSignOutError: nil + ) let clearCredentialStoreEventSent = expectation(description: "clearCredentialStoreEventSent") let dispatcher = MockDispatcher { event in @@ -104,9 +108,11 @@ class RevokeTokenTests: XCTestCase { cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics ) - let action = RevokeToken(signedInData: .testData, - hostedUIError: nil, - globalSignOutError: nil) + let action = RevokeToken( + signedInData: .testData, + hostedUIError: nil, + globalSignOutError: nil + ) let clearCredentialStoreEventSent = expectation(description: "clearCredentialStoreEventSent") let dispatcher = MockDispatcher { event in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift index af2129ad19..067d145579 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/ShowHostedUISignOutTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import AWSPluginsCore import XCTest +@testable import AWSCognitoAuthPlugin class ShowHostedUISignOutTests: XCTestCase { private var mockHostedUIResult: Result<[URLQueryItem], HostedUIError>! private var signOutRedirectURI: String! - + override func setUp() { signOutRedirectURI = "myapp://" mockHostedUIResult = .success([.init(name: "key", value: "value")]) } - + override func tearDown() { signOutRedirectURI = nil mockHostedUIResult = nil @@ -38,7 +38,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .signOutGlobally(let data, let error) = event.eventType else { + case .signOutGlobally(let data, let error) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return @@ -47,7 +48,7 @@ class ShowHostedUISignOutTests: XCTestCase { XCTAssertNil(error) XCTAssertEqual(data, signInData) self.validateDebugInformation(signInData: signInData, action: action) - + expectation.fulfill() }, environment: Defaults.makeDefaultAuthEnvironment( @@ -58,7 +59,7 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action with global sign out set to false /// When: execute is invoked with a success result /// Then: A .revokeToken event is dispatched @@ -73,7 +74,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .revokeToken(let data, let error, let globalSignOutError) = event.eventType else { + case .revokeToken(let data, let error, let globalSignOutError) = event.eventType + else { XCTFail("Expected SignOutEvent.revokeToken, got \(event)") expectation.fulfill() return @@ -92,14 +94,14 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action /// When: execute is invoked but fails to create a HostedUI session /// Then: A .userCancelled event is dispatched func testExecute_withInvalidResult_shouldDispatchUserCancelledEvent() async { mockHostedUIResult = .failure(.cancelled) let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -132,7 +134,7 @@ class ShowHostedUISignOutTests: XCTestCase { func testExecute_withSignOutURIError_shouldThrowConfigurationError() async { mockHostedUIResult = .failure(HostedUIError.signOutURI) let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -142,7 +144,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return @@ -166,14 +169,14 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action /// When: execute is invoked but fails to create a HostedUI session with a HostedUIError.invalidContext /// Then: A .signOutGlobally event is dispatched with a HosterUIError.invalidState error func testExecute_withInvalidContext_shouldThrowInvalidStateError() async { mockHostedUIResult = .failure(HostedUIError.invalidContext) let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -183,7 +186,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.hostedUISignOutError, got \(event)") expectation.fulfill() return @@ -208,14 +212,14 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action with an invalid SignOutRedirectURI /// When: execute is invoked /// Then: A .signOutGlobally event is dispatched with a HosterUIError.configuration error func testExecute_withInvalidSignOutURI_shouldThrowConfigurationError() async { signOutRedirectURI = "invalidURI" let signInData = SignedInData.testData - + let action = ShowHostedUISignOut( signOutEvent: .testData, signInData: signInData @@ -225,7 +229,8 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return @@ -263,12 +268,13 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return } - + guard case .configuration(let errorDescription, _, let serviceError) = hostedUIError.authError else { XCTFail("Expected AuthError.configuration") expectation.fulfill() @@ -287,7 +293,7 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + /// Given: A ShowHostedUISignOut action /// When: execute is invoked with an invalid environment /// Then: A .signOutGlobally event is dispatched with a HosterUIError.configuration error @@ -301,12 +307,13 @@ class ShowHostedUISignOutTests: XCTestCase { await action.execute( withDispatcher: MockDispatcher { event in guard let event = event as? SignOutEvent, - case .hostedUISignOutError(let hostedUIError) = event.eventType else { + case .hostedUISignOutError(let hostedUIError) = event.eventType + else { XCTFail("Expected SignOutEvent.signOutGlobally, got \(event)") expectation.fulfill() return } - + guard case .configuration(let errorDescription, _, let serviceError) = hostedUIError.authError else { XCTFail("Expected AuthError.configuration") expectation.fulfill() @@ -322,7 +329,7 @@ class ShowHostedUISignOutTests: XCTestCase { await fulfillment(of: [expectation], timeout: 1) } - + private func validateDebugInformation(signInData: SignedInData, action: ShowHostedUISignOut) { XCTAssertFalse(action.debugDescription.isEmpty) guard let signInDataDictionary = action.debugDictionary["signInData"] as? [String: Any] else { @@ -333,13 +340,14 @@ class ShowHostedUISignOutTests: XCTestCase { for key in signInDataDictionary.keys { guard let left = signInDataDictionary[key] as? any Equatable, - let right = signInData.debugDictionary[key] as? any Equatable else { + let right = signInData.debugDictionary[key] as? any Equatable + else { continue } XCTAssertTrue(left.isEqual(to: right)) } } - + private var hostedUIEnvironment: HostedUIEnvironment { BasicHostedUIEnvironment( configuration: .init( @@ -365,7 +373,7 @@ class ShowHostedUISignOutTests: XCTestCase { } ) } - + private func identityProviderFactory() throws -> CognitoUserPoolBehavior { return MockIdentityProvider( mockInitiateAuthResponse: { _ in @@ -374,7 +382,8 @@ class ShowHostedUISignOutTests: XCTestCase { accessToken: "accessTokenNew", expiresIn: 100, idToken: "idTokenNew", - refreshToken: "refreshTokenNew") + refreshToken: "refreshTokenNew" + ) ) } ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift index 44f7f866d0..df80746768 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift index 9937d86b74..62cc76e694 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift @@ -5,25 +5,28 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import AWSCognitoIdentityProvider import AWSClientRuntime -@testable import AWSPluginsTestCommon +import AWSCognitoIdentityProvider +import XCTest @testable import AWSCognitoAuthPlugin +@testable import AWSPluginsTestCommon class VerifySignInChallengeTests: XCTestCase { typealias CognitoFactory = BasicSRPAuthEnvironment.CognitoUserPoolFactory - let mockRespondAuthChallenge = RespondToAuthChallenge(challenge: .smsMfa, - username: "usernameMock", - session: "mockSession", - parameters: [:]) + let mockRespondAuthChallenge = RespondToAuthChallenge( + challenge: .smsMfa, + username: "usernameMock", + session: "mockSession", + parameters: [:] + ) let mockConfirmEvent = ConfirmSignInEventData( answer: "1233", attributes: [:], metadata: [:], - friendlyDeviceName: nil) + friendlyDeviceName: nil + ) /// Test if valid input are given the service call is made /// @@ -47,9 +50,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) await action.execute( withDispatcher: MockDispatcher { _ in }, @@ -82,9 +87,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let passwordVerifierError = expectation(description: "passwordVerifierError") @@ -131,9 +138,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let verifyChallengeComplete = expectation(description: "verifyChallengeComplete") @@ -181,9 +190,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let passwordVerifierError = expectation( description: "passwordVerifierError") @@ -231,9 +242,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let passwordVerifierError = expectation(description: "passwordVerifierError") let dispatcher = MockDispatcher { event in @@ -277,9 +290,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let verifyChallengeComplete = expectation(description: "verifyChallengeComplete") @@ -321,9 +336,11 @@ class VerifySignInChallengeTests: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: identityProviderFactory) - let action = VerifySignInChallenge(challenge: mockRespondAuthChallenge, - confirmSignEventData: mockConfirmEvent, - signInMethod: .apiBased(.userSRP)) + let action = VerifySignInChallenge( + challenge: mockRespondAuthChallenge, + confirmSignEventData: mockConfirmEvent, + signInMethod: .apiBased(.userSRP) + ) let verifyChallengeComplete = expectation(description: "verifyChallengeComplete") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift index 4b18e2071d..9ac9488fc6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ClientBehaviorTests/AuthGetCurrentUserTests.swift @@ -33,8 +33,7 @@ class AuthGetCurrentUserTests: XCTestCase { do { _ = try await plugin.getCurrentUser() XCTFail("Should throw AuthError.signedOut") - } - catch AuthError.signedOut { } + } catch AuthError.signedOut { } catch { XCTFail("Should throw AuthError.signedOut") } @@ -49,8 +48,7 @@ class AuthGetCurrentUserTests: XCTestCase { do { _ = try await plugin.getCurrentUser() XCTFail("Should throw AuthError.configuration") - } - catch AuthError.configuration { } + } catch AuthError.configuration { } catch { XCTFail("Should throw AuthError.configuration") } @@ -65,8 +63,7 @@ class AuthGetCurrentUserTests: XCTestCase { do { _ = try await plugin.getCurrentUser() XCTFail("Should throw AuthError.invalidState") - } - catch AuthError.invalidState { } + } catch AuthError.invalidState { } catch { XCTFail("Should throw AuthError.invalidState") } @@ -75,9 +72,11 @@ class AuthGetCurrentUserTests: XCTestCase { - private func createPlugin(authState: AuthState, - file: StaticString = #filePath, - line: UInt = #line) throws -> AWSCognitoAuthPlugin { + private func createPlugin( + authState: AuthState, + file: StaticString = #filePath, + line: UInt = #line + ) throws -> AWSCognitoAuthPlugin { let plugin = AWSCognitoAuthPlugin() plugin.authStateMachine = Defaults.makeDefaultAuthStateMachine(initialState: authState) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift index 395ab17f39..81512fc99e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/ASFCognitoTests.swift @@ -12,13 +12,13 @@ class ASFCognitoTests: XCTestCase { func testTimeZoneOffetNegative() { let asf = CognitoUserPoolASF() - let timezoneOffet = asf.timeZoneOffet(seconds: -25200) + let timezoneOffet = asf.timeZoneOffet(seconds: -25_200) XCTAssertEqual("-07:00", timezoneOffet) } func testTimeZoneOffetPositive() { let asf = CognitoUserPoolASF() - let timezoneOffet = asf.timeZoneOffet(seconds: 25200) + let timezoneOffet = asf.timeZoneOffet(seconds: 25_200) XCTAssertEqual("+07:00", timezoneOffet) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift index b5dbf122cf..382e13c3e0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CognitoASFTests/CognitoUserPoolASFTests.swift @@ -5,20 +5,20 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import XCTest +@testable import AWSCognitoAuthPlugin class CognitoUserPoolASFTests: XCTestCase { private var userPool: CognitoUserPoolASF! - + override func setUp() { userPool = CognitoUserPoolASF() } - + override func tearDown() { userPool = nil } - + /// Given: A CognitoUserPoolASF /// When: userContextData is invoked /// Then: A non-empty string is returned @@ -32,7 +32,7 @@ class CognitoUserPoolASFTests: XCTestCase { ) XCTAssertFalse(result.isEmpty) } - + /// Given: A CognitoUserPoolASF /// When: calculateSecretHash is invoked /// Then: A non-empty string is returned @@ -43,7 +43,7 @@ class CognitoUserPoolASFTests: XCTestCase { ) XCTAssertFalse(result.isEmpty) } - + /// Given: A CognitoUserPoolASF /// When: calculateSecretHash is invoked with a clientId that cannot be parsed /// Then: A ASFError.hashKey is thrown diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift index 85eba053d7..29cb5086b8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginAmplifyOutputsConfigTests.swift @@ -52,10 +52,11 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase { try Amplify.add(plugin: plugin) let amplifyConfig = AmplifyOutputsData(auth: .init( - awsRegion: "us-east-1", - userPoolId: "xx", - userPoolClientId: "xx", - identityPoolId: "xx")) + awsRegion: "us-east-1", + userPoolId: "xx", + userPoolClientId: "xx", + identityPoolId: "xx" + )) do { try Amplify.configure(amplifyConfig) } catch { @@ -76,9 +77,10 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase { try Amplify.add(plugin: plugin) let amplifyConfig = AmplifyOutputsData(auth: .init( - awsRegion: "us-east-1", - userPoolId: "xx", - userPoolClientId: "xx")) + awsRegion: "us-east-1", + userPoolId: "xx", + userPoolClientId: "xx" + )) do { try Amplify.configure(amplifyConfig) } catch { @@ -99,14 +101,16 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase { networkPreferences: .init( maxRetryCount: 2, timeoutIntervalForRequest: 60, - timeoutIntervalForResource: 60)) + timeoutIntervalForResource: 60 + )) try Amplify.add(plugin: plugin) let amplifyConfig = AmplifyOutputsData(auth: .init( - awsRegion: "us-east-1", - userPoolId: "xx", - userPoolClientId: "xx", - identityPoolId: "xx")) + awsRegion: "us-east-1", + userPoolId: "xx", + userPoolClientId: "xx", + identityPoolId: "xx" + )) do { try Amplify.configure(amplifyConfig) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift index 8ba574028e..4b8824ec98 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/AWSCognitoAuthPluginConfigTests.swift @@ -56,8 +56,10 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["PoolId": "xx", - "Region": "us-east-1"] + [ + "PoolId": "xx", + "Region": "us-east-1" + ] ]], "CognitoUserPool": ["Default": [ "PoolId": "xx", @@ -89,8 +91,10 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["PoolId": "cc", - "Region": "us-east-1"] + [ + "PoolId": "cc", + "Region": "us-east-1" + ] ]] ] ]) @@ -146,8 +150,10 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["xx": "xx", - "xx2": "us-east-1"] + [ + "xx": "xx", + "xx2": "us-east-1" + ] ]], "CognitoUserPool": ["Default": [ "xx": "xx", @@ -203,14 +209,17 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { networkPreferences: .init( maxRetryCount: 2, timeoutIntervalForRequest: 60, - timeoutIntervalForResource: 60)) + timeoutIntervalForResource: 60 + )) try Amplify.add(plugin: plugin) let categoryConfig = AuthCategoryConfiguration(plugins: [ "awsCognitoAuthPlugin": [ "CredentialsProvider": ["CognitoIdentity": ["Default": - ["PoolId": "xx", - "Region": "us-east-1"] + [ + "PoolId": "xx", + "Region": "us-east-1" + ] ]], "CognitoUserPool": ["Default": [ "PoolId": "xx", @@ -222,7 +231,7 @@ class AWSCognitoAuthPluginConfigTests: XCTestCase { let amplifyConfig = AmplifyConfiguration(auth: categoryConfig) do { try Amplify.configure(amplifyConfig) - + let escapeHatch = plugin.getEscapeHatch() guard case .userPoolAndIdentityPool(let userPoolClient, let identityPoolClient) = escapeHatch else { XCTFail("Expected .userPool, got \(escapeHatch)") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift index 1a3cdea3c7..de85857960 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift @@ -7,27 +7,29 @@ import Foundation -import XCTest import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import AWSCognitoIdentityProvider class ClientSecretConfigurationTests: XCTestCase { let networkTimeout = TimeInterval(2) var mockIdentityProvider: CognitoUserPoolBehavior! var plugin: AWSCognitoAuthPlugin! - + var initialState: AuthState { AuthState.configured( AuthenticationState.signedIn( SignedInData( signedInDate: Date(), signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) } override func setUp() { @@ -38,25 +40,30 @@ class ClientSecretConfigurationTests: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -64,7 +71,8 @@ class ClientSecretConfigurationTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } @@ -156,23 +164,26 @@ class ClientSecretConfigurationTests: XCTestCase { /// func testClientSecretWithSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { request in XCTAssertNotNil(request.secretHash) return .init( codeDeliveryDetails: .init( attributeName: "some attribute", deliveryMedium: .email, - destination: "random@random.com"), + destination: "random@random.com" + ), userConfirmed: false, - userSub: "userId") + userSub: "userId" + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: nil) + options: nil + ) guard case .confirmUser = result.nextStep else { XCTFail("Result should be .confirmUser for next step") @@ -190,14 +201,14 @@ class ClientSecretConfigurationTests: XCTestCase { /// func testClientSecretWithConfirmSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { request in XCTAssertNotNil(request.secretHash) return .init() } ) - _ = try await self.plugin.confirmSignUp( + _ = try await plugin.confirmSignUp( for: "someuser", confirmationCode: "code", options: nil @@ -213,15 +224,17 @@ class ClientSecretConfigurationTests: XCTestCase { /// - Plugin should pass the secret hash created with client secret /// func testClientSecretWithRevokeToken() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { request in XCTAssertNotNil(request.clientSecret) return .testData }, mockGlobalSignOutResponse: { _ in return .testData - }) + } + ) guard let result = await plugin.signOut() as? AWSCognitoSignOutResult, - case .complete = result else { + case .complete = result + else { XCTFail("Did not return complete signOut") return } @@ -237,7 +250,7 @@ class ClientSecretConfigurationTests: XCTestCase { /// func testClientSecretWithInitiateAuth() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { request in XCTAssertNotNil(request.clientSecret) return .testData @@ -247,7 +260,8 @@ class ClientSecretConfigurationTests: XCTestCase { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockGlobalSignOutResponse: { _ in return .testData @@ -261,23 +275,29 @@ class ClientSecretConfigurationTests: XCTestCase { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") - }) + session: "session" + ) + } + ) _ = await plugin.signOut() - - let pluginOptions = AWSAuthSignInOptions(validationData: ["somekey": "somevalue"], - metadata: ["somekey": "somevalue"]) + + let pluginOptions = AWSAuthSignInOptions( + validationData: ["somekey": "somevalue"], + metadata: ["somekey": "somevalue"] + ) let options = AuthSignInRequest.Options(pluginOptions: pluginOptions) do { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") return diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift index acf3ec1c0d..6c8b53084d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/EscapeHatchTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import enum Amplify.JSONValue import XCTest @testable import func AmplifyTestCommon.XCTAssertThrowFatalError -import enum Amplify.JSONValue @testable import AWSCognitoAuthPlugin @@ -103,7 +103,7 @@ class EscapeHatchTests: XCTestCase { return } } - + /// Test escape hatch without a valid configuration /// /// - Given: A AWSCognitoAuthPlugin plugin without being configured diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift index a5587e1f95..b74336fbc2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/CredentialStore/CredentialStoreOperationClientTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import Foundation import XCTest -import Amplify @testable import AWSCognitoAuthPlugin class CredentialStoreOperationClientTests: XCTestCase { @@ -27,7 +27,8 @@ class CredentialStoreOperationClientTests: XCTestCase { let credentialStateMachine = CredentialStoreStateMachine( resolver: CredentialStoreState.Resolver(), environment: credentialEnvironment, - initialState: .idle) + initialState: .idle + ) credentialClient = CredentialStoreOperationClient( credentialStoreStateMachine: credentialStateMachine) @@ -50,7 +51,7 @@ class CredentialStoreOperationClientTests: XCTestCase { func testMultipleSuccess() async throws { await withThrowingTaskGroup(of: Void.self, body: { group in - for _ in 1...100 { + for _ in 1 ... 100 { group.addTask { let deviceId = "someDeviceID-\(UUID().uuidString)" let username = "someUsername-\(UUID().uuidString)" @@ -84,7 +85,7 @@ class CredentialStoreOperationClientTests: XCTestCase { func testMultipleFailuresDuringFetch() async throws { await withThrowingTaskGroup(of: Void.self, body: { group in - for _ in 1...100 { + for _ in 1 ... 100 { group.addTask { let deviceId = "someDeviceID-\(UUID().uuidString)" let username = "someUsername-\(UUID().uuidString)" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift index 496e7d2331..ed62514dfe 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift @@ -4,13 +4,14 @@ // // SPDX-License-Identifier: Apache-2.0 // + import Foundation +import AWSCognitoIdentity +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentity -import AWSCognitoIdentityProvider class AuthHubEventHandlerTests: XCTestCase { @@ -312,7 +313,8 @@ class AuthHubEventHandlerTests: XCTestCase { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -321,10 +323,12 @@ class AuthHubEventHandlerTests: XCTestCase { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let initialState = AuthState.configured(.signedOut(.init(lastKnownUserName: nil)), .configured) @@ -337,8 +341,10 @@ class AuthHubEventHandlerTests: XCTestCase { AuthenticationState.signingIn(.resolvingChallenge( .waitingForAnswer(.testData(), .apiBased(.userSRP)), .smsMfa, - .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) let mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in @@ -351,10 +357,13 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForDeleteUserEvent() { let initialState = AuthState.configured( AuthenticationState.signedIn( - SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) let mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in @@ -373,10 +382,13 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForSignOutEvent() { let initialState = AuthState.configured( AuthenticationState.signedIn( - SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) let mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in @@ -393,7 +405,8 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForFederationEvent() { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), - AuthorizationState.configured) + AuthorizationState.configured + ) let mockIdentityProvider = MockIdentityProvider() @@ -403,7 +416,8 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePluginForClearedFederationEvent() { let initialState = AuthState.configured( AuthenticationState.federatedToIdentityPool, - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) let mockIdentityProvider = MockIdentityProvider() @@ -414,7 +428,8 @@ class AuthHubEventHandlerTests: XCTestCase { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let mockIdentityProvider = MockIdentityProvider( mockInitiateAuthResponse: { _ in @@ -435,10 +450,12 @@ class AuthHubEventHandlerTests: XCTestCase { private func configurePlugin(initialState: AuthState, userPoolFactory: CognitoUserPoolBehavior) { plugin = AWSCognitoAuthPlugin() - let mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testData.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + let mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testData.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, + "expires_in": 10 + ] as [String: Any] let mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) let mockState = "someState" let mockProof = "someProof" @@ -463,37 +480,44 @@ class AuthHubEventHandlerTests: XCTestCase { return MockRandomStringGenerator(mockString: mockState, mockUUID: mockState) } - let hostedUIEnv = BasicHostedUIEnvironment(configuration: hostedUIconfig, - hostedUISessionFactory: sessionFactory, - urlSessionFactory: urlSessionMock, - randomStringFactory: mockRandomString) + let hostedUIEnv = BasicHostedUIEnvironment( + configuration: hostedUIconfig, + hostedUISessionFactory: sessionFactory, + urlSessionFactory: urlSessionMock, + randomStringFactory: mockRandomString + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, userPoolFactory: { userPoolFactory }, - hostedUIEnvironment: hostedUIEnv) + hostedUIEnvironment: hostedUIEnv + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, userPoolFactory: { userPoolFactory }, - hostedUIEnvironment: hostedUIEnv) + hostedUIEnvironment: hostedUIEnv + ) let authHandler = AuthHubEventHandler() @@ -503,7 +527,8 @@ class AuthHubEventHandlerTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: authHandler, - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } override func tearDown() async throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift index bf141098ef..36cd42f3c9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockAnalyticsHandler.swift @@ -6,8 +6,8 @@ // import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin struct MockAnalyticsHandler: UserPoolAnalyticsBehavior { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift index 3bdd67555c..6047c6af84 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/AWSCognitoUserPoolTokens+Mock.swift @@ -21,11 +21,13 @@ extension AWSCognitoUserPoolTokens { idToken: CognitoAuthTestHelper.buildToken(for: tokenData), accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), refreshToken: "refreshToken", - expiresIn: Int(Date(timeIntervalSinceNow: 121).timeIntervalSince1970)) + expiresIn: Int(Date(timeIntervalSinceNow: 121).timeIntervalSince1970) + ) } static let expiredTestData = AWSCognitoUserPoolTokens( - idToken: "XX", accessToken: "XX", refreshToken: "XX", expiresIn: -10000) + idToken: "XX", accessToken: "XX", refreshToken: "XX", expiresIn: -10_000 + ) static func testData(username: String, sub: String) -> AWSCognitoUserPoolTokens { let tokenData = [ @@ -38,7 +40,8 @@ extension AWSCognitoUserPoolTokens { idToken: CognitoAuthTestHelper.buildToken(for: tokenData), accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), refreshToken: "refreshToken", - expiresIn: 121) + expiresIn: 121 + ) } static var testDataWithoutExp: AWSCognitoUserPoolTokens { @@ -51,6 +54,7 @@ extension AWSCognitoUserPoolTokens { idToken: CognitoAuthTestHelper.buildToken(for: tokenDataWithoutExp), accessToken: CognitoAuthTestHelper.buildToken(for: tokenDataWithoutExp), refreshToken: "refreshToken", - expiresIn: nil) + expiresIn: nil + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift index 18affcafee..c4a6b2f4fd 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/GlobalSignOutOutputResponse+Mock.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension GlobalSignOutOutput { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift index 81b5296c34..e42ff8f5b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/RevokeTokenOutputResponse+Mock.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import AWSCognitoIdentityProvider +import Foundation extension RevokeTokenOutput { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift index e5520078d6..19d5c6d200 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Mocks/MockData/SignedInData+Mock.swift @@ -12,26 +12,33 @@ extension SignedInData { static var testData: SignedInData { let tokens = AWSCognitoUserPoolTokens.testData - return SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: tokens + ) } static var expiredTestData: SignedInData { let tokens = AWSCognitoUserPoolTokens.expiredTestData - return SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: tokens + ) } static var hostedUISignInData: SignedInData { let tokens = AWSCognitoUserPoolTokens.testData - return SignedInData(signedInDate: Date(), - signInMethod: .hostedUI(.init( - scopes: [], - providerInfo: .init(authProvider: .google, idpIdentifier: ""), - presentationAnchor: nil, - preferPrivateSession: false)), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .hostedUI(.init( + scopes: [], + providerInfo: .init(authProvider: .google, idpIdentifier: ""), + presentationAnchor: nil, + preferPrivateSession: false + )), + cognitoUserPoolTokens: tokens + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift index 21db49f383..f62c949b3d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateConfiguringTests.swift @@ -19,7 +19,8 @@ class AuthStateConfiguringTests: XCTestCase { let expected = AuthState.validatingCredentialsAndConfiguration let resolution = resolver.resolve( oldState: oldState, - byApplying: AuthEvent.validateCredentialAndConfiguration) + byApplying: AuthEvent.validateCredentialAndConfiguration + ) XCTAssertEqual(resolution.newState, expected) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift index ab3552121d..c3b7e6b485 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthState/AuthStateTestData.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider import Foundation @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider extension AuthEvent { @@ -22,26 +22,32 @@ extension AuthEvent { static let configureAuth = AuthEvent( id: "configureAuth", - eventType: .configureAuth(.testData)) + eventType: .configureAuth(.testData) + ) static let configureAuthentication = AuthEvent( id: "configureAuthentication", - eventType: .configureAuthentication(.testData, .testData)) + eventType: .configureAuthentication(.testData, .testData) + ) static let configureAuthorization = AuthEvent( id: "configureAuthorization", - eventType: .configureAuthorization(.testData, .testData)) + eventType: .configureAuthorization(.testData, .testData) + ) static let authenticationConfigured = AuthEvent( id: "authenticationConfigured", - eventType: .authenticationConfigured(.testData, .testData)) + eventType: .authenticationConfigured(.testData, .testData) + ) static let authorizationConfigured = AuthEvent( id: "authorizationConfigured", - eventType: .authorizationConfigured) + eventType: .authorizationConfigured + ) static let validateCredentialAndConfiguration = AuthEvent( id: "validateCredentialAndConfiguration", - eventType: .validateCredentialAndConfiguration(.testData, .testData)) + eventType: .validateCredentialAndConfiguration(.testData, .testData) + ) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift index 01a4bff480..e942ba00fc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthTestData.swift @@ -65,9 +65,11 @@ extension AuthenticationError { } extension SignInEventData { - static let testData = SignInEventData(username: "testUserName", - password: "testPassword", - signInMethod: .apiBased(.userSRP)) + static let testData = SignInEventData( + username: "testUserName", + password: "testPassword", + signInMethod: .apiBased(.userSRP) + ) } extension SignOutEventData { @@ -84,7 +86,8 @@ extension SignInState { static let testData = SignInState.signingInWithSRP(.notStarted, SignInEventData( username: "", password: "", - signInMethod:.apiBased(.userSRP))) + signInMethod: .apiBased(.userSRP) + )) } extension UserPoolConfigurationData { @@ -98,8 +101,10 @@ extension UserPoolConfigurationData { } extension IdentityPoolConfigurationData { - static let testData = IdentityPoolConfigurationData(poolId: "poolId", - region: "regionId") + static let testData = IdentityPoolConfigurationData( + poolId: "poolId", + region: "regionId" + ) } struct MockInvalidEnvironment: Environment { } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift index b2d9f55c5a..e8389d786d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationStateResolverTests.swift @@ -12,9 +12,10 @@ import XCTest typealias AuthorizationStateSequence = StateSequence extension AuthorizationStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = AuthorizationState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -28,17 +29,23 @@ class AuthorizationStateResolverTests: XCTestCase { let authorizationError = AuthorizationError.configuration(message: "someError") let testCredentials = AmplifyCredentials.testData let validSequences: [AuthorizationStateSequence] = [ - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent(eventType: .configure), - expected: .configured), - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent( + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent(eventType: .configure), + expected: .configured + ), + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent( eventType: .cachedCredentialsAvailable(testCredentials)), - expected: .sessionEstablished(testCredentials)), - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent( + expected: .sessionEstablished(testCredentials) + ), + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent( eventType: .throwError(authorizationError)), - expected: .error(authorizationError)) + expected: .error(authorizationError) + ) ] @@ -51,12 +58,16 @@ class AuthorizationStateResolverTests: XCTestCase { let authorizationError = AuthorizationError.configuration(message: "someError") let invalidSequences: [AuthorizationStateSequence] = [ - AuthorizationStateSequence(oldState: .notConfigured, - event: AuthorizationEvent(eventType: .throwError(authorizationError)), - expected: .configured), - AuthorizationStateSequence(oldState: .configured, - event: AuthorizationEvent(eventType: .throwError(authorizationError)), - expected: .notConfigured) + AuthorizationStateSequence( + oldState: .notConfigured, + event: AuthorizationEvent(eventType: .throwError(authorizationError)), + expected: .configured + ), + AuthorizationStateSequence( + oldState: .configured, + event: AuthorizationEvent(eventType: .throwError(authorizationError)), + expected: .notConfigured + ) ] for sequence in invalidSequences { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift index 0eb909095e..fb49ce7412 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/AuthorizationTestData.swift @@ -12,26 +12,32 @@ import Foundation extension AWSAuthCognitoSession { static var testData: AWSAuthCognitoSession { - AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .success("identityId"), - awsCredentialsResult: .success(AuthAWSCognitoCredentials.testData), - cognitoTokensResult: .success(AWSCognitoUserPoolTokens.testData)) + AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .success("identityId"), + awsCredentialsResult: .success(AuthAWSCognitoCredentials.testData), + cognitoTokensResult: .success(AWSCognitoUserPoolTokens.testData) + ) } } extension AuthAWSCognitoCredentials { static var testData: AuthAWSCognitoCredentials { - AuthAWSCognitoCredentials(accessKeyId: "accessKey", - secretAccessKey: "secretAccessKey", - sessionToken: "sessionToken", - expiration: Date() + 121) + AuthAWSCognitoCredentials( + accessKeyId: "accessKey", + secretAccessKey: "secretAccessKey", + sessionToken: "sessionToken", + expiration: Date() + 121 + ) } static var expiredTestData: AuthAWSCognitoCredentials { - AuthAWSCognitoCredentials(accessKeyId: "accessKey", - secretAccessKey: "secretAccessKey", - sessionToken: "sessionToken", - expiration: Date() - 10000) + AuthAWSCognitoCredentials( + accessKeyId: "accessKey", + secretAccessKey: "secretAccessKey", + sessionToken: "sessionToken", + expiration: Date() - 10_000 + ) } } @@ -43,36 +49,48 @@ extension FederatedToken { extension AmplifyCredentials { static var testData: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .testData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .testData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } static var testDataIdentityPool: AmplifyCredentials { - AmplifyCredentials.identityPoolOnly(identityID: "someId", - credentials: .testData) + AmplifyCredentials.identityPoolOnly( + identityID: "someId", + credentials: .testData + ) } static var hostedUITestData: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .hostedUISignInData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .hostedUISignInData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } static var testDataWithExpiredTokens: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .expiredTestData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .expiredTestData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } static var testDataWithExpiredAWSCredentials: AmplifyCredentials { - AmplifyCredentials.userPoolAndIdentityPool(signedInData: .testData, - identityID: "identityId", - credentials: AuthAWSCognitoCredentials.expiredTestData) + AmplifyCredentials.userPoolAndIdentityPool( + signedInData: .testData, + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.expiredTestData + ) } static var testDataIdentityPoolWithExpiredTokens: AmplifyCredentials { - AmplifyCredentials.identityPoolOnly(identityID: "identityId", - credentials: AuthAWSCognitoCredentials.testData) + AmplifyCredentials.identityPoolOnly( + identityID: "identityId", + credentials: AuthAWSCognitoCredentials.testData + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift index 43a8f7b9e0..9d7c7c7e82 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/AuthorizationState/FetchAuthSessionStateResolverTests.swift @@ -5,17 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify +import XCTest @testable import AWSCognitoAuthPlugin typealias FetchAuthSessionStateSequence = StateSequence extension FetchAuthSessionStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = FetchAuthSessionState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -27,25 +28,8 @@ extension FetchAuthSessionStateSequence { class FetchAuthSessionStateResolverTests: XCTestCase { func testValidFetchAuthSessionStateSequences() throws { -// let cognitoSession = AWSAuthCognitoSession.testData - - let validSequences: [FetchAuthSessionStateSequence] = [ -// StateSequence(oldState: .initializingFetchAuthSession, -// event: FetchAuthSessionEvent(eventType: .fetchIdentity(cognitoSession)), -// expected: .fetchingIdentity(FetchIdentityState.configuring)), -// StateSequence(oldState: .initializingFetchAuthSession, -// event: FetchAuthSessionEvent(eventType: .fetchUserPoolTokens(cognitoSession)), -// expected: .fetchingUserPoolTokens(FetchUserPoolTokensState.configuring)), -// StateSequence(oldState: .fetchingUserPoolTokens(FetchUserPoolTokensState.configuring), -// event: FetchAuthSessionEvent(eventType: .fetchIdentity(cognitoSession)), -// expected: .fetchingIdentity(FetchIdentityState.configuring)), -// StateSequence(oldState: .fetchingIdentity(FetchIdentityState.configuring), -// event: FetchAuthSessionEvent(eventType: .fetchAWSCredentials(cognitoSession)), -// expected: .fetchingAWSCredentials(FetchAWSCredentialsState.configuring)), -// StateSequence(oldState: .fetchingAWSCredentials(FetchAWSCredentialsState.fetched), -// event: FetchAuthSessionEvent(eventType: .fetchedAuthSession(cognitoSession)), -// expected: .sessionEstablished) - ] + + let validSequences: [FetchAuthSessionStateSequence] = [] for sequence in validSequences { sequence.assertResolvesToExpected() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift index 6316967d01..cedf486bfc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/CredentialStoreState/CredentialStoreStateResolverTests.swift @@ -5,16 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSPluginsCore +import XCTest @testable import AWSCognitoAuthPlugin typealias CredentialStoreStateSequence = StateSequence extension CredentialStoreStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = CredentialStoreState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -32,71 +33,88 @@ class CredentialStoreStateResolverTests: XCTestCase { CredentialStoreStateSequence( oldState: .notConfigured, event: CredentialStoreEvent(eventType: .migrateLegacyCredentialStore), - expected: .migratingLegacyStore), + expected: .migratingLegacyStore + ), CredentialStoreStateSequence( oldState: .migratingLegacyStore, event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .loadingStoredCredentials), + expected: .loadingStoredCredentials + ), CredentialStoreStateSequence( oldState: .loadingStoredCredentials, event: CredentialStoreEvent(eventType: .completedOperation(.amplifyCredentials(testData))), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .loadingStoredCredentials, event: CredentialStoreEvent(eventType: .throwError(credentialStoreError)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .clearingCredentials, event: CredentialStoreEvent(eventType: .credentialCleared(.amplifyCredentials)), - expected: .clearedCredential(.amplifyCredentials)), + expected: .clearedCredential(.amplifyCredentials) + ), CredentialStoreStateSequence( oldState: .clearingCredentials, event: CredentialStoreEvent(eventType: .throwError(credentialStoreError)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .storingCredentials, event: CredentialStoreEvent(eventType: .completedOperation(.amplifyCredentials(testData))), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .storingCredentials, event: CredentialStoreEvent(eventType: .throwError(credentialStoreError)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .success(.amplifyCredentials(testData)), event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .success(.amplifyCredentials(testData)), event: CredentialStoreEvent(eventType: .storeCredentials(.amplifyCredentials(testData))), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .success(.amplifyCredentials(testData)), event: CredentialStoreEvent(eventType: .clearCredentialStore(.amplifyCredentials)), - expected: .success(.amplifyCredentials(testData))), + expected: .success(.amplifyCredentials(testData)) + ), CredentialStoreStateSequence( oldState: .error(credentialStoreError), event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .error(credentialStoreError), event: CredentialStoreEvent(eventType: .storeCredentials(.amplifyCredentials(testData))), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .error(credentialStoreError), event: CredentialStoreEvent(eventType: .clearCredentialStore(.amplifyCredentials)), - expected: .error(credentialStoreError)), + expected: .error(credentialStoreError) + ), CredentialStoreStateSequence( oldState: .idle, event: CredentialStoreEvent(eventType: .loadCredentialStore(.amplifyCredentials)), - expected: .loadingStoredCredentials), + expected: .loadingStoredCredentials + ), CredentialStoreStateSequence( oldState: .idle, event: CredentialStoreEvent(eventType: .storeCredentials(.amplifyCredentials(testData))), - expected: .storingCredentials), + expected: .storingCredentials + ), CredentialStoreStateSequence( oldState: .idle, event: CredentialStoreEvent(eventType: .clearCredentialStore(.amplifyCredentials)), - expected: .clearingCredentials) + expected: .clearingCredentials + ) ] for sequence in validSequences { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift index 4ecd257a5d..dfab6d1aee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SRPSignInState/SRPTestData.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin // MARK: - Test Data @@ -28,43 +28,50 @@ extension InitiateAuthOutput { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: nil, - session: nil) + session: nil + ) static let validTestData = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "session") + session: "session" + ) static let invalidChallenge = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: [:], - session: nil) + session: nil + ) static let invalidTestDataWithNoSalt = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsNoSalt, - session: "session") + session: "session" + ) static let invalidTestDataWithNoSecretBlock = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsNoSecretBlock, - session: "session") + session: "session" + ) static let invalidTestDataWithNoSRPB = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsNoSRPB, - session: "session") + session: "session" + ) static let invalidTestDataForException = InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.invalidChalengeParamsForException, - session: "session") + session: "session" + ) } extension RespondToAuthChallengeOutput { @@ -75,13 +82,15 @@ extension RespondToAuthChallengeOutput { idToken: "idTokenXXX", newDeviceMetadata: nil, refreshToken: "refreshTokenXXX", - tokenType: "Bearer") + tokenType: "Bearer" + ) return RespondToAuthChallengeOutput( authenticationResult: result, challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) } static func testDataWithNewDevice() -> RespondToAuthChallengeOutput { @@ -91,13 +100,15 @@ extension RespondToAuthChallengeOutput { idToken: "idTokenXXX", newDeviceMetadata: .init(deviceGroupKey: "mockGroupKey", deviceKey: "mockKey"), refreshToken: "refreshTokenXXX", - tokenType: "Bearer") + tokenType: "Bearer" + ) return RespondToAuthChallengeOutput( authenticationResult: result, challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) } static func testDataWithVerifyDevice() -> RespondToAuthChallengeOutput { @@ -105,17 +116,20 @@ extension RespondToAuthChallengeOutput { authenticationResult: nil, challengeName: .deviceSrpAuth, challengeParameters: [:], - session: "session") + session: "session" + ) } static func testData( challenge: CognitoIdentityProviderClientTypes.ChallengeNameType = .smsMfa, - challengeParameters: [String: String] = [:]) -> RespondToAuthChallengeOutput { + challengeParameters: [String: String] = [:] + ) -> RespondToAuthChallengeOutput { return RespondToAuthChallengeOutput( authenticationResult: nil, challengeName: challenge, challengeParameters: challengeParameters, - session: "session") + session: "session" + ) } } @@ -126,12 +140,14 @@ extension RespondToAuthChallenge { challenge: CognitoIdentityProviderClientTypes.ChallengeNameType = .smsMfa, username: String = "username", session: String = "session", - parameters: [String: String] = [:]) -> RespondToAuthChallenge { + parameters: [String: String] = [:] + ) -> RespondToAuthChallenge { RespondToAuthChallenge( challenge: challenge, username: username, session: session, - parameters: parameters) + parameters: parameters + ) } } @@ -212,7 +228,8 @@ extension SRPStateData { "1739014fed1802170702c5a034b2ff47d5a8d871db7e5bf51cb3ad29553101ed4cbd" + "98bab9079c01ab6acd0e75518d0cda640b9a1f011c9a7cefab68b6ddce666c874659" + "8a502c0e6adef0722bac", - privateKeyHexValue: "c142c2d2471fd53bca99c2fdec84e522adec8ee2dcda0d9fff9dbea52ac4a65f"), + privateKeyHexValue: "c142c2d2471fd53bca99c2fdec84e522adec8ee2dcda0d9fff9dbea52ac4a65f" + ), clientTimestamp: Date(timeIntervalSinceReferenceDate: 656_187_908.969623) ) } @@ -230,14 +247,16 @@ extension InitiateAuthOutput { "SALT": "a", "USER_ID_FOR_SRP": "royji2", "SRP_B": "a", - "USERNAME": "a"] + "USERNAME": "a" + ] static let invalidChalengeParamsForException: [String: String] = [ "SALT": "a", "SECRET_BLOCK": "", "USER_ID_FOR_SRP": "royji2", "SRP_B": "za", - "USERNAME": "a"] + "USERNAME": "a" + ] static let invalidChalengeParamsNoSRPB: [String: String] = [ "SALT": "a", @@ -267,7 +286,8 @@ extension InitiateAuthOutput { "bA7jMS0q3ld4sAAw8YfRNf0KggdA9Iolz9qdI/8xVLTLWsdvv1NA1JIPb8lPtlkqTlFYDp" + "inYbJk4W/1BOS85TSWPBwadRpVhEIDeH42hIgnvEPA==", "USER_ID_FOR_SRP": "royji2", - "USERNAME": "a"] + "USERNAME": "a" + ] static let validChalengeParams: [String: String] = [ "SALT": "79b00c90ebb6221ab4cad530f41441ed", @@ -308,7 +328,8 @@ extension InitiateAuthOutput { "96eec45283edfc75060a4bd0dc31544eb424cd25939626c014199ad433079b26a0ecab" + "129c2eef61d22994ad70c96d286e6e8c1abc65e7060ba69cb0d8c4a31cc08cc7d76ef9" + "2f757b2a34e7ae236aadbced9bb7a4a06e67da3a084833e0f3a0b903af0a74816031", - "USERNAME": "royji2"] + "USERNAME": "royji2" + ] static let validSMSChallengeParams: [String: String] = [ "CODE_DELIVERY_DELIVERY_MEDIUM": "SMS", diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift index f660e7e837..32f135b3ee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateResolverTests.swift @@ -12,9 +12,10 @@ import XCTest typealias SignOutStateSequence = StateSequence extension SignOutStateSequence { - init(oldState: MyState, - event: MyEvent, - expected: MyState + init( + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = SignOutState.Resolver().logging().eraseToAnyResolver() self.oldState = oldState @@ -29,25 +30,31 @@ class SignOutStateResolverTests: XCTestCase { SignOutStateSequence( oldState: .notStarted, event: SignOutEvent(eventType: .signOutGlobally(.testData)), - expected: .signingOutGlobally), + expected: .signingOutGlobally + ), SignOutStateSequence( oldState: .notStarted, event: SignOutEvent(eventType: .revokeToken(.testData)), - expected: .revokingToken), + expected: .revokingToken + ), SignOutStateSequence( oldState: .signingOutGlobally, event: SignOutEvent(eventType: .revokeToken(.testData)), - expected: .revokingToken), + expected: .revokingToken + ), SignOutStateSequence( oldState: .signingOutGlobally, event: SignOutEvent(eventType: .globalSignOutError( .testData, - globalSignOutError: .init(accessToken: "", error: .service("", "", nil)))), - expected: .buildingRevokeTokenError), + globalSignOutError: .init(accessToken: "", error: .service("", "", nil)) + )), + expected: .buildingRevokeTokenError + ), SignOutStateSequence( oldState: .revokingToken, event: SignOutEvent(eventType: .signOutLocally(.testData)), - expected: .signingOutLocally(.testData)) + expected: .signingOutLocally(.testData) + ) ] for sequence in validSequences { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift index 2036eb387f..fff84bb7b1 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignOutState/SignOutStateTestData.swift @@ -7,8 +7,8 @@ import Foundation -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin // MARK: - Test Data diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift index 406b48a76c..2b790c6c38 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/ConfirmSignUpInputTests.swift @@ -16,15 +16,18 @@ class ConfirmSignUpInputTests: XCTestCase { func testConfirmSignUpInputWithClientSecretAndAsfDeviceId() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let confirmSignUpInput = await ConfirmSignUpInput( username: username, @@ -32,7 +35,8 @@ class ConfirmSignUpInputTests: XCTestCase { clientMetadata: [:], asfDeviceId: "asdfDeviceId", forceAliasCreation: nil, - environment: environment) + environment: environment + ) XCTAssertNotNil(confirmSignUpInput.secretHash) XCTAssertNotNil(confirmSignUpInput.userContextData) @@ -41,15 +45,18 @@ class ConfirmSignUpInputTests: XCTestCase { func testConfirmSignUpInputWithoutClientSecretAndAsfDeviceId() async throws { let username = "jeff" - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: nil) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: nil + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let confirmSignUpInput = await ConfirmSignUpInput( username: username, @@ -57,7 +64,8 @@ class ConfirmSignUpInputTests: XCTestCase { clientMetadata: [:], asfDeviceId: nil, forceAliasCreation: nil, - environment: environment) + environment: environment + ) XCTAssertNil(confirmSignUpInput.secretHash) XCTAssertNil(confirmSignUpInput.userContextData) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift index 4bcbe80f42..698dd2a06b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/RespondToAuthInputTests.swift @@ -16,15 +16,18 @@ class RespondToAuthInputTests: XCTestCase { func testDevicePasswordVerifierInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.devicePasswordVerifier( username: username, @@ -34,7 +37,8 @@ class RespondToAuthInputTests: XCTestCase { signature: "signature", deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), asfDeviceId: "asfDeviceId", - environment: environment) + environment: environment + ) XCTAssertNotNil(respondToAuthChallengeInput.challengeResponses?["SECRET_HASH"]) XCTAssertNotNil(respondToAuthChallengeInput.userContextData) @@ -43,15 +47,18 @@ class RespondToAuthInputTests: XCTestCase { func testVerifyChallengeInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.verifyChallenge( username: username, @@ -63,7 +70,8 @@ class RespondToAuthInputTests: XCTestCase { asfDeviceId: "asfDeviceId", attributes: [:], deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), - environment: environment) + environment: environment + ) XCTAssertEqual(respondToAuthChallengeInput.challengeResponses?["CODE"], "1234") XCTAssertNotNil(respondToAuthChallengeInput.userContextData) @@ -72,15 +80,18 @@ class RespondToAuthInputTests: XCTestCase { func testPasswordVerifierInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.passwordVerifier( username: username, @@ -91,7 +102,8 @@ class RespondToAuthInputTests: XCTestCase { clientMetadata: ["test": "test"], deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), asfDeviceId: "asfDeviceId", - environment: environment) + environment: environment + ) XCTAssertNotNil(respondToAuthChallengeInput.challengeResponses?["PASSWORD_CLAIM_SECRET_BLOCK"]) XCTAssertNotNil(respondToAuthChallengeInput.challengeResponses?["PASSWORD_CLAIM_SIGNATURE"]) @@ -101,15 +113,18 @@ class RespondToAuthInputTests: XCTestCase { func testDeviceSrpInput() async throws { let username = "jeff" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) let respondToAuthChallengeInput = await RespondToAuthChallengeInput.deviceSRP( username: username, @@ -117,7 +132,8 @@ class RespondToAuthInputTests: XCTestCase { deviceMetadata: .metadata(.init(deviceKey: "", deviceGroupKey: "")), asfDeviceId: "asfDeviceId", session: "session", - publicHexValue: "somehexValue") + publicHexValue: "somehexValue" + ) XCTAssertEqual(respondToAuthChallengeInput.challengeResponses?["SRP_A"], "somehexValue") XCTAssertNotNil(respondToAuthChallengeInput.userContextData) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift index 2e834c6d32..7fbfdce705 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ResolverTests/SignUpState/SignUpInputTests.swift @@ -17,22 +17,27 @@ class SignUpInputTests: XCTestCase { let username = "jeff" let password = "a2z" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) - let input = await SignUpInput(username: username, - password: password, - clientMetadata: [:], - validationData: [:], - attributes: [:], - asfDeviceId: "asFDeviceId", - environment: environment) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) + let input = await SignUpInput( + username: username, + password: password, + clientMetadata: [:], + validationData: [:], + attributes: [:], + asfDeviceId: "asFDeviceId", + environment: environment + ) XCTAssertNotNil(input.secretHash) XCTAssertNotNil(input.userContextData) @@ -42,22 +47,27 @@ class SignUpInputTests: XCTestCase { let username = "jeff" let password = "a2z" - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: nil) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: nil + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) - let input = await SignUpInput(username: username, - password: password, - clientMetadata: [:], - validationData: [:], - attributes: [:], - asfDeviceId: nil, - environment: environment) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) + let input = await SignUpInput( + username: username, + password: password, + clientMetadata: [:], + validationData: [:], + attributes: [:], + asfDeviceId: nil, + environment: environment + ) XCTAssertNil(input.secretHash) XCTAssertNil(input.userContextData) @@ -68,22 +78,27 @@ class SignUpInputTests: XCTestCase { let username = "jeff" let password = "a2z" let clientSecret = UUID().uuidString - let userPoolConfiguration = UserPoolConfigurationData(poolId: "", - clientId: "123456", - region: "", - clientSecret: clientSecret) + let userPoolConfiguration = UserPoolConfigurationData( + poolId: "", + clientId: "123456", + region: "", + clientSecret: clientSecret + ) let environment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfiguration, cognitoUserPoolFactory: Defaults.makeDefaultUserPool, cognitoUserPoolASFFactory: Defaults.makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics) - let input = await SignUpInput(username: username, - password: password, - clientMetadata: [:], - validationData: [:], - attributes: [:], - asfDeviceId: "asFDeviceId", - environment: environment) + cognitoUserPoolAnalyticsHandlerFactory: Defaults.makeUserPoolAnalytics + ) + let input = await SignUpInput( + username: username, + password: password, + clientMetadata: [:], + validationData: [:], + attributes: [:], + asfDeviceId: "asFDeviceId", + environment: environment + ) XCTAssertNotNil(input.validationData) XCTAssertNotNil(input.userContextData) @@ -98,10 +113,12 @@ class SignUpInputTests: XCTestCase { } #endif - func assertHasAttributeType(name: String, - validationData: [CognitoIdentityProviderClientTypes.AttributeType], - file: StaticString = #file, line: UInt = #line) - { + func assertHasAttributeType( + name: String, + validationData: [CognitoIdentityProviderClientTypes.AttributeType], + file: StaticString = #file, + line: UInt = #line + ) { let attribute = validationData.first(where: { $0.name == name }) XCTAssertNotNil(attribute, "Attribute not found for name: \(name)", file: file, line: line) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift index 4da92d4fe7..6ec9655cd2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/SRPTests/SRPClientTests.swift @@ -70,8 +70,10 @@ class SRPClientTests: XCTestCase { "05b324629b160935d15cdb18d1f8dfe55f2d84afaef0f761bec33eba21" + "78b426a7bf2985" - let u = try srpClientType().calculateUHexValue(clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let u = try srpClientType().calculateUHexValue( + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(u, "c3a1193f8683863acc9c1d9532105c589696e3347b860080853435906b61342a".uppercased()) } @@ -108,8 +110,10 @@ class SRPClientTests: XCTestCase { "36d9644b1bf9a84deb0f8c99c208d4aa4095c8f7e95ecdba0e651562d0" + "d80ac6272a0785" - let u = try srpClientType().calculateUHexValue(clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let u = try srpClientType().calculateUHexValue( + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(u, "bf078ed83130247cc16c6e07d646e39dda9362f5b1c6eb4f6368723b55f728e7".uppercased()) } @@ -144,8 +148,10 @@ class SRPClientTests: XCTestCase { "35aaab2db72fe322cd6d1cdd2eb8e8620726a6781a2890830c1f597c50798" + "8525156cbc17f39621a8e1963fa7cb6ac048" - let u = try srpClientType().calculateUHexValue(clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let u = try srpClientType().calculateUHexValue( + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(u, "4aa339a24ed483e6058e9e7afdc001409a4586af2f08ff009e4c3f8d12a0bce4".uppercased()) } @@ -205,12 +211,14 @@ class SRPClientTests: XCTestCase { "3edf54d1f2b24e4afcd40d69888" let srpClient = try srpClient(NHexValue: validNHexValue, gHexValue: "2") - let S = try srpClient.calculateSharedSecret(username: "VEUHc88gProyji7", - password: "dummy123@", - saltHexValue: "8bb7dcf905f418bf27b6623aa4d2f58f", - clientPrivateKeyHexValue: clientPrivateKey, - clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let S = try srpClient.calculateSharedSecret( + username: "VEUHc88gProyji7", + password: "dummy123@", + saltHexValue: "8bb7dcf905f418bf27b6623aa4d2f58f", + clientPrivateKeyHexValue: clientPrivateKey, + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(S, expectedSharedSecret.uppercased()) } @@ -267,12 +275,14 @@ class SRPClientTests: XCTestCase { "81ec6baefe0b389ee7248a7d58fdf523c1f1ebc3" let srpClient = try srpClient(NHexValue: validNHexValue, gHexValue: "2") - let S = try srpClient.calculateSharedSecret(username: "baTBpG5tZroyji7", - password: "dummy123@", - saltHexValue: "d1c1181916afc59efe7eb71674d627c", - clientPrivateKeyHexValue: clientPrivateKey, - clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: serverPublicKey) + let S = try srpClient.calculateSharedSecret( + username: "baTBpG5tZroyji7", + password: "dummy123@", + saltHexValue: "d1c1181916afc59efe7eb71674d627c", + clientPrivateKeyHexValue: clientPrivateKey, + clientPublicKeyHexValue: clientPublicKey, + serverPublicKeyHexValue: serverPublicKey + ) XCTAssertEqual(S, expectedSharedSecret.uppercased()) } @@ -322,7 +332,8 @@ class SRPClientTests: XCTestCase { saltHexValue: "8bb7dcf905f418bf27b6623aa4d2f58f", clientPrivateKeyHexValue: clientPrivateKey, clientPublicKeyHexValue: clientPublicKey, - serverPublicKeyHexValue: illegalServerPublicKey) + serverPublicKeyHexValue: illegalServerPublicKey + ) ) { error in guard let srpError = error as? SRPError else { XCTFail("Should return SRPError") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift index 43db976492..b375fa3664 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/AWSAuthCognitoSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin -import AWSPluginsCore import Amplify +import AWSPluginsCore import XCTest +@testable import AWSCognitoAuthPlugin class AWSAuthCognitoSessionTests: XCTestCase { @@ -24,14 +24,18 @@ class AWSAuthCognitoSessionTests: XCTestCase { "exp": String(Date(timeIntervalSinceNow: 121).timeIntervalSince1970) ] let error = AuthError.unknown("", nil) - let tokens = AWSCognitoUserPoolTokens(idToken: CognitoAuthTestHelper.buildToken(for: tokenData), - accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), - refreshToken: "refreshToken") - - let session = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(error), - awsCredentialsResult: .failure(error), - cognitoTokensResult: .success(tokens)) + let tokens = AWSCognitoUserPoolTokens( + idToken: CognitoAuthTestHelper.buildToken(for: tokenData), + accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), + refreshToken: "refreshToken" + ) + + let session = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(error), + awsCredentialsResult: .failure(error), + cognitoTokensResult: .success(tokens) + ) let cognitoTokens = try! session.getCognitoTokens().get() as! AWSCognitoUserPoolTokens XCTAssertFalse(cognitoTokens.doesExpire(in: 120)) XCTAssertTrue(cognitoTokens.doesExpire(in: 122)) @@ -50,14 +54,18 @@ class AWSAuthCognitoSessionTests: XCTestCase { "exp": String(Date(timeIntervalSinceNow: 1).timeIntervalSince1970) ] let error = AuthError.unknown("", nil) - let tokens = AWSCognitoUserPoolTokens(idToken: CognitoAuthTestHelper.buildToken(for: tokenData), - accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), - refreshToken: "refreshToken") + let tokens = AWSCognitoUserPoolTokens( + idToken: CognitoAuthTestHelper.buildToken(for: tokenData), + accessToken: CognitoAuthTestHelper.buildToken(for: tokenData), + refreshToken: "refreshToken" + ) - let session = AWSAuthCognitoSession(isSignedIn: true, - identityIdResult: .failure(error), - awsCredentialsResult: .failure(error), - cognitoTokensResult: .success(tokens)) + let session = AWSAuthCognitoSession( + isSignedIn: true, + identityIdResult: .failure(error), + awsCredentialsResult: .failure(error), + cognitoTokensResult: .success(tokens) + ) let cognitoTokens = try! session.getCognitoTokens().get() as! AWSCognitoUserPoolTokens XCTAssertFalse(cognitoTokens.doesExpire()) @@ -120,14 +128,15 @@ class AWSAuthCognitoSessionTests: XCTestCase { ) guard case .failure(let error) = session.getUserSub(), - case .unknown(let errorDescription, _) = error else { + case .unknown(let errorDescription, _) = error + else { XCTFail("Expected AuthError.unknown") return } XCTAssertEqual(errorDescription, "Could not retreive user sub from the fetched Cognito tokens.") } - + /// Given: An AWSAuthCognitoSession that is signed out /// When: getUserSub is invoked /// Then: A .failure with AuthError.signedOut error is returned @@ -141,7 +150,8 @@ class AWSAuthCognitoSessionTests: XCTestCase { ) guard case .failure(let error) = session.getUserSub(), - case .signedOut(let errorDescription, let recoverySuggestion, _) = error else { + case .signedOut(let errorDescription, let recoverySuggestion, _) = error + else { XCTFail("Expected AuthError.signedOut") return } @@ -149,7 +159,7 @@ class AWSAuthCognitoSessionTests: XCTestCase { XCTAssertEqual(errorDescription, AuthPluginErrorConstants.userSubSignOutError.errorDescription) XCTAssertEqual(recoverySuggestion, AuthPluginErrorConstants.userSubSignOutError.recoverySuggestion) } - + /// Given: An AWSAuthCognitoSession that has a service error /// When: getUserSub is invoked /// Then: A .failure with AuthError.signedOut error is returned @@ -169,7 +179,7 @@ class AWSAuthCognitoSessionTests: XCTestCase { XCTAssertEqual(error, serviceError) } - + /// Given: An AuthAWSCognitoCredentials and an AWSCognitoUserPoolTokens instance /// When: Two AWSAuthCognitoSession are created from the same values /// Then: The two AWSAuthCognitoSession are considered equal @@ -211,7 +221,7 @@ class AWSAuthCognitoSessionTests: XCTestCase { XCTAssertEqual(session1, session2) XCTAssertEqual(session1.debugDictionary.count, session2.debugDictionary.count) - for key in session1.debugDictionary.keys where (key != "AWS Credentials" && key != "cognitoTokens") { + for key in session1.debugDictionary.keys where key != "AWS Credentials" && key != "cognitoTokens" { XCTAssertEqual(session1.debugDictionary[key] as? String, session2.debugDictionary[key] as? String) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift index b7fc80f7f4..2113047534 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CognitoAuthTestHelper.swift @@ -8,7 +8,7 @@ import CryptoKit import Foundation -struct CognitoAuthTestHelper { +enum CognitoAuthTestHelper { /// Helper to build a JWT Token static func buildToken(for payload: [String: String]) -> String { @@ -38,7 +38,7 @@ struct CognitoAuthTestHelper { } } -fileprivate extension Data { +private extension Data { func urlSafeBase64EncodedString() -> String { return base64EncodedString() .replacingOccurrences(of: "+", with: "-") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift index ee6ea93a1e..e59541cc1f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/ConfigurationHelperTests.swift @@ -23,7 +23,8 @@ final class ConfigurationHelperTests: XCTestCase { userVerificationTypes: [.email], unauthenticatedIdentitiesEnabled: true, mfaConfiguration: nil, - mfaMethods: nil) + mfaMethods: nil + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -45,19 +46,23 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - oauth: AmplifyOutputsData.Auth.OAuth(identityProviders: ["provider1", "provider2"], - domain: "domain", - scopes: ["scope1", "scope2"], - redirectSignInUri: ["redirect1", "redirect2"], - redirectSignOutUri: ["signOut1", "signOut2"], - responseType: "responseType")) + oauth: AmplifyOutputsData.Auth.OAuth( + identityProviders: ["provider1", "provider2"], + domain: "domain", + scopes: ["scope1", "scope2"], + redirectSignInUri: ["redirect1", "redirect2"], + redirectSignOutUri: ["signOut1", "signOut2"], + responseType: "responseType" + ) + ) guard let config = ConfigurationHelper.parseUserPoolData(config), - let hostedUIConfig = config.hostedUIConfig else { + let hostedUIConfig = config.hostedUIConfig + else { XCTFail("Expected to parse UserPoolData into object") return } - + XCTAssertEqual(hostedUIConfig.clientId, "clientId") XCTAssertNil(hostedUIConfig.clientSecret, "Client secret should be nil as its not supported in Gen2") XCTAssertEqual(hostedUIConfig.oauth.scopes, ["scope1", "scope2"]) @@ -72,14 +77,18 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - passwordPolicy: .init(minLength: 5, - requireNumbers: true, - requireLowercase: true, - requireUppercase: true, - requireSymbols: true)) + passwordPolicy: .init( + minLength: 5, + requireNumbers: true, + requireLowercase: true, + requireUppercase: true, + requireSymbols: true + ) + ) guard let config = ConfigurationHelper.parseUserPoolData(config), - let result = config.passwordProtectionSettings else { + let result = config.passwordProtectionSettings + else { XCTFail("Expected to parse UserPoolData into object") return } @@ -97,7 +106,8 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - usernameAttributes: [.email, .phoneNumber]) + usernameAttributes: [.email, .phoneNumber] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -126,7 +136,8 @@ final class ConfigurationHelperTests: XCTestCase { .preferredUsername, .profile, .website - ]) + ] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -161,7 +172,8 @@ final class ConfigurationHelperTests: XCTestCase { .sub, .updatedAt, .zoneinfo - ]) + ] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -177,7 +189,8 @@ final class ConfigurationHelperTests: XCTestCase { awsRegion: "us-east-1", userPoolId: "poolId", userPoolClientId: "clientId", - userVerificationTypes: [.phoneNumber, .email]) + userVerificationTypes: [.phoneNumber, .email] + ) guard let result = ConfigurationHelper.parseUserPoolData(config) else { XCTFail("Expected to parse UserPoolData into object") @@ -195,14 +208,15 @@ final class ConfigurationHelperTests: XCTestCase { let config = AuthConfiguration .userPools(.init( poolId: "", - clientId: "", + clientId: "", region: "", passwordProtectionSettings: .init(from: .init( minLength: 8, requireNumbers: true, requireLowercase: true, requireUppercase: true, - requireSymbols: true)), + requireSymbols: true + )), usernameAttributes: [ .init(from: .email), .init(from: .phoneNumber) @@ -214,7 +228,8 @@ final class ConfigurationHelperTests: XCTestCase { verificationMechanisms: [ .init(from: .email), .init(from: .phoneNumber) - ])) + ] + )) let json = ConfigurationHelper.createUserPoolJsonConfiguration(config) guard let authConfig = json.Auth?.Default else { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift index 62c3e537f2..7cab8ec037 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/CustomEndpoint+AuthConfigurationJSONTestCase.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -@testable import AWSCognitoAuthPlugin import Amplify +import Foundation import XCTest +@testable import AWSCognitoAuthPlugin class CustomEndpoint_AuthConfigurationJSONTestCase: XCTestCase { /// Given: The `awsCognitoAuthPlugin` portion of an `amplifyconfiguration.json` diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift index 600609dc2d..32088717c2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolving+ValidationStepTestCase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import XCTest @testable import AWSCognitoAuthPlugin -import Amplify class EndpointResolving_ValidationStepTestCase: XCTestCase { // MARK: EndpointResolving.ValidationStep.schemeIsEmpty() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift index d460299d87..8ca7741c76 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/CustomEndpoint/EndpointResolvingTestCase.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import Amplify import XCTest @testable import AWSCognitoAuthPlugin -import Amplify class EndpointResolvingTestCase: XCTestCase { /// Given: A String representation of a URL. diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift index 13e5a8781e..05fe361998 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation -@testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import AWSPluginsCore import ClientRuntime +import Foundation @testable import Amplify -import AWSPluginsCore +@testable import AWSCognitoAuthPlugin enum Defaults { @@ -72,17 +72,19 @@ enum Defaults { static func makeUserPoolAnalytics() -> UserPoolAnalyticsBehavior { MockAnalyticsHandler() } - + static func makeIdentity() throws -> CognitoIdentityBehavior { let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } return MockIdentity(mockGetIdResponse: getId, mockGetCredentialsResponse: getCredentials) @@ -90,17 +92,21 @@ enum Defaults { static func makeDefaultUserPoolConfigData(withHostedUI: HostedUIConfigurationData? = nil) -> UserPoolConfigurationData { - UserPoolConfigurationData(poolId: userPoolId, - clientId: appClientId, - region: regionString, - clientSecret: appClientSecret, - pinpointAppId: "", - hostedUIConfig: withHostedUI) + UserPoolConfigurationData( + poolId: userPoolId, + clientId: appClientId, + region: regionString, + clientSecret: appClientSecret, + pinpointAppId: "", + hostedUIConfig: withHostedUI + ) } static func makeIdentityConfigData() -> IdentityPoolConfigurationData { - IdentityPoolConfigurationData(poolId: identityPoolId, - region: regionString) + IdentityPoolConfigurationData( + poolId: identityPoolId, + region: regionString + ) } static func makeDefaultAuthConfigData(withHostedUI: HostedUIConfigurationData? = nil) -> AuthConfiguration { @@ -148,13 +154,17 @@ enum Defaults { userPoolConfiguration: userPoolConfigData, cognitoUserPoolFactory: userPoolFactory, cognitoUserPoolASFFactory: makeDefaultASF, - cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics) - let authenticationEnvironment = BasicAuthenticationEnvironment(srpSignInEnvironment: srpSignInEnvironment, - userPoolEnvironment: userPoolEnvironment, - hostedUIEnvironment: hostedUIEnvironment) + cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics + ) + let authenticationEnvironment = BasicAuthenticationEnvironment( + srpSignInEnvironment: srpSignInEnvironment, + userPoolEnvironment: userPoolEnvironment, + hostedUIEnvironment: hostedUIEnvironment + ) let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: identityPoolFactory) + cognitoIdentityFactory: identityPoolFactory + ) let authEnv = AuthEnvironment( configuration: Defaults.makeDefaultAuthConfigData(), userPoolConfigData: userPoolConfigData, @@ -172,38 +182,53 @@ enum Defaults { initialState: AuthState? = nil, identityPoolFactory: @escaping () throws -> CognitoIdentityBehavior = makeIdentity, userPoolFactory: @escaping () throws -> CognitoUserPoolBehavior = makeDefaultUserPool, - hostedUIEnvironment: HostedUIEnvironment? = nil) -> + hostedUIEnvironment: HostedUIEnvironment? = nil + ) -> AuthStateMachine { - let environment = makeDefaultAuthEnvironment(identityPoolFactory: identityPoolFactory, - userPoolFactory: userPoolFactory, - hostedUIEnvironment: hostedUIEnvironment) - return AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + let environment = makeDefaultAuthEnvironment( + identityPoolFactory: identityPoolFactory, + userPoolFactory: userPoolFactory, + hostedUIEnvironment: hostedUIEnvironment + ) + return AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) } static func makeDefaultCredentialStateMachine() -> CredentialStoreStateMachine { - return CredentialStoreStateMachine(resolver: CredentialStoreState.Resolver(), - environment: makeDefaultCredentialStoreEnvironment(), - initialState: .idle) + return CredentialStoreStateMachine( + resolver: CredentialStoreState.Resolver(), + environment: makeDefaultCredentialStoreEnvironment(), + initialState: .idle + ) } - static func authStateMachineWith(environment: AuthEnvironment = makeDefaultAuthEnvironment(), - initialState: AuthState? = nil) + static func authStateMachineWith( + environment: AuthEnvironment = makeDefaultAuthEnvironment(), + initialState: AuthState? = nil + ) -> AuthStateMachine { - return AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + return AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) } - static func makeAuthState(tokens: AWSCognitoUserPoolTokens, - signedInDate: Date = Date(), - signInMethod: SignInMethod = .apiBased(.userSRP)) -> AuthState { + static func makeAuthState( + tokens: AWSCognitoUserPoolTokens, + signedInDate: Date = Date(), + signInMethod: SignInMethod = .apiBased(.userSRP) + ) -> AuthState { - let signedInData = SignedInData(signedInDate: signedInDate, - signInMethod: signInMethod, - cognitoUserPoolTokens: tokens) + let signedInData = SignedInData( + signedInDate: signedInDate, + signInMethod: signInMethod, + cognitoUserPoolTokens: tokens + ) let authNState: AuthenticationState = .signedIn(signedInData) let authZState: AuthorizationState = .configured @@ -219,10 +244,12 @@ enum Defaults { ) } - static func makeCognitoUserPoolTokens(idToken: String = "XX", - accessToken: String = "", - refreshToken: String = "XX", - expiresIn: Int = 300) -> AWSCognitoUserPoolTokens { + static func makeCognitoUserPoolTokens( + idToken: String = "XX", + accessToken: String = "", + refreshToken: String = "XX", + expiresIn: Int = 300 + ) -> AWSCognitoUserPoolTokens { AWSCognitoUserPoolTokens(idToken: idToken, accessToken: accessToken, refreshToken: refreshToken, expiresIn: expiresIn) } @@ -246,8 +273,7 @@ struct MockCredentialStoreOperationClient: CredentialStoreStateBehavior { let device = try mockAmplifyStore.retrieveASFDevice(for: username) return .asfDeviceId(device, username) } - } - catch KeychainStoreError.itemNotFound { + } catch KeychainStoreError.itemNotFound { switch type { case .amplifyCredentials: return .amplifyCredentials(.testData) @@ -255,12 +281,12 @@ struct MockCredentialStoreOperationClient: CredentialStoreStateBehavior { return .deviceMetadata(.metadata(.init( deviceKey: "key", deviceGroupKey: "key", - deviceSecret: "secret")), username) + deviceSecret: "secret" + )), username) case .asfDeviceId(username: let username): return .asfDeviceId("id", username) } - } - catch { + } catch { fatalError() } } @@ -292,7 +318,8 @@ class MockAmplifyStore: AmplifyAuthCredentialStoreBehavior { func retrieveCredential() throws -> AmplifyCredentials { guard let data = Self.dict.getValue(forKey: credentialsKey), - let cred = (try? JSONDecoder().decode(AmplifyCredentials.self, from: data)) else { + let cred = (try? JSONDecoder().decode(AmplifyCredentials.self, from: data)) + else { throw KeychainStoreError.itemNotFound } return cred @@ -313,7 +340,8 @@ class MockAmplifyStore: AmplifyAuthCredentialStoreBehavior { func retrieveDevice(for username: String) throws -> DeviceMetadata { guard let data = Self.dict.getValue(forKey: username), - let device = (try? JSONDecoder().decode(DeviceMetadata.self, from: data)) else { + let device = (try? JSONDecoder().decode(DeviceMetadata.self, from: data)) + else { throw KeychainStoreError.itemNotFound } return device @@ -331,7 +359,8 @@ class MockAmplifyStore: AmplifyAuthCredentialStoreBehavior { func retrieveASFDevice(for username: String) throws -> String { guard let data = Self.dict.getValue(forKey: username), - let device = (try? JSONDecoder().decode(String.self, from: data)) else { + let device = (try? JSONDecoder().decode(String.self, from: data)) + else { throw KeychainStoreError.itemNotFound } return device @@ -370,10 +399,12 @@ struct MockLegacyStore: KeychainStoreBehavior { } struct MockASF: AdvancedSecurityBehavior { - func userContextData(for username: String, - deviceInfo: ASFDeviceBehavior, - appInfo: ASFAppInfoBehavior, - configuration: UserPoolConfigurationData) throws -> String { + func userContextData( + for username: String, + deviceInfo: ASFDeviceBehavior, + appInfo: ASFAppInfoBehavior, + configuration: UserPoolConfigurationData + ) throws -> String { return "" } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift index 5e44e233f1..a5d323bb17 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIASWebAuthenticationSessionTests.swift @@ -8,19 +8,19 @@ #if os(iOS) || os(macOS) import Amplify import AuthenticationServices -@testable import AWSCognitoAuthPlugin import XCTest +@testable import AWSCognitoAuthPlugin class HostedUIASWebAuthenticationSessionTests: XCTestCase { private var session: HostedUIASWebAuthenticationSession! private var factory: ASWebAuthenticationSessionFactory! - + override func setUp() { session = HostedUIASWebAuthenticationSession() factory = ASWebAuthenticationSessionFactory() session.authenticationSessionFactory = factory.createSession(url:callbackURLScheme:completionHandler:) } - + override func tearDown() { session = nil factory = nil @@ -36,7 +36,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { XCTAssertEqual(queryItems.first?.name, "name") XCTAssertEqual(queryItems.first?.value, "value") } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns a URL without query items /// Then: An empty array should be returned @@ -45,7 +45,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { let queryItems = try await session.showHostedUI() XCTAssertTrue(queryItems.isEmpty) } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns a URL with query items representing errors /// Then: A HostedUIError.serviceMessage should be returned @@ -68,7 +68,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { XCTFail("Expected HostedUIError.serviceMessage, got \(error)") } } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns ASWebAuthenticationSessionErrors /// Then: A HostedUIError corresponding to the error code should be returned @@ -98,7 +98,7 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { } } } - + /// Given: A HostedUIASWebAuthenticationSession /// When: showHostedUI is invoked and the session factory returns an error /// Then: A HostedUIError.unknown should be returned @@ -170,7 +170,7 @@ class MockASWebAuthenticationSession: ASWebAuthenticationSession { completionHandler: completionHandler ) } - + var mockedURL: URL? = nil var mockedError: Error? = nil override func start() -> Bool { @@ -190,13 +190,14 @@ extension HostedUIASWebAuthenticationSession { url: URL(string: "https://test.com")!, callbackScheme: "https", inPrivate: false, - presentationAnchor: nil) + presentationAnchor: nil + ) } } #else -@testable import AWSCognitoAuthPlugin import XCTest +@testable import AWSCognitoAuthPlugin class HostedUIASWebAuthenticationSessionTests: XCTestCase { func testShowHostedUI_shouldThrowServiceError() async { @@ -206,7 +207,8 @@ class HostedUIASWebAuthenticationSessionTests: XCTestCase { url: URL(string: "https://test.com")!, callbackScheme: "https", inPrivate: false, - presentationAnchor: nil) + presentationAnchor: nil + ) } catch let error as HostedUIError { if case .serviceMessage(let message) = error { XCTAssertEqual(message, "HostedUI is only available in iOS and macOS") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift index 69f8ae19a0..e62234191f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift @@ -7,9 +7,9 @@ import Foundation -@testable import AWSCognitoAuthPlugin import Amplify import XCTest +@testable import AWSCognitoAuthPlugin class HostedUIRequestHelperTests: XCTestCase { private var configuration: HostedUIConfigurationData! @@ -24,7 +24,8 @@ class HostedUIRequestHelperTests: XCTestCase { idpIdentifier: nil ), presentationAnchor: nil, - preferPrivateSession: false) + preferPrivateSession: false + ) ) override func setUp() { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift index ed6d2a48e0..929feeb725 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentity.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentity import ClientRuntime +@testable import AWSCognitoAuthPlugin struct MockIdentity: CognitoIdentityBehavior { @@ -19,8 +19,10 @@ struct MockIdentity: CognitoIdentityBehavior { let mockGetIdResponse: MockGetIdResponse? let mockGetCredentialsResponse: MockGetCredentialsResponse? - init(mockGetIdResponse: MockGetIdResponse? = nil, - mockGetCredentialsResponse: MockGetCredentialsResponse? = nil) { + init( + mockGetIdResponse: MockGetIdResponse? = nil, + mockGetCredentialsResponse: MockGetCredentialsResponse? = nil + ) { self.mockGetIdResponse = mockGetIdResponse self.mockGetCredentialsResponse = mockGetCredentialsResponse } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift index 5558466828..5cb525f25f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/MockIdentityProvider.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +@testable import AWSCognitoAuthPlugin struct MockIdentityProvider: CognitoUserPoolBehavior { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift index 8f30f50335..a77649ae61 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/StateSequence.swift @@ -7,8 +7,8 @@ import XCTest -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +@testable import AWSCognitoAuthPlugin struct StateSequence: CustomStringConvertible where MyState: State, MyEvent: StateMachineEvent { let resolver: AnyResolver @@ -16,10 +16,11 @@ struct StateSequence: CustomStringConvertible where MyState: S let event: MyEvent let expected: MyState - init(resolver: AnyResolver, - oldState: MyState, - event: MyEvent, - expected: MyState + init( + resolver: AnyResolver, + oldState: MyState, + event: MyEvent, + expected: MyState ) { self.resolver = resolver self.oldState = oldState diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift index 604c0b24d8..58576b0806 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift @@ -7,11 +7,11 @@ import Foundation +import AWSCognitoIdentity +import AWSPluginsCore import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentity -import AWSPluginsCore // swiftlint:disable file_length // swiftlint:disable type_body_length @@ -37,7 +37,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { input in @@ -68,25 +69,31 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.notConfigured, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.federatedToIdentityPool, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredAWSCredentials)), + AmplifyCredentials.testDataWithExpiredAWSCredentials) + ), AuthState.configured( AuthenticationState.notConfigured, - AuthorizationState.configured), + AuthorizationState.configured + ), AuthState.configured( AuthenticationState.error(.testData), - AuthorizationState.configured), + AuthorizationState.configured + ), AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.error(.sessionExpired( - error: NotAuthorizedException(message: "message")))) + error: NotAuthorizedException(message: "message"))) + ) ] for initialState in statesToTest { @@ -94,9 +101,11 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let federatedResult = try await plugin.federateToIdentityPool(withProviderToken: authenticationToken, for: provider) XCTAssertNotNil(federatedResult) @@ -130,7 +139,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) let getId: MockIdentity.MockGetIdResponse = { input in @@ -160,14 +170,17 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let federatedResult = try await plugin.federateToIdentityPool(withProviderToken: authenticationToken, for: provider) @@ -220,10 +233,12 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let statesToTest = [ AuthState.configured( AuthenticationState.signedOut(.testData), - AuthorizationState.notConfigured), + AuthorizationState.notConfigured + ), AuthState.configured( AuthenticationState.signedIn(.testData), - AuthorizationState.configured) + AuthorizationState.configured + ) ] for initialState in statesToTest { @@ -231,9 +246,11 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { _ = try await plugin.federateToIdentityPool(withProviderToken: authenticationToken, for: provider) XCTFail("Should not succeed") @@ -261,7 +278,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) let getId: MockIdentity.MockGetIdResponse = { _ in if shouldThrowError { @@ -279,23 +297,28 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, initialState: AuthState.configured( AuthenticationState.error(.testData), - AuthorizationState.error(.invalidState(message: "")))) + AuthorizationState.error(.invalidState(message: "")) + ) + ) do { // Should setup the plugin with a token shouldThrowError = false _ = try await plugin.federateToIdentityPool( withProviderToken: "someToken", - for: .facebook) + for: .facebook + ) // Push the AuthState to an error state shouldThrowError = true _ = try? await plugin.federateToIdentityPool( withProviderToken: "someToken", - for: .facebook) + for: .facebook + ) // Should still be able to clear credentials try await plugin.clearFederationToIdentityPool() @@ -318,7 +341,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") @@ -334,10 +358,13 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { AuthorizationState.sessionEstablished(.identityPoolWithFederation( federatedToken: .testData, identityID: "identityId", - credentials: .testData))), + credentials: .testData + )) + ), AuthState.configured( AuthenticationState.error(.testData), - AuthorizationState.error(.invalidState(message: ""))) + AuthorizationState.error(.invalidState(message: "")) + ) ] for initialState in statesToTest { @@ -345,13 +372,16 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { _ = try await plugin.federateToIdentityPool( withProviderToken: "someToken", - for: .facebook) + for: .facebook + ) try await plugin.clearFederationToIdentityPool() } catch { XCTFail("Received failure with error \(error)") @@ -382,13 +412,16 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let statesToTest = [ AuthState.configured( AuthenticationState.federatedToIdentityPool, - AuthorizationState.configured), + AuthorizationState.configured + ), AuthState.configured( AuthenticationState.configured, AuthorizationState.sessionEstablished(.identityPoolWithFederation( federatedToken: .testData, identityID: "identityId", - credentials: .testData))) + credentials: .testData + )) + ) ] for initialState in statesToTest { @@ -396,9 +429,11 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { try await plugin.clearFederationToIdentityPool() XCTFail("Should not succeed") @@ -433,7 +468,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let cognitoAPIExpectation = expectation(description: "Cognito API gets called") cognitoAPIExpectation.expectedFulfillmentCount = 1 @@ -464,15 +500,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .expiredTestData))) + credentials: .expiredTestData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertTrue(session.isSignedIn) @@ -489,8 +529,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { do { _ = try (session as? AuthCognitoTokensProvider)?.getCognitoTokens().get() - } - catch let error as AuthError { + } catch let error as AuthError { guard case .invalidState = error else { XCTFail("Should throw Auth Error with invalid state \(error)") return @@ -526,7 +565,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("Get ID should not get called") @@ -544,15 +584,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .testData))) + credentials: .testData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertTrue(session.isSignedIn) @@ -568,8 +612,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { do { _ = try (session as? AuthCognitoTokensProvider)?.getCognitoTokens().get() - } - catch let error as AuthError { + } catch let error as AuthError { guard case .invalidState = error else { XCTFail("Should throw Auth Error with invalid state \(error)") return @@ -604,7 +647,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let cognitoAPIExpectation = expectation(description: "Cognito API gets called") cognitoAPIExpectation.expectedFulfillmentCount = 1 @@ -635,15 +679,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .expiredTestData))) + credentials: .expiredTestData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let session = try await plugin.fetchAuthSession(options: .forceRefresh()) @@ -660,8 +708,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { do { _ = try (session as? AuthCognitoTokensProvider)?.getCognitoTokens().get() - } - catch let error as AuthError { + } catch let error as AuthError { guard case .invalidState = error else { XCTFail("Should throw Auth Error with invalid state \(error)") return @@ -695,7 +742,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("Get ID should not get called") @@ -719,18 +767,22 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.notConfigured, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)), + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ), AuthState.configured( AuthenticationState.federatedToIdentityPool, AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredAWSCredentials)), + AmplifyCredentials.testDataWithExpiredAWSCredentials) + ), AuthState.configured( AuthenticationState.notConfigured, - AuthorizationState.configured) + AuthorizationState.configured + ) ] for initialState in statesToTest { @@ -738,14 +790,17 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) do { let federatedResult = try await plugin.federateToIdentityPool( withProviderToken: authenticationToken, for: provider, - options: .init(developerProvidedIdentityID: mockIdentityId)) + options: .init(developerProvidedIdentityID: mockIdentityId) + ) XCTAssertNotNil(federatedResult) XCTAssertEqual(federatedResult.credentials.sessionToken, credentials.sessionToken) XCTAssertEqual(federatedResult.credentials.accessKeyId, credentials.accessKeyId) @@ -770,7 +825,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { /// func testFederateToIdentityPoolWhenGetIdErrorsOut() async throws { - var shouldThrowError: Bool = false + var shouldThrowError = false let provider = AuthProvider.facebook let authenticationToken = "authenticationToken" @@ -780,7 +835,8 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { input in return .init(identityId: mockIdentityId) @@ -797,15 +853,18 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) shouldThrowError = true do { @@ -849,14 +908,15 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let mockIdentityId = "mockIdentityId" - var shouldThrowError: Bool = false + var shouldThrowError = false let federatedToken: FederatedToken = .testData let credentials = CognitoIdentityClientTypes.Credentials( accessKeyId: "accessKey", expiration: Date(), secretKey: "secretAccessKey", - sessionToken: "sessionKey") + sessionToken: "sessionKey" + ) let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("GetId should not be called") @@ -877,15 +937,19 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { .identityPoolWithFederation( federatedToken: federatedToken, identityID: mockIdentityId, - credentials: .expiredTestData))) + credentials: .expiredTestData + )) + ) let plugin = configurePluginWith( identityPool: { MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) }, - initialState: initialState) + initialState: initialState + ) shouldThrowError = true @@ -925,6 +989,6 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { XCTFail("Received failure with error \(error)") } } - + } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift index a67aa2522b..14ed0e30dc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift @@ -7,13 +7,13 @@ import Foundation -import XCTest -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentity import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon @@ -37,24 +37,32 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testData)) + AmplifyCredentials.testData) + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertTrue(session.isSignedIn) @@ -92,14 +100,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testData)) + AmplifyCredentials.testData) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in resultExpectation.fulfill() return InitiateAuthOutput(authenticationResult: .init( accessToken: "accessToken", - expiresIn: 1000, + expiresIn: 1_000, idToken: "idToken", - refreshToken: "refreshToke")) + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -108,14 +118,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { accessKeyId: "accessKey", expiration: Date(), secretKey: "secret", - sessionToken: "session") + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: .forceRefresh()) resultExpectation.fulfill() XCTAssertTrue(session.isSignedIn) @@ -152,24 +164,32 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -183,7 +203,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let error) = tokensResult, - case .signedOut = error else { + case .signedOut = error + else { XCTFail("Should return signed out error") return } @@ -206,7 +227,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in throw try await AWSCognitoIdentityProvider.NotAuthorizedException( @@ -226,14 +248,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .sessionExpired = identityIdError else { + case .sessionExpired = identityIdError + else { XCTFail("Should return sessionExpired error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .sessionExpired = tokenError else { + case .sessionExpired = tokenError + else { XCTFail("Should return sessionExpired error") return } @@ -256,13 +280,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: "accessToken", - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: "accessToken", + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -274,7 +301,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -287,14 +315,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .sessionExpired = identityIdError else { + case .sessionExpired = identityIdError + else { XCTFail("Should return sessionExpired error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .sessionExpired = tokenError else { + case .sessionExpired = tokenError + else { XCTFail("Should return sessionExpired error") return } @@ -490,18 +520,22 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: nil, - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: nil, + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -514,14 +548,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .unknown = identityIdError else { + case .unknown = identityIdError + else { XCTFail("Should return unknown error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .unknown = tokenError else { + case .unknown = tokenError + else { XCTFail("Should return unknown error") return } @@ -543,13 +579,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: "accessToken", - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: "accessToken", + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -558,7 +597,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -571,14 +611,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .unknown = identityIdError else { + case .unknown = identityIdError + else { XCTFail("Should return unknown error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .unknown = tokenError else { + case .unknown = tokenError + else { XCTFail("Should return unknown error") return } @@ -600,24 +642,32 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), - AuthorizationState.error(.sessionError(.service(AuthError.unknown("error")), .noCredentials))) + AuthorizationState.error(.sessionError(.service(AuthError.unknown("error")), .noCredentials)) + ) let getId: MockIdentity.MockGetIdResponse = { _ in return .init(identityId: "mockIdentityId") } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -631,7 +681,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let error) = tokensResult, - case .signedOut = error else { + case .signedOut = error + else { XCTFail("Should return signed out error") return } @@ -654,19 +705,25 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedOut(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataIdentityPoolWithExpiredTokens)) + AmplifyCredentials.testDataIdentityPoolWithExpiredTokens) + ) let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") - return GetCredentialsForIdentityOutput(credentials: credentials, - identityId: "ss") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) + return GetCredentialsForIdentityOutput( + credentials: credentials, + identityId: "ss" + ) } let plugin = configurePluginWith( identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -684,7 +741,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .signedOut = tokenError else { + case .signedOut = tokenError + else { XCTFail("Should return signedOut error") return } @@ -706,7 +764,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException(message: "NotAuthorized") @@ -714,7 +773,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -722,21 +782,24 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let credentialsResult = (session as? AuthAWSCredentialsProvider)?.getAWSCredentials() guard case .failure(let error) = credentialsResult, - case .sessionExpired = error else { + case .sessionExpired = error + else { XCTFail("Should return sessionExpired error") return } let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .sessionExpired = identityIdError else { + case .sessionExpired = identityIdError + else { XCTFail("Should return sessionExpired error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .sessionExpired = tokenError else { + case .sessionExpired = tokenError + else { XCTFail("Should return sessionExpired error") return } @@ -767,17 +830,24 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } - let plugin = configurePluginWith(identityPool: { - MockIdentity(mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) }, - initialState: initialState) + let plugin = configurePluginWith( + identityPool: { + MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) + }, + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) XCTAssertFalse(session.isSignedIn) @@ -806,13 +876,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let initialState = AuthState.configured( AuthenticationState.signedIn(.testData), AuthorizationState.sessionEstablished( - AmplifyCredentials.testDataWithExpiredTokens)) + AmplifyCredentials.testDataWithExpiredTokens) + ) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - return InitiateAuthOutput(authenticationResult: .init(accessToken: "accessToken", - expiresIn: 1000, - idToken: "idToken", - refreshToken: "refreshToke")) + return InitiateAuthOutput(authenticationResult: .init( + accessToken: "accessToken", + expiresIn: 1_000, + idToken: "idToken", + refreshToken: "refreshToke" + )) } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in @@ -821,7 +894,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let plugin = configurePluginWith( userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, identityPool: { MockIdentity(mockGetCredentialsResponse: awsCredentials) }, - initialState: initialState) + initialState: initialState + ) let session = try await plugin.fetchAuthSession(options: AuthFetchSessionRequest.Options()) @@ -834,14 +908,16 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { let identityIdResult = (session as? AuthCognitoIdentityProvider)?.getIdentityId() guard case .failure(let identityIdError) = identityIdResult, - case .service = identityIdError else { + case .service = identityIdError + else { XCTFail("Should return service error") return } let tokensResult = (session as? AuthCognitoTokensProvider)?.getCognitoTokens() guard case .failure(let tokenError) = tokensResult, - case .service = tokenError else { + case .service = tokenError + else { XCTFail("Should return service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift index 560584a639..2b66c149e9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/BaseAuthorizationTests.swift @@ -14,24 +14,30 @@ class BaseAuthorizationTests: XCTestCase { let apiTimeout = 2.0 - func configurePluginWith(authConfiguration: AuthConfiguration = Defaults.makeDefaultAuthConfigData(), - userPool: @escaping () throws -> CognitoUserPoolBehavior = Defaults.makeDefaultUserPool, - identityPool: @escaping () throws -> CognitoIdentityBehavior = Defaults.makeIdentity, - initialState: AuthState) -> AWSCognitoAuthPlugin { + func configurePluginWith( + authConfiguration: AuthConfiguration = Defaults.makeDefaultAuthConfigData(), + userPool: @escaping () throws -> CognitoUserPoolBehavior = Defaults.makeDefaultUserPool, + identityPool: @escaping () throws -> CognitoIdentityBehavior = Defaults.makeIdentity, + initialState: AuthState + ) -> AWSCognitoAuthPlugin { let plugin = AWSCognitoAuthPlugin() let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: identityPool, - userPoolFactory: userPool) - let statemachine = AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + userPoolFactory: userPool + ) + let statemachine = AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) plugin.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), authEnvironment: environment, authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift index e940246c43..51e440650b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -19,16 +19,18 @@ class AWSAuthSignOutTaskTests: BasePluginTest { override var initialState: AuthState { AuthState.configured( AuthenticationState.signedIn(.testData), - AuthorizationState.sessionEstablished(.testData)) + AuthorizationState.sessionEstablished(.testData) + ) } func testSuccessfullSignOut() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in return .testData }, mockGlobalSignOutResponse: { _ in return .testData - }) + } + ) guard let result = await plugin.signOut() as? AWSCognitoSignOutResult, case .complete = result else { XCTFail("Did not return complete signOut") @@ -37,16 +39,19 @@ class AWSAuthSignOutTaskTests: BasePluginTest { } func testGlobalSignOutFailed() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in return .testData }, mockGlobalSignOutResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() - }) + } + ) guard let result = await plugin.signOut(options: .init(globalSignOut: true)) as? AWSCognitoSignOutResult, - case .partial(revokeTokenError: let revokeTokenError, - globalSignOutError: let globalSignOutError, - hostedUIError: let hostedUIError) = result else { + case .partial( + revokeTokenError: let revokeTokenError, + globalSignOutError: let globalSignOutError, + hostedUIError: let hostedUIError + ) = result else { XCTFail("Did not return partial signOut") return } @@ -57,16 +62,19 @@ class AWSAuthSignOutTaskTests: BasePluginTest { } func testRevokeSignOutFailed() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() }, mockGlobalSignOutResponse: { _ in return .testData - }) + } + ) guard let result = await plugin.signOut(options: .init(globalSignOut: true)) as? AWSCognitoSignOutResult, - case .partial(revokeTokenError: let revokeTokenError, - globalSignOutError: let globalSignOutError, - hostedUIError: let hostedUIError) = result else { + case .partial( + revokeTokenError: let revokeTokenError, + globalSignOutError: let globalSignOutError, + hostedUIError: let hostedUIError + ) = result else { XCTFail("Did not return partial signOut") return } @@ -79,7 +87,8 @@ class AWSAuthSignOutTaskTests: BasePluginTest { let initialState = AuthState.configured( AuthenticationState.federatedToIdentityPool, - AuthorizationState.sessionEstablished(.testData)) + AuthorizationState.sessionEstablished(.testData) + ) let authPlugin = configureCustomPluginWith(initialState: initialState) @@ -98,7 +107,8 @@ class AWSAuthSignOutTaskTests: BasePluginTest { let initialState = AuthState.configured( AuthenticationState.signedIn(.hostedUISignInData), - AuthorizationState.sessionEstablished(.hostedUITestData)) + AuthorizationState.sessionEstablished(.hostedUITestData) + ) let authPlugin = configureCustomPluginWith(initialState: initialState) @@ -118,7 +128,8 @@ class AWSAuthSignOutTaskTests: BasePluginTest { let initialState = AuthState.configured( AuthenticationState.signedOut(.init()), - AuthorizationState.sessionEstablished(.testDataIdentityPool)) + AuthorizationState.sessionEstablished(.testDataIdentityPool) + ) let authPlugin = configureCustomPluginWith(initialState: initialState) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift index 9b17dbf1dc..7b818aeca8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSCognitoAuthClientBehaviorTests.swift @@ -7,11 +7,11 @@ import Foundation -import XCTest import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider class AWSCognitoAuthClientBehaviorTests: XCTestCase { let networkTimeout = TimeInterval(10) @@ -21,10 +21,12 @@ class AWSCognitoAuthClientBehaviorTests: XCTestCase { AuthState.configured( AuthenticationState.signedIn( SignedInData( - signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) } override func setUp() { @@ -35,25 +37,30 @@ class AWSCognitoAuthClientBehaviorTests: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -61,7 +68,8 @@ class AWSCognitoAuthClientBehaviorTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } override func tearDown() async throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift index d7d8080386..e111cdcece 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift @@ -7,13 +7,13 @@ import Foundation +import AWSClientRuntime +import AWSCognitoIdentityProvider +import AwsCommonRuntimeKit +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime -import AwsCommonRuntimeKit -import AWSClientRuntime class AuthenticationProviderDeleteUserTests: BasePluginTest { @@ -84,7 +84,7 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { try await GlobalSignOutOutput(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutput: { _ in - throw CommonRunTimeError.crtError(CRTError(code: 1059)) + throw CommonRunTimeError.crtError(CRTError(code: 1_059)) } ) do { @@ -92,7 +92,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .network = (underlyingError as? AWSCognitoAuthError) else { + case .network = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce network error instead of \(error)") return } @@ -118,7 +119,7 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { try await GlobalSignOutOutput(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutput: { _ in - throw CommonRunTimeError.crtError(CRTError(code: 1059)) + throw CommonRunTimeError.crtError(CRTError(code: 1_059)) } ) do { @@ -126,7 +127,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .network = (underlyingError as? AWSCognitoAuthError) else { + case .network = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce network error instead of \(error)") return } @@ -217,7 +219,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce invalidParameter error instead of \(error)") return } @@ -284,7 +287,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .passwordResetRequired = (underlyingError as? AWSCognitoAuthError) else { + case .passwordResetRequired = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce unknown error instead of \(error)") return } @@ -318,7 +322,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .resourceNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .resourceNotFound = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce unknown error instead of \(error)") return } @@ -352,7 +357,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .requestLimitExceeded = (underlyingError as? AWSCognitoAuthError) else { + case .requestLimitExceeded = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce unknown error instead of \(error)") return } @@ -386,7 +392,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userNotConfirmed = (underlyingError as? AWSCognitoAuthError) else { + case .userNotConfirmed = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce userNotConfirmed error instead of \(error)") return } @@ -421,7 +428,8 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { XCTFail("Should not get success") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .userNotFound = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce userNotFound error but instead produced \(error)") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift index b8445af966..eb0c9a7d16 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift @@ -7,13 +7,13 @@ import Foundation -import XCTest import AWSCognitoIdentity import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests { @@ -113,10 +113,12 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests } ) let pluginOptions = AWSAuthConfirmResetPasswordOptions(metadata: ["key": "value"]) - try await plugin.confirmResetPassword(for: "username", - with: "newpassword", - confirmationCode: "code", - options: .init(pluginOptions: pluginOptions)) + try await plugin.confirmResetPassword( + for: "username", + with: "newpassword", + confirmationCode: "code", + options: .init(pluginOptions: pluginOptions) + ) } /// Test a confirmResetPassword call with empty new password diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift index e24e688536..d6130ad368 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { @@ -60,9 +60,11 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { /// - I should get a successful result /// func testSuccessfulResetPassword() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: "attribute", - deliveryMedium: .email, - destination: "Amplify@amazon.com") + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: "attribute", + deliveryMedium: .email, + destination: "Amplify@amazon.com" + ) mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutput: { _ in ForgotPasswordOutput(codeDeliveryDetails: codeDeliveryDetails) @@ -108,9 +110,11 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { /// func testResetPasswordWithEmptyUsername() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: "attribute", - deliveryMedium: .email, - destination: "Amplify@amazon.com") + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: "attribute", + deliveryMedium: .email, + destination: "Amplify@amazon.com" + ) mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutput: { _ in ForgotPasswordOutput(codeDeliveryDetails: codeDeliveryDetails) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift index e713f439d8..1ad230ca21 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift @@ -7,11 +7,11 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider import AWSClientRuntime +import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -27,7 +27,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithTOTPPreferred() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( preferredMfaSetting: "SOFTWARE_TOKEN_MFA", @@ -54,7 +54,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithSMSPreferred() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( preferredMfaSetting: "SMS_MFA", @@ -81,7 +81,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithNonePreferred() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( userMFASettingList: ["SOFTWARE_TOKEN_MFA", "SMS_MFA"] @@ -107,7 +107,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testInvalidResponseForUserMFASettingsList() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( userMFASettingList: ["DUMMY"] @@ -133,7 +133,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testInvalidResponseForUserMFAPreference() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( preferredMfaSetting: "DUMMY", @@ -160,7 +160,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { /// func testSuccessfulPreferenceFetchWithNonePreferredAndNoneEnabled() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init() }) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift index 7d21c937a3..e62a2ed4dd 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift @@ -7,11 +7,11 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider import AWSClientRuntime +import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -27,7 +27,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSuccessfulSetUpTOTPRequest() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in return .init(secretCode: "sharedSecret") }) @@ -53,7 +53,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithConcurrentModificationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ConcurrentModificationException( message: "Exception" @@ -85,7 +85,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithForbiddenException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ForbiddenException( message: "Exception" @@ -117,7 +117,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -149,7 +149,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -183,7 +183,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpTOTPWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -213,7 +213,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -245,7 +245,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .resourceNotFound as underlyingError /// func testSetUpTOTPInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ResourceNotFoundException( message: "Exception" @@ -278,7 +278,7 @@ class SetUpTOTPTaskTests: BasePluginTest { /// func testSetUpWithUnknownException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in throw AWSClientRuntime.UnknownAWSHTTPServiceError( httpResponse: .init(body: .empty, statusCode: .ok), diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift index a4c6fa9d27..36dda8d2ca 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift @@ -7,11 +7,11 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider import AWSClientRuntime +import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -33,7 +33,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { // Test all the combinations for preference types for smsPreference in allSMSPreferences { for totpPreference in allTOTPPreference { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockGetUserAttributeResponse: { request in return .init( userMFASettingList: ["SOFTWARE_TOKEN_MFA", "SMS_MFA"] @@ -42,18 +42,22 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { mockSetUserMFAPreferenceResponse: { request in XCTAssertEqual( request.smsMfaSettings, - smsPreference.smsSetting()) + smsPreference.smsSetting() + ) XCTAssertEqual( request.softwareTokenMfaSettings, - totpPreference.softwareTokenSetting()) + totpPreference.softwareTokenSetting() + ) return .init() - }) + } + ) do { try await plugin.updateMFAPreference( sms: smsPreference, - totp: totpPreference) + totp: totpPreference + ) } catch { XCTFail("Received failure with error \(error)") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift index 0cd03bf4e9..ad2f071123 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift @@ -7,11 +7,11 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider import AWSClientRuntime +import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -27,7 +27,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testSuccessfulVerifyTOTPSetupRequest() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in XCTAssertEqual(request.userCode, "123456") XCTAssertEqual(request.friendlyDeviceName, "device") @@ -37,7 +37,8 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { do { let pluginOptions = VerifyTOTPSetupOptions(friendlyDeviceName: "device") try await plugin.verifyTOTPSetup( - code: "123456", options: .init(pluginOptions: pluginOptions)) + code: "123456", options: .init(pluginOptions: pluginOptions) + ) } catch { XCTFail("Received failure with error \(error)") } @@ -56,7 +57,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithForbiddenException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ForbiddenException( message: "Exception" @@ -88,7 +89,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -120,7 +121,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -154,7 +155,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -184,7 +185,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -216,7 +217,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .resourceNotFound as underlyingError /// func testVerifyTOTPSetupInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.ResourceNotFoundException( message: "Exception" @@ -249,7 +250,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// func testVerifyTOTPSetupWithUnknownException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSClientRuntime.UnknownAWSHTTPServiceError( httpResponse: .init(body: .empty, statusCode: .ok), @@ -281,7 +282,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testVerifyTOTPSetupInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -313,7 +314,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .softwareTokenMFANotEnabled as underlyingError /// func testVerifyTOTPSetupInWithEnableSoftwareTokenMFAException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.EnableSoftwareTokenMFAException( message: "Exception" @@ -345,7 +346,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .passwordResetRequired as underlyingError /// func testVerifyTOTPSetupInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -377,7 +378,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .requestLimitExceeded as underlyingError /// func testVerifyTOTPSetupInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -409,7 +410,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .userNotFound as underlyingError /// func testVerifyTOTPSetupInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" @@ -441,7 +442,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error with .userNotConfirmed as underlyingError /// func testVerifyTOTPSetupInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -473,7 +474,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - I should get a .service error /// func testVerifyTOTPSetupInWithInvalidUserPoolConfigurationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift index da1a27739a..b41c051a4d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift @@ -7,23 +7,27 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length class AuthenticationProviderConfirmSigninTests: BasePluginTest { - + override var initialState: AuthState { AuthState.configured( AuthenticationState.signingIn( - .resolvingChallenge(.waitingForAnswer(.testData(), .apiBased(.userSRP)), - .smsMfa, .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .resolvingChallenge( + .waitingForAnswer(.testData(), .apiBased(.userSRP)), + .smsMfa, + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) } - + /// Test a successful confirmSignIn call with .done as next step /// /// - Given: an auth plugin with mocked service. Mocked service calls should mock a successful response @@ -33,14 +37,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a successful result with .done as the next step /// func testSuccessfulConfirmSignIn() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .smsMfa) XCTAssertEqual(request.challengeResponses?["SMS_MFA_CODE"], "code") return .testData() }) - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") guard case .done = confirmSignInResult.nextStep else { @@ -52,7 +56,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Received failure with error \(error)") } } - + /// Test a confirmSignIn call with an empty confirmation code /// /// - Given: an auth plugin with mocked service. Mocked service should mock a successful response @@ -62,13 +66,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get an .validation error /// func testConfirmSignInWithEmptyResponse() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "") XCTFail("Should not succeed") @@ -79,7 +83,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with an empty confirmation code followed by a second valid confirmSignIn call /// /// - Given: an auth plugin with mocked service. Mocked service should mock a successful response @@ -89,12 +93,12 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a successful result with .done as the next step /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "") XCTFail("Should not succeed") @@ -103,7 +107,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Should produce validation error instead of \(error)") return } - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") XCTAssertTrue(confirmSignInResult.isSignedIn, "Signin result should be complete") @@ -125,10 +129,11 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { let confirmSignInOptions = AWSAuthConfirmSignInOptions( userAttributes: [.init(.email, value: "some@some.com")], - metadata: ["metadata": "test"]) + metadata: ["metadata": "test"] + ) - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(confirmSignInOptions.metadata, input.clientMetadata) XCTAssertEqual(input.challengeResponses?["userAttributes.email"], "some@some.com") @@ -138,7 +143,8 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { do { let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "code", - options: .init(pluginOptions: confirmSignInOptions)) + options: .init(pluginOptions: confirmSignInOptions) + ) guard case .done = confirmSignInResult.nextStep else { XCTFail("Result should be .done for next step") return @@ -148,9 +154,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Received failure with error \(error)") } } - + // MARK: Service error handling test - + /// Test a confirmSignIn call with aliasExistsException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -161,14 +167,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .aliasExists as underlyingError /// func testConfirmSignInWithAliasExistsException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -180,7 +186,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTAssertEqual(underlyingError as? AWSCognitoAuthError, .aliasExists) } } - + /// Test a confirmSignIn call with CodeMismatchException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -191,13 +197,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -214,7 +220,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -234,7 +240,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) @@ -247,7 +253,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } - + /// Test a confirmSignIn call with CodeExpiredException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -258,14 +264,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .codeExpired as underlyingError /// func testConfirmSignInWithExpiredCodeException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.ExpiredCodeException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -280,7 +286,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InternalErrorException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a InternalErrorException response @@ -290,14 +296,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get an .unknown error /// func testConfirmSignInWithInternalErrorException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -308,7 +314,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidLambdaResponseException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -319,13 +325,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -340,7 +346,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidParameterException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -352,14 +358,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .invalidParameter as underlyingError /// func testConfirmSignInWithInvalidParameterException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -374,7 +380,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidPasswordException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -386,14 +392,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .invalidPassword as underlyingError /// func testConfirmSignInWithInvalidPasswordException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -408,7 +414,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidSmsRoleAccessPolicy response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -419,13 +425,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -440,7 +446,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with InvalidSmsRoleTrustRelationship response from service /// /// - Given: Given an auth plugin with mocked service. Mocked service should mock a @@ -451,13 +457,13 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -486,7 +492,8 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -496,8 +503,10 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -505,7 +514,8 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: "code") @@ -530,14 +540,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .mfaMethodNotFound as underlyingError /// func testCofirmSignInWithMFAMethodNotFoundException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should not succeed") @@ -552,7 +562,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with NotAuthorizedException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -564,14 +574,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .notAuthorized error /// func testConfirmSignInWithNotAuthorizedException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -582,7 +592,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn with PasswordResetRequiredException from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -594,14 +604,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .resetPassword as next step /// func testConfirmSignInWithPasswordResetRequiredException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" ) }) - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") guard case .resetPassword = confirmSignInResult.nextStep else { @@ -613,7 +623,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } - + /// Test a confirmSignIn call with SoftwareTokenMFANotFoundException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -625,14 +635,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .softwareTokenMFANotEnabled as underlyingError /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -647,7 +657,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with TooManyRequestsException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -659,14 +669,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .requestLimitExceeded as underlyingError /// func testConfirmSignInWithTooManyRequestsException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -681,7 +691,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with UnexpectedLambdaException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -693,14 +703,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithUnexpectedLambdaException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -715,7 +725,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with UserLambdaValidationException response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -727,14 +737,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithUserLambdaValidationException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") @@ -749,7 +759,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with UserNotConfirmedException response from service /// /// - Given: Given an auth plugin with mocked service. Mocked service should mock a @@ -761,14 +771,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get .confirmSignUp as next step /// func testConfirmSignInWithUserNotConfirmedException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" ) }) - + do { let confirmSignInResult = try await plugin.confirmSignIn(challengeResponse: "code") guard case .confirmSignUp = confirmSignInResult.nextStep else { @@ -779,7 +789,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Should not return error \(error)") } } - + /// Test a confirmSignIn call with UserNotFound response from service /// /// - Given: an auth plugin with mocked service. Mocked service should mock a @@ -791,14 +801,14 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { /// - I should get a .userNotFound error /// func testConfirmSignInWithUserNotFoundException() async { - - self.mockIdentityProvider = MockIdentityProvider( + + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" ) }) - + do { _ = try await plugin.confirmSignIn(challengeResponse: "code") XCTFail("Should return an error if the result from service is invalid") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift index de2caa7054..8b61c473ad 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift @@ -5,14 +5,14 @@ // SPDX-License-Identifier: Apache-2.0 // +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider class AWSAuthMigrationSignInTaskTests: XCTestCase { @@ -30,25 +30,30 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } let mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -56,7 +61,8 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } override func tearDown() { @@ -68,10 +74,12 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - return .init(authenticationResult: .init(accessToken: Defaults.validAccessToken, - expiresIn: 2, - idToken: "idToken", - refreshToken: "refreshToken")) + return .init(authenticationResult: .init( + accessToken: Defaults.validAccessToken, + expiresIn: 2, + idToken: "idToken", + refreshToken: "refreshToken" + )) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift index 3968b20914..096b5ff865 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInOptionsTestCase.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthSignInOptionsTestCase: BasePluginTest { override var initialState: AuthState { @@ -24,7 +24,8 @@ class AWSAuthSignInOptionsTestCase: BasePluginTest { authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -33,10 +34,12 @@ class AWSAuthSignInOptionsTestCase: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) } @@ -174,7 +177,7 @@ class AWSAuthSignInOptionsTestCase: BasePluginTest { } } -fileprivate extension AuthState { +private extension AuthState { var authenticationState: AuthenticationState? { if case .configured(let authenticationState, _) = self { return authenticationState @@ -183,7 +186,7 @@ fileprivate extension AuthState { } } -fileprivate extension AuthenticationState { +private extension AuthenticationState { var signInEvent: SignInEventData? { if case .signingIn(.signingInWithSRP(_, let eventData)) = self { return eventData diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift index 1b4a9c973d..36df741b80 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthSignInPluginTests: BasePluginTest { @@ -29,13 +29,14 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSuccessfulSignIn() async { let clientMetadata = ["somekey": "somevalue"] - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return RespondToAuthChallengeOutput( @@ -45,10 +46,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: clientMetadata) @@ -77,12 +80,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSuccessfulSignInWithAuthFlow() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -91,10 +95,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -126,7 +132,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithEmptyUsername() async { - self.mockIdentityProvider = MockIdentityProvider() + mockIdentityProvider = MockIdentityProvider() let options = AuthSignInRequest.Options() @@ -152,16 +158,18 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithEmptyPassword() async { - self.mockIdentity = MockIdentity( + mockIdentity = MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -170,10 +178,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -200,7 +210,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput() }) let options = AuthSignInRequest.Options() @@ -226,7 +236,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSecondSignInAfterSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput() }) let options = AuthSignInRequest.Options() @@ -234,12 +244,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { let result = try await plugin.signIn(username: "username", password: "password", options: options) XCTFail("Should not receive a success response \(result)") } catch { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -248,10 +259,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) do { @@ -274,18 +287,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepSMS() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: [:], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -313,20 +328,22 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testCustomAuthWithAdditionalInfo() async { let clientMetadata = ["somekey": "somevalue"] - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(clientMetadata, input.clientMetadata) return RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .customChallenge, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -362,18 +379,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSMSMFAWithAdditionalInfo() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -405,18 +424,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepNewPassword() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .newPasswordRequired, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -444,18 +465,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testNewPasswordWithAdditionalInfo() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .newPasswordRequired, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -487,18 +510,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepCustomChallenge() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .customChallenge, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(authFlowType: .customWithSRP) @@ -526,18 +551,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextStepUnknown() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .sdkUnknown("no idea"), challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -563,18 +590,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNextDeviceSRP() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .deviceSrpAuth, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .devicePasswordVerifier, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -586,7 +615,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service = error else { @@ -607,18 +637,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithCustomAuthIncorrectCode() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .customChallenge, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions( @@ -630,7 +662,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) guard case .confirmSignInWithCustomChallenge = result.nextStep, case let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "245234" @@ -647,18 +680,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepTOTP() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .softwareTokenMfa, challengeParameters: ["paramKey": "value"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -676,18 +711,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepSelectMFAType() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .selectMfaType, challengeParameters: ["MFAS_CAN_CHOOSE": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"], - session: "session") + session: "session" + ) }) let options = AuthSignInRequest.Options() @@ -707,18 +744,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepSetupMFA() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"], - session: "session") + session: "session" + ) }, mockAssociateSoftwareTokenResponse: { _ in return .init(secretCode: "123456", session: "session") } ) @@ -740,18 +779,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNextStepSetupMFAWithUnavailableMFAType() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\"]"], - session: "session") + session: "session" + ) }, mockAssociateSoftwareTokenResponse: { _ in return .init(secretCode: "123456", session: "session") } ) @@ -782,7 +823,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException() }) @@ -810,7 +851,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException() }) @@ -820,7 +861,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .lambda = (underlyingError as? AWSCognitoAuthError) else { + case .lambda = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce lambda error but instead produced \(error)") return } @@ -839,7 +881,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException() }) @@ -849,7 +891,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce invalidParameter error but instead produced \(error)") return } @@ -868,7 +911,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidUserPoolConfigurationException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException() }) @@ -896,7 +939,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() }) @@ -924,7 +967,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) @@ -953,7 +996,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithPasswordResetRequiredException2() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw try await AWSCognitoIdentityProvider.PasswordResetRequiredException( httpResponse: .init(body: .empty, statusCode: .badRequest), decoder: nil, @@ -987,7 +1030,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) @@ -997,7 +1040,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .resourceNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .resourceNotFound = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce resourceNotFound error but instead produced \(error)") return } @@ -1016,7 +1060,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException() }) @@ -1026,7 +1070,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .requestLimitExceeded = (underlyingError as? AWSCognitoAuthError) else { + case .requestLimitExceeded = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce requestLimitExceeded error but instead produced \(error)") return } @@ -1045,7 +1090,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUnexpectedLambdaException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException() }) @@ -1055,7 +1100,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .lambda = (underlyingError as? AWSCognitoAuthError) else { + case .lambda = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce lambda error but instead produced \(error)") return } @@ -1074,7 +1120,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserLambdaValidationException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException() }) @@ -1084,7 +1130,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .lambda = (underlyingError as? AWSCognitoAuthError) else { + case .lambda = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce lambda error but instead produced \(error)") return } @@ -1102,7 +1149,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// - I should get a .confirmSignUp as next step /// func testSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) @@ -1131,7 +1178,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserNotConfirmedException2() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw try await AWSCognitoIdentityProvider.UserNotConfirmedException( httpResponse: .init(body: .empty, statusCode: .badRequest) ) @@ -1162,7 +1209,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException() }) @@ -1172,7 +1219,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .userNotFound = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce userNotFound error but instead produced \(error)") return } @@ -1193,12 +1241,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithAliasExistsException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException() }) @@ -1209,7 +1258,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .aliasExists = (underlyingError as? AWSCognitoAuthError) else { + case .aliasExists = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce aliasExists error but instead produced \(error)") return } @@ -1228,12 +1278,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithInvalidPasswordException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException() }) @@ -1244,7 +1295,8 @@ class AWSAuthSignInPluginTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidPassword = (underlyingError as? AWSCognitoAuthError) else { + case .invalidPassword = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce invalidPassword error but instead produced \(error)") return } @@ -1262,18 +1314,20 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testRestartSignIn() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: ["somekey": "somevalue"]) @@ -1286,12 +1340,13 @@ class AWSAuthSignInPluginTests: BasePluginTest { return } XCTAssertFalse(result.isSignedIn) - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -1300,10 +1355,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let result2 = try await plugin.signIn(username: "username2", password: "password", options: options) guard case .done = result2.nextStep else { @@ -1329,22 +1386,24 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSuccessfulSignInWithFailingIdentity() async { - self.mockIdentity = MockIdentity( + mockIdentity = MockIdentity( mockGetIdResponse: { _ in throw AWSCognitoIdentity.InvalidParameterException( message: "Invalid parameter passed" ) }, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) - self.mockIdentityProvider = MockIdentityProvider(mockRevokeTokenResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockRevokeTokenResponse: { _ in RevokeTokenOutput() }, mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .init( @@ -1353,10 +1412,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { idToken: "idToken", newDeviceMetadata: nil, refreshToken: "refreshToken", - tokenType: ""), + tokenType: "" + ), challengeName: .none, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: ["somekey": "somevalue"]) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift index 98849dce07..89551406da 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -25,8 +25,10 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { .apiBased(.userSRP) ), .totpMFA, - .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) } /// Test a successful confirmSignIn call with .done as next step @@ -39,7 +41,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testSuccessfulConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .softwareTokenMfa) XCTAssertEqual(request.challengeResponses?["SOFTWARE_TOKEN_MFA_CODE"], "code") @@ -69,7 +71,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithEmptyResponse() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -96,7 +98,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) @@ -131,10 +133,11 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { let confirmSignInOptions = AWSAuthConfirmSignInOptions( userAttributes: [.init(.email, value: "some@some.com")], - metadata: ["metadata": "test"]) + metadata: ["metadata": "test"] + ) - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { input in XCTAssertEqual(confirmSignInOptions.metadata, input.clientMetadata) XCTAssertEqual(input.challengeResponses?["userAttributes.email"], "some@some.com") @@ -144,7 +147,8 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { do { let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "code", - options: .init(pluginOptions: confirmSignInOptions)) + options: .init(pluginOptions: confirmSignInOptions) + ) guard case .done = confirmSignInResult.nextStep else { XCTFail("Result should be .done for next step") return @@ -168,7 +172,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithAliasExistsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException( message: "Exception" @@ -200,7 +204,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -232,7 +236,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -252,7 +256,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData() }) @@ -277,7 +281,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithExpiredCodeException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.ExpiredCodeException( message: "Exception" @@ -309,7 +313,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -337,7 +341,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( message: "Exception" @@ -371,7 +375,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -405,7 +409,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidPasswordException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "Exception" @@ -437,7 +441,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( message: "Exception" @@ -469,7 +473,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( message: "Exception" @@ -504,7 +508,8 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -514,8 +519,10 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -523,7 +530,8 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: "code") @@ -549,7 +557,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testCofirmSignInWithMFAMethodNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( message: "Exception" @@ -583,7 +591,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -613,7 +621,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -644,7 +652,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -678,7 +686,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -712,7 +720,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUnexpectedLambdaException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException( message: "Exception" @@ -746,7 +754,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUserLambdaValidationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException( message: "Exception" @@ -780,7 +788,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -810,7 +818,7 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift index da3e22fa6c..55033052ee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -25,8 +25,10 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { .apiBased(.userSRP) ), .selectMFAType, - .apiBased(.userSRP))), - AuthorizationState.sessionEstablished(.testData)) + .apiBased(.userSRP) + )), + AuthorizationState.sessionEstablished(.testData) + ) } /// Test a successful confirmSignIn call with .confirmSignInWithSMSMFACode as next step @@ -39,7 +41,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testSuccessfulConfirmSignInWithSMSAsMFASelection() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .selectMfaType) @@ -71,7 +73,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testSuccessfulConfirmSignInWithTOTPAsMFASelection() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.challengeName, .selectMfaType) @@ -103,7 +105,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidMFASelection() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -119,7 +121,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { } } } - + /// Test a confirmSignIn call with an empty confirmation code /// @@ -131,7 +133,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithEmptyResponse() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -158,7 +160,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData(challenge: .softwareTokenMfa) }) @@ -198,7 +200,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithAliasExistsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.AliasExistsException( message: "Exception" @@ -230,7 +232,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -264,7 +266,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I invoke confirmSignIn with a valid MFA selection, I should get a successful result /// func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -284,7 +286,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in return .testData(challenge: .softwareTokenMfa) }) @@ -313,7 +315,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithExpiredCodeException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.ExpiredCodeException( message: "Exception" @@ -345,7 +347,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -373,7 +375,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .lambda as underlyingError /// func testConfirmSignInWithInvalidLambdaResponseException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( message: "Exception" @@ -407,7 +409,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -441,7 +443,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidPasswordException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "Exception" @@ -473,7 +475,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( message: "Exception" @@ -505,7 +507,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// - I should get a .service error with .smsRole as underlyingError /// func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( message: "Exception" @@ -540,7 +542,8 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -550,8 +553,10 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -559,7 +564,8 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: MFAType.totp.challengeResponse) @@ -585,7 +591,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testCofirmSignInWithMFAMethodNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( message: "Exception" @@ -619,7 +625,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -649,7 +655,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -680,7 +686,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -714,7 +720,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -748,7 +754,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUnexpectedLambdaException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UnexpectedLambdaException( message: "Exception" @@ -782,7 +788,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUserLambdaValidationException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserLambdaValidationException( message: "Exception" @@ -816,7 +822,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -846,7 +852,7 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift index b0ab9ad69a..bc27e4a470 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift @@ -7,10 +7,10 @@ import Foundation -import XCTest import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import XCTest +@testable import AWSCognitoAuthPlugin // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -23,9 +23,12 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { .waitingForAnswer(.init( secretCode: "sharedSecret", session: "session", - username: "username")), - .testData)), - AuthorizationState.sessionEstablished(.testData)) + username: "username" + )), + .testData + )), + AuthorizationState.sessionEstablished(.testData) + ) } /// Test a successful confirmSignIn call with .done as next step @@ -38,7 +41,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testSuccessfulTOTPMFASetupStep() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.session, "verifiedSession") return .testData() @@ -55,7 +58,8 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { let pluginOptions = AWSAuthConfirmSignInOptions(friendlyDeviceName: "device") let confirmSignInResult = try await plugin.confirmSignIn( challengeResponse: "123456", - options: .init(pluginOptions: pluginOptions)) + options: .init(pluginOptions: pluginOptions) + ) guard case .done = confirmSignInResult.nextStep else { XCTFail("Result should be .done for next step") return @@ -77,7 +81,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithEmptyResponse() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in XCTFail("Cognito service should not be called") return .testData() @@ -104,7 +108,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testSuccessfullyConfirmSignInAfterAFailedConfirmSignIn() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.session, "verifiedSession") return .testData() @@ -150,7 +154,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -183,9 +187,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// - I should get a .service error with .codeMismatch as underlyingError /// Then: /// - RETRY SHOULD ALSO SUCCEED - /// + /// func testConfirmSignInRetryWithCodeMismatchException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.CodeMismatchException( message: "Exception" @@ -206,7 +210,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { return } - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { request in XCTAssertEqual(request.session, "verifiedSession") return .testData() @@ -237,7 +241,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InternalErrorException( message: "Exception" @@ -268,7 +272,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "Exception" @@ -303,7 +307,8 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { let identityPoolConfigData = Defaults.makeIdentityConfigData() let authorizationEnvironment = BasicAuthorizationEnvironment( identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: Defaults.makeIdentity) + cognitoIdentityFactory: Defaults.makeIdentity + ) let environment = AuthEnvironment( configuration: .identityPools(identityPoolConfigData), userPoolConfigData: nil, @@ -313,8 +318,10 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { credentialsClient: Defaults.makeCredentialStoreOperationBehavior(), logger: Amplify.Logging.logger(forCategory: "awsCognitoAuthPluginTest") ) - let stateMachine = Defaults.authStateMachineWith(environment: environment, - initialState: .notConfigured) + let stateMachine = Defaults.authStateMachineWith( + environment: environment, + initialState: .notConfigured + ) let plugin = AWSCognitoAuthPlugin() plugin.configure( authConfiguration: .identityPools(identityPoolConfigData), @@ -322,7 +329,8 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) do { _ = try await plugin.confirmSignIn(challengeResponse: "") @@ -348,7 +356,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "Exception" @@ -378,7 +386,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithPasswordResetRequiredException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "Exception" @@ -409,7 +417,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( message: "Exception" @@ -443,7 +451,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithTooManyRequestsException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "Exception" @@ -477,7 +485,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotConfirmedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "Exception" @@ -507,7 +515,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { /// func testConfirmSignInWithUserNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "Exception" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift index 387a70f340..732a338857 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest +import AWSClientRuntime import AWSCognitoIdentity +import AWSCognitoIdentityProvider +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import AWSClientRuntime class SignInSetUpTOTPTests: BasePluginTest { @@ -28,16 +28,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// - I should get a .continueSignInWithTOTPSetup response /// func testSuccessfulTOTPSetupChallenge() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init(secretCode: "sharedSecret", session: "newSession") }) @@ -47,7 +49,8 @@ class SignInSetUpTOTPTests: BasePluginTest { let result = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) guard case .continueSignInWithTOTPSetup(let totpDetails) = result.nextStep else { XCTFail("Result should be .continueSignInWithTOTPSetup for next step") return @@ -62,18 +65,20 @@ class SignInSetUpTOTPTests: BasePluginTest { func testSignInWithNextStepSetupMFAWithUnavailableMFAType() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\"]"], - session: "session") + session: "session" + ) }, mockAssociateSoftwareTokenResponse: { _ in return .init(secretCode: "123456", session: "session") } ) @@ -101,16 +106,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// - I should get a .continueSignInWithTOTPSetup response /// func testSuccessfulTOTPSetupChallengeWithEmptyMFASCanSetup() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: [:]) + challengeParameters: [:] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init(secretCode: "sharedSecret", session: "newSession") }) @@ -120,7 +127,8 @@ class SignInSetUpTOTPTests: BasePluginTest { _ = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) XCTFail("Should throw an error") } catch { guard case AuthError.service(_, _, _) = error else { @@ -142,16 +150,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: [:]) + challengeParameters: [:] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init() }) @@ -161,7 +171,8 @@ class SignInSetUpTOTPTests: BasePluginTest { _ = try await plugin.signIn( username: "username", password: "password", - options: options) + options: options + ) XCTFail("Should throw an error") } catch { guard case AuthError.service(_, _, _) = error else { @@ -182,16 +193,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSecondSignInAfterSignInWithInvalidResult() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init() }) @@ -200,16 +213,18 @@ class SignInSetUpTOTPTests: BasePluginTest { let result = try await plugin.signIn(username: "username", password: "password", options: options) XCTFail("Should not receive a success response \(result)") } catch { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in return .init(secretCode: "sharedSecret", session: "newSession") }) @@ -243,16 +258,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.InternalErrorException() }) @@ -281,16 +298,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithInvalidParameterException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.InvalidParameterException() }) @@ -301,7 +320,8 @@ class SignInSetUpTOTPTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce invalidParameter error but instead produced \(error)") return } @@ -320,16 +340,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.NotAuthorizedException() }) @@ -358,16 +380,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithResourceNotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) @@ -378,7 +402,8 @@ class SignInSetUpTOTPTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .resourceNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .resourceNotFound = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce resourceNotFound error but instead produced \(error)") return } @@ -397,16 +422,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithConcurrentModificationException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.ConcurrentModificationException() }) @@ -435,16 +462,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithForbiddenException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.ForbiddenException() }) @@ -473,16 +502,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithSoftwareTokenMFANotFoundException() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException() }) @@ -493,7 +524,8 @@ class SignInSetUpTOTPTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .softwareTokenMFANotEnabled = (underlyingError as? AWSCognitoAuthError) else { + case .softwareTokenMFANotEnabled = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should produce resourceNotFound error but instead produced \(error)") return } @@ -512,16 +544,18 @@ class SignInSetUpTOTPTests: BasePluginTest { /// func testSignInWithUnknownAWSHttpServiceError() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { input in return InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { input in return .testData( challenge: .mfaSetup, - challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) + challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"] + ) }, mockAssociateSoftwareTokenResponse: { input in throw AWSClientRuntime.UnknownAWSHTTPServiceError( httpResponse: .init(body: .empty, statusCode: .ok), diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift index 92812c342d..1d8290387f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift @@ -5,13 +5,13 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest +import AWSClientRuntime import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime -import AWSClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthConfirmSignUpAPITests: BasePluginTest { @@ -23,7 +23,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSuccessfulSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { request in XCTAssertNil(request.clientMetadata) XCTAssertNil(request.forceAliasCreation) @@ -31,10 +31,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { } ) - let result = try await self.plugin.confirmSignUp( + let result = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "123456", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") @@ -45,7 +46,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSuccessfulSignUpWithOptions() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { request in XCTAssertNotNil(request.clientMetadata) XCTAssertEqual(request.clientMetadata?["key"], "value") @@ -56,12 +57,14 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { let pluginOptions = AWSAuthConfirmSignUpOptions( metadata: ["key": "value"], - forceAliasCreation: true) + forceAliasCreation: true + ) let options = AuthConfirmSignUpRequest.Options(pluginOptions: pluginOptions) - let result = try await self.plugin.confirmSignUp( + let result = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "123456", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") @@ -72,7 +75,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithEmptyUsername() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in XCTFail("Sign up API should not be called") return .init() @@ -80,10 +83,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "", confirmationCode: "123456", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { @@ -96,7 +100,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithEmptyConfirmationCode() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in XCTFail("Sign up API should not be called") return .init() @@ -104,10 +108,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { @@ -137,32 +142,36 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { for errorToTest in errorsToTest { await validateConfirmSignUpServiceErrors( confirmSignUpOutputError: errorToTest.confirmSignUpOutputError, - expectedCognitoError: errorToTest.cognitoError) + expectedCognitoError: errorToTest.cognitoError + ) } } func testSignUpWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .notAuthorized(let errorDescription, - let recoverySuggestion, - let notAuthorizedError) = authError else { + guard case .notAuthorized( + let errorDescription, + let recoverySuggestion, + let notAuthorizedError + ) = authError else { XCTFail("Auth error should be of type notAuthorized") return } @@ -175,7 +184,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw try await AWSCognitoIdentityProvider.InternalErrorException( httpResponse: .init(body: .empty, statusCode: .accepted) @@ -184,10 +193,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") @@ -205,7 +215,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpWithUnknownErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw AWSClientRuntime.UnknownAWSHTTPServiceError.init( httpResponse: .init(body: .empty, statusCode: .accepted), @@ -217,10 +227,11 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") @@ -238,27 +249,31 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func validateConfirmSignUpServiceErrors( confirmSignUpOutputError: Error, - expectedCognitoError: AWSCognitoAuthError) async { - self.mockIdentityProvider = MockIdentityProvider( + expectedCognitoError: AWSCognitoAuthError + ) async { + mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in throw confirmSignUpOutputError } ) do { - let _ = try await self.plugin.confirmSignUp( + let _ = try await plugin.confirmSignUp( for: "jeffb", confirmationCode: "12345", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .service(let errorMessage, - let recovery, - let serviceError) = authError else { + guard case .service( + let errorMessage, + let recovery, + let serviceError + ) = authError else { XCTFail("Auth error should be of type service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift index 62a488fce2..d21c6d6c53 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift @@ -11,13 +11,13 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSClientRuntime +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime -import AWSClientRuntime -import AWSCognitoIdentityProvider class AWSAuthConfirmSignUpTaskTests: XCTestCase { @@ -39,9 +39,11 @@ class AWSAuthConfirmSignUpTaskTests: XCTestCase { let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockConfirmSignUpResponse: confirmSignUp)}) - let request = AuthConfirmSignUpRequest(username: "jeffb", - code: "213", - options: AuthConfirmSignUpRequest.Options()) + let request = AuthConfirmSignUpRequest( + username: "jeffb", + code: "213", + options: AuthConfirmSignUpRequest.Options() + ) let task = AWSAuthConfirmSignUpTask(request, authEnvironment: authEnvironment) let confirmSignUpResult = try await task.value print("Confirm Sign Up Result: \(confirmSignUpResult)") @@ -63,9 +65,11 @@ class AWSAuthConfirmSignUpTaskTests: XCTestCase { let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockConfirmSignUpResponse: confirmSignUp)}) - let request = AuthConfirmSignUpRequest(username: "jeffb", - code: "213", - options: AuthConfirmSignUpRequest.Options()) + let request = AuthConfirmSignUpRequest( + username: "jeffb", + code: "213", + options: AuthConfirmSignUpRequest.Options() + ) do { let task = AWSAuthConfirmSignUpTask(request, authEnvironment: authEnvironment) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift index 9ad2404e72..6e46895c36 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { @@ -61,9 +61,11 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { /// func testResendSignupCodeWithSuccess() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: nil, - deliveryMedium: .email, - destination: nil) + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: nil, + deliveryMedium: .email, + destination: nil + ) mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutput: { _ in ResendConfirmationCodeOutput(codeDeliveryDetails: codeDeliveryDetails) @@ -87,9 +89,11 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { /// func testResendSignupCodeWithEmptyUsername() async throws { - let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType(attributeName: nil, - deliveryMedium: .email, - destination: nil) + let codeDeliveryDetails = CognitoIdentityProviderClientTypes.CodeDeliveryDetailsType( + attributeName: nil, + deliveryMedium: .email, + destination: nil + ) mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutput: { _ in ResendConfirmationCodeOutput(codeDeliveryDetails: codeDeliveryDetails) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift index 206a32f568..6194d30514 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity -@testable import Amplify -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import XCTest +@testable import Amplify +@testable import AWSCognitoAuthPlugin class AWSAuthSignUpAPITests: BasePluginTest { @@ -24,18 +24,21 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSuccessfulSignUp() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in - return .init(codeDeliveryDetails: nil, - userConfirmed: true, - userSub: UUID().uuidString) + return .init( + codeDeliveryDetails: nil, + userConfirmed: true, + userSub: UUID().uuidString + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: options) + options: options + ) guard case .done = result.nextStep else { XCTFail("Result should be .done for next step") @@ -46,17 +49,18 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpWithEmptyUsername() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in XCTFail("Sign up API should not be called") return .init(codeDeliveryDetails: nil, userConfirmed: true, userSub: nil) } ) - do { _ = try await self.plugin.signUp( + do { _ = try await plugin.signUp( username: "", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { @@ -69,22 +73,25 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpWithUserConfirmationRequired() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in return .init( codeDeliveryDetails: .init( attributeName: "some attribute", deliveryMedium: .email, - destination: "random@random.com"), + destination: "random@random.com" + ), userConfirmed: false, - userSub: "userId") + userSub: "userId" + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: options) + options: options + ) guard case .confirmUser(let deliveryDetails, let additionalInfo, let userId) = result.nextStep else { XCTFail("Result should be .confirmUser for next step") @@ -100,19 +107,21 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpNilCognitoResponse() async throws { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in return .init( codeDeliveryDetails: nil, userConfirmed: false, - userSub: nil) + userSub: nil + ) } ) - let result = try await self.plugin.signUp( + let result = try await plugin.signUp( username: "jeffb", password: "Valid&99", - options: options) + options: options + ) guard case .confirmUser(let deliveryDetails, let additionalInfo, let userId) = result.nextStep else { XCTFail("Result should be .done for next step") @@ -205,32 +214,36 @@ class AWSAuthSignUpAPITests: BasePluginTest { for errorToTest in errorsToTest { await validateSignUpServiceErrors( signUpOutputError: errorToTest.signUpOutputError, - expectedCognitoError: errorToTest.cognitoError) + expectedCognitoError: errorToTest.cognitoError + ) } } func testSignUpWithNotAuthorizedException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) do { - _ = try await self.plugin.signUp( + _ = try await plugin.signUp( username: "username", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .notAuthorized(let errorDescription, - let recoverySuggestion, - let notAuthorizedError) = authError else { + guard case .notAuthorized( + let errorDescription, + let recoverySuggestion, + let notAuthorizedError + ) = authError else { XCTFail("Auth error should be of type notAuthorized") return } @@ -243,7 +256,7 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpWithInternalErrorException() async { - self.mockIdentityProvider = MockIdentityProvider( + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in throw try await AWSCognitoIdentityProvider.InternalErrorException( httpResponse: .init(body: .empty, statusCode: .accepted) @@ -252,10 +265,11 @@ class AWSAuthSignUpAPITests: BasePluginTest { ) do { - _ = try await self.plugin.signUp( + _ = try await plugin.signUp( username: "username", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") @@ -273,27 +287,31 @@ class AWSAuthSignUpAPITests: BasePluginTest { func validateSignUpServiceErrors( signUpOutputError: Error, - expectedCognitoError: AWSCognitoAuthError) async { - self.mockIdentityProvider = MockIdentityProvider( + expectedCognitoError: AWSCognitoAuthError + ) async { + mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in throw signUpOutputError } ) do { - _ = try await self.plugin.signUp( + _ = try await plugin.signUp( username: "username", password: "Valid&99", - options: options) + options: options + ) } catch { guard let authError = error as? AuthError else { XCTFail("Should throw Auth error") return } - guard case .service(let errorMessage, - let recovery, - let serviceError) = authError else { + guard case .service( + let errorMessage, + let recovery, + let serviceError + ) = authError else { XCTFail("Auth error should be of type service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift index df79b450dc..19404c3d79 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSClientRuntime +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime -import AWSClientRuntime import AWSCognitoIdentityProvider @@ -34,9 +34,11 @@ class AWSAuthSignUpTaskTests: XCTestCase { return .init(codeDeliveryDetails: nil, userConfirmed: true, userSub: UUID().uuidString) } - let request = AuthSignUpRequest(username: "jeffb", - password: "Valid&99", - options: AuthSignUpRequest.Options()) + let request = AuthSignUpRequest( + username: "jeffb", + password: "Valid&99", + options: AuthSignUpRequest.Options() + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockSignUpResponse: signUp)}) let task = AWSAuthSignUpTask(request, authEnvironment: authEnvironment) @@ -58,9 +60,11 @@ class AWSAuthSignUpTaskTests: XCTestCase { ) } - let request = AuthSignUpRequest(username: "jeffb", - password: "Valid&99", - options: AuthSignUpRequest.Options()) + let request = AuthSignUpRequest( + username: "jeffb", + password: "Valid&99", + options: AuthSignUpRequest.Options() + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockSignUpResponse: signUp)}) @@ -85,9 +89,11 @@ class AWSAuthSignUpTaskTests: XCTestCase { return .init(codeDeliveryDetails: nil, userConfirmed: true, userSub: UUID().uuidString) } - let request = AuthSignUpRequest(username: "jeffb", - password: "Valid&99", - options: AuthSignUpRequest.Options()) + let request = AuthSignUpRequest( + username: "jeffb", + password: "Valid&99", + options: AuthSignUpRequest.Options() + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: {MockIdentityProvider(mockSignUpResponse: signUp)}) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift index b8fc44a77d..925d882821 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class DeviceBehaviorFetchDevicesTests: BasePluginTest { @@ -85,7 +85,8 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { deviceLastAuthenticatedDate: dateToTest, deviceLastModifiedDate: dateToTest ) - ], paginationToken: nil) + ], paginationToken: nil + ) } ) let listDevicesResult = try await plugin.fetchDevices() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift index a8cc6e99cc..3435c5e5bc 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class DeviceBehaviorForgetDeviceTests: BasePluginTest { @@ -47,12 +47,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { /// func testSuccessfulForgetDevice() async throws { - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) } @@ -108,12 +110,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error") @@ -152,7 +156,8 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { XCTFail("Should return an error if the result from service is invalid") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Underlying error should be invalidParameter \(error)") return } @@ -178,18 +183,21 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .invalidParameter = (underlyingError as? AWSCognitoAuthError) else { + case .invalidParameter = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Underlying error should be invalidParameter \(error)") return } @@ -245,12 +253,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -311,12 +321,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -381,12 +393,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -455,12 +469,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -529,12 +545,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -603,12 +621,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") @@ -677,12 +697,14 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { ) } ) - let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", - name: "name", - attributes: nil, - createdDate: nil, - lastAuthenticatedDate: nil, - lastModifiedDate: nil) + let awsAuthDevice = AWSAuthDevice( + id: "authDeviceID", + name: "name", + attributes: nil, + createdDate: nil, + lastAuthenticatedDate: nil, + lastModifiedDate: nil + ) do { try await plugin.forgetDevice(awsAuthDevice, options: AuthForgetDeviceRequest.Options()) XCTFail("Should return an error if the result from service is invalid") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift index 5f92f37bcf..0ba9931cae 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift @@ -7,12 +7,12 @@ import Foundation -import XCTest -import AWSCognitoIdentityProvider import Amplify +import AWSCognitoIdentityProvider +import ClientRuntime +import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon -import ClientRuntime class DeviceBehaviorRememberDeviceTests: BasePluginTest { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift index 420d8f5abd..6808245663 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/HostedUITests/AWSAuthHostedUISignInTests.swift @@ -9,11 +9,11 @@ import Foundation +import AuthenticationServices +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AuthenticationServices -import AWSCognitoIdentityProvider class AWSAuthHostedUISignInTests: XCTestCase { @@ -21,10 +21,12 @@ class AWSAuthHostedUISignInTests: XCTestCase { let networkTimeout = TimeInterval(5) var mockIdentityProvider: CognitoUserPoolBehavior! var mockHostedUIResult: Result<[URLQueryItem], HostedUIError>! - var mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testData.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + var mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testData.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, + "expires_in": 10 + ] as [String: Any] var mockState = "someState" var mockProof = "someProof" var mockJson: Data! @@ -57,13 +59,16 @@ class AWSAuthHostedUISignInTests: XCTestCase { return MockRandomStringGenerator(mockString: mockState, mockUUID: mockState) } - let environment = BasicHostedUIEnvironment(configuration: configuration, - hostedUISessionFactory: sessionFactory, - urlSessionFactory: urlSessionMock, - randomStringFactory: mockRandomString) + let environment = BasicHostedUIEnvironment( + configuration: configuration, + hostedUISessionFactory: sessionFactory, + urlSessionFactory: urlSessionMock, + randomStringFactory: mockRandomString + ) let authEnvironment = Defaults.makeDefaultAuthEnvironment( userPoolFactory: { self.mockIdentityProvider }, - hostedUIEnvironment: environment) + hostedUIEnvironment: environment + ) let stateMachine = Defaults.authStateMachineWith( environment: authEnvironment, initialState: initialState @@ -75,7 +80,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { authStateMachine: stateMachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } @MainActor @@ -90,9 +96,11 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testSuccessfulSignIn_missingExpiresIn() async throws { - mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testData.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken] as [String: Any] + mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testData.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -108,9 +116,11 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testSuccessfulSignIn_missingExpiresIn_testTokenMissingExp() async throws { - mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, - "access_token": AWSCognitoUserPoolTokens.testData.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken] as [String: Any] + mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, + "access_token": AWSCognitoUserPoolTokens.testData.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -126,9 +136,11 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testSuccessfulSignIn_missingExpiresIn_testBothTokenMissingExp() async throws { - mockTokenResult = ["id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, - "access_token": AWSCognitoUserPoolTokens.testDataWithoutExp.accessToken, - "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken] as [String: Any] + mockTokenResult = [ + "id_token": AWSCognitoUserPoolTokens.testDataWithoutExp.idToken, + "access_token": AWSCognitoUserPoolTokens.testDataWithoutExp.accessToken, + "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -151,7 +163,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { XCTFail("Should not succeed") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userCancelled = (underlyingError as? AWSCognitoAuthError) else { + case .userCancelled = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should not fail with error = \(error)") return } @@ -169,7 +182,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { XCTFail("Should not succeed") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .userCancelled = (underlyingError as? AWSCognitoAuthError) else { + case .userCancelled = (underlyingError as? AWSCognitoAuthError) + else { XCTFail("Should not fail with error = \(error)") return } @@ -253,7 +267,8 @@ class AWSAuthHostedUISignInTests: XCTestCase { ]) mockTokenResult = [ "refresh_token": AWSCognitoUserPoolTokens.testData.refreshToken, - "expires_in": 10] as [String: Any] + "expires_in": 10 + ] as [String: Any] mockJson = try! JSONSerialization.data(withJSONObject: mockTokenResult) MockURLProtocol.requestHandler = { _ in return (HTTPURLResponse(), self.mockJson) @@ -324,18 +339,20 @@ class AWSAuthHostedUISignInTests: XCTestCase { @MainActor func testRestartSignInWithWebUI() async { - self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in + mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in InitiateAuthOutput( authenticationResult: .none, challengeName: .passwordVerifier, challengeParameters: InitiateAuthOutput.validChalengeParams, - session: "someSession") + session: "someSession" + ) }, mockRespondToAuthChallengeResponse: { _ in RespondToAuthChallengeOutput( authenticationResult: .none, challengeName: .smsMfa, challengeParameters: [:], - session: "session") + session: "session" + ) }) let pluginOptions = AWSAuthSignInOptions(metadata: ["somekey": "somevalue"]) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift index 3c3eebe100..049638dd9d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift @@ -7,10 +7,10 @@ import Foundation +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider class AWSCognitoAuthUserBehaviorTests: BasePluginTest { @@ -150,7 +150,8 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) let pluginOptions = AWSSendUserAttributeVerificationCodeOptions(metadata: ["key": "value"]) let options = AuthSendUserAttributeVerificationCodeRequest.Options(pluginOptions: pluginOptions) @@ -174,7 +175,8 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) let pluginOptions = AWSSendUserAttributeVerificationCodeOptions(metadata: ["key": "value"]) let options = AuthSendUserAttributeVerificationCodeRequest.Options(pluginOptions: pluginOptions) @@ -195,7 +197,8 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) _ = try await plugin.sendVerificationCode(forUserAttributeKey: .email) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift index ea6171b1b9..7c2accbc8b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/BasePluginTest.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentity +import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin @@ -14,11 +14,10 @@ class BasePluginTest: XCTestCase { let apiTimeout = 2.0 var mockIdentityProvider: CognitoUserPoolBehavior! - lazy var mockIdentity: CognitoIdentityBehavior = { - MockIdentity( - mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) - }() + lazy var mockIdentity: CognitoIdentityBehavior = MockIdentity( + mockGetIdResponse: getId, + mockGetCredentialsResponse: getCredentials + ) var plugin: AWSCognitoAuthPlugin! let getId: MockIdentity.MockGetIdResponse = { _ in @@ -26,20 +25,25 @@ class BasePluginTest: XCTestCase { } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - let credentials = CognitoIdentityClientTypes.Credentials(accessKeyId: "accessKey", - expiration: Date(), - secretKey: "secret", - sessionToken: "session") + let credentials = CognitoIdentityClientTypes.Credentials( + accessKeyId: "accessKey", + expiration: Date(), + secretKey: "secret", + sessionToken: "session" + ) return .init(credentials: credentials, identityId: "responseIdentityID") } var initialState: AuthState { AuthState.configured( AuthenticationState.signedIn( - SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData)), - AuthorizationState.sessionEstablished(AmplifyCredentials.testData)) + SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: AWSCognitoUserPoolTokens.testData + )), + AuthorizationState.sessionEstablished(AmplifyCredentials.testData) + ) } override func setUp() { @@ -47,12 +51,14 @@ class BasePluginTest: XCTestCase { let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: { self.mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) let statemachine = Defaults.makeDefaultAuthStateMachine( initialState: initialState, identityPoolFactory: { self.mockIdentity }, - userPoolFactory: { self.mockIdentityProvider }) + userPoolFactory: { self.mockIdentityProvider } + ) plugin?.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), @@ -60,28 +66,34 @@ class BasePluginTest: XCTestCase { authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) } func configureCustomPluginWith( authConfiguration: AuthConfiguration = Defaults.makeDefaultAuthConfigData(), userPool: @escaping () throws -> CognitoUserPoolBehavior = Defaults.makeDefaultUserPool, identityPool: @escaping () throws -> CognitoIdentityBehavior = Defaults.makeIdentity, - initialState: AuthState) -> AWSCognitoAuthPlugin { + initialState: AuthState + ) -> AWSCognitoAuthPlugin { let plugin = AWSCognitoAuthPlugin() let environment = Defaults.makeDefaultAuthEnvironment( identityPoolFactory: identityPool, - userPoolFactory: userPool) - let statemachine = AuthStateMachine(resolver: AuthState.Resolver(), - environment: environment, - initialState: initialState) + userPoolFactory: userPool + ) + let statemachine = AuthStateMachine( + resolver: AuthState.Resolver(), + environment: environment, + initialState: initialState + ) plugin.configure( authConfiguration: Defaults.makeDefaultAuthConfigData(), authEnvironment: environment, authStateMachine: statemachine, credentialStoreStateMachine: Defaults.makeDefaultCredentialStateMachine(), hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift index cf2a4239d9..d5e0296ab7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/SendUserAttributeVerificationCodeTests.swift @@ -7,11 +7,11 @@ import Foundation +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime class SendUserAttributeVerificationCodeTests: BasePluginTest { @@ -30,7 +30,8 @@ class SendUserAttributeVerificationCodeTests: BasePluginTest { codeDeliveryDetails: .init( attributeName: "attributeName", deliveryMedium: .email, - destination: "destination")) + destination: "destination" + )) }) let attribute = try await plugin.sendVerificationCode(forUserAttributeKey: .email) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift index 4b17d9d05e..18ce0336c8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift @@ -7,11 +7,11 @@ import Foundation +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime class UserBehaviorChangePasswordTests: BasePluginTest { @@ -24,7 +24,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// - I should get a successful result /// func testSuccessfulChangePassword() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in return try await ChangePasswordOutput(httpResponse: .init(body: .empty, statusCode: .ok)) }) try await plugin.update(oldPassword: "old password", to: "new password") @@ -40,7 +40,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithInternalErrorException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.InternalErrorException( message: "internal error exception" ) @@ -68,7 +68,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithInvalidParameterException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.InvalidParameterException( message: "invalid parameter exception" ) @@ -100,7 +100,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithInvalidPasswordException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.InvalidPasswordException( message: "invalid password exception" ) @@ -132,7 +132,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithLimitExceededException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw try await AWSCognitoIdentityProvider.LimitExceededException( httpResponse: .init(body: .empty, statusCode: .accepted), decoder: nil, @@ -167,7 +167,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithNotAuthorizedException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.NotAuthorizedException( message: "not authorized exception" ) @@ -195,7 +195,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithPasswordResetRequiredException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.PasswordResetRequiredException( message: "password reset required exception" ) @@ -227,7 +227,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithResourceNotFoundException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.ResourceNotFoundException( message: "resource not found exception" ) @@ -259,7 +259,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithTooManyRequestsException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.TooManyRequestsException( message: "too many requests exception" ) @@ -291,7 +291,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithUserNotConfirmedException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.UserNotConfirmedException( message: "user not confirmed exception" ) @@ -323,7 +323,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testChangePasswordWithUserNotFoundException() async throws { - self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in + mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutput: { _ in throw AWSCognitoIdentityProvider.UserNotFoundException( message: "user not found exception" ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift index 870afbbe4f..bff945a7e3 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift @@ -5,11 +5,11 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime class UserBehaviorConfirmAttributeTests: BasePluginTest { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift index d814fe0090..1a65365c75 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSClientRuntime +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime -import AWSClientRuntime class UserBehaviorFetchAttributesTests: BasePluginTest { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift index 75f7d52024..1b32d8f855 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSClientRuntime +import AWSCognitoIdentityProvider +import ClientRuntime import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider -import ClientRuntime -import AWSClientRuntime class UserBehaviorUpdateAttributesTests: BasePluginTest { @@ -26,9 +26,12 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in UpdateUserAttributesOutput(codeDeliveryDetailsList: [ - .init(attributeName: "attributeName", - deliveryMedium: .email, - destination: "destination")]) + .init( + attributeName: "attributeName", + deliveryMedium: .email, + destination: "destination" + ) + ]) }) let attributes = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift index e5ffca104e..5faf265dae 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAPIDecoding/TestHarnessAPIDecoder.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // +import Foundation @testable import Amplify @testable import AWSCognitoAuthPlugin -import Foundation -struct TestHarnessAPIDecoder { +enum TestHarnessAPIDecoder { static func decode( specification: FeatureSpecification) -> AmplifyAPI { @@ -40,32 +40,38 @@ struct TestHarnessAPIDecoder { return signInAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .signUp: return signUpAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .deleteUser: return deleteUserAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .confirmSignIn: return confirmSignInAPI( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .fetchAuthSession: return fetchAuthSession( params: specification.api.params, responseType: responseType, - data: data) + data: data + ) case .signOut: return signOutApi( options: specification.api.options, responseType: responseType, - data: data) + data: data + ) default: fatalError() } @@ -86,8 +92,10 @@ struct TestHarnessAPIDecoder { return .signIn( input: .init( username: username, - password: inputPassword, options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + password: inputPassword, options: .init() + ), + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func signUpAPI( @@ -105,8 +113,10 @@ struct TestHarnessAPIDecoder { return .signUp( input: .init( username: username, - password: inputPassword, options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + password: inputPassword, options: .init() + ), + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func resetPasswordAPI( @@ -118,9 +128,12 @@ struct TestHarnessAPIDecoder { fatalError("missing username parameter") } return .resetPassword( - input: .init(username: username, - options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + input: .init( + username: username, + options: .init() + ), + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func confirmSignInAPI( @@ -133,7 +146,8 @@ struct TestHarnessAPIDecoder { } return .confirmSignIn( input: .init(challengeResponse: challengeResponse, options: .init()), - expectedOutput: generateResult(responseType: responseType, data: data)) + expectedOutput: generateResult(responseType: responseType, data: data) + ) } private static func fetchAuthSession( @@ -143,11 +157,13 @@ struct TestHarnessAPIDecoder { ) -> AmplifyAPI { let result: Result? = generateResult( - responseType: responseType, data: data) + responseType: responseType, data: data + ) return .fetchAuthSession( input: .init(options: .init()), - expectedOutput: result) + expectedOutput: result + ) } private static func signOutApi( @@ -162,11 +178,13 @@ struct TestHarnessAPIDecoder { } let result: Result? = generateResult( - responseType: responseType, data: data) + responseType: responseType, data: data + ) return .signOut( input: .init(options: .init(globalSignOut: globalSignOut)), - expectedOutput: result) + expectedOutput: result + ) } private static func deleteUserAPI( @@ -175,10 +193,11 @@ struct TestHarnessAPIDecoder { data: Data? ) -> AmplifyAPI { - guard let responseType = responseType, let data = data else { + guard let responseType, let data else { return .deleteUser( input: (), - expectedOutput: nil) + expectedOutput: nil + ) } let result: Result @@ -186,7 +205,8 @@ struct TestHarnessAPIDecoder { switch responseType { case "failure": let authError = try! JSONDecoder().decode( - AuthError.self, from: data) + AuthError.self, from: data + ) result = .failure(authError) case "success": result = .success(()) @@ -195,13 +215,15 @@ struct TestHarnessAPIDecoder { } return .deleteUser( input: (), - expectedOutput: result) + expectedOutput: result + ) } private static func generateResult( - responseType: String?, data: Data?) -> Result? { + responseType: String?, data: Data? + ) -> Result? { - guard let responseType = responseType, let data = data else { + guard let responseType, let data else { return nil } @@ -210,11 +232,13 @@ struct TestHarnessAPIDecoder { switch responseType { case "failure": let authError = try! JSONDecoder().decode( - AuthError.self, from: data) + AuthError.self, from: data + ) result = .failure(authError) case "success": let output = try! JSONDecoder().decode( - Output.self, from: data) + Output.self, from: data + ) result = .success(output) default: fatalError("invalid response type") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift index eef6bf85c1..01eacb3b28 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoIdentityProvider import XCTest @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSCognitoIdentityProvider class AmplifyAuthCognitoPluginTests: XCTestCase { @@ -42,32 +42,44 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { func beginTest( for plugin: AWSCognitoAuthPlugin, - with testHarness: AuthTestHarness) async { + with testHarness: AuthTestHarness + ) async { switch testHarness.apiUnderTest { - case .resetPassword(let resetPasswordRequest, - let expectedOutput): + case .resetPassword( + let resetPasswordRequest, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.resetPassword( for: resetPasswordRequest.username, - options: resetPasswordRequest.options) + options: resetPasswordRequest.options + ) } - case .signUp(let signUpRequest, - let expectedOutput): + case .signUp( + let signUpRequest, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.signUp( username: signUpRequest.username, - password: signUpRequest.password, options: signUpRequest.options) + password: signUpRequest.password, options: signUpRequest.options + ) } - case .signIn(let request, - let expectedOutput): + case .signIn( + let request, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.signIn( username: request.username, - password: request.password, options: request.options) + password: request.password, options: request.options + ) } - case .fetchAuthSession(let request, - let expectedOutput): + case .fetchAuthSession( + let request, + let expectedOutput + ): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.fetchAuthSession(options: request.options) as! AWSAuthCognitoSession } @@ -96,17 +108,19 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { case .confirmSignIn(let request, expectedOutput: let expectedOutput): await validateAPI(expectedOutput: expectedOutput) { return try await plugin.confirmSignIn( - challengeResponse: request.challengeResponse, options: request.options) + challengeResponse: request.challengeResponse, options: request.options + ) } } } - + // Helper to validate API Result func validateAPI( expectedOutput: Result?, - apiCall: @escaping () async throws -> T) async { + apiCall: @escaping () async throws -> T + ) async { let expectation = expectation(description: "expectation") do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift index aaf462cfc7..549981032a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ChangePasswordInput+Codable.swift @@ -27,7 +27,8 @@ extension ChangePasswordInput: Decodable { self.init( accessToken: accessTokenDecoded, previousPassword: previousPasswordDecoded, - proposedPassword: proposedPasswordDecoded) + proposedPassword: proposedPasswordDecoded + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift index 8ca5db107f..ee926761e5 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ConfirmDeviceInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension ConfirmDeviceInput: Decodable { @@ -33,7 +33,8 @@ extension ConfirmDeviceInput: Decodable { deviceName: deviceName, deviceSecretVerifierConfig: .init( passwordVerifier: passwordVerifier, - salt: salt) + salt: salt + ) ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift index 457096b9a0..9eeca91844 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/ForgotPasswordInput+Codable.swift @@ -24,7 +24,8 @@ extension ForgotPasswordInput: Decodable { self.init( clientId: clientId, clientMetadata: clientMetadata, - username: username) + username: username + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift index 1b8cfcab72..d9eb4a09b6 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetCredentialsForIdentityInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension GetCredentialsForIdentityInput: Decodable { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift index 992ac9ea7a..6dd40e1a95 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/GetIdInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension GetIdInput: Decodable { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift index b37894ccb8..bed368ee19 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/InitiateAuthInput+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import AWSCognitoIdentityProvider import AWSCognitoIdentity +import AWSCognitoIdentityProvider import ClientRuntime extension InitiateAuthInput: Decodable { @@ -27,6 +27,7 @@ extension InitiateAuthInput: Decodable { authFlow: authFlow, authParameters: authParameters, clientId: clientId, - clientMetadata: clientMetadata) + clientMetadata: clientMetadata + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift index f98185a19a..5235a793db 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Input/RevokeTokenInput+Codable.swift @@ -24,7 +24,8 @@ extension RevokeTokenInput: Decodable { self.init( clientId: clientId, clientSecret: clientSecret, - token: token) + token: token + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift index ada8712912..51d4b48897 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ChangePasswordOutputResponse+Codable.swift @@ -11,7 +11,7 @@ import ClientRuntime extension ChangePasswordOutput: Codable { enum CodingKeys: String, CodingKey { - case httpResponse = "httpResponse" + case httpResponse } public init(from decoder: Decoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift index 2cb298d4a5..618b596846 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/ConfirmDeviceOutputResponse+Codable.swift @@ -14,7 +14,7 @@ extension ConfirmDeviceOutput: Codable { case userConfirmationNecessary = "UserConfirmationNecessary" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let userConfirmationNecessaryDecoded = try containerValues.decode(Swift.Bool.self, forKey: .userConfirmationNecessary) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift index 05b56dcaf9..ad438fe696 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetCredentialsForIdentityOutputResponse+Codable.swift @@ -14,7 +14,7 @@ extension GetCredentialsForIdentityOutput: Codable { case identityId = "IdentityId" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let identityIdDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .identityId) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift index 2180ce9402..e9bfb0904e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/GetIdOutputResponse+Codable.swift @@ -13,7 +13,7 @@ extension GetIdOutput: Codable { case identityId = "IdentityId" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let identityIdDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .identityId) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift index 20c6f99f1e..14b51540b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/HttpResponse+Codable.swift @@ -11,21 +11,21 @@ import ClientRuntime extension HttpResponse: Codable { } enum HttpResponseCodingKeys: String, CodingKey { - case statusCode = "statusCode" + case statusCode } -extension Encodable where Self: HttpResponse { +public extension Encodable where Self: HttpResponse { - public func encode(to encoder: Encoder) throws { + func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: HttpResponseCodingKeys.self) try container.encode(statusCode.rawValue, forKey: .statusCode) } } -extension Decodable where Self: HttpResponse { +public extension Decodable where Self: HttpResponse { - public init(from decoder: Decoder) throws { + init(from decoder: Decoder) throws { let containerValues = try decoder.container(keyedBy: HttpResponseCodingKeys.self) let httpStatusCode = try containerValues.decodeIfPresent(Int.self, forKey: .statusCode) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift index 5e9eae1202..aba374bd8a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/InitiateAuthOutputResponse+Codable.swift @@ -17,7 +17,7 @@ extension InitiateAuthOutput: Codable { case session = "Session" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let challengeNameDecoded = try containerValues.decodeIfPresent(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName) @@ -25,11 +25,11 @@ extension InitiateAuthOutput: Codable { let sessionDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .session) session = sessionDecoded let challengeParametersContainer = try containerValues.decodeIfPresent([Swift.String: Swift.String?].self, forKey: .challengeParameters) - var challengeParametersDecoded0: [Swift.String:Swift.String]? = nil - if let challengeParametersContainer = challengeParametersContainer { - challengeParametersDecoded0 = [Swift.String:Swift.String]() + var challengeParametersDecoded0: [Swift.String: Swift.String]? = nil + if let challengeParametersContainer { + challengeParametersDecoded0 = [Swift.String: Swift.String]() for (key0, stringtype0) in challengeParametersContainer { - if let stringtype0 = stringtype0 { + if let stringtype0 { challengeParametersDecoded0?[key0] = stringtype0 } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift index 692887ad89..696282db3f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/RespondToAuthChallengeOutputResponse+Codable.swift @@ -16,7 +16,7 @@ extension RespondToAuthChallengeOutput: Codable { case session = "Session" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let challengeNameDecoded = try containerValues.decodeIfPresent(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName) @@ -24,11 +24,11 @@ extension RespondToAuthChallengeOutput: Codable { let sessionDecoded = try containerValues.decodeIfPresent(Swift.String.self, forKey: .session) session = sessionDecoded let challengeParametersContainer = try containerValues.decodeIfPresent([Swift.String: Swift.String?].self, forKey: .challengeParameters) - var challengeParametersDecoded0: [Swift.String:Swift.String]? = nil - if let challengeParametersContainer = challengeParametersContainer { - challengeParametersDecoded0 = [Swift.String:Swift.String]() + var challengeParametersDecoded0: [Swift.String: Swift.String]? = nil + if let challengeParametersContainer { + challengeParametersDecoded0 = [Swift.String: Swift.String]() for (key0, stringtype0) in challengeParametersContainer { - if let stringtype0 = stringtype0 { + if let stringtype0 { challengeParametersDecoded0?[key0] = stringtype0 } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift index e6f9255302..202138a402 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Cognito/Response/SignUpOutputResponse+Codable.swift @@ -15,7 +15,7 @@ extension SignUpOutput: Codable { case userSub = "UserSub" } - public init (from decoder: Swift.Decoder) throws { + public init(from decoder: Swift.Decoder) throws { self.init() let containerValues = try decoder.container(keyedBy: CodingKeys.self) let userConfirmedDecoded = try containerValues.decode(Swift.Bool.self, forKey: .userConfirmed) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift index 12de2f5742..d2f346427d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSAuthCognitoSession+Codable.swift @@ -6,8 +6,8 @@ // import Foundation -@testable import AWSCognitoAuthPlugin @testable import Amplify +@testable import AWSCognitoAuthPlugin extension AWSAuthCognitoSession: Codable { enum CodingKeys: String, CodingKey { @@ -44,7 +44,8 @@ extension AWSAuthCognitoSession: Codable { idToken: accessToken, accessToken: idToken, refreshToken: refreshToken, - expiration: userPoolTokenExpiration) + expiration: userPoolTokenExpiration + ) let accessKeyId = try awsCredentialChildren.decode(String.self, forKey: .accessKeyId) let secretAccessKey = try awsCredentialChildren.decode(String.self, forKey: .secretAccessKey) @@ -55,13 +56,15 @@ extension AWSAuthCognitoSession: Codable { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, sessionToken: sessionToken, - expiration: expiration) + expiration: expiration + ) self.init( isSignedIn: isSignedIn, identityIdResult: .success(identityIdResult), awsCredentialsResult: .success(awsCredentials), - cognitoTokensResult: .success(userPoolTokens)) + cognitoTokensResult: .success(userPoolTokens) + ) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift index a874428ad4..d7f65c16c4 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AWSCognitoSignOutResult+Codable.swift @@ -6,8 +6,8 @@ // import Foundation -@testable import AWSCognitoAuthPlugin @testable import Amplify +@testable import AWSCognitoAuthPlugin extension AWSCognitoSignOutResult: Equatable { public static func == (lhs: AWSCognitoSignOutResult, rhs: AWSCognitoSignOutResult) -> Bool { @@ -60,23 +60,26 @@ extension AWSCognitoSignOutResult: Codable { let accessToken = try globalSignOutError?.decodeIfPresent(String.self, forKey: .accessToken) var revokeTokenErrorObject: AWSCognitoRevokeTokenError? = nil - if let revokeAuthError = revokeAuthError, - let refreshToken = refreshToken { + if let revokeAuthError, + let refreshToken { revokeTokenErrorObject = AWSCognitoRevokeTokenError( - refreshToken: refreshToken, error: revokeAuthError) + refreshToken: refreshToken, error: revokeAuthError + ) } var globalSignOutErrorObject: AWSCognitoGlobalSignOutError? = nil - if let globalAuthError = globalAuthError, - let accessToken = accessToken { + if let globalAuthError, + let accessToken { globalSignOutErrorObject = AWSCognitoGlobalSignOutError( - accessToken: accessToken, error: globalAuthError) + accessToken: accessToken, error: globalAuthError + ) } self = .partial( revokeTokenError: revokeTokenErrorObject, globalSignOutError: globalSignOutErrorObject, - hostedUIError: nil) + hostedUIError: nil + ) } else { fatalError("type not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift index 0cc890d123..19f6555fde 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthResetPasswordResult+Codable.swift @@ -18,8 +18,10 @@ extension AuthResetPasswordResult: Codable { let values = try decoder.container(keyedBy: CodingKeys.self) let isPasswordReset = try values.decode(Bool.self, forKey: .isPasswordReset) let resetPasswordStep = try values.decode(AuthResetPasswordStep.self, forKey: .nextStep) - self.init(isPasswordReset: isPasswordReset, - nextStep: resetPasswordStep) + self.init( + isPasswordReset: isPasswordReset, + nextStep: resetPasswordStep + ) } public func encode(to encoder: Encoder) throws { @@ -43,13 +45,16 @@ extension AuthResetPasswordStep: Codable { let codeDeliveryDetails = try values.decode( AuthCodeDeliveryDetails.self, - forKey: .codeDeliveryDetails) + forKey: .codeDeliveryDetails + ) let additionalInfo = try values.decode( AdditionalInfo.self, - forKey: .additionalInfo) + forKey: .additionalInfo + ) self = .confirmResetPasswordWithCode( codeDeliveryDetails, - additionalInfo) + additionalInfo + ) } else { fatalError("next step type not supported") } @@ -89,12 +94,14 @@ extension AuthCodeDeliveryDetails: Codable { let attributeName = try values.decodeIfPresent(String.self, forKey: .attributeName) if attributeName == "EMAIL" { attributeKey = .email - } else if let attributeName = attributeName { + } else if let attributeName { attributeKey = .unknown(attributeName) } - self.init(destination: destination, - attributeKey: attributeKey) + self.init( + destination: destination, + attributeKey: attributeKey + ) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift index 8fc03da9af..1806be279b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignInResult+Codable.swift @@ -62,7 +62,8 @@ extension AuthSignInStep: Codable { let additionalInfo = try values.decodeIfPresent([String: String].self, forKey: .additionalInfo) self = .confirmSignInWithSMSMFACode( codeDeliveryDetails, - additionalInfo) + additionalInfo + ) } else { fatalError("next step type not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift index 899d43be13..ecf80b4d91 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthCodableImplementations/Results/AuthSignUpResult+Codable.swift @@ -59,14 +59,17 @@ extension AuthSignUpStep: Codable { let codeDeliveryDetails = try values.decode( AuthCodeDeliveryDetails.self, - forKey: .codeDeliveryDetails) + forKey: .codeDeliveryDetails + ) let additionalInfo = try values.decode( AdditionalInfo.self, - forKey: .additionalInfo) + forKey: .additionalInfo + ) self = .confirmUser( codeDeliveryDetails, additionalInfo, - nil) + nil + ) } else { fatalError("next step type not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift index b219711dee..da14b28223 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift @@ -38,18 +38,20 @@ class AuthTestHarness { } guard let authConfiguration = try? ConfigurationHelper - .authConfiguration(jsonValueConfiguration) else { + .authConfiguration(jsonValueConfiguration) + else { fatalError("Unable to create auth configuarion") } - testHarnessInput = await AuthTestHarnessInput.createInput( + self.testHarnessInput = await AuthTestHarnessInput.createInput( from: featureSpecification) - mockedCognitoHelper = MockedAuthCognitoPluginHelper( + self.mockedCognitoHelper = MockedAuthCognitoPluginHelper( authConfiguration: authConfiguration, initialAuthState: testHarnessInput.initialAuthState, mockIdentityProvider: testHarnessInput.getMockIdentityProvider(), - mockIdentity: testHarnessInput.getMockIdentity()) + mockIdentity: testHarnessInput.getMockIdentity() + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift index 7c190a1060..43200d158d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessConstants.swift @@ -7,7 +7,7 @@ import Foundation -struct AuthTestHarnessConstants { +enum AuthTestHarnessConstants { static let authConfigurationResourcePath = "TestResources/configuration" static let authStatesResourcePath = "TestResources/states" static let testSuitesPath = "TestResources/testSuites" diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift index bf7d92f287..345ef32fef 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift @@ -10,9 +10,9 @@ import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime +import Foundation @testable import Amplify @testable import AWSCognitoAuthPlugin -import Foundation struct AuthTestHarnessInput { let initialAuthState: AuthState @@ -27,11 +27,11 @@ extension AuthTestHarnessInput { from specification: FeatureSpecification ) async -> AuthTestHarnessInput { return await AuthTestHarnessInput( - initialAuthState: specification.preConditions.initialAuthState, - expectedAuthState: getExpectedAuthState(from: specification), - amplifyAPI: getAmplifyAPIUnderTest(from: specification), - cognitoAPI: getCognitoAPI(from: specification) - ) + initialAuthState: specification.preConditions.initialAuthState, + expectedAuthState: getExpectedAuthState(from: specification), + amplifyAPI: getAmplifyAPIUnderTest(from: specification), + cognitoAPI: getCognitoAPI(from: specification) + ) } private static func getAmplifyAPIUnderTest(from specification: FeatureSpecification) -> AmplifyAPI { @@ -61,25 +61,32 @@ extension AuthTestHarnessInput { enum AmplifyAPI { case resetPassword( input: AuthResetPasswordRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case signUp( input: AuthSignUpRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case signIn( input: AuthSignInRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case fetchAuthSession( input: AuthFetchSessionRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case signOut( input: AuthSignOutRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) case deleteUser( input: Void, - expectedOutput: Result?) + expectedOutput: Result? + ) case confirmSignIn( input: AuthConfirmSignInRequest, - expectedOutput: Result?) + expectedOutput: Result? + ) } enum CognitoAPI { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift index 870ef3469b..d5f572234d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthState+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension AuthState: Codable { @@ -26,7 +26,8 @@ extension AuthState: Codable { let authorizationState = try values.decode(AuthorizationState.self, forKey: .authorizationState) self = .configured( authenticationState, - authorizationState) + authorizationState + ) } else { fatalError("Decoding not supported") } @@ -46,14 +47,17 @@ extension AuthState: Codable { static func initialize( fileName: String, - with fileExtension: String = "") -> AuthState { + with fileExtension: String = "" + ) -> AuthState { let bundle = Bundle.authCognitoTestBundle() let url = bundle.url( forResource: fileName, withExtension: fileExtension, - subdirectory: AuthTestHarnessConstants.authStatesResourcePath)! + subdirectory: AuthTestHarnessConstants.authStatesResourcePath + )! let fileData: Data = try! Data(contentsOf: url) return try! JSONDecoder().decode( - AuthState.self, from: fileData) + AuthState.self, from: fileData + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift index 492f6cdcd6..045f349916 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthenticationState+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension AuthenticationState: Codable { @@ -31,7 +31,7 @@ extension AuthenticationState: Codable { let signedOutData = SignedOutData(lastKnownUserName: nil) self = .signedOut(signedOutData) } else if type == "AuthenticationState.SigningIn" { - self = .signingIn(try values.decode(SignInState.self, forKey: .SignInState)) + self = try .signingIn(values.decode(SignInState.self, forKey: .SignInState)) } else { fatalError("Decoding not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift index 9d79544b97..dc4e04c7b7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/AuthorizationState+Codable.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension AuthorizationState: Codable { @@ -56,7 +56,8 @@ extension AuthorizationState: Codable { idToken: accessToken, accessToken: idToken, refreshToken: refreshToken, - expiration: userPoolExpiration) + expiration: userPoolExpiration + ) let accessKeyId = try awsCredentialChildren.decode(String.self, forKey: .accessKeyId) let secretAccessKey = try awsCredentialChildren.decode(String.self, forKey: .secretAccessKey) @@ -67,15 +68,18 @@ extension AuthorizationState: Codable { accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, sessionToken: sessionToken, - expiration: expiration) + expiration: expiration + ) self = .sessionEstablished(.userPoolAndIdentityPool( signedInData: .init( signedInDate: Date(), signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: userPoolTokens), + cognitoUserPoolTokens: userPoolTokens + ), identityID: identityId, - credentials: awsCredentials)) + credentials: awsCredentials + )) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift index 0dc049110d..7cd8e0e1f7 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/CodableStates.swift @@ -5,19 +5,19 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin +import Amplify import AWSCognitoIdentityProvider -import Foundation import AWSPluginsCore -import Amplify +import Foundation +@testable import AWSCognitoAuthPlugin extension DeviceMetadata { - public init(from decoder: Decoder) throws { + init(from decoder: Decoder) throws { self = .noData } - public func encode(to encoder: Encoder) throws { + func encode(to encoder: Encoder) throws { fatalError() } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift index 467535a3c9..5cf2f3372d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInChallengeState+Codable.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import Foundation +@testable import AWSCognitoAuthPlugin extension SignInChallengeState: Codable { enum CodingKeys: String, CodingKey { @@ -22,16 +22,18 @@ extension SignInChallengeState: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let nestedContainerValue = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .authChallenge) - + let type = try values.decode(String.self, forKey: .type) if type == "SignInChallengeState.WaitingForAnswer" { - self = .waitingForAnswer( + self = try .waitingForAnswer( RespondToAuthChallenge( - challenge: try nestedContainerValue.decode(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName), - username: try nestedContainerValue.decode(String.self, forKey: .username), - session: try nestedContainerValue.decode(String.self, forKey: .session), - parameters: try nestedContainerValue.decode([String: String].self, forKey: .parameters)), - .apiBased(.userSRP)) + challenge: nestedContainerValue.decode(CognitoIdentityProviderClientTypes.ChallengeNameType.self, forKey: .challengeName), + username: nestedContainerValue.decode(String.self, forKey: .username), + session: nestedContainerValue.decode(String.self, forKey: .session), + parameters: nestedContainerValue.decode([String: String].self, forKey: .parameters) + ), + .apiBased(.userSRP) + ) } else { fatalError("Decoding not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift index e28731918f..c00fa85c01 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CodableStates/SignInState+Codable.swift @@ -5,12 +5,12 @@ // SPDX-License-Identifier: Apache-2.0 // -@testable import AWSCognitoAuthPlugin import Foundation +@testable import AWSCognitoAuthPlugin extension SignInState: Codable { - + enum CodingKeys: String, CodingKey { case type case SignInChallengeState @@ -21,10 +21,11 @@ extension SignInState: Codable { let type = try values.decode(String.self, forKey: .type) if type == "SignInState.ResolvingChallenge" { - self = .resolvingChallenge( - try values.decode(SignInChallengeState.self, forKey: .SignInChallengeState), + self = try .resolvingChallenge( + values.decode(SignInChallengeState.self, forKey: .SignInChallengeState), .smsMfa, - .apiBased(.userSRP)) + .apiBased(.userSRP) + ) } else { fatalError("Decoding not supported") } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift index 2c33d8e7ab..945fa84f22 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift @@ -5,17 +5,17 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSClientRuntime import AWSCognitoIdentity import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -import AWSClientRuntime +import Foundation @testable import Amplify @testable import AWSCognitoAuthPlugin -import Foundation -struct CognitoAPIDecodingHelper { +enum CognitoAPIDecodingHelper { static func decode(with specification: FeatureSpecification) async -> [API.APIName: CognitoAPI] { @@ -25,7 +25,8 @@ struct CognitoAPIDecodingHelper { // Response guard mockedResponse["type"] == .string("cognitoIdentityProvider") || - mockedResponse["type"] == .string("cognitoIdentity") else { + mockedResponse["type"] == .string("cognitoIdentity") + else { continue } @@ -43,108 +44,89 @@ struct CognitoAPIDecodingHelper { let requestData = requestData( for: specification, - with: apiName) + with: apiName + ) switch apiName { case "forgotPassword": decodedAPIs[.forgotPassword] = await .forgotPassword( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "signUp": decodedAPIs[.signUp] = await .signUp( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "deleteUser": decodedAPIs[.deleteUser] = await .deleteUser( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "respondToAuthChallenge": decodedAPIs[.confirmSignIn] = await .respondToAuthChallenge( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "confirmDevice": decodedAPIs[.confirmDevice] = await .confirmDevice( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "initiateAuth": decodedAPIs[.initiateAuth] = await .initiateAuth( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "revokeToken": decodedAPIs[.revokeToken] = await .revokeToken( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "getId": decodedAPIs[.getId] = await .getId( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "getCredentialsForIdentity": decodedAPIs[.getCredentialsForIdentity] = await .getCredentialsForIdentity( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) case "globalSignOut": decodedAPIs[.globalSignOut] = await .globalSignOut( - { - await getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) - }() + getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) ) default: fatalError() @@ -154,9 +136,11 @@ struct CognitoAPIDecodingHelper { return decodedAPIs } - private static func requestData(for specification: FeatureSpecification, - with apiName: String) -> Data? { - var requestData: Data? = nil + private static func requestData( + for specification: FeatureSpecification, + with apiName: String + ) -> Data? { + var requestData: Data? // Request if let cognitoResponseValidation = specification.validations.first(where: { validation in validation.value(at: "type") == .string("cognitoIdentityProvider") && @@ -182,7 +166,7 @@ struct CognitoAPIDecodingHelper { ) async -> CognitoAPIData { var input: Input? = nil - if let request = request { + if let request { input = try! JSONDecoder().decode(Input.self, from: request) } @@ -192,7 +176,8 @@ struct CognitoAPIDecodingHelper { switch responseType { case "failure": guard case .string(let errorType) = response["errorType"], - case .string(let errorMessage) = response["errorType"] else { + case .string(let errorMessage) = response["errorType"] + else { fatalError() } @@ -201,7 +186,8 @@ struct CognitoAPIDecodingHelper { case "success": let responseData = try! JSONEncoder().encode(response) let output = try! JSONDecoder().decode( - Output.self, from: responseData) + Output.self, from: responseData + ) result = .success(output) default: fatalError("invalid response type") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift index 26ef2771e6..d05b7a11db 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/FeatureSpecification.swift @@ -22,17 +22,21 @@ struct FeatureSpecification: Codable { var api: API var validations: [JSONValue] - init(fileName: String, - fileExtension: String = "", - subdirectory: String) { + init( + fileName: String, + fileExtension: String = "", + subdirectory: String + ) { let bundle = Bundle.authCognitoTestBundle() let url = bundle.url( forResource: fileName, withExtension: fileExtension, - subdirectory: subdirectory)! + subdirectory: subdirectory + )! let fileData: Data = try! Data(contentsOf: url) self = try! JSONDecoder().decode( - FeatureSpecification.self, from: fileData) + FeatureSpecification.self, from: fileData + ) } } @@ -48,9 +52,11 @@ struct Preconditions: Codable { var initialAuthState: AuthState var mockedResponses: [JSONValue] - init(amplifyConfiguration: AmplifyConfiguration, - initialAuthState: AuthState, - expectedResponses: [JSONValue]) { + init( + amplifyConfiguration: AmplifyConfiguration, + initialAuthState: AuthState, + expectedResponses: [JSONValue] + ) { self.initialAuthState = initialAuthState self.amplifyConfiguration = amplifyConfiguration self.mockedResponses = expectedResponses @@ -94,7 +100,7 @@ struct API: Codable { case confirmSignIn case fetchAuthSession case signOut - + case getId case getCredentialsForIdentity case confirmDevice @@ -106,9 +112,9 @@ struct API: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) - name = try values.decode(APIName.self, forKey: .name) - params = try values.decode(JSONValue.self, forKey: .params) - options = try values.decode(JSONValue.self, forKey: .options) + self.name = try values.decode(APIName.self, forKey: .name) + self.params = try values.decode(JSONValue.self, forKey: .params) + self.options = try values.decode(JSONValue.self, forKey: .options) } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift index 3f06b0ec1e..8663e5705d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Helpers/AmplifyConfigurationInitializationInTest.swift @@ -9,14 +9,17 @@ import Foundation @testable import Amplify extension AmplifyConfiguration { - init(fileName: String, - fileExtension: String = "") { + init( + fileName: String, + fileExtension: String = "" + ) { let bundle = Bundle.authCognitoTestBundle() let url = bundle.url( forResource: fileName, withExtension: fileExtension, - subdirectory: AuthTestHarnessConstants.authConfigurationResourcePath)! + subdirectory: AuthTestHarnessConstants.authConfigurationResourcePath + )! self = try! AmplifyConfiguration.loadAmplifyConfiguration(from: url) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift index 951744d216..3ece205b21 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentity.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -import Foundation import AWSCognitoIdentity +import Foundation +import XCTest extension AuthTestHarnessInput { @@ -49,7 +49,8 @@ extension AuthTestHarnessInput { return MockIdentity( mockGetIdResponse: getId, - mockGetCredentialsResponse: getCredentials) + mockGetCredentialsResponse: getCredentials + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift index cca624fbb3..83139ef899 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/AuthTestHarnessInput+MockIdentityProvider.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AWSCognitoIdentityProvider +import XCTest extension AuthTestHarnessInput { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift index 12b744f71f..3341ed87db 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/Mocks/MockedAuthCognitoPlugin.swift @@ -33,11 +33,13 @@ struct MockedAuthCognitoPluginHelper { let authStateMachine = StateMachine( resolver: authResolver, environment: authEnvironment, - initialState: initialAuthState) + initialState: initialAuthState + ) let credentialStoreMachine = StateMachine( resolver: credentialStoreResolver, - environment: credentialEnvironment) + environment: credentialEnvironment + ) let plugin = AWSCognitoAuthPlugin() @@ -47,7 +49,8 @@ struct MockedAuthCognitoPluginHelper { authStateMachine: authStateMachine, credentialStoreStateMachine: credentialStoreMachine, hubEventHandler: MockAuthHubEventBehavior(), - analyticsHandler: MockAnalyticsHandler()) + analyticsHandler: MockAnalyticsHandler() + ) return plugin } @@ -57,7 +60,7 @@ struct MockedAuthCognitoPluginHelper { private func makeUserPool() throws -> CognitoUserPoolBehavior { switch authConfiguration { case .userPools, .userPoolsAndIdentityPools: - return self.mockIdentityProvider + return mockIdentityProvider default: fatalError() } @@ -124,7 +127,8 @@ struct MockedAuthCognitoPluginHelper { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: nil, credentialsClient: makeCredentialStoreClient(), - logger: log) + logger: log + ) case .identityPools(let identityPoolConfigurationData): let authorizationEnvironment = authorizationEnvironment( @@ -136,10 +140,13 @@ struct MockedAuthCognitoPluginHelper { authenticationEnvironment: nil, authorizationEnvironment: authorizationEnvironment, credentialsClient: makeCredentialStoreClient(), - logger: log) + logger: log + ) - case .userPoolsAndIdentityPools(let userPoolConfigurationData, - let identityPoolConfigurationData): + case .userPoolsAndIdentityPools( + let userPoolConfigurationData, + let identityPoolConfigurationData + ): let authenticationEnvironment = authenticationEnvironment( userPoolConfigData: userPoolConfigurationData) let authorizationEnvironment = authorizationEnvironment( @@ -151,40 +158,50 @@ struct MockedAuthCognitoPluginHelper { authenticationEnvironment: authenticationEnvironment, authorizationEnvironment: authorizationEnvironment, credentialsClient: makeCredentialStoreClient(), - logger: log) + logger: log + ) } } private func authenticationEnvironment(userPoolConfigData: UserPoolConfigurationData) -> AuthenticationEnvironment { - let srpAuthEnvironment = BasicSRPAuthEnvironment(userPoolConfiguration: userPoolConfigData, - cognitoUserPoolFactory: makeUserPool) + let srpAuthEnvironment = BasicSRPAuthEnvironment( + userPoolConfiguration: userPoolConfigData, + cognitoUserPoolFactory: makeUserPool + ) let srpSignInEnvironment = BasicSRPSignInEnvironment(srpAuthEnvironment: srpAuthEnvironment) let userPoolEnvironment = BasicUserPoolEnvironment( userPoolConfiguration: userPoolConfigData, cognitoUserPoolFactory: makeUserPool, cognitoUserPoolASFFactory: makeCognitoASF, - cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics) + cognitoUserPoolAnalyticsHandlerFactory: makeUserPoolAnalytics + ) let hostedUIEnvironment = hostedUIEnvironment(userPoolConfigData) - return BasicAuthenticationEnvironment(srpSignInEnvironment: srpSignInEnvironment, - userPoolEnvironment: userPoolEnvironment, - hostedUIEnvironment: hostedUIEnvironment) + return BasicAuthenticationEnvironment( + srpSignInEnvironment: srpSignInEnvironment, + userPoolEnvironment: userPoolEnvironment, + hostedUIEnvironment: hostedUIEnvironment + ) } private func hostedUIEnvironment(_ configuration: UserPoolConfigurationData) -> HostedUIEnvironment? { guard let hostedUIConfig = configuration.hostedUIConfig else { return nil } - return BasicHostedUIEnvironment(configuration: hostedUIConfig, - hostedUISessionFactory: makeHostedUISession, - urlSessionFactory: makeURLSession, - randomStringFactory: makeRandomString) + return BasicHostedUIEnvironment( + configuration: hostedUIConfig, + hostedUISessionFactory: makeHostedUISession, + urlSessionFactory: makeURLSession, + randomStringFactory: makeRandomString + ) } private func authorizationEnvironment( identityPoolConfigData: IdentityPoolConfigurationData) -> BasicAuthorizationEnvironment { - BasicAuthorizationEnvironment(identityPoolConfiguration: identityPoolConfigData, - cognitoIdentityFactory: makeIdentityClient) + BasicAuthorizationEnvironment( + identityPoolConfiguration: identityPoolConfigData, + cognitoIdentityFactory: makeIdentityClient + ) } private func credentialStoreEnvironment(authConfiguration: AuthConfiguration) -> CredentialEnvironment { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift index cdb8ccdc6b..0821c5b743 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineListenerTests.swift @@ -91,13 +91,13 @@ class StateMachineListenerTests: XCTestCase { func testOrderOfSubsription() async throws { let loop = 1_000 - for _ in 1...loop { + for _ in 1 ... loop { let notified = expectation(description: "notified") notified.expectedFulfillmentCount = 3 await stateMachine.send(Counter.Event(id: "set1", eventType: .set(10))) let seq = await stateMachine.listen() - await self.stateMachine.send(Counter.Event(id: "set2", eventType: .set(11))) + await stateMachine.send(Counter.Event(id: "set2", eventType: .set(11))) Task { var count = 0 for await state in seq { @@ -143,12 +143,12 @@ class StateMachineListenerTests: XCTestCase { let task2 = Task { - for index in 1...100 { + for index in 1 ... 100 { let event = Counter.Event(id: "test", eventType: .adjustBy(index)) await stateMachine.send(event) - if (index == 30) { + if index == 30 { task.cancel() await Task.yield() } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift index c0d3dbca65..2d7ac2d6bb 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/hierarchical-state-machine-swiftTests/StateMachineTests.swift @@ -40,7 +40,7 @@ class StateMachineTests: XCTestCase { let taskCompletion = expectation(description: "Completed sending event") taskCompletion.expectedFulfillmentCount = 1_000 Task { - for i in 1...1_000 { + for i in 1 ... 1_000 { if i.isMultiple(of: 2) { await testMachine.send(increment) } else { diff --git a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift index 5a5f5e792a..bb1161ab0d 100644 --- a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift +++ b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntDecimalTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyBigInteger +import XCTest final class AmplifyBigIntDecimalTests: XCTestCase { diff --git a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift index a4068d5098..12484fd65a 100644 --- a/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AmplifyBigIntegerUnitTests/AmplifyBigIntegerHelperTests.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import AmplifyBigInteger +import XCTest final class AmplifyBigIntegerHelperTests: XCTestCase { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift index 69668eee0d..5ae8447ddb 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AWSAuthBaseTest.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @_spi(InternalAmplifyConfiguration) @testable import Amplify -import AWSCognitoAuthPlugin class AWSAuthBaseTest: XCTestCase { @@ -21,8 +21,8 @@ class AWSAuthBaseTest: XCTestCase { } var randomPhoneNumber: String { - "+1" + (1...10) - .map { _ in String(Int.random(in: 0...9)) } + "+1" + (1 ... 10) + .map { _ in String(Int.random(in: 0 ... 9)) } .joined() } @@ -43,7 +43,7 @@ class AWSAuthBaseTest: XCTestCase { initializeAmplify() _ = await Amplify.Auth.signOut() } - + override func tearDown() async throws { try await super.tearDown() await Amplify.reset() @@ -102,7 +102,8 @@ class AWSAuthBaseTest: XCTestCase { "AppClientId": userPooldAppClientID, "Region": region ] - ]]] + ]] + ] ) let configuration = AmplifyConfiguration(auth: authConfiguration) let authPlugin = AWSCognitoAuthPlugin() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift index 6a34b479ed..2d0da51aba 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthDeleteUserTests: AWSAuthBaseTest { @@ -28,9 +28,11 @@ class AuthDeleteUserTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") // Check if the auth session is signed in diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift index c817772286..0b65189f60 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthEventTests/AuthEventIntegrationTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthEventIntegrationTests: AWSAuthBaseTest { @@ -49,7 +49,8 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) } @@ -79,7 +80,8 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) _ = await Amplify.Auth.signOut() await fulfillment(of: [signOutExpectation], timeout: networkTimeout) } @@ -115,10 +117,11 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { _ = try await Amplify.Auth.fetchAuthSession() - AuthSessionHelper.invalidateSession(with: self.amplifyConfiguration) + AuthSessionHelper.invalidateSession(with: amplifyConfiguration) _ = try await Amplify.Auth.fetchAuthSession() } await fulfillment(of: [signInExpectation, sessionExpiredExpectation], timeout: networkTimeout) @@ -154,7 +157,8 @@ class AuthEventIntegrationTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) do { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift index 78f9b2a099..50755fb814 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthUserAttributesTests/AuthUserAttributesTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthUserAttributesTests: AWSAuthBaseTest { @@ -33,14 +33,16 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let attributes = try await Amplify.Auth.fetchUserAttributes() if let emailAttribute = attributes.filter({ $0.key == .email }).first { - XCTAssertEqual(emailAttribute.value, self.defaultTestEmail) + XCTAssertEqual(emailAttribute.value, defaultTestEmail) } else { XCTFail("Email attribute not found") } @@ -63,9 +65,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let updatedEmail = "\(username)@amazon.com" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSAuthUpdateUserAttributeOptions(metadata: ["mydata": "myvalue"]) @@ -98,9 +102,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let updatedFamilyName = "\(username)@amazon.com" let updatedName = "Name\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSAuthUpdateUserAttributesOptions(metadata: ["mydata": "myvalue"]) @@ -124,7 +130,7 @@ class AuthUserAttributesTests: AWSAuthBaseTest { XCTFail("name attribute not found") } } - + /// - Given: A confirmed user /// - When: /// - I invoke Amplify.Auth.update with email attribute and then confirm the email attribute with an invalid code @@ -136,9 +142,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let updatedEmail = "\(username)@amazon.com" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSAuthUpdateUserAttributeOptions(metadata: ["mydata": "myvalue"]) @@ -151,7 +159,7 @@ class AuthUserAttributesTests: AWSAuthBaseTest { case .done: print("Update completed") } - + do { try await Amplify.Auth.confirm(userAttribute: .email, confirmationCode: "123") XCTFail("User attribute confirmation unexpectedly succeeded") @@ -180,9 +188,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let updatedEmail = "\(username)@amazon.com" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") _ = try await Amplify.Auth.update(userAttribute: AuthUserAttribute(.email, value: updatedEmail)) @@ -207,9 +217,11 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let pluginOptions = AWSSendUserAttributeVerificationCodeOptions(metadata: ["mydata": "myvalue"]) @@ -230,16 +242,18 @@ class AuthUserAttributesTests: AWSAuthBaseTest { let oldPassword = "P123@\(UUID().uuidString)" let updatedPassword = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: oldPassword, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: oldPassword, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") try await Amplify.Auth.update(oldPassword: oldPassword, to: updatedPassword) let attributes = try await Amplify.Auth.fetchUserAttributes() if let emailAttribute = attributes.filter({ $0.key == .email }).first { - XCTAssertEqual(emailAttribute.value, self.defaultTestEmail) + XCTAssertEqual(emailAttribute.value, defaultTestEmail) } else { XCTFail("Email attribute not found") } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift index 0dd8d34e9f..d090be1711 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/CredentialStore/CredentialStoreConfigurationTests.swift @@ -34,7 +34,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let awsCredentials = AuthAWSCognitoCredentials.testData let initialCognitoCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let configData = Defaults.makeIdentityConfigData() let initialAuthConfig = AuthConfiguration.identityPools(configData) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) @@ -46,8 +47,10 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { // When configuration changed let userPoolConfiguration = Defaults.makeDefaultUserPoolConfigData() - let newAuthConfig = AuthConfiguration.userPoolsAndIdentityPools(userPoolConfiguration, - configData) + let newAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( + userPoolConfiguration, + configData + ) let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: newAuthConfig) // Then @@ -78,10 +81,12 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let initialCognitoCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: .testData, identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) do { try credentialStore.saveCredential(initialCognitoCredentials) @@ -94,9 +99,11 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { // Then guard let credentials = try? newCredentialStore.retrieveCredential(), - case .userPoolAndIdentityPool(let retrievedTokens, - let retrievedIdentityID, - let retrievedCredentials) = credentials else { + case .userPoolAndIdentityPool( + let retrievedTokens, + let retrievedIdentityID, + let retrievedCredentials + ) = credentials else { XCTFail("Unable to retrieve Credentials") return } @@ -122,7 +129,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let awsCredentials = AuthAWSCognitoCredentials.testData let initialCognitoCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.userPools(Defaults.makeDefaultUserPoolConfigData()) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) do { @@ -134,7 +142,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { // When configuration changed let newAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: newAuthConfig) // Then @@ -156,7 +165,8 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let awsCredentials = AuthAWSCognitoCredentials.testData let initialCognitoCredentials = AmplifyCredentials.identityPoolOnly( identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.identityPools(Defaults.makeIdentityConfigData()) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) @@ -167,8 +177,10 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { } // When configuration changed - let newAuthConfig = AuthConfiguration.identityPools(IdentityPoolConfigurationData(poolId: "changed", - region: "changed")) + let newAuthConfig = AuthConfiguration.identityPools(IdentityPoolConfigurationData( + poolId: "changed", + region: "changed" + )) let newCredentialStore = AWSCognitoAuthCredentialStore(authConfiguration: newAuthConfig) // Then @@ -191,10 +203,12 @@ class CredentialStoreConfigurationTests: AWSAuthBaseTest { let initialCognitoCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: .testData, identityID: identityId, - credentials: awsCredentials) + credentials: awsCredentials + ) let initialAuthConfig = AuthConfiguration.userPoolsAndIdentityPools( Defaults.makeDefaultUserPoolConfigData(), - Defaults.makeIdentityConfigData()) + Defaults.makeIdentityConfigData() + ) let credentialStore = AWSCognitoAuthCredentialStore(authConfiguration: initialAuthConfig) do { try credentialStore.saveCredential(initialCognitoCredentials) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift index e893bb5a2b..aabc36f07f 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthFetchDeviceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthFetchDeviceTests: AWSAuthBaseTest { @@ -52,11 +52,12 @@ class AuthFetchDeviceTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) } catch { print(error) } - + await fulfillment(of: [signInExpectation], timeout: networkTimeout) // fetch devices diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift index b1df2d456a..d01ce6a0ae 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthForgetDeviceTests: AWSAuthBaseTest { @@ -52,7 +52,8 @@ class AuthForgetDeviceTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) _ = try await Amplify.Auth.rememberDevice() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift index d54ce32273..4099d9ee61 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthRememberDeviceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthRememberDeviceTests: AWSAuthBaseTest { @@ -52,7 +52,8 @@ class AuthRememberDeviceTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) await fulfillment(of: [signInExpectation], timeout: networkTimeout) _ = try await Amplify.Auth.rememberDevice() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift index cf495aa7fb..f8c07e003a 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthEnvironmentHelper.swift @@ -17,16 +17,20 @@ enum Defaults { static let appClientSecret = "XXX" static func makeDefaultUserPoolConfigData() -> UserPoolConfigurationData { - UserPoolConfigurationData(poolId: userPoolId, - clientId: appClientId, - region: regionString, - clientSecret: appClientSecret, - pinpointAppId: "") + UserPoolConfigurationData( + poolId: userPoolId, + clientId: appClientId, + region: regionString, + clientSecret: appClientSecret, + pinpointAppId: "" + ) } static func makeIdentityConfigData() -> IdentityPoolConfigurationData { - IdentityPoolConfigurationData(poolId: identityPoolId, - region: regionString) + IdentityPoolConfigurationData( + poolId: identityPoolId, + region: regionString + ) } } @@ -38,7 +42,8 @@ extension AuthAWSCognitoCredentials { accessKeyId: "xx", secretAccessKey: "xx", sessionToken: "xx", - expiration: Date()) + expiration: Date() + ) } } @@ -53,9 +58,11 @@ extension SignedInData { static var testData: SignedInData { let tokens = AWSCognitoUserPoolTokens.testData - return SignedInData(signedInDate: Date(), - signInMethod: .apiBased(.userSRP), - cognitoUserPoolTokens: tokens) + return SignedInData( + signedInDate: Date(), + signInMethod: .apiBased(.userSRP), + cognitoUserPoolTokens: tokens + ) } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift index 72855132de..c5296d1095 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSessionHelper.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSPluginsCore @testable import Amplify @testable import AWSCognitoAuthPlugin -import AWSPluginsCore @_spi(KeychainStore) import AWSPluginsCore import CryptoKit import Foundation @@ -18,7 +18,8 @@ struct AuthSessionHelper { static func getCurrentAmplifySession( shouldForceRefresh: Bool = false, for testCase: XCTestCase, - with timeout: TimeInterval) async throws -> AWSAuthCognitoSession? { + with timeout: TimeInterval + ) async throws -> AWSAuthCognitoSession? { var cognitoSession: AWSAuthCognitoSession? let session = try await Amplify.Auth.fetchAuthSession(options: .init(forceRefresh: shouldForceRefresh)) cognitoSession = (session as? AWSAuthCognitoSession) @@ -38,25 +39,30 @@ struct AuthSessionHelper { return } switch credentials { - case .userPoolAndIdentityPool(signedInData: let signedInData, - identityID: let identityID, - credentials: let awsCredentials): + case .userPoolAndIdentityPool( + signedInData: let signedInData, + identityID: let identityID, + credentials: let awsCredentials + ): let updatedToken = updateTokenWithPastExpiry(signedInData.cognitoUserPoolTokens) let signedInData = SignedInData( signedInDate: signedInData.signedInDate, signInMethod: signedInData.signInMethod, - cognitoUserPoolTokens: updatedToken) + cognitoUserPoolTokens: updatedToken + ) let updatedCredentials = AmplifyCredentials.userPoolAndIdentityPool( signedInData: signedInData, identityID: identityID, - credentials: awsCredentials) + credentials: awsCredentials + ) try! credentialStore.saveCredential(updatedCredentials) case .userPoolOnly(signedInData: let signedInData): let updatedToken = updateTokenWithPastExpiry(signedInData.cognitoUserPoolTokens) let signedInData = SignedInData( signedInDate: signedInData.signedInDate, signInMethod: signedInData.signInMethod, - cognitoUserPoolTokens: updatedToken) + cognitoUserPoolTokens: updatedToken + ) let updatedCredentials = AmplifyCredentials.userPoolOnly(signedInData: signedInData) try! credentialStore.saveCredential(updatedCredentials) default: break @@ -64,33 +70,37 @@ struct AuthSessionHelper { } - static private func updateTokenWithPastExpiry(_ tokens: AWSCognitoUserPoolTokens) + private static func updateTokenWithPastExpiry(_ tokens: AWSCognitoUserPoolTokens) -> AWSCognitoUserPoolTokens { var idToken = tokens.idToken var accessToken = tokens.accessToken if var idTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: idToken).get(), var accessTokenClaims = try? AWSAuthService().getTokenClaims(tokenString: accessToken).get() { - idTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3000).timeIntervalSince1970) as AnyObject - accessTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3000).timeIntervalSince1970) as AnyObject + idTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3_000).timeIntervalSince1970) as AnyObject + accessTokenClaims["exp"] = String(Date(timeIntervalSinceNow: -3_000).timeIntervalSince1970) as AnyObject idToken = CognitoAuthTestHelper.buildToken(for: idTokenClaims) accessToken = CognitoAuthTestHelper.buildToken(for: accessTokenClaims) } - return AWSCognitoUserPoolTokens(idToken: idToken, - accessToken: accessToken, - refreshToken: "invalid", - expiration: Date().addingTimeInterval(-50000)) + return AWSCognitoUserPoolTokens( + idToken: idToken, + accessToken: accessToken, + refreshToken: "invalid", + expiration: Date().addingTimeInterval(-50_000) + ) } - static private func getAuthConfiguration(configuration: AmplifyConfiguration) -> AuthConfiguration { + private static func getAuthConfiguration(configuration: AmplifyConfiguration) -> AuthConfiguration { let jsonValueConfiguration = configuration.auth!.plugins["awsCognitoAuthPlugin"]! let userPoolConfigData = parseUserPoolConfigData(jsonValueConfiguration) let identityPoolConfigData = parseIdentityPoolConfigData(jsonValueConfiguration) - return try! authConfiguration(userPoolConfig: userPoolConfigData, - identityPoolConfig: identityPoolConfigData) + return try! authConfiguration( + userPoolConfig: userPoolConfigData, + identityPoolConfig: identityPoolConfigData + ) } - static private func parseUserPoolConfigData(_ config: JSONValue) -> UserPoolConfigurationData? { + private static func parseUserPoolConfigData(_ config: JSONValue) -> UserPoolConfigurationData? { // TODO: Use JSON serialization here to convert. guard let cognitoUserPoolJSON = config.value(at: "CognitoUserPool.Default") else { Amplify.Logging.info("Could not find Cognito User Pool configuration") @@ -107,13 +117,15 @@ struct AuthSessionHelper { if case .string(let clientSecretFromConfig) = cognitoUserPoolJSON.value(at: "AppClientSecret") { clientSecret = clientSecretFromConfig } - return UserPoolConfigurationData(poolId: poolId, - clientId: appClientId, - region: region, - clientSecret: clientSecret) + return UserPoolConfigurationData( + poolId: poolId, + clientId: appClientId, + region: region, + clientSecret: clientSecret + ) } - static private func parseIdentityPoolConfigData(_ config: JSONValue) -> IdentityPoolConfigurationData? { + private static func parseIdentityPoolConfigData(_ config: JSONValue) -> IdentityPoolConfigurationData? { guard let cognitoIdentityPoolJSON = config.value(at: "CredentialsProvider.CognitoIdentity.Default") else { Amplify.Logging.info("Could not find Cognito Identity Pool configuration") @@ -127,8 +139,10 @@ struct AuthSessionHelper { return IdentityPoolConfigurationData(poolId: poolId, region: region) } - static private func authConfiguration(userPoolConfig: UserPoolConfigurationData?, - identityPoolConfig: IdentityPoolConfigurationData?) throws -> AuthConfiguration { + private static func authConfiguration( + userPoolConfig: UserPoolConfigurationData?, + identityPoolConfig: IdentityPoolConfigurationData? + ) throws -> AuthConfiguration { if let userPoolConfigNonNil = userPoolConfig, let identityPoolConfigNonNil = identityPoolConfig { return .userPoolsAndIdentityPools(userPoolConfigNonNil, identityPoolConfigNonNil) @@ -148,7 +162,7 @@ struct AuthSessionHelper { } } -struct CognitoAuthTestHelper { +enum CognitoAuthTestHelper { /// Helper to build a JWT Token static func buildToken(for payload: [String: AnyObject]) -> String { @@ -184,7 +198,7 @@ struct CognitoAuthTestHelper { } } -fileprivate extension Data { +private extension Data { func urlSafeBase64EncodedString() -> String { return base64EncodedString() .replacingOccurrences(of: "+", with: "-") diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift index 1dc43decc6..e3a807a265 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/AuthSignInHelper.swift @@ -9,7 +9,7 @@ import Amplify import XCTest enum AuthSignInHelper { - + static func signOut() async { let session = try? await Amplify.Auth.fetchAuthSession() if session?.isSignedIn ?? false { @@ -21,13 +21,14 @@ enum AuthSignInHelper { username: String, password: String, email: String, - phoneNumber: String? = nil) async throws -> Bool { + phoneNumber: String? = nil + ) async throws -> Bool { var userAttributes = [ AuthUserAttribute(.email, value: email) ] - if let phoneNumber = phoneNumber { + if let phoneNumber { userAttributes.append(AuthUserAttribute(.phoneNumber, value: phoneNumber)) } @@ -45,12 +46,14 @@ enum AuthSignInHelper { username: String, password: String, email: String, - phoneNumber: String? = nil) async throws -> Bool { + phoneNumber: String? = nil + ) async throws -> Bool { let signedUp = try await AuthSignInHelper.signUpUser( username: username, password: password, email: email, - phoneNumber: phoneNumber) + phoneNumber: phoneNumber + ) guard signedUp else { throw AuthError.invalidState("Auth sign up failed", "", nil) } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift index f7c2203689..5089ec32a0 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/Helpers/TOTPHelper.swift @@ -8,7 +8,7 @@ import CryptoKit import XCTest -struct TOTPHelper { +enum TOTPHelper { static func generateTOTPCode(sharedSecret: String) -> String { @@ -25,16 +25,17 @@ struct TOTPHelper { private static func otpCode(secret: Data, date: Date, period: TimeInterval, digits: Int) -> String { let counter = UInt64(date.timeIntervalSince1970 / period) - let counterBytes = (0..<8).reversed().map { UInt8(counter >> (8 * $0) & 0xff) } + let counterBytes = (0 ..< 8).reversed().map { UInt8(counter >> (8 * $0) & 0xff) } let hash = HMAC.authenticationCode( for: counterBytes, - using: SymmetricKey(data: secret)) + using: SymmetricKey(data: secret) + ) let offset = Int(hash.suffix(1)[0] & 0x0f) let hash32 = hash .dropFirst(offset) .prefix(4) - .reduce(0, { ($0 << 8) | UInt32($1) }) - let hash31 = hash32 & 0x7FFF_FFFF + .reduce(0) { ($0 << 8) | UInt32($1) } + let hash31 = hash32 & 0x7fffffff let pad = String(repeating: "0", count: digits) return String((pad + String(hash31)).suffix(digits)) } @@ -43,22 +44,22 @@ struct TOTPHelper { private static let __: UInt8 = 255 private static let alphabetDecodeTable: [UInt8] = [ - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x00 - 0x0F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x10 - 0x1F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x20 - 0x2F - __,__,26,27, 28,29,30,31, __,__,__,__, __,__,__,__, // 0x30 - 0x3F - __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x40 - 0x4F - 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x50 - 0x5F - __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, // 0x60 - 0x6F - 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__, // 0x70 - 0x7F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x80 - 0x8F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0x90 - 0x9F - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xA0 - 0xAF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xB0 - 0xBF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xC0 - 0xCF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xD0 - 0xDF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xE0 - 0xEF - __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__, // 0xF0 - 0xFF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x00 - 0x0F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x10 - 0x1F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x20 - 0x2F + __, __, 26, 27, 28, 29, 30, 31, __, __, __, __, __, __, __, __, // 0x30 - 0x3F + __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 0x40 - 0x4F + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, __, __, __, __, __, // 0x50 - 0x5F + __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 0x60 - 0x6F + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, __, __, __, __, __, // 0x70 - 0x7F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x80 - 0x8F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0x90 - 0x9F + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xA0 - 0xAF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xB0 - 0xBF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xC0 - 0xCF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xD0 - 0xDF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xE0 - 0xEF + __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 0xF0 - 0xFF ] private static func base32decode(_ string: String, _ table: [UInt8]) -> [UInt8]? { @@ -116,12 +117,12 @@ struct TOTPHelper { (data: UnsafeBufferPointer) -> [UInt8] in var encoded = data.baseAddress! - var result = Array(repeating: 0, count: dataSize) + var result = [UInt8](repeating: 0, count: dataSize) var decodedOffset = 0 // decode regular blocks var value0, value1, value2, value3, value4, value5, value6, value7: UInt8 - (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0) + (value0, value1, value2, value3, value4, value5, value6, value7) = (0, 0, 0, 0, 0, 0, 0, 0) while remainEncodedLength >= 8 { value0 = table[Int(encoded[0])] value1 = table[Int(encoded[1])] @@ -144,7 +145,7 @@ struct TOTPHelper { } // decode last block - (value0, value1, value2, value3, value4, value5, value6, value7) = (0,0,0,0,0,0,0,0) + (value0, value1, value2, value3, value4, value5, value6, value7) = (0, 0, 0, 0, 0, 0, 0, 0) switch remainEncodedLength { case 7: value6 = table[Int(encoded[6])] diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift index 587830f71c..d9a82487b0 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFAPreferenceTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class MFAPreferenceTests: AWSAuthBaseTest { @@ -34,7 +34,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { username: username, password: password, email: email ?? defaultTestEmail, - phoneNumber: phoneNumber) + phoneNumber: phoneNumber + ) XCTAssertTrue(didSucceed, "Signup and sign in should succeed") } @@ -88,7 +89,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test enabled try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -98,7 +100,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test preferred try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .preferred) + totp: .preferred + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -109,7 +112,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test notPreferred try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .notPreferred) + totp: .notPreferred + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -119,7 +123,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test disabled try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .disabled) + totp: .disabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNil(fetchMFAResult.enabled) @@ -151,7 +156,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test enabled try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -161,7 +167,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test preferred try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -172,7 +179,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test notPreferred try await authCognitoPlugin.updateMFAPreference( sms: .notPreferred, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -182,7 +190,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test disabled try await authCognitoPlugin.updateMFAPreference( sms: .disabled, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNil(fetchMFAResult.enabled) @@ -201,8 +210,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { /// - I should get valid fetchMFAPreference results corresponding to the updateMFAPreference /// func testFetchAndUpdateMFAPreferenceForSMSAndTOTP() async throws { - let randomPhoneNumber = "+1" + (1...10) - .map { _ in String(Int.random(in: 0...9)) } + let randomPhoneNumber = "+1" + (1 ... 10) + .map { _ in String(Int.random(in: 0 ... 9)) } .joined() try await signUpAndSignIn( @@ -223,7 +232,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test both MFA types as enabled try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -233,7 +243,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as preferred, TOTP as enabled try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -244,7 +255,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as notPreferred, TOTP as preferred try await authCognitoPlugin.updateMFAPreference( sms: .notPreferred, - totp: .preferred) + totp: .preferred + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -255,7 +267,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as disabled, no change to TOTP try await authCognitoPlugin.updateMFAPreference( sms: .disabled, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -266,7 +279,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as preferred, no change to TOTP (which should remove TOTP from preferred list) try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: nil) + totp: nil + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertNotNil(fetchMFAResult.enabled) @@ -297,12 +311,14 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test both MFA types as enabled try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: .preferred) + totp: .preferred + ) XCTFail("Should not proceed, because MFA types cannot be marked as preferred") } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } @@ -340,7 +356,8 @@ class MFAPreferenceTests: AWSAuthBaseTest { // Test SMS as preferred, TOTP as enabled try await authCognitoPlugin.updateMFAPreference( sms: .preferred, - totp: .enabled) + totp: .enabled + ) fetchMFAResult = try await authCognitoPlugin.fetchMFAPreference() XCTAssertEqual(fetchMFAResult.enabled, [.sms, .totp]) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift index cbfb0bb6b5..c86cb44acb 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/MFASignInTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class MFASignInTests: AWSAuthBaseTest { @@ -58,7 +58,8 @@ class MFASignInTests: AWSAuthBaseTest { try await Amplify.Auth.verifyTOTPSetup(code: totpCode) try await authCognitoPlugin.updateMFAPreference( sms: nil, - totp: .enabled) + totp: .enabled + ) await AuthSignInHelper.signOut() /// Sleep for 30 secs so that TOTP code can be regenerated for use during sign in otherwise will get @@ -75,7 +76,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .confirmSignInWithTOTPCode = result.nextStep else { XCTFail("Next step should be confirmSignInWithTOTPCode") return @@ -126,7 +128,8 @@ class MFASignInTests: AWSAuthBaseTest { for: "awsCognitoAuthPlugin") as! AWSCognitoAuthPlugin try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: nil) + totp: nil + ) await AuthSignInHelper.signOut() @@ -137,7 +140,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .confirmSignInWithSMSMFACode(let codeDeliveryDetails, _) = result.nextStep else { XCTFail("Next step should be confirmSignInWithSMSMFACode") return @@ -178,7 +182,8 @@ class MFASignInTests: AWSAuthBaseTest { username: username, password: password, email: randomEmail, - phoneNumber: randomPhoneNumber) + phoneNumber: randomPhoneNumber + ) XCTAssertTrue(didSucceed, "Signup and sign in should succeed") @@ -190,7 +195,8 @@ class MFASignInTests: AWSAuthBaseTest { try await Amplify.Auth.verifyTOTPSetup(code: totpCode) try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: .enabled) + totp: .enabled + ) await AuthSignInHelper.signOut() /// Sleep for 30 secs so that TOTP code can be regenerated for use during sign in otherwise will get @@ -206,7 +212,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithMFASelection(let allowedMFATypes) = result.nextStep else { XCTFail("Next step should be continueSignInWithMFASelection") return @@ -270,7 +277,8 @@ class MFASignInTests: AWSAuthBaseTest { try await Amplify.Auth.verifyTOTPSetup(code: totpCode) try await authCognitoPlugin.updateMFAPreference( sms: .enabled, - totp: .enabled) + totp: .enabled + ) await AuthSignInHelper.signOut() // Once all preconditions are satisfied, try signing in @@ -278,7 +286,8 @@ class MFASignInTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithMFASelection(let allowedMFATypes) = result.nextStep else { XCTFail("Next step should be continueSignInWithMFASelection") return diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift index f76d5d5c1a..9ad0d5e7bd 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenAuthenticatedTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class TOTPSetupWhenAuthenticatedTests: AWSAuthBaseTest { @@ -76,7 +76,8 @@ class TOTPSetupWhenAuthenticatedTests: AWSAuthBaseTest { } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift index 4e514f81e4..ecd6212fe2 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/MFATests/TOTPSetupWhenUnauthenticatedTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest import Amplify import AWSCognitoAuthPlugin +import XCTest class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { @@ -54,7 +54,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let totpSetupDetails) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -96,7 +97,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .confirmSignInWithSMSMFACode(let codeDeliveryDetails, _) = result.nextStep else { XCTFail("Next step should be confirmSignInWithSMSMFACode") return @@ -146,7 +148,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let totpSetupDetails) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -157,7 +160,7 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let confirmSignInResult = try await Amplify.Auth.confirmSignIn( challengeResponse: totpCode) XCTAssertTrue(confirmSignInResult.isSignedIn) - + } catch { XCTFail("SignIn should successfully complete. \(error)") } @@ -195,7 +198,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let details) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -209,7 +213,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } @@ -263,7 +268,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { let result = try await Amplify.Auth.signIn( username: username, password: password, - options: .init()) + options: .init() + ) guard case .continueSignInWithTOTPSetup(let details) = result.nextStep else { XCTFail("Next step should be continueSignInWithTOTPSetup") return @@ -277,7 +283,8 @@ class TOTPSetupWhenUnauthenticatedTests: AWSAuthBaseTest { } catch { guard let authError = error as? AuthError, - case .service(_, _, let underlyingError) = authError else { + case .service(_, _, let underlyingError) = authError + else { XCTFail("Should throw service error") return } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift index 299d67b6a1..bf91d52c24 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthConfirmResetPasswordTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthConfirmResetPasswordTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift index cabe4a672b..99249901c1 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/ResetPasswordTests/AuthResetPasswordTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthResetPasswordTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift index 2fc5743290..51ae5668ae 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/FederatedSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class FederatedSessionTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift index dd203b6ab5..093e4cbf9a 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/GetCurrentUserTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class GetCurrentUserTests: AWSAuthBaseTest { @@ -36,7 +36,8 @@ class GetCurrentUserTests: AWSAuthBaseTest { _ = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) let authUser = try await Amplify.Auth.getCurrentUser() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift index 159f222430..5128307b51 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedInAuthSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class SignedInAuthSessionTests: AWSAuthBaseTest { @@ -33,26 +33,33 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { func testSuccessfulForceSessionFetch() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let firstCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( for: self, - with: networkTimeout) + with: networkTimeout + ) let secondCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( for: self, - with: networkTimeout) + with: networkTimeout + ) let thirdCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( shouldForceRefresh: true, for: self, - with: networkTimeout) + with: networkTimeout + ) let fourthCognitoSession = try await AuthSessionHelper.getCurrentAmplifySession( for: self, - with: networkTimeout) + with: networkTimeout + ) // First 2 sessions should match XCTAssertEqual(firstCognitoSession, secondCognitoSession) @@ -75,8 +82,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { func testSuccessfulSessionFetch() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let session = try await Amplify.Auth.fetchAuthSession() @@ -95,8 +105,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { throw XCTSkip("TODO: fix this test. We need to find a way to mock credential store") let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let session = try await Amplify.Auth.fetchAuthSession() @@ -108,7 +121,7 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { } // Manually invalidate the tokens and then try to fetch the session. - AuthSessionHelper.invalidateSession(with: self.amplifyConfiguration) + AuthSessionHelper.invalidateSession(with: amplifyConfiguration) let anotherSession = try await Amplify.Auth.fetchAuthSession() do { let authSession = anotherSession as? AuthCognitoTokensProvider @@ -116,7 +129,8 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { XCTFail("Should not receive a valid token") } catch { guard let authError = error as? AuthError, - case .sessionExpired = authError else { + case .sessionExpired = authError + else { XCTFail("Should receive a session expired error but received \(error)") return } @@ -135,8 +149,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { throw XCTSkip("TODO: fix this test. We need to find a way to mock credential store") let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let session = try await Amplify.Auth.fetchAuthSession() @@ -155,7 +172,8 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { XCTFail("Should not receive a valid token") } catch { guard let authError = error as? AuthError, - case .signedOut = authError else { + case .signedOut = authError + else { XCTFail("Should receive a session expired error but received \(error)") return } @@ -173,8 +191,11 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { func testMultipleSuccessfulSessionFetch() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") let firstSession = try await Amplify.Auth.fetchAuthSession() @@ -205,16 +226,17 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { let identityIDExpectation = expectation(description: "Identity id should be fetched") identityIDExpectation.expectedFulfillmentCount = 100 - for index in 1...100 { + for index in 1 ... 100 { Task { // Randomly yield the task so that below execution of signOut happen - if index%6 == 0 { + if index % 6 == 0 { await Task.yield() } let firstSession = try await Amplify.Auth.fetchAuthSession() guard let cognitoSession = firstSession as? AWSAuthCognitoSession, - let _ = try? cognitoSession.identityIdResult.get() else { + let _ = try? cognitoSession.identityIdResult.get() + else { XCTFail("Could not fetch Identity ID") return } @@ -226,7 +248,7 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { _ = await Amplify.Auth.signOut() let fetchSessionExptectation = expectation(description: "Session should be fetched") fetchSessionExptectation.expectedFulfillmentCount = 50 - for _ in 1...50 { + for _ in 1 ... 50 { Task { let firstSession = try await Amplify.Auth.fetchAuthSession() XCTAssertFalse(firstSession.isSignedIn, "Session state should be signed out") @@ -265,7 +287,8 @@ class SignedInAuthSessionTests: AWSAuthBaseTest { let didSucceed = try await AuthSignInHelper.registerAndSignInUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") session = try await Amplify.Auth.fetchAuthSession() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift index 8722221457..caa0bdc541 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SessionTests/SignedOutAuthSessionTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class SignedOutAuthSessionTests: AWSAuthBaseTest { @@ -49,7 +49,8 @@ class SignedOutAuthSessionTests: AWSAuthBaseTest { let result = try await Amplify.Auth.fetchAuthSession() guard let cognitoResult = result as? AWSAuthCognitoSession, - let identityID1 = try? cognitoResult.identityIdResult.get() else { + let identityID1 = try? cognitoResult.identityIdResult.get() + else { XCTFail("Should retreive identity ID") return } @@ -58,7 +59,8 @@ class SignedOutAuthSessionTests: AWSAuthBaseTest { let result2 = try await Amplify.Auth.fetchAuthSession() guard let cognitoResult = result2 as? AWSAuthCognitoSession, - let identityID2 = try? cognitoResult.identityIdResult.get() else { + let identityID2 = try? cognitoResult.identityIdResult.get() + else { XCTFail("Should retreive identity ID") return } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift index 685ea89498..4535f30e3f 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthCustomSignInTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthCustomSignInTests: AWSAuthBaseTest { @@ -58,8 +58,11 @@ class AuthCustomSignInTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let isSignedUp = try await AuthSignInHelper.signUpUser(username: username, password: password, - email: defaultTestEmail) + let isSignedUp = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(isSignedUp) var confirmationCodeForValidation = "" @@ -120,15 +123,20 @@ class AuthCustomSignInTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let isSignedUp = try await AuthSignInHelper.signUpUser(username: username, password: password, - email: defaultTestEmail) + let isSignedUp = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(isSignedUp) let option = AWSAuthSignInOptions(authFlowType: .customWithSRP) do { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password, - options: AuthSignInRequest.Options(pluginOptions: option)) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password, + options: AuthSignInRequest.Options(pluginOptions: option) + ) XCTAssertTrue(signInResult.isSignedIn, "SignIn should be complete") } catch { XCTFail("Should successfully login") @@ -138,9 +146,11 @@ class AuthCustomSignInTests: AWSAuthBaseTest { let srpOption = AWSAuthSignInOptions(authFlowType: .userSRP) do { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password, - options: AuthSignInRequest.Options(pluginOptions: srpOption)) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password, + options: AuthSignInRequest.Options(pluginOptions: srpOption) + ) XCTAssertTrue(signInResult.isSignedIn, "SignIn should be complete") } catch { XCTFail("SignIn with a valid username/password should not fail \(error)") @@ -193,9 +203,11 @@ class AuthCustomSignInTests: AWSAuthBaseTest { var confirmationCodeForValidation = "" let option = AWSAuthSignInOptions(authFlowType: .custom) do { - let signInResult = try await Amplify.Auth.signIn(username: username, - password: password, - options: AuthSignInRequest.Options(pluginOptions: option)) + let signInResult = try await Amplify.Auth.signIn( + username: username, + password: password, + options: AuthSignInRequest.Options(pluginOptions: option) + ) if case .confirmSignInWithCustomChallenge(let additionalInfo) = signInResult.nextStep { confirmationCodeForValidation = additionalInfo?["code"] ?? "" } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift index ffbecc10d4..7931d83d4d 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift @@ -5,10 +5,10 @@ // SPDX-License-Identifier: Apache-2.0 // -import XCTest -@testable import Amplify import AWSCognitoAuthPlugin import AWSPluginsCore +import XCTest +@testable import Amplify class AuthSRPSignInTests: AWSAuthBaseTest { @@ -33,9 +33,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { func testSuccessfulSignIn() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.signUpUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") do { let signInResult = try await Amplify.Auth.signIn(username: username, password: password) @@ -56,9 +58,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { func testSignInWithWrongPassword() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.signUpUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") do { @@ -129,8 +133,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.signUpUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.signUpUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") let awsAuthSignInOptions = AWSAuthSignInOptions(metadata: ["mySignInData": "myvalue"]) @@ -186,8 +193,11 @@ class AuthSRPSignInTests: AWSAuthBaseTest { func testSignInWhenAlreadySignedIn() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "SignIn operation failed") do { @@ -264,10 +274,12 @@ class AuthSRPSignInTests: AWSAuthBaseTest { userAttributes: [ AuthUserAttribute(.email, value: defaultTestEmail) ], - metadata: nil) + metadata: nil + ) let result = try await Amplify.Auth.confirmSignIn( challengeResponse: newPassword, - options: .init(pluginOptions: pluginOptions)) + options: .init(pluginOptions: pluginOptions) + ) if case .done = result.nextStep { confirmOperationExpectation.fulfill() } @@ -311,7 +323,8 @@ class AuthSRPSignInTests: AWSAuthBaseTest { let didSucceed = try await AuthSignInHelper.signUpUser( username: username, password: password, - email: defaultTestEmail) + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") do { let signInResult = try await Amplify.Auth.signIn(username: username, password: password) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift index 2c71d77056..7014457c6e 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignOutTests/AuthSignOutTests.swift @@ -40,9 +40,11 @@ class AuthSignOutTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") @@ -61,9 +63,11 @@ class AuthSignOutTests: AWSAuthBaseTest { func testNonGlobalSignOut() async throws { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let didSucceed = try await AuthSignInHelper.registerAndSignInUser(username: username, - password: password, - email: defaultTestEmail) + let didSucceed = try await AuthSignInHelper.registerAndSignInUser( + username: username, + password: password, + email: defaultTestEmail + ) XCTAssertTrue(didSucceed, "Signup operation failed") print("calling signOut...") try await signOut(globalSignOut: false) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift index b706fcf957..47cbf0df80 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthConfirmSignUpTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthConfirmSignUpTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift index f6965e61b5..6ae7b26823 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthResendSignUpCodeTests: AWSAuthBaseTest { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift index 73ce715670..877f858d84 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // +import AWSCognitoAuthPlugin import XCTest @testable import Amplify -import AWSCognitoAuthPlugin class AuthSignUpTests: AWSAuthBaseTest { @@ -24,10 +24,13 @@ class AuthSignUpTests: AWSAuthBaseTest { let password = "P123@\(UUID().uuidString)" let options = AuthSignUpRequest.Options(userAttributes: [ - AuthUserAttribute(.email, value: defaultTestEmail)]) - let signUpResult = try await Amplify.Auth.signUp(username: username, - password: password, - options: options) + AuthUserAttribute(.email, value: defaultTestEmail) + ]) + let signUpResult = try await Amplify.Auth.signUp( + username: username, + password: password, + options: options + ) XCTAssertTrue(signUpResult.isSignUpComplete, "Signup should be complete") } @@ -37,7 +40,7 @@ class AuthSignUpTests: AWSAuthBaseTest { let signUpExpectation = expectation(description: "Sign up completed") signUpExpectation.expectedFulfillmentCount = 2 - for _ in 0.. AmplifyConfiguration { do { return try ConfigurationHelper.retrieveAmplifyConfiguration( diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift index 715142da7d..d7103bad7c 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/ContentView.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify +import SwiftUI struct ContentView: View { @@ -17,7 +17,7 @@ struct ContentView: View { NavigationView { if !loading { VStack { - if self.username != nil { + if username != nil { SignedInView(username: $username) } else { SignedOutView() @@ -28,7 +28,7 @@ struct ContentView: View { }.onAppear { Task { - await self.configureAuth() + await configureAuth() } } } @@ -36,11 +36,11 @@ struct ContentView: View { func configureAuth() async { do { let user = try await Amplify.Auth.getCurrentUser() - self.username = user.username + username = user.username } catch { - self.username = nil + username = nil } - self.loading = false + loading = false } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift index 4538e239ed..6644c676bb 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/AuthError+Info.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify import AWSCognitoAuthPlugin +import Foundation extension AuthError { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift index 7881ee5d31..4425a429d6 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Utils/ConfigurationHelper.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import Foundation import Amplify +import Foundation class ConfigurationHelper { @@ -42,7 +42,8 @@ class ConfigurationHelper { "AppClientId": userPooldAppClientID, "Region": region ] - ]]] + ]] + ] ) return AmplifyConfiguration(auth: authConfiguration) } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift index e21bb3c942..cc9fe17e0f 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignUpView.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify +import SwiftUI struct SignUpView: View { @@ -44,11 +44,11 @@ struct SignUpView: View { } .accessibility(identifier: Identifiers.signUpButton) Spacer() - if let error = self.errorLabel { + if let error = errorLabel { Text("Error occured: \(error)") .accessibilityLabel(Identifiers.errorLabel) } - if let successLabel = self.successLabel { + if let successLabel { Text("SignUp Succeeded \(successLabel)") .accessibilityLabel(Identifiers.successLabel) } @@ -57,8 +57,8 @@ struct SignUpView: View { } func signUp() async { - self.successLabel = nil - self.errorLabel = nil + successLabel = nil + errorLabel = nil print("Password \(password)") do { let options = AuthSignUpRequest.Options(userAttributes: [.init(.email, value: username)]) @@ -68,13 +68,13 @@ struct SignUpView: View { options: options ) if signUpResult.isSignUpComplete { - self.successLabel = "Complete" + successLabel = "Complete" } else { - self.errorLabel = "SignUp is not complete: \(signUpResult.nextStep)" + errorLabel = "SignUp is not complete: \(signUpResult.nextStep)" } } catch { print("Unexpected error: \(error)") - self.errorLabel = error.info() + errorLabel = error.info() } } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift index 6fea279a8d..2361c25bfc 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedInView.swift @@ -5,9 +5,9 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify import AWSCognitoAuthPlugin +import SwiftUI struct SignedInView: View { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift index 5fa41255f9..17b426b927 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp/Views/SignedOutView.swift @@ -5,8 +5,8 @@ // SPDX-License-Identifier: Apache-2.0 // -import SwiftUI import Amplify +import SwiftUI struct SignedOutView: View { @@ -42,11 +42,11 @@ struct SignedOutView: View { } .accessibility(identifier: Identifiers.signUpNav) Spacer() - if let error = self.errorLabel { + if let error = errorLabel { Text("Error occured: \(error)") .accessibilityLabel(Identifiers.errorLabel) } - if let successLabel = self.successLabel { + if let successLabel { Text("Succeeded: \(successLabel)") .accessibilityLabel(Identifiers.successLabel) } @@ -59,11 +59,11 @@ struct SignedOutView: View { do { let signInResult = try await Amplify.Auth.signInWithWebUI(presentationAnchor: anchor) if signInResult.isSignedIn { - self.successLabel = "SignedIn" + successLabel = "SignedIn" } } catch { print("Unexpected error: \(error)") - self.errorLabel = error.info() + errorLabel = error.info() } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift index 8bfc88e1e0..650865b1c8 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/AuthenticationTest/HostedUISignInTests.swift @@ -26,7 +26,7 @@ class HostedUISignInTests: UITestCase { .dismissSignInAlert() .signIn(username: username, password: password) .testSignInSucceeded() - + } func testSignInWithoutPresentationAnchorSuccess() throws { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift index e184c1e758..c064594f52 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/AuthenticatedScreen.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest struct AuthenticatedScreen: Screen { diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift index 26d1584c2d..9d46a4f7de 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/Screen/SignInScreen.swift @@ -51,16 +51,16 @@ struct SignInScreen: Screen { func signIn(username: String, password: String) -> Self { - let signInTextFieldName: String + let signInTextFieldName // Ideally we align the provisioning of Gen1 and Gen2 backends // to create a HostedUI endpoint that has the same username text field. // The Gen1 steps are updated in the README already, we re-provision the backend // in Gen1 according to those steps, this check can be removed and expect // "Email Email" to be the text field. - if useGen2Configuration { - signInTextFieldName = "Email Email" + = if useGen2Configuration { + "Email Email" } else { - signInTextFieldName = "Username" + "Username" } _ = app.webViews.textFields[signInTextFieldName].waitForExistence(timeout: 60) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift index 86e4450d4a..1f2512c3c8 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIAppUITests/UITestCase.swift @@ -4,6 +4,7 @@ // // SPDX-License-Identifier: Apache-2.0 // + import XCTest protocol Screen {