From aeaa5d469ff23be1f4676b68647d0cfed36e4463 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 28 Sep 2023 13:27:08 -0400 Subject: [PATCH 01/23] base From eec34b02c73672bdfe7c660cf6993df3b4b6906f Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 28 Sep 2023 15:56:04 -0400 Subject: [PATCH 02/23] fix: resolve compiler errors in AWSPluginsCore after sdk update (#3247) --- .../AWSPluginsCore/Auth/AWSAuthService.swift | 2 +- .../Auth/AWSAuthServiceBehavior.swift | 2 +- .../AmplifyAWSCredentialsProvider.swift | 2 +- .../AmplifyAWSSignatureV4Signer.swift | 4 +- .../Auth/Provider/IAMCredentialProvider.swift | 4 +- .../AmplifyAWSServiceConfiguration.swift | 48 +++++++++++++++++++ .../ClientRuntimeFoundationBridge.swift | 12 ++--- .../FoundationClientEngine.swift | 2 +- .../UserAgentSuffixAppender.swift | 11 ++--- .../Utils/UserAgentSuffixAppenderTests.swift | 5 +- .../MockAWSAuthService.swift | 4 +- .../MockAWSSignatureV4Signer.swift | 2 +- Package.resolved | 18 +++---- Package.swift | 2 +- 14 files changed, 80 insertions(+), 38 deletions(-) diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift index 4f89dfe86d..ab72c799a8 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthService.swift @@ -13,7 +13,7 @@ public class AWSAuthService: AWSAuthServiceBehavior { public init() {} - public func getCredentialsProvider() -> CredentialsProvider { + public func getCredentialsProvider() -> CredentialsProviding { return AmplifyAWSCredentialsProvider() } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift index b9e9582418..e984116ede 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/AWSAuthServiceBehavior.swift @@ -11,7 +11,7 @@ import AWSClientRuntime public protocol AWSAuthServiceBehavior: AnyObject { - func getCredentialsProvider() -> CredentialsProvider + func getCredentialsProvider() -> CredentialsProviding func getTokenClaims(tokenString: String) -> Result<[String: AnyObject], AuthError> diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSCredentialsProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSCredentialsProvider.swift index 730760c54f..1959aa58b5 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSCredentialsProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSCredentialsProvider.swift @@ -10,7 +10,7 @@ import AWSClientRuntime import AwsCommonRuntimeKit import Foundation -public class AmplifyAWSCredentialsProvider: AWSClientRuntime.CredentialsProvider { +public class AmplifyAWSCredentialsProvider: AWSClientRuntime.CredentialsProviding { public func getCredentials() async throws -> AWSClientRuntime.AWSCredentials { let authSession = try await Amplify.Auth.fetchAuthSession() diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift index dfe7eb94a5..4da2777291 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/AmplifyAWSSignatureV4Signer.swift @@ -13,7 +13,7 @@ import AwsCommonRuntimeKit public protocol AWSSignatureV4Signer { func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, - credentialsProvider: AWSClientRuntime.CredentialsProvider, + credentialsProvider: AWSClientRuntime.CredentialsProviding, signingName: Swift.String, signingRegion: Swift.String, date: ClientRuntime.Date) async throws -> SdkHttpRequest? @@ -24,7 +24,7 @@ public class AmplifyAWSSignatureV4Signer: AWSSignatureV4Signer { } public func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, - credentialsProvider: AWSClientRuntime.CredentialsProvider, + credentialsProvider: AWSClientRuntime.CredentialsProviding, signingName: Swift.String, signingRegion: Swift.String, date: ClientRuntime.Date) async throws -> SdkHttpRequest? { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/IAMCredentialProvider.swift b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/IAMCredentialProvider.swift index 3d96e06798..3ceee7167e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/IAMCredentialProvider.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Auth/Provider/IAMCredentialProvider.swift @@ -10,7 +10,7 @@ import Amplify import AWSClientRuntime public protocol IAMCredentialsProvider { - func getCredentialsProvider() -> CredentialsProvider + func getCredentialsProvider() -> CredentialsProviding } public struct BasicIAMCredentialsProvider: IAMCredentialsProvider { @@ -20,7 +20,7 @@ public struct BasicIAMCredentialsProvider: IAMCredentialsProvider { self.authService = authService } - public func getCredentialsProvider() -> CredentialsProvider { + public func getCredentialsProvider() -> CredentialsProviding { return authService.getCredentialsProvider() } } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift b/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift index 0848074acc..c7ca2994c6 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift @@ -9,6 +9,54 @@ import Foundation import AWSClientRuntime import Amplify +// TODO: FrameworkMetadata Replacement +private let tokenNoHashCharacterSet = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!$%'*+-.^_`|~") +private let tokenCharacterSet = tokenNoHashCharacterSet.union(Set("#")) +private let substituteCharacter = Character("-") + +extension String { + + var userAgentToken: String { + String(map { tokenCharacterSet.contains($0) ? $0 : substituteCharacter }) + } + + var userAgentTokenNoHash: String { + String(map { tokenNoHashCharacterSet.contains($0) ? $0 : substituteCharacter }) + } +} + + +public struct FrameworkMetadata { + let name: String + let version: String + let extras: [String: String] + + var sanitizedName: String { + name.userAgentToken + } + var sanitizedVersion: String { + version.userAgentToken + } + + public init(name: String, version: String, extras: [String: String] = [String: String]()) { + self.name = name + self.version = version + self.extras = extras + } + } + +extension FrameworkMetadata: CustomStringConvertible { + public var description: String { + let extrasMetaData = !extras.isEmpty + ? extras.map { + " md/\($0.key.userAgentToken)/\($0.value.userAgentToken)" + }.joined() + : "" + return "lib/\(sanitizedName)/\(sanitizedVersion)\(extrasMetaData)" + } +} +// MARK: - End TODO: FrameworkMetadata Replacement + /// Convenience class that is used by Amplify to include metadata such as values for a "User-Agent" during /// server interactions. /// diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift index b503ed5f3d..763e43ac31 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift @@ -9,7 +9,7 @@ import Foundation import ClientRuntime extension Foundation.URLRequest { - init(sdkRequest: ClientRuntime.SdkHttpRequest) throws { + init(sdkRequest: ClientRuntime.SdkHttpRequest) async throws { guard let url = sdkRequest.endpoint.url else { throw FoundationClientEngineError.invalidRequestURL(sdkRequest: sdkRequest) } @@ -22,11 +22,7 @@ extension Foundation.URLRequest { } } - switch sdkRequest.body { - case .data(let data): httpBody = data - case .stream(let stream): httpBody = stream.toBytes().getData() - case .none: break - } + httpBody = try await sdkRequest.body.readData() } } @@ -49,7 +45,9 @@ extension ClientRuntime.HttpResponse { convenience init(httpURLResponse: HTTPURLResponse, data: Data) throws { let headers = Self.headers(from: httpURLResponse.allHeaderFields) - let body = HttpBody.stream(ByteStream.from(data: data)) + // TODO: double check if this works as expected + // Previously this needed to be `HttpBody.stream()` + let body = HttpBody.data(data) guard let statusCode = HttpStatusCode(rawValue: httpURLResponse.statusCode) else { // This shouldn't happen, but `HttpStatusCode` only exposes a failable diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/FoundationClientEngine.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/FoundationClientEngine.swift index 3bda16f9c1..cbf7f36be7 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/FoundationClientEngine.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/FoundationClientEngine.swift @@ -12,7 +12,7 @@ import Amplify @_spi(FoundationClientEngine) public struct FoundationClientEngine: HttpClientEngine { public func execute(request: ClientRuntime.SdkHttpRequest) async throws -> ClientRuntime.HttpResponse { - let urlRequest = try URLRequest(sdkRequest: request) + let urlRequest = try await URLRequest(sdkRequest: request) let (data, response) = try await URLSession.shared.data(for: urlRequest) guard let httpURLResponse = response as? HTTPURLResponse else { diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift index c21664e7a3..e03eb69ce3 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift @@ -25,13 +25,10 @@ extension UserAgentSuffixAppender: HttpClientEngine { guard let target = target else { throw ClientError.unknownError("HttpClientEngine is not set") } - var headers = request.headers - let currentUserAgent = headers.value(for: userAgentHeader) ?? "" - headers.update( - name: userAgentHeader, - value: "\(currentUserAgent) \(suffix)" - ) - request.headers = headers + + let currentUserAgent = request.headers.value(for: userAgentHeader) ?? "" + request.withHeader(name: userAgentHeader, value: "\(currentUserAgent) \(suffix)") + return try await target.execute(request: request) } } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift index d680cfee36..a112451510 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift @@ -31,7 +31,7 @@ class UserAgentSuffixAppenderTests: XCTestCase { /// Then: The user agent suffix is appended func testExecute_withExistingUserAgentHeader_shouldAppendSuffix() async throws { let request = createRequest() - request.headers.add(name: userAgentKey, value: "existingUserAgent") + request.withHeader(name: userAgentKey, value: "existingUserAgent") _ = try await appender.execute(request: request) XCTAssertEqual(httpClientEngine.executeCount, 1) @@ -72,8 +72,7 @@ class UserAgentSuffixAppenderTests: XCTestCase { private func createRequest() -> SdkHttpRequest { return SdkHttpRequest( method: .get, - endpoint: .init(host: "customHost"), - headers: .init() + endpoint: .init(host: "customHost") ) } } diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift index 7f6bd46fbf..8c5d7cfa62 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSAuthService.swift @@ -28,7 +28,7 @@ public class MockAWSAuthService: AWSAuthServiceBehavior { interactions.append(#function) } - public func getCredentialsProvider() -> CredentialsProvider { + public func getCredentialsProvider() -> CredentialsProviding { interactions.append(#function) let cognitoCredentialsProvider = MyCustomCredentialsProvider() return cognitoCredentialsProvider @@ -61,7 +61,7 @@ public class MockAWSAuthService: AWSAuthServiceBehavior { } } -struct MyCustomCredentialsProvider: CredentialsProvider { +struct MyCustomCredentialsProvider: CredentialsProviding { func getCredentials() async throws -> AWSClientRuntime.AWSCredentials { AWSCredentials( accessKey: "AKIDEXAMPLE", diff --git a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift index e4dc290015..090010b65a 100644 --- a/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift +++ b/AmplifyPlugins/Core/AWSPluginsTestCommon/MockAWSSignatureV4Signer.swift @@ -12,7 +12,7 @@ import Foundation class MockAWSSignatureV4Signer: AWSSignatureV4Signer { func sigV4SignedRequest(requestBuilder: SdkHttpRequestBuilder, - credentialsProvider: CredentialsProvider, + credentialsProvider: CredentialsProviding, signingName: String, signingRegion: String, date: Date) throws -> SdkHttpRequest? { diff --git a/Package.resolved b/Package.resolved index 681d2bacf7..56f06fed2e 100644 --- a/Package.resolved +++ b/Package.resolved @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/awslabs/aws-crt-swift", "state" : { - "revision" : "6feec6c3787877807aa9a00fad09591b96752376", - "version" : "0.6.1" + "revision" : "997904873945e074aaf5c51ea968d9a84684525a", + "version" : "0.13.0" } }, { @@ -32,8 +32,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/awslabs/aws-sdk-swift.git", "state" : { - "revision" : "24bae88a2391fe75da8a940a544d1ef6441f5321", - "version" : "0.13.0" + "revision" : "ace826dbfe96e7e3103fe7f45f815b8a590bcf21", + "version" : "0.26.0" } }, { @@ -57,10 +57,10 @@ { "identity" : "smithy-swift", "kind" : "remoteSourceControl", - "location" : "https://github.com/awslabs/smithy-swift", + "location" : "https://github.com/smithy-lang/smithy-swift", "state" : { - "revision" : "7b28da158d92cd06a3549140d43b8fbcf64a94a6", - "version" : "0.15.0" + "revision" : "eed3f3d8e5aa704fcd60bb227b0fc89bf3328c42", + "version" : "0.30.0" } }, { @@ -104,8 +104,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/MaxDesiatov/XMLCoder.git", "state" : { - "revision" : "b1e944cbd0ef33787b13f639a5418d55b3bed501", - "version" : "0.17.1" + "revision" : "80b4a1646399b8e4e0ce80711653476a85bd5e37", + "version" : "0.17.0" } } ], diff --git a/Package.swift b/Package.swift index 959479d75f..486a7c9310 100644 --- a/Package.swift +++ b/Package.swift @@ -9,7 +9,7 @@ let platforms: [SupportedPlatform] = [ .watchOS(.v9) ] let dependencies: [Package.Dependency] = [ - .package(url: "https://github.com/awslabs/aws-sdk-swift.git", exact: "0.13.0"), + .package(url: "https://github.com/awslabs/aws-sdk-swift.git", exact: "0.26.0"), .package(url: "https://github.com/aws-amplify/aws-appsync-realtime-client-ios.git", from: "3.0.0"), .package(url: "https://github.com/stephencelis/SQLite.swift.git", exact: "0.13.2"), .package(url: "https://github.com/mattgallagher/CwlPreconditionTesting.git", from: "2.1.0"), From 8c3eefa5da06b52094fc4583ef635c19ab988a1c Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Fri, 29 Sep 2023 13:45:54 -0400 Subject: [PATCH 03/23] fix: update sdk error handling in AWSCognitoAuthPlugin (#3251) --- .../AWSCognitoAuthPlugin+Configure.swift | 8 +- .../FetchIdentity/FetchAuthIdentityId.swift | 7 +- .../InformSessionError.swift | 13 +- .../SignIn/SRPAuth/VerifyPasswordSRP.swift | 6 +- .../SignIn/VerifySignInChallenge.swift | 6 +- ...CognitoIdentity+AuthErrorConvertible.swift | 116 ++++++ ...dentityProvider+AuthErrorConvertible.swift | 361 ++++++++++++++++++ ...teSoftwareTokenOutputError+AuthError.swift | 51 --- .../ErrorMapping/AuthErrorConvertible.swift | 1 - .../ChangePasswordOutputError+AuthError.swift | 63 --- .../ClientError+AuthErrorConvertible.swift | 33 ++ ...mForgotPasswordOutputError+AuthError.swift | 81 ---- .../ConfirmSignUpOutputError+AuthError.swift | 121 ------ .../DeleteUserOutputError+AuthError.swift | 55 --- .../ForgetDeviceOutputError+AuthError.swift | 58 --- .../ForgotPasswordOutputError+AuthError.swift | 90 ----- ...ialsForIdentityOutputError+AuthError.swift | 50 --- .../GetIdOutputError+AuthError.swift | 52 --- ...erificationCodeOutputError+AuthError.swift | 88 ----- .../GetUserOutputError+AuthError.swift | 56 --- .../InitiateAuthOutputError+AuthError.swift | 78 ---- .../ListDevicesOutputError+AuthError.swift | 58 --- ...endConfirmationCodeOutputError+Error.swift | 90 ----- ...ToAuthChallengeOutputError+AuthError.swift | 102 ----- .../ErrorMapping/SdkError+AuthError.swift | 136 ------- ...erMFAPreferenceOutputError+AuthError.swift | 57 --- .../SignUpOutputError+AuthError.swift | 120 ------ ...ateDeviceStatusOutputError+AuthError.swift | 58 --- ...eUserAttributesOutputError+AuthError.swift | 96 ----- ...fySoftwareTokenOutputError+AuthError.swift | 81 ---- ...fyUserAttributeOutputError+AuthError.swift | 105 ----- .../Service/SdkTypealiases.swift | 2 - .../ErrorMapping/SignInError+Helper.swift | 40 +- .../Task/AWSAuthChangePasswordTask.swift | 10 +- .../AWSAuthConfirmResetPasswordTask.swift | 4 +- .../Task/AWSAuthConfirmSignUpTask.swift | 12 +- .../Task/AWSAuthResendSignUpCodeTask.swift | 4 +- .../Task/AWSAuthResetPasswordTask.swift | 4 +- .../Task/AWSAuthSignUpTask.swift | 10 +- .../Task/AWSAuthWebUISignInTask.swift | 8 +- .../Task/FetchMFAPreferenceTask.swift | 4 +- .../Task/SetUpTOTPTask.swift | 4 +- .../Task/UpdateMFAPreferenceTask.swift | 4 +- ...hAttributeResendConfirmationCodeTask.swift | 12 +- .../AWSAuthConfirmUserAttributeTask.swift | 4 +- .../AWSAuthFetchUserAttributeTask.swift | 4 +- .../AWSAuthUpdateUserAttributeTask.swift | 7 +- .../AWSAuthUpdateUserAttributesTask.swift | 4 +- .../Task/VerifyTOTPSetupTask.swift | 4 +- 49 files changed, 561 insertions(+), 1877 deletions(-) create mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift create mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AssociateSoftwareTokenOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ChangePasswordOutputError+AuthError.swift create mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmForgotPasswordOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmSignUpOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/DeleteUserOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgetDeviceOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgotPasswordOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetCredentialsForIdentityOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetIdOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserAttributeVerificationCodeOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/InitiateAuthOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ListDevicesOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ResendConfirmationCodeOutputError+Error.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/RespondToAuthChallengeOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SdkError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SetUserMFAPreferenceOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SignUpOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateDeviceStatusOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateUserAttributesOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifySoftwareTokenOutputError+AuthError.swift delete mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifyUserAttributeOutputError+AuthError.swift diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift index ae80ff67f2..ab44a86fc8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift @@ -86,10 +86,10 @@ extension AWSCognitoAuthPlugin { private func makeUserPool() throws -> CognitoUserPoolBehavior { switch authConfiguration { case .userPools(let userPoolConfig), .userPoolsAndIdentityPools(let userPoolConfig, _): + // TODO: FrameworkMetadata Replacement let configuration = try CognitoIdentityProviderClient.CognitoIdentityProviderClientConfiguration( - endpointResolver: userPoolConfig.endpoint?.resolver, - frameworkMetadata: AmplifyAWSServiceConfiguration.frameworkMetaData(), - region: userPoolConfig.region + region: userPoolConfig.region, + serviceSpecific: .init(endpointResolver: userPoolConfig.endpoint?.resolver) ) if var httpClientEngineProxy = httpClientEngineProxy { @@ -121,8 +121,8 @@ extension AWSCognitoAuthPlugin { private func makeIdentityClient() throws -> CognitoIdentityBehavior { switch authConfiguration { case .identityPools(let identityPoolConfig), .userPoolsAndIdentityPools(_, let identityPoolConfig): + // TODO: FrameworkMetadata Replacement let configuration = try CognitoIdentityClient.CognitoIdentityClientConfiguration( - frameworkMetadata: AmplifyAWSServiceConfiguration.frameworkMetaData(), region: identityPoolConfig.region ) diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift index da2a09c174..97ffabda08 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/FetchIdentity/FetchAuthIdentityId.swift @@ -65,12 +65,7 @@ struct FetchAuthIdentityId: Action { } func isNotAuthorizedError(_ error: Error) -> Bool { - - if let getIdError: GetIdOutputError = error.internalAWSServiceError(), - case .notAuthorizedException = getIdError { - return true - } - return false + error is AWSCognitoIdentity.NotAuthorizedException } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift index 6c6107578f..c556bf89d4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/FetchAuthorizationSession/InformSessionError.swift @@ -37,17 +37,8 @@ struct InformSessionError: Action { } func isNotAuthorizedError(_ error: Error) -> Bool { - - - if let serviceError: GetCredentialsForIdentityOutputError = error.internalAWSServiceError(), - case .notAuthorizedException = serviceError { - return true - } - if let serviceError: InitiateAuthOutputError = error.internalAWSServiceError(), - case .notAuthorizedException = serviceError { - return true - } - return false + error is AWSCognitoIdentity.NotAuthorizedException + || error is AWSCognitoIdentityProvider.NotAuthorizedException } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift index ec5ccf0ade..969b2b1c93 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP.swift @@ -110,11 +110,7 @@ struct VerifyPasswordSRP: Action { return false } - if let serviceError: RespondToAuthChallengeOutputError = error.internalAWSServiceError(), - case .resourceNotFoundException = serviceError { - return true - } - return false + return error is AWSCognitoIdentityProvider.ResourceNotFoundException } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift index ac19a29d86..5761ac2d06 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/VerifySignInChallenge.swift @@ -89,11 +89,7 @@ struct VerifySignInChallenge: Action { return false } - if let serviceError: RespondToAuthChallengeOutputError = error.internalAWSServiceError(), - case .resourceNotFoundException = serviceError { - return true - } - return false + return error is AWSCognitoIdentityProvider.ResourceNotFoundException } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift new file mode 100644 index 0000000000..dd16b203a0 --- /dev/null +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCognitoIdentity+AuthErrorConvertible.swift @@ -0,0 +1,116 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AWSCognitoIdentity +import AWSClientRuntime + +// AWSCognitoIdentity +extension AWSCognitoIdentity.ExternalServiceException: AuthErrorConvertible { + var fallbackDescription: String { "External service threw error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.externalServiceException, + AWSCognitoAuthError.externalServiceException + ) + } +} + +extension AWSCognitoIdentity.InternalErrorException: AuthErrorConvertible { + var fallbackDescription: String { "Internal exception occurred" } + + var authError: AuthError { + .unknown(properties.message ?? fallbackDescription) + } +} + +// AWSCognitoIdentity +extension AWSCognitoIdentity.InvalidIdentityPoolConfigurationException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid IdentityPool Configuration error." } + + var authError: AuthError { + .configuration( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.configurationError + ) + } +} + +extension AWSCognitoIdentity.InvalidParameterException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid parameter error" } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.invalidParameterError, + AWSCognitoAuthError.invalidParameter + ) + } +} + +extension AWSCognitoIdentity.NotAuthorizedException: AuthErrorConvertible { + var fallbackDescription: String { "Not authorized error." } + + var authError: AuthError { + .notAuthorized( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.notAuthorizedError + ) + } +} + +extension AWSCognitoIdentity.ResourceConflictException: AuthErrorConvertible { + var fallbackDescription: String { "Resource conflict error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.resourceConflictException, + AWSCognitoAuthError.resourceConflictException + ) + } +} + +extension AWSCognitoIdentity.ResourceNotFoundException: AuthErrorConvertible { + var fallbackDescription: String { "Resource not found error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.resourceNotFoundError, + AWSCognitoAuthError.resourceNotFound + ) + } +} + +extension AWSCognitoIdentity.TooManyRequestsException: AuthErrorConvertible { + var fallbackDescription: String { "Too many requests error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.tooManyRequestError, + AWSCognitoAuthError.requestLimitExceeded + ) + } +} + + +extension AWSCognitoIdentity.LimitExceededException: AuthErrorConvertible { + var fallbackDescription: String { "Too many requests error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.limitExceededException, + AWSCognitoAuthError.limitExceededException + ) + } +} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift new file mode 100644 index 0000000000..6179940724 --- /dev/null +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AWSCongnitoIdentityProvider+AuthErrorConvertible.swift @@ -0,0 +1,361 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AWSCognitoIdentityProvider +import AWSClientRuntime + +extension ForbiddenException: AuthErrorConvertible { + var fallbackDescription: String { "Access to the requested resource is forbidden" } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.forbiddenError + ) + } +} + +extension InternalErrorException: AuthErrorConvertible { + var fallbackDescription: String { "Internal exception occurred" } + + var authError: AuthError { + .unknown(properties.message ?? fallbackDescription) + } +} + +extension InvalidParameterException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid parameter error" } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.invalidParameterError, + AWSCognitoAuthError.invalidParameter + ) + } +} + +extension InvalidPasswordException: AuthErrorConvertible { + var fallbackDescription: String { "Encountered invalid password." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.invalidPasswordError, + AWSCognitoAuthError.invalidPassword + ) + } +} + +extension LimitExceededException: AuthErrorConvertible { + var fallbackDescription: String { "Limit exceeded error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.limitExceededError, + AWSCognitoAuthError.limitExceeded + ) + } +} + +extension NotAuthorizedException: AuthErrorConvertible { + var fallbackDescription: String { "Not authorized error." } + + var authError: AuthError { + .notAuthorized( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.notAuthorizedError + ) + } +} + +extension PasswordResetRequiredException: AuthErrorConvertible { + var fallbackDescription: String { "Password reset required error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.passwordResetRequired, + AWSCognitoAuthError.passwordResetRequired + ) + } +} + +extension ResourceNotFoundException: AuthErrorConvertible { + var fallbackDescription: String { "Resource not found error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.resourceNotFoundError, + AWSCognitoAuthError.resourceNotFound + ) + } +} + +extension TooManyRequestsException: AuthErrorConvertible { + var fallbackDescription: String { "Too many requests error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.tooManyRequestError, + AWSCognitoAuthError.requestLimitExceeded + ) + } +} + +extension UserNotConfirmedException: AuthErrorConvertible { + var fallbackDescription: String { "User not confirmed error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.userNotConfirmedError, + AWSCognitoAuthError.userNotConfirmed + ) + } +} + +extension UserNotFoundException: AuthErrorConvertible { + var fallbackDescription: String { "User not found error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.userNotFoundError, + AWSCognitoAuthError.userNotFound + ) + } +} + +extension CodeMismatchException: AuthErrorConvertible { + var fallbackDescription: String { "Provided code does not match what the server was expecting." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.codeMismatchError, + AWSCognitoAuthError.codeMismatch + ) + } +} + +extension InvalidLambdaResponseException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid lambda response error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.lambdaError, + AWSCognitoAuthError.lambda + ) + } +} + + +extension ExpiredCodeException: AuthErrorConvertible { + var fallbackDescription: String { "Provided code has expired." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.codeExpiredError, + AWSCognitoAuthError.codeExpired + ) + } +} + +extension TooManyFailedAttemptsException: AuthErrorConvertible { + var fallbackDescription: String { "Too many failed attempts error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.tooManyFailedError, + AWSCognitoAuthError.failedAttemptsLimitExceeded + ) + } +} + +extension UnexpectedLambdaException: AuthErrorConvertible { + var fallbackDescription: String { "Unexpected lambda error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.lambdaError, + AWSCognitoAuthError.lambda + ) + } +} + +extension UserLambdaValidationException: AuthErrorConvertible { + var fallbackDescription: String { "User lambda validation error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.lambdaError, + AWSCognitoAuthError.lambda + ) + } +} + +extension AliasExistsException: AuthErrorConvertible { + var fallbackDescription: String { "Alias exists error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.aliasExistsError, + AWSCognitoAuthError.aliasExists + ) + } +} + +extension InvalidUserPoolConfigurationException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid UserPool Configuration error." } + + var authError: AuthError { + .configuration( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.configurationError + ) + } +} + +extension CodeDeliveryFailureException: AuthErrorConvertible { + var fallbackDescription: String { "Code Delivery Failure error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.codeDeliveryError, + AWSCognitoAuthError.codeDelivery + ) + } +} + +extension InvalidEmailRoleAccessPolicyException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid email role access policy error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.invalidEmailRoleError, + AWSCognitoAuthError.emailRole + ) + } +} + + +extension InvalidSmsRoleAccessPolicyException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid SMS Role Access Policy error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.invalidSMSRoleError, + AWSCognitoAuthError.smsRole + ) + } +} + +extension InvalidSmsRoleTrustRelationshipException: AuthErrorConvertible { + var fallbackDescription: String { "Invalid SMS Role Trust Relationship error." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.invalidSMSRoleError, + AWSCognitoAuthError.smsRole + ) + } +} + +extension MFAMethodNotFoundException: AuthErrorConvertible { + var fallbackDescription: String { "Amazon Cognito cannot find a multi-factor authentication (MFA) method." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.mfaMethodNotFoundError, + AWSCognitoAuthError.mfaMethodNotFound + ) + } +} + +extension SoftwareTokenMFANotFoundException: AuthErrorConvertible { + var fallbackDescription: String { "Software token TOTP multi-factor authentication (MFA) is not enabled for the user pool." } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.softwareTokenNotFoundError, + AWSCognitoAuthError.softwareTokenMFANotEnabled + ) + } +} + +extension UsernameExistsException: AuthErrorConvertible { + var fallbackDescription: String { "Username exists error" } + + var authError: AuthError { + .service( + properties.message ?? fallbackDescription, + AuthPluginErrorConstants.userNameExistsError, + AWSCognitoAuthError.usernameExists + ) + } +} + +extension AWSCognitoIdentityProvider.ConcurrentModificationException: AuthErrorConvertible { + var fallbackDescription: String { "Concurrent modification error" } + + var authError: AuthError { + .service( + message ?? fallbackDescription, + AuthPluginErrorConstants.concurrentModificationException + ) + } +} + + +extension AWSCognitoIdentityProvider.EnableSoftwareTokenMFAException: AuthErrorConvertible { + var fallbackDescription: String { "Unable to enable software token MFA" } + + var authError: AuthError { + .service( + message ?? fallbackDescription, + AuthPluginErrorConstants.softwareTokenNotFoundError, + AWSCognitoAuthError.softwareTokenMFANotEnabled + ) + } +} + +extension AWSClientRuntime.UnknownAWSHTTPServiceError: AuthErrorConvertible { + var fallbackDescription: String { "" } + + var authError: AuthError { + .unknown( + """ + Unknown service error occured with: + - status: \(httpResponse.statusCode) + - message: \(message ?? fallbackDescription) + """, + self + ) + } +} + + + + diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AssociateSoftwareTokenOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AssociateSoftwareTokenOutputError+AuthError.swift deleted file mode 100644 index 4adf7e6a0c..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AssociateSoftwareTokenOutputError+AuthError.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import AWSCognitoIdentityProvider - -extension AssociateSoftwareTokenOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .concurrentModificationException(let concurrentModificationException): - return .service( - concurrentModificationException.message ?? "Concurrent modification error", - AuthPluginErrorConstants.concurrentModificationException) - case .forbiddenException(let forbiddenException): - return .service( - forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - case .internalErrorException(let internalErrorException): - return .unknown( - internalErrorException.message ?? "Internal exception occurred") - case .invalidParameterException(let invalidParameterException): - return .service( - invalidParameterException.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .notAuthorizedException(let notAuthorizedException): - return .notAuthorized( - notAuthorizedException.message ?? "Not authorized Error", - AuthPluginErrorConstants.notAuthorizedError, - nil) - case .resourceNotFoundException(let resourceNotFoundException): - return AuthError.service( - resourceNotFoundException.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .softwareTokenMFANotFoundException(let exception): - return AuthError.service( - exception.message ?? "Software token TOTP multi-factor authentication (MFA) is not enabled for the user pool.", - AuthPluginErrorConstants.softwareTokenNotFoundError, - AWSCognitoAuthError.mfaMethodNotFound) - case .unknown(let unknownAWSHttpServiceError): - let statusCode = unknownAWSHttpServiceError._statusCode?.rawValue ?? -1 - let message = unknownAWSHttpServiceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift index 34b5a80ba1..e811b761d9 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/AuthErrorConvertible.swift @@ -11,7 +11,6 @@ import Amplify /// A type that can be represented as an AuthError /// protocol AuthErrorConvertible { - var authError: AuthError { get } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ChangePasswordOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ChangePasswordOutputError+AuthError.swift deleted file mode 100644 index 0aec3eeb86..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ChangePasswordOutputError+AuthError.swift +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension ChangePasswordOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return AuthError.service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let exception): - return AuthError.service(exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - case .invalidPasswordException(let exception): - return AuthError.service(exception.message ?? "Encountered invalid password.", - AuthPluginErrorConstants.invalidPasswordError, - AWSCognitoAuthError.invalidPassword) - case .limitExceededException(let limitExceededException): - return .service(limitExceededException.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded) - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift new file mode 100644 index 0000000000..942c410f70 --- /dev/null +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ClientError+AuthErrorConvertible.swift @@ -0,0 +1,33 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import ClientRuntime + +extension ClientError: AuthErrorConvertible { + var fallbackDescription: String { "Client Error" } + + var authError: AuthError { + switch self { + case .pathCreationFailed(let message), + .queryItemCreationFailed(let message), + .serializationFailed(let message), + .dataNotFound(let message): + return .service(message, "", self) + + case .authError(let message): + return .notAuthorized( + message, + "Check if you are authorized to perform the request" + ) + + case .unknownError(let message): + return AuthError.unknown(message, self) + } + } +} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmForgotPasswordOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmForgotPasswordOutputError+AuthError.swift deleted file mode 100644 index 9f004cb7a7..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmForgotPasswordOutputError+AuthError.swift +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension ConfirmForgotPasswordOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .codeMismatchException(let exception): - return AuthError.service(exception.message ?? "Provided code does not match what the server was expecting.", - AuthPluginErrorConstants.codeMismatchError, - AWSCognitoAuthError.codeMismatch) - case .expiredCodeException(let exception): - return AuthError.service(exception.message ?? "Provided code has expired.", - AuthPluginErrorConstants.codeExpiredError, - AWSCognitoAuthError.codeExpired) - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidLambdaResponseException(let exception): - return .service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidPasswordException(let exception): - return AuthError.service(exception.message ?? "Invalid password error", - AuthPluginErrorConstants.invalidPasswordError, - AWSCognitoAuthError.invalidPassword) - case .limitExceededException(let exception): - return .service(exception.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyFailedAttemptsException(let exception): - return AuthError.service(exception.message ?? "Too many failed attempts error", - AuthPluginErrorConstants.tooManyFailedError, - AWSCognitoAuthError.failedAttemptsLimitExceeded) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return .service(exception.message ?? "Unexpected lambda error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userLambdaValidationException(let exception): - return .service(exception.message ?? "User lambda validation error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userNotConfirmedException(let userNotConfirmedException): - return .service(userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmSignUpOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmSignUpOutputError+AuthError.swift deleted file mode 100644 index 1a29be5c77..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ConfirmSignUpOutputError+AuthError.swift +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import Foundation -import AWSCognitoIdentityProvider - -extension ConfirmSignUpOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .aliasExistsException(let exception): - - return .service( - exception.message ?? "Alias exists error", - AuthPluginErrorConstants.aliasExistsError, - AWSCognitoAuthError.aliasExists - ) - case .codeMismatchException(let exception): - - return .service( - exception.message ?? "Code mismatch error", - AuthPluginErrorConstants.codeMismatchError, - AWSCognitoAuthError.codeMismatch - ) - case .expiredCodeException(let exception): - - return .service( - exception.message ?? "Expired code error", - AuthPluginErrorConstants.codeExpiredError, - AWSCognitoAuthError.codeExpired - ) - case .limitExceededException(let exception): - - return .service( - exception.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded - ) - case .tooManyFailedAttemptsException(let exception): - - return .service( - exception.message ?? "Too many failed attempts error", - AuthPluginErrorConstants.tooManyFailedError, - AWSCognitoAuthError.requestLimitExceeded - ) - case .userNotFoundException(let exception): - - return .service( - exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound - ) - case .internalErrorException(let exception): - - return .unknown( - exception.message ?? "Internal exception occurred" - ) - case .invalidLambdaResponseException(let exception): - - return .service( - exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .invalidParameterException(let exception): - - return .service( - exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter - ) - case .notAuthorizedException(let exception): - - return .notAuthorized( - exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .resourceNotFoundException(let exception): - - return .service( - exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound - ) - case .tooManyRequestsException(let exception): - - return .service( - exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded - ) - case .unexpectedLambdaException(let exception): - - return .service( - exception.message ?? "Unexpected lambda error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .userLambdaValidationException(let exception): - - return .service( - exception.message ?? "User lambda validation error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } - -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/DeleteUserOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/DeleteUserOutputError+AuthError.swift deleted file mode 100644 index a858393471..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/DeleteUserOutputError+AuthError.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension DeleteUserOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authrozied error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return AuthError.service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let exception): - return AuthError.service(exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgetDeviceOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgetDeviceOutputError+AuthError.swift deleted file mode 100644 index 8208febe99..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgetDeviceOutputError+AuthError.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension ForgetDeviceOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidUserPoolConfigurationException(let exception): - return .configuration(exception.message ?? "Invalid UserPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .notAuthorizedException(let exception): - return .notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return .service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return .service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return .service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let userNotConfirmedException): - return .service(userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return .service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgotPasswordOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgotPasswordOutputError+AuthError.swift deleted file mode 100644 index 7e844880d4..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ForgotPasswordOutputError+AuthError.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension ForgotPasswordOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .codeDeliveryFailureException(let exception): - return .service( - exception.message ?? "Code Delivery Failure error", - AuthPluginErrorConstants.codeDeliveryError, - AWSCognitoAuthError.codeDelivery - ) - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidEmailRoleAccessPolicyException(let exception): - return .service( - exception.message ?? "Invalid email role access policy error", - AuthPluginErrorConstants.invalidEmailRoleError, - AWSCognitoAuthError.emailRole - ) - case .invalidLambdaResponseException(let exception): - return .service( - exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidSmsRoleAccessPolicyException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Access Policy error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole) - case .invalidSmsRoleTrustRelationshipException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Trust Relationship error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole) - case .limitExceededException(let exception): - return .service( - exception.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded - ) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return .service( - exception.message ?? "Unexpected lambda error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .userLambdaValidationException(let exception): - return .service( - exception.message ?? "User lambda validation error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetCredentialsForIdentityOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetCredentialsForIdentityOutputError+AuthError.swift deleted file mode 100644 index 1a26155124..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetCredentialsForIdentityOutputError+AuthError.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentity -import Amplify - -extension GetCredentialsForIdentityOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .externalServiceException(let externalServiceException): - return .service(externalServiceException.message ?? "External service threw error", - AuthPluginErrorConstants.externalServiceException, - AWSCognitoAuthError.externalServiceException) - case .internalErrorException(let internalErrorException): - return .unknown(internalErrorException.message ?? "Internal exception occurred") - case .invalidIdentityPoolConfigurationException(let invalidIdentityPoolConfigurationException): - return AuthError.configuration(invalidIdentityPoolConfigurationException.message ?? "Invalid IdentityPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .invalidParameterException(let invalidParameterException): - return AuthError.service(invalidParameterException.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .notAuthorizedException(let notAuthorizedException): - return .notAuthorized(notAuthorizedException.message ?? "Not authorized Error", - AuthPluginErrorConstants.notAuthorizedError, - nil) - case .resourceConflictException(let resourceConflictException): - return .service(resourceConflictException.message ?? "Resource conflict error", - AuthPluginErrorConstants.resourceConflictException, - AWSCognitoAuthError.resourceConflictException) - case .resourceNotFoundException(let resourceNotFoundException): - return AuthError.service(resourceNotFoundException.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let tooManyRequestsException): - return .service(tooManyRequestsException.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unknown(let unknownAWSHttpServiceError): - let statusCode = unknownAWSHttpServiceError._statusCode?.rawValue ?? -1 - let message = unknownAWSHttpServiceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetIdOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetIdOutputError+AuthError.swift deleted file mode 100644 index 37be0a6d7f..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetIdOutputError+AuthError.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentity -import Amplify - -extension GetIdOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .externalServiceException(let externalServiceException): - return .service(externalServiceException.message ?? "External service threw error", - AuthPluginErrorConstants.externalServiceException, - AWSCognitoAuthError.externalServiceException) - case .internalErrorException(let internalErrorException): - return .unknown(internalErrorException.message ?? "Internal exception occurred") - case .invalidParameterException(let invalidParameterException): - return .service(invalidParameterException.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .limitExceededException(let limitExceededException): - return .service(limitExceededException.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededException, - AWSCognitoAuthError.limitExceededException) - case .notAuthorizedException(let notAuthorizedException): - return .notAuthorized(notAuthorizedException.message ?? "Not authorized Error", - AuthPluginErrorConstants.notAuthorizedError, - nil) - case .resourceConflictException(let resourceConflictException): - return .service(resourceConflictException.message ?? "Resource conflict error", - AuthPluginErrorConstants.resourceConflictException, - AWSCognitoAuthError.resourceConflictException) - case .resourceNotFoundException(let resourceNotFoundException): - return AuthError.service(resourceNotFoundException.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let tooManyRequestsException): - return .service(tooManyRequestsException.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unknown(let unknownAWSHttpServiceError): - let statusCode = unknownAWSHttpServiceError._statusCode?.rawValue ?? -1 - let message = unknownAWSHttpServiceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - } - } - -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserAttributeVerificationCodeOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserAttributeVerificationCodeOutputError+AuthError.swift deleted file mode 100644 index 073837cb7d..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserAttributeVerificationCodeOutputError+AuthError.swift +++ /dev/null @@ -1,88 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension GetUserAttributeVerificationCodeOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .codeDeliveryFailureException(let exception): - return .service(exception.message ?? "Code Delivery Failure error", - AuthPluginErrorConstants.codeDeliveryError, - AWSCognitoAuthError.codeDelivery) - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidEmailRoleAccessPolicyException(let exception): - return .service(exception.message ?? "Invalid email role access policy error", - AuthPluginErrorConstants.invalidEmailRoleError, - AWSCognitoAuthError.emailRole) - case .invalidLambdaResponseException(let exception): - return .service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .invalidParameterException(let exception): - return .service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidSmsRoleAccessPolicyException(let exception): - return .service(exception.message ?? "Invalid SMS Role Access Policy error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.smsRole) - case .invalidSmsRoleTrustRelationshipException(let exception): - return .service(exception.message ?? "Invalid SMS Role Trust Relationship error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.smsRole) - case .limitExceededException(let limitExceededException): - return .service(limitExceededException.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded) - case .notAuthorizedException(let exception): - return .notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return .service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return .service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return .service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return .service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userLambdaValidationException(let exception): - return .service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userNotConfirmedException(let userNotConfirmedException): - return .service(userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let userNotFoundException): - return .service(userNotFoundException.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let unknownAWSHttpServiceError): - let statusCode = unknownAWSHttpServiceError._statusCode?.rawValue ?? -1 - let message = unknownAWSHttpServiceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } - -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserOutputError+AuthError.swift deleted file mode 100644 index bc364ab427..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/GetUserOutputError+AuthError.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension GetUserOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidParameterException(let exception): - return .service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .notAuthorizedException(let exception): - return .notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return .service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return .service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return .service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let userNotConfirmedException): - return .service(userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let userNotFoundException): - return .service(userNotFoundException.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let unknownAWSHttpServiceError): - let statusCode = unknownAWSHttpServiceError._statusCode?.rawValue ?? -1 - let message = unknownAWSHttpServiceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } - -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/InitiateAuthOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/InitiateAuthOutputError+AuthError.swift deleted file mode 100644 index e4e648af2a..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/InitiateAuthOutputError+AuthError.swift +++ /dev/null @@ -1,78 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension InitiateAuthOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidLambdaResponseException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidSmsRoleAccessPolicyException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Access Policy error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.smsRole) - case .invalidSmsRoleTrustRelationshipException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Trust Relationship error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.smsRole) - case .invalidUserPoolConfigurationException(let exception): - return AuthError.configuration(exception.message ?? "Invalid UserPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return AuthError.service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userLambdaValidationException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userNotConfirmedException(let exception): - return AuthError.service(exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ListDevicesOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ListDevicesOutputError+AuthError.swift deleted file mode 100644 index 42af26acf9..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ListDevicesOutputError+AuthError.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension ListDevicesOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidUserPoolConfigurationException(let exception): - return .configuration(exception.message ?? "Invalid UserPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .notAuthorizedException(let exception): - return .notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return .service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return .service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return .service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let userNotConfirmedException): - return .service(userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return .service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ResendConfirmationCodeOutputError+Error.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ResendConfirmationCodeOutputError+Error.swift deleted file mode 100644 index 2abc4185bb..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/ResendConfirmationCodeOutputError+Error.swift +++ /dev/null @@ -1,90 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension ResendConfirmationCodeOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .codeDeliveryFailureException(let exception): - return .service( - exception.message ?? "Code Delivery Failure error", - AuthPluginErrorConstants.codeDeliveryError, - AWSCognitoAuthError.codeDelivery - ) - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidEmailRoleAccessPolicyException(let exception): - return .service( - exception.message ?? "Invalid email role access policy error", - AuthPluginErrorConstants.invalidEmailRoleError, - AWSCognitoAuthError.emailRole - ) - case .invalidLambdaResponseException(let exception): - return .service( - exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidSmsRoleAccessPolicyException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Access Policy error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole) - case .invalidSmsRoleTrustRelationshipException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Trust Relationship error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole) - case .limitExceededException(let exception): - return .service( - exception.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded - ) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return .service( - exception.message ?? "Unexpected lambda error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .userLambdaValidationException(let exception): - return .service( - exception.message ?? "User lambda validation error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/RespondToAuthChallengeOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/RespondToAuthChallengeOutputError+AuthError.swift deleted file mode 100644 index eae169e4e6..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/RespondToAuthChallengeOutputError+AuthError.swift +++ /dev/null @@ -1,102 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension RespondToAuthChallengeOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .aliasExistsException(let exception): - return AuthError.service(exception.message ?? "An account with this email or phone already exists.", - AuthPluginErrorConstants.aliasExistsError, - AWSCognitoAuthError.aliasExists) - case .codeMismatchException(let exception): - return AuthError.service(exception.message ?? "Provided code does not match what the server was expecting.", - AuthPluginErrorConstants.codeMismatchError, - AWSCognitoAuthError.codeMismatch) - case .expiredCodeException(let exception): - return AuthError.service(exception.message ?? "Provided code has expired.", - AuthPluginErrorConstants.codeExpiredError, - AWSCognitoAuthError.codeExpired) - case .invalidPasswordException(let exception): - return AuthError.service(exception.message ?? "Encountered invalid password.", - AuthPluginErrorConstants.invalidPasswordError, - AWSCognitoAuthError.invalidPassword) - case .mFAMethodNotFoundException(let exception): - return AuthError.service(exception.message ?? "Amazon Cognito cannot find a multi-factor authentication (MFA) method.", - AuthPluginErrorConstants.mfaMethodNotFoundError, - AWSCognitoAuthError.mfaMethodNotFound) - case .softwareTokenMFANotFoundException(let exception): - return AuthError.service(exception.message ?? "Software token TOTP multi-factor authentication (MFA) is not enabled for the user pool.", - AuthPluginErrorConstants.softwareTokenNotFoundError, - AWSCognitoAuthError.softwareTokenMFANotEnabled) - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidLambdaResponseException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidSmsRoleAccessPolicyException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Access Policy error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole) - case .invalidSmsRoleTrustRelationshipException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Trust Relationship error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole) - case .invalidUserPoolConfigurationException(let exception): - return AuthError.configuration(exception.message ?? "Invalid UserPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authrozied error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return AuthError.service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userLambdaValidationException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userNotConfirmedException(let exception): - return AuthError.service(exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SdkError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SdkError+AuthError.swift deleted file mode 100644 index 5cea0f5d2e..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SdkError+AuthError.swift +++ /dev/null @@ -1,136 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import Amplify -import ClientRuntime - -extension SdkError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - - case .service(let serviceError, _): - if let authErrorMappable = serviceError as? AuthErrorConvertible { - return authErrorMappable.authError - } else if let otherError = serviceError as? Error { - return AuthError.service(otherError.localizedDescription, "", otherError) - } else { - return AuthError.unknown(String(describing: serviceError)) - } - case .client(let clientError, let httpResponse): - return convertToAuthError(clientError: clientError, httpResponse: httpResponse) - case .unknown(let unknownError): - return AuthError.unknown("An unknown error occured, check the underlying error for more details", - unknownError) - } - } - - func convertToAuthError(clientError: ClientError, - httpResponse: HttpResponse? = nil) -> AuthError { - switch clientError { - case .networkError(let error): - return AuthError.service(error.localizedDescription, - """ - Check your network connection, retry when the network is available. - HTTP Response stauts code: \(String(describing: httpResponse?.statusCode)) - """, - AWSCognitoAuthError.network) - - case .crtError(let cRTError): - return AuthError.service(cRTError.localizedDescription, - "Check the underlying error for more details", - cRTError) - - case .pathCreationFailed(let message): - return AuthError.service(message, "", clientError) - - case .queryItemCreationFailed(let message): - return AuthError.service(message, "", clientError) - - case .serializationFailed(let message): - return AuthError.service(message, "", clientError) - - case .deserializationFailed(let error): - return AuthError.service(error.localizedDescription, - "", - error) - - case .dataNotFound(let message): - return AuthError.service(message, "", clientError) - - case .authError(let message): - return AuthError.notAuthorized(message, "Check if you are authorized to perform the request") - - case .retryError(let error): - if let authError = error as? AuthErrorConvertible { - return authError.authError - } else { - return AuthError.service( - error.localizedDescription, - """ - Check your network connection, retry when the network is available. - HTTP Response stauts code: \(String(describing: httpResponse?.statusCode)) - """, - AWSCognitoAuthError.network) - - } - - case .unknownError(let message): - return AuthError.unknown(message, clientError) - } - } - -} - -extension Error { - func internalAWSServiceError() -> E? { - if let internalError = self as? E { - return internalError - } - - if let sdkError = self as? SdkError { - return sdkError.internalAWSServiceError() - } - return nil - } -} - -extension SdkError { - - func internalAWSServiceError() -> E? { - switch self { - - case .service(let error, _): - if let serviceError = error as? E { - return serviceError - } - - case .client(let clientError, _): - return clientError.internalAWSServiceError() - - default: break - - } - return nil - } -} - -extension ClientError { - - func internalAWSServiceError() -> E? { - switch self { - case .retryError(let retryError): - if let sdkError = retryError as? SdkError { - return sdkError.internalAWSServiceError() - } - - default: break - } - return nil - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SetUserMFAPreferenceOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SetUserMFAPreferenceOutputError+AuthError.swift deleted file mode 100644 index 0a58116414..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SetUserMFAPreferenceOutputError+AuthError.swift +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSCognitoIdentityProvider -import Amplify - -extension SetUserMFAPreferenceOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .internalErrorException(let exception): - return .unknown( - exception.message ?? "Internal exception occurred") - case .invalidParameterException(let exception): - return AuthError.service( - exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .notAuthorizedException(let exception): - return .notAuthorized( - exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return .service( - exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return .service( - exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .userNotConfirmedException(let userNotConfirmedException): - return .service( - userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return .service( - exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .forbiddenException(let forbiddenException): - return .service( - forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SignUpOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SignUpOutputError+AuthError.swift deleted file mode 100644 index dc530dc3b4..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/SignUpOutputError+AuthError.swift +++ /dev/null @@ -1,120 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import Foundation -import AWSCognitoIdentityProvider - -extension SignUpOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .codeDeliveryFailureException(let exception): - - return .service( - exception.message ?? "Code Delivery Failure error", - AuthPluginErrorConstants.codeDeliveryError, - AWSCognitoAuthError.codeDelivery - ) - case .internalErrorException(let exception): - - return .unknown( - exception.message ?? "Internal exception occurred" - ) - case .invalidEmailRoleAccessPolicyException(let exception): - - return .service( - exception.message ?? "Invalid email role access policy error", - AuthPluginErrorConstants.invalidEmailRoleError, - AWSCognitoAuthError.emailRole - ) - case .invalidLambdaResponseException(let exception): - - return .service( - exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .invalidParameterException(let exception): - - return .service( - exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter - ) - case .invalidPasswordException(let exception): - - return .service( - exception.message ?? "Invalid password error", - AuthPluginErrorConstants.invalidPasswordError, - AWSCognitoAuthError.invalidPassword - ) - case .invalidSmsRoleAccessPolicyException(let exception): - - return .service( - exception.message ?? "Invalid SMS role access policy error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole - ) - case .invalidSmsRoleTrustRelationshipException(let exception): - - return .service( - exception.message ?? "Invalid SMS role access policy error", - AuthPluginErrorConstants.invalidSMSRoleError, - AWSCognitoAuthError.smsRole - ) - case .notAuthorizedException(let exception): - - return .notAuthorized( - exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .resourceNotFoundException(let exception): - - return .service( - exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound - ) - case .tooManyRequestsException(let exception): - - return .service( - exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded - ) - case .unexpectedLambdaException(let exception): - - return .service( - exception.message ?? "Unexpected lambda error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .userLambdaValidationException(let exception): - - return .service( - exception.message ?? "User lambda validation error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda - ) - case .usernameExistsException(let exception): - - return .service( - exception.message ?? "Username exists error", - AuthPluginErrorConstants.userNameExistsError, - AWSCognitoAuthError.usernameExists - ) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } - -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateDeviceStatusOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateDeviceStatusOutputError+AuthError.swift deleted file mode 100644 index 5df867d387..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateDeviceStatusOutputError+AuthError.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentityProvider -import Amplify - -extension UpdateDeviceStatusOutputError: AuthErrorConvertible { - - var authError: AuthError { - switch self { - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidUserPoolConfigurationException(let exception): - return .configuration(exception.message ?? "Invalid UserPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .notAuthorizedException(let exception): - return .notAuthorized(exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return .service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return .service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return .service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let userNotConfirmedException): - return .service(userNotConfirmedException.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return .service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateUserAttributesOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateUserAttributesOutputError+AuthError.swift deleted file mode 100644 index 2d68f8c446..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/UpdateUserAttributesOutputError+AuthError.swift +++ /dev/null @@ -1,96 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Foundation -import AWSCognitoIdentity -import Amplify -import AWSCognitoIdentityProvider - -extension UpdateUserAttributesOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .aliasExistsException(let exception): - return AuthError.service(exception.message ?? "An account with this email or phone already exists.", - AuthPluginErrorConstants.aliasExistsError, - AWSCognitoAuthError.aliasExists) - case .codeMismatchException(let exception): - return AuthError.service(exception.message ?? "Provided code does not match what the server was expecting.", - AuthPluginErrorConstants.codeMismatchError, - AWSCognitoAuthError.codeMismatch) - case .expiredCodeException(let exception): - return AuthError.service(exception.message ?? "Provided code has expired.", - AuthPluginErrorConstants.codeExpiredError, - AWSCognitoAuthError.codeExpired) - case .internalErrorException(let exception): - return .unknown(exception.message ?? "Internal exception occurred") - case .invalidLambdaResponseException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .invalidParameterException(let exception): - return AuthError.service(exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidSmsRoleAccessPolicyException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Access Policy error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.smsRole) - case .invalidSmsRoleTrustRelationshipException(let exception): - return AuthError.service(exception.message ?? "Invalid SMS Role Trust Relationship error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.smsRole) - case .notAuthorizedException(let exception): - return AuthError.notAuthorized(exception.message ?? "Not authrozied error", - AuthPluginErrorConstants.notAuthorizedError) - case .passwordResetRequiredException(let exception): - return AuthError.service(exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let exception): - return AuthError.service(exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service(exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .unexpectedLambdaException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userLambdaValidationException(let exception): - return AuthError.service(exception.message ?? "Invalid lambda response error", - AuthPluginErrorConstants.lambdaError, - AWSCognitoAuthError.lambda) - case .userNotConfirmedException(let exception): - return AuthError.service(exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service(exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - case .codeDeliveryFailureException(let exception): - return .service(exception.message ?? "Code Delivery Failure error", - AuthPluginErrorConstants.codeDeliveryError, - AWSCognitoAuthError.codeDelivery) - case .invalidEmailRoleAccessPolicyException(let exception): - return .service(exception.message ?? "Invalid email role access policy error", - AuthPluginErrorConstants.invalidEmailRoleError, - AWSCognitoAuthError.emailRole) - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } - -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifySoftwareTokenOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifySoftwareTokenOutputError+AuthError.swift deleted file mode 100644 index d7b56959ad..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifySoftwareTokenOutputError+AuthError.swift +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import AWSCognitoIdentityProvider - -extension VerifySoftwareTokenOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .codeMismatchException(let exception): - return AuthError.service( - exception.message ?? "Provided code does not match what the server was expecting.", - AuthPluginErrorConstants.codeMismatchError, - AWSCognitoAuthError.codeMismatch) - case .enableSoftwareTokenMFAException(let exception): - return AuthError.service( - exception.message ?? "Unable to enable software token MFA", - AuthPluginErrorConstants.softwareTokenNotFoundError, - AWSCognitoAuthError.softwareTokenMFANotEnabled) - case .forbiddenException(let forbiddenException): - return .service( - forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - case .internalErrorException(let internalErrorException): - return .unknown( - internalErrorException.message ?? "Internal exception occurred") - case .invalidParameterException(let invalidParameterException): - return .service( - invalidParameterException.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter) - case .invalidUserPoolConfigurationException(let exception): - return .configuration( - exception.message ?? "Invalid UserPool Configuration error", - AuthPluginErrorConstants.configurationError) - case .notAuthorizedException(let notAuthorizedException): - return .notAuthorized( - notAuthorizedException.message ?? "Not authorized Error", - AuthPluginErrorConstants.notAuthorizedError, - nil) - case .passwordResetRequiredException(let exception): - return AuthError.service( - exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired) - case .resourceNotFoundException(let resourceNotFoundException): - return AuthError.service( - resourceNotFoundException.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound) - case .softwareTokenMFANotFoundException(let exception): - return AuthError.service( - exception.message ?? "Software token TOTP multi-factor authentication (MFA) is not enabled for the user pool.", - AuthPluginErrorConstants.softwareTokenNotFoundError, - AWSCognitoAuthError.mfaMethodNotFound) - case .tooManyRequestsException(let exception): - return AuthError.service( - exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded) - case .userNotConfirmedException(let exception): - return AuthError.service( - exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed) - case .userNotFoundException(let exception): - return AuthError.service( - exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound) - case .unknown(let unknownAWSHttpServiceError): - let statusCode = unknownAWSHttpServiceError._statusCode?.rawValue ?? -1 - let message = unknownAWSHttpServiceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifyUserAttributeOutputError+AuthError.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifyUserAttributeOutputError+AuthError.swift deleted file mode 100644 index 812e6b71ce..0000000000 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/VerifyUserAttributeOutputError+AuthError.swift +++ /dev/null @@ -1,105 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import Foundation -import AWSCognitoIdentityProvider - -extension VerifyUserAttributeOutputError: AuthErrorConvertible { - var authError: AuthError { - switch self { - case .codeMismatchException(let exception): - - return .service( - exception.message ?? "Code mismatch error", - AuthPluginErrorConstants.codeMismatchError, - AWSCognitoAuthError.codeMismatch - ) - case .expiredCodeException(let exception): - - return .service( - exception.message ?? "Expired code error", - AuthPluginErrorConstants.codeExpiredError, - AWSCognitoAuthError.codeExpired - ) - case .limitExceededException(let exception): - - return .service( - exception.message ?? "Limit exceeded error", - AuthPluginErrorConstants.limitExceededError, - AWSCognitoAuthError.limitExceeded - ) - case .userNotFoundException(let exception): - - return .service( - exception.message ?? "User not found error", - AuthPluginErrorConstants.userNotFoundError, - AWSCognitoAuthError.userNotFound - ) - case .internalErrorException(let exception): - - return .unknown( - exception.message ?? "Internal exception occurred" - ) - case .invalidParameterException(let exception): - - return .service( - exception.message ?? "Invalid parameter error", - AuthPluginErrorConstants.invalidParameterError, - AWSCognitoAuthError.invalidParameter - ) - case .notAuthorizedException(let exception): - - return .notAuthorized( - exception.message ?? "Not authorized error", - AuthPluginErrorConstants.notAuthorizedError - ) - case .resourceNotFoundException(let exception): - - return .service( - exception.message ?? "Resource not found error", - AuthPluginErrorConstants.resourceNotFoundError, - AWSCognitoAuthError.resourceNotFound - ) - case .tooManyRequestsException(let exception): - - return .service( - exception.message ?? "Too many requests error", - AuthPluginErrorConstants.tooManyRequestError, - AWSCognitoAuthError.requestLimitExceeded - ) - - case .unknown(let serviceError): - let statusCode = serviceError._statusCode?.rawValue ?? -1 - let message = serviceError._message ?? "" - return .unknown("Unknown service error occurred with status \(statusCode) \(message)") - - case .passwordResetRequiredException(let exception): - return .service( - exception.message ?? "Password reset required error", - AuthPluginErrorConstants.passwordResetRequired, - AWSCognitoAuthError.passwordResetRequired - ) - - case .userNotConfirmedException(let exception): - return AuthError.service( - exception.message ?? "User not confirmed error", - AuthPluginErrorConstants.userNotConfirmedError, - AWSCognitoAuthError.userNotConfirmed - ) - case .aliasExistsException(let exception): - return AuthError.service( - exception.message ?? "An account with this email or phone already exists.", - AuthPluginErrorConstants.aliasExistsError, - AWSCognitoAuthError.aliasExists) - - case .forbiddenException(let forbiddenException): - return .service(forbiddenException.message ?? "Access to the requested resource is forbidden", - AuthPluginErrorConstants.forbiddenError) - } - } -} diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift index 28d19fa107..c4328aac58 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/SdkTypealiases.swift @@ -9,6 +9,4 @@ import Foundation import AWSClientRuntime import ClientRuntime -public typealias SdkResult = Result> - public typealias NetworkResult = (Result) -> Void diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift index 9cec199958..31b7d6b12e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/ErrorMapping/SignInError+Helper.swift @@ -15,47 +15,19 @@ extension SignInError { var isUserNotConfirmed: Bool { switch self { case .service(error: let serviceError): - - if let internalError: InitiateAuthOutputError = serviceError.internalAWSServiceError(), - case .userNotConfirmedException = internalError { - return true - } - - if let internalError: RespondToAuthChallengeOutputError = serviceError.internalAWSServiceError(), - case .userNotConfirmedException = internalError { - return true - } - - if let internalError: VerifySoftwareTokenOutputError = serviceError.internalAWSServiceError(), - case .userNotConfirmedException = internalError { - return true - } - - default: break + return serviceError is AWSCognitoIdentityProvider.UserNotConfirmedException + default: + return false } - return false } var isResetPassword: Bool { switch self { case .service(error: let serviceError): - if let internalError: InitiateAuthOutputError = serviceError.internalAWSServiceError(), - case .passwordResetRequiredException = internalError { - return true - } - - if let internalError: RespondToAuthChallengeOutputError = serviceError.internalAWSServiceError(), - case .passwordResetRequiredException = internalError { - return true - } - - if let internalError: VerifySoftwareTokenOutputError = serviceError.internalAWSServiceError(), - case .passwordResetRequiredException = internalError { - return true - } - default: break + return serviceError is AWSCognitoIdentityProvider.PasswordResetRequiredException + default: + return false } - return false } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift index 32b7da1c83..ad3987d7f4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthChangePasswordTask.swift @@ -41,10 +41,12 @@ class AWSAuthChangePasswordTask: AuthChangePasswordTask, DefaultLogger { log.verbose("Received success") } catch let error as AuthErrorConvertible { throw error.authError - } catch let error as AuthError { - throw error - } catch let error { - throw AuthError.configuration("Unable to execute auth task", AuthPluginErrorConstants.configurationError, error) + } catch { + throw AuthError.configuration( + "Unable to execute auth task", + AuthPluginErrorConstants.configurationError, + error + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift index d8b485acb0..bd9c8e0bc4 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmResetPasswordTask.swift @@ -36,9 +36,7 @@ class AWSAuthConfirmResetPasswordTask: AuthConfirmResetPasswordTask, DefaultLogg try await confirmResetPassword() } catch let error as AuthErrorConvertible { 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/AWSAuthConfirmSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift index db0148eea5..962ae5c95a 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthConfirmSignUpTask.swift @@ -42,16 +42,14 @@ class AWSAuthConfirmSignUpTask: AuthConfirmSignUpTask, DefaultLogger { _ = try await client.confirmSignUp(input: input) log.verbose("Received success") return AuthSignUpResult(.done, userID: nil) - } catch let error as AuthError { - throw error - } catch let error as AuthErrorConvertible { + } catch let error as AuthErrorConvertible { throw error.authError - } catch let error { - let error = AuthError.configuration( + } catch { + throw AuthError.configuration( "Unable to create a Swift SDK user pool service", AuthPluginErrorConstants.configurationError, - error) - throw error + error + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift index a39373f944..44b1836d24 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResendSignUpCodeTask.swift @@ -38,9 +38,7 @@ class AWSAuthResendSignUpCodeTask: AuthResendSignUpCodeTask, DefaultLogger { return details } catch let error as AuthErrorConvertible { 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/AWSAuthResetPasswordTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift index 47b52040c0..a8bb33034e 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthResetPasswordTask.swift @@ -38,9 +38,7 @@ class AWSAuthResetPasswordTask: AuthResetPasswordTask, DefaultLogger { return result } catch let error as AuthErrorConvertible { 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/AWSAuthSignUpTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift index 6400464697..485663d3d8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthSignUpTask.swift @@ -52,16 +52,14 @@ class AWSAuthSignUpTask: AuthSignUpTask, DefaultLogger { let response = try await client.signUp(input: input) log.verbose("Received result") return response.authResponse - } catch let error as AuthError { - throw error } catch let error as AuthErrorConvertible { throw error.authError - } catch let error { - let error = AuthError.configuration( + } catch { + throw AuthError.configuration( "Unable to create a Swift SDK user pool service", AuthPluginErrorConstants.configurationError, - error) - throw error + error + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift index 9e48e9f2f0..be7690da99 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/AWSAuthWebUISignInTask.swift @@ -41,11 +41,9 @@ class AWSAuthWebUISignInTask: AuthWebUISignInTask, DefaultLogger { return result } catch let autherror as AuthErrorConvertible { throw autherror.authError - } catch let autherror as AuthError { - throw autherror - } catch let error { - let error = AuthError.unknown("Not able to signIn to the webUI", error) - throw error + } catch { + throw AuthError.unknown("Not able to signIn to the webUI", error) + } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift index 008b3647c1..b3a456214d 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/FetchMFAPreferenceTask.swift @@ -46,9 +46,7 @@ class FetchMFAPreferenceTask: AuthFetchMFAPreferenceTask, DefaultLogger { return try await fetchMFAPreference(with: accessToken) } catch let error as AuthErrorConvertible { 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/SetUpTOTPTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift index 78d90b3b6b..6a7ab2b6ea 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/SetUpTOTPTask.swift @@ -37,9 +37,7 @@ class SetUpTOTPTask: AuthSetUpTOTPTask, DefaultLogger { return try await setUpTOTP(with: accessToken) } catch let error as AuthErrorConvertible { 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/UpdateMFAPreferenceTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift index de0774fb7a..b9bedf4fe8 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UpdateMFAPreferenceTask.swift @@ -52,9 +52,7 @@ class UpdateMFAPreferenceTask: AuthUpdateMFAPreferenceTask, DefaultLogger { return try await updateMFAPreference(with: accessToken) } catch let error as AuthErrorConvertible { 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/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift index b169211da5..66796374ef 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthAttributeResendConfirmationCodeTask.swift @@ -37,12 +37,12 @@ class AWSAuthAttributeResendConfirmationCodeTask: AuthAttributeResendConfirmatio return devices } catch let error as AuthErrorConvertible { throw error.authError - } catch let error as AuthError { - throw error - } catch let error { - throw AuthError.configuration("Unable to execute auth task", - AuthPluginErrorConstants.configurationError, - error) + } catch { + throw AuthError.configuration( + "Unable to execute auth task", + AuthPluginErrorConstants.configurationError, + error + ) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift index 390f15a2c2..8ed94106df 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthConfirmUserAttributeTask.swift @@ -37,9 +37,7 @@ class AWSAuthConfirmUserAttributeTask: AuthConfirmUserAttributeTask { try await confirmUserAttribute(with: accessToken) } catch let error as AuthErrorConvertible { 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/UserTasks/AWSAuthFetchUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift index 5a4ce680a0..cf15cc9395 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthFetchUserAttributeTask.swift @@ -37,9 +37,7 @@ class AWSAuthFetchUserAttributeTask: AuthFetchUserAttributeTask { return try await getUserAttributes(with: accessToken) } catch let error as AuthErrorConvertible { 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/UserTasks/AWSAuthUpdateUserAttributeTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift index e0f6b9c386..9b25a406bf 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributeTask.swift @@ -36,11 +36,8 @@ class AWSAuthUpdateUserAttributeTask: AuthUpdateUserAttributeTask { return try await updateUserAttribute(with: accessToken) } catch let error as AuthErrorConvertible { throw error.authError - } catch let error as AuthError { - throw error - } catch let error { - let error = AuthError.unknown("Unable to execute auth task", error) - throw error + } catch { + throw AuthError.unknown("Unable to execute auth task", error) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift index 30879838b4..0b0b8ed3dd 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/UserTasks/AWSAuthUpdateUserAttributesTask.swift @@ -36,9 +36,7 @@ class AWSAuthUpdateUserAttributesTask: AuthUpdateUserAttributesTask { return try await updateUserAttribute(with: accessToken) } catch let error as AuthErrorConvertible { 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/VerifyTOTPSetupTask.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift index 38d49134b4..40156b2e12 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Task/VerifyTOTPSetupTask.swift @@ -41,9 +41,7 @@ class VerifyTOTPSetupTask: AuthVerifyTOTPSetupTask, DefaultLogger { with: accessToken, userCode: request.code) } catch let error as AuthErrorConvertible { throw error.authError - } catch let error as AuthError { - throw error - } catch let error { + } catch { throw AuthError.unknown("Unable to execute auth task", error) } } From e3a49ce8420cd69793f1230cf40056893a3d280b Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Fri, 29 Sep 2023 14:39:27 -0400 Subject: [PATCH 04/23] fix: new error handling in auth plugin unit test suites (#3254) --- .../VerifyPasswordSRPTests.swift | 13 +- .../SignOut/RevokeTokenTests.swift | 4 +- .../SignOut/SignOutGloballyTests.swift | 4 +- .../VerifySignInChallengeTests.swift | 13 +- .../ClientSecretConfigurationTests.swift | 2 +- .../AuthHubEventHandlerTests.swift | 15 +- ...AWSAuthFederationToIdentityPoolTests.swift | 8 +- ...AuthFetchSignInSessionOperationTests.swift | 14 +- .../AWSAuthSignOutTaskTests.swift | 4 +- ...uthenticationProviderDeleteUserTests.swift | 94 +++++----- ...entBehaviorConfirmResetPasswordTests.swift | 73 +++++--- .../ClientBehaviorResetPasswordTests.swift | 59 ++++-- .../MFA/FetchMFAPreferenceTaskTests.swift | 23 ++- .../MFA/SetUpTOTPTaskTests.swift | 47 +++-- .../MFA/UpdateMFAPreferenceTaskTests.swift | 23 ++- .../MFA/VerifyTOTPSetupTaskTests.swift | 79 ++++---- .../AWSAuthConfirmSignInTaskTests.swift | 100 ++++++----- .../AWSAuthMigrationSignInTaskTests.swift | 56 +++--- .../SignIn/AWSAuthSignInPluginTests.swift | 49 ++--- .../SignIn/ConfirmSignInTOTPTaskTests.swift | 95 ++++++---- ...nfirmSignInWithMFASelectionTaskTests.swift | 95 ++++++---- .../ConfirmSignInWithSetUpMFATaskTests.swift | 52 +++--- .../SignIn/SignInSetUpTOTPTests.swift | 26 +-- .../SignUp/AWSAuthConfirmSignUpAPITests.swift | 44 ++--- .../AWSAuthConfirmSignUpTaskTests.swift | 11 +- .../AWSAuthResendSignUpCodeAPITests.swift | 59 ++++-- .../SignUp/AWSAuthSignUpAPITests.swift | 37 ++-- .../SignUp/AWSAuthSignUpTaskTests.swift | 5 +- .../DeviceBehaviorFetchDevicesTests.swift | 41 +++-- .../DeviceBehaviorForgetDeviceTests.swift | 80 ++++++--- .../DeviceBehaviorRememberDeviceTests.swift | 46 +++-- .../AWSCognitoAuthUserBehaviorTests.swift | 4 +- .../UserBehaviorChangePasswordTests.swift | 48 +++-- .../UserBehaviorConfirmAttributeTests.swift | 32 ++-- .../UserBehaviorFetchAttributeTests.swift | 31 ++-- .../UserBehaviorResendCodeTests.swift | 28 +-- .../UserBehaviorUpdateAttributeTests.swift | 51 +++--- .../AmplifyAuthCognitoPluginTests.swift | 14 +- ...ChangePasswordOutputResponse+Codable.swift | 2 +- .../TestHarness/AuthTestHarness.swift | 4 +- .../TestHarness/AuthTestHarnessInput.swift | 19 +- .../CognitoAPIDecodingHelper.swift | 169 ++++++++++-------- .../Mocks/MockCredentialsProvider.swift | 2 +- 43 files changed, 1026 insertions(+), 649 deletions(-) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift index 5700fa456b..74efd601fb 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyPasswordSRPTests.swift @@ -7,6 +7,7 @@ import XCTest import AWSCognitoIdentityProvider +import AWSClientRuntime @testable import AWSPluginsTestCommon @testable import AWSCognitoAuthPlugin @@ -393,7 +394,13 @@ class VerifyPasswordSRPTests: XCTestCase { let identityProviderFactory: CognitoFactory = { MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw try RespondToAuthChallengeOutputError(httpResponse: MockHttpResponse.ok) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: MockHttpResponse.ok, + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) } @@ -441,9 +448,7 @@ class VerifyPasswordSRPTests: XCTestCase { let identityProviderFactory: CognitoFactory = { MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.resourceNotFoundException( - ResourceNotFoundException() - ) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift index d73b22ae01..eeab3c66de 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/RevokeTokenTests.swift @@ -18,7 +18,7 @@ class RevokeTokenTests: XCTestCase { MockIdentityProvider( mockRevokeTokenResponse: { _ in revokeTokenInvoked.fulfill() - return try RevokeTokenOutputResponse(httpResponse: MockHttpResponse.ok) + return try await RevokeTokenOutputResponse(httpResponse: MockHttpResponse.ok) } ) } @@ -86,7 +86,7 @@ class RevokeTokenTests: XCTestCase { let identityProviderFactory: BasicUserPoolEnvironment.CognitoUserPoolFactory = { MockIdentityProvider( mockRevokeTokenResponse: { _ in - return try RevokeTokenOutputResponse(httpResponse: MockHttpResponse.ok) + return try await RevokeTokenOutputResponse(httpResponse: MockHttpResponse.ok) } ) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift index e13d8f2548..d0af7dd4e5 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/SignOut/SignOutGloballyTests.swift @@ -18,7 +18,7 @@ class SignOutGloballyTests: XCTestCase { MockIdentityProvider( mockGlobalSignOutResponse: { _ in globalSignOutInvoked.fulfill() - return try GlobalSignOutOutputResponse(httpResponse: MockHttpResponse.ok) + return try await GlobalSignOutOutputResponse(httpResponse: MockHttpResponse.ok) } ) } @@ -82,7 +82,7 @@ class SignOutGloballyTests: XCTestCase { let identityProviderFactory: BasicUserPoolEnvironment.CognitoUserPoolFactory = { MockIdentityProvider( mockGlobalSignOutResponse: { _ in - return try GlobalSignOutOutputResponse(httpResponse: MockHttpResponse.ok) + return try await GlobalSignOutOutputResponse(httpResponse: MockHttpResponse.ok) } ) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift index b0d5dba2c0..b123bdc820 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/VerifySignInChallenge/VerifySignInChallengeTests.swift @@ -7,6 +7,7 @@ import XCTest import AWSCognitoIdentityProvider +import AWSClientRuntime @testable import AWSPluginsTestCommon @testable import AWSCognitoAuthPlugin @@ -158,7 +159,13 @@ class VerifySignInChallengeTests: XCTestCase { let identityProviderFactory: CognitoFactory = { MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw try RespondToAuthChallengeOutputError(httpResponse: MockHttpResponse.ok) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: MockHttpResponse.ok, + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) } @@ -205,9 +212,7 @@ class VerifySignInChallengeTests: XCTestCase { let identityProviderFactory: CognitoFactory = { MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.resourceNotFoundException( - ResourceNotFoundException() - ) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift index 55bd81bec7..2c63eced5e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ConfigurationTests/ClientSecretConfigurationTests.swift @@ -104,7 +104,7 @@ class ClientSecretConfigurationTests: XCTestCase { mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { request in XCTAssertNotNil(request.secretHash) - return try ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) + return try await ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) } ) try await plugin.confirmResetPassword( diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift index 097407401d..63ce899f7a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/HubEventTests/AuthHubEventHandlerTests.swift @@ -337,12 +337,12 @@ class AuthHubEventHandlerTests: XCTestCase { let mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - try DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) } ) @@ -359,10 +359,10 @@ class AuthHubEventHandlerTests: XCTestCase { let mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) } ) @@ -397,8 +397,9 @@ class AuthHubEventHandlerTests: XCTestCase { let mockIdentityProvider = MockIdentityProvider( mockInitiateAuthResponse: { _ in - throw try InitiateAuthOutputError.notAuthorizedException( - NotAuthorizedException.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw try await AWSCognitoIdentityProvider.NotAuthorizedException( + httpResponse: .init(body: .empty, statusCode: .ok) + ) }) configurePlugin(initialState: initialState, userPoolFactory: mockIdentityProvider) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift index 76f3c02779..41caa72e6c 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFederationToIdentityPoolTests.swift @@ -264,7 +264,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let getId: MockIdentity.MockGetIdResponse = { _ in if shouldThrowError { - throw GetIdOutputError.internalErrorException(.init()) + throw AWSCognitoIdentity.InternalErrorException() } else { return .init(identityId: "mockIdentityId") } @@ -787,7 +787,7 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let getCredentials: MockIdentity.MockGetCredentialsResponse = { input in if shouldThrowError { - throw GetCredentialsForIdentityOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentity.InvalidParameterException() } else { return .init(credentials: credentials, identityId: mockIdentityId) } @@ -859,12 +859,12 @@ class AWSAuthFederationToIdentityPoolTests: BaseAuthorizationTests { let getId: MockIdentity.MockGetIdResponse = { _ in XCTFail("GetId should not be called") - throw GetIdOutputError.internalErrorException(.init()) + throw AWSCognitoIdentity.InternalErrorException() } let getCredentials: MockIdentity.MockGetCredentialsResponse = { _ in if shouldThrowError { - throw GetCredentialsForIdentityOutputError.internalErrorException(.init()) + throw AWSCognitoIdentity.InternalErrorException() } else { return .init(credentials: credentials, identityId: mockIdentityId) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift index 51e0e00d86..bc209b500f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/AuthorizationTests/AWSAuthFetchSignInSessionOperationTests.swift @@ -209,8 +209,9 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { AmplifyCredentials.testDataWithExpiredTokens)) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - throw try InitiateAuthOutputError.notAuthorizedException( - NotAuthorizedException.init(httpResponse: MockHttpResponse.ok)) + throw try await AWSCognitoIdentityProvider.NotAuthorizedException( + httpResponse: MockHttpResponse.ok + ) } let plugin = configurePluginWith(userPool: { MockIdentityProvider(mockInitiateAuthResponse: initAuth) }, initialState: initialState) @@ -265,8 +266,8 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { } let awsCredentials: MockIdentity.MockGetCredentialsResponse = { _ in - throw try GetCredentialsForIdentityOutputError.notAuthorizedException( - NotAuthorizedException.init(httpResponse: MockHttpResponse.ok) + throw try await AWSCognitoIdentityProvider.NotAuthorizedException( + httpResponse: MockHttpResponse.ok ) } @@ -655,10 +656,7 @@ class AWSAuthFetchSignInSessionOperationTests: BaseAuthorizationTests { AmplifyCredentials.testDataWithExpiredTokens)) let initAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in - let notAuthorized = InitiateAuthOutputError.notAuthorizedException(.init(message: "NotAuthorized")) - let serviceError = SdkError.service(notAuthorized, .init(body: .none, statusCode: .accepted)) - let clientError = ClientError.retryError(serviceError) - throw SdkError.client(clientError, nil) + throw AWSCognitoIdentityProvider.NotAuthorizedException(message: "NotAuthorized") } let plugin = configurePluginWith( diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift index 1d84bbd17d..094e68c275 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AWSAuthSignOutTaskTests.swift @@ -41,7 +41,7 @@ class AWSAuthSignOutTaskTests: BasePluginTest { mockRevokeTokenResponse: { _ in return .testData }, mockGlobalSignOutResponse: { _ in - throw GlobalSignOutOutputError.internalErrorException(.init()) + throw AWSCognitoIdentityProvider.InternalErrorException() }) guard let result = await plugin.signOut(options: .init(globalSignOut: true)) as? AWSCognitoSignOutResult, case .partial(revokeTokenError: let revokeTokenError, @@ -59,7 +59,7 @@ class AWSAuthSignOutTaskTests: BasePluginTest { func testRevokeSignOutFailed() async { self.mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - throw RevokeTokenOutputError.internalErrorException(.init()) + throw AWSCognitoIdentityProvider.InternalErrorException() }, mockGlobalSignOutResponse: { _ in return .testData }) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift index b308b04586..c24e5357ba 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift @@ -13,18 +13,19 @@ import XCTest import AWSCognitoIdentityProvider import ClientRuntime import AwsCommonRuntimeKit +import AWSClientRuntime class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserSuccess() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - try DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) } ) do { @@ -48,12 +49,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testSignOutFailureWhenDeleteUserIsSuccess() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - throw RevokeTokenOutputError.unsupportedTokenTypeException(.init()) + throw AWSCognitoIdentityProvider.UnsupportedTokenTypeException() }, mockGlobalSignOutResponse: { _ in - throw GlobalSignOutOutputError.internalErrorException(.init()) + throw AWSCognitoIdentityProvider.InternalErrorException() }, mockDeleteUserOutputResponse: { _ in - try DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) } ) do { @@ -75,16 +76,17 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { /// - Then: /// - I should get a .service error with .network as underlying error /// - func testOfflineDeleteUser() async { + func testOfflineDeleteUser() async throws { + // TODO: How are client side retry errors now modeled? + throw XCTSkip() mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - let crtError = ClientRuntime.ClientError.retryError(CommonRunTimeError.crtError(CRTError(code: 1059))) - throw SdkError.client(crtError) + throw CommonRunTimeError.crtError(CRTError(code: 1059)) } ) do { @@ -110,16 +112,17 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { /// - I should get a .service error with .network as underlying error for the first call /// - I should get a valid response for the second call /// - func testOfflineDeleteUserAndRetry() async { + func testOfflineDeleteUserAndRetry() async throws { + // TODO: How are client side retry errors now modeled? + throw XCTSkip() mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - let crtError = ClientRuntime.ClientError.retryError(CommonRunTimeError.crtError(CRTError(code: 1059))) - throw SdkError.client(crtError) + throw CommonRunTimeError.crtError(CRTError(code: 1059)) } ) do { @@ -135,12 +138,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - try DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await DeleteUserOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) } ) do { @@ -166,12 +169,17 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserInternalErrorException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.unknown(.init(httpResponse: .init(body: .empty, statusCode: .badRequest))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .badRequest), + message: nil, + requestID: nil, + typeName: nil + ) } ) @@ -199,12 +207,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithInvalidParameterException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() } ) @@ -233,12 +241,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithNotAuthorizedException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) @@ -266,12 +274,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithPasswordResetRequiredException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() } ) @@ -300,12 +308,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithResourceNotFoundException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() } ) @@ -334,12 +342,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithTooManyRequestsException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() } ) @@ -368,12 +376,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithUserNotConfirmedException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() } ) @@ -403,12 +411,12 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { func testDeleteUserWithUserNotFoundException() async { mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in - try RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockGlobalSignOutResponse: { _ in - try GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await GlobalSignOutOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockDeleteUserOutputResponse: { _ in - throw DeleteUserOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() } ) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift index c518c7ab0a..83ee5c4c3a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorConfirmResetPasswordTests.swift @@ -21,7 +21,7 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests super.setUp() mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - try ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) + try await ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) } ) } @@ -63,7 +63,7 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests func testSuccessfulConfirmResetPassword() async throws { mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - try ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) + try await ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) } ) try await plugin.confirmResetPassword(for: "username", with: "newpassword", confirmationCode: "code", options: nil) @@ -81,7 +81,7 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - try ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) + try await ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) } ) do { @@ -109,7 +109,7 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockConfirmForgotPasswordOutputResponse: { request in XCTAssertNoThrow(request.clientMetadata) XCTAssertEqual(request.clientMetadata?["key"], "value") - return try ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) + return try await ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) } ) let pluginOptions = AWSAuthConfirmResetPasswordOptions(metadata: ["key": "value"]) @@ -131,7 +131,7 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - try ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) + try await ConfirmForgotPasswordOutputResponse(httpResponse: MockHttpResponse.ok) } ) do { @@ -158,7 +158,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.codeMismatchException(CodeMismatchException(message: "code mismatch")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "code mismatch" + ) } ) do { @@ -189,7 +191,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.expiredCodeException(ExpiredCodeException(message: "code expired")) + throw AWSCognitoIdentityProvider.ExpiredCodeException( + message: "code expired" + ) } ) do { @@ -219,7 +223,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.internalErrorException(InternalErrorException(message: "internal error")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "internal error" + ) } ) do { @@ -245,10 +251,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests func testConfirmResetPasswordWithInvalidLambdaResponseException() async throws { mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw SdkError.service( - ConfirmForgotPasswordOutputError.invalidLambdaResponseException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InvalidLambdaResponseException( + httpResponse: .init(body: .empty, statusCode: .accepted) + ) } ) do { @@ -280,7 +285,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.invalidParameterException(InvalidParameterException(message: "invalid parameter")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter" + ) } ) do { @@ -312,7 +319,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.invalidPasswordException(InvalidPasswordException(message: "invalid password")) + throw AWSCognitoIdentityProvider.InvalidPasswordException( + message: "invalid password" + ) } ) do { @@ -344,7 +353,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.limitExceededException(LimitExceededException(message: "limit exceeded")) + throw AWSCognitoIdentityProvider.LimitExceededException( + message: "limit exceeded" + ) } ) do { @@ -376,7 +387,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) do { @@ -404,7 +417,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) do { @@ -436,7 +451,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.tooManyFailedAttemptsException(TooManyFailedAttemptsException(message: "too many failed attempts")) + throw AWSCognitoIdentityProvider.TooManyFailedAttemptsException( + message: "too many failed attempts" + ) } ) do { @@ -468,7 +485,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) do { @@ -500,7 +519,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.unexpectedLambdaException(UnexpectedLambdaException(message: "unexpected lambda")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "unexpected lambda" + ) } ) do { @@ -532,7 +553,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.userLambdaValidationException(UserLambdaValidationException(message: "user lambda invalid")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "user lambda invalid" + ) } ) do { @@ -564,7 +587,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.userNotConfirmedException(UserNotConfirmedException(message: "user not confirmed")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "user not confirmed" + ) } ) do { @@ -596,7 +621,9 @@ class ClientBehaviorConfirmResetPasswordTests: AWSCognitoAuthClientBehaviorTests mockIdentityProvider = MockIdentityProvider( mockConfirmForgotPasswordOutputResponse: { _ in - throw ConfirmForgotPasswordOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift index 59e440aa9e..1b53c1be34 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/ClientBehaviorResetPasswordTests.swift @@ -141,7 +141,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.codeDeliveryFailureException(CodeDeliveryFailureException(message: "Code delivery failure")) + throw AWSCognitoIdentityProvider.CodeDeliveryFailureException( + message: "Code delivery failure" + ) } ) do { @@ -171,10 +173,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw SdkError.service( - ForgotPasswordOutputError.internalErrorException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InternalErrorException( + httpResponse: .init(body: .empty, statusCode: .accepted) + ) } ) do { @@ -200,7 +201,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { func testResetPasswordWithInvalidEmailRoleAccessPolicyException() async throws { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.invalidEmailRoleAccessPolicyException(InvalidEmailRoleAccessPolicyException(message: "invalid email role")) + throw AWSCognitoIdentityProvider.InvalidEmailRoleAccessPolicyException( + message: "invalid email role" + ) } ) do { @@ -230,7 +233,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { func testResetPasswordWithInvalidLambdaResponseException() async throws { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.invalidLambdaResponseException(InvalidLambdaResponseException(message: "Invalid lambda response")) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( + message: "Invalid lambda response" + ) } ) do { @@ -262,7 +267,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.invalidParameterException(InvalidParameterException(message: "invalid parameter")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter" + ) } ) do { @@ -292,7 +299,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { func testResetPasswordWithInvalidSmsRoleAccessPolicyException() async throws { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.invalidSmsRoleAccessPolicyException(InvalidSmsRoleAccessPolicyException(message: "invalid sms role")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( + message: "invalid sms role" + ) } ) do { @@ -322,7 +331,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { func testResetPasswordWithInvalidSmsRoleTrustRelationshipException() async throws { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.invalidSmsRoleTrustRelationshipException(InvalidSmsRoleTrustRelationshipException(message: "invalid sms role trust relationship")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( + message: "invalid sms role trust relationship" + ) } ) do { @@ -354,7 +365,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.limitExceededException(LimitExceededException(message: "limit exceeded")) + throw AWSCognitoIdentityProvider.LimitExceededException( + message: "limit exceeded" + ) } ) do { @@ -386,7 +399,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) do { @@ -414,7 +429,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) do { @@ -446,7 +463,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) do { @@ -478,7 +497,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.unexpectedLambdaException(UnexpectedLambdaException(message: "unexpected lambda")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "unexpected lambda" + ) } ) do { @@ -510,7 +531,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.userLambdaValidationException(UserLambdaValidationException(message: "user lambda validation exception")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "user lambda validation exception" + ) } ) do { @@ -585,7 +608,9 @@ class ClientBehaviorResetPasswordTests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockForgotPasswordOutputResponse: { _ in - throw ForgotPasswordOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift index 11a7b322a9..e713f439d8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/FetchMFAPreferenceTaskTests.swift @@ -11,6 +11,7 @@ import XCTest import Amplify @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import AWSClientRuntime // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -186,7 +187,13 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithInternalErrorException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.unknown(.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) do { @@ -211,7 +218,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithInvalidParameterException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) do { @@ -240,7 +247,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithNotAuthorizedException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.notAuthorizedException(.init(message: "message")) + throw AWSCognitoIdentityProvider.NotAuthorizedException(message: "message") }) do { @@ -267,7 +274,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithPasswordResetRequiredException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) do { @@ -298,7 +305,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithResourceNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) do { @@ -329,7 +336,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithTooManyRequestsException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() }) do { @@ -360,7 +367,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithUserNotConfirmedException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) do { _ = try await plugin.fetchMFAPreference() @@ -390,7 +397,7 @@ class FetchMFAPreferenceTaskTests: BasePluginTest { func testFetchMFAPreferenceWithUserNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() }) do { _ = try await plugin.fetchMFAPreference() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift index 67083280a7..7d21c937a3 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/SetUpTOTPTaskTests.swift @@ -11,6 +11,7 @@ import XCTest import Amplify @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import AWSClientRuntime // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -54,8 +55,9 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .concurrentModificationException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.ConcurrentModificationException( + message: "Exception" + ) }) do { @@ -85,8 +87,9 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .forbiddenException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.ForbiddenException( + message: "Exception" + ) }) do { @@ -116,8 +119,9 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .internalErrorException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "Exception" + ) }) do { @@ -147,8 +151,9 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .invalidParameterException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "Exception" + ) }) do { @@ -180,8 +185,9 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .notAuthorizedException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Exception" + ) }) do { @@ -209,8 +215,9 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .softwareTokenMFANotFoundException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( + message: "Exception" + ) }) do { @@ -221,7 +228,7 @@ class SetUpTOTPTaskTests: BasePluginTest { XCTFail("Should produce service error instead of \(error)") return } - guard case .mfaMethodNotFound = (underlyingError as? AWSCognitoAuthError) else { + guard case .softwareTokenMFANotEnabled = (underlyingError as? AWSCognitoAuthError) else { XCTFail("Underlying error should be softwareTokenMFANotEnabled \(error)") return } @@ -240,8 +247,9 @@ class SetUpTOTPTaskTests: BasePluginTest { func testSetUpTOTPInWithResourceNotFoundException() async { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .resourceNotFoundException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "Exception" + ) }) do { @@ -272,8 +280,13 @@ class SetUpTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockAssociateSoftwareTokenResponse: { request in - throw AssociateSoftwareTokenOutputError - .unknown(.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift index 29c9b0b41b..a4c6fa9d27 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/UpdateMFAPreferenceTaskTests.swift @@ -11,6 +11,7 @@ import XCTest import Amplify @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import AWSClientRuntime // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -80,7 +81,13 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.unknown(.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) } ) @@ -113,7 +120,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() } ) @@ -150,7 +157,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.notAuthorizedException(.init(message: "message")) + throw AWSCognitoIdentityProvider.NotAuthorizedException(message: "message") } ) @@ -185,7 +192,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() } ) @@ -224,7 +231,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() } ) @@ -263,7 +270,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.forbiddenException(.init()) + throw AWSCognitoIdentityProvider.ForbiddenException() } ) @@ -298,7 +305,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() } ) do { @@ -336,7 +343,7 @@ class UpdateMFAPreferenceTaskTests: BasePluginTest { ) }, mockSetUserMFAPreferenceResponse: { _ in - throw SetUserMFAPreferenceOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift index 125df7031e..0cd03bf4e9 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/MFA/VerifyTOTPSetupTaskTests.swift @@ -11,6 +11,7 @@ import XCTest import Amplify @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider +import AWSClientRuntime // swiftlint:disable type_body_length // swiftlint:disable file_length @@ -57,8 +58,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .forbiddenException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.ForbiddenException( + message: "Exception" + ) }) do { @@ -88,8 +90,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .internalErrorException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "Exception" + ) }) do { @@ -119,8 +122,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .invalidParameterException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "Exception" + ) }) do { @@ -152,8 +156,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .notAuthorizedException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Exception" + ) }) do { @@ -175,14 +180,15 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { /// - When: /// - I invoke verifyTOTPSetup /// - Then: - /// - I should get a .service error with .mfaMethodNotFound as underlyingError + /// - I should get a .service error with .softwareTokenMFANotEnabled as underlyingError /// func testVerifyTOTPSetupWithSoftwareTokenMFANotFoundException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .softwareTokenMFANotFoundException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( + message: "Exception" + ) }) do { @@ -193,7 +199,7 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { XCTFail("Should produce service error instead of \(error)") return } - guard case .mfaMethodNotFound = (underlyingError as? AWSCognitoAuthError) else { + guard case .softwareTokenMFANotEnabled = (underlyingError as? AWSCognitoAuthError) else { XCTFail("Underlying error should be softwareTokenMFANotEnabled \(error)") return } @@ -212,8 +218,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithResourceNotFoundException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .resourceNotFoundException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "Exception" + ) }) do { @@ -244,8 +251,13 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .unknown(.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) do { @@ -271,8 +283,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .codeMismatchException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -302,8 +315,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithEnableSoftwareTokenMFAException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .enableSoftwareTokenMFAException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.EnableSoftwareTokenMFAException( + message: "Exception" + ) }) do { @@ -333,8 +347,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithPasswordResetRequiredException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .passwordResetRequiredException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "Exception" + ) }) do { @@ -364,8 +379,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithTooManyRequestsException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .tooManyRequestsException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "Exception" + ) }) do { @@ -395,8 +411,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithUserNotFoundException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .userNotFoundException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "Exception" + ) }) do { @@ -426,8 +443,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithUserNotConfirmedException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .userNotConfirmedException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "Exception" + ) }) do { @@ -457,8 +475,9 @@ class VerifyTOTPSetupTaskTests: BasePluginTest { func testVerifyTOTPSetupInWithInvalidUserPoolConfigurationException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError - .invalidUserPoolConfigurationException(.init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( + message: "Exception" + ) }) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift index 9e21edf0bc..da1a27739a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthConfirmSignInTaskTests.swift @@ -164,8 +164,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.aliasExistsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.AliasExistsException( + message: "Exception" + ) }) do { @@ -176,10 +177,7 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { XCTFail("Should produce service error instead of \(error)") return } - guard case .aliasExists = (underlyingError as? AWSCognitoAuthError) else { - XCTFail("Underlying error should be aliasExists \(error)") - return - } + XCTAssertEqual(underlyingError as? AWSCognitoAuthError, .aliasExists) } } @@ -195,8 +193,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { func testConfirmSignInWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -217,8 +216,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { func testConfirmSignInRetryWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -261,8 +261,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.expiredCodeException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.ExpiredCodeException( + message: "Exception" + ) }) do { @@ -292,8 +293,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.internalErrorException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "Exception" + ) }) do { @@ -319,8 +321,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { func testConfirmSignInWithInvalidLambdaResponseException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidLambdaResponseException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( + message: "Exception" + ) }) do { @@ -352,8 +355,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidParameterException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "Exception" + ) }) do { @@ -385,8 +389,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidPasswordException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidPasswordException( + message: "Exception" + ) }) do { @@ -416,8 +421,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidSmsRoleAccessPolicyException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( + message: "Exception" + ) }) do { @@ -447,8 +453,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidSmsRoleTrustRelationshipException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( + message: "Exception" + ) }) do { @@ -526,8 +533,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.mFAMethodNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( + message: "Exception" + ) }) do { @@ -559,8 +567,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.notAuthorizedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Exception" + ) }) do { @@ -588,8 +597,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.passwordResetRequiredException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "Exception" + ) }) do { @@ -618,8 +628,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.softwareTokenMFANotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( + message: "Exception" + ) }) do { @@ -651,8 +662,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.tooManyRequestsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "Exception" + ) }) do { @@ -684,8 +696,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.unexpectedLambdaException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "Exception" + ) }) do { @@ -717,8 +730,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userLambdaValidationException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "Exception" + ) }) do { @@ -750,8 +764,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userNotConfirmedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "Exception" + ) }) do { @@ -779,8 +794,9 @@ class AuthenticationProviderConfirmSigninTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "Exception" + ) }) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift index e1116dbbb9..fe9dc91900 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthMigrationSignInTaskTests.swift @@ -92,7 +92,7 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.internalErrorException(.init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.InternalErrorException(message: "Error Occurred") } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -115,7 +115,7 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.invalidLambdaResponseException(.init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException(message: "Error Occurred") } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -142,7 +142,7 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.invalidParameterException(.init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.InvalidParameterException(message: "Error Occurred") } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -169,8 +169,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.invalidSmsRoleAccessPolicyException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -197,8 +198,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.invalidUserPoolConfigurationException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -221,8 +223,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.notAuthorizedException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -245,8 +248,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.passwordResetRequiredException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -268,8 +272,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.resourceNotFoundException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -295,8 +300,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.tooManyRequestsException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -322,8 +328,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.unexpectedLambdaException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -349,8 +356,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.userLambdaValidationException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -376,8 +384,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.userNotConfirmedException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) @@ -399,8 +408,9 @@ class AWSAuthMigrationSignInTaskTests: XCTestCase { let initiateAuth: MockIdentityProvider.MockInitiateAuthResponse = { _ in initiateAuthExpectation.fulfill() - throw InitiateAuthOutputError.userNotFoundException( - .init(message: "Error Occurred")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "Error Occurred" + ) } mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: initiateAuth) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift index 481a7324ef..7302e89996 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/AWSAuthSignInPluginTests.swift @@ -783,7 +783,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithInternalErrorException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.internalErrorException(.init()) + throw AWSCognitoIdentityProvider.InternalErrorException() }) let options = AuthSignInRequest.Options() @@ -811,7 +811,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithInvalidLambdaResponseException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.invalidLambdaResponseException(.init()) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException() }) let options = AuthSignInRequest.Options() @@ -840,7 +840,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithInvalidParameterException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) let options = AuthSignInRequest.Options() @@ -869,7 +869,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithInvalidUserPoolConfigurationException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.invalidUserPoolConfigurationException(.init()) + throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException() }) let options = AuthSignInRequest.Options() @@ -897,7 +897,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithNotAuthorizedException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() }) let options = AuthSignInRequest.Options() @@ -925,7 +925,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithPasswordResetRequiredException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) let options = AuthSignInRequest.Options() @@ -954,10 +954,12 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithPasswordResetRequiredException2() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - let serviceError = SdkError - .service(.passwordResetRequiredException(PasswordResetRequiredException()), - .init(body: .none, statusCode: .badRequest)) - throw SdkError.client(.retryError(serviceError), nil) + throw try await AWSCognitoIdentityProvider.PasswordResetRequiredException( + httpResponse: .init(body: .none, statusCode: .badRequest), + decoder: nil, + message: nil, + requestID: nil + ) }) let options = AuthSignInRequest.Options() @@ -986,7 +988,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithResourceNotFoundException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) let options = AuthSignInRequest.Options() @@ -1015,7 +1017,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithTooManyRequestsException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() }) let options = AuthSignInRequest.Options() @@ -1044,7 +1046,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithUnexpectedLambdaException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.unexpectedLambdaException(.init()) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException() }) let options = AuthSignInRequest.Options() @@ -1073,7 +1075,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithUserLambdaValidationException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.userLambdaValidationException(.init()) + throw AWSCognitoIdentityProvider.UserLambdaValidationException() }) let options = AuthSignInRequest.Options() @@ -1101,7 +1103,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { /// func testSignInWithUserNotConfirmedException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) let options = AuthSignInRequest.Options() @@ -1130,10 +1132,9 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithUserNotConfirmedException2() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - let serviceError = SdkError - .service(.userNotConfirmedException(UserNotConfirmedException()), - .init(body: .none, statusCode: .badRequest)) - throw SdkError.client(.retryError(serviceError), nil) + throw try await AWSCognitoIdentityProvider.UserNotConfirmedException( + httpResponse: .init(body: .none, statusCode: .badRequest) + ) }) let options = AuthSignInRequest.Options() @@ -1162,7 +1163,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { func testSignInWithUserNotFoundException() async { self.mockIdentityProvider = MockIdentityProvider(mockInitiateAuthResponse: { _ in - throw InitiateAuthOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() }) let options = AuthSignInRequest.Options() @@ -1199,7 +1200,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { challengeParameters: InitiateAuthOutputResponse.validChalengeParams, session: "someSession") }, mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.aliasExistsException(.init()) + throw AWSCognitoIdentityProvider.AliasExistsException() }) let options = AuthSignInRequest.Options() @@ -1234,7 +1235,7 @@ class AWSAuthSignInPluginTests: BasePluginTest { challengeParameters: InitiateAuthOutputResponse.validChalengeParams, session: "someSession") }, mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidPasswordException(.init()) + throw AWSCognitoIdentityProvider.InvalidPasswordException() }) let options = AuthSignInRequest.Options() @@ -1330,7 +1331,9 @@ class AWSAuthSignInPluginTests: BasePluginTest { self.mockIdentity = MockIdentity( mockGetIdResponse: { _ in - throw GetIdOutputError.invalidParameterException(.init(message: "Invalid parameter passed")) + throw AWSCognitoIdentity.InvalidParameterException( + message: "Invalid parameter passed" + ) }, mockGetCredentialsResponse: getCredentials) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift index 8c8b3bce14..98849dce07 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInTOTPTaskTests.swift @@ -170,8 +170,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.aliasExistsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.AliasExistsException( + message: "Exception" + ) }) do { @@ -201,8 +202,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { func testConfirmSignInWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -232,8 +234,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { func testConfirmSignInRetryWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -276,8 +279,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.expiredCodeException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.ExpiredCodeException( + message: "Exception" + ) }) do { @@ -307,8 +311,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.internalErrorException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "Exception" + ) }) do { @@ -334,8 +339,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { func testConfirmSignInWithInvalidLambdaResponseException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidLambdaResponseException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( + message: "Exception" + ) }) do { @@ -367,8 +373,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidParameterException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "Exception" + ) }) do { @@ -400,8 +407,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidPasswordException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidPasswordException( + message: "Exception" + ) }) do { @@ -431,8 +439,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidSmsRoleAccessPolicyException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( + message: "Exception" + ) }) do { @@ -462,8 +471,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidSmsRoleTrustRelationshipException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( + message: "Exception" + ) }) do { @@ -541,8 +551,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.mFAMethodNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( + message: "Exception" + ) }) do { @@ -574,8 +585,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.notAuthorizedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Exception" + ) }) do { @@ -603,8 +615,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.passwordResetRequiredException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "Exception" + ) }) do { @@ -633,8 +646,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.softwareTokenMFANotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( + message: "Exception" + ) }) do { @@ -666,8 +680,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.tooManyRequestsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "Exception" + ) }) do { @@ -699,8 +714,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.unexpectedLambdaException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "Exception" + ) }) do { @@ -732,8 +748,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userLambdaValidationException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "Exception" + ) }) do { @@ -765,8 +782,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userNotConfirmedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "Exception" + ) }) do { @@ -794,8 +812,9 @@ class ConfirmSignInTOTPTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "Exception" + ) }) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift index b7c442f3a9..da3e22fa6c 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithMFASelectionTaskTests.swift @@ -200,8 +200,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.aliasExistsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.AliasExistsException( + message: "Exception" + ) }) do { @@ -231,8 +232,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { func testConfirmSignInWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -264,8 +266,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { func testConfirmSignInRetryWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) }) do { @@ -312,8 +315,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.expiredCodeException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.ExpiredCodeException( + message: "Exception" + ) }) do { @@ -343,8 +347,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.internalErrorException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "Exception" + ) }) do { @@ -370,8 +375,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { func testConfirmSignInWithInvalidLambdaResponseException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidLambdaResponseException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( + message: "Exception" + ) }) do { @@ -403,8 +409,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidParameterException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "Exception" + ) }) do { @@ -436,8 +443,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidPasswordException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidPasswordException( + message: "Exception" + ) }) do { @@ -467,8 +475,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { func testConfirmSignInWithinvalidSmsRoleAccessPolicyException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidSmsRoleAccessPolicyException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( + message: "Exception" + ) }) do { @@ -498,8 +507,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { func testConfirmSignInWithInvalidSmsRoleTrustRelationshipException() async { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.invalidSmsRoleTrustRelationshipException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( + message: "Exception" + ) }) do { @@ -577,8 +587,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.mFAMethodNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.MFAMethodNotFoundException( + message: "Exception" + ) }) do { @@ -610,8 +621,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.notAuthorizedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Exception" + ) }) do { @@ -639,8 +651,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.passwordResetRequiredException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "Exception" + ) }) do { @@ -669,8 +682,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.softwareTokenMFANotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( + message: "Exception" + ) }) do { @@ -702,8 +716,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.tooManyRequestsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "Exception" + ) }) do { @@ -735,8 +750,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.unexpectedLambdaException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "Exception" + ) }) do { @@ -768,8 +784,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userLambdaValidationException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "Exception" + ) }) do { @@ -801,8 +818,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userNotConfirmedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "Exception" + ) }) do { @@ -830,8 +848,9 @@ class ConfirmSignInWithMFASelectionTaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockRespondToAuthChallengeResponse: { _ in - throw RespondToAuthChallengeOutputError.userNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "Exception" + ) }) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift index 67dfc8ef6c..b0ab9ad69a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/ConfirmSignInWithSetUpMFATaskTests.swift @@ -152,8 +152,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) } ) @@ -186,8 +187,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { func testConfirmSignInRetryWithCodeMismatchException() async { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.codeMismatchException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.CodeMismatchException( + message: "Exception" + ) } ) @@ -237,8 +239,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.internalErrorException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "Exception" + ) } ) @@ -267,8 +270,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.invalidParameterException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "Exception" + ) }) do { @@ -346,8 +350,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.notAuthorizedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "Exception" + ) }) do { @@ -375,8 +380,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.passwordResetRequiredException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "Exception" + ) }) do { @@ -405,8 +411,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.softwareTokenMFANotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException( + message: "Exception" + ) }) do { @@ -417,7 +424,7 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { XCTFail("Should produce service error instead of \(error)") return } - guard case .mfaMethodNotFound = (underlyingError as? AWSCognitoAuthError) else { + guard case .softwareTokenMFANotEnabled = (underlyingError as? AWSCognitoAuthError) else { XCTFail("Underlying error should be softwareTokenMFANotEnabled \(error)") return } @@ -438,8 +445,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.tooManyRequestsException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "Exception" + ) }) do { @@ -471,8 +479,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.userNotConfirmedException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "Exception" + ) }) do { @@ -500,8 +509,9 @@ class ConfirmSignInWithSetUpMFATaskTests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockVerifySoftwareTokenResponse: { request in - throw VerifySoftwareTokenOutputError.userNotFoundException( - .init(message: "Exception")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "Exception" + ) }) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift index bcf1cb0e02..6a6e10ab93 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignIn/SignInSetUpTOTPTests.swift @@ -10,7 +10,7 @@ import AWSCognitoIdentity @testable import Amplify @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider -import ClientRuntime +import AWSClientRuntime class SignInSetUpTOTPTests: BasePluginTest { @@ -254,7 +254,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.internalErrorException(.init()) + throw AWSCognitoIdentityProvider.InternalErrorException() }) let options = AuthSignInRequest.Options() @@ -292,7 +292,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) let options = AuthSignInRequest.Options() @@ -331,7 +331,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() }) let options = AuthSignInRequest.Options() @@ -369,7 +369,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) let options = AuthSignInRequest.Options() @@ -408,7 +408,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.concurrentModificationException(.init()) + throw AWSCognitoIdentityProvider.ConcurrentModificationException() }) let options = AuthSignInRequest.Options() @@ -446,7 +446,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.forbiddenException(.init()) + throw AWSCognitoIdentityProvider.ForbiddenException() }) let options = AuthSignInRequest.Options() @@ -484,7 +484,7 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.softwareTokenMFANotFoundException(.init()) + throw AWSCognitoIdentityProvider.SoftwareTokenMFANotFoundException() }) let options = AuthSignInRequest.Options() @@ -493,7 +493,7 @@ class SignInSetUpTOTPTests: BasePluginTest { XCTFail("Should not produce result - \(result)") } catch { guard case AuthError.service(_, _, let underlyingError) = error, - case .mfaMethodNotFound = (underlyingError as? AWSCognitoAuthError) else { + case .softwareTokenMFANotEnabled = (underlyingError as? AWSCognitoAuthError) else { XCTFail("Should produce resourceNotFound error but instead produced \(error)") return } @@ -523,7 +523,13 @@ class SignInSetUpTOTPTests: BasePluginTest { challenge: .mfaSetup, challengeParameters: ["MFAS_CAN_SETUP": "[\"SMS_MFA\",\"SOFTWARE_TOKEN_MFA\"]"]) }, mockAssociateSoftwareTokenResponse: { input in - throw AssociateSoftwareTokenOutputError.unknown(.init(httpResponse: .init(body: .empty, statusCode: .accepted))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) let options = AuthSignInRequest.Options() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift index 2b65918975..fe5c8124c2 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpAPITests.swift @@ -11,6 +11,7 @@ import AWSCognitoIdentity @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import AWSClientRuntime class AWSAuthConfirmSignUpAPITests: BasePluginTest { @@ -114,18 +115,18 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { func testSignUpServiceError() async { - let errorsToTest: [(confirmSignUpOutputError: ConfirmSignUpOutputError, cognitoError: AWSCognitoAuthError)] = [ - (.aliasExistsException(.init()), .aliasExists), - (.codeMismatchException(.init()), .codeMismatch), - (.invalidLambdaResponseException(.init()), .lambda), - (.invalidParameterException(.init()), .invalidParameter), - (.resourceNotFoundException(.init()), .resourceNotFound), - (.tooManyRequestsException(.init()), .requestLimitExceeded), - (.unexpectedLambdaException(.init()), .lambda), - (.userLambdaValidationException(.init()), .lambda), - (.userNotFoundException(.init()), .userNotFound), - (.limitExceededException(.init()), .limitExceeded), - (.tooManyFailedAttemptsException(.init()), .requestLimitExceeded), + let errorsToTest: [(confirmSignUpOutputError: Error, cognitoError: AWSCognitoAuthError)] = [ + (AWSCognitoIdentityProvider.AliasExistsException(), .aliasExists), + (AWSCognitoIdentityProvider.CodeMismatchException(), .codeMismatch), + (AWSCognitoIdentityProvider.InvalidLambdaResponseException(), .lambda), + (AWSCognitoIdentityProvider.InvalidParameterException(), .invalidParameter), + (AWSCognitoIdentityProvider.ResourceNotFoundException(), .resourceNotFound), + (AWSCognitoIdentityProvider.TooManyRequestsException(), .requestLimitExceeded), + (AWSCognitoIdentityProvider.UnexpectedLambdaException(), .lambda), + (AWSCognitoIdentityProvider.UserLambdaValidationException(), .lambda), + (AWSCognitoIdentityProvider.UserNotFoundException(), .userNotFound), + (AWSCognitoIdentityProvider.LimitExceededException(), .limitExceeded), + (AWSCognitoIdentityProvider.TooManyFailedAttemptsException(), .failedAttemptsLimitExceeded) ] for errorToTest in errorsToTest { @@ -139,7 +140,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in - throw ConfirmSignUpOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) @@ -171,10 +172,9 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in - throw SdkError.service( - ConfirmSignUpOutputError.internalErrorException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InternalErrorException( + httpResponse: .init(body: .empty, statusCode: .accepted) + ) } ) @@ -202,8 +202,12 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in - throw ConfirmSignUpOutputError.unknown( - .init(httpResponse: .init(body: .empty, statusCode: .accepted))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError.init( + httpResponse: .init(body: .empty, statusCode: .accepted), + message: nil, + requestID: nil, + typeName: nil + ) } ) @@ -228,7 +232,7 @@ class AWSAuthConfirmSignUpAPITests: BasePluginTest { } func validateConfirmSignUpServiceErrors( - confirmSignUpOutputError: ConfirmSignUpOutputError, + confirmSignUpOutputError: Error, expectedCognitoError: AWSCognitoAuthError) async { self.mockIdentityProvider = MockIdentityProvider( mockConfirmSignUpResponse: { _ in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift index 9236e24c98..990deb5615 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthConfirmSignUpTaskTests.swift @@ -16,7 +16,7 @@ import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon import ClientRuntime - +import AWSClientRuntime import AWSCognitoIdentityProvider class AWSAuthConfirmSignUpTaskTests: XCTestCase { @@ -33,7 +33,7 @@ class AWSAuthConfirmSignUpTaskTests: XCTestCase { let functionExpectation = expectation(description: "API call should be invoked") let confirmSignUp: MockIdentityProvider.MockConfirmSignUpResponse = { _ in functionExpectation.fulfill() - return try .init(httpResponse: MockHttpResponse.ok) + return try await .init(httpResponse: MockHttpResponse.ok) } let authEnvironment = Defaults.makeDefaultAuthEnvironment( @@ -52,7 +52,12 @@ class AWSAuthConfirmSignUpTaskTests: XCTestCase { let functionExpectation = expectation(description: "API call should be invoked") let confirmSignUp: MockIdentityProvider.MockConfirmSignUpResponse = { _ in functionExpectation.fulfill() - throw try ConfirmSignUpOutputError(httpResponse: MockHttpResponse.ok) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: MockHttpResponse.ok, + message: nil, + requestID: nil, + typeName: nil + ) } let authEnvironment = Defaults.makeDefaultAuthEnvironment( diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift index d8cf555e19..80858c4bf8 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthResendSignUpCodeAPITests.swift @@ -148,10 +148,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw SdkError.service( - ResendConfirmationCodeOutputError.codeDeliveryFailureException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.CodeDeliveryFailureException( + httpResponse: .init(body: .empty, statusCode: .accepted) + ) } ) do { @@ -180,7 +179,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithInternalErrorException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.internalErrorException(InternalErrorException(message: "internal error")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "internal error" + ) } ) do { @@ -206,7 +207,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithInvalidEmailRoleAccessPolicyException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.invalidEmailRoleAccessPolicyException(InvalidEmailRoleAccessPolicyException(message: "Invalid email role access policy")) + throw AWSCognitoIdentityProvider.InvalidEmailRoleAccessPolicyException( + message: "Invalid email role access policy" + ) } ) do { @@ -236,7 +239,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithinvalidSmsRoleAccessPolicyException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.invalidSmsRoleAccessPolicyException(InvalidSmsRoleAccessPolicyException(message: "Invalid sms role access policy")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException( + message: "Invalid sms role access policy" + ) } ) do { @@ -266,7 +271,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithInvalidSmsRoleTrustRelationshipException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.invalidSmsRoleTrustRelationshipException(InvalidSmsRoleTrustRelationshipException(message: "Invalid sms role trust relationship")) + throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException( + message: "Invalid sms role trust relationship" + ) } ) do { @@ -296,7 +303,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithInvalidLambdaResponseException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.invalidLambdaResponseException(InvalidLambdaResponseException(message: "Invalid lambda response")) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException( + message: "Invalid lambda response" + ) } ) do { @@ -327,7 +336,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithInvalidParameterException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.invalidParameterException(InvalidParameterException(message: "invalid parameter")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter" + ) } ) do { @@ -358,7 +369,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithLimitExceededException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.limitExceededException(LimitExceededException(message: "limit exceeded")) + throw AWSCognitoIdentityProvider.LimitExceededException( + message: "limit exceeded" + ) } ) do { @@ -389,7 +402,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithNotAuthorizedException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) do { @@ -416,7 +431,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithResourceNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) do { @@ -447,7 +464,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithTooManyRequestsException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) do { @@ -478,7 +497,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithUnexpectedLambdaException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.unexpectedLambdaException(UnexpectedLambdaException(message: "unexpected lambda")) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException( + message: "unexpected lambda" + ) } ) do { @@ -509,7 +530,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeWithUserLambdaValidationException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.userLambdaValidationException(UserLambdaValidationException(message: "user lambda validation exception")) + throw AWSCognitoIdentityProvider.UserLambdaValidationException( + message: "user lambda validation exception" + ) } ) do { @@ -540,7 +563,9 @@ class AWSAuthResendSignUpCodeAPITests: AWSCognitoAuthClientBehaviorTests { func testResendSignupCodeUpWithUserNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider( mockResendConfirmationCodeOutputResponse: { _ in - throw ResendConfirmationCodeOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift index b0f514aae8..206a32f568 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpAPITests.swift @@ -187,19 +187,19 @@ class AWSAuthSignUpAPITests: BasePluginTest { func testSignUpServiceError() async { - let errorsToTest: [(signUpOutputError: SignUpOutputError, cognitoError: AWSCognitoAuthError)] = [ - (.codeDeliveryFailureException(.init()), .codeDelivery), - (.invalidEmailRoleAccessPolicyException(.init()), .emailRole), - (.invalidLambdaResponseException(.init()), .lambda), - (.invalidParameterException(.init()), .invalidParameter), - (.invalidPasswordException(.init()), .invalidPassword), - (.invalidSmsRoleAccessPolicyException(.init()), .smsRole), - (.invalidSmsRoleTrustRelationshipException(.init()), .smsRole), - (.resourceNotFoundException(.init()), .resourceNotFound), - (.tooManyRequestsException(.init()), .requestLimitExceeded), - (.unexpectedLambdaException(.init()), .lambda), - (.userLambdaValidationException(.init()), .lambda), - (.usernameExistsException(.init()), .usernameExists), + let errorsToTest: [(signUpOutputError: Error, cognitoError: AWSCognitoAuthError)] = [ + (AWSCognitoIdentityProvider.CodeDeliveryFailureException(), .codeDelivery), + (AWSCognitoIdentityProvider.InvalidEmailRoleAccessPolicyException(), .emailRole), + (AWSCognitoIdentityProvider.InvalidLambdaResponseException(), .lambda), + (AWSCognitoIdentityProvider.InvalidParameterException(), .invalidParameter), + (AWSCognitoIdentityProvider.InvalidPasswordException(), .invalidPassword), + (AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException(), .smsRole), + (AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException(), .smsRole), + (AWSCognitoIdentityProvider.ResourceNotFoundException(), .resourceNotFound), + (AWSCognitoIdentityProvider.TooManyRequestsException(), .requestLimitExceeded), + (AWSCognitoIdentityProvider.UnexpectedLambdaException(), .lambda), + (AWSCognitoIdentityProvider.UserLambdaValidationException(), .lambda), + (AWSCognitoIdentityProvider.UsernameExistsException(), .usernameExists), ] for errorToTest in errorsToTest { @@ -213,7 +213,7 @@ class AWSAuthSignUpAPITests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in - throw SignUpOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() } ) @@ -245,10 +245,9 @@ class AWSAuthSignUpAPITests: BasePluginTest { self.mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in - throw SdkError.service( - SignUpOutputError.internalErrorException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InternalErrorException( + httpResponse: .init(body: .empty, statusCode: .accepted) + ) } ) @@ -273,7 +272,7 @@ class AWSAuthSignUpAPITests: BasePluginTest { } func validateSignUpServiceErrors( - signUpOutputError: SignUpOutputError, + signUpOutputError: Error, expectedCognitoError: AWSCognitoAuthError) async { self.mockIdentityProvider = MockIdentityProvider( mockSignUpResponse: { _ in diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift index 4368f834f5..54981fb260 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/SignUp/AWSAuthSignUpTaskTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import AWSCognitoAuthPlugin @testable import AWSPluginsTestCommon import ClientRuntime +import AWSClientRuntime import AWSCognitoIdentityProvider @@ -52,7 +53,9 @@ class AWSAuthSignUpTaskTests: XCTestCase { let functionExpectation = expectation(description: "API call should be invoked") let signUp: MockIdentityProvider.MockSignUpResponse = { _ in functionExpectation.fulfill() - throw try SignUpOutputError(httpResponse: MockHttpResponse.ok) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: MockHttpResponse.ok, message: nil, requestID: nil, typeName: nil + ) } let request = AuthSignUpRequest(username: "jeffb", diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift index f9893f0f7a..54c3b1b34b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorFetchDevicesTests.swift @@ -20,7 +20,7 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { super.setUp() mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - try ListDevicesOutputResponse(httpResponse: MockHttpResponse.ok) + try await ListDevicesOutputResponse(httpResponse: MockHttpResponse.ok) } ) } @@ -124,10 +124,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw SdkError.service( - ListDevicesOutputError.internalErrorException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InternalErrorException( + httpResponse: .init(body: .empty, statusCode: .accepted) + ) } ) do { @@ -155,7 +154,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.invalidParameterException(InvalidParameterException(message: "invalid parameter")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter" + ) } ) do { @@ -187,7 +188,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.invalidUserPoolConfigurationException(InvalidUserPoolConfigurationException(message: "invalid user pool configuration")) + throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( + message: "invalid user poo configuration" + ) } ) do { @@ -215,7 +218,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) do { @@ -243,7 +248,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.passwordResetRequiredException(PasswordResetRequiredException(message: "password reset required")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "password reset required" + ) } ) do { @@ -275,7 +282,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) do { @@ -307,7 +316,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) do { @@ -339,7 +350,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.userNotConfirmedException(UserNotConfirmedException(message: "user not confirmed")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "user not confirmed" + ) } ) do { @@ -371,7 +384,9 @@ class DeviceBehaviorFetchDevicesTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockListDevicesOutputResponse: { _ in - throw ListDevicesOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift index 7b2d57ed4d..bc9cab19e4 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorForgetDeviceTests.swift @@ -20,7 +20,7 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { super.setUp() mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - try ForgetDeviceOutputResponse(httpResponse: MockHttpResponse.ok) + try await ForgetDeviceOutputResponse(httpResponse: MockHttpResponse.ok) } ) } @@ -72,7 +72,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.internalErrorException(InternalErrorException(message: "internal error")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "internal error" + ) } ) @@ -101,7 +103,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.internalErrorException(InternalErrorException(message: "internal error")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "internal error" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -135,10 +139,12 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw SdkError.service( - ForgetDeviceOutputError.invalidParameterException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InvalidParameterException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) } ) do { @@ -167,7 +173,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.invalidParameterException(InvalidParameterException(message: "invalid parameter")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -202,7 +210,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.invalidUserPoolConfigurationException(InvalidUserPoolConfigurationException(message: "invalid user pool configuration")) + throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( + message: "invalid user pool configuration" + ) } ) do { @@ -230,7 +240,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.invalidUserPoolConfigurationException(InvalidUserPoolConfigurationException(message: "invalid user pool configuration")) + throw AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( + message: "invalid user pool configuration" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -264,7 +276,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) do { @@ -292,7 +306,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -326,7 +342,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.passwordResetRequiredException(PasswordResetRequiredException(message: "password reset required")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "password reset required" + ) } ) do { @@ -358,7 +376,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.passwordResetRequiredException(PasswordResetRequiredException(message: "password reset required")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "password reset required" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -396,7 +416,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) do { @@ -428,7 +450,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -466,7 +490,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) do { @@ -498,7 +524,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -536,7 +564,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.userNotConfirmedException(UserNotConfirmedException(message: "user not confirmed")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "user not confirmed" + ) } ) do { @@ -568,7 +598,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.userNotConfirmedException(UserNotConfirmedException(message: "user not confirmed")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "user not confirmed" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", @@ -606,7 +638,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) do { @@ -638,7 +672,9 @@ class DeviceBehaviorForgetDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockForgetDeviceResponse: { _ in - throw ForgetDeviceOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) let awsAuthDevice = AWSAuthDevice(id: "authDeviceID", diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift index 6d1126ab79..6403a5534c 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/DeviceBehaviorTests/DeviceBehaviorRememberDeviceTests.swift @@ -20,7 +20,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { super.setUp() mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - try UpdateDeviceStatusOutputResponse(httpResponse: MockHttpResponse.ok) + try await UpdateDeviceStatusOutputResponse( + httpResponse: MockHttpResponse.ok + ) } ) } @@ -77,7 +79,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.internalErrorException(InternalErrorException(message: "internal error")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "internal error" + ) } ) do { @@ -105,7 +109,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.invalidParameterException(InvalidParameterException(message: "invalid parameter")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter" + ) } ) do { @@ -137,10 +143,12 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw SdkError.service( - UpdateDeviceStatusOutputError.invalidUserPoolConfigurationException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InvalidUserPoolConfigurationException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) } ) do { @@ -168,7 +176,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.notAuthorizedException(NotAuthorizedException(message: "not authorized")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized" + ) } ) do { @@ -196,7 +206,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.passwordResetRequiredException(PasswordResetRequiredException(message: "password reset required")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "password reset required" + ) } ) do { @@ -228,7 +240,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.resourceNotFoundException(ResourceNotFoundException(message: "resource not found")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found" + ) } ) do { @@ -260,7 +274,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.tooManyRequestsException(TooManyRequestsException(message: "too many requests")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests" + ) } ) do { @@ -292,7 +308,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.userNotConfirmedException(UserNotConfirmedException(message: "user not confirmed")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "user not confirmed" + ) } ) do { @@ -324,7 +342,9 @@ class DeviceBehaviorRememberDeviceTests: BasePluginTest { mockIdentityProvider = MockIdentityProvider( mockRememberDeviceResponse: { _ in - throw UpdateDeviceStatusOutputError.userNotFoundException(UserNotFoundException(message: "user not found")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found" + ) } ) do { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift index b5fd736e52..4412af3802 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/AWSCognitoAuthUserBehaviorTests.swift @@ -27,10 +27,10 @@ class AWSCognitoAuthUserBehaviorTests: BasePluginTest { UpdateUserAttributesOutputResponse() }, mockConfirmUserAttributeOutputResponse: { _ in - try VerifyUserAttributeOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await VerifyUserAttributeOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }, mockChangePasswordOutputResponse: { _ in - try ChangePasswordOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await ChangePasswordOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) } ) } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift index 3bd2c488f8..2ff8da0acd 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorChangePasswordTests.swift @@ -25,7 +25,7 @@ class UserBehaviorChangePasswordTests: BasePluginTest { /// func testSuccessfulChangePassword() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - return try! ChangePasswordOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + return try await ChangePasswordOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }) try await plugin.update(oldPassword: "old password", to: "new password") } @@ -41,7 +41,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithInternalErrorException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.internalErrorException(.init(message: "internal error exception")) + throw AWSCognitoIdentityProvider.InternalErrorException( + message: "internal error exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -67,7 +69,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithInvalidParameterException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.invalidParameterException(.init(message: "invalid parameter exception")) + throw AWSCognitoIdentityProvider.InvalidParameterException( + message: "invalid parameter exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -97,7 +101,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithInvalidPasswordException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.invalidPasswordException(.init(message: "invalid password exception")) + throw AWSCognitoIdentityProvider.InvalidPasswordException( + message: "invalid password exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -127,10 +133,12 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithLimitExceededException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw SdkError.service( - ChangePasswordOutputError.limitExceededException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.LimitExceededException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -160,7 +168,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithNotAuthorizedException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.notAuthorizedException(.init(message: "not authorized exception")) + throw AWSCognitoIdentityProvider.NotAuthorizedException( + message: "not authorized exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -186,7 +196,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithPasswordResetRequiredException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.passwordResetRequiredException(.init(message: "password reset required exception")) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException( + message: "password reset required exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -216,7 +228,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithResourceNotFoundException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.resourceNotFoundException(.init(message: "resource not found exception")) + throw AWSCognitoIdentityProvider.ResourceNotFoundException( + message: "resource not found exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -246,7 +260,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithTooManyRequestsException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.tooManyRequestsException(.init(message: "too many requests exception")) + throw AWSCognitoIdentityProvider.TooManyRequestsException( + message: "too many requests exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -276,7 +292,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithUserNotConfirmedException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.userNotConfirmedException(.init(message: "user not confirmed exception")) + throw AWSCognitoIdentityProvider.UserNotConfirmedException( + message: "user not confirmed exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") @@ -306,7 +324,9 @@ class UserBehaviorChangePasswordTests: BasePluginTest { func testChangePasswordWithUserNotFoundException() async throws { self.mockIdentityProvider = MockIdentityProvider(mockChangePasswordOutputResponse: { _ in - throw ChangePasswordOutputError.userNotFoundException(.init(message: "user not found exception")) + throw AWSCognitoIdentityProvider.UserNotFoundException( + message: "user not found exception" + ) }) do { try await plugin.update(oldPassword: "old password", to: "new password") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift index 9d202f27c2..b69c260145 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorConfirmAttributeTests.swift @@ -23,7 +23,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { /// func testSuccessfulConfirmUpdateUserAttributes() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - try VerifyUserAttributeOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) + try await VerifyUserAttributeOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) }) try await plugin.confirm(userAttribute: .email, confirmationCode: "code") } @@ -41,7 +41,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { /// func testConfirmUpdateUserAttributesWithCodeMismatchException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.codeMismatchException(.init()) + throw AWSCognitoIdentityProvider.CodeMismatchException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -70,7 +70,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithExpiredCodeException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.expiredCodeException(.init()) + throw AWSCognitoIdentityProvider.ExpiredCodeException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -98,10 +98,12 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testcConfirmUpdateUserAttributesWithInternalErrorException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw SdkError.service( - VerifyUserAttributeOutputError.internalErrorException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.InternalErrorException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -127,7 +129,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithInvalidParameterException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -157,7 +159,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithLimitExceededException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.limitExceededException(.init()) + throw AWSCognitoIdentityProvider.LimitExceededException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -187,7 +189,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithNotAuthorizedException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -213,7 +215,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithPasswordResetRequiredException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -243,7 +245,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithResourceNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") @@ -273,7 +275,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithTooManyRequestsException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() }) do { @@ -304,7 +306,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithUserNotConfirmedException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) do { @@ -335,7 +337,7 @@ class UserBehaviorConfirmAttributeTests: BasePluginTest { func testConfirmUpdateUserAttributesWithUserNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockConfirmUserAttributeOutputResponse: { _ in - throw VerifyUserAttributeOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() }) do { try await plugin.confirm(userAttribute: .email, confirmationCode: "code") diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift index 89ed57376e..2ce26faf7e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorFetchAttributeTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import AWSClientRuntime class UserBehaviorFetchAttributesTests: BasePluginTest { @@ -75,7 +76,13 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithInternalErrorException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.unknown(.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) do { @@ -100,7 +107,7 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithInvalidParameterException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) do { @@ -129,10 +136,12 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithNotAuthorizedException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw SdkError.service( - GetUserOutputError.notAuthorizedException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.NotAuthorizedException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) }) do { @@ -159,7 +168,7 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithPasswordResetRequiredException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) do { @@ -190,7 +199,7 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithResourceNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) do { @@ -221,7 +230,7 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithTooManyRequestsException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() }) do { @@ -252,7 +261,7 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithUserNotConfirmedException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) do { _ = try await plugin.fetchUserAttributes() @@ -282,7 +291,7 @@ class UserBehaviorFetchAttributesTests: BasePluginTest { func testFetchUserAttributesWithUserNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeResponse: { _ in - throw GetUserOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() }) do { _ = try await plugin.fetchUserAttributes() diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorResendCodeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorResendCodeTests.swift index 53952ac4c6..401fb27a0b 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorResendCodeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorResendCodeTests.swift @@ -76,10 +76,12 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithCodeMismatchException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw SdkError.service( - GetUserAttributeVerificationCodeOutputError.codeDeliveryFailureException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.CodeDeliveryFailureException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -107,7 +109,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithInternalErrorException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.internalErrorException(.init()) + throw AWSCognitoIdentityProvider.InternalErrorException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -133,7 +135,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithInvalidParameterException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -163,7 +165,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithLimitExceededException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.limitExceededException(.init()) + throw AWSCognitoIdentityProvider.LimitExceededException() }) do { @@ -194,7 +196,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithNotAuthorizedException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -220,7 +222,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithPasswordResetRequiredException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -250,7 +252,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithResourceNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -280,7 +282,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithTooManyRequestsException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -310,7 +312,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithUserNotConfirmedException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) @@ -340,7 +342,7 @@ class UserBehaviorResendCodeTests: BasePluginTest { func testResendConfirmationCodeWithUserNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockGetUserAttributeVerificationCodeOutputResponse: { _ in - throw GetUserAttributeVerificationCodeOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() }) do { _ = try await plugin.resendConfirmationCode(forUserAttributeKey: .email) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift index e2aac23bdf..568e0bdb42 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/UserBehaviourTests/UserBehaviorUpdateAttributeTests.swift @@ -10,6 +10,7 @@ import XCTest @testable import AWSCognitoAuthPlugin import AWSCognitoIdentityProvider import ClientRuntime +import AWSClientRuntime class UserBehaviorUpdateAttributesTests: BasePluginTest { @@ -67,10 +68,12 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithAliasExistsException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw SdkError.service( - UpdateUserAttributesOutputError.aliasExistsException( - .init()), - .init(body: .empty, statusCode: .accepted)) + throw try await AWSCognitoIdentityProvider.AliasExistsException( + httpResponse: .init(body: .empty, statusCode: .accepted), + decoder: nil, + message: nil, + requestID: nil + ) }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -99,7 +102,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithCodeDeliveryFailureException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.codeDeliveryFailureException(.init()) + throw AWSCognitoIdentityProvider.CodeDeliveryFailureException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -128,7 +131,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithCodeMismatchException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.codeMismatchException(.init()) + throw AWSCognitoIdentityProvider.CodeMismatchException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -157,7 +160,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithExpiredCodeException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.expiredCodeException(.init()) + throw AWSCognitoIdentityProvider.ExpiredCodeException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -185,7 +188,13 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithInternalErrorException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.unknown(.init(httpResponse: .init(body: .empty, statusCode: .ok))) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: .init(body: .empty, statusCode: .ok), + message: nil, + requestID: nil, + requestID2: nil, + typeName: nil + ) }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -209,7 +218,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { /// func testUpdateUserAttributesWithInvalidEmailRoleAccessPolicyException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.invalidEmailRoleAccessPolicyException(.init()) + throw AWSCognitoIdentityProvider.InvalidEmailRoleAccessPolicyException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -237,7 +246,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { /// func testUpdateUserAttributesWithInvalidLambdaResponseException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.invalidLambdaResponseException(.init()) + throw AWSCognitoIdentityProvider.InvalidLambdaResponseException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -267,7 +276,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithInvalidParameterException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.invalidParameterException(.init()) + throw AWSCognitoIdentityProvider.InvalidParameterException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -295,7 +304,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { /// func testUpdateUserAttributesWithinvalidSmsRoleAccessPolicyException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.invalidSmsRoleAccessPolicyException(.init()) + throw AWSCognitoIdentityProvider.InvalidSmsRoleAccessPolicyException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -323,7 +332,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { /// func testUpdateUserAttributesCodeWithInvalidSmsRoleTrustRelationshipException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.invalidSmsRoleTrustRelationshipException(.init()) + throw AWSCognitoIdentityProvider.InvalidSmsRoleTrustRelationshipException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -353,7 +362,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithNotAuthorizedException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.notAuthorizedException(.init()) + throw AWSCognitoIdentityProvider.NotAuthorizedException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -379,7 +388,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithPasswordResetRequiredException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.passwordResetRequiredException(.init()) + throw AWSCognitoIdentityProvider.PasswordResetRequiredException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -409,7 +418,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithResourceNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.resourceNotFoundException(.init()) + throw AWSCognitoIdentityProvider.ResourceNotFoundException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -439,7 +448,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithTooManyRequestsException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.tooManyRequestsException(.init()) + throw AWSCognitoIdentityProvider.TooManyRequestsException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -469,7 +478,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithUnexpectedLambdaException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.unexpectedLambdaException(.init()) + throw AWSCognitoIdentityProvider.UnexpectedLambdaException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -499,7 +508,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithUserLambdaValidationException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.userLambdaValidationException(.init()) + throw AWSCognitoIdentityProvider.UserLambdaValidationException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -529,7 +538,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithUserNotConfirmedException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.userNotConfirmedException(.init()) + throw AWSCognitoIdentityProvider.UserNotConfirmedException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) @@ -559,7 +568,7 @@ class UserBehaviorUpdateAttributesTests: BasePluginTest { func testUpdateUserAttributesWithUserNotFoundException() async throws { mockIdentityProvider = MockIdentityProvider(mockUpdateUserAttributeResponse: { _ in - throw UpdateUserAttributesOutputError.userNotFoundException(.init()) + throw AWSCognitoIdentityProvider.UserNotFoundException() }) do { _ = try await plugin.update(userAttribute: AuthUserAttribute(.email, value: "Amplify@amazon.com")) diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift index f13550cafa..064ccb693c 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AmplifyAuthCognitoPluginTests.swift @@ -14,7 +14,8 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { let apiTimeout = 1.0 - func testAuthCognitoPlugin() { + @MainActor + func testAuthCognitoPlugin() async { // Load the json configs let bundle = Bundle.authCognitoTestBundle() @@ -28,12 +29,13 @@ class AmplifyAuthCognitoPluginTests: XCTestCase { atPath: testSuiteSubdirectoryPath) for testSuiteFile in testSuiteFiles { + print("Test Suite File: ---> \(directory)/\(testSuiteFile)") + let specification = FeatureSpecification( + fileName: testSuiteFile, + subdirectory: "\(AuthTestHarnessConstants.testSuitesPath)/\(directory)" + ) + let authTestHarness = await AuthTestHarness(featureSpecification: specification) XCTContext.runActivity(named: testSuiteFile) { activity in - print("Test Suite File: ---> \(directory)/\(testSuiteFile)") - let specification = FeatureSpecification( - fileName: testSuiteFile, - subdirectory: "\(AuthTestHarnessConstants.testSuitesPath)/\(directory)") - let authTestHarness = AuthTestHarness(featureSpecification: specification) beginTest(for: authTestHarness.plugin, with: authTestHarness) } 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 b016f5fd2b..dbc5cd16d9 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 @@ -19,7 +19,7 @@ extension ChangePasswordOutputResponse: Codable { guard let httpResponse = try containerValues.decodeIfPresent(HttpResponse.self, forKey: .httpResponse) else { fatalError("Unable to decode http response") } - try self.init(httpResponse: httpResponse) + self.init() } public func encode(to encoder: Encoder) throws { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift index e877dbadf4..b219711dee 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarness.swift @@ -29,7 +29,7 @@ class AuthTestHarness { mockedCognitoHelper.createPlugin() } - init(featureSpecification: FeatureSpecification) { + init(featureSpecification: FeatureSpecification) async { let awsCognitoAuthConfig = featureSpecification.preConditions.amplifyConfiguration.auth?.plugins["awsCognitoAuthPlugin"] @@ -42,7 +42,7 @@ class AuthTestHarness { fatalError("Unable to create auth configuarion") } - testHarnessInput = AuthTestHarnessInput.createInput( + testHarnessInput = await AuthTestHarnessInput.createInput( from: featureSpecification) mockedCognitoHelper = MockedAuthCognitoPluginHelper( diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift index b887487ba6..0f0b21a54a 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/AuthTestHarnessInput.swift @@ -23,9 +23,10 @@ struct AuthTestHarnessInput { extension AuthTestHarnessInput { - static func createInput(from specification: FeatureSpecification) -> AuthTestHarnessInput { - - return AuthTestHarnessInput( + static func createInput( + from specification: FeatureSpecification + ) async -> AuthTestHarnessInput { + return await AuthTestHarnessInput( initialAuthState: specification.preConditions.initialAuthState, expectedAuthState: getExpectedAuthState(from: specification), amplifyAPI: getAmplifyAPIUnderTest(from: specification), @@ -39,8 +40,9 @@ extension AuthTestHarnessInput { } private static func getCognitoAPI( - from specification: FeatureSpecification) -> [API.APIName: CognitoAPI] { - return CognitoAPIDecodingHelper.decode(with: specification) + from specification: FeatureSpecification + ) async -> [API.APIName: CognitoAPI] { + return await CognitoAPIDecodingHelper.decode(with: specification) } private static func getExpectedAuthState(from specification: FeatureSpecification) -> AuthState? { @@ -93,9 +95,8 @@ enum CognitoAPI { case globalSignOut(CognitoAPIData) } -struct CognitoAPIData { - +struct CognitoAPIData { let expectedInput: Input? - let output: Result - + let errorBinding: E.Type + let output: Result } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift index 867fbf1a97..283f467f9f 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TestHarness/CognitoAPIDecoding/CognitoAPIDecodingHelper.swift @@ -16,7 +16,7 @@ import Foundation struct CognitoAPIDecodingHelper { - static func decode(with specification: FeatureSpecification) -> [API.APIName: CognitoAPI] { + static func decode(with specification: FeatureSpecification) async -> [API.APIName: CognitoAPI] { var decodedAPIs: [API.APIName: CognitoAPI] = [:] @@ -46,84 +46,104 @@ struct CognitoAPIDecodingHelper { switch apiName { case "forgotPassword": - decodedAPIs[.forgotPassword] = .forgotPassword( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.forgotPassword] = await .forgotPassword( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "signUp": - decodedAPIs[.signUp] = .signUp( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.signUp] = await .signUp( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "deleteUser": - decodedAPIs[.deleteUser] = .deleteUser( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.deleteUser] = await .deleteUser( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "respondToAuthChallenge": - decodedAPIs[.confirmSignIn] = .respondToAuthChallenge( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.confirmSignIn] = await .respondToAuthChallenge( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "confirmDevice": - decodedAPIs[.confirmDevice] = .confirmDevice( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.confirmDevice] = await .confirmDevice( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "initiateAuth": - decodedAPIs[.initiateAuth] = .initiateAuth( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.initiateAuth] = await .initiateAuth( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "revokeToken": - decodedAPIs[.revokeToken] = .revokeToken( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.revokeToken] = await .revokeToken( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "getId": - decodedAPIs[.getId] = .getId( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.getId] = await .getId( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "getCredentialsForIdentity": - decodedAPIs[.getCredentialsForIdentity] = .getCredentialsForIdentity( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.getCredentialsForIdentity] = await .getCredentialsForIdentity( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) case "globalSignOut": - decodedAPIs[.globalSignOut] = .globalSignOut( - getApiInputAndOutput( - request: requestData, - response: response, - responseType: responseType - ) + decodedAPIs[.globalSignOut] = await .globalSignOut( + { + await getApiInputAndOutput( + request: requestData, + response: response, + responseType: responseType + ) + }() ) default: fatalError() @@ -154,11 +174,12 @@ struct CognitoAPIDecodingHelper { private static func getApiInputAndOutput< Input: Decodable, Output: Decodable, - Error: Swift.Error & ClientRuntime.HttpResponseBinding>( - request: Data?, - response: [String: JSONValue], - responseType: String - ) -> CognitoAPIData { + ErrorGenerator: ClientRuntime.HttpResponseErrorBinding + >( + request: Data?, + response: [String: JSONValue], + responseType: String + ) async -> CognitoAPIData { var input: Input? = nil if let request = request { @@ -166,7 +187,7 @@ struct CognitoAPIDecodingHelper { } - let result: Result + let result: Result switch responseType { case "failure": @@ -175,15 +196,17 @@ struct CognitoAPIDecodingHelper { fatalError() } - let error = try! Error( + let error = try! await ErrorGenerator.makeError( httpResponse: .init( headers: Headers( [ "x-amzn-error-message": errorMessage, "X-Amzn-Errortype": "#\(errorType):"]), body: .empty, - statusCode: .ok), - decoder: nil) + statusCode: .ok + ), + decoder: nil + ) result = .failure(error) case "success": let responseData = try! JSONEncoder().encode(response) @@ -193,6 +216,10 @@ struct CognitoAPIDecodingHelper { default: fatalError("invalid response type") } - return CognitoAPIData(expectedInput: input, output: result) + return CognitoAPIData( + expectedInput: input, + errorBinding: ErrorGenerator.self, + output: result + ) } } diff --git a/AmplifyTestCommon/Mocks/MockCredentialsProvider.swift b/AmplifyTestCommon/Mocks/MockCredentialsProvider.swift index 732384c615..90a1984d6b 100644 --- a/AmplifyTestCommon/Mocks/MockCredentialsProvider.swift +++ b/AmplifyTestCommon/Mocks/MockCredentialsProvider.swift @@ -8,7 +8,7 @@ import AWSClientRuntime import Foundation -class MockCredentialsProvider: CredentialsProvider { +class MockCredentialsProvider: CredentialsProviding { func getCredentials() async throws -> AWSCredentials { return AWSCredentials( accessKey: "accessKey", From 0051fa428fe789927a723eea138d5269a9f4a94c Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Fri, 29 Sep 2023 14:51:15 -0400 Subject: [PATCH 05/23] fix: misc. changes to AWSAPIPlugin (#3255) --- .../RequestInterceptor/IAMURLRequestInterceptor.swift | 3 ++- .../SubscriptionInterceptor/IAMAuthInterceptor.swift | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift index 0a9b53fe93..28ef8b9ce9 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift @@ -42,7 +42,8 @@ struct IAMURLRequestInterceptor: URLRequestInterceptor { let httpMethod = (request.httpMethod?.uppercased()) .flatMap(HttpMethodType.init(rawValue:)) ?? .get - let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems? + .map { ClientRuntime.URLQueryItem(name: $0.name, value: $0.value)} ?? [] let requestBuilder = SdkHttpRequestBuilder() .withHost(host) diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift index 10e66289cb..7d1bb4df11 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift @@ -21,10 +21,10 @@ class IAMAuthInterceptor: AuthInterceptorAsync { RealtimeProviderConstants.amzDate.lowercased(), RealtimeProviderConstants.iamSecurityTokenKey.lowercased()] - let authProvider: CredentialsProvider + let authProvider: CredentialsProviding let region: AWSRegionType - init(_ authProvider: CredentialsProvider, region: AWSRegionType) { + init(_ authProvider: CredentialsProviding, region: AWSRegionType) { self.authProvider = authProvider self.region = region } @@ -60,8 +60,8 @@ class IAMAuthInterceptor: AuthInterceptorAsync { guard var urlComponents = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else { return request } - let headerQuery = URLQueryItem(name: RealtimeProviderConstants.header, value: base64Auth) - let payloadQuery = URLQueryItem(name: RealtimeProviderConstants.payload, value: payloadBase64) + let headerQuery = Foundation.URLQueryItem(name: RealtimeProviderConstants.header, value: base64Auth) + let payloadQuery = Foundation.URLQueryItem(name: RealtimeProviderConstants.payload, value: payloadBase64) urlComponents.queryItems = [headerQuery, payloadQuery] guard let signedUrl = urlComponents.url else { return request From d2b7476ae2a18506f8029315f313e8eec65af2e7 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Fri, 29 Sep 2023 16:46:31 -0400 Subject: [PATCH 06/23] fix: error handling changes in geo and geo test suite (#3256) --- .../AWSLocationGeoPlugin+ClientBehavior.swift | 18 ++++- .../AWSLocationGeoPlugin+Configure.swift | 7 +- .../Support/Utils/GeoErrorConvertible.swift | 79 +++++++++++++++++++ .../Support/Utils/GeoErrorHelper.swift | 63 --------------- .../Mocks/MockAWSClientConfiguration.swift | 61 +++----------- .../Mocks/MockAWSLocation.swift | 3 +- 6 files changed, 110 insertions(+), 121 deletions(-) create mode 100644 AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift delete mode 100644 AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorHelper.swift diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift index 8fc5ec2d33..f79c09981f 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+ClientBehavior.swift @@ -97,9 +97,14 @@ extension AWSLocationGeoPlugin { country: $0.country) } return places + } catch let error as GeoErrorConvertible { + throw error.geoError } catch { - let geoError = GeoErrorHelper.mapAWSLocationError(error) - throw geoError + throw Geo.Error.unknown( + error.localizedDescription, + "See underlying error.", + error + ) } } @@ -167,9 +172,14 @@ extension AWSLocationGeoPlugin { country: $0.country) } return places + } catch let error as GeoErrorConvertible { + throw error.geoError } catch { - let geoError = GeoErrorHelper.mapAWSLocationError(error) - throw geoError + throw Geo.Error.unknown( + error.localizedDescription, + "See underlying error.", + error + ) } } diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift index c210cdd23f..d1a4caf9ae 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift @@ -30,10 +30,11 @@ extension AWSLocationGeoPlugin { let authService = AWSAuthService() let credentialsProvider = authService.getCredentialsProvider() let region = configuration.regionName + // TODO: FrameworkMetadata Replacement let serviceConfiguration = try LocationClient.LocationClientConfiguration( - credentialsProvider: credentialsProvider, - frameworkMetadata: AmplifyAWSServiceConfiguration.frameworkMetaData(), - region: region) + region: region, + credentialsProvider: credentialsProvider + ) #if os(iOS) || os(macOS) // no-op #else diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift new file mode 100644 index 0000000000..ad35aea33a --- /dev/null +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorConvertible.swift @@ -0,0 +1,79 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Amplify +import Foundation +import AWSLocation +import AWSClientRuntime + +protocol GeoErrorConvertible { + var geoError: Geo.Error { get } +} + +extension AWSLocation.AccessDeniedException: GeoErrorConvertible { + var geoError: Geo.Error { + .accessDenied( + message ?? "", + GeoPluginErrorConstants.accessDenied, + self + ) + } +} + +extension AWSLocation.InternalServerException: GeoErrorConvertible { + var geoError: Geo.Error { + .serviceError( + message ?? "", + GeoPluginErrorConstants.internalServer, + self + ) + } +} + +extension AWSLocation.ResourceNotFoundException: GeoErrorConvertible { + var geoError: Geo.Error { + .serviceError( + message ?? "", + GeoPluginErrorConstants.resourceNotFound, + self + ) + } +} + +extension AWSLocation.ThrottlingException: GeoErrorConvertible { + var geoError: Geo.Error { + .serviceError( + message ?? "", + GeoPluginErrorConstants.throttling, + self + ) + } +} + +extension AWSLocation.ValidationException: GeoErrorConvertible { + var geoError: Geo.Error { + .serviceError( + message ?? "", + GeoPluginErrorConstants.validation, + self + ) + } +} + +extension AWSClientRuntime.UnknownAWSHTTPServiceError: GeoErrorConvertible { + var geoError: Geo.Error { + .unknown( + """ + Unknown service error occured with: + - status: \(httpResponse.statusCode) + - message: \(message ?? "") + """, + "", + self + ) + } +} diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorHelper.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorHelper.swift deleted file mode 100644 index c21666a68e..0000000000 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/Support/Utils/GeoErrorHelper.swift +++ /dev/null @@ -1,63 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import Foundation - -import AWSLocation - -class GeoErrorHelper { - static func getDefaultError(_ error: Error) -> Geo.Error { - return Geo.Error.unknown(error.localizedDescription, "See underlying error.", error) - } - - static func mapAWSLocationError(_ error: Error) -> Geo.Error { - let defaultError = GeoErrorHelper.getDefaultError(error) - - if let searchPlaceIndexForTextOutputError = error as? SearchPlaceIndexForTextOutputError { - return GeoErrorHelper.mapError(error: searchPlaceIndexForTextOutputError) ?? defaultError - } else if let searchPlaceIndexForPositionOutputError = error as? SearchPlaceIndexForPositionOutputError { - return GeoErrorHelper.mapError(error: searchPlaceIndexForPositionOutputError) ?? defaultError - } - - return defaultError - } - - static func mapError(error: SearchPlaceIndexForTextOutputError) -> Geo.Error? { - switch error { - case .accessDeniedException(let accessDeniedException): - return Geo.Error.accessDenied(accessDeniedException.message ?? "", GeoPluginErrorConstants.accessDenied, error) - case .internalServerException(let internalServerException): - return Geo.Error.serviceError(internalServerException.message ?? "", GeoPluginErrorConstants.internalServer, error) - case .resourceNotFoundException(let resournceNotFoundException): - return Geo.Error.serviceError(resournceNotFoundException.message ?? "", GeoPluginErrorConstants.resourceNotFound, error) - case .throttlingException(let throttlingException): - return Geo.Error.serviceError(throttlingException.message ?? "", GeoPluginErrorConstants.throttling, error) - case .validationException(let validationException): - return Geo.Error.serviceError(validationException.message ?? "", GeoPluginErrorConstants.validation, error) - case .unknown(let unknownAWSHttpServiceError): - return Geo.Error.unknown(unknownAWSHttpServiceError._message ?? "", "See underlying error.", error) - } - } - - static func mapError(error: SearchPlaceIndexForPositionOutputError) -> Geo.Error? { - switch error { - case .accessDeniedException(let accessDeniedException): - return Geo.Error.accessDenied(accessDeniedException.message ?? "", GeoPluginErrorConstants.accessDenied, error) - case .internalServerException(let internalServerException): - return Geo.Error.serviceError(internalServerException.message ?? "", GeoPluginErrorConstants.internalServer, error) - case .resourceNotFoundException(let resournceNotFoundException): - return Geo.Error.serviceError(resournceNotFoundException.message ?? "", GeoPluginErrorConstants.resourceNotFound, error) - case .throttlingException(let throttlingException): - return Geo.Error.serviceError(throttlingException.message ?? "", GeoPluginErrorConstants.throttling, error) - case .validationException(let validationException): - return Geo.Error.serviceError(validationException.message ?? "", GeoPluginErrorConstants.validation, error) - case .unknown(let unknownAWSHttpServiceError): - return Geo.Error.unknown(unknownAWSHttpServiceError._message ?? "", "See underlying error.", error) - } - } -} diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift index 378d825711..ec24a7486d 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSClientConfiguration.swift @@ -14,56 +14,17 @@ import XCTest @testable import AWSLocationGeoPlugin @testable import AWSPluginsTestCommon -class MockAWSClientConfiguration: LocationClientConfigurationProtocol { - var encoder: ClientRuntime.RequestEncoder? - - var decoder: ClientRuntime.ResponseDecoder? - - var httpClientEngine: ClientRuntime.HttpClientEngine - - var httpClientConfiguration: ClientRuntime.HttpClientConfiguration - - var idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator - - var clientLogMode: ClientRuntime.ClientLogMode - - var partitionID: String? - - var useFIPS: Bool? - - var useDualStack: Bool? - - var endpoint: String? - - var credentialsProvider: CredentialsProvider - - var region: String? - - var signingRegion: String? - - var endpointResolver: EndpointResolver - - var regionResolver: RegionResolver? - - var frameworkMetadata: FrameworkMetadata? - - var logger: LogAgent - - var retryer: SDKRetryer - - init(config: AWSLocationGeoPluginConfiguration) throws { - let defaultSDKRuntimeConfig = try DefaultSDKRuntimeConfiguration("MockAWSClientConfiguration") - - self.httpClientEngine = defaultSDKRuntimeConfig.httpClientEngine - self.httpClientConfiguration = defaultSDKRuntimeConfig.httpClientConfiguration - self.idempotencyTokenGenerator = defaultSDKRuntimeConfig.idempotencyTokenGenerator - self.clientLogMode = defaultSDKRuntimeConfig.clientLogMode - self.credentialsProvider = MockAWSAuthService().getCredentialsProvider() - self.region = config.regionName - self.signingRegion = "" - self.endpointResolver = MockEndPointResolver() - self.logger = MockLogAgent() - self.retryer = try SDKRetryer(options: RetryOptions(jitterMode: .default)) +extension LocationClient.LocationClientConfiguration { + static func mock(region: String) throws -> LocationClient.LocationClientConfiguration { + try .init( + region: region, + credentialsProvider: MockAWSAuthService().getCredentialsProvider(), + serviceSpecific: .init( + endpointResolver: MockEndPointResolver() + ), + signingRegion: "", + retryMode: .standard + ) } } diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift index fe7a6cb9d8..0dc4080432 100644 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift +++ b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/Mocks/MockAWSLocation.swift @@ -27,7 +27,8 @@ public class MockAWSLocation: AWSLocationBehavior { public init(pluginConfig: AWSLocationGeoPluginConfiguration) throws { self.locationClient = try LocationClient( - config: MockAWSClientConfiguration(config: pluginConfig)) + config: .mock(region: pluginConfig.regionName) + ) } public func getEscapeHatch() -> LocationClient { From 59e78375e6fcd0d99a6e35e6690b8d5c61accf24 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 2 Oct 2023 11:49:06 -0400 Subject: [PATCH 07/23] fix: error handling and misc. in storage plugin (#3258) --- .../Dependency/AWSS3Adapter.swift | 6 +- .../Dependency/AWSS3Behavior.swift | 4 +- .../AWSS3PreSignedURLBuilderAdapter.swift | 6 +- ...S3ClientConfiguration+withAccelerate.swift | 53 ++++++ ...ClientConfigurationProtocol+Endpoint.swift | 14 +- .../S3ClientConfigurationProxy.swift | 161 ------------------ .../Dependency/SdkTypealiases.swift | 3 - .../UploadPartInput+presignURL.swift | 6 +- .../Error/AWSS3+StorageErrorConvertible.swift | 52 ++++++ .../Error/StorageErrorConvertible.swift | 17 ++ ...orageService+GetPreSignedURLBehavior.swift | 52 ++---- .../AWSS3StorageService+ListBehavior.swift | 3 +- .../Service/Storage/AWSS3StorageService.swift | 5 +- .../Support/Utils/SdkError+Properties.swift | 85 --------- .../S3ClientConfigurationProxyTests.swift | 114 +++++++------ ...eServiceGetPreSignedURLBehaviorTests.swift | 10 +- .../AWSS3StorageServiceListTests.swift | 10 +- 17 files changed, 229 insertions(+), 372 deletions(-) create mode 100644 AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfiguration+withAccelerate.swift delete mode 100644 AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProxy.swift create mode 100644 AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/AWSS3+StorageErrorConvertible.swift create mode 100644 AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/StorageErrorConvertible.swift diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Adapter.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Adapter.swift index 0e15b170b7..969fd6475f 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Adapter.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Adapter.swift @@ -19,9 +19,9 @@ import AWSClientRuntime /// same method using the AWSS3 instance. class AWSS3Adapter: AWSS3Behavior { let awsS3: S3Client - let config: S3ClientConfigurationProtocol + let config: S3Client.S3ClientConfiguration - init(_ awsS3: S3Client, config: S3ClientConfigurationProtocol) { + init(_ awsS3: S3Client, config: S3Client.S3ClientConfiguration) { self.awsS3 = awsS3 self.config = config } @@ -66,7 +66,7 @@ class AWSS3Adapter: AWSS3Behavior { } let listResult = StorageListResult(items: items) completion(.success(listResult)) - } catch let error as SdkError { + } catch let error as StorageErrorConvertible { completion(.failure(error.storageError)) } catch { completion(.failure(StorageError(error: error))) diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Behavior.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Behavior.swift index 19a2b4cdd0..7319878805 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Behavior.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3Behavior.swift @@ -26,7 +26,7 @@ protocol AWSS3Behavior { func createMultipartUpload(_ request: CreateMultipartUploadRequest, completion: @escaping (Result) -> Void) // Get list of uploaded parts (supports development) - func listParts(bucket: String, key: String, uploadId: UploadID, completion: @escaping (SdkResult) -> Void) + func listParts(bucket: String, key: String, uploadId: UploadID, completion: @escaping (Result) -> Void) // Completes a Multipart Upload. func completeMultipartUpload(_ request: AWSS3CompleteMultipartUploadRequest, completion: @escaping (Result) -> Void) @@ -40,7 +40,7 @@ protocol AWSS3Behavior { } extension AWSS3Behavior { - func listParts(bucket: String, key: String, uploadId: UploadID, completion: @escaping (SdkResult) -> Void) { + func listParts(bucket: String, key: String, uploadId: UploadID, completion: @escaping (Result) -> Void) { // do nothing } } diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3PreSignedURLBuilderAdapter.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3PreSignedURLBuilderAdapter.swift index 0ff4a5db4b..5153e90c89 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3PreSignedURLBuilderAdapter.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/AWSS3PreSignedURLBuilderAdapter.swift @@ -19,7 +19,7 @@ class AWSS3PreSignedURLBuilderAdapter: AWSS3PreSignedURLBuilderBehavior { let defaultExpiration: Int64 = 50 * 60 // 50 minutes let bucket: String - let config: S3ClientConfigurationProtocol + let config: S3Client.S3ClientConfiguration let logger: Logger /// Creates a pre-signed URL builder. @@ -38,9 +38,7 @@ class AWSS3PreSignedURLBuilderAdapter: AWSS3PreSignedURLBuilderBehavior { expires: Int64? = nil) async throws -> URL { let expiresDate = Date(timeIntervalSinceNow: Double(expires ?? defaultExpiration)) let expiration = expiresDate.timeIntervalSinceNow - let config = (accelerate == nil) ? self.config : S3ClientConfigurationProxy( - target: self.config, - accelerateOverride: accelerate) + let config = try config.withAccelerate(accelerate) let preSignedUrl: URL? switch signingOperation { case .getObject: diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfiguration+withAccelerate.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfiguration+withAccelerate.swift new file mode 100644 index 0000000000..bd3cac4d8b --- /dev/null +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfiguration+withAccelerate.swift @@ -0,0 +1,53 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import AWSS3 + +extension S3Client.S3ClientConfiguration { + func withAccelerate(_ shouldAccelerate: Bool?) throws -> S3Client.S3ClientConfiguration { + // if `shouldAccelerate` is `nil`, this is a noop - return self + guard let shouldAccelerate else { + return self + } + + // if `shouldAccelerate` isn't `nil` and + // is equal to the exisiting config's `serviceSpecific.accelerate + // we can avoid allocating a new configuration object. + if shouldAccelerate == serviceSpecific.accelerate { + return self + } + + // This shouldn't happen based on how we're initially + // creating the configuration, but we can't reasonably prove + // it at compile time - so we have to unwrap. + guard let region else { return self } + + // `S3Client.ServiceSpecificConfiguration` is a struct + // so we're copying by value here. + var serviceSpecific = serviceSpecific + serviceSpecific.accelerate = shouldAccelerate + + // `S3Client.S3ClientConfiguration` is a `class` so we need to make + // a deep copy here as not to change the value of the existing base + // configuration. + let copy = try S3Client.S3ClientConfiguration( + region: region, + credentialsProvider: credentialsProvider, + endpoint: endpoint, + serviceSpecific: serviceSpecific, + signingRegion: signingRegion, + useDualStack: useDualStack, + useFIPS: useFIPS, + retryMode: awsRetryMode, + appID: appID, + connectTimeoutMs: connectTimeoutMs + ) + + return copy + } +} diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProtocol+Endpoint.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProtocol+Endpoint.swift index 892446c243..5eac989093 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProtocol+Endpoint.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProtocol+Endpoint.swift @@ -6,20 +6,20 @@ import Foundation import AWSS3 -extension S3ClientConfigurationProtocol { - +extension S3Client.S3ClientConfiguration { func endpointParams(withBucket bucket: String?) -> EndpointParams { EndpointParams( - accelerate: accelerate ?? false, + accelerate: serviceSpecific.accelerate ?? false, bucket: bucket, - disableMultiRegionAccessPoints: disableMultiRegionAccessPoints ?? false, + disableMultiRegionAccessPoints: serviceSpecific.disableMultiRegionAccessPoints ?? false, endpoint: endpoint, - forcePathStyle: forcePathStyle, + forcePathStyle: serviceSpecific.forcePathStyle ?? false, region: region, - useArnRegion: useArnRegion, + useArnRegion: serviceSpecific.useArnRegion, useDualStack: useDualStack ?? false, useFIPS: useFIPS ?? false, - useGlobalEndpoint: useGlobalEndpoint ?? false) + useGlobalEndpoint: serviceSpecific.useGlobalEndpoint ?? false + ) } } diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProxy.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProxy.swift deleted file mode 100644 index 6a6ebb04d3..0000000000 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/S3ClientConfigurationProxy.swift +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 - -import AWSS3 -import AWSClientRuntime -import ClientRuntime -import Foundation - -/// Convenience proxy class around a -/// [S3ClientConfigurationProtocol](x-source-tag://S3ClientConfigurationProtocol) -/// implementaitons that allows Amplify to change configuration values JIT. -/// -/// - Tag: S3ClientConfigurationProxy -struct S3ClientConfigurationProxy { - - /// - Tag: S3ClientConfigurationProxy.target - var target: S3ClientConfigurationProtocol - - /// - Tag: S3ClientConfigurationProxy.accelerateOverride - var accelerateOverride: Bool? -} - -extension S3ClientConfigurationProxy: S3ClientConfigurationProtocol { - - var accelerate: Bool? { - if let accelerateOverride = accelerateOverride { - return accelerateOverride - } - return target.accelerate - } - - var disableMultiRegionAccessPoints: Bool? { - return target.disableMultiRegionAccessPoints - } - - var endpointResolver: EndpointResolver { - return target.endpointResolver - } - - var forcePathStyle: Bool? { - return target.forcePathStyle - } - - var useArnRegion: Bool? { - return target.useArnRegion - } - - var useGlobalEndpoint: Bool? { - return target.useGlobalEndpoint - } - - var credentialsProvider: AWSClientRuntime.CredentialsProvider { - get { - return target.credentialsProvider - } - set(newValue) { - target.credentialsProvider = newValue - } - } - - var region: String? { - get { - return target.region - } - set(newValue) { - target.region = newValue - } - } - - var signingRegion: String? { - get { - return target.signingRegion - } - set(newValue) { - target.signingRegion = newValue - } - } - - var regionResolver: RegionResolver? { - get { - return target.regionResolver - } - set(newValue) { - target.regionResolver = newValue - } - } - - var frameworkMetadata: FrameworkMetadata? { - get { - return target.frameworkMetadata - } - set(newValue) { - target.frameworkMetadata = newValue - } - } - - var useFIPS: Bool? { - get { - return target.useFIPS - } - set(newValue) { - target.useFIPS = newValue - } - } - - var useDualStack: Bool? { - get { - return target.useDualStack - } - set(newValue) { - target.useDualStack = newValue - } - } - - var logger: LogAgent { - return target.logger - } - - var retryer: ClientRuntime.SDKRetryer { - return target.retryer - } - - var endpoint: String? { - get { - return target.endpoint - } - set(newValue) { - target.endpoint = newValue - } - } - - var encoder: ClientRuntime.RequestEncoder? { - return target.encoder - } - - var decoder: ClientRuntime.ResponseDecoder? { - return target.decoder - } - - var httpClientEngine: ClientRuntime.HttpClientEngine { - return target.httpClientEngine - } - - var httpClientConfiguration: ClientRuntime.HttpClientConfiguration { - return target.httpClientConfiguration - } - - var idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator { - return target.idempotencyTokenGenerator - } - - var clientLogMode: ClientRuntime.ClientLogMode { - return target.clientLogMode - } - - var partitionID: String? { - return target.partitionID - } -} diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/SdkTypealiases.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/SdkTypealiases.swift index 64d76e908f..d0cdf91669 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/SdkTypealiases.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/SdkTypealiases.swift @@ -9,8 +9,5 @@ import Foundation import AWSClientRuntime import ClientRuntime -/// - Tag: SdkResult -public typealias SdkResult = Result> - /// - Tag: NetworkResult public typealias NetworkResult = (Result) -> Void diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/UploadPartInput+presignURL.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/UploadPartInput+presignURL.swift index 83f4958c77..38af518a9c 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/UploadPartInput+presignURL.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Dependency/UploadPartInput+presignURL.swift @@ -10,7 +10,7 @@ import ClientRuntime import AWSClientRuntime extension UploadPartInput { - func customPresignURL(config: S3ClientConfigurationProtocol, expiration: TimeInterval) async throws -> ClientRuntime.URL? { + func customPresignURL(config: S3Client.S3ClientConfiguration, expiration: TimeInterval) async throws -> ClientRuntime.URL? { let serviceName = "S3" let input = self let encoder = ClientRuntime.XMLEncoder() @@ -34,10 +34,10 @@ extension UploadPartInput { var operation = ClientRuntime.OperationStack(id: "uploadPart") operation.initializeStep.intercept(position: .after, middleware: ClientRuntime.URLPathMiddleware()) operation.initializeStep.intercept(position: .after, middleware: ClientRuntime.URLHostMiddleware()) - operation.buildStep.intercept(position: .before, middleware: EndpointResolverMiddleware(endpointResolver: config.endpointResolver, endpointParams: config.endpointParams(withBucket: input.bucket))) + operation.buildStep.intercept(position: .before, middleware: EndpointResolverMiddleware(endpointResolver: config.serviceSpecific.endpointResolver, endpointParams: config.endpointParams(withBucket: input.bucket))) operation.serializeStep.intercept(position: .after, middleware: UploadPartInputBodyMiddleware()) operation.serializeStep.intercept(position: .after, middleware: QueryItemMiddleware()) - operation.finalizeStep.intercept(position: .after, middleware: RetryerMiddleware(retryer: config.retryer)) + operation.finalizeStep.intercept(position: .after, middleware: ClientRuntime.RetryMiddleware(options: config.retryStrategyOptions)) let sigv4Config = AWSClientRuntime.SigV4Config( signatureType: .requestQueryParams, useDoubleURIEncode: false, diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/AWSS3+StorageErrorConvertible.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/AWSS3+StorageErrorConvertible.swift new file mode 100644 index 0000000000..7b4a08ab76 --- /dev/null +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/AWSS3+StorageErrorConvertible.swift @@ -0,0 +1,52 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AWSS3 +import AWSClientRuntime + +extension AWSS3.NoSuchBucket: StorageErrorConvertible { + var storageError: StorageError { + .service( + "The specific bucket does not exist", + "", + self + ) + } +} + +extension AWSClientRuntime.UnknownAWSHTTPServiceError: StorageErrorConvertible { + var storageError: StorageError { + let error: StorageError + switch httpResponse.statusCode { + case .unauthorized, .forbidden: + error = .accessDenied( + StorageErrorConstants.accessDenied.errorDescription, + StorageErrorConstants.accessDenied.recoverySuggestion, + self + ) + case .notFound: + error = .keyNotFound( + StorageError.serviceKey, + "Received HTTP Response status code 404 NotFound", + "Make sure the key exists before trying to download it.", + self + ) + default: + error = .unknown( + """ + Unknown service error occured with: + - status: \(httpResponse.statusCode) + - message: \(message ?? "") + """, + self + ) + } + return error + } +} diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/StorageErrorConvertible.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/StorageErrorConvertible.swift new file mode 100644 index 0000000000..9f9e55c5a6 --- /dev/null +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Error/StorageErrorConvertible.swift @@ -0,0 +1,17 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify + +protocol StorageErrorConvertible { + var storageError: StorageError { get } +} + +extension StorageError: StorageErrorConvertible { + var storageError: StorageError { self } +} diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+GetPreSignedURLBehavior.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+GetPreSignedURLBehavior.swift index 1716891ab1..b13c4a25f6 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+GetPreSignedURLBehavior.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+GetPreSignedURLBehavior.swift @@ -19,8 +19,9 @@ extension AWSS3StorageService { return try await preSignedURLBuilder.getPreSignedURL( key: serviceKey, signingOperation: signingOperation, - accelerate: accelerate, - expires: Int64(expires)) + accelerate: nil, + expires: Int64(expires) + ) } func validateObjectExistence(serviceKey: String) async throws { @@ -29,49 +30,20 @@ extension AWSS3StorageService { bucket: self.bucket, key: serviceKey )) - } catch let error as HeadObjectOutputError { - // Because the AWS SDK may wrap the HeadObjectOutputError in an - // SdkError, it is necessary to do some more - // complex error pattern matching. - throw Self.validateObjectExistenceMap(headObjectOutputError: error, serviceKey: serviceKey) - } catch let error as SdkError { - throw Self.validateObjectExistenceMap(sdkError: error, serviceKey: serviceKey) - } - } - - private static func validateObjectExistenceMap(sdkError: SdkError, serviceKey: String) -> StorageError { - switch sdkError { - case .service(let serviceError, _): - return validateObjectExistenceMap(headObjectOutputError: serviceError, serviceKey: serviceKey) - case .client(let clientError, _): - switch clientError { - case .retryError(let error as HeadObjectOutputError): - return validateObjectExistenceMap(headObjectOutputError: error, serviceKey: serviceKey) - case .retryError(let error as SdkError): - return validateObjectExistenceMap(sdkError: error, serviceKey: serviceKey) - default: - return validateObjectExistenceMap(unexpectedError: clientError, serviceKey: serviceKey) - } - case .unknown(let error): - return validateObjectExistenceMap(unexpectedError: error, serviceKey: serviceKey) - } - } - - private static func validateObjectExistenceMap(headObjectOutputError: HeadObjectOutputError, serviceKey: String) -> StorageError { - switch headObjectOutputError { - case .notFound: - return StorageError.keyNotFound( + } catch is AWSS3.NotFound { + throw StorageError.keyNotFound( serviceKey, "Unable to generate URL for non-existent key: \(serviceKey)", "Please ensure the key is valid or the object has been uploaded", nil ) - default: - return validateObjectExistenceMap(unexpectedError: headObjectOutputError, serviceKey: serviceKey) + } catch let error as StorageErrorConvertible { + throw error.storageError + } catch { + throw StorageError.unknown( + "Unable to get object information for \(serviceKey)", + error + ) } } - - private static func validateObjectExistenceMap(unexpectedError: Error?, serviceKey: String) -> StorageError { - return StorageError.unknown("Unable to get object information for \(serviceKey)", unexpectedError) - } } diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+ListBehavior.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+ListBehavior.swift index 186f70d330..817822f346 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+ListBehavior.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService+ListBehavior.swift @@ -42,11 +42,10 @@ extension AWSS3StorageService { try StorageListResult.Item(s3Object: $0, prefix: prefix) } return StorageListResult(items: items, nextToken: response.nextContinuationToken) - } catch let error as SdkError { + } catch let error as StorageErrorConvertible { throw error.storageError } catch { throw StorageError(error: error) } } - } diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift index 58329ddb84..e2c7fe59ce 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift @@ -60,9 +60,10 @@ class AWSS3StorageService: AWSS3StorageServiceBehavior, StorageServiceProxy { logger: Logger = storageLogger) throws { let credentialsProvider = authService.getCredentialsProvider() let clientConfig = try S3Client.S3ClientConfiguration( - credentialsProvider: credentialsProvider, region: region, - signingRegion: region) + credentialsProvider: credentialsProvider, + signingRegion: region + ) if var proxy = httpClientEngineProxy { let httpClientEngine: HttpClientEngine diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Support/Utils/SdkError+Properties.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Support/Utils/SdkError+Properties.swift index 6dbbb395aa..b4b240df18 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Support/Utils/SdkError+Properties.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Support/Utils/SdkError+Properties.swift @@ -6,95 +6,10 @@ // import Foundation - import Amplify -import AWSS3 -import ClientRuntime -import AWSClientRuntime extension StorageError { static var serviceKey: String { "s3" } } - -extension SdkError { - var httpResponse: HttpResponse? { - switch self { - case .service(_, let response): - return response - case .client(_, let response): - return response - default: - return nil - } - } - - var statusCode: HttpStatusCode? { - if let statusCode = httpResponse?.statusCode { - return statusCode - } - - guard case let .retryError(error) = clientError, - let sdkError = error as? Self else { - return nil - } - - return sdkError.statusCode - } - - var clientError: ClientError? { - switch self { - case .client(let clientError, _): - return clientError - default: - return nil - } - } - - var unknownError: Error? { - switch self { - case .unknown(let error): - return error - default: - return nil - } - } - - func isOk(statusCode: Int) -> Bool { - (200..<299).contains(statusCode) - } - - func isAccessDenied(statusCode: Int) -> Bool { - [401, 403].contains(statusCode) - } - - func isNotFound(statusCode: Int) -> Bool { - 404 == statusCode - } - - var storageError: StorageError { - let storageError: StorageError - if let statusCode = statusCode?.rawValue, - !isOk(statusCode: statusCode) { - if isAccessDenied(statusCode: statusCode) { - storageError = StorageError.accessDenied(StorageErrorConstants.accessDenied.errorDescription, - StorageErrorConstants.accessDenied.recoverySuggestion, - self) - } else if isNotFound(statusCode: statusCode) { - storageError = StorageError.keyNotFound(StorageError.serviceKey, - "Received HTTP Response status code 404 NotFound", - "Make sure the key exists before trying to download it.") - } else { - storageError = StorageError.httpStatusError(statusCode, localizedDescription, self) - } - } else if let clientError = clientError { - storageError = StorageError.unknown(clientError.localizedDescription, clientError) - } else { - storageError = StorageError.unknown(localizedDescription, self) - } - - return storageError - } - -} diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift index 19a38fb062..7830779aec 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift @@ -13,67 +13,77 @@ import XCTest @testable import AWSS3StoragePlugin -final class S3ClientConfigurationProxyTests: XCTestCase { +final class S3ClientConfigurationAccelerateTestCase: XCTestCase { - /// Given: A client configuration that has a value for a property such as `accelerate`. - /// When: An override is set on its proxy configuration. - /// Then: The proxy returns the value from the override. + /// Given: A base configuration that has a value for a property such as `accelerate`. + /// When: An override is set through `withAccelerate(_:)` + /// Then: The base configuration is not mutated. func testPropertyOverrides() async throws { - let target = try await S3Client.S3ClientConfiguration() - target.accelerate = true - - let sut = S3ClientConfigurationProxy(target: target, accelerateOverride: false) - XCTAssertEqual(sut.accelerate, false) - XCTAssertEqual(target.accelerate, true) + let baseConfiguration = try await S3Client.S3ClientConfiguration() + baseConfiguration.serviceSpecific.accelerate = true + + let sut = try baseConfiguration.withAccelerate(false) + XCTAssertEqual(sut.serviceSpecific.accelerate, false) + XCTAssertEqual(baseConfiguration.serviceSpecific.accelerate, true) + } + + /// Given: A client configuration. + /// When: Calling `withAccelerate` with a `nil` value. + /// Then: The existing and new configurations should share a reference. + func test_copySemantics_nilAccelerate() async throws { + let baseAccelerate = Bool.random() + let baseConfiguration = try await configuration(accelerate: baseAccelerate) + + let nilAccelerate = try baseConfiguration.withAccelerate(nil) + XCTAssertIdentical(baseConfiguration, nilAccelerate) + } + + /// Given: A client configuration. + /// When: Calling `withAccelerate` with a non-nil value equal to that of the existing config's. + /// Then: The existing and new configurations should share a reference. + func test_copySemantics_equalAccelerate() async throws { + let baseAccelerate = Bool.random() + let baseConfiguration = try await configuration(accelerate: baseAccelerate) + + let equalAccelerate = try baseConfiguration.withAccelerate(baseAccelerate) + XCTAssertIdentical(baseConfiguration, equalAccelerate) } - /// Given: A client configuration with random values. - /// When: A proxy configuration around it is created **without overrides**. - /// Then: The values returned by the proxy are equal to those from the **client configuration**. - func testPropertyBypass() async throws { - let target = try await S3Client.S3ClientConfiguration( - accelerate: Bool.random(), + /// Given: A client configuration. + /// When: Calling `withAccelerate` with a non-nil value **not** equal to that of the existing config's. + /// Then: The existing and new configurations should not share a reference. + func test_copySemantics_nonEqualAccelerate() async throws { + let baseAccelerate = Bool.random() + let baseConfiguration = try await configuration(accelerate: baseAccelerate) + + let nonEqualAccelerate = try baseConfiguration.withAccelerate(!baseAccelerate) + XCTAssertNotIdentical(baseConfiguration, nonEqualAccelerate) + } + + + // Helper configuration method + private func configuration(accelerate: Bool) async throws -> S3Client.S3ClientConfiguration { + var serviceSpecific = try S3Client.ServiceSpecificConfiguration() + serviceSpecific.accelerate = accelerate + serviceSpecific.useArnRegion = .random() + serviceSpecific.useGlobalEndpoint = .random() + serviceSpecific.disableMultiRegionAccessPoints = .random() + serviceSpecific.forcePathStyle = .random() + + let baseConfiguration = try await S3Client.S3ClientConfiguration( credentialsProvider: nil, - disableMultiRegionAccessPoints: Bool.random(), endpoint: UUID().uuidString, - endpointResolver: nil, - forcePathStyle: Bool.random(), - frameworkMetadata: nil, + serviceSpecific: serviceSpecific, + region: nil, regionResolver: nil, signingRegion: UUID().uuidString, - useArnRegion: Bool.random(), - useDualStack: Bool.random(), - useFIPS: Bool.random(), - useGlobalEndpoint: Bool.random() + useDualStack: .random(), + useFIPS: .random(), + retryMode: .adaptive, + appID: UUID().uuidString, + connectTimeoutMs: .random(in: UInt32.min...UInt32.max) ) - - var sut = S3ClientConfigurationProxy(target: target, accelerateOverride: nil) - XCTAssertEqual(sut.accelerate, target.accelerate) - XCTAssertEqual(sut.disableMultiRegionAccessPoints, target.disableMultiRegionAccessPoints) - XCTAssertEqual(sut.forcePathStyle, target.forcePathStyle) - XCTAssertEqual(sut.useArnRegion, target.useArnRegion) - XCTAssertEqual(sut.useDualStack, target.useDualStack) - XCTAssertEqual(sut.region, target.region) - XCTAssertEqual(sut.signingRegion, target.signingRegion) - XCTAssertEqual(sut.useFIPS, target.useFIPS) - XCTAssertEqual(sut.useGlobalEndpoint, target.useGlobalEndpoint) - XCTAssertEqual(sut.endpoint, target.endpoint) - - sut.region = UUID().uuidString - sut.signingRegion = UUID().uuidString - sut.useFIPS = !(sut.useFIPS ?? false) - sut.useDualStack = !(sut.useDualStack ?? false) - sut.endpoint = UUID().uuidString - XCTAssertEqual(sut.accelerate, target.accelerate) - XCTAssertEqual(sut.disableMultiRegionAccessPoints, target.disableMultiRegionAccessPoints) - XCTAssertEqual(sut.forcePathStyle, target.forcePathStyle) - XCTAssertEqual(sut.useArnRegion, target.useArnRegion) - XCTAssertEqual(sut.useDualStack, target.useDualStack) - XCTAssertEqual(sut.region, target.region) - XCTAssertEqual(sut.signingRegion, target.signingRegion) - XCTAssertEqual(sut.useFIPS, target.useFIPS) - XCTAssertEqual(sut.useGlobalEndpoint, target.useGlobalEndpoint) - XCTAssertEqual(sut.endpoint, target.endpoint) + return baseConfiguration } } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceGetPreSignedURLBehaviorTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceGetPreSignedURLBehaviorTests.swift index 4f725a5780..787cd2ad3d 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceGetPreSignedURLBehaviorTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceGetPreSignedURLBehaviorTests.swift @@ -110,7 +110,7 @@ class AWSS3StorageServiceGetPreSignedURLBehaviorTests: XCTestCase { /// - Then: A StorageError.keyNotFound is thrown func testvalidateObjectExistenceForNonExistentKey() async throws { client.headObjectHandler = { _ in - throw HeadObjectOutputError.notFound(.init()) + throw AWSS3.NotFound() } let nonExistentKey = UUID().uuidString do { @@ -126,8 +126,9 @@ class AWSS3StorageServiceGetPreSignedURLBehaviorTests: XCTestCase { /// - Then: An SdkError.service is thrown func testvalidateObjectExistenceForNonExistentKeyWithSdkServiceError() async throws { client.headObjectHandler = { _ in - let headObjectError = HeadObjectOutputError.notFound(.init()) - throw SdkError.service(headObjectError, HttpResponse(body: .none, statusCode: .notFound)) + throw try await AWSS3.NotFound( + httpResponse: HttpResponse(body: .none, statusCode: .notFound) + ) } let nonExistentKey = UUID().uuidString do { @@ -143,8 +144,7 @@ class AWSS3StorageServiceGetPreSignedURLBehaviorTests: XCTestCase { /// - Then: An SdkError.client is thrown func testvalidateObjectExistenceForNonExistentKeyWithSdkClientError() async throws { client.headObjectHandler = { _ in - let headObjectError = HeadObjectOutputError.notFound(.init()) - throw SdkError.client(ClientError.retryError(headObjectError)) + throw AWSS3.NotFound() } let nonExistentKey = UUID().uuidString do { diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceListTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceListTests.swift index 10ad1df2e3..5a4f5dc878 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceListTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceListTests.swift @@ -10,7 +10,7 @@ import AWSS3 import Amplify import ClientRuntime import XCTest - +import AWSClientRuntime @testable import AWSPluginsTestCommon @testable import AWSS3StoragePlugin @@ -98,8 +98,12 @@ final class AWSS3StorageServiceListTests: XCTestCase { /// Then: The service throws a `StorageError` error func testSdkError() async throws { client.listObjectsV2Handler = { _ in - let response = HttpResponse(body: .empty, statusCode: .forbidden) - throw try SdkError.service(ListObjectsV2OutputError(httpResponse: response), response) + throw AWSClientRuntime.UnknownAWSHTTPServiceError( + httpResponse: HttpResponse(body: .empty, statusCode: .forbidden), + message: nil, + requestID: nil, + typeName: nil + ) } let options = StorageListRequest.Options(accessLevel: .protected, targetIdentityId: targetIdentityId, path: path) do { From a231b99ff9830857b629ff1c92578ba0e1fd2953 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 2 Oct 2023 11:49:24 -0400 Subject: [PATCH 08/23] fix(cloudwatch-logging): clientruntime name changes for sdk update (#3260) --- .../AWSCloudWatchLoggingCategoryClient.swift | 4 ++-- .../AWSCloudWatchLoggingSessionController.swift | 10 +++++----- .../DefaultRemoteLoggingConstraintsProvider.swift | 8 +++++--- .../MockCloudWatchLogsClient.swift | 12 +++++++++++- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingCategoryClient.swift b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingCategoryClient.swift index 9416ecae34..4503f4eaf1 100644 --- a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingCategoryClient.swift +++ b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingCategoryClient.swift @@ -26,7 +26,7 @@ final class AWSCloudWatchLoggingCategoryClient { private let lock = NSLock() private let logGroupName: String private let region: String - private let credentialsProvider: CredentialsProvider + private let credentialsProvider: CredentialsProviding private let authentication: AuthCategoryUserBehavior private var loggersByKey: [LoggerKey: AWSCloudWatchLoggingSessionController] = [:] private let localStoreMaxSizeInMB: Int @@ -38,7 +38,7 @@ final class AWSCloudWatchLoggingCategoryClient { init( enable: Bool, - credentialsProvider: CredentialsProvider, + credentialsProvider: CredentialsProviding, authentication: AuthCategoryUserBehavior, loggingConstraintsResolver: AWSCloudWatchLoggingConstraintsResolver, logGroupName: String, diff --git a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift index b12e9c134e..cb0c07da3c 100644 --- a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift +++ b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift @@ -25,7 +25,7 @@ final class AWSCloudWatchLoggingSessionController { private let logGroupName: String private let region: String private let localStoreMaxSizeInMB: Int - private let credentialsProvider: CredentialsProvider + private let credentialsProvider: CredentialsProviding private let authentication: AuthCategoryUserBehavior private let category: String private var session: AWSCloudWatchLoggingSession? @@ -59,7 +59,7 @@ final class AWSCloudWatchLoggingSessionController { } /// - Tag: CloudWatchLogSessionController.init - init(credentialsProvider: CredentialsProvider, + init(credentialsProvider: CredentialsProviding, authentication: AuthCategoryUserBehavior, logFilter: AWSCloudWatchLoggingFilterBehavior, category: String, @@ -103,10 +103,10 @@ final class AWSCloudWatchLoggingSessionController { private func createConsumer() throws -> LogBatchConsumer? { if self.client == nil { + // TODO: FrameworkMetadata Replacement let configuration = try CloudWatchLogsClient.CloudWatchLogsClientConfiguration( - credentialsProvider: credentialsProvider, - frameworkMetadata: AmplifyAWSServiceConfiguration.frameworkMetaData(), - region: region + region: region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op diff --git a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Configuration/DefaultRemoteLoggingConstraintsProvider.swift b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Configuration/DefaultRemoteLoggingConstraintsProvider.swift index 540bc7e3f9..5f8b29c344 100644 --- a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Configuration/DefaultRemoteLoggingConstraintsProvider.swift +++ b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Configuration/DefaultRemoteLoggingConstraintsProvider.swift @@ -14,7 +14,7 @@ import ClientRuntime public class DefaultRemoteLoggingConstraintsProvider: RemoteLoggingConstraintsProvider { public let refreshIntervalInSeconds: Int private let endpoint: URL - private let credentialProvider: CredentialsProvider? + private let credentialProvider: CredentialsProviding? private let region: String private let loggingConstraintsLocalStore: LoggingConstraintsLocalStore = UserDefaults.standard @@ -31,7 +31,7 @@ public class DefaultRemoteLoggingConstraintsProvider: RemoteLoggingConstraintsPr public init( endpoint: URL, region: String, - credentialProvider: CredentialsProvider? = nil, + credentialProvider: CredentialsProviding? = nil, refreshIntervalInSeconds: Int = 1200 ) { self.endpoint = endpoint @@ -79,7 +79,9 @@ public class DefaultRemoteLoggingConstraintsProvider: RemoteLoggingConstraintsPr let httpMethod = (request.httpMethod?.uppercased()) .flatMap(HttpMethodType.init(rawValue:)) ?? .get - let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)? + .queryItems? + .map { ClientRuntime.URLQueryItem(name: $0.name, value: $0.value) } ?? [] let requestBuilder = SdkHttpRequestBuilder() .withHost(host) diff --git a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/MockCloudWatchLogsClient.swift b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/MockCloudWatchLogsClient.swift index e71877c8b6..1d290c6c00 100644 --- a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/MockCloudWatchLogsClient.swift +++ b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/MockCloudWatchLogsClient.swift @@ -224,5 +224,15 @@ class MockCloudWatchLogsClient: CloudWatchLogsClientProtocol { throw MockError.unimplemented } - + func deleteAccountPolicy(input: AWSCloudWatchLogs.DeleteAccountPolicyInput) async throws -> AWSCloudWatchLogs.DeleteAccountPolicyOutputResponse { + throw MockError.unimplemented + } + + func describeAccountPolicies(input: AWSCloudWatchLogs.DescribeAccountPoliciesInput) async throws -> AWSCloudWatchLogs.DescribeAccountPoliciesOutputResponse { + throw MockError.unimplemented + } + + func putAccountPolicy(input: AWSCloudWatchLogs.PutAccountPolicyInput) async throws -> AWSCloudWatchLogs.PutAccountPolicyOutputResponse { + throw MockError.unimplemented + } } From 7f07ac41a6ba7b6865b39ce66c102f5c35d5545b Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 2 Oct 2023 15:49:04 -0400 Subject: [PATCH 09/23] fix(predictions): new error handling and tests (#3257) --- .../AWSTranscribeStreamingAdapter.swift | 4 +- .../AWSPredictionsService+Comprehend.swift | 4 +- .../AWSPredictionsService+Polly.swift | 18 ++- .../AWSPredictionsService+Rekognition.swift | 42 +++--- .../AWSPredictionsService+Textract.swift | 4 +- .../AWSPredictionsService+Translate.swift | 4 +- .../Predictions/AWSPredictionsService.swift | 22 +-- ...mprehend+PredictionsErrorConvertible.swift | 31 +++++ ...ng+DetectDominantLanguageOutputError.swift | 24 ---- .../Polly+PredictionsErrorConvertible.swift | 93 +++++++++++++ ...rMapping+SynthesizeSpeechOutputError.swift | 66 --------- ...ognition+PredictionsErrorConvertible.swift | 121 ++++++++++++++++ .../RekognitionCommonExceptions.swift | 75 ---------- ...eErrorMapping+DetectFacesOutputError.swift | 48 ------- ...ErrorMapping+DetectLabelsOutputError.swift | 48 ------- ...ng+DetectModerationLabelsOutputError.swift | 57 -------- ...ceErrorMapping+DetectTextOutputError.swift | 48 ------- ...ping+RekognizeCelebritiesOutputError.swift | 42 ------ ...apping+SearchFacesByImageOutputError.swift | 49 ------- .../ErrorHandling/ServiceErrorMapping.swift | 16 --- ...Textract+PredictionsErrorConvertible.swift | 130 ++++++++++++++++++ ...orMapping+AnalyzeDocumentOutputError.swift | 61 -------- ...apping+DetectDocumentTextOutputError.swift | 51 ------- .../Textract/TextractCommonException.swift | 60 -------- ...ranslate+PredictionsErrorConvertible.swift | 52 +++++++ ...rrorMapping+TranslateTextOutputError.swift | 32 ----- .../PollyErrorMappingTestCase.swift | 34 +++-- .../TextractErrorMappingTestCase.swift | 31 +++-- .../Service/MockRekognitionBehavior.swift | 9 ++ .../Mocks/Service/MockTranslateBehavior.swift | 1 + 30 files changed, 524 insertions(+), 753 deletions(-) create mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend+PredictionsErrorConvertible.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend/ServiceErrorMapping+DetectDominantLanguageOutputError.swift create mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly+PredictionsErrorConvertible.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly/ServiceErrorMapping+SynthesizeSpeechOutputError.swift create mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition+PredictionsErrorConvertible.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/RekognitionCommonExceptions.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectFacesOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectLabelsOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectModerationLabelsOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectTextOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+RekognizeCelebritiesOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+SearchFacesByImageOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/ServiceErrorMapping.swift create mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract+PredictionsErrorConvertible.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+AnalyzeDocumentOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+DetectDocumentTextOutputError.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/TextractCommonException.swift create mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate+PredictionsErrorConvertible.swift delete mode 100644 AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate/ServiceErrorMapping+TranslateTextOutputError.swift diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Dependency/AWSTranscribeStreamingAdapter.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Dependency/AWSTranscribeStreamingAdapter.swift index ada2ff5135..97aed80ff8 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Dependency/AWSTranscribeStreamingAdapter.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Dependency/AWSTranscribeStreamingAdapter.swift @@ -22,10 +22,10 @@ class AWSTranscribeStreamingAdapter: AWSTranscribeStreamingBehavior { let mediaSampleRateHertz: Int } - let credentialsProvider: CredentialsProvider + let credentialsProvider: CredentialsProviding let region: String - init(credentialsProvider: CredentialsProvider, region: String) { + init(credentialsProvider: CredentialsProviding, region: String) { self.credentialsProvider = credentialsProvider self.region = region } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Comprehend.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Comprehend.swift index ed04516078..d44e7729f3 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Comprehend.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Comprehend.swift @@ -38,8 +38,8 @@ extension AWSPredictionsService: AWSComprehendServiceBehavior { .map(Predictions.Language.init(locale:)) ?? .undetermined return (predictionsLanguage, dominantLanguage?.score.map(Double.init)) - } catch let error as DetectDominantLanguageOutputError { - throw ServiceErrorMapping.detectDominantLanguage.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift index ef070be2e2..507e968448 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift @@ -34,12 +34,18 @@ extension AWSPredictionsService: AWSPollyServiceBehavior { ) } - let textToSpeechResult = Predictions.Convert.TextToSpeech.Result( - audioData: speech.toBytes().getData() - ) - return textToSpeechResult - } catch let error as SynthesizeSpeechOutputError { - throw ServiceErrorMapping.synthesizeSpeech.map(error) + switch speech { + case .data(let data?): + let textToSpeechResult = Predictions.Convert.TextToSpeech.Result( + audioData: data + ) + return textToSpeechResult + // TODO: figure out what to throw here + default: throw PredictionsError.unknown("Missing respose", "", nil) + } + + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Rekognition.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Rekognition.swift index 8a67da343b..0846015c48 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Rekognition.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Rekognition.swift @@ -24,8 +24,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let labelsResult = try await detectLabels(image: imageData) let newLabels = IdentifyLabelsResultTransformers.processLabels(labelsResult.labels ?? []) return Predictions.Identify.Labels.Result(labels: newLabels, unsafeContent: nil) - } catch let error as DetectLabelsOutputError { - throw ServiceErrorMapping.detectLabels.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -35,8 +35,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let unsafeContent = !moderationLabels.isEmpty let labels = IdentifyLabelsResultTransformers.processModerationLabels(moderationLabels) return Predictions.Identify.Labels.Result(labels: labels, unsafeContent: unsafeContent) - } catch let error as DetectModerationLabelsOutputError { - throw ServiceErrorMapping.detectModerationLabels.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) @@ -67,8 +67,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let newCelebs = IdentifyCelebritiesResultTransformers.processCelebs(celebrities) return Predictions.Identify.Celebrities.Result(celebrities: newCelebs) - } catch let error as RecognizeCelebritiesOutputError { - throw ServiceErrorMapping.detectCelebrities.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -94,8 +94,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { .searchFacesByImage(input: input).faceMatches ?? [] let faceMatches = IdentifyEntitiesResultTransformers.processCollectionFaces(faces) return Predictions.Identify.EntityMatches.Result(entities: faceMatches) - } catch let error as SearchFacesByImageOutputError { - throw ServiceErrorMapping.searchFacesByImage.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -112,8 +112,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let faces = try await awsRekognition.detectFaces(input: input).faceDetails ?? [] let newFaces = IdentifyEntitiesResultTransformers.processFaces(faces) return Predictions.Identify.Entities.Result(entities: newFaces) - } catch let error as DetectFacesOutputError { - throw ServiceErrorMapping.detectFaces.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unknownServiceError(error) } @@ -128,8 +128,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { do { textResult = try await awsRekognition.detectText(input: request) - } catch let error as DetectTextOutputError { - throw ServiceErrorMapping.detectText.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -147,8 +147,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let documentTextResult: DetectDocumentTextOutputResponse do { documentTextResult = try await detectDocumentText(image: imageData) - } catch let error as DetectDocumentTextOutputError { - throw ServiceErrorMapping.detectDocumentText.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -200,8 +200,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let textResult: DetectTextOutputResponse do { textResult = try await awsRekognition.detectText(input: request) - } catch let error as DetectTextOutputError { - throw ServiceErrorMapping.detectText.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -220,8 +220,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let documentTextResult: DetectDocumentTextOutputResponse do { documentTextResult = try await detectDocumentText(image: imageData) - } catch let error as DetectDocumentTextOutputError { - throw ServiceErrorMapping.detectDocumentText.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } @@ -275,10 +275,8 @@ extension AWSPredictionsService: AWSRekognitionServiceBehavior { let moderationLabels = moderationLabelsOutput.moderationLabels ?? [] let unsafeContent = !moderationLabels.isEmpty return Predictions.Identify.Labels.Result(labels: allLabels, unsafeContent: unsafeContent) - } catch let error as DetectLabelsOutputError { - throw ServiceErrorMapping.detectLabels.map(error) - } catch let error as DetectModerationLabelsOutputError { - throw ServiceErrorMapping.detectModerationLabels.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Textract.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Textract.swift index ec1e1b70ce..fd882740d9 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Textract.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Textract.swift @@ -41,8 +41,8 @@ extension AWSPredictionsService: AWSTextractServiceBehavior { let documentResult: AnalyzeDocumentOutputResponse do { documentResult = try await awsTextract.analyzeDocument(input: request) - } catch let error as AnalyzeDocumentOutputError { - throw ServiceErrorMapping.analyzeDocument.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Translate.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Translate.swift index a09318f4ed..81d3a47d20 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Translate.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Translate.swift @@ -35,8 +35,8 @@ extension AWSPredictionsService: AWSTranslateServiceBehavior { let textTranslateResult: TranslateTextOutputResponse do { textTranslateResult = try await awsTranslate.translateText(input: request) - } catch let error as TranslateTextOutputError { - throw ServiceErrorMapping.translateText.map(error) + } catch let error as PredictionsErrorConvertible { + throw error.predictionsError } catch { throw PredictionsError.unexpectedServiceErrorType(error) } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift index 08a3336789..9d87be3f5f 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift @@ -31,12 +31,12 @@ class AWSPredictionsService { convenience init( configuration: PredictionsPluginConfiguration, - credentialsProvider: CredentialsProvider, + credentialsProvider: CredentialsProviding, identifier: String ) throws { let translateClientConfiguration = try TranslateClient.TranslateClientConfiguration( - credentialsProvider: credentialsProvider, - region: configuration.convert.region + region: configuration.convert.region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op #else @@ -47,8 +47,8 @@ class AWSPredictionsService { let awsTranslateClient = TranslateClient(config: translateClientConfiguration) let pollyClientConfiguration = try PollyClient.PollyClientConfiguration( - credentialsProvider: credentialsProvider, - region: configuration.convert.region + region: configuration.convert.region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op #else @@ -59,8 +59,8 @@ class AWSPredictionsService { let awsPollyClient = PollyClient(config: pollyClientConfiguration) let comprehendClientConfiguration = try ComprehendClient.ComprehendClientConfiguration( - credentialsProvider: credentialsProvider, - region: configuration.convert.region + region: configuration.convert.region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op #else @@ -71,8 +71,8 @@ class AWSPredictionsService { let awsComprehendClient = ComprehendClient(config: comprehendClientConfiguration) let rekognitionClientConfiguration = try RekognitionClient.RekognitionClientConfiguration( - credentialsProvider: credentialsProvider, - region: configuration.identify.region + region: configuration.identify.region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op #else @@ -83,8 +83,8 @@ class AWSPredictionsService { let awsRekognitionClient = RekognitionClient(config: rekognitionClientConfiguration) let textractClientConfiguration = try TextractClient.TextractClientConfiguration( - credentialsProvider: credentialsProvider, - region: configuration.identify.region + region: configuration.identify.region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op #else diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend+PredictionsErrorConvertible.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend+PredictionsErrorConvertible.swift new file mode 100644 index 0000000000..d1ad4a9911 --- /dev/null +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend+PredictionsErrorConvertible.swift @@ -0,0 +1,31 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AWSComprehend +import Amplify + +protocol PredictionsErrorConvertible { + var predictionsError: PredictionsError { get } +} + +extension AWSComprehend.InternalServerException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.internalServerError) + } +} + +extension AWSComprehend.InvalidRequestException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.invalidRequest) + } +} + +extension AWSComprehend.TextSizeLimitExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.textSizeLimitExceeded) + } +} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend/ServiceErrorMapping+DetectDominantLanguageOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend/ServiceErrorMapping+DetectDominantLanguageOutputError.swift deleted file mode 100644 index de5b76f695..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Comprehend/ServiceErrorMapping+DetectDominantLanguageOutputError.swift +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSComprehend -import Amplify - -extension ServiceErrorMapping where T == DetectDominantLanguageOutputError { - static let detectDominantLanguage: Self = .init { error in - switch error { - case .internalServerException: - return PredictionsError.service(.internalServerError) - case .invalidRequestException: - return PredictionsError.service(.invalidRequest) - case .textSizeLimitExceededException: - return PredictionsError.service(.textSizeLimitExceeded) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly+PredictionsErrorConvertible.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly+PredictionsErrorConvertible.swift new file mode 100644 index 0000000000..78796e95ce --- /dev/null +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly+PredictionsErrorConvertible.swift @@ -0,0 +1,93 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AWSPolly +import Amplify + +extension AWSPolly.InvalidSampleRateException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.invalidSampleRate) + } +} + +extension AWSPolly.LanguageNotSupportedException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.unsupportedLanguage) + } +} + +extension AWSPolly.ServiceFailureException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.internalServerError) + } +} + +extension AWSPolly.TextLengthExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.textSizeLimitExceeded) + } +} + +extension AWSPolly.LexiconNotFoundException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "Amazon Polly can't find the specified lexicon. This could be caused by a lexicon that is missing, its name is misspelled or specifying a lexicon that is in a different region.", + recoverySuggestion: "Verify that the lexicon exists, is in the region (see ListLexicons) and that you spelled its name is spelled correctly. Then try again.", + underlyingError: self + ) + ) + } +} + +extension AWSPolly.MarksNotSupportedForFormatException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "Speech marks are not supported for the OutputFormat selected.", + recoverySuggestion: "Speech marks are only available for content in json format.", + underlyingError: self + ) + ) + } +} + +extension AWSPolly.InvalidSsmlException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The SSML you provided is invalid.", + recoverySuggestion: "Verify the SSML syntax, spelling of tags and values, and then try again.", + underlyingError: self + ) + ) + } +} + +extension AWSPolly.SsmlMarksNotSupportedForTextTypeException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "SSML speech marks are not supported for plain text-type input.", + recoverySuggestion: "", + underlyingError: self + ) + ) + } +} + +extension AWSPolly.EngineNotSupportedException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "This engine is not compatible with the voice that you have designated.", + recoverySuggestion: "Choose a new voice that is compatible with the engine or change the engine and restart the operation.", + underlyingError: self + ) + ) + } +} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly/ServiceErrorMapping+SynthesizeSpeechOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly/ServiceErrorMapping+SynthesizeSpeechOutputError.swift deleted file mode 100644 index 60688eb7cd..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Polly/ServiceErrorMapping+SynthesizeSpeechOutputError.swift +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSPolly -import Amplify - -extension ServiceErrorMapping where T == SynthesizeSpeechOutputError { - static let synthesizeSpeech: Self = .init { error in - switch error { - case .invalidSampleRateException: - return PredictionsError.service(.invalidSampleRate) - case .languageNotSupportedException: - return PredictionsError.service(.unsupportedLanguage) - case .serviceFailureException: - return PredictionsError.service(.internalServerError) - case .textLengthExceededException: - return PredictionsError.service(.textSizeLimitExceeded) - case .lexiconNotFoundException: - return PredictionsError.service( - .init( - description: "Amazon Polly can't find the specified lexicon. This could be caused by a lexicon that is missing, its name is misspelled or specifying a lexicon that is in a different region.", - recoverySuggestion: "Verify that the lexicon exists, is in the region (see ListLexicons) and that you spelled its name is spelled correctly. Then try again.", - underlyingError: error - ) - ) - case .marksNotSupportedForFormatException: - return PredictionsError.service( - .init( - description: "Speech marks are not supported for the OutputFormat selected.", - recoverySuggestion: "Speech marks are only available for content in json format.", - underlyingError: error - ) - ) - case .invalidSsmlException: - return PredictionsError.service( - .init( - description: "The SSML you provided is invalid.", - recoverySuggestion: "Verify the SSML syntax, spelling of tags and values, and then try again.", - underlyingError: error - ) - ) - case .ssmlMarksNotSupportedForTextTypeException: - return PredictionsError.service( - .init( - description: "SSML speech marks are not supported for plain text-type input.", - recoverySuggestion: "", - underlyingError: error - ) - ) - case .engineNotSupportedException: - return PredictionsError.service( - .init( - description: "This engine is not compatible with the voice that you have designated.", - recoverySuggestion: "Choose a new voice that is compatible with the engine or change the engine and restart the operation.", - underlyingError: error - ) - ) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition+PredictionsErrorConvertible.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition+PredictionsErrorConvertible.swift new file mode 100644 index 0000000000..464060e9da --- /dev/null +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition+PredictionsErrorConvertible.swift @@ -0,0 +1,121 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AWSRekognition +import Amplify +import ClientRuntime + + +extension AWSRekognition.HumanLoopQuotaExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The number of in-progress human reviews you have has exceeded the number allowed.", + recoverySuggestion: "Try again later.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSRekognition.ResourceNotFoundException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.resourceNotFound) + } +} + +extension AWSRekognition.ThrottlingException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.throttling) + } +} + +extension AWSRekognition.InternalServerError: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.internalServerError) + } +} + +extension AWSRekognition.AccessDeniedException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.accessDenied) + } +} + +extension AWSRekognition.ImageTooLargeException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The image you sent was too large.", + recoverySuggestion: "Try downsizing the image and sending it again.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSRekognition.InvalidImageFormatException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The provided image format isn't supported.", + recoverySuggestion: "Use a supported image format (.JPEG and .PNG) and try again.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSRekognition.InvalidParameterException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "An input parameter violated a constraint.", + recoverySuggestion: "Validate your parameters before calling the API operation again.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSRekognition.InvalidS3ObjectException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The number of requests exceeded your throughput limit.", + recoverySuggestion: """ + Decrease the number of calls you are making until it is below the limit for your region. + Check the limits here: + https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition + """, + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSRekognition.ProvisionedThroughputExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The number of requests exceeded your throughput limit.", + recoverySuggestion: """ + Decrease the number of calls you are making until it is below the limit for your region. + Check the limits here: + https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition + """, + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/RekognitionCommonExceptions.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/RekognitionCommonExceptions.swift deleted file mode 100644 index 3f7933a26c..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/RekognitionCommonExceptions.swift +++ /dev/null @@ -1,75 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify -import ClientRuntime - -enum RekognitionCommonExceptions { - static func imageTooLarge(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - return .service( - .init( - description: "The image you sent was too large.", - recoverySuggestion: "Try downsizing the image and sending it again.", - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func invalidImageFormat(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - return .service( - .init( - description: "The provided image format isn't supported.", - recoverySuggestion: "Use a supported image format (.JPEG and .PNG) and try again.", - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func invalidParameter(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - return .service( - .init( - description: "An input parameter violated a constraint.", - recoverySuggestion: "Validate your parameters before calling the API operation again.", - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func invalidS3Object(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - .service( - .init( - description: "The number of requests exceeded your throughput limit.", - recoverySuggestion: """ - Decrease the number of calls you are making until it is below the limit for your region. - Check the limits here: - https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition - """, - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func provisionedThroughputExceeded(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - .service( - .init( - description: "The number of requests exceeded your throughput limit.", - recoverySuggestion: """ - Decrease the number of calls you are making until it is below the limit for your region. - Check the limits here: - https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition - """, - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectFacesOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectFacesOutputError.swift deleted file mode 100644 index 4b79ce1683..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectFacesOutputError.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify - -extension ServiceErrorMapping where T == DetectFacesOutputError { - static let detectFaces: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .imageTooLargeException(let imageTooLargeException): - return RekognitionCommonExceptions.imageTooLarge( - error, statusCode: imageTooLargeException._statusCode - ) - case .internalServerError: - return PredictionsError.service(.internalServerError) - case .invalidImageFormatException(let invalidImageFormatException): - return RekognitionCommonExceptions.invalidImageFormat( - error, - statusCode: invalidImageFormatException._statusCode - ) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException: - return PredictionsError.service(.throttling) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectLabelsOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectLabelsOutputError.swift deleted file mode 100644 index be00516c14..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectLabelsOutputError.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify - -extension ServiceErrorMapping where T == DetectLabelsOutputError { - static let detectLabels: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .imageTooLargeException(let imageTooLargeException): - return RekognitionCommonExceptions.imageTooLarge( - error, statusCode: imageTooLargeException._statusCode - ) - case .internalServerError: - return PredictionsError.service(.internalServerError) - case .invalidImageFormatException(let invalidImageFormatException): - return RekognitionCommonExceptions.invalidImageFormat( - error, - statusCode: invalidImageFormatException._statusCode - ) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException: - return PredictionsError.service(.throttling) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectModerationLabelsOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectModerationLabelsOutputError.swift deleted file mode 100644 index 37d855ae67..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectModerationLabelsOutputError.swift +++ /dev/null @@ -1,57 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify - -extension ServiceErrorMapping where T == DetectModerationLabelsOutputError { - static let detectModerationLabels: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .imageTooLargeException(let imageTooLargeException): - return RekognitionCommonExceptions.imageTooLarge( - error, statusCode: imageTooLargeException._statusCode - ) - case .internalServerError: - return PredictionsError.service(.internalServerError) - case .invalidImageFormatException(let invalidImageFormatException): - return RekognitionCommonExceptions.invalidImageFormat( - error, - statusCode: invalidImageFormatException._statusCode - ) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException: - return PredictionsError.service(.throttling) - case .humanLoopQuotaExceededException(let humanLoopQuotaExceededException): - return .service( - .init( - description: "", - recoverySuggestion: "", - httpStatusCode: humanLoopQuotaExceededException._statusCode?.rawValue, - underlyingError: error - ) - ) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectTextOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectTextOutputError.swift deleted file mode 100644 index 0e76a4a4b9..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+DetectTextOutputError.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify - -extension ServiceErrorMapping where T == DetectTextOutputError { - static let detectText: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .imageTooLargeException(let imageTooLargeException): - return RekognitionCommonExceptions.imageTooLarge( - error, statusCode: imageTooLargeException._statusCode - ) - case .internalServerError: - return PredictionsError.service(.internalServerError) - case .invalidImageFormatException(let invalidImageFormatException): - return RekognitionCommonExceptions.invalidImageFormat( - error, - statusCode: invalidImageFormatException._statusCode - ) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException: - return PredictionsError.service(.throttling) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+RekognizeCelebritiesOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+RekognizeCelebritiesOutputError.swift deleted file mode 100644 index 0faa619191..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+RekognizeCelebritiesOutputError.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify - -extension ServiceErrorMapping where T == RecognizeCelebritiesOutputError { - static let detectCelebrities: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .imageTooLargeException(let imageTooLargeException): - return RekognitionCommonExceptions.imageTooLarge(error, statusCode: imageTooLargeException._statusCode) - case .internalServerError(let internalServerError): - return PredictionsError.service(.internalServerError) - case .invalidImageFormatException(let invalidImageFormatException): - return RekognitionCommonExceptions.invalidImageFormat( - error, statusCode: invalidImageFormatException._statusCode - ) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException(let throttlingException): - return PredictionsError.service(.throttling) - case .unknown(let unknown): - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+SearchFacesByImageOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+SearchFacesByImageOutputError.swift deleted file mode 100644 index 9205f15493..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Rekognition/ServiceErrorMapping+SearchFacesByImageOutputError.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSRekognition -import Amplify - -extension ServiceErrorMapping where T == SearchFacesByImageOutputError { - static let searchFacesByImage: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .imageTooLargeException(let imageTooLargeException): - return RekognitionCommonExceptions.imageTooLarge( - error, statusCode: imageTooLargeException._statusCode - ) - case .internalServerError(let internalServerError): - return PredictionsError.service(.internalServerError) - case .invalidImageFormatException(let invalidImageFormatException): - return RekognitionCommonExceptions.invalidImageFormat( - error, statusCode: invalidImageFormatException._statusCode - ) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .resourceNotFoundException(let resourceNotFoundException): - return PredictionsError.service(.resourceNotFound) - case .throttlingException(let throttlingException): - return PredictionsError.service(.throttling) - case .unknown(let unknownAWSHttpServiceError): - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/ServiceErrorMapping.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/ServiceErrorMapping.swift deleted file mode 100644 index 5fec8447cf..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/ServiceErrorMapping.swift +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify - -struct ServiceErrorMapping { - let map: (T) -> PredictionsError - - static func map(_ error: T, with rule: ServiceErrorMapping) -> PredictionsError { - rule.map(error) - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract+PredictionsErrorConvertible.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract+PredictionsErrorConvertible.swift new file mode 100644 index 0000000000..9aa5908460 --- /dev/null +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract+PredictionsErrorConvertible.swift @@ -0,0 +1,130 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AWSTextract +import Amplify +import ClientRuntime + + +extension AWSTextract.HumanLoopQuotaExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The number of in-progress human reviews you have has exceeded the number allowed.", + recoverySuggestion: "Try again later.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSTextract.ThrottlingException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.throttling) + } +} + +extension AWSTextract.InternalServerError: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.internalServerError) + } +} + +extension AWSTextract.AccessDeniedException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.accessDenied) + } +} + +extension AWSTextract.InvalidParameterException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "An input parameter violated a constraint.", + recoverySuggestion: "Validate your parameters before calling the API operation again.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSTextract.InvalidS3ObjectException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The number of requests exceeded your throughput limit.", + recoverySuggestion: """ + Decrease the number of calls you are making until it is below the limit for your region. + Check the limits here: + https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition + """, + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSTextract.ProvisionedThroughputExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The number of requests exceeded your throughput limit.", + recoverySuggestion: """ + Decrease the number of calls you are making until it is below the limit for your region. + Check the limits here: + https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_rekognition + """, + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + + +extension AWSTextract.BadDocumentException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The image sent over was corrupt or malformed.", + recoverySuggestion: "Please double check the image sent over and try again.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + +extension AWSTextract.DocumentTooLargeException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The image sent over was too large.", + recoverySuggestion: "Please decrease the size of the image sent over and try again.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} + + +extension AWSTextract.UnsupportedDocumentException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service( + .init( + description: "The document type sent over is unsupported", + recoverySuggestion: "The formats supported are PNG or JPEG format.", + httpStatusCode: httpResponse.statusCode.rawValue, + underlyingError: self + ) + ) + } +} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+AnalyzeDocumentOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+AnalyzeDocumentOutputError.swift deleted file mode 100644 index 6312a60644..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+AnalyzeDocumentOutputError.swift +++ /dev/null @@ -1,61 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSTextract -import Amplify -import ClientRuntime - -extension ServiceErrorMapping where T == AnalyzeDocumentOutputError { - static let analyzeDocument: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .badDocumentException(let badDocumentException): - return TextractCommonException.badDocument( - error, statusCode: badDocumentException._statusCode - ) - case .documentTooLargeException(let documentTooLargeException): - return TextractCommonException.documentTooLarge( - error, statusCode: documentTooLargeException._statusCode - ) - case .humanLoopQuotaExceededException(let humanLoopQuotaExceededException): - return .service( - .init( - description: "", - recoverySuggestion: "", - httpStatusCode: humanLoopQuotaExceededException._statusCode?.rawValue, - underlyingError: error - ) - ) - case .internalServerError: - return PredictionsError.service(.internalServerError) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return TextractCommonException.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException: - return PredictionsError.service(.throttling) - case .unsupportedDocumentException(let unsupportedDocumentException): - return TextractCommonException.unsupportedDocument( - error, statusCode: unsupportedDocumentException._statusCode - ) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+DetectDocumentTextOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+DetectDocumentTextOutputError.swift deleted file mode 100644 index d6d48521d9..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/ServiceErrorMapping+DetectDocumentTextOutputError.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSTextract -import Amplify - -extension ServiceErrorMapping where T == DetectDocumentTextOutputError { - static let detectDocumentText: Self = .init { error in - switch error { - case .accessDeniedException(let accessDeniedException): - return PredictionsError.service(.accessDenied) - case .internalServerError: - return PredictionsError.service(.internalServerError) - case .invalidParameterException(let invalidParameterException): - return RekognitionCommonExceptions.invalidParameter( - error, - statusCode: invalidParameterException._statusCode - ) - case .invalidS3ObjectException(let invalidS3ObjectException): - return RekognitionCommonExceptions.invalidS3Object( - error, - statusCode: invalidS3ObjectException._statusCode - ) - case .provisionedThroughputExceededException(let provisionedThroughputExceededException): - return RekognitionCommonExceptions.provisionedThroughputExceeded( - error, - statusCode: provisionedThroughputExceededException._statusCode - ) - case .throttlingException: - return PredictionsError.service(.throttling) - case .unknown: - return PredictionsError.unknownServiceError(error) - case .badDocumentException(let badDocumentException): - return TextractCommonException.badDocument( - error, statusCode: badDocumentException._statusCode - ) - case .documentTooLargeException(let documentTooLargeException): - return TextractCommonException.documentTooLarge( - error, statusCode: documentTooLargeException._statusCode - ) - case .unsupportedDocumentException(let unsupportedDocumentException): - return TextractCommonException.unsupportedDocument( - error, statusCode: unsupportedDocumentException._statusCode - ) - } - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/TextractCommonException.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/TextractCommonException.swift deleted file mode 100644 index 415284f354..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Textract/TextractCommonException.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSTextract -import Amplify -import ClientRuntime - -enum TextractCommonException { - static func badDocument(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - return .service( - .init( - description: "The image sent over was corrupt or malformed.", - recoverySuggestion: "Please double check the image sent over and try again.", - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func documentTooLarge(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - return .service( - .init( - description: "The image sent over was too large.", - recoverySuggestion: "Please decrease the size of the image sent over and try again.", - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func unsupportedDocument(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - return .service( - .init( - description: "The document type sent over is unsupported", - recoverySuggestion: "The formats supported are PNG or JPEG format.", - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } - - static func provisionedThroughputExceeded(_ error: Error, statusCode: HttpStatusCode?) -> PredictionsError { - .service( - .init( - description: "The number of requests exceeded your throughput limit.", - recoverySuggestion: """ - Decrease the number of calls you are making until it is below the limit for your region. - Check the limits here: - https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_textract - """, - httpStatusCode: statusCode?.rawValue, - underlyingError: error - ) - ) - } -} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate+PredictionsErrorConvertible.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate+PredictionsErrorConvertible.swift new file mode 100644 index 0000000000..aeb5897aac --- /dev/null +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate+PredictionsErrorConvertible.swift @@ -0,0 +1,52 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AWSTranslate +import Amplify + +extension AWSTranslate.DetectedLanguageLowConfidenceException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.detectedLanguageLowConfidence) + } +} + +extension AWSTranslate.InternalServerException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.internalServerError) + } +} + + +extension AWSTranslate.InvalidRequestException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.invalidRequest) + } +} + +extension AWSTranslate.ResourceNotFoundException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.resourceNotFound) + } +} + +extension AWSTranslate.TextSizeLimitExceededException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.textSizeLimitExceeded) + } +} + +extension AWSTranslate.TooManyRequestsException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.throttling) + } +} + +extension AWSTranslate.UnsupportedLanguagePairException: PredictionsErrorConvertible { + var predictionsError: PredictionsError { + .service(.unsupportedLanguagePair) + } +} diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate/ServiceErrorMapping+TranslateTextOutputError.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate/ServiceErrorMapping+TranslateTextOutputError.swift deleted file mode 100644 index 15706934c4..0000000000 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Support/Internal/ErrorHandling/Translate/ServiceErrorMapping+TranslateTextOutputError.swift +++ /dev/null @@ -1,32 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSTranslate -import Amplify - -extension ServiceErrorMapping where T == TranslateTextOutputError { - static let translateText: Self = .init { error in - switch error { - case .detectedLanguageLowConfidenceException(let detectedLanguageLowConfidenceException): - return PredictionsError.service(.detectedLanguageLowConfidence) - case .internalServerException(let internalServerException): - return PredictionsError.service(.internalServerError) - case .invalidRequestException(let invalidRequestException): - return PredictionsError.service(.invalidRequest) - case .resourceNotFoundException, .serviceUnavailableException: - return PredictionsError.service(.resourceNotFound) - case .textSizeLimitExceededException(let textSizeLimitExceededException): - return PredictionsError.service(.textSizeLimitExceeded) - case .tooManyRequestsException(let tooManyRequestsException): - return PredictionsError.service(.throttling) - case .unsupportedLanguagePairException(let unsupportedLanguagePairException): - return PredictionsError.service(.unsupportedLanguagePair) - case .unknown: - return PredictionsError.unknownServiceError(error) - } - } -} diff --git a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/PollyErrorMappingTestCase.swift b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/PollyErrorMappingTestCase.swift index c9576ca6a5..62133dac70 100644 --- a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/PollyErrorMappingTestCase.swift +++ b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/PollyErrorMappingTestCase.swift @@ -12,37 +12,41 @@ import Amplify final class PollyErrorMappingTestCase: XCTestCase { private func assertCatchVariations( - for sdkError: SynthesizeSpeechOutputError, + for sdkError: Error, expecting expectedServiceError: PredictionsError.ServiceError, label: String ) { - let predictionsError = ServiceErrorMapping.synthesizeSpeech.map(sdkError) let unexpected: (Error) -> String = { "Expected PredictionsError.service(.\(label), received \($0)" } + // catch variation 1. - do { throw predictionsError } - catch PredictionsError.service(expectedServiceError) {} + do { throw sdkError } + catch let error as PredictionsErrorConvertible { + guard case .service(expectedServiceError) = error.predictionsError else { + return XCTFail(unexpected(error.predictionsError)) + } + } catch { XCTFail(unexpected(error)) } // catch variation 2. - do { throw predictionsError } - catch let error as PredictionsError { - guard case .service(expectedServiceError) = error else { - return XCTFail(unexpected(error)) + do { throw sdkError } + catch let error as PredictionsErrorConvertible { + guard case .service(expectedServiceError) = error.predictionsError else { + return XCTFail(unexpected(error.predictionsError)) } } catch { XCTFail(unexpected(error)) } // catch variation 3. - do { throw predictionsError } + do { throw sdkError } catch { - guard let error = error as? PredictionsError, - case .service(expectedServiceError) = error + guard let error = error as? PredictionsErrorConvertible, + case .service(expectedServiceError) = error.predictionsError else { return XCTFail(unexpected(error)) } @@ -51,7 +55,7 @@ final class PollyErrorMappingTestCase: XCTestCase { func testSynthesizeSpeech_invalidSampleRateException() throws { assertCatchVariations( - for: .invalidSampleRateException(.init()), + for: InvalidSampleRateException(), expecting: .invalidSampleRate, label: "invalidSampleRate" ) @@ -59,7 +63,7 @@ final class PollyErrorMappingTestCase: XCTestCase { func testSynthesizeSpeech_languageNotSupportedException() throws { assertCatchVariations( - for: .languageNotSupportedException(.init()), + for: LanguageNotSupportedException(), expecting: .unsupportedLanguage, label: "unsupportedLanguage" ) @@ -67,7 +71,7 @@ final class PollyErrorMappingTestCase: XCTestCase { func testSynthesizeSpeech_serviceFailureException() throws { assertCatchVariations( - for: .serviceFailureException(.init()), + for: ServiceFailureException(), expecting: .internalServerError, label: "internalServerError" ) @@ -75,7 +79,7 @@ final class PollyErrorMappingTestCase: XCTestCase { func testSynthesizeSpeech_textLengthExceededException() throws { assertCatchVariations( - for: .textLengthExceededException(.init()), + for: TextLengthExceededException(), expecting: .textSizeLimitExceeded, label: "textSizeLimitExceeded" ) diff --git a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/TextractErrorMappingTestCase.swift b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/TextractErrorMappingTestCase.swift index bafe9a75ce..526b3d37ae 100644 --- a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/TextractErrorMappingTestCase.swift +++ b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ErrorMapping/TextractErrorMappingTestCase.swift @@ -12,37 +12,40 @@ import Amplify final class TextractErrorMappingTestCase: XCTestCase { private func assertCatchVariations( - for sdkError: AnalyzeDocumentOutputError, + for sdkError: Error, expecting expectedServiceError: PredictionsError.ServiceError, label: String ) { - let predictionsError = ServiceErrorMapping.analyzeDocument.map(sdkError) let unexpected: (Error) -> String = { "Expected PredictionsError.service(.\(label), received \($0)" } // catch variation 1. - do { throw predictionsError } - catch PredictionsError.service(expectedServiceError) {} + do { throw sdkError } + catch let error as PredictionsErrorConvertible { + guard case .service(expectedServiceError) = error.predictionsError else { + return XCTFail(unexpected(error.predictionsError)) + } + } catch { XCTFail(unexpected(error)) } // catch variation 2. - do { throw predictionsError } - catch let error as PredictionsError { - guard case .service(expectedServiceError) = error else { - return XCTFail(unexpected(error)) + do { throw sdkError } + catch let error as PredictionsErrorConvertible { + guard case .service(expectedServiceError) = error.predictionsError else { + return XCTFail(unexpected(error.predictionsError)) } } catch { XCTFail(unexpected(error)) } // catch variation 3. - do { throw predictionsError } + do { throw sdkError } catch { - guard let error = error as? PredictionsError, - case .service(expectedServiceError) = error + guard let error = error as? PredictionsErrorConvertible, + case .service(expectedServiceError) = error.predictionsError else { return XCTFail(unexpected(error)) } @@ -51,7 +54,7 @@ final class TextractErrorMappingTestCase: XCTestCase { func testAnalyzeDocument_internalServerError() throws { assertCatchVariations( - for: .internalServerError(.init()), + for: InternalServerError(), expecting: .internalServerError, label: "internalServerError" ) @@ -59,7 +62,7 @@ final class TextractErrorMappingTestCase: XCTestCase { func testAnalyzeDocument_accessDeniedException() throws { assertCatchVariations( - for: .accessDeniedException(.init()), + for: AccessDeniedException(), expecting: .accessDenied, label: "accessDenied" ) @@ -67,7 +70,7 @@ final class TextractErrorMappingTestCase: XCTestCase { func testAnalyzeDocument_throttlingException() throws { assertCatchVariations( - for: .throttlingException(.init()), + for: ThrottlingException(), expecting: .throttling, label: "throttling" ) diff --git a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockRekognitionBehavior.swift b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockRekognitionBehavior.swift index 9dcd814c82..ffcb4cdfb7 100644 --- a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockRekognitionBehavior.swift +++ b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockRekognitionBehavior.swift @@ -112,4 +112,13 @@ extension MockRekognitionBehavior { func untagResource(input: AWSRekognition.UntagResourceInput) async throws -> AWSRekognition.UntagResourceOutputResponse { fatalError() } func updateDatasetEntries(input: AWSRekognition.UpdateDatasetEntriesInput) async throws -> AWSRekognition.UpdateDatasetEntriesOutputResponse { fatalError() } func updateStreamProcessor(input: AWSRekognition.UpdateStreamProcessorInput) async throws -> AWSRekognition.UpdateStreamProcessorOutputResponse { fatalError() } + func associateFaces(input: AWSRekognition.AssociateFacesInput) async throws -> AWSRekognition.AssociateFacesOutputResponse { fatalError() } + func createFaceLivenessSession(input: AWSRekognition.CreateFaceLivenessSessionInput) async throws -> AWSRekognition.CreateFaceLivenessSessionOutputResponse { fatalError() } + func createUser(input: AWSRekognition.CreateUserInput) async throws -> AWSRekognition.CreateUserOutputResponse { fatalError() } + func deleteUser(input: AWSRekognition.DeleteUserInput) async throws -> AWSRekognition.DeleteUserOutputResponse { fatalError() } + func disassociateFaces(input: AWSRekognition.DisassociateFacesInput) async throws -> AWSRekognition.DisassociateFacesOutputResponse { fatalError() } + func getFaceLivenessSessionResults(input: AWSRekognition.GetFaceLivenessSessionResultsInput) async throws -> AWSRekognition.GetFaceLivenessSessionResultsOutputResponse { fatalError() } + func listUsers(input: AWSRekognition.ListUsersInput) async throws -> AWSRekognition.ListUsersOutputResponse { fatalError() } + func searchUsers(input: AWSRekognition.SearchUsersInput) async throws -> AWSRekognition.SearchUsersOutputResponse { fatalError() } + func searchUsersByImage(input: AWSRekognition.SearchUsersByImageInput) async throws -> AWSRekognition.SearchUsersByImageOutputResponse { fatalError() } } diff --git a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockTranslateBehavior.swift b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockTranslateBehavior.swift index 5a1b1e86c2..ec91544aaa 100644 --- a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockTranslateBehavior.swift +++ b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/Mocks/Service/MockTranslateBehavior.swift @@ -41,4 +41,5 @@ extension MockTranslateBehavior { func tagResource(input: AWSTranslate.TagResourceInput) async throws -> AWSTranslate.TagResourceOutputResponse { fatalError() } func untagResource(input: AWSTranslate.UntagResourceInput) async throws -> AWSTranslate.UntagResourceOutputResponse { fatalError() } func updateParallelData(input: AWSTranslate.UpdateParallelDataInput) async throws -> AWSTranslate.UpdateParallelDataOutputResponse { fatalError() } + func translateDocument(input: AWSTranslate.TranslateDocumentInput) async throws -> AWSTranslate.TranslateDocumentOutputResponse { fatalError() } } From f9ab142300cf7d4266a8736af76c139e76a68008 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 2 Oct 2023 16:16:34 -0400 Subject: [PATCH 10/23] fix(push-notifications): error handling (#3262) --- ...or+PushNotificationsErrorConvertible.swift | 23 +++++ ...nt+PushNotificationsErrorConvertible.swift | 97 +++++++++++++++++++ .../PushNotificationsErrorConvertible.swift | 13 +++ .../Extensions/Error+PushNotifications.swift | 75 ++++---------- 4 files changed, 154 insertions(+), 54 deletions(-) create mode 100644 AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/CommonRunTimeError+PushNotificationsErrorConvertible.swift create mode 100644 AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/Pinpoint+PushNotificationsErrorConvertible.swift create mode 100644 AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/PushNotificationsErrorConvertible.swift diff --git a/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/CommonRunTimeError+PushNotificationsErrorConvertible.swift b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/CommonRunTimeError+PushNotificationsErrorConvertible.swift new file mode 100644 index 0000000000..c74f540617 --- /dev/null +++ b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/CommonRunTimeError+PushNotificationsErrorConvertible.swift @@ -0,0 +1,23 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AwsCommonRuntimeKit +@_spi(InternalAWSPinpoint) import InternalAWSPinpoint + +extension CommonRunTimeError: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + switch self { + case .crtError(let crtError): + let errorDescription = isConnectivityError + ? AWSPinpointErrorConstants.deviceOffline.errorDescription + : crtError.message + return .unknown(errorDescription, self) + } + } +} diff --git a/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/Pinpoint+PushNotificationsErrorConvertible.swift b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/Pinpoint+PushNotificationsErrorConvertible.swift new file mode 100644 index 0000000000..9c3aaf2749 --- /dev/null +++ b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/Pinpoint+PushNotificationsErrorConvertible.swift @@ -0,0 +1,97 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AWSPinpoint +import ClientRuntime +import AWSClientRuntime + +private func recoverySuggestion(for error: ClientRuntime.ModeledError) -> String { + type(of: error).isRetryable + ? PushNotificationsPluginErrorConstants.retryableServiceError.recoverySuggestion + : PushNotificationsPluginErrorConstants.nonRetryableServiceError.recoverySuggestion +} + +extension AWSPinpoint.BadRequestException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSPinpoint.ForbiddenException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSPinpoint.InternalServerErrorException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSPinpoint.MethodNotAllowedException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSPinpoint.NotFoundException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSPinpoint.PayloadTooLargeException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSPinpoint.TooManyRequestsException: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .service( + properties.message ?? "", + recoverySuggestion(for: self), + self + ) + } +} + +extension AWSClientRuntime.UnknownAWSHTTPServiceError: PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { + .unknown( + message ?? "An unknown error has occurred.", + self + ) + } +} diff --git a/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/PushNotificationsErrorConvertible.swift b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/PushNotificationsErrorConvertible.swift new file mode 100644 index 0000000000..3043828e1b --- /dev/null +++ b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Error/PushNotificationsErrorConvertible.swift @@ -0,0 +1,13 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify + +protocol PushNotificationsErrorConvertible { + var pushNotificationsError: PushNotificationsError { get } +} diff --git a/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Extensions/Error+PushNotifications.swift b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Extensions/Error+PushNotifications.swift index 9694ece00a..f18f092489 100644 --- a/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Extensions/Error+PushNotifications.swift +++ b/AmplifyPlugins/Notifications/Push/Sources/AWSPinpointPushNotificationsPlugin/Extensions/Error+PushNotifications.swift @@ -13,60 +13,27 @@ import Foundation extension Error { var pushNotificationsError: PushNotificationsError { - if let sdkError = self as? SdkError { - return sdkError.pushNotificationsError + switch self { + case let error as PushNotificationsErrorConvertible: + return error.pushNotificationsError + default: + let networkErrorCodes = [ + NSURLErrorCannotFindHost, + NSURLErrorCannotConnectToHost, + NSURLErrorNetworkConnectionLost, + NSURLErrorDNSLookupFailed, + NSURLErrorNotConnectedToInternet + ] + + if networkErrorCodes.contains(where: { $0 == (self as NSError).code }) { + return .network( + PushNotificationsPluginErrorConstants.deviceOffline.errorDescription, + PushNotificationsPluginErrorConstants.deviceOffline.recoverySuggestion, + self + ) + } + + return PushNotificationsError(error: self) } - - if let sdkError = self as? SdkError { - return sdkError.pushNotificationsError - } - - if let clientError = self as? ClientError, - case .networkError(_) = clientError { - return .network( - PushNotificationsPluginErrorConstants.deviceOffline.errorDescription, - PushNotificationsPluginErrorConstants.deviceOffline.recoverySuggestion, - clientError - ) - } - - let networkErrorCodes = [ - NSURLErrorCannotFindHost, - NSURLErrorCannotConnectToHost, - NSURLErrorNetworkConnectionLost, - NSURLErrorDNSLookupFailed, - NSURLErrorNotConnectedToInternet - ] - if networkErrorCodes.contains(where: { $0 == (self as NSError).code }) { - return .network( - PushNotificationsPluginErrorConstants.deviceOffline.errorDescription, - PushNotificationsPluginErrorConstants.deviceOffline.recoverySuggestion, - self - ) - } - - return PushNotificationsError(error: self) - } -} - -extension SdkError { - var pushNotificationsError: PushNotificationsError { - if isConnectivityError { - return .network( - PushNotificationsPluginErrorConstants.deviceOffline.errorDescription, - PushNotificationsPluginErrorConstants.deviceOffline.recoverySuggestion, - rootError ?? self - ) - } - - let recoverySuggestion = isRetryable ? - PushNotificationsPluginErrorConstants.retryableServiceError.recoverySuggestion : - PushNotificationsPluginErrorConstants.nonRetryableServiceError.recoverySuggestion - - return .service( - errorDescription, - recoverySuggestion, - rootError ?? self - ) } } From a2e878ce07fa1adbb79478a06946d766b5537d9e Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 2 Oct 2023 16:16:46 -0400 Subject: [PATCH 11/23] fix(analytics): update error handling (#3261) --- .../Extensions/SdkError+Analytics.swift | 20 --- ...WSPinpoint+AnalyticsErrorConvertible.swift | 53 ++++++++ .../Utils/AnalyticsErrorConvertible.swift | 19 +++ .../Support/Utils/AnalyticsErrorHelper.swift | 20 ++- ...nTimeError+AnalyticsErrorConvertible.swift | 23 ++++ .../Analytics/ClientError+IsRetryable.swift | 29 ++++ .../Analytics/EventRecorder.swift | 35 ++--- .../Analytics/SdkError+IsRetryable.swift | 74 ----------- .../Context/PinpointContext.swift | 4 +- ...mmonRunTimeError+isConnectivityError.swift | 41 ++++++ .../PinpointClient+CredentialsProvider.swift | 8 +- .../Extensions/SdkError+Pinpoint.swift | 124 ------------------ .../Support/ModeledErrorDescribable.swift | 42 ++++++ .../Utils/PinpointRequestsRegistry.swift | 6 +- 14 files changed, 238 insertions(+), 260 deletions(-) delete mode 100644 AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/SdkError+Analytics.swift create mode 100644 AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift create mode 100644 AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift create mode 100644 AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift create mode 100644 AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/ClientError+IsRetryable.swift delete mode 100644 AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/SdkError+IsRetryable.swift create mode 100644 AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift delete mode 100644 AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/SdkError+Pinpoint.swift create mode 100644 AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/ModeledErrorDescribable.swift diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/SdkError+Analytics.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/SdkError+Analytics.swift deleted file mode 100644 index 34725ba1c5..0000000000 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Extensions/SdkError+Analytics.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import ClientRuntime -import Foundation -@_spi(InternalAWSPinpoint) import InternalAWSPinpoint - -extension SdkError { - var analyticsError: AnalyticsError { - return .unknown( - isConnectivityError ? AWSPinpointErrorConstants.deviceOffline.errorDescription : errorDescription, - rootError ?? self - ) - } -} diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift new file mode 100644 index 0000000000..42c5464f9e --- /dev/null +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AWSPinpoint+AnalyticsErrorConvertible.swift @@ -0,0 +1,53 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AWSPinpoint +import ClientRuntime + +extension AWSPinpoint.BadRequestException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} + +extension AWSPinpoint.ForbiddenException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} + +extension AWSPinpoint.InternalServerErrorException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} + +extension AWSPinpoint.MethodNotAllowedException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} + +extension AWSPinpoint.NotFoundException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} + +extension AWSPinpoint.PayloadTooLargeException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} + +extension AWSPinpoint.TooManyRequestsException: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + .unknown(properties.message ?? "", self) + } +} diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift new file mode 100644 index 0000000000..e21c889309 --- /dev/null +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorConvertible.swift @@ -0,0 +1,19 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify + +protocol AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { get } +} + +extension AnalyticsError: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + self + } +} diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift index 28af56447f..684289ca1b 100644 --- a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/AnalyticsErrorHelper.swift @@ -5,22 +5,18 @@ // SPDX-License-Identifier: Apache-2.0 // -import Amplify -import AWSPinpoint -import ClientRuntime import Foundation +import Amplify +import AwsCommonRuntimeKit -class AnalyticsErrorHelper { +enum AnalyticsErrorHelper { static func getDefaultError(_ error: Error) -> AnalyticsError { - if let sdkError = error as? SdkError{ - return sdkError.analyticsError + switch error { + case let error as AnalyticsErrorConvertible: + return error.analyticsError + default: + return getDefaultError(error as NSError) } - - if let analyticsError = error as? AnalyticsError { - return analyticsError - } - - return getDefaultError(error as NSError) } static func getDefaultError(_ error: NSError) -> AnalyticsError { diff --git a/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift new file mode 100644 index 0000000000..b65918f472 --- /dev/null +++ b/AmplifyPlugins/Analytics/Sources/AWSPinpointAnalyticsPlugin/Support/Utils/CommonRunTimeError+AnalyticsErrorConvertible.swift @@ -0,0 +1,23 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +@_spi(InternalAWSPinpoint) import InternalAWSPinpoint +import AwsCommonRuntimeKit + +extension CommonRunTimeError: AnalyticsErrorConvertible { + var analyticsError: AnalyticsError { + switch self { + case .crtError(let crtError): + let errorDescription = isConnectivityError + ? AWSPinpointErrorConstants.deviceOffline.errorDescription + : crtError.message + return .unknown(errorDescription, self) + } + } +} diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/ClientError+IsRetryable.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/ClientError+IsRetryable.swift new file mode 100644 index 0000000000..77f1cb2c5e --- /dev/null +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/ClientError+IsRetryable.swift @@ -0,0 +1,29 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import ClientRuntime +import Foundation + +extension ClientError { + // TODO: Should some of these really be retried? + var isRetryable: Bool { + switch self { + case .authError: + return true + case .dataNotFound: + return true + case .pathCreationFailed: + return true + case .queryItemCreationFailed: + return true + case .serializationFailed: + return false + case .unknownError: + return true + } + } +} diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift index 39397cb0e5..5c2675cdbe 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/EventRecorder.swift @@ -8,6 +8,7 @@ import Amplify import AWSPinpoint import ClientRuntime +import enum AwsCommonRuntimeKit.CommonRunTimeError import Foundation /// AnalyticsEventRecording saves and submits pinpoint events @@ -206,26 +207,21 @@ class EventRecorder: AnalyticsEventRecording { } private func isErrorRetryable(_ error: Error) -> Bool { - switch error { - case let clientError as ClientError: - return clientError.isRetryable - case let putEventsOutputError as PutEventsOutputError: - return putEventsOutputError.isRetryable - case let sdkPutEventsOutputError as SdkError: - return sdkPutEventsOutputError.isRetryable - case let sdkError as SdkError: - return sdkError.isRetryable - default: + guard case let modeledError as ModeledError = error else { return false } + return type(of: modeledError).isRetryable } private func errorDescription(_ error: Error) -> String { switch error { - case let sdkPutEventsOutputError as SdkError: - return sdkPutEventsOutputError.errorDescription - case let sdkError as SdkError: - return sdkError.errorDescription + case let error as ModeledErrorDescribable: + return error.errorDescription + case let error as CommonRunTimeError: + switch error { + case .crtError(let crtError): + return crtError.message + } default: return error.localizedDescription } @@ -233,15 +229,8 @@ class EventRecorder: AnalyticsEventRecording { private func isConnectivityError(_ error: Error) -> Bool { switch error { - case let clientError as ClientError: - if case .networkError(_) = clientError { - return true - } - return false - case let sdkPutEventsOutputError as SdkError: - return sdkPutEventsOutputError.isConnectivityError - case let sdkError as SdkError: - return sdkError.isConnectivityError + case let error as CommonRunTimeError: + return error.isConnectivityError case let error as NSError: let networkErrorCodes = [ NSURLErrorCannotFindHost, diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/SdkError+IsRetryable.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/SdkError+IsRetryable.swift deleted file mode 100644 index 5db7bde825..0000000000 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Analytics/SdkError+IsRetryable.swift +++ /dev/null @@ -1,74 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import AWSPinpoint -import ClientRuntime -import Foundation - -@_spi(InternalAWSPinpoint) -public extension SdkError { - var isRetryable: Bool { - switch self { - case .service(let error, _): - return (error as? PutEventsOutputError)?.isRetryable == true - case .client(let error, _): - return error.isRetryable - default: - return true - } - } -} - -extension ClientError { - var isRetryable: Bool { - switch self { - case .authError: - return true - case .crtError: - return true - case .dataNotFound: - return true - case .deserializationFailed: - return false - case .networkError: - return true - case .pathCreationFailed: - return true - case .queryItemCreationFailed(_): - return true - case .retryError: - return true - case .serializationFailed: - return false - case .unknownError: - return true - } - } -} - -extension PutEventsOutputError { - var isRetryable: Bool { - switch self { - case .badRequestException(let exception): - return exception._retryable - case .forbiddenException(let exception): - return exception._retryable - case .internalServerErrorException(let exception): - return exception._retryable - case .methodNotAllowedException(let exception): - return exception._retryable - case .notFoundException(let exception): - return exception._retryable - case .payloadTooLargeException(let exception): - return exception._retryable - case .tooManyRequestsException(let exception): - return exception._retryable - case .unknown(let exception): - return exception._retryable - } - } -} diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift index b64742422f..70303f278e 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Context/PinpointContext.swift @@ -76,14 +76,14 @@ struct PinpointContextConfiguration { /// The Pinpoint region let region: String /// Used to retrieve the proper AWSCredentials when creating the PinpointCLient - let credentialsProvider: CredentialsProvider + let credentialsProvider: CredentialsProviding /// Indicates if the App is in Debug or Release build. Defaults to `false` /// Setting this flag to true will set the Endpoint Profile to have a channel type of "APNS_SANDBOX". let isDebug: Bool init(appId: String, region: String, - credentialsProvider: CredentialsProvider, + credentialsProvider: CredentialsProviding, isDebug: Bool = false) { self.appId = appId self.region = region diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift new file mode 100644 index 0000000000..a0555c2da5 --- /dev/null +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift @@ -0,0 +1,41 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Amplify +import AwsCIo +import AwsCHttp +import AwsCommonRuntimeKit +import AWSPinpoint +import ClientRuntime +import Foundation + +@_spi(InternalAWSPinpoint) +extension CommonRunTimeError { + static let connectivityErrorCodes: Set = [ + AWS_ERROR_HTTP_CONNECTION_CLOSED.rawValue, + AWS_ERROR_HTTP_SERVER_CLOSED.rawValue, + AWS_IO_DNS_INVALID_NAME.rawValue, + AWS_IO_DNS_NO_ADDRESS_FOR_HOST.rawValue, + AWS_IO_DNS_QUERY_FAILED.rawValue, + AWS_IO_SOCKET_CONNECT_ABORTED.rawValue, + AWS_IO_SOCKET_CONNECTION_REFUSED.rawValue, + AWS_IO_SOCKET_CLOSED.rawValue, + AWS_IO_SOCKET_NETWORK_DOWN.rawValue, + AWS_IO_SOCKET_NO_ROUTE_TO_HOST.rawValue, + AWS_IO_SOCKET_NOT_CONNECTED.rawValue, + AWS_IO_SOCKET_TIMEOUT.rawValue, + AWS_IO_TLS_NEGOTIATION_TIMEOUT.rawValue, + UInt32(AWS_HTTP_STATUS_CODE_408_REQUEST_TIMEOUT.rawValue) + ] + + public var isConnectivityError: Bool { + switch self { + case .crtError(let error): + Self.connectivityErrorCodes.contains(UInt32(error.code)) + } + } +} diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift index 447d092b61..2a2e1a30f9 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift @@ -11,11 +11,11 @@ import AWSPinpoint @_spi(FoundationClientEngine) import AWSPluginsCore extension PinpointClient { - convenience init(region: String, credentialsProvider: CredentialsProvider) throws { + convenience init(region: String, credentialsProvider: CredentialsProviding) throws { + // TODO: FrameworkMetadata Replacement let configuration = try PinpointClientConfiguration( - credentialsProvider: credentialsProvider, - frameworkMetadata: AmplifyAWSServiceConfiguration.frameworkMetaData(), - region: region + region: region, + credentialsProvider: credentialsProvider ) #if os(iOS) || os(macOS) // no-op #else diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/SdkError+Pinpoint.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/SdkError+Pinpoint.swift deleted file mode 100644 index a24a602cff..0000000000 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/SdkError+Pinpoint.swift +++ /dev/null @@ -1,124 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import Amplify -import AwsCIo -import AwsCHttp -import AwsCommonRuntimeKit -import AWSPinpoint -import ClientRuntime -import Foundation - -@_spi(InternalAWSPinpoint) -extension SdkError { - private var clientError: ClientError? { - guard case .client(let clientError, _) = self else { - return nil - } - - return clientError - } - - private var commonRunTimeError: CommonRunTimeError? { - if case .crtError(let commonRunTimeError) = clientError { - return commonRunTimeError - } - - if case .retryError(let commonRunTimeError as CommonRunTimeError) = clientError { - return commonRunTimeError - } - - return nil - } - - private var crtError: CRTError? { - if case .crtError(let crtError) = commonRunTimeError { - return crtError - } - - return nil - } - - private var putEventsOutputError: PutEventsOutputError? { - guard case .retryError(let sdkError as SdkError) = clientError, - case .service(let putEventsError as PutEventsOutputError, _) = sdkError else { - return nil - } - - return putEventsError - } - - public var errorDescription: String { - guard let putEventsOutputError = putEventsOutputError else { - return crtError?.message ?? localizedDescription - } - - switch putEventsOutputError { - case .badRequestException(let exception as ServiceError), - .forbiddenException(let exception as ServiceError), - .internalServerErrorException(let exception as ServiceError), - .methodNotAllowedException(let exception as ServiceError), - .notFoundException(let exception as ServiceError), - .payloadTooLargeException(let exception as ServiceError), - .tooManyRequestsException(let exception as ServiceError), - .unknown(let exception as ServiceError): - return exception._message ?? localizedDescription - } - } - - public var rootError: Error? { - if putEventsOutputError != nil { - return putEventsOutputError - } - - if commonRunTimeError != nil { - return commonRunTimeError - } - - guard let clientError = clientError else { - return nil - } - - switch clientError { - case .networkError(let error), - .deserializationFailed(let error), - .retryError(let error): - return error - default: - return nil - } - } - - public var isConnectivityError: Bool { - if case .networkError(_) = clientError { - return true - } - - guard let crtError = crtError else { - return false - } - - let connectivityErrorCodes: [UInt32] = [ - AWS_ERROR_HTTP_CONNECTION_CLOSED.rawValue, - AWS_ERROR_HTTP_SERVER_CLOSED.rawValue, - AWS_IO_DNS_INVALID_NAME.rawValue, - AWS_IO_DNS_NO_ADDRESS_FOR_HOST.rawValue, - AWS_IO_DNS_QUERY_FAILED.rawValue, - AWS_IO_SOCKET_CONNECT_ABORTED.rawValue, - AWS_IO_SOCKET_CONNECTION_REFUSED.rawValue, - AWS_IO_SOCKET_CLOSED.rawValue, - AWS_IO_SOCKET_NETWORK_DOWN.rawValue, - AWS_IO_SOCKET_NO_ROUTE_TO_HOST.rawValue, - AWS_IO_SOCKET_NOT_CONNECTED.rawValue, - AWS_IO_SOCKET_TIMEOUT.rawValue, - AWS_IO_TLS_NEGOTIATION_TIMEOUT.rawValue, - UInt32(AWS_HTTP_STATUS_CODE_408_REQUEST_TIMEOUT.rawValue) - ] - - return connectivityErrorCodes.contains(where: { $0 == crtError.code }) - } -} diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/ModeledErrorDescribable.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/ModeledErrorDescribable.swift new file mode 100644 index 0000000000..60608de459 --- /dev/null +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/ModeledErrorDescribable.swift @@ -0,0 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AWSPinpoint + +protocol ModeledErrorDescribable { + var errorDescription: String { get } +} + +extension AWSPinpoint.BadRequestException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} + +extension AWSPinpoint.ForbiddenException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} + +extension AWSPinpoint.InternalServerErrorException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} + +extension AWSPinpoint.MethodNotAllowedException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} + +extension AWSPinpoint.NotFoundException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} + +extension AWSPinpoint.PayloadTooLargeException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} + +extension AWSPinpoint.TooManyRequestsException: ModeledErrorDescribable { + var errorDescription: String { properties.message ?? "" } +} diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift index 7bcd61a0a5..d28826561e 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift @@ -70,7 +70,11 @@ private struct CustomPinpointHttpClientEngine: HttpClientEngine { let currentUserAgent = headers.value(for: userAgentHeader) ?? "" headers.update(name: userAgentHeader, value: "\(currentUserAgent)\(userAgentSuffix)") - request.headers = headers + for header in headers.headers { + for value in header.value { + request.withHeader(name: header.name, value: value) + } + } await PinpointRequestsRegistry.shared.unregisterSources(for: pinpointApi) return try await httpClientEngine.execute(request: request) From 3ad5911008ca1ed39e25b39ad0dee44c198590ce Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 2 Oct 2023 17:04:47 -0400 Subject: [PATCH 12/23] fix(analytics): user-agent patch (#3264) --- .../Support/Utils/PinpointRequestsRegistry.swift | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift index d28826561e..d104e1a1af 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift @@ -66,15 +66,11 @@ private struct CustomPinpointHttpClientEngine: HttpClientEngine { return try await httpClientEngine.execute(request: request) } - var headers = request.headers let currentUserAgent = headers.value(for: userAgentHeader) ?? "" - headers.update(name: userAgentHeader, - value: "\(currentUserAgent)\(userAgentSuffix)") - for header in headers.headers { - for value in header.value { - request.withHeader(name: header.name, value: value) - } - } + request.withHeader( + name: userAgentHeader, + value: "\(currentUserAgent)\(userAgentSuffix)" + ) await PinpointRequestsRegistry.shared.unregisterSources(for: pinpointApi) return try await httpClientEngine.execute(request: request) From bacddcb978b3af4239bfebdfd566fa10ad6265f2 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Tue, 3 Oct 2023 09:15:46 -0400 Subject: [PATCH 13/23] fix(analytics): add missing headers prop (#3267) --- .../Support/Utils/PinpointRequestsRegistry.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift index d104e1a1af..9b7d27b1da 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift @@ -66,6 +66,7 @@ private struct CustomPinpointHttpClientEngine: HttpClientEngine { return try await httpClientEngine.execute(request: request) } + let headers = request.headers let currentUserAgent = headers.value(for: userAgentHeader) ?? "" request.withHeader( name: userAgentHeader, From 3735f80656c73eb5f916984fb598df2d490a3f6c Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Tue, 3 Oct 2023 10:51:44 -0400 Subject: [PATCH 14/23] fix(analytics): add explicit return cause 5.7 (#3268) --- .../Extensions/CommonRunTimeError+isConnectivityError.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift index a0555c2da5..c3a3c3dd20 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/CommonRunTimeError+isConnectivityError.swift @@ -35,7 +35,9 @@ extension CommonRunTimeError { public var isConnectivityError: Bool { switch self { case .crtError(let error): - Self.connectivityErrorCodes.contains(UInt32(error.code)) + return Self.connectivityErrorCodes.contains( + UInt32(error.code) + ) } } } From d898ea3c575ca0ac1cff45e0180a34354a57534c Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Wed, 4 Oct 2023 16:04:08 -0400 Subject: [PATCH 15/23] fix(internal-pinpoint-tests): update tests for new sdk version (#3275) --- .../Mocks/MockEndpointClient.swift | 2 +- .../Mocks/MockPinpointClient.swift | 12 +++++ .../PinpointRequestsRegistryTests.swift | 44 ++++--------------- 3 files changed, 21 insertions(+), 37 deletions(-) diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockEndpointClient.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockEndpointClient.swift index bac6c68b15..4af9110ff9 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockEndpointClient.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockEndpointClient.swift @@ -13,7 +13,7 @@ import Foundation actor MockEndpointClient: EndpointClientBehaviour { let pinpointClient: PinpointClientProtocol = MockPinpointClient() - class MockCredentialsProvider: CredentialsProvider { + class MockCredentialsProvider: CredentialsProviding { func getCredentials() async throws -> AWSCredentials { return AWSCredentials(accessKey: "", secret: "", expirationTimeout: Date().addingTimeInterval(1000)) } diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockPinpointClient.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockPinpointClient.swift index 605c4031b8..9abb1ccb88 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockPinpointClient.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/Mocks/MockPinpointClient.swift @@ -9,6 +9,18 @@ import AWSPinpoint import Foundation class MockPinpointClient: PinpointClientProtocol { + func getJourneyRunExecutionActivityMetrics(input: GetJourneyRunExecutionActivityMetricsInput) async throws -> GetJourneyRunExecutionActivityMetricsOutputResponse { + fatalError("Not supported") + } + + func getJourneyRunExecutionMetrics(input: GetJourneyRunExecutionMetricsInput) async throws -> GetJourneyRunExecutionMetricsOutputResponse { + fatalError("Not supported") + } + + func getJourneyRuns(input: GetJourneyRunsInput) async throws -> GetJourneyRunsOutputResponse { + fatalError("Not supported") + } + func createApp(input: CreateAppInput) async throws -> CreateAppOutputResponse { fatalError("Not supported") } diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift index 9a7bd28978..d028cf9dff 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift @@ -72,13 +72,14 @@ class PinpointRequestsRegistryTests: XCTestCase { private func createSdkRequest(for api: PinpointRequestsRegistry.API?) throws -> SdkHttpRequest { let apiPath = api?.rawValue ?? "otherApi" - let endpoint = try Endpoint(urlString: "https://host:42/path/\(apiPath)/suffix") - let headers = [ - "User-Agent": "mocked_user_agent" - ] - return SdkHttpRequest(method: .put, - endpoint: endpoint, - headers: .init(headers)) + let endpoint = try Endpoint( + urlString: "https://host:42/path/\(apiPath)/suffix", + headers: .init(["User-Agent": "mocked_user_agent"]) + ) + return SdkHttpRequest( + method: .put, + endpoint: endpoint + ) } } @@ -88,35 +89,6 @@ private extension HttpClientEngine { } } -private class MockSDKRuntimeConfiguration: SDKRuntimeConfiguration { - var encoder: ClientRuntime.RequestEncoder? - var decoder: ClientRuntime.ResponseDecoder? - var httpClientConfiguration: ClientRuntime.HttpClientConfiguration - var idempotencyTokenGenerator: ClientRuntime.IdempotencyTokenGenerator - var clientLogMode: ClientRuntime.ClientLogMode - var partitionID: String? - - let logger: LogAgent - let retryer: SDKRetryer - var endpoint: String? = nil - private let mockedHttpClientEngine : HttpClientEngine - - init(httpClientEngine: HttpClientEngine) throws { - let defaultSDKRuntimeConfig = try DefaultSDKRuntimeConfiguration("MockSDKRuntimeConfiguration") - httpClientConfiguration = defaultSDKRuntimeConfig.httpClientConfiguration - idempotencyTokenGenerator = defaultSDKRuntimeConfig.idempotencyTokenGenerator - clientLogMode = defaultSDKRuntimeConfig.clientLogMode - - logger = MockLogAgent() - retryer = try SDKRetryer(options: RetryOptions(jitterMode: .default)) - mockedHttpClientEngine = httpClientEngine - } - - var httpClientEngine: HttpClientEngine { - mockedHttpClientEngine - } -} - private class MockHttpClientEngine: HttpClientEngine { var executeCount = 0 func execute(request: SdkHttpRequest) async throws -> HttpResponse { From 0e2d7609002f47918adb8d4ecdcd2654a3878cd6 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Wed, 4 Oct 2023 16:10:44 -0400 Subject: [PATCH 16/23] fix(core): add user-agent client engine (#3274) --- .../APIKeyURLRequestInterceptor.swift | 2 +- .../AuthTokenURLRequestInterceptor.swift | 2 +- .../IAMURLRequestInterceptor.swift | 2 +- .../AWSGraphQLSubscriptionTaskRunner.swift | 6 +- .../AWSCognitoAuthPlugin+Configure.swift | 35 ++---- .../AmplifyAWSServiceConfiguration.swift | 87 +------------- .../PluginClientEngine.swift | 26 ++++ .../SdkHttpRequest+updatingUserAgent.swift | 35 ++++++ .../UserAgentSettingClientEngine.swift | 47 ++++++++ .../UserAgentSuffixAppender.swift | 7 +- .../AmplifyAWSServiceConfigurationTests.swift | 51 -------- .../UserAgentSettingClientEngineTests.swift | 111 ++++++++++++++++++ .../Utils/UserAgentSuffixAppenderTests.swift | 8 +- .../AWSLocationGeoPlugin+Configure.swift | 9 +- .../PinpointClient+CredentialsProvider.swift | 10 +- .../Utils/PinpointRequestsRegistry.swift | 12 +- ...WSCloudWatchLoggingSessionController.swift | 9 +- .../Predictions/AWSPredictionsService.swift | 49 +++----- .../Service/Storage/AWSS3StorageService.swift | 28 ++--- 19 files changed, 283 insertions(+), 253 deletions(-) create mode 100644 AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift create mode 100644 AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift create mode 100644 AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSettingClientEngine.swift delete mode 100644 AmplifyPlugins/Core/AWSPluginsCoreTests/ServiceConfiguration/AmplifyAWSServiceConfigurationTests.swift create mode 100644 AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSettingClientEngineTests.swift diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift index 7ace300b74..e737479d9c 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/APIKeyURLRequestInterceptor.swift @@ -11,7 +11,7 @@ import Foundation struct APIKeyURLRequestInterceptor: URLRequestInterceptor { - private let userAgent = AmplifyAWSServiceConfiguration.frameworkMetaData().description + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib let apiKeyProvider: APIKeyProvider init(apiKeyProvider: APIKeyProvider) { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift index d7392748e8..2d639afca4 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/AuthTokenURLRequestInterceptor.swift @@ -13,7 +13,7 @@ struct AuthTokenURLRequestInterceptor: URLRequestInterceptor { static let AWSDateISO8601DateFormat2 = "yyyyMMdd'T'HHmmss'Z'" - private let userAgent = AmplifyAWSServiceConfiguration.frameworkMetaData().description + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib let authTokenProvider: AuthTokenProvider init(authTokenProvider: AuthTokenProvider) { diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift index 28ef8b9ce9..4ad5159992 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/RequestInterceptor/IAMURLRequestInterceptor.swift @@ -16,7 +16,7 @@ struct IAMURLRequestInterceptor: URLRequestInterceptor { let iamCredentialsProvider: IAMCredentialsProvider let region: AWSRegionType let endpointType: AWSAPICategoryPluginEndpointType - private let userAgent = AmplifyAWSServiceConfiguration.frameworkMetaData().description + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib init(iamCredentialsProvider: IAMCredentialsProvider, region: AWSRegionType, diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift index d0225d095e..a9bf16eee9 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Operation/AWSGraphQLSubscriptionTaskRunner.swift @@ -21,8 +21,8 @@ public class AWSGraphQLSubscriptionTaskRunner: InternalTaskRunner, let subscriptionConnectionFactory: SubscriptionConnectionFactory let authService: AWSAuthServiceBehavior var apiAuthProviderFactory: APIAuthProviderFactory - private let userAgent = AmplifyAWSServiceConfiguration.frameworkMetaData().description - + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib + var subscriptionConnection: SubscriptionConnection? var subscriptionItem: SubscriptionItem? private var running = false @@ -203,7 +203,7 @@ final public class AWSGraphQLSubscriptionOperation: GraphQLSubscri let pluginConfig: AWSAPICategoryPluginConfiguration let subscriptionConnectionFactory: SubscriptionConnectionFactory let authService: AWSAuthServiceBehavior - private let userAgent = AmplifyAWSServiceConfiguration.frameworkMetaData().description + private let userAgent = AmplifyAWSServiceConfiguration.userAgentLib var subscriptionConnection: SubscriptionConnection? var subscriptionItem: SubscriptionItem? diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift index ab44a86fc8..2fb118bdfa 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/AWSCognitoAuthPlugin+Configure.swift @@ -12,7 +12,9 @@ import AWSCognitoIdentity import AWSCognitoIdentityProvider import AWSPluginsCore import ClientRuntime -@_spi(FoundationClientEngine) import AWSPluginsCore +import AWSClientRuntime +@_spi(PluginHTTPClientEngine) import AWSPluginsCore +@_spi(InternalHttpEngineProxy) import AWSPluginsCore extension AWSCognitoAuthPlugin { @@ -86,30 +88,18 @@ extension AWSCognitoAuthPlugin { private func makeUserPool() throws -> CognitoUserPoolBehavior { switch authConfiguration { case .userPools(let userPoolConfig), .userPoolsAndIdentityPools(let userPoolConfig, _): - // TODO: FrameworkMetadata Replacement let configuration = try CognitoIdentityProviderClient.CognitoIdentityProviderClientConfiguration( region: userPoolConfig.region, serviceSpecific: .init(endpointResolver: userPoolConfig.endpoint?.resolver) ) if var httpClientEngineProxy = httpClientEngineProxy { - let httpClientEngine: HttpClientEngine - #if os(iOS) || os(macOS) - // networking goes through CRT - httpClientEngine = configuration.httpClientEngine - #else - // networking goes through Foundation - httpClientEngine = FoundationClientEngine() - #endif - httpClientEngineProxy.target = httpClientEngine - configuration.httpClientEngine = httpClientEngineProxy + httpClientEngineProxy.target = baseClientEngine(for: configuration) + configuration.httpClientEngine = UserAgentSettingClientEngine( + target: httpClientEngineProxy + ) } else { - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - configuration.httpClientEngine = FoundationClientEngine() - #endif + configuration.httpClientEngine = .userAgentEngine(for: configuration) } return CognitoIdentityProviderClient(config: configuration) @@ -121,17 +111,10 @@ extension AWSCognitoAuthPlugin { private func makeIdentityClient() throws -> CognitoIdentityBehavior { switch authConfiguration { case .identityPools(let identityPoolConfig), .userPoolsAndIdentityPools(_, let identityPoolConfig): - // TODO: FrameworkMetadata Replacement let configuration = try CognitoIdentityClient.CognitoIdentityClientConfiguration( region: identityPoolConfig.region ) - - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - configuration.httpClientEngine = FoundationClientEngine() - #endif + configuration.httpClientEngine = .userAgentEngine(for: configuration) return CognitoIdentityClient(config: configuration) default: diff --git a/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift b/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift index c7ca2994c6..aa3acc070c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/ServiceConfiguration/AmplifyAWSServiceConfiguration.swift @@ -6,57 +6,8 @@ // import Foundation -import AWSClientRuntime import Amplify -// TODO: FrameworkMetadata Replacement -private let tokenNoHashCharacterSet = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!$%'*+-.^_`|~") -private let tokenCharacterSet = tokenNoHashCharacterSet.union(Set("#")) -private let substituteCharacter = Character("-") - -extension String { - - var userAgentToken: String { - String(map { tokenCharacterSet.contains($0) ? $0 : substituteCharacter }) - } - - var userAgentTokenNoHash: String { - String(map { tokenNoHashCharacterSet.contains($0) ? $0 : substituteCharacter }) - } -} - - -public struct FrameworkMetadata { - let name: String - let version: String - let extras: [String: String] - - var sanitizedName: String { - name.userAgentToken - } - var sanitizedVersion: String { - version.userAgentToken - } - - public init(name: String, version: String, extras: [String: String] = [String: String]()) { - self.name = name - self.version = version - self.extras = extras - } - } - -extension FrameworkMetadata: CustomStringConvertible { - public var description: String { - let extrasMetaData = !extras.isEmpty - ? extras.map { - " md/\($0.key.userAgentToken)/\($0.value.userAgentToken)" - }.joined() - : "" - return "lib/\(sanitizedName)/\(sanitizedVersion)\(extrasMetaData)" - } -} -// MARK: - End TODO: FrameworkMetadata Replacement - /// Convenience class that is used by Amplify to include metadata such as values for a "User-Agent" during /// server interactions. /// @@ -69,41 +20,5 @@ public class AmplifyAWSServiceConfiguration { /// - Tag: AmplifyAWSServiceConfiguration.platformName public static let platformName = "amplify-swift" - /// Returns basic amount of metadata that includes both - /// [AmplifyAWSServiceConfiguration.amplifyVersion](x-source-tag://AmplifyAWSServiceConfiguration.amplifyVersion) - /// and - /// [AmplifyAWSServiceConfiguration.platformName](x-source-tag://AmplifyAWSServiceConfiguration.platformName) - /// in addition to the operating system version if `includesOS` is set to `true`. - /// - /// - Tag: AmplifyAWSServiceConfiguration.frameworkMetaDataWithOS - public static func frameworkMetaData(includeOS: Bool = false) -> FrameworkMetadata { - let osKey = "os" - guard let flutterVersion = platformMapping[Platform.flutter] else { - if includeOS { - return FrameworkMetadata( - name: platformName, - version: amplifyVersion, - extras: [osKey: frameworkOS()] - ) - } - return FrameworkMetadata(name: platformName, version: amplifyVersion) - } - var extras = [platformName: amplifyVersion] - if includeOS { - extras[osKey] = frameworkOS() - } - return FrameworkMetadata(name: Platform.flutter.rawValue, - version: flutterVersion, - extras: extras) - } - - private static func frameworkOS() -> String { - // Please note that because the value returned by this function will be - // sanitized by FrameworkMetadata by removing anything not in a special - // character set that does NOT include the forward slash (/), the - // backslash (\) is used as a separator instead. - let separator = "\\" - let operatingSystem = DeviceInfo.current.operatingSystem - return [operatingSystem.name, operatingSystem.version].joined(separator: separator) - } + public static let userAgentLib: String = "lib/\(platformName)#\(amplifyVersion)" } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift new file mode 100644 index 0000000000..f779aa7fbe --- /dev/null +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/PluginClientEngine.swift @@ -0,0 +1,26 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import ClientRuntime +import AWSClientRuntime + +@_spi(PluginHTTPClientEngine) +public func baseClientEngine( + for configuration: AWSClientConfiguration +) -> HttpClientEngine { + let baseClientEngine: HttpClientEngine + #if os(iOS) || os(macOS) + // networking goes through CRT + baseClientEngine = configuration.httpClientEngine + #else + // networking goes through Foundation + baseClientEngine = FoundationClientEngine() + #endif + return baseClientEngine +} + diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift new file mode 100644 index 0000000000..690b8f932f --- /dev/null +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/SdkHttpRequest+updatingUserAgent.swift @@ -0,0 +1,35 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import ClientRuntime + +@_spi(PluginHTTPClientEngine) +extension SdkHttpRequest { + public func updatingUserAgent(with value: String) -> SdkHttpRequest { + let userAgentKey = "User-Agent" + var headers = headers + headers.remove(name: userAgentKey) + headers.add(name: userAgentKey, value: value) + + let endpoint = ClientRuntime.Endpoint( + host: endpoint.host, + path: endpoint.path, + port: endpoint.port, + queryItems: endpoint.queryItems, + protocolType: endpoint.protocolType, + headers: headers, + properties: endpoint.properties + ) + + return SdkHttpRequest( + method: method, + endpoint: endpoint, + body: body + ) + } +} diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSettingClientEngine.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSettingClientEngine.swift new file mode 100644 index 0000000000..aff15e315c --- /dev/null +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSettingClientEngine.swift @@ -0,0 +1,47 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import ClientRuntime +import AWSClientRuntime + +@_spi(PluginHTTPClientEngine) +public struct UserAgentSettingClientEngine: AWSPluginExtension { + @_spi(InternalHttpEngineProxy) + public let target: HttpClientEngine + private let userAgentKey = "User-Agent" + + public init(target: HttpClientEngine) { + self.target = target + } +} + +@_spi(PluginHTTPClientEngine) +extension UserAgentSettingClientEngine: HttpClientEngine { + // CI updates the `platformName` property in `AmplifyAWSServiceConfiguration`. + // We can / probably should move this in the future + // as it's no longer necessary there. + var lib: String { AmplifyAWSServiceConfiguration.userAgentLib } + + public func execute(request: SdkHttpRequest) async throws -> HttpResponse { + let existingUserAgent = request.headers.value(for: userAgentKey) ?? "" + let userAgent = "\(existingUserAgent) \(lib)" + let updatedRequest = request.updatingUserAgent(with: userAgent) + + return try await target.execute(request: updatedRequest) + } +} + +@_spi(PluginHTTPClientEngine) +extension HttpClientEngine where Self == UserAgentSettingClientEngine { + public static func userAgentEngine( + for configuration: AWSClientConfiguration + ) -> Self { + let baseClientEngine = baseClientEngine(for: configuration) + return self.init(target: baseClientEngine) + } +} diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift index e03eb69ce3..863fa636bf 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/UserAgentSuffixAppender.swift @@ -12,7 +12,7 @@ public class UserAgentSuffixAppender: AWSPluginExtension { @_spi(InternalHttpEngineProxy) public var target: HttpClientEngine? = nil public let suffix: String - private let userAgentHeader = "User-Agent" + private let userAgentKey = "User-Agent" public init(suffix: String) { self.suffix = suffix @@ -26,8 +26,9 @@ extension UserAgentSuffixAppender: HttpClientEngine { throw ClientError.unknownError("HttpClientEngine is not set") } - let currentUserAgent = request.headers.value(for: userAgentHeader) ?? "" - request.withHeader(name: userAgentHeader, value: "\(currentUserAgent) \(suffix)") + let existingUserAgent = request.headers.value(for: userAgentKey) ?? "" + let userAgent = "\(existingUserAgent) \(suffix)" + let request = request.updatingUserAgent(with: userAgent) return try await target.execute(request: request) } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/ServiceConfiguration/AmplifyAWSServiceConfigurationTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/ServiceConfiguration/AmplifyAWSServiceConfigurationTests.swift deleted file mode 100644 index 28fd9f6b80..0000000000 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/ServiceConfiguration/AmplifyAWSServiceConfigurationTests.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -import XCTest -@testable import AWSPluginsCore -@testable import AWSClientRuntime - -class AmplifyAWSServiceConfigurationTests: XCTestCase { - - override func tearDown() { - AmplifyAWSServiceConfiguration.platformMapping = [:] - } - - /// Test initiating AmplifyAWSServiceConfiguration - /// - /// - Given: Amplify library - /// - When: - /// - I call AmplifyAWSServiceConfiguration with credential provider - /// - Then: - /// - AmplifyAWSServiceConfiguration should be configured properly - /// - func testInstantiation() { - let frameworkMetaData = AmplifyAWSServiceConfiguration.frameworkMetaData() - XCTAssertNotNil(frameworkMetaData) - XCTAssertEqual(frameworkMetaData.sanitizedName, "amplify-swift") - XCTAssertEqual(frameworkMetaData.sanitizedVersion, AmplifyAWSServiceConfiguration.amplifyVersion) - } - - /// Test adding a new platform to AmplifyAWSServiceConfiguration - /// - /// - Given: Amplify library - /// - When: - /// - I add a new platform to the AmplifyAWSServiceConfiguration - /// - Then: - /// - AmplifyAWSServiceConfiguration should be configured properly with the new platform added. - /// - func testAddNewPlatform() { - AmplifyAWSServiceConfiguration.addUserAgentPlatform(.flutter, version: "1.1") - let frameworkMetaData = AmplifyAWSServiceConfiguration.frameworkMetaData() - XCTAssertNotNil(frameworkMetaData) - XCTAssertEqual(frameworkMetaData.sanitizedName, "amplify-flutter") - XCTAssertEqual(frameworkMetaData.sanitizedVersion, "1.1") - - XCTAssertNotNil(frameworkMetaData.extras) - XCTAssertEqual(frameworkMetaData.extras["amplify-swift"], AmplifyAWSServiceConfiguration.amplifyVersion) - } -} diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSettingClientEngineTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSettingClientEngineTests.swift new file mode 100644 index 0000000000..1e09f72d9d --- /dev/null +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSettingClientEngineTests.swift @@ -0,0 +1,111 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +@_spi(InternalAmplifyPluginExtension) +@_spi(PluginHTTPClientEngine) +@_spi(InternalHttpEngineProxy) +import AWSPluginsCore +import ClientRuntime +import XCTest + +class UserAgentSettingClientEngineTestCase: XCTestCase { + let userAgentKey = "User-Agent" + + /// Given: A `UserAgentSettingClientEngine`. + /// When: A request is invoked **with** an existing User-Agent. + /// Then: The `lib` component of the user-agent is added. + func test_existingUserAgent_addsLibComponent() async throws { + let request: SdkHttpRequest = .mock + let existingUserAgent = "foo/bar/baz" + request.withHeader(name: userAgentKey, value: existingUserAgent) + + let target = MockTargetEngine() + let engine = UserAgentSettingClientEngine(target: target) + _ = try await engine.execute(request: request) + let userAgent = try XCTUnwrap(target.request?.headers.value(for: userAgentKey)) + + XCTAssertEqual( + userAgent, + "\(existingUserAgent) \(AmplifyAWSServiceConfiguration.userAgentLib)" + ) + } + + /// Given: A `UserAgentSettingClientEngine`. + /// When: A request is invoked **without** existing User-Agent. + /// Then: The `lib` component of the user-agent is added. + func test_nonExistingUserAgent_addsLibComponent() async throws { + let request: SdkHttpRequest = .mock + let target = MockTargetEngine() + let engine = UserAgentSettingClientEngine(target: target) + _ = try await engine.execute(request: request) + let userAgent = try XCTUnwrap(target.request?.headers.value(for: userAgentKey)).trim() + + XCTAssertEqual(userAgent, AmplifyAWSServiceConfiguration.userAgentLib) + } + + /// Given: A `UserAgentSettingClientEngine` targeting a `UserAgentSuffixAppender`. + /// When: A request is invoked **with** existing User-Agent. + /// Then: The `lib` component of the user-agent and the suffix are added. + func test_existingUserAgentCombinedWithSuffixAppender_addLibAndSuffix() async throws { + let request: SdkHttpRequest = .mock + let existingUserAgent = "foo/bar/baz" + request.withHeader(name: userAgentKey, value: existingUserAgent) + + let target = MockTargetEngine() + let suffix = "a/b/c" + let suffixAppender = UserAgentSuffixAppender(suffix: suffix) + suffixAppender.target = target + let engine = UserAgentSettingClientEngine(target: suffixAppender) + + _ = try await engine.execute(request: request) + let userAgent = try XCTUnwrap(target.request?.headers.value(for: userAgentKey)) + XCTAssertEqual( + userAgent, + "\(existingUserAgent) \(AmplifyAWSServiceConfiguration.userAgentLib) \(suffix)" + ) + } + + /// Given: A `UserAgentSettingClientEngine` targeting a `UserAgentSuffixAppender`. + /// When: A request is invoked **without** existing User-Agent. + /// Then: The `lib` component of the user-agent and the suffix are added. + func test_nonExistingUserAgentCombinedWithSuffixAppender_addLibAndSuffix() async throws { + let request: SdkHttpRequest = .mock + + let target = MockTargetEngine() + let suffix = "a/b/c" + let suffixAppender = UserAgentSuffixAppender(suffix: suffix) + suffixAppender.target = target + let engine = UserAgentSettingClientEngine(target: suffixAppender) + + _ = try await engine.execute(request: request) + let userAgent = try XCTUnwrap(target.request?.headers.value(for: userAgentKey)).trim() + XCTAssertEqual( + userAgent, + "\(AmplifyAWSServiceConfiguration.userAgentLib) \(suffix)" + ) + } +} + +class MockTargetEngine: HttpClientEngine { + var request: SdkHttpRequest? + + func execute( + request: SdkHttpRequest + ) async throws -> HttpResponse { + self.request = request + return .init(body: .empty, statusCode: .accepted) + } +} + +extension SdkHttpRequest { + static var mock: SdkHttpRequest { + .init( + method: .get, + endpoint: .init(host: "amplify") + ) + } +} diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift index a112451510..221ead103c 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Utils/UserAgentSuffixAppenderTests.swift @@ -36,7 +36,9 @@ class UserAgentSuffixAppenderTests: XCTestCase { _ = try await appender.execute(request: request) XCTAssertEqual(httpClientEngine.executeCount, 1) XCTAssertNotNil(httpClientEngine.executeRequest) - let userAgent = try XCTUnwrap(request.headers.value(for: userAgentKey)) + let userAgent = try XCTUnwrap( + httpClientEngine.executeRequest?.headers.value(for: userAgentKey) + ) XCTAssertTrue(userAgent.hasSuffix(customSuffix)) } @@ -49,7 +51,9 @@ class UserAgentSuffixAppenderTests: XCTestCase { _ = try await appender.execute(request: request) XCTAssertEqual(httpClientEngine.executeCount, 1) XCTAssertNotNil(httpClientEngine.executeRequest) - let userAgent = try XCTUnwrap(request.headers.value(for: userAgentKey)) + let userAgent = try XCTUnwrap( + httpClientEngine.executeRequest?.headers.value(for: userAgentKey) + ) XCTAssertTrue(userAgent.hasSuffix(customSuffix)) } diff --git a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift index d1a4caf9ae..5bf5d34e23 100644 --- a/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift +++ b/AmplifyPlugins/Geo/Sources/AWSLocationGeoPlugin/AWSLocationGeoPlugin+Configure.swift @@ -8,7 +8,7 @@ import Foundation import Amplify import AWSPluginsCore -@_spi(FoundationClientEngine) import AWSPluginsCore +@_spi(PluginHTTPClientEngine) import AWSPluginsCore import AWSLocation import AWSClientRuntime @@ -36,12 +36,7 @@ extension AWSLocationGeoPlugin { credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - serviceConfiguration.httpClientEngine = FoundationClientEngine() - #endif + serviceConfiguration.httpClientEngine = .userAgentEngine(for: serviceConfiguration) let location = LocationClient(config: serviceConfiguration) let locationService = AWSLocationAdapter(location: location) diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift index 2a2e1a30f9..e93baf21c2 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Extensions/PinpointClient+CredentialsProvider.swift @@ -8,7 +8,7 @@ import AWSClientRuntime import AWSPluginsCore import AWSPinpoint -@_spi(FoundationClientEngine) import AWSPluginsCore +@_spi(PluginHTTPClientEngine) import AWSPluginsCore extension PinpointClient { convenience init(region: String, credentialsProvider: CredentialsProviding) throws { @@ -17,12 +17,8 @@ extension PinpointClient { region: region, credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - configuration.httpClientEngine = FoundationClientEngine() - #endif + + configuration.httpClientEngine = .userAgentEngine(for: configuration) PinpointRequestsRegistry.shared.setCustomHttpEngine(on: configuration) self.init(config: configuration) } diff --git a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift index 9b7d27b1da..6c0b33dc99 100644 --- a/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift +++ b/AmplifyPlugins/Internal/Sources/InternalAWSPinpoint/Support/Utils/PinpointRequestsRegistry.swift @@ -8,6 +8,8 @@ import Foundation import AWSPinpoint import ClientRuntime +@_spi(PluginHTTPClientEngine) +import AWSPluginsCore @globalActor actor PinpointRequestsRegistry { static let shared = PinpointRequestsRegistry() @@ -66,15 +68,11 @@ private struct CustomPinpointHttpClientEngine: HttpClientEngine { return try await httpClientEngine.execute(request: request) } - let headers = request.headers - let currentUserAgent = headers.value(for: userAgentHeader) ?? "" - request.withHeader( - name: userAgentHeader, - value: "\(currentUserAgent)\(userAgentSuffix)" - ) + let currentUserAgent = request.headers.value(for: userAgentHeader) ?? "" + let updatedRequest = request.updatingUserAgent(with: "\(currentUserAgent) \(userAgentSuffix)") await PinpointRequestsRegistry.shared.unregisterSources(for: pinpointApi) - return try await httpClientEngine.execute(request: request) + return try await httpClientEngine.execute(request: updatedRequest) } private func userAgent(for api: PinpointRequestsRegistry.API) async -> String? { diff --git a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift index cb0c07da3c..7cb6c4a74e 100644 --- a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift +++ b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSessionController.swift @@ -6,7 +6,7 @@ // import AWSPluginsCore -@_spi(FoundationClientEngine) import AWSPluginsCore +@_spi(PluginHTTPClientEngine) import AWSPluginsCore import Amplify import Combine import Foundation @@ -109,12 +109,7 @@ final class AWSCloudWatchLoggingSessionController { credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - configuration.httpClientEngine = FoundationClientEngine() - #endif + configuration.httpClientEngine = .userAgentEngine(for: configuration) self.client = CloudWatchLogsClient(config: configuration) } diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift index 9d87be3f5f..b90c7e0a03 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService.swift @@ -12,7 +12,7 @@ import AWSTextract import AWSComprehend import AWSPolly import AWSPluginsCore -@_spi(FoundationClientEngine) import AWSPluginsCore +@_spi(PluginHTTPClientEngine) import AWSPluginsCore import Foundation import ClientRuntime import AWSClientRuntime @@ -38,60 +38,47 @@ class AWSPredictionsService { region: configuration.convert.region, credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - translateClientConfiguration.httpClientEngine = FoundationClientEngine() - #endif + translateClientConfiguration.httpClientEngine = .userAgentEngine( + for: translateClientConfiguration + ) + let awsTranslateClient = TranslateClient(config: translateClientConfiguration) let pollyClientConfiguration = try PollyClient.PollyClientConfiguration( region: configuration.convert.region, credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - pollyClientConfiguration.httpClientEngine = FoundationClientEngine() - #endif + pollyClientConfiguration.httpClientEngine = .userAgentEngine( + for: pollyClientConfiguration + ) let awsPollyClient = PollyClient(config: pollyClientConfiguration) let comprehendClientConfiguration = try ComprehendClient.ComprehendClientConfiguration( region: configuration.convert.region, credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - comprehendClientConfiguration.httpClientEngine = FoundationClientEngine() - #endif + comprehendClientConfiguration.httpClientEngine = .userAgentEngine( + for: comprehendClientConfiguration + ) + let awsComprehendClient = ComprehendClient(config: comprehendClientConfiguration) let rekognitionClientConfiguration = try RekognitionClient.RekognitionClientConfiguration( region: configuration.identify.region, credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - rekognitionClientConfiguration.httpClientEngine = FoundationClientEngine() - #endif + rekognitionClientConfiguration.httpClientEngine = .userAgentEngine( + for: rekognitionClientConfiguration + ) let awsRekognitionClient = RekognitionClient(config: rekognitionClientConfiguration) let textractClientConfiguration = try TextractClient.TextractClientConfiguration( region: configuration.identify.region, credentialsProvider: credentialsProvider ) - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - textractClientConfiguration.httpClientEngine = FoundationClientEngine() - #endif + textractClientConfiguration.httpClientEngine = .userAgentEngine( + for: textractClientConfiguration + ) let awsTextractClient = TextractClient(config: textractClientConfiguration) let awsTranscribeStreamingAdapter = AWSTranscribeStreamingAdapter( diff --git a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift index e2c7fe59ce..1daf10edd6 100644 --- a/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift +++ b/AmplifyPlugins/Storage/Sources/AWSS3StoragePlugin/Service/Storage/AWSS3StorageService.swift @@ -6,11 +6,10 @@ // import Foundation - import AWSS3 import Amplify import AWSPluginsCore -@_spi(FoundationClientEngine) import AWSPluginsCore +@_spi(PluginHTTPClientEngine) import AWSPluginsCore import ClientRuntime /// - Tag: AWSS3StorageService @@ -65,24 +64,13 @@ class AWSS3StorageService: AWSS3StorageServiceBehavior, StorageServiceProxy { signingRegion: region ) - if var proxy = httpClientEngineProxy { - let httpClientEngine: HttpClientEngine - #if os(iOS) || os(macOS) - httpClientEngine = clientConfig.httpClientEngine - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - httpClientEngine = FoundationClientEngine() - #endif - proxy.target = httpClientEngine - clientConfig.httpClientEngine = proxy + if var httpClientEngineProxy = httpClientEngineProxy { + httpClientEngineProxy.target = baseClientEngine(for: clientConfig) + clientConfig.httpClientEngine = UserAgentSettingClientEngine( + target: httpClientEngineProxy + ) } else { - #if os(iOS) || os(macOS) // no-op - #else - // For any platform except iOS or macOS - // Use Foundation instead of CRT for networking. - clientConfig.httpClientEngine = FoundationClientEngine() - #endif + clientConfig.httpClientEngine = .userAgentEngine(for: clientConfig) } let s3Client = S3Client(config: clientConfig) @@ -142,7 +130,7 @@ class AWSS3StorageService: AWSS3StorageServiceBehavior, StorageServiceProxy { self.preSignedURLBuilder = preSignedURLBuilder self.awsS3 = awsS3 self.bucket = bucket - self.userAgent = AmplifyAWSServiceConfiguration.frameworkMetaData(includeOS: true).description + self.userAgent = AmplifyAWSServiceConfiguration.userAgentLib StorageBackgroundEventsRegistry.register(identifier: identifier) From ba2247b47c9a0e69367fa35c353ee331aa44043e Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Wed, 4 Oct 2023 17:07:54 -0400 Subject: [PATCH 17/23] fix(pinpoint-requests-registry-tests): target executed request in tests (#3276) --- .../PinpointRequestsRegistryTests.swift | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift index d028cf9dff..d5ddb3974b 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/PinpointRequestsRegistryTests.swift @@ -35,12 +35,12 @@ class PinpointRequestsRegistryTests: XCTestCase { await PinpointRequestsRegistry.shared.registerSource(.pushNotifications, for: .recordEvent) let sdkRequest = try createSdkRequest(for: .recordEvent) _ = try await httpClientEngine.execute(request: sdkRequest) + let executedRequest = mockedHttpSdkClient.request XCTAssertEqual(mockedHttpSdkClient.executeCount, 1) - guard let userAgent = sdkRequest.headers.value(for: "User-Agent") else { - XCTFail("Expected User-Agent") - return - } + let userAgent = try XCTUnwrap( + executedRequest?.headers.value(for: "User-Agent") + ) XCTAssertTrue(userAgent.contains(AWSPinpointSource.analytics.rawValue)) XCTAssertTrue(userAgent.contains(AWSPinpointSource.pushNotifications.rawValue)) } @@ -54,12 +54,12 @@ class PinpointRequestsRegistryTests: XCTestCase { let oldUserAgent = sdkRequest.headers.value(for: "User-Agent") _ = try await httpClientEngine.execute(request: sdkRequest) + let executedRequest = mockedHttpSdkClient.request XCTAssertEqual(mockedHttpSdkClient.executeCount, 1) - guard let newUserAgent = sdkRequest.headers.value(for: "User-Agent") else { - XCTFail("Expected User-Agent") - return - } + let newUserAgent = try XCTUnwrap( + executedRequest?.headers.value(for: "User-Agent") + ) XCTAssertEqual(newUserAgent, oldUserAgent) XCTAssertFalse(newUserAgent.contains(AWSPinpointSource.analytics.rawValue)) @@ -91,8 +91,11 @@ private extension HttpClientEngine { private class MockHttpClientEngine: HttpClientEngine { var executeCount = 0 + var request: SdkHttpRequest? + func execute(request: SdkHttpRequest) async throws -> HttpResponse { executeCount += 1 + self.request = request return .init(body: .none, statusCode: .accepted) } From 937de0c9c0f189d82020762dd42788c6b061d9bb Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 5 Oct 2023 11:29:09 -0400 Subject: [PATCH 18/23] fix(storage-test): use identity comparison operators not XCTest methods (#3278) --- .../S3ClientConfigurationProxyTests.swift | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift index 7830779aec..77d1ec3b3d 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Configuration/S3ClientConfigurationProxyTests.swift @@ -19,9 +19,7 @@ final class S3ClientConfigurationAccelerateTestCase: XCTestCase { /// When: An override is set through `withAccelerate(_:)` /// Then: The base configuration is not mutated. func testPropertyOverrides() async throws { - let baseConfiguration = try await S3Client.S3ClientConfiguration() - baseConfiguration.serviceSpecific.accelerate = true - + let baseConfiguration = try await configuration(accelerate: true) let sut = try baseConfiguration.withAccelerate(false) XCTAssertEqual(sut.serviceSpecific.accelerate, false) XCTAssertEqual(baseConfiguration.serviceSpecific.accelerate, true) @@ -35,7 +33,7 @@ final class S3ClientConfigurationAccelerateTestCase: XCTestCase { let baseConfiguration = try await configuration(accelerate: baseAccelerate) let nilAccelerate = try baseConfiguration.withAccelerate(nil) - XCTAssertIdentical(baseConfiguration, nilAccelerate) + XCTAssert(baseConfiguration === nilAccelerate) } /// Given: A client configuration. @@ -46,7 +44,7 @@ final class S3ClientConfigurationAccelerateTestCase: XCTestCase { let baseConfiguration = try await configuration(accelerate: baseAccelerate) let equalAccelerate = try baseConfiguration.withAccelerate(baseAccelerate) - XCTAssertIdentical(baseConfiguration, equalAccelerate) + XCTAssert(baseConfiguration === equalAccelerate) } /// Given: A client configuration. @@ -57,7 +55,7 @@ final class S3ClientConfigurationAccelerateTestCase: XCTestCase { let baseConfiguration = try await configuration(accelerate: baseAccelerate) let nonEqualAccelerate = try baseConfiguration.withAccelerate(!baseAccelerate) - XCTAssertNotIdentical(baseConfiguration, nonEqualAccelerate) + XCTAssert(baseConfiguration !== nonEqualAccelerate) } @@ -74,7 +72,7 @@ final class S3ClientConfigurationAccelerateTestCase: XCTestCase { credentialsProvider: nil, endpoint: UUID().uuidString, serviceSpecific: serviceSpecific, - region: nil, + region: "us-east-1", regionResolver: nil, signingRegion: UUID().uuidString, useDualStack: .random(), From f042a1c29cb11d248b7f722bc8a8635d9bc48574 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 5 Oct 2023 13:47:12 -0400 Subject: [PATCH 19/23] rebase main From c56ff9268e2d4d281ee06da99174dbfe9886406e Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 5 Oct 2023 14:31:26 -0400 Subject: [PATCH 20/23] fix(predictions): use readData on textToSpeech bytestream (#3280) --- .../AWSPredictionsService+Polly.swift | 13 +---- .../project.pbxproj | 53 ++----------------- 2 files changed, 6 insertions(+), 60 deletions(-) diff --git a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift index 507e968448..62dbf18308 100644 --- a/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift +++ b/AmplifyPlugins/Predictions/AWSPredictionsPlugin/Service/Predictions/AWSPredictionsService+Polly.swift @@ -24,7 +24,7 @@ extension AWSPredictionsService: AWSPollyServiceBehavior { do { let synthesizedSpeechResult = try await awsPolly.synthesizeSpeech(input: input) - guard let speech = synthesizedSpeechResult.audioStream + guard let speech = try await synthesizedSpeechResult.audioStream?.readData() else { throw PredictionsError.service( .init( @@ -34,16 +34,7 @@ extension AWSPredictionsService: AWSPollyServiceBehavior { ) } - switch speech { - case .data(let data?): - let textToSpeechResult = Predictions.Convert.TextToSpeech.Result( - audioData: data - ) - return textToSpeechResult - // TODO: figure out what to throw here - default: throw PredictionsError.unknown("Missing respose", "", nil) - } - + return .init(audioData: speech) } catch let error as PredictionsErrorConvertible { throw error.predictionsError } catch { diff --git a/AmplifyPlugins/Predictions/Tests/PredictionsHostApp/PredictionsHostApp.xcodeproj/project.pbxproj b/AmplifyPlugins/Predictions/Tests/PredictionsHostApp/PredictionsHostApp.xcodeproj/project.pbxproj index a2b9f1f0a9..ba091df90b 100644 --- a/AmplifyPlugins/Predictions/Tests/PredictionsHostApp/PredictionsHostApp.xcodeproj/project.pbxproj +++ b/AmplifyPlugins/Predictions/Tests/PredictionsHostApp/PredictionsHostApp.xcodeproj/project.pbxproj @@ -18,9 +18,6 @@ 6875F90F2A3CCCB7001C9AAF /* InterpretBasicIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9054235A291425630000D108 /* InterpretBasicIntegrationTests.swift */; }; 6875F9102A3CCCB7001C9AAF /* AWSPredictionsPluginTestBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90542359291425630000D108 /* AWSPredictionsPluginTestBase.swift */; }; 6875F9112A3CCCB7001C9AAF /* ConvertBasicIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90542358291425630000D108 /* ConvertBasicIntegrationTests.swift */; }; - 6875F9142A3CCCB7001C9AAF /* Amplify in Frameworks */ = {isa = PBXBuildFile; productRef = 6875F9092A3CCCB7001C9AAF /* Amplify */; }; - 6875F9152A3CCCB7001C9AAF /* AWSPredictionsPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 6875F90B2A3CCCB7001C9AAF /* AWSPredictionsPlugin */; }; - 6875F9162A3CCCB7001C9AAF /* AWSCognitoAuthPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 6875F90A2A3CCCB7001C9AAF /* AWSCognitoAuthPlugin */; }; 6875F9182A3CCCB7001C9AAF /* testImageText.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 9054235E291425630000D108 /* testImageText.jpg */; }; 6875F9192A3CCCB7001C9AAF /* testImageCeleb.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 90542363291425630000D108 /* testImageCeleb.jpg */; }; 6875F91A2A3CCCB7001C9AAF /* testImageTextWithTables.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 90542360291425630000D108 /* testImageTextWithTables.jpg */; }; @@ -38,10 +35,6 @@ 9028304E2914042800897087 /* AWSCognitoAuthPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 9028304D2914042800897087 /* AWSCognitoAuthPlugin */; }; 902830502914042800897087 /* AWSPredictionsPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 9028304F2914042800897087 /* AWSPredictionsPlugin */; }; 902830522914042800897087 /* CoreMLPredictionsPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 902830512914042800897087 /* CoreMLPredictionsPlugin */; }; - 904D63AD291439890057D06F /* Amplify in Frameworks */ = {isa = PBXBuildFile; productRef = 904D63AC291439890057D06F /* Amplify */; }; - 904D63AF291439890057D06F /* AWSCognitoAuthPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 904D63AE291439890057D06F /* AWSCognitoAuthPlugin */; }; - 904D63B1291439890057D06F /* AWSPredictionsPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 904D63B0291439890057D06F /* AWSPredictionsPlugin */; }; - 904D63B3291439890057D06F /* CoreMLPredictionsPlugin in Frameworks */ = {isa = PBXBuildFile; productRef = 904D63B2291439890057D06F /* CoreMLPredictionsPlugin */; }; 905423522914254B0000D108 /* audio.wav in Resources */ = {isa = PBXBuildFile; fileRef = 9054234E2914254B0000D108 /* audio.wav */; }; 905423532914254B0000D108 /* people.jpg in Resources */ = {isa = PBXBuildFile; fileRef = 9054234F2914254B0000D108 /* people.jpg */; }; 905423542914254B0000D108 /* CoreMLPredictionsPluginIntegrationTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 905423502914254B0000D108 /* CoreMLPredictionsPluginIntegrationTest.swift */; }; @@ -132,9 +125,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 6875F9142A3CCCB7001C9AAF /* Amplify in Frameworks */, - 6875F9152A3CCCB7001C9AAF /* AWSPredictionsPlugin in Frameworks */, - 6875F9162A3CCCB7001C9AAF /* AWSCognitoAuthPlugin in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -160,10 +150,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 904D63B3291439890057D06F /* CoreMLPredictionsPlugin in Frameworks */, - 904D63AD291439890057D06F /* Amplify in Frameworks */, - 904D63B1291439890057D06F /* AWSPredictionsPlugin in Frameworks */, - 904D63AF291439890057D06F /* AWSCognitoAuthPlugin in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -326,9 +312,6 @@ ); name = AWSPredictionsPluginIntegrationTestsWatch; packageProductDependencies = ( - 6875F9092A3CCCB7001C9AAF /* Amplify */, - 6875F90A2A3CCCB7001C9AAF /* AWSCognitoAuthPlugin */, - 6875F90B2A3CCCB7001C9AAF /* AWSPredictionsPlugin */, ); productName = AWSPredictionsPluginIntegrationTests; productReference = 6875F9242A3CCCB7001C9AAF /* AWSPredictionsPluginIntegrationTestsWatch.xctest */; @@ -391,10 +374,6 @@ ); name = AWSPredictionsPluginIntegrationTests; packageProductDependencies = ( - 904D63AC291439890057D06F /* Amplify */, - 904D63AE291439890057D06F /* AWSCognitoAuthPlugin */, - 904D63B0291439890057D06F /* AWSPredictionsPlugin */, - 904D63B2291439890057D06F /* CoreMLPredictionsPlugin */, ); productName = AWSPredictionsPluginIntegrationTests; productReference = 903555F829141355004B83C2 /* AWSPredictionsPluginIntegrationTests.xctest */; @@ -882,6 +861,7 @@ "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; + OTHER_LDFLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = io.coffee.PredictionsHostApp; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "appletvos appletvsimulator iphoneos iphonesimulator"; @@ -916,6 +896,7 @@ "@executable_path/Frameworks", ); MARKETING_VERSION = 1.0; + OTHER_LDFLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = io.coffee.PredictionsHostApp; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "appletvos appletvsimulator iphoneos iphonesimulator"; @@ -943,6 +924,7 @@ "@loader_path/Frameworks", ); MARKETING_VERSION = 1.0; + OTHER_LDFLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = io.coffee.CoreMLPredictionsPluginIntegrationTests; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "appletvos appletvsimulator iphoneos iphonesimulator"; @@ -973,6 +955,7 @@ "@loader_path/Frameworks", ); MARKETING_VERSION = 1.0; + OTHER_LDFLAGS = ""; PRODUCT_BUNDLE_IDENTIFIER = io.coffee.CoreMLPredictionsPluginIntegrationTests; PRODUCT_NAME = "$(TARGET_NAME)"; SUPPORTED_PLATFORMS = "appletvos appletvsimulator iphoneos iphonesimulator"; @@ -1119,18 +1102,6 @@ isa = XCSwiftPackageProductDependency; productName = AWSPredictionsPlugin; }; - 6875F9092A3CCCB7001C9AAF /* Amplify */ = { - isa = XCSwiftPackageProductDependency; - productName = Amplify; - }; - 6875F90A2A3CCCB7001C9AAF /* AWSCognitoAuthPlugin */ = { - isa = XCSwiftPackageProductDependency; - productName = AWSCognitoAuthPlugin; - }; - 6875F90B2A3CCCB7001C9AAF /* AWSPredictionsPlugin */ = { - isa = XCSwiftPackageProductDependency; - productName = AWSPredictionsPlugin; - }; 9028304B2914042800897087 /* Amplify */ = { isa = XCSwiftPackageProductDependency; productName = Amplify; @@ -1147,22 +1118,6 @@ isa = XCSwiftPackageProductDependency; productName = CoreMLPredictionsPlugin; }; - 904D63AC291439890057D06F /* Amplify */ = { - isa = XCSwiftPackageProductDependency; - productName = Amplify; - }; - 904D63AE291439890057D06F /* AWSCognitoAuthPlugin */ = { - isa = XCSwiftPackageProductDependency; - productName = AWSCognitoAuthPlugin; - }; - 904D63B0291439890057D06F /* AWSPredictionsPlugin */ = { - isa = XCSwiftPackageProductDependency; - productName = AWSPredictionsPlugin; - }; - 904D63B2291439890057D06F /* CoreMLPredictionsPlugin */ = { - isa = XCSwiftPackageProductDependency; - productName = CoreMLPredictionsPlugin; - }; /* End XCSwiftPackageProductDependency section */ }; rootObject = 90282FFA2914027000897087 /* Project object */; From 63229466d7763e3471a53522182394ca1d09d08b Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Thu, 5 Oct 2023 14:45:10 -0400 Subject: [PATCH 21/23] fix(geo): remove error helper mapping tests --- .../GeoErrorHelperTests.swift | 187 ------------------ 1 file changed, 187 deletions(-) delete mode 100644 AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/GeoErrorHelperTests.swift diff --git a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/GeoErrorHelperTests.swift b/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/GeoErrorHelperTests.swift deleted file mode 100644 index 9ae8f0ec1f..0000000000 --- a/AmplifyPlugins/Geo/Tests/AWSLocationGeoPluginTests/GeoErrorHelperTests.swift +++ /dev/null @@ -1,187 +0,0 @@ -// -// Copyright Amazon.com Inc. or its affiliates. -// All Rights Reserved. -// -// SPDX-License-Identifier: Apache-2.0 -// - -@testable import AWSClientRuntime -@testable import AWSLocation -@testable import Amplify -@testable import AWSLocationGeoPlugin -import XCTest - -class GeoErrorHelperTests: AWSLocationGeoPluginTestBase { - /// - Given: a generic error - /// - When: GeoErrorHelper.mapAWSLocationError is called with the generic error - /// - Then: a default Geo.Error.unknown is returned - func testGeoErrorHelperMapsDefaultError() { - let error = GeoErrorHelper.mapAWSLocationError(GenericError.validation) - switch error { - case .unknown(_, _, _): - break - default: - XCTFail("Failed to map to default error") - } - } - - /// - Given: SearchPlaceIndexForTextOutputError of access denied - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForTextOutputError - /// - Then: a default Geo.Error.accessDenied is returned - func testGeoErrorHelperMapsSearchPlaceIndexForTextOutputErrorAccessDenied() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForTextOutputError.accessDeniedException(AccessDeniedException())) - switch error { - case .accessDenied(_, _, _): - break - default: - XCTFail("Failed to map to default error") - } - } - - /// - Given: SearchPlaceIndexForTextOutputError of internal server - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForTextOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForTextOutputErrorInternalServer() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForTextOutputError.internalServerException(InternalServerException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to default error") - } - } - - /// - Given: SearchPlaceIndexForTextOutputError of resource not found - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForTextOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForTextOutputErrorResourceNotFound() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForTextOutputError.resourceNotFoundException(ResourceNotFoundException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to service error") - } - } - - /// - Given: SearchPlaceIndexForTextOutputError of throttling - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForTextOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForTextOutputErrorThrottling() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForTextOutputError.throttlingException(ThrottlingException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to service error") - } - } - - /// - Given: SearchPlaceIndexForTextOutputError of validation - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForTextOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForTextOutputErrorValidation() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForTextOutputError.validationException(ValidationException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to service error") - } - } - - /// - Given: SearchPlaceIndexForTextOutputError of unknown - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForTextOutputError - /// - Then: a default Geo.Error.unknown is returned - func testGeoErrorHelperMapsSearchPlaceIndexForTextOutputErrorUnknown() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForTextOutputError.unknown(UnknownAWSHttpServiceError())) - switch error { - case .unknown(_, _, _): - break - default: - XCTFail("Failed to map to unknown error") - } - } - - /// - Given: SearchPlaceIndexForPositionOutputError of access denied - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForPositionOutputError - /// - Then: a default Geo.Error.accessDenied is returned - func testGeoErrorHelperMapsSearchPlaceIndexForPositionOutputErrorAccessDenied() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForPositionOutputError.accessDeniedException(AccessDeniedException())) - switch error { - case .accessDenied(_, _, _): - break - default: - XCTFail("Failed to map to default error") - } - } - - /// - Given: SearchPlaceIndexForPositionOutputError of internal server - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForPositionOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForPositionOutputErrorInternalServer() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForPositionOutputError.internalServerException(InternalServerException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to default error") - } - } - - /// - Given: SearchPlaceIndexForPositionOutputError of resource not found - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForPositionOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForPositionOutputErrorErrorResourceNotFound() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForPositionOutputError.resourceNotFoundException(ResourceNotFoundException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to service error") - } - } - - /// - Given: SearchPlaceIndexForPositionOutputError of throttling - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForPositionOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForPositionOutputErrorThrottling() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForPositionOutputError.throttlingException(ThrottlingException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to service error") - } - } - - /// - Given: SearchPlaceIndexForPositionOutputError of validation - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForPositionOutputError - /// - Then: a default Geo.Error.serviceError is returned - func testGeoErrorHelperMapsSearchPlaceIndexForPositionOutputErrorValidation() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForPositionOutputError.validationException(ValidationException())) - switch error { - case .serviceError(_, _, _): - break - default: - XCTFail("Failed to map to service error") - } - } - - /// - Given: SearchPlaceIndexForPositionOutputError of unknown - /// - When: GeoErrorHelper.mapAWSLocationError is called with the SearchPlaceIndexForPositionOutputError - /// - Then: a default Geo.Error.unknown is returned - func testGeoErrorHelperMapsSSearchPlaceIndexForPositionOutputErrorUnknown() { - let error = GeoErrorHelper.mapAWSLocationError(SearchPlaceIndexForPositionOutputError.unknown(UnknownAWSHttpServiceError())) - switch error { - case .unknown(_, _, _): - break - default: - XCTFail("Failed to map to unknown error") - } - } -} - -enum GenericError: Error { - case validation -} From 6117f76af085ac0f6080cb8b08cf83abc30d44b8 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Mon, 9 Oct 2023 14:57:35 -0400 Subject: [PATCH 22/23] fix: remaining integration tests for sdk update (#3283) --- .github/workflows/integ_test_auth.yml | 8 +- .github/workflows/integ_test_predictions.yml | 4 +- .../xcshareddata/swiftpm/Package.resolved | 18 ++-- .../xcshareddata/swiftpm/Package.resolved | 18 ++-- .../AuthDeleteUserTests.swift | 22 +++-- .../DeviceTests/AuthForgetDeviceTests.swift | 8 +- .../SignInTests/AuthSRPSignInTests.swift | 19 ++-- .../AuthResendSignUpCodeTests.swift | 19 ++-- .../SignUpTests/AuthSignUpTests.swift | 2 +- .../xcschemes/AuthHostedUIApp.xcscheme | 3 +- .../AmplifyAWSServiceConfiguration.swift | 2 + ...reMLPredictionsPluginIntegrationTest.swift | 2 +- .../project.pbxproj | 86 +++++++++++++++++++ .../PredictionsHostApp/ContentView.swift | 66 -------------- .../Service/Storage/AWSS3StorageService.swift | 2 +- ...S3StoragePluginBasicIntegrationTests.swift | 4 +- .../AWSS3StoragePluginTestBase.swift | 1 + .../xcshareddata/swiftpm/Package.resolved | 18 ++-- .../xcschemes/StorageHostApp.xcscheme | 2 +- 19 files changed, 175 insertions(+), 129 deletions(-) diff --git a/.github/workflows/integ_test_auth.yml b/.github/workflows/integ_test_auth.yml index 1a76717c21..b628e68abe 100644 --- a/.github/workflows/integ_test_auth.yml +++ b/.github/workflows/integ_test_auth.yml @@ -9,7 +9,7 @@ permissions: jobs: auth-integration-test-iOS: - runs-on: macos-12 + runs-on: macos-13 environment: IntegrationTest steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b @@ -32,6 +32,8 @@ jobs: with: project_path: ./AmplifyPlugins/Auth/Tests/AuthHostApp/ scheme: AuthIntegrationTests + destination: 'platform=iOS Simulator,name=iPhone 14,OS=latest' + xcode_path: '/Applications/Xcode_14.3.app' auth-integration-test-tvOS: runs-on: macos-13 @@ -90,7 +92,7 @@ jobs: xcode_path: '/Applications/Xcode_14.3.app' auth-ui-integration-test-iOS: - runs-on: macos-12 + runs-on: macos-13 environment: IntegrationTest steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b @@ -113,3 +115,5 @@ jobs: with: project_path: ./AmplifyPlugins/Auth/Tests/AuthHostedUIApp/ scheme: AuthHostedUIApp + destination: 'platform=iOS Simulator,name=iPhone 14,OS=latest' + xcode_path: '/Applications/Xcode_14.3.app' diff --git a/.github/workflows/integ_test_predictions.yml b/.github/workflows/integ_test_predictions.yml index d0a9b8ac3d..58be80d7e8 100644 --- a/.github/workflows/integ_test_predictions.yml +++ b/.github/workflows/integ_test_predictions.yml @@ -11,7 +11,7 @@ jobs: predictions-integration-test-iOS: continue-on-error: true timeout-minutes: 30 - runs-on: macos-12 + runs-on: macos-13 environment: IntegrationTest steps: - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b @@ -37,6 +37,8 @@ jobs: with: project_path: ./AmplifyPlugins/Predictions/Tests/PredictionsHostApp scheme: AWSPredictionsPluginIntegrationTests + destination: 'platform=iOS Simulator,name=iPhone 14,OS=latest' + xcode_path: '/Applications/Xcode_14.3.app' predictions-integration-test-tvOS: continue-on-error: true diff --git a/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 2ef4d7901c..6203f7a6b6 100644 --- a/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/AmplifyPlugins/Analytics/Tests/AnalyticsHostApp/AnalyticsHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/awslabs/aws-crt-swift", "state" : { - "revision" : "6feec6c3787877807aa9a00fad09591b96752376", - "version" : "0.6.1" + "revision" : "997904873945e074aaf5c51ea968d9a84684525a", + "version" : "0.13.0" } }, { @@ -32,8 +32,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/awslabs/aws-sdk-swift.git", "state" : { - "revision" : "24bae88a2391fe75da8a940a544d1ef6441f5321", - "version" : "0.13.0" + "revision" : "ace826dbfe96e7e3103fe7f45f815b8a590bcf21", + "version" : "0.26.0" } }, { @@ -57,10 +57,10 @@ { "identity" : "smithy-swift", "kind" : "remoteSourceControl", - "location" : "https://github.com/awslabs/smithy-swift", + "location" : "https://github.com/smithy-lang/smithy-swift", "state" : { - "revision" : "7b28da158d92cd06a3549140d43b8fbcf64a94a6", - "version" : "0.15.0" + "revision" : "eed3f3d8e5aa704fcd60bb227b0fc89bf3328c42", + "version" : "0.30.0" } }, { @@ -104,8 +104,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/MaxDesiatov/XMLCoder.git", "state" : { - "revision" : "b1e944cbd0ef33787b13f639a5418d55b3bed501", - "version" : "0.17.1" + "revision" : "80b4a1646399b8e4e0ce80711653476a85bd5e37", + "version" : "0.17.0" } } ], diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index a8b70a2420..574dbfb6b0 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthHostApp.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/awslabs/aws-crt-swift.git", "state" : { - "revision" : "6feec6c3787877807aa9a00fad09591b96752376", - "version" : "0.6.1" + "revision" : "997904873945e074aaf5c51ea968d9a84684525a", + "version" : "0.13.0" } }, { @@ -32,8 +32,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/awslabs/aws-sdk-swift.git", "state" : { - "revision" : "24bae88a2391fe75da8a940a544d1ef6441f5321", - "version" : "0.13.0" + "revision" : "ace826dbfe96e7e3103fe7f45f815b8a590bcf21", + "version" : "0.26.0" } }, { @@ -57,10 +57,10 @@ { "identity" : "smithy-swift", "kind" : "remoteSourceControl", - "location" : "https://github.com/awslabs/smithy-swift.git", + "location" : "https://github.com/smithy-lang/smithy-swift", "state" : { - "revision" : "7b28da158d92cd06a3549140d43b8fbcf64a94a6", - "version" : "0.15.0" + "revision" : "eed3f3d8e5aa704fcd60bb227b0fc89bf3328c42", + "version" : "0.30.0" } }, { @@ -104,8 +104,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/MaxDesiatov/XMLCoder.git", "state" : { - "revision" : "c438dad94f6a243b411b70a4b4bac54595064808", - "version" : "0.15.0" + "revision" : "80b4a1646399b8e4e0ce80711653476a85bd5e37", + "version" : "0.17.0" } } ], diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift index a77f580fa9..5304a5b5e1 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift @@ -48,15 +48,21 @@ class AuthDeleteUserTests: AWSAuthBaseTest { do { _ = try await AuthSignInHelper.signInUser(username: username, password: password) XCTFail("signIn after account deletion should fail") - } catch { - guard case AuthError.service(_, _, let underlyingError) = error else { - XCTFail("Should produce service error instead of \(String(describing: error))") - return - } - guard case .userNotFound = (underlyingError as? AWSCognitoAuthError) else { - XCTFail("Underlying error should be userNotFound instead of \(String(describing: error))") - return + } catch let error as AuthError { + switch error { + case .service(_, _, let underlying): + XCTAssert( + [.userNotFound, .limitExceeded].contains(underlying as? AWSCognitoAuthError) + ) + default: + XCTFail(""" + Should produce .service error with underlyingError of .userNotFound || .limitExceed + Received: \(error) + """) + } + } catch { + XCTFail("Expected AuthError - received: \(error)") } // Check if the auth session is signed out diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift index 3a2527539a..b1df2d456a 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/DeviceTests/AuthForgetDeviceTests.swift @@ -38,14 +38,12 @@ class AuthForgetDeviceTests: AWSAuthBaseTest { let username = "integTest\(UUID().uuidString)" let password = "P123@\(UUID().uuidString)" - let signInExpectation = asyncExpectation(description: "SignIn event should be fired") + let signInExpectation = expectation(description: "SignIn event should be fired") unsubscribeToken = Amplify.Hub.listen(to: .auth) { payload in switch payload.eventName { case HubPayload.EventName.Auth.signedIn: - Task { - await signInExpectation.fulfill() - } + signInExpectation.fulfill() default: break } @@ -55,7 +53,7 @@ class AuthForgetDeviceTests: AWSAuthBaseTest { username: username, password: password, email: defaultTestEmail) - await waitForExpectations([signInExpectation], timeout: networkTimeout) + await fulfillment(of: [signInExpectation], timeout: networkTimeout) _ = try await Amplify.Auth.rememberDevice() _ = try await Amplify.Auth.forgetDevice() diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift index 0c35eca521..3728939c28 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignInTests/AuthSRPSignInTests.swift @@ -159,13 +159,20 @@ class AuthSRPSignInTests: AWSAuthBaseTest { do { _ = try await Amplify.Auth.signIn(username: "username-doesnot-exist", password: "password") XCTFail("SignIn with unknown user should not succeed") + } catch let error as AuthError { + let underlyingError = error.underlyingError as? AWSCognitoAuthError + switch underlyingError { + case .userNotFound, .limitExceeded: break + default: + XCTFail( + """ + Expected AWSCognitoAuthError.userNotFound || AWSCognitoAuthError.limitExceed + Recevied: \(error) + """ + ) + } } catch { - guard let authError = error as? AuthError, let cognitoError = authError.underlyingError as? AWSCognitoAuthError, - case .userNotFound = cognitoError - else { - XCTFail("Should return userNotFound error") - return - } + XCTFail("Expected `AuthError` - received: \(error)") } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift index 53e6865176..05f8161581 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthResendSignUpCodeTests.swift @@ -23,13 +23,20 @@ class AuthResendSignUpCodeTests: AWSAuthBaseTest { do { _ = try await Amplify.Auth.resendSignUpCode(for: "user-non-exists") XCTFail("resendSignUpCode with non existing user should not return result") - } catch { - guard let authError = error as? AuthError, let cognitoError = authError.underlyingError as? AWSCognitoAuthError, - case .userNotFound = cognitoError else { - print(error) - XCTFail("Should return userNotFound") - return + } catch let error as AuthError { + let underlyingError = error.underlyingError as? AWSCognitoAuthError + switch underlyingError { + case .userNotFound, .limitExceeded: break + default: + XCTFail( + """ + Expected AWSCognitoAuthError.userNotFound || AWSCognitoAuthError.limitExceed + Recevied: \(error) + """ + ) } + } catch { + XCTFail("Expected `AuthError` - received: \(error)") } } } diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift index e637b596c9..7f694195d5 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/SignUpTests/AuthSignUpTests.swift @@ -54,7 +54,7 @@ class AuthSignUpTests: AWSAuthBaseTest { signUpExpectation.fulfill() } } - await waitForExpectations(timeout: 2) + await fulfillment(of: [signUpExpectation], timeout: 5, enforceOrder: false) } // /// Test if user registration is successful. diff --git a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp.xcodeproj/xcshareddata/xcschemes/AuthHostedUIApp.xcscheme b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp.xcodeproj/xcshareddata/xcschemes/AuthHostedUIApp.xcscheme index b919f7e960..bed1ed8b62 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp.xcodeproj/xcshareddata/xcschemes/AuthHostedUIApp.xcscheme +++ b/AmplifyPlugins/Auth/Tests/AuthHostedUIApp/AuthHostedUIApp.xcodeproj/xcshareddata/xcschemes/AuthHostedUIApp.xcscheme @@ -30,8 +30,7 @@ shouldAutocreateTestPlan = "YES"> + skipped = "NO"> From a76284a55880354a9c5a1b1f289fecf62155cb62 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Tue, 10 Oct 2023 09:59:02 -0400 Subject: [PATCH 23/23] fix: add AuthErrorConvertible conformance to CommonRuntimeError (#3287) --- ...monRunTimeError+AuthErrorConvertible.swift | 42 +++++++++++++++++++ ...uthenticationProviderDeleteUserTests.swift | 4 -- .../AuthDeleteUserTests.swift | 1 - .../ClientRuntimeFoundationBridge.swift | 2 - 4 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift new file mode 100644 index 0000000000..8244b277a5 --- /dev/null +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Service/ErrorMapping/CommonRunTimeError+AuthErrorConvertible.swift @@ -0,0 +1,42 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import Amplify +import AwsCommonRuntimeKit +import AwsCIo +import AwsCHttp + +private let connectivityErrorCodes: Set = [ + AWS_ERROR_HTTP_CONNECTION_CLOSED.rawValue, + AWS_ERROR_HTTP_SERVER_CLOSED.rawValue, + AWS_IO_DNS_INVALID_NAME.rawValue, + AWS_IO_DNS_NO_ADDRESS_FOR_HOST.rawValue, + AWS_IO_DNS_QUERY_FAILED.rawValue, + AWS_IO_SOCKET_CONNECT_ABORTED.rawValue, + AWS_IO_SOCKET_CONNECTION_REFUSED.rawValue, + AWS_IO_SOCKET_CLOSED.rawValue, + AWS_IO_SOCKET_NETWORK_DOWN.rawValue, + AWS_IO_SOCKET_NO_ROUTE_TO_HOST.rawValue, + AWS_IO_SOCKET_NOT_CONNECTED.rawValue, + AWS_IO_SOCKET_TIMEOUT.rawValue, + AWS_IO_TLS_NEGOTIATION_TIMEOUT.rawValue, + UInt32(AWS_HTTP_STATUS_CODE_408_REQUEST_TIMEOUT.rawValue) +] + +extension CommonRunTimeError: AuthErrorConvertible { + var authError: AuthError { + let error: CRTError + switch self { case .crtError(let crtError): error = crtError } + + if connectivityErrorCodes.contains(UInt32(error.code)) { + return .service(error.name, error.message, AWSCognitoAuthError.network) + } else { + return .unknown("\(error.name) - \(error.message)", self) + } + } +} diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift index c24e5357ba..d665ea8881 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/TaskTests/ClientBehaviorTests/AuthenticationProviderDeleteUserTests.swift @@ -77,8 +77,6 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { /// - I should get a .service error with .network as underlying error /// func testOfflineDeleteUser() async throws { - // TODO: How are client side retry errors now modeled? - throw XCTSkip() mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) @@ -113,8 +111,6 @@ class AuthenticationProviderDeleteUserTests: BasePluginTest { /// - I should get a valid response for the second call /// func testOfflineDeleteUserAndRetry() async throws { - // TODO: How are client side retry errors now modeled? - throw XCTSkip() mockIdentityProvider = MockIdentityProvider( mockRevokeTokenResponse: { _ in try await RevokeTokenOutputResponse(httpResponse: .init(body: .empty, statusCode: .ok)) diff --git a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift index 5304a5b5e1..a7d09a8796 100644 --- a/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift +++ b/AmplifyPlugins/Auth/Tests/AuthHostApp/AuthIntegrationTests/AuthDeleteUserTests/AuthDeleteUserTests.swift @@ -59,7 +59,6 @@ class AuthDeleteUserTests: AWSAuthBaseTest { Should produce .service error with underlyingError of .userNotFound || .limitExceed Received: \(error) """) - } } catch { XCTFail("Expected AuthError - received: \(error)") diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift index 763e43ac31..306165b134 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Utils/CustomHttpClientEngine/ClientRuntimeFoundationBridge.swift @@ -45,8 +45,6 @@ extension ClientRuntime.HttpResponse { convenience init(httpURLResponse: HTTPURLResponse, data: Data) throws { let headers = Self.headers(from: httpURLResponse.allHeaderFields) - // TODO: double check if this works as expected - // Previously this needed to be `HttpBody.stream()` let body = HttpBody.data(data) guard let statusCode = HttpStatusCode(rawValue: httpURLResponse.statusCode) else {