Skip to content

Commit

Permalink
Merge branch 'main' into mattcreaser/delete-conflict
Browse files Browse the repository at this point in the history
  • Loading branch information
tylerjroach authored Jul 26, 2023
2 parents 183b520 + ce2bf64 commit 6f9923c
Show file tree
Hide file tree
Showing 9 changed files with 55 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,12 +103,13 @@ internal class AuthEnvironment internal constructor(
}

suspend fun getDeviceMetadata(username: String): DeviceMetadata.Metadata? {
val deviceCredentials =
var deviceCredentials =
credentialStoreClient.loadCredentials(CredentialType.Device(username)) as? AmplifyCredential.DeviceData
if (deviceCredentials == null) {
logger.warn("loadCredentials returned unexpected AmplifyCredential Type.")
deviceCredentials = AmplifyCredential.DeviceData(DeviceMetadata.Empty)
}
return (deviceCredentials as AmplifyCredential.DeviceData).deviceMetadata as? DeviceMetadata.Metadata
return deviceCredentials.deviceMetadata as? DeviceMetadata.Metadata
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ import com.amplifyframework.auth.cognito.result.RevokeTokenError
import com.amplifyframework.auth.cognito.usecases.ResetPasswordUseCase
import com.amplifyframework.auth.exceptions.ConfigurationException
import com.amplifyframework.auth.exceptions.InvalidStateException
import com.amplifyframework.auth.exceptions.NotAuthorizedException
import com.amplifyframework.auth.exceptions.ServiceException
import com.amplifyframework.auth.exceptions.SessionExpiredException
import com.amplifyframework.auth.exceptions.SignedOutException
import com.amplifyframework.auth.exceptions.UnknownException
Expand Down Expand Up @@ -1053,9 +1055,15 @@ internal class RealAWSCognitoAuthPlugin(
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(error.exception))
sendHubEvent(AuthChannelEventName.SESSION_EXPIRED.toString())
}
is ServiceException -> {
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(error.exception))
}
is NotAuthorizedException -> {
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(error.exception))
}
else -> {
val errorResult = UnknownException("Fetch auth session failed.", error)
onSuccess.accept(error.amplifyCredential.getCognitoSession(errorResult))
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(errorResult))
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import com.amplifyframework.statemachine.codegen.actions.FetchAuthSessionActions
import com.amplifyframework.statemachine.codegen.data.AWSCredentials
import com.amplifyframework.statemachine.codegen.data.AmplifyCredential
import com.amplifyframework.statemachine.codegen.data.CognitoUserPoolTokens
import com.amplifyframework.statemachine.codegen.data.DeviceMetadata
import com.amplifyframework.statemachine.codegen.data.LoginsMapProvider
import com.amplifyframework.statemachine.codegen.data.SignedInData
import com.amplifyframework.statemachine.codegen.events.AuthorizationEvent
Expand Down Expand Up @@ -62,7 +63,7 @@ internal object FetchAuthSessionCognitoActions : FetchAuthSessionActions {
secretHash?.let { authParameters[KEY_SECRET_HASH] = it }

val encodedContextData = getUserContextData(username)
val deviceMetadata = getDeviceMetadata(username)
val deviceMetadata: DeviceMetadata.Metadata? = getDeviceMetadata(username)
deviceMetadata?.let { authParameters[KEY_DEVICE_KEY] = it.deviceKey }
val pinpointEndpointId = getPinpointEndpointId()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,6 @@ internal object SignInChallengeCognitoActions : SignInChallengeActions {
dispatcher.send(evt)
}

override fun resetToWaitingForAnswer(
event: SignInChallengeEvent.EventType.ThrowError,
challenge: AuthChallenge
): Action = Action<AuthEnvironment>("ResetToWaitingForAnswer") { id, dispatcher ->
logger.verbose("$id Starting execution")
dispatcher.send(SignInChallengeEvent(SignInChallengeEvent.EventType.WaitForAnswer(challenge)))
}

private fun getChallengeResponseKey(challengeName: String): String? {
return when (ChallengeNameType.fromValue(challengeName)) {
is ChallengeNameType.SmsMfa -> "SMS_MFA_CODE"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
*/
package com.amplifyframework.auth.cognito.exceptions.service

import com.amplifyframework.auth.exceptions.ServiceException
import com.amplifyframework.auth.AuthException

/**
* Could not perform the action because the token was unable to be parsed
* @param message Explains the reason for the exception
*/
open class InvalidGrantException(message: String) :
ServiceException(message, TODO_RECOVERY_SUGGESTION)
open class InvalidGrantException(message: String, description: String?) :
AuthException(message, description ?: TODO_RECOVERY_SUGGESTION)
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import com.amplifyframework.AmplifyException
import com.amplifyframework.auth.cognito.exceptions.service.InvalidGrantException
import com.amplifyframework.auth.cognito.exceptions.service.ParseTokenException
import com.amplifyframework.auth.exceptions.ServiceException
import com.amplifyframework.auth.exceptions.SessionExpiredException
import com.amplifyframework.statemachine.codegen.data.CognitoUserPoolTokens
import java.io.BufferedReader
import java.io.DataOutputStream
Expand Down Expand Up @@ -66,6 +67,7 @@ internal object HostedUIHttpHelper {
connection.errorStream
}
val responseString = responseStream.bufferedReader().use(BufferedReader::readText)

return parseTokenResponse(responseString)
} else {
throw ServiceException(
Expand All @@ -86,7 +88,7 @@ internal object HostedUIHttpHelper {

response.error?.let {
if (it == "invalid_grant") {
throw InvalidGrantException(it)
throw SessionExpiredException(it, cause = InvalidGrantException(it, response.errorDescription))
} else {
throw ServiceException(it, AmplifyException.TODO_RECOVERY_SUGGESTION)
}
Expand All @@ -99,11 +101,13 @@ internal object HostedUIHttpHelper {
expiration = response.expiration
)
} catch (e: Exception) {
throw ServiceException(
message = e.message ?: "An unknown service error has occurred",
recoverySuggestion = AmplifyException.TODO_RECOVERY_SUGGESTION,
cause = e
)
if (e !is SessionExpiredException && e !is ServiceException) {
throw ServiceException(
message = e.message ?: "An unknown service error has occurred",
recoverySuggestion = AmplifyException.TODO_RECOVERY_SUGGESTION,
cause = e
)
} else throw e
}
}
}
Expand All @@ -114,7 +118,8 @@ internal class FetchTokenResponse(
@SerialName("id_token") val idToken: String? = null,
@SerialName("refresh_token") val refreshToken: String? = null,
@SerialName("expires_in") private val expiresIn: Int? = null,
@SerialName("error") val error: String? = null
@SerialName("error") val error: String? = null,
@SerialName("error_description") val errorDescription: String? = null
) {
val expiration = expiresIn?.let { Instant.now().plus(it.seconds).epochSeconds }
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,4 @@ internal interface SignInChallengeActions {
event: SignInChallengeEvent.EventType.VerifyChallengeAnswer,
challenge: AuthChallenge
): Action
fun resetToWaitingForAnswer(
event: SignInChallengeEvent.EventType.ThrowError,
challenge: AuthChallenge
): Action
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,27 @@ object FetchAuthSessionTestCaseGenerator : SerializableProvider {
).toJsonElement()
)

private val mockedIdentityIdResponse = MockResponse(
CognitoType.CognitoIdentity,
"getId",
ResponseType.Success,
mapOf("identityId" to "someIdentityId").toJsonElement()
)

private val mockedAWSCredentialsResponse = MockResponse(
CognitoType.CognitoIdentity,
"getCredentialsForIdentity",
ResponseType.Success,
mapOf(
"credentials" to mapOf(
"accessKeyId" to "someAccessKey",
"secretKey" to "someSecretKey",
"sessionToken" to AuthStateJsonGenerator.dummyToken,
"expiration" to 2342134
)
).toJsonElement()
)

private val expectedSuccess = AWSCognitoAuthSession(
isSignedIn = true,
identityIdResult = AuthSessionResult.success("someIdentityId"),
Expand Down Expand Up @@ -94,15 +115,17 @@ object FetchAuthSessionTestCaseGenerator : SerializableProvider {

private val refreshSuccessCase: FeatureTestCase = baseCase.copy(
description = "AuthSession object is successfully returned after refresh",
preConditions = baseCase.preConditions.copy(
preConditions = PreConditions(
"authconfiguration.json",
"SignedIn_SessionEstablished.json",
mockedResponses = listOf(mockedInitiateAuthResponse)
),
api = API(
name = AuthAPI.fetchAuthSession,
params = JsonObject(emptyMap()),
options = mapOf("forceRefresh" to true).toJsonElement(),
JsonObject(emptyMap())
),
validations = baseCase.validations
validations = listOf(apiReturnValidation)
)

private val identityPoolCase: FeatureTestCase = baseCase.copy(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
"params": {
},
"options": {
"forceRefresh": true
}
},
"validations": [
Expand Down

0 comments on commit 6f9923c

Please sign in to comment.