mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
e186a772a8
commit
b4d8483348
7 files changed
+374
-15
No files matched your search
@@ -348,8 +348,12 @@ the callback in `CallbackURLs`. No domain is needed; on a custom domain the same
|
||||
without the client's `ExplicitAuthFlows`. On success it sets a `cognito` session cookie
|
||||
(one hour) and redirects to the callback with `code` and `state`. A wrong password shows
|
||||
the form again with `Incorrect username or password.`; an unknown user reads the same.
|
||||
4. `POST /cognito-idp/oauth2/token` redeems the code. The ID token carries the request's
|
||||
`nonce`.
|
||||
4. `POST /cognito-idp/oauth2/token` redeems the code. It invokes the pre token generation
|
||||
trigger with triggerSource `TokenGeneration_HostedAuth`, as AWS does for a hosted-UI
|
||||
sign-in, so a pool that customises its claims gets the same tokens here as from
|
||||
`InitiateAuth`. The trigger is told the scopes the request asked for, narrowed to the
|
||||
client's `AllowedOAuthScopes`, since the authorize endpoint does not check them itself. The
|
||||
ID token carries the request's `nonce`, which the trigger cannot override.
|
||||
5. `GET /cognito-idp/logout?client_id=...&logout_uri=...` ends the session and redirects to
|
||||
`logout_uri`, which must be one of the client's `LogoutURLs`. With `redirect_uri` and
|
||||
`response_type=code` instead of `logout_uri`, it ends the session and redirects to the
|
||||
@@ -374,8 +378,6 @@ Differences from AWS:
|
||||
- **One session cookie per host.** Floci's own host serves every pool, so signing in to a
|
||||
second pool there replaces the first pool's session. Custom domains keep separate sessions,
|
||||
as on AWS. Sessions are held in memory and are lost on restart.
|
||||
- **No PreTokenGeneration on code redemption.** As with federated sign-in, the token endpoint
|
||||
does not invoke the pre token generation trigger.
|
||||
|
||||
```bash
|
||||
EP=http://localhost:4566
|
||||
|
||||
+27
-6
@@ -436,7 +436,7 @@ final class CognitoAuthFlowHandler {
|
||||
throw ae;
|
||||
}
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user,
|
||||
clientMetadata, "TokenGeneration_RefreshTokens");
|
||||
clientMetadata, "TokenGeneration_RefreshTokens", List.of());
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", service.generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
auth.put("IdToken", service.generateSignedJwt(user, pool, "id", client, override, refreshTokenUuid));
|
||||
@@ -1291,13 +1291,15 @@ final class CognitoAuthFlowHandler {
|
||||
}
|
||||
|
||||
private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
Map<String, String> clientMetadata, String triggerSource) {
|
||||
Map<String, String> clientMetadata, String triggerSource,
|
||||
List<String> scopes) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("groupConfiguration", buildGroupConfiguration(user));
|
||||
req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
|
||||
// V2 lambdas (CognitoEventUserPoolsPreTokenGenV2) require `scopes` to deserialize.
|
||||
// V1 lambdas tolerate the extra field.
|
||||
req.put("scopes", List.of());
|
||||
// V1 lambdas tolerate the extra field. Only an OAuth flow has requested scopes to send;
|
||||
// the others pass an empty list, which is what the request carries there.
|
||||
req.put("scopes", scopes == null ? List.of() : List.copyOf(scopes));
|
||||
TriggerResult result = invokeTrigger(pool, client, user, "PreTokenGeneration", triggerSource, req);
|
||||
if (!result.configured() || result.errored()) return null;
|
||||
|
||||
@@ -1457,12 +1459,31 @@ final class CognitoAuthFlowHandler {
|
||||
private Map<String, Object> issueTokens(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String triggerSource, Map<String, String> clientMetadata) {
|
||||
firePostAuthentication(pool, client, user, clientMetadata, false);
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource);
|
||||
CognitoService.ClaimsOverride override = firePreTokenGeneration(pool, client, user, clientMetadata, triggerSource,
|
||||
List.of());
|
||||
return service.generateAuthResult(user, pool, client, override);
|
||||
}
|
||||
|
||||
CognitoService.ClaimsOverride preTokenGenerationForRefresh(UserPool pool, UserPoolClient client, CognitoUser user) {
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens");
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_RefreshTokens", List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires PreTokenGeneration for a sign-in whose tokens the OAuth token endpoint mints when it
|
||||
* redeems an authorization code: managed login and federated sign-in both land here.
|
||||
*
|
||||
* <p>Separate from {@link #issueTokens} because the authorization-code flow splits authentication
|
||||
* from token issuance: the user authenticates at the authorize/login endpoints, and the tokens are
|
||||
* minted later, on a different request, by whoever presents the code. PostAuthentication has
|
||||
* already fired at sign-in, so only PreTokenGeneration is owed here.
|
||||
*
|
||||
* <p>AWS names this trigger source {@code TokenGeneration_HostedAuth}, which it uses for sign-in
|
||||
* through the hosted UI regardless of whether the user is native or federated. {@code scopes} are
|
||||
* the scopes the authorization request asked for, which a V2 lambda may branch on.
|
||||
*/
|
||||
CognitoService.ClaimsOverride preTokenGenerationForHostedAuth(UserPool pool, UserPoolClient client,
|
||||
CognitoUser user, List<String> scopes) {
|
||||
return firePreTokenGeneration(pool, client, user, Map.of(), "TokenGeneration_HostedAuth", scopes);
|
||||
}
|
||||
|
||||
private static String resolveTriggerArn(UserPool pool, String triggerKey) {
|
||||
|
||||
+2
-2
@@ -417,8 +417,8 @@ public class CognitoOAuthController {
|
||||
try {
|
||||
UserPool pool = cognitoService.describeUserPool(consumedCode.userPoolId());
|
||||
CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId());
|
||||
Map<String, Object> authentication = cognitoService.generateAuthResult(user, pool, client,
|
||||
nonceClaim(consumedCode.nonce()));
|
||||
Map<String, Object> authentication = cognitoService.generateAuthResultForHostedAuth(user, pool, client,
|
||||
nonceClaim(consumedCode.nonce()), consumedCode.scopes());
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
body.put("access_token", (String) authentication.get("AccessToken"));
|
||||
body.put("id_token", (String) authentication.get("IdToken"));
|
||||
|
||||
@@ -3296,6 +3296,85 @@ public class CognitoService implements ResourceProvider {
|
||||
return generateAuthResult(user, pool, client, override, originJti);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints the tokens the OAuth token endpoint returns for a redeemed authorization code, firing
|
||||
* PreTokenGeneration first, as AWS does for a hosted-UI sign-in, so a pool that customises its
|
||||
* claims gets the same tokens here as it does from {@code InitiateAuth}.
|
||||
*
|
||||
* <p>{@code protocolClaims} carries claims the OIDC flow itself owns, currently the request's
|
||||
* {@code nonce}. They are applied <em>after</em> the trigger's, so a trigger cannot displace them:
|
||||
* AWS likewise refuses to let this trigger override {@code nonce} and the other reserved claims.
|
||||
* Passing {@code null} for either side leaves the other's claims untouched. {@code requestedScopes}
|
||||
* are the scopes the authorization request asked for, narrowed to the ones the client may actually
|
||||
* use before the trigger is told about them.
|
||||
*/
|
||||
Map<String, Object> generateAuthResultForHostedAuth(CognitoUser user, UserPool pool, UserPoolClient client,
|
||||
ClaimsOverride protocolClaims, List<String> requestedScopes) {
|
||||
ClaimsOverride trigger = authFlowHandler.preTokenGenerationForHostedAuth(pool, client, user,
|
||||
scopesAllowedForClient(client, requestedScopes));
|
||||
return generateAuthResult(user, pool, client, mergeUnderProtocolClaims(trigger, protocolClaims));
|
||||
}
|
||||
|
||||
/**
|
||||
* The requested scopes the client is allowed to use, in the order requested and without duplicates.
|
||||
*
|
||||
* <p>An authorization request names its own scopes, and nothing checks them against the client's
|
||||
* AllowedOAuthScopes when the code is issued, so the stored code can carry a scope the client may
|
||||
* not use. A V2 trigger is free to grant claims or add scopes based on what it is told was
|
||||
* requested, so it is told only what the client was entitled to ask for. An unallowed scope is
|
||||
* dropped rather than refused, which is how AWS treats a scope that is not associated with the
|
||||
* client.
|
||||
*/
|
||||
private static List<String> scopesAllowedForClient(UserPoolClient client, List<String> requestedScopes) {
|
||||
if (requestedScopes == null || requestedScopes.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> allowed = client.getAllowedOAuthScopes();
|
||||
if (allowed == null || allowed.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> kept = new ArrayList<>();
|
||||
for (String scope : requestedScopes) {
|
||||
if (allowed.contains(scope) && !kept.contains(scope)) {
|
||||
kept.add(scope);
|
||||
}
|
||||
}
|
||||
return List.copyOf(kept);
|
||||
}
|
||||
|
||||
/**
|
||||
* Layers {@code protocolClaims} over {@code trigger}, keeping every other field the trigger set
|
||||
* (suppressions, groups, roles, scopes).
|
||||
*/
|
||||
private static ClaimsOverride mergeUnderProtocolClaims(ClaimsOverride trigger, ClaimsOverride protocolClaims) {
|
||||
if (trigger == null) {
|
||||
return protocolClaims;
|
||||
}
|
||||
if (protocolClaims == null) {
|
||||
return trigger;
|
||||
}
|
||||
return new ClaimsOverride(
|
||||
claimsWithProtocolLast(trigger.idClaimsToAddOrOverride(), protocolClaims.idClaimsToAddOrOverride()),
|
||||
trigger.idClaimsToSuppress(),
|
||||
claimsWithProtocolLast(trigger.accessClaimsToAddOrOverride(), protocolClaims.accessClaimsToAddOrOverride()),
|
||||
trigger.accessClaimsToSuppress(),
|
||||
trigger.scopesToAdd(), trigger.scopesToSuppress(),
|
||||
trigger.groupsToOverride(), trigger.iamRolesToOverride(), trigger.preferredRole());
|
||||
}
|
||||
|
||||
private static Map<String, Object> claimsWithProtocolLast(Map<String, Object> triggerClaims,
|
||||
Map<String, Object> protocolClaims) {
|
||||
if (protocolClaims == null || protocolClaims.isEmpty()) {
|
||||
return triggerClaims;
|
||||
}
|
||||
if (triggerClaims == null || triggerClaims.isEmpty()) {
|
||||
return protocolClaims;
|
||||
}
|
||||
Map<String, Object> merged = new HashMap<>(triggerClaims);
|
||||
merged.putAll(protocolClaims);
|
||||
return merged;
|
||||
}
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti));
|
||||
|
||||
+154
@@ -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(
|
||||
|
||||
+81
@@ -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,
|
||||
|
||||
+25
-3
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user