mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cognito): add GetUserAuthFactors (#4764)
* feat(cognito): add GetUserAuthFactors * fix(cognito): refuse access tokens with no scope claim where a scope is required * fix(cognito): use AWS's message for a missing access-token scope
This commit is contained in:
1 parent
a0be062f9f
commit
31038ee2a4
9 files changed
+666
-22
No files matched your search
+376
@@ -0,0 +1,376 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* GetUserAuthFactors over the JSON 1.1 wire protocol. The pools use email as a username
|
||||
* attribute, so each user's username is its generated sub, which is what AWS returns as
|
||||
* {@code Username} for such a pool.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CognitoGetUserAuthFactorsIntegrationTest {
|
||||
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final Pattern SIX_DIGIT_CODE = Pattern.compile("\\b(\\d{6})\\b");
|
||||
private static final String PASSWORD = "Factors1234!";
|
||||
|
||||
private static String passwordOnlyPoolId;
|
||||
private static String passwordOnlyClientId;
|
||||
private static String passwordlessPoolId;
|
||||
private static String passwordlessClientId;
|
||||
|
||||
@Inject
|
||||
Clock clock;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void setUpPoolsAndClients() throws Exception {
|
||||
passwordOnlyPoolId = createPool("AuthFactorsPasswordOnlyPool", "[\"PASSWORD\"]");
|
||||
passwordOnlyClientId = createClient(passwordOnlyPoolId);
|
||||
passwordlessPoolId = createPool("AuthFactorsPasswordlessPool", "[\"PASSWORD\", \"EMAIL_OTP\"]");
|
||||
passwordlessClientId = createClient(passwordlessPoolId);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void passwordAndVerifiedEmailAreReportedEvenWhenThePoolAllowsOnlyPassword() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(passwordOnlyPoolId, email, """
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "email_verified", "Value": "true" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(passwordOnlyClientId, email);
|
||||
String username = cognitoJson("GetUser", accessTokenBody(accessToken)).path("Username").asText();
|
||||
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Username", equalTo(username))
|
||||
.body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP"))
|
||||
.body("$", not(hasKey("PreferredMfaSetting")))
|
||||
.body("$", not(hasKey("UserMFASettingList")));
|
||||
assertNotEquals(email, username, "an email-username pool keys the user by its sub");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void unverifiedEmailIsNotAFactor() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(passwordOnlyPoolId, email, """
|
||||
{ "Name": "email", "Value": "%s" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(passwordOnlyClientId, email);
|
||||
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ConfiguredUserAuthFactors", contains("PASSWORD"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void verifiedPhoneNumberAddsSmsOtpAfterEmailOtp() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(passwordOnlyPoolId, email, """
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "email_verified", "Value": "true" },
|
||||
{ "Name": "phone_number", "Value": "+15555550123" },
|
||||
{ "Name": "phone_number_verified", "Value": "true" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(passwordOnlyClientId, email);
|
||||
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP", "SMS_OTP"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void passwordlessUserSignedInWithEmailOtpHasNoPasswordFactor() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
cognitoAction("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"MessageAction": "SUPPRESS",
|
||||
"UserAttributes": [
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "email_verified", "Value": "true" }
|
||||
]
|
||||
}
|
||||
""".formatted(passwordlessPoolId, email, email))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given().delete("/_aws/ses").then().statusCode(200);
|
||||
JsonNode challenge = cognitoJson("InitiateAuth", """
|
||||
{
|
||||
"ClientId": "%s",
|
||||
"AuthFlow": "USER_AUTH",
|
||||
"AuthParameters": { "USERNAME": "%s", "PREFERRED_CHALLENGE": "EMAIL_OTP" }
|
||||
}
|
||||
""".formatted(passwordlessClientId, email));
|
||||
assertEquals("EMAIL_OTP", challenge.path("ChallengeName").asText());
|
||||
JsonNode auth = cognitoJson("RespondToAuthChallenge", """
|
||||
{
|
||||
"ClientId": "%s",
|
||||
"ChallengeName": "EMAIL_OTP",
|
||||
"Session": "%s",
|
||||
"ChallengeResponses": { "USERNAME": "%s", "EMAIL_OTP_CODE": "%s" }
|
||||
}
|
||||
""".formatted(passwordlessClientId, challenge.path("Session").asText(),
|
||||
challenge.path("ChallengeParameters").path("USERNAME").asText(),
|
||||
fetchLatestSesCode(email)));
|
||||
String accessToken = auth.path("AuthenticationResult").path("AccessToken").asText();
|
||||
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ConfiguredUserAuthFactors", contains("EMAIL_OTP"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void emailMfaPreferenceIsReportedAsMfaSettings() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(passwordOnlyPoolId, email, """
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "email_verified", "Value": "true" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(passwordOnlyClientId, email);
|
||||
|
||||
cognitoAction("SetUserMFAPreference", """
|
||||
{ "AccessToken": "%s", "EmailMfaSettings": { "Enabled": true } }
|
||||
""".formatted(accessToken))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("UserMFASettingList", contains("EMAIL_OTP"))
|
||||
.body("$", not(hasKey("PreferredMfaSetting")));
|
||||
|
||||
cognitoAction("SetUserMFAPreference", """
|
||||
{ "AccessToken": "%s", "EmailMfaSettings": { "Enabled": true, "PreferredMfa": true } }
|
||||
""".formatted(accessToken))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP"))
|
||||
.body("PreferredMfaSetting", equalTo("EMAIL_OTP"))
|
||||
.body("UserMFASettingList", contains("EMAIL_OTP"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void invalidAccessTokenIsRejected() {
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody("not-a-valid-token"))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Invalid Access Token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void globallySignedOutTokenIsRejectedLikeGetUser() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(passwordOnlyPoolId, email, """
|
||||
{ "Name": "email", "Value": "%s" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(passwordOnlyClientId, email);
|
||||
cognitoAction("GlobalSignOut", accessTokenBody(accessToken)).then().statusCode(200);
|
||||
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token has been revoked"));
|
||||
cognitoAction("GetUser", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token has been revoked"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void deletedUserTokenIsRejectedLikeGetUser() throws Exception {
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(passwordOnlyPoolId, email, """
|
||||
{ "Name": "email", "Value": "%s" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(passwordOnlyClientId, email);
|
||||
cognitoAction("AdminDeleteUser", """
|
||||
{ "UserPoolId": "%s", "Username": "%s" }
|
||||
""".formatted(passwordOnlyPoolId, email))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UserNotFoundException"));
|
||||
cognitoAction("GetUser", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("UserNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void verifiedSoftwareTokenIsReportedLastButAnUnverifiedOneIsNot() throws Exception {
|
||||
String poolId = createPool("AuthFactorsTotpPool", "[\"PASSWORD\"]");
|
||||
cognitoAction("SetUserPoolMfaConfig", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"MfaConfiguration": "OPTIONAL",
|
||||
"SoftwareTokenMfaConfiguration": { "Enabled": true }
|
||||
}
|
||||
""".formatted(poolId))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
String clientId = createClient(poolId);
|
||||
String email = uniqueEmail();
|
||||
createUserWithPassword(poolId, email, """
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "email_verified", "Value": "true" },
|
||||
{ "Name": "phone_number", "Value": "+15555550124" },
|
||||
{ "Name": "phone_number_verified", "Value": "true" }
|
||||
""".formatted(email));
|
||||
String accessToken = signInWithPassword(clientId, email);
|
||||
|
||||
String secret = cognitoJson("AssociateSoftwareToken", accessTokenBody(accessToken))
|
||||
.path("SecretCode").asText();
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ConfiguredUserAuthFactors", contains("PASSWORD", "EMAIL_OTP", "SMS_OTP"));
|
||||
|
||||
JsonNode verified = cognitoJson("VerifySoftwareToken", """
|
||||
{ "AccessToken": "%s", "UserCode": "%s" }
|
||||
""".formatted(accessToken, CognitoTotp.code(secret, clock.instant())));
|
||||
assertEquals("SUCCESS", verified.path("Status").asText());
|
||||
cognitoAction("GetUserAuthFactors", accessTokenBody(accessToken))
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ConfiguredUserAuthFactors",
|
||||
contains("PASSWORD", "EMAIL_OTP", "SMS_OTP", "SOFTWARE_TOKEN"));
|
||||
}
|
||||
|
||||
private static String createPool(String name, String allowedFirstAuthFactors) throws Exception {
|
||||
JsonNode response = cognitoJson("CreateUserPool", """
|
||||
{
|
||||
"PoolName": "%s",
|
||||
"UsernameAttributes": ["email"],
|
||||
"UserPoolTier": "ESSENTIALS",
|
||||
"Policies": { "SignInPolicy": { "AllowedFirstAuthFactors": %s } }
|
||||
}
|
||||
""".formatted(name, allowedFirstAuthFactors));
|
||||
return response.path("UserPool").path("Id").asText();
|
||||
}
|
||||
|
||||
private static String createClient(String poolId) throws Exception {
|
||||
JsonNode response = cognitoJson("CreateUserPoolClient", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"ClientName": "auth-factors-client",
|
||||
"ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_USER_AUTH"]
|
||||
}
|
||||
""".formatted(poolId));
|
||||
return response.path("UserPoolClient").path("ClientId").asText();
|
||||
}
|
||||
|
||||
private static void createUserWithPassword(String poolId, String email, String attributes) {
|
||||
cognitoAction("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"MessageAction": "SUPPRESS",
|
||||
"UserAttributes": [ %s ]
|
||||
}
|
||||
""".formatted(poolId, email, attributes))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
cognitoAction("AdminSetUserPassword", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"Password": "%s",
|
||||
"Permanent": true
|
||||
}
|
||||
""".formatted(poolId, email, PASSWORD))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String signInWithPassword(String clientId, String email) throws Exception {
|
||||
JsonNode auth = cognitoJson("InitiateAuth", """
|
||||
{
|
||||
"ClientId": "%s",
|
||||
"AuthFlow": "USER_PASSWORD_AUTH",
|
||||
"AuthParameters": { "USERNAME": "%s", "PASSWORD": "%s" }
|
||||
}
|
||||
""".formatted(clientId, email, PASSWORD));
|
||||
return auth.path("AuthenticationResult").path("AccessToken").asText();
|
||||
}
|
||||
|
||||
private static String accessTokenBody(String accessToken) {
|
||||
return """
|
||||
{ "AccessToken": "%s" }
|
||||
""".formatted(accessToken);
|
||||
}
|
||||
|
||||
private static String uniqueEmail() {
|
||||
return "factors+" + UUID.randomUUID() + "@example.com";
|
||||
}
|
||||
|
||||
private static String fetchLatestSesCode(String recipient) throws Exception {
|
||||
String response = given()
|
||||
.queryParam("email", recipient)
|
||||
.get("/_aws/ses")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.asString();
|
||||
JsonNode messages = JSON.readTree(response).path("messages");
|
||||
assertTrue(messages.isArray() && !messages.isEmpty(), "an EMAIL_OTP code should have been sent");
|
||||
Matcher matcher = SIX_DIGIT_CODE.matcher(messages.get(0).path("Body").path("text_part").asText());
|
||||
assertTrue(matcher.find(), "the EMAIL_OTP message should carry a six-digit code");
|
||||
return matcher.group(1);
|
||||
}
|
||||
}
|
||||
+19
@@ -709,6 +709,25 @@ class CognitoLambdaTriggersTest {
|
||||
assertTrue(!tokens.contains("phone"), "phone dropped by scopesToSuppress");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void preTokenGenerationV2SuppressingEveryScopeRemovesTheScopeClaim() throws Exception {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createClient(pool);
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("claimsAndScopeOverrideDetails", Map.of(
|
||||
"accessTokenGeneration", Map.of(
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin"))))));
|
||||
|
||||
Map<String, Object> result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
|
||||
String accessToken = (String) ((Map<String, Object>) result.get("AuthenticationResult")).get("AccessToken");
|
||||
|
||||
Map<String, Object> claims = MAPPER.readValue(decodeJwtPayload(accessToken), new TypeReference<>() {});
|
||||
assertFalse(claims.containsKey("scope"), "suppressing the only scope leaves no scope claim: " + claims);
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void preTokenGenerationV2ResolvesArnFromPreTokenGenerationConfigKey() {
|
||||
|
||||
+89
-2
@@ -257,6 +257,75 @@ class CognitoManagedLoginIntegrationTest {
|
||||
"admin/superuser is not in the client's AllowedOAuthScopes, so the trigger never sees it");
|
||||
}
|
||||
|
||||
/**
|
||||
* GetUserAuthFactors needs {@code aws.cognito.signin.user.admin} in the access token's scope.
|
||||
* Floci stamps that scope on every code-grant access token whatever the request asked for, so a
|
||||
* V2 trigger reshapes this token's scope to the {@code openid email} the request named.
|
||||
*/
|
||||
@Test
|
||||
void codeGrantAccessTokenWithoutTheAdminScopeCannotReadAuthFactors() throws Exception {
|
||||
String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of(
|
||||
"scopesToAdd", List.of("openid", "email"),
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin")));
|
||||
assertEquals("openid email", jwtPayload(accessToken).path("scope").asText());
|
||||
|
||||
cognitoAction("GetUserAuthFactors", """
|
||||
{"AccessToken":"%s"}
|
||||
""".formatted(accessToken))
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token does not have required scopes"));
|
||||
}
|
||||
|
||||
/** A trigger that suppresses the token's only scope leaves no scope claim, which grants nothing. */
|
||||
@Test
|
||||
void codeGrantAccessTokenWithEveryScopeSuppressedCannotReadAuthFactors() throws Exception {
|
||||
String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of(
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin")));
|
||||
assertFalse(jwtPayload(accessToken).has("scope"));
|
||||
|
||||
cognitoAction("GetUserAuthFactors", """
|
||||
{"AccessToken":"%s"}
|
||||
""".formatted(accessToken))
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token does not have required scopes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeGrantAccessTokenWithEveryScopeSuppressedCannotVerifyAnAttribute() throws Exception {
|
||||
String accessToken = codeGrantAccessTokenReshapedByTrigger(Map.of(
|
||||
"scopesToSuppress", List.of("aws.cognito.signin.user.admin")));
|
||||
assertFalse(jwtPayload(accessToken).has("scope"));
|
||||
|
||||
cognitoAction("VerifyUserAttribute", """
|
||||
{"AccessToken":"%s","AttributeName":"email","Code":"123456"}
|
||||
""".formatted(accessToken))
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("NotAuthorizedException"))
|
||||
.body("message", equalTo("Access Token does not have required scopes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeGrantAccessTokenWithTheAdminScopeReadsAuthFactors() throws Exception {
|
||||
String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginAdminScopePool\"}")
|
||||
.path("UserPool").path("Id").asText();
|
||||
Pool pool = withUser(poolId,
|
||||
codeClient(poolId, "\"openid\",\"email\",\"aws.cognito.signin.user.admin\""),
|
||||
"user-" + System.nanoTime());
|
||||
Map<String, String> query = authorizeRequest(pool.clientId());
|
||||
query.put("scope", "openid email aws.cognito.signin.user.admin");
|
||||
String accessToken = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER)
|
||||
.path("access_token");
|
||||
|
||||
cognitoAction("GetUserAuthFactors", """
|
||||
{"AccessToken":"%s"}
|
||||
""".formatted(accessToken))
|
||||
.then().statusCode(200)
|
||||
.body("Username", equalTo(pool.username()))
|
||||
.body("ConfiguredUserAuthFactors", equalTo(List.of("PASSWORD")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeIsRefusedWithAWrongOrMissingVerifierAndAWrongOneSpendsIt() throws Exception {
|
||||
Pool pool = newPool();
|
||||
@@ -527,17 +596,35 @@ class CognitoManagedLoginIntegrationTest {
|
||||
return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs a new pool's user in through the code grant, with a V2 PreTokenGeneration trigger
|
||||
* answering {@code accessTokenGeneration}, and returns the access token it mints.
|
||||
*/
|
||||
private String codeGrantAccessTokenReshapedByTrigger(Map<String, Object> accessTokenGeneration) throws Exception {
|
||||
Pool pool = newPoolWithPreTokenGenerationTrigger();
|
||||
when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), any(), any()))
|
||||
.thenReturn(triggerResponse(Map.of("claimsAndScopeOverrideDetails",
|
||||
Map.of("accessTokenGeneration", accessTokenGeneration))));
|
||||
return redeem(null, pool.clientId(),
|
||||
code(signIn(null, pool, authorizeRequest(pool.clientId()))), VERIFIER).path("access_token");
|
||||
}
|
||||
|
||||
/** A successful trigger invocation returning {@code response} as the Lambda's payload. */
|
||||
private static InvokeResult triggerResponse(Map<String, Object> response) throws Exception {
|
||||
return new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of("response", response)), null, "req-id");
|
||||
}
|
||||
|
||||
private static String codeClient(String poolId) throws Exception {
|
||||
return codeClient(poolId, "\"openid\",\"email\"");
|
||||
}
|
||||
|
||||
/** {@code allowedScopes} is the body of the AllowedOAuthScopes JSON array. */
|
||||
private static String codeClient(String poolId, String allowedScopes) throws Exception {
|
||||
return cognitoJson("CreateUserPoolClient", """
|
||||
{"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true,
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],
|
||||
"AllowedOAuthFlows":["code"],"AllowedOAuthScopes":[%s],"CallbackURLs":["%s"],
|
||||
"LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]}
|
||||
""".formatted(poolId, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText();
|
||||
""".formatted(poolId, allowedScopes, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText();
|
||||
}
|
||||
|
||||
private static Pool withUser(String poolId, String clientId, String username) throws Exception {
|
||||
|
||||
@@ -4953,6 +4953,68 @@ class CognitoServiceTest {
|
||||
assertThrows(AwsException.class, () -> service.getUserAttributeVerificationCode(invalid, "email"));
|
||||
assertThrows(AwsException.class, () -> service.globalSignOut(invalid));
|
||||
assertThrows(AwsException.class, () -> service.setUserMFAPreference(invalid, true, false));
|
||||
assertThrows(AwsException.class, () -> service.getUserAuthFactors(invalid));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserAuthFactors_userWithoutPassword_omitsPasswordFactor() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "PasswordlessPool"), "us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "bob",
|
||||
Map.of("email", "bob@example.com", "email_verified", "true"), null);
|
||||
String accessToken = service.generateSignedJwt(user, pool, "access", client, null, null);
|
||||
|
||||
Map<String, Object> result = service.getUserAuthFactors(accessToken);
|
||||
|
||||
assertEquals("bob", result.get("Username"));
|
||||
assertEquals(List.of("EMAIL_OTP"), result.get("ConfiguredUserAuthFactors"),
|
||||
"a verified email is a factor whether or not Floci's code delivery is wired");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserAuthFactors_userWithNoFactors_returnsOnlyUsername() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "NoFactorPool"), "us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "carol",
|
||||
Map.of("email", "carol@example.com"), null);
|
||||
String accessToken = service.generateSignedJwt(user, pool, "access", client, null, null);
|
||||
|
||||
assertEquals(Map.of("Username", "carol"), service.getUserAuthFactors(accessToken));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserAuthFactors_accessTokenWithoutAdminScope_isRejected() {
|
||||
UserPool pool = createPoolAndUser();
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
String accessToken = service.generateSignedJwt(user, pool, "access", client,
|
||||
new CognitoService.ClaimsOverride(null, null, null, null,
|
||||
List.of("openid", "email"), List.of("aws.cognito.signin.user.admin"),
|
||||
null, null, null));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.getUserAuthFactors(accessToken));
|
||||
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("Access Token does not have required scopes", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUserAuthFactors_accessTokenWithNoScopeClaim_isRejected() {
|
||||
UserPool pool = createPoolAndUser();
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
|
||||
String accessToken = service.generateSignedJwt(user, pool, "access", client,
|
||||
new CognitoService.ClaimsOverride(null, null, null, List.of("scope"),
|
||||
null, null, null, null, null));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> service.getUserAuthFactors(accessToken));
|
||||
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("Access Token does not have required scopes", ex.getMessage());
|
||||
}
|
||||
|
||||
private void assertInvalidAccessToken(String token, String reason) {
|
||||
|
||||
Reference in new issue
Block a user