fix(cognito): pass the groups' IAM roles to the pre token generation trigger (#8134)

The pre token generation event always carried
groupConfiguration.iamRolesToOverride = [] and preferredRole = null, so a
trigger that reads the role Cognito computed for the user (to copy it into
the access token, for instance) got nothing. AWS fills both from the
user's groups: every group role, and the role of the lowest-precedence
group that has one, none when groups tied at that rank name different
roles.

Build groupConfiguration after checking that the pool has a pre token
generation trigger, read the pool's groups once instead of once per
membership, sort the test imports, and pin that a group without a role
does not outrank one with a role.

Closes #8222
This commit is contained in:
Giovanni Brethenoux authored and GitHub committed 2026-11-13 16:34:20 -04:00
1 parent f1a6260a94
commit 63b8da91f5
2 files changed
+94 -5

No files matched your search

@@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.SmithyValidationErrors;
import io.floci.aws.services.cognito.model.CognitoGroup;
import io.floci.aws.services.cognito.model.CognitoUser;
import io.floci.aws.services.cognito.model.UserPool;
import io.floci.aws.services.cognito.model.UserPoolClient;
@@ -34,6 +35,7 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalLong;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@@ -2200,13 +2202,17 @@ final class CognitoAuthFlowHandler {
private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user,
Map<String, String> clientMetadata, String triggerSource,
List<String> scopes) {
if (lambdaService == null || resolveTriggerArn(pool, "PreTokenGeneration") == null) {
// No trigger to hand the event to: skip reading the user's groups for it.
return null;
}
Map<String, Object> req = new HashMap<>();
if (user == null) {
// A machine identity has neither attributes nor groups.
req.put("userAttributes", Map.of());
req.put("groupConfiguration", null);
} else {
req.put("groupConfiguration", buildGroupConfiguration(user));
req.put("groupConfiguration", buildGroupConfiguration(pool, user));
}
req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
// V2 lambdas (CognitoEventUserPoolsPreTokenGenV2) require `scopes` to deserialize.
@@ -2311,14 +2317,41 @@ final class CognitoAuthFlowHandler {
return out;
}
private static Map<String, Object> buildGroupConfiguration(CognitoUser user) {
/**
* The groupConfiguration AWS hands the pre token generation trigger: the user's groups, the
* IAM roles of those groups, and the preferred role Cognito would put in the token.
*/
private Map<String, Object> buildGroupConfiguration(UserPool pool, CognitoUser user) {
List<String> names = user.getGroupNames() == null ? List.of() : new ArrayList<>(user.getGroupNames());
// One read of the pool's groups; a membership whose group is gone carries no role.
List<CognitoGroup> groups = names.isEmpty() ? List.of() : service.listGroups(pool.getId()).stream()
.filter(group -> names.contains(group.getGroupName())).toList();
Map<String, Object> cfg = new HashMap<>();
cfg.put("groupsToOverride", user.getGroupNames() == null ? List.of() : new ArrayList<>(user.getGroupNames()));
cfg.put("iamRolesToOverride", List.of());
cfg.put("preferredRole", null);
cfg.put("groupsToOverride", names);
cfg.put("iamRolesToOverride", groups.stream().map(CognitoGroup::getRoleArn)
.filter(role -> role != null && !role.isBlank()).distinct().toList());
cfg.put("preferredRole", preferredRole(groups));
return cfg;
}
/**
* The role of the group with the lowest Precedence among the groups that have a role; a group
* without a Precedence ranks after every group with one. When the groups tied at that rank
* name different roles, AWS sets no preferred role.
*/
static String preferredRole(List<CognitoGroup> groups) {
List<CognitoGroup> withRole = groups.stream()
.filter(group -> group.getRoleArn() != null && !group.getRoleArn().isBlank()).toList();
if (withRole.isEmpty()) {
return null;
}
Integer best = withRole.stream().map(CognitoGroup::getPrecedence).filter(Objects::nonNull)
.min(Integer::compare).orElse(null);
List<String> roles = withRole.stream().filter(group -> Objects.equals(group.getPrecedence(), best))
.map(CognitoGroup::getRoleArn).distinct().toList();
return roles.size() == 1 ? roles.get(0) : null;
}
private CognitoUser tryUserMigration(UserPool pool, UserPoolClient client, String username, String password,
Map<String, String> validationData, Map<String, String> clientMetadata,
String triggerSource) {
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.acm.AcmService;
import io.floci.aws.services.cognito.model.CognitoGroup;
import io.floci.aws.services.cognito.model.CognitoUser;
import io.floci.aws.services.cognito.model.ResourceServerScope;
import io.floci.aws.services.cognito.model.UserPool;
@@ -1356,6 +1357,61 @@ class CognitoLambdaTriggersTest {
assertNotNull(req.get("userAttributes"));
}
@Test
@SuppressWarnings("unchecked")
void preTokenGenerationGroupConfigurationCarriesTheGroupsRoles() throws Exception {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
String admin = "arn:aws:iam::000000000000:role/admin";
String reader = "arn:aws:iam::000000000000:role/reader";
service.createGroup(pool.getId(), "admins", null, 1, admin);
service.createGroup(pool.getId(), "readers", null, 5, reader);
service.createGroup(pool.getId(), "no-role", null, 0, null);
service.adminAddUserToGroup(pool.getId(), "admins", "alice");
service.adminAddUserToGroup(pool.getId(), "readers", "alice");
service.adminAddUserToGroup(pool.getId(), "no-role", "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.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
Map<String, Object> event = MAPPER.readValue(payloadCap.getValue(), new TypeReference<>() {});
Map<String, Object> groups = (Map<String, Object>) ((Map<String, Object>) event.get("request"))
.get("groupConfiguration");
assertEquals(Set.of("admins", "readers", "no-role"), Set.copyOf((List<String>) groups.get("groupsToOverride")));
assertEquals(Set.of(admin, reader), Set.copyOf((List<String>) groups.get("iamRolesToOverride")));
assertEquals(admin, groups.get("preferredRole"),
"the role of the lowest-precedence group that has one, as on AWS");
}
@Test
void preferredRoleFollowsAwsPrecedenceRules() {
String a = "arn:aws:iam::000000000000:role/a";
String b = "arn:aws:iam::000000000000:role/b";
assertEquals(a, CognitoAuthFlowHandler.preferredRole(List.of(group(1, a), group(2, b))));
assertEquals(a, CognitoAuthFlowHandler.preferredRole(List.of(group(null, b), group(3, a))),
"a group without precedence ranks after every group with one");
assertEquals(a, CognitoAuthFlowHandler.preferredRole(List.of(group(1, a), group(1, a))),
"a tie on the same role keeps that role");
assertNull(CognitoAuthFlowHandler.preferredRole(List.of(group(1, a), group(1, b))),
"a tie between different roles sets none");
assertEquals(b, CognitoAuthFlowHandler.preferredRole(List.of(group(null, b))));
assertNull(CognitoAuthFlowHandler.preferredRole(List.of(group(0, null))));
assertEquals(b, CognitoAuthFlowHandler.preferredRole(List.of(group(0, null), group(5, b))),
"a group without a role does not outrank one with a role (CreateGroup: the lowest "
+ "precedence group whose role ARN is given)");
}
private static CognitoGroup group(Integer precedence, String roleArn) {
CognitoGroup group = new CognitoGroup();
group.setPrecedence(precedence);
group.setRoleArn(roleArn);
return group;
}
// =========================================================================
// PreTokenGeneration for client credentials (M2M)
// =========================================================================