fix(cognito): fire PreTokenGeneration when the token endpoint redeems a code (#4438)

* fix(cognito): fire PreTokenGeneration when the token endpoint redeems a code

Managed login and federated sign-in both mint their tokens at
POST /oauth2/token, which called generateAuthResult directly and so never
invoked the pre token generation trigger. A pool whose trigger adds claims
got them from InitiateAuth but not from a hosted-UI sign-in, so an
application that authorizes on a custom claim rejected every token a browser
obtained while the same user's tokens from InitiateAuth were accepted.

Redemption now mints through a hosted-auth path that fires the trigger with
triggerSource TokenGeneration_HostedAuth, which is what AWS uses for a
sign-in through the hosted UI, for a pool's own users and federated users
alike. The authorization request's nonce is applied after the trigger's
claims so a trigger cannot displace it; AWS likewise does not let this
trigger override nonce.

* fix(cognito): pass the requested scopes to the hosted-auth trigger

Review feedback. The authorization code stores the scopes the authorize
request asked for, but the hosted-auth trigger call sent an empty list, so a
V2 lambda that branches on requested scopes had nothing to branch on. Thread
the code's scopes through to the trigger event. The other call sites keep
sending an empty list, which is what their non-OAuth flows carry.

Also replace the em-dashes in the new comments, per AGENTS.md.

* fix(cognito): narrow the trigger's scopes to the client's allowed set

Review feedback. An authorization request names its own scopes and nothing
checks them against the client's AllowedOAuthScopes when the code is issued,
so a stored code can carry a scope the client may not use. Passing those
straight through meant a V2 trigger could grant claims, or add scopes, from a
scope the client was never entitled to request.

The hosted-auth path now narrows the requested scopes to the client's allowed
set before the trigger is told about them, dropping the rest the way AWS
ignores a scope that is not associated with the client. The narrowing lives in
the service method rather than at the call site, so every caller gets it.

* style(cognito): brace the new conditionals

Review feedback. AGENTS.md requires braces in all conditionals, and the four
early returns in the claims-merge helpers omitted them.
This commit is contained in:
Emmanuel Olowosulu authored and GitHub committed 2026-09-26 16:43:52 -05:00
1 parent e186a772a8
commit b4d8483348
7 files changed
+374 -15

No files matched your search

@@ -107,6 +107,13 @@ class CognitoLambdaTriggersTest {
null, null, List.of(), null, null);
}
/** An OAuth client for the authorization-code flow, allowed exactly {@code allowedScopes}. */
private UserPoolClient createOAuthClient(UserPool pool, List<String> allowedScopes) {
return service.createUserPoolClient(pool.getId(), "oauth", false, true, List.of("code"), allowedScopes,
null, List.of("https://application.example.test/callback"), null, AUTH_FLOWS, null, null,
List.of(), null, List.of(), null, null, null, List.of(), null, null);
}
private void seedUser(UserPool pool, String username, String password) {
service.adminCreateUser(pool.getId(), username,
Map.of("email", username + "@example.com"), null);
@@ -696,9 +703,156 @@ class CognitoLambdaTriggersTest {
assertEquals("alice", user.getUsername());
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any());
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());
// Sign-in issues no tokens in the authorization-code flow: it hands back a code, and the
// token endpoint mints the tokens later. PreTokenGeneration therefore belongs to redemption,
// not here; see the hostedAuth tests below.
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::pretoken"), any(byte[].class), any());
}
@Test
@SuppressWarnings("unchecked")
void preTokenGenerationFiresWhenTheTokenEndpointRedeemsAnAuthorizationCode() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
ArgumentCaptor<byte[]> payloadCap = ArgumentCaptor.forClass(byte[].class);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))
.thenReturn(ok(Map.of("claimsOverrideDetails", Map.of(
"claimsToAddOrOverride", Map.of("tenant", "acme"),
"groupOverrideDetails", Map.of("groupsToOverride", List.of("admins"))))));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client, null,
List.of("openid", "email"));
Map<String, Object> event;
Map<String, Object> idClaims;
Map<String, Object> accessClaims;
try {
event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {});
idClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("IdToken")), new TypeReference<>() {});
accessClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("AccessToken")), new TypeReference<>() {});
} catch (Exception e) {
throw new RuntimeException(e);
}
assertEquals("TokenGeneration_HostedAuth", event.get("triggerSource"),
"AWS uses TokenGeneration_HostedAuth for sign-in through the hosted UI");
assertEquals(List.of("openid", "email"), ((Map<String, Object>) event.get("request")).get("scopes"),
"a V2 lambda may branch on the scopes the authorization request asked for");
assertEquals("acme", idClaims.get("tenant"), "the trigger's claims should reach the ID token");
assertEquals("acme", accessClaims.get("tenant"), "the trigger's claims should reach the access token");
assertEquals(List.of("admins"), accessClaims.get("cognito:groups"),
"groupOverrideDetails should apply on redemption as it does on InitiateAuth");
}
/**
* Nothing checks an authorization request's scopes against the client's AllowedOAuthScopes when the
* code is issued, so the stored code can name a scope the client may not use. A V2 trigger may grant
* claims or scopes from what it is told was requested, so it must never be told about one.
*/
@Test
@SuppressWarnings("unchecked")
void aScopeTheClientIsNotAllowedNeverReachesTheTrigger() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createOAuthClient(pool, List.of("openid", "email"));
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
ArgumentCaptor<byte[]> payloadCap = ArgumentCaptor.forClass(byte[].class);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))
.thenReturn(ok(Map.of()));
service.generateAuthResultForHostedAuth(user, pool, client, null,
List.of("openid", "admin/superuser", "email"));
Map<String, Object> event;
try {
event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {});
} catch (Exception e) {
throw new RuntimeException(e);
}
assertEquals(List.of("openid", "email"), ((Map<String, Object>) event.get("request")).get("scopes"),
"an unallowed scope must be dropped, so a trigger cannot grant entitlements from it");
}
@Test
void anOAuthClientWithNoAllowedScopesSendsTheTriggerNone() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createOAuthClient(pool, List.of());
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
ArgumentCaptor<byte[]> payloadCap = ArgumentCaptor.forClass(byte[].class);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), payloadCap.capture(), any()))
.thenReturn(ok(Map.of()));
service.generateAuthResultForHostedAuth(user, pool, client, null, List.of("openid"));
Map<String, Object> event;
try {
event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {});
} catch (Exception e) {
throw new RuntimeException(e);
}
@SuppressWarnings("unchecked")
Object scopes = ((Map<String, Object>) event.get("request")).get("scopes");
assertEquals(List.of(), scopes, "a client allowed no scopes grants the trigger none");
}
/**
* The OIDC flow owns {@code nonce}, and AWS lists it among the claims this trigger cannot
* override or suppress. A trigger that tries must not displace the request's value.
*/
@Test
@SuppressWarnings("unchecked")
void redemptionKeepsTheRequestNonceOverATriggerThatTriesToChangeIt() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))
.thenReturn(ok(Map.of("claimsOverrideDetails", Map.of(
"claimsToAddOrOverride", Map.of("nonce", "trigger-nonce", "tier", "gold"),
"claimsToSuppress", List.of("nonce")))));
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client,
new CognitoService.ClaimsOverride(Map.of("nonce", "request-nonce"), null, null, null,
null, null, null, null, null), List.of("openid"));
Map<String, Object> idClaims;
try {
idClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("IdToken")), new TypeReference<>() {});
} catch (Exception e) {
throw new RuntimeException(e);
}
assertEquals("request-nonce", idClaims.get("nonce"),
"the authorization request's nonce must survive a trigger that overrides or suppresses it");
assertEquals("gold", idClaims.get("tier"), "the trigger's other claims should still apply");
}
@Test
void redemptionMintsTokensWhenNoPreTokenGenerationTriggerIsConfigured() {
UserPool pool = createPoolWithLambdaConfig(Map.of());
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
CognitoUser user = service.adminGetUser(pool.getId(), "alice");
Map<String, Object> auth = service.generateAuthResultForHostedAuth(user, pool, client,
new CognitoService.ClaimsOverride(Map.of("nonce", "request-nonce"), null, null, null,
null, null, null, null, null), List.of("openid"));
assertNotNull(auth.get("IdToken"));
assertNotNull(auth.get("AccessToken"));
assertNotNull(auth.get("RefreshToken"));
Map<String, Object> idClaims;
try {
idClaims = MAPPER.readValue(decodeJwtPayload((String) auth.get("IdToken")), new TypeReference<>() {});
} catch (Exception e) {
throw new RuntimeException(e);
}
assertEquals("request-nonce", idClaims.get("nonce"));
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
}
@Test
void managedLoginPreAuthenticationErrorBlocksSignIn() {
UserPool pool = createPoolWithLambdaConfig(Map.of(
@@ -1,12 +1,17 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.net.URI;
import java.net.URLDecoder;
@@ -31,6 +36,10 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* Managed login for a pool's own users, driven over HTTP the way a browser drives it:
@@ -50,6 +59,12 @@ class CognitoManagedLoginIntegrationTest {
private static final String INCORRECT_CREDENTIALS = "Incorrect username or password";
private static final Pattern HIDDEN_FIELD = Pattern.compile("<input type=\"hidden\" name=\"([^\"]*)\" value=\"([^\"]*)\">");
private static final Pattern FORM_ACTION = Pattern.compile("<form method=\"post\" action=\"([^\"]*)\">");
private static final String PRE_TOKEN_GENERATION_ARN = "arn:aws:lambda:::pre-token-generation";
private static final ObjectMapper MAPPER = new ObjectMapper();
/** Only the PreTokenGeneration trigger is configured on any pool here, so nothing else invokes it. */
@InjectMock
LambdaService lambdaService;
@BeforeAll
static void configureRestAssured() {
@@ -188,6 +203,60 @@ class CognitoManagedLoginIntegrationTest {
assertFalse(accessToken.has("nonce"));
}
/**
* A pool whose PreTokenGeneration trigger adds a claim must get it from a managed-login sign-in
* too, not only from {@code InitiateAuth}: the token endpoint is what mints these tokens, so that
* is where the trigger has to fire. The authorization request's {@code nonce} outranks the
* trigger, as it does on AWS.
*/
@Test
void redeemingTheCodeFiresPreTokenGenerationAndAppliesItsClaims() throws Exception {
Pool pool = newPoolWithPreTokenGenerationTrigger();
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), event.capture(), any()))
.thenReturn(triggerResponse(Map.of("claimsOverrideDetails", Map.of(
"claimsToAddOrOverride", Map.of("tenant", "acme", "nonce", "trigger-nonce")))));
Response tokens = redeem(null, pool.clientId(),
code(signIn(null, pool, authorizeRequest(pool.clientId()))), VERIFIER);
tokens.then().statusCode(200);
JsonNode triggerEvent = MAPPER.readTree(event.getValue());
assertEquals("TokenGeneration_HostedAuth", triggerEvent.path("triggerSource").asText(),
"AWS uses TokenGeneration_HostedAuth for a sign-in through the hosted UI");
assertEquals(List.of("openid", "email"),
MAPPER.convertValue(triggerEvent.path("request").path("scopes"), List.class),
"the authorization request's scopes reach the trigger");
JsonNode idToken = jwtPayload(tokens.path("id_token"));
assertEquals("acme", idToken.path("tenant").asText(), "the trigger's claim should reach the ID token");
assertEquals("client-nonce", idToken.path("nonce").asText(),
"the request's nonce must outrank a trigger that tries to replace it");
assertEquals("acme", jwtPayload(tokens.path("access_token")).path("tenant").asText(),
"the trigger's claim should reach the access token");
}
/**
* The authorize endpoint stores the scopes the request named without checking them against the
* client's AllowedOAuthScopes, so a request can carry one the client may not use. A V2 trigger can
* grant claims or scopes from what it is told was requested, so an unallowed scope must not reach it.
*/
@Test
void aScopeTheClientIsNotAllowedDoesNotReachTheTrigger() throws Exception {
Pool pool = newPoolWithPreTokenGenerationTrigger();
Map<String, String> query = authorizeRequest(pool.clientId());
query.put("scope", "openid email admin/superuser");
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
when(lambdaService.invoke(anyString(), eq(PRE_TOKEN_GENERATION_ARN), event.capture(), any()))
.thenReturn(triggerResponse(Map.of()));
Response tokens = redeem(null, pool.clientId(), code(signIn(null, pool, query)), VERIFIER);
tokens.then().statusCode(200);
assertEquals(List.of("openid", "email"),
MAPPER.convertValue(MAPPER.readTree(event.getValue()).path("request").path("scopes"), List.class),
"admin/superuser is not in the client's AllowedOAuthScopes, so the trigger never sees it");
}
@Test
void codeIsRefusedWithAWrongOrMissingVerifierAndAWrongOneSpendsIt() throws Exception {
Pool pool = newPool();
@@ -451,6 +520,18 @@ class CognitoManagedLoginIntegrationTest {
return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime());
}
private static Pool newPoolWithPreTokenGenerationTrigger() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"ManagedLoginTriggerPool","LambdaConfig":{"PreTokenGeneration":"%s"}}
""".formatted(PRE_TOKEN_GENERATION_ARN)).path("UserPool").path("Id").asText();
return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime());
}
/** 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 cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true,
@@ -33,6 +33,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class CognitoOAuthControllerTest {
@@ -239,7 +241,7 @@ class CognitoOAuthControllerTest {
CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null)))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
@@ -391,7 +393,7 @@ class CognitoOAuthControllerTest {
void tokenPutsTheNonceInTheIdTokenOnly() {
String code = putAuthorizationCode("request-nonce", null);
ArgumentCaptor<CognitoService.ClaimsOverride> override = ArgumentCaptor.forClass(CognitoService.ClaimsOverride.class);
when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), override.capture()))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), override.capture(), any()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
@@ -403,6 +405,26 @@ class CognitoOAuthControllerTest {
assertNull(override.getValue().groupsToOverride());
}
/**
* Redemption must mint through the hosted-auth path, which is what fires PreTokenGeneration;
* the plain {@code generateAuthResult} does not, and using it here silently drops the trigger.
* The code's requested scopes travel with it, so a V2 lambda sees what was asked for.
*/
@Test
void tokenMintsThroughTheHostedAuthPathSoPreTokenGenerationFires() {
String code = putAuthorizationCode(null, null);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> scopes = ArgumentCaptor.forClass(List.class);
Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));
assertEquals(200, response.getStatus());
verify(cognitoService).generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client),
any(), scopes.capture());
assertEquals(List.of("openid"), scopes.getValue(), "the code's requested scopes reach the trigger");
verify(cognitoService, never()).generateAuthResult(any(CognitoUser.class), any(UserPool.class), any(), any());
}
private String putTransaction(String relyingPartyState) {
return stateStore.putTransaction(new CognitoAuthorizationTransaction(POOL_ID, CLIENT_ID, CALLBACK_URI,
List.of("openid"), "nonce", "ExampleOidc", relyingPartyState, null, CLOCK.instant().plusSeconds(60)));
@@ -418,7 +440,7 @@ class CognitoOAuthControllerTest {
CLOCK.instant().plusSeconds(60)));
when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool());
when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user());
when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null)))
when(cognitoService.generateAuthResultForHostedAuth(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null), any()))
.thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",
"ExpiresIn", 3600, "TokenType", "Bearer"));
return code;