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:
jwoa95 authored and GitHub committed 2026-09-30 21:45:10 -05:00
1 parent a0be062f9f
commit 31038ee2a4
9 files changed
+666 -22

No files matched your search

@@ -1014,25 +1014,57 @@ final class CognitoAuthFlowHandler {
/** The set of USER_AUTH challenges this user currently qualifies for. */
private List<String> availableUserAuthChallenges(CognitoUser user) {
List<String> available = new ArrayList<>();
if (user.getPasswordHash() != null) {
if (hasPassword(user)) {
available.add("PASSWORD");
}
if (user.getSrpVerifier() != null) {
available.add("PASSWORD_SRP");
}
Map<String, String> attrs = user.getAttributes();
if (attrs != null && service.verificationServicesConfigured()) {
if (Boolean.parseBoolean(attrs.getOrDefault("email_verified", "false")) && attrs.get("email") != null) {
if (service.verificationServicesConfigured()) {
if (hasVerifiedAttribute(user, "email")) {
available.add("EMAIL_OTP");
}
if (Boolean.parseBoolean(attrs.getOrDefault("phone_number_verified", "false"))
&& attrs.get("phone_number") != null) {
if (hasVerifiedAttribute(user, "phone_number")) {
available.add("SMS_OTP");
}
}
return available;
}
/**
* The sign-in factors {@code user} has set up, as GetUserAuthFactors reports them, in the
* {@code AuthFactorType} enum's order. AWS lists what the user holds, not what the pool's
* {@code AllowedFirstAuthFactors} permits, so neither that policy nor Floci's code-delivery
* wiring filters this list. {@code WEB_AUTHN} never appears: Floci stores no passkeys.
*/
List<String> configuredUserAuthFactors(CognitoUser user) {
List<String> factors = new ArrayList<>();
if (hasPassword(user)) {
factors.add("PASSWORD");
}
if (hasVerifiedAttribute(user, "email")) {
factors.add("EMAIL_OTP");
}
if (hasVerifiedAttribute(user, "phone_number")) {
factors.add("SMS_OTP");
}
if (user.getSoftwareTokenMfaSecret() != null) {
factors.add("SOFTWARE_TOKEN");
}
return factors;
}
private static boolean hasPassword(CognitoUser user) {
return user.getPasswordHash() != null;
}
private static boolean hasVerifiedAttribute(CognitoUser user, String attributeName) {
Map<String, String> attrs = user.getAttributes();
return attrs != null
&& Boolean.parseBoolean(attrs.getOrDefault(attributeName + "_verified", "false"))
&& attrs.get(attributeName) != null;
}
private void requireSignInEligible(CognitoUser user) {
if (!user.isEnabled()) {
throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
@@ -105,6 +105,7 @@ public class CognitoJsonHandler {
case "ForgotPassword" -> handleForgotPassword(request);
case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);
case "GetUser" -> handleGetUser(request);
case "GetUserAuthFactors" -> handleGetUserAuthFactors(request);
case "GetUserAttributeVerificationCode" -> handleGetUserAttributeVerificationCode(request);
case "VerifyUserAttribute" -> handleVerifyUserAttribute(request);
case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);
@@ -1023,6 +1024,11 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.valueToTree(result)).build();
}
private Response handleGetUserAuthFactors(JsonNode request) {
Map<String, Object> result = service.getUserAuthFactors(request.path("AccessToken").asText());
return Response.ok(objectMapper.valueToTree(result)).build();
}
private Response handleGetUserAttributeVerificationCode(JsonNode request) {
Map<String, Object> deliveryDetails = service.getUserAttributeVerificationCode(
request.path("AccessToken").asText(),
@@ -3091,6 +3091,41 @@ public class CognitoService implements ResourceProvider {
return result;
}
/**
* GetUserAuthFactors. The MFA members come from the email MFA preference, the one per-user
* MFA setting Floci stores; SetUserMFAPreference accepts SMS and software-token settings
* without keeping them.
*/
public Map<String, Object> getUserAuthFactors(String accessToken) {
VerifiedAccessToken token;
try {
token = verifyAccessToken(accessToken);
} catch (AwsException e) {
if ("NotAuthorizedException".equals(e.getErrorCode())
&& INVALID_ACCESS_TOKEN_MESSAGE.equals(e.getMessage())) {
throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400);
}
throw e;
}
requireScope(accessToken, "aws.cognito.signin.user.admin");
CognitoUser user = adminGetUser(token.poolId(), token.username());
Map<String, Object> result = new LinkedHashMap<>();
result.put("Username", user.getUsername());
List<String> factors = authFlowHandler.configuredUserAuthFactors(user);
if (!factors.isEmpty()) {
result.put("ConfiguredUserAuthFactors", factors);
}
EmailMfaSettings emailMfa = user.getEmailMfaSettings();
if (emailMfa != null && emailMfa.isEnabled()) {
if (emailMfa.isPreferredMfa()) {
result.put("PreferredMfaSetting", "EMAIL_OTP");
}
result.put("UserMFASettingList", List.of("EMAIL_OTP"));
}
return result;
}
public Map<String, Object> getUserAttributeVerificationCode(String accessToken, String attributeName) {
VerifiedAccessToken token;
try {
@@ -3692,7 +3727,11 @@ public class CognitoService implements ResourceProvider {
if (override.scopesToAdd() != null) {
for (String s : override.scopesToAdd()) if (!current.contains(s)) current.add(s);
}
if (!current.isEmpty()) claims.put("scope", String.join(" ", current));
if (current.isEmpty()) {
claims.remove("scope");
} else {
claims.put("scope", String.join(" ", current));
}
}
}
@@ -4575,39 +4614,40 @@ public class CognitoService implements ResourceProvider {
/**
* Extracts the space-separated {@code scope} claim from an already-verified access token
* (call after {@link #verifyAccessToken}). {@code null} means no scope claim at all, which
* every token this simulator currently issues also is not the case for access tokens (see
* {@code generateSignedJwt}, which always sets a default scope) but a caller-suppressed
* scope list still needs to be tolerated as "no restriction modeled" rather than treated the
* same as an empty, restrictive list.
* The scopes in the space-separated {@code scope} claim of an already-verified access token
* (call after {@link #verifyAccessToken}), empty when the claim is absent or blank. Every access
* token Floci mints sets the claim (see {@code generateSignedJwt}); it is missing only when a
* PreTokenGeneration trigger removed it, and such a token grants no scope.
*/
private Set<String> extractScopesFromToken(String token) {
try {
String[] parts = token.split("\\.", -1);
JsonNode claims = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[1]));
String scope = textClaim(claims, "scope");
if (scope == null || scope.isBlank()) return null;
Set<String> scopes = new HashSet<>();
if (scope == null) {
return scopes;
}
for (String s : scope.split(" ")) {
if (!s.isBlank()) scopes.add(s);
}
return scopes;
} catch (Exception e) {
return null;
LOG.debug("Could not read the scope claim of an access token", e);
return Set.of();
}
}
/**
* AWS requires an access token carrying the given scope for some operations (for example
* VerifyUserAttribute requires aws.cognito.signin.user.admin). Call after
* {@link #verifyAccessToken}, which already confirms the token is a valid, unexpired access
* token; this only adds the scope check on top.
* VerifyUserAttribute requires aws.cognito.signin.user.admin), and refuses a token with no
* scope claim. Call after {@link #verifyAccessToken}, which already confirms the token is a
* valid, unexpired access token; this only adds the scope check on top.
*/
void requireScope(String accessToken, String requiredScope) {
Set<String> scopes = extractScopesFromToken(accessToken);
if (scopes != null && !scopes.contains(requiredScope)) {
throw new AwsException("NotAuthorizedException", "Access Token does not have the required scope", 400);
if (!scopes.contains(requiredScope)) {
throw new AwsException("NotAuthorizedException", "Access Token does not have required scopes", 400);
}
}