diff --git a/compatibility-tests/sdk-test-awscli/test/cognito.bats b/compatibility-tests/sdk-test-awscli/test/cognito.bats index 40d711fb9f..225aeae9a1 100644 --- a/compatibility-tests/sdk-test-awscli/test/cognito.bats +++ b/compatibility-tests/sdk-test-awscli/test/cognito.bats @@ -229,3 +229,28 @@ teardown() { assert_failure [[ "$output" == *"ValidationException"* ]] } + +@test "Cognito: describe-user-pool returns all 20 standard SchemaAttributes" { + out=$(aws_cmd cognito-idp create-user-pool --pool-name "bats-test-pool-$(unique_name)") + POOL_ID=$(json_get "$out" '.UserPool.Id') + + run aws_cmd cognito-idp describe-user-pool --user-pool-id "$POOL_ID" + assert_success + + count=$(echo "$output" | jq '.UserPool.SchemaAttributes | length') + [ "$count" -eq 20 ] + + for attr in sub name given_name family_name middle_name nickname \ + preferred_username profile picture website email email_verified \ + gender birthdate zoneinfo locale phone_number phone_number_verified \ + address updated_at; do + found=$(echo "$output" | jq --arg n "$attr" '[.UserPool.SchemaAttributes[] | select(.Name == $n)] | length') + [ "$found" -eq 1 ] || { echo "missing standard attribute: $attr"; return 1; } + done + + sub_required=$(echo "$output" | jq '[.UserPool.SchemaAttributes[] | select(.Name == "sub")] | .[0].Required') + [ "$sub_required" = "true" ] + + sub_mutable=$(echo "$output" | jq '[.UserPool.SchemaAttributes[] | select(.Name == "sub")] | .[0].Mutable') + [ "$sub_mutable" = "false" ] +} diff --git a/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go b/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go index 7d6ca75b96..c9cf8985aa 100644 --- a/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go +++ b/compatibility-tests/sdk-test-go/internal/testutil/fixtures.go @@ -11,6 +11,7 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/acm" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" "github.com/aws/aws-sdk-go-v2/service/ecr" "github.com/aws/aws-sdk-go-v2/service/pipes" "github.com/aws/aws-sdk-go-v2/service/cloudwatch" @@ -132,6 +133,11 @@ func RDSClient() *rds.Client { return rds.NewFromConfig(Config()) } +// CognitoClient returns a new Cognito Identity Provider client. +func CognitoClient() *cognitoidentityprovider.Client { + return cognitoidentityprovider.NewFromConfig(Config()) +} + // ProxyHost returns the host to use for direct TCP connections to RDS/ElastiCache proxies. func ProxyHost() string { ep := Endpoint() diff --git a/compatibility-tests/sdk-test-go/tests/cognito_test.go b/compatibility-tests/sdk-test-go/tests/cognito_test.go new file mode 100644 index 0000000000..448641eb8c --- /dev/null +++ b/compatibility-tests/sdk-test-go/tests/cognito_test.go @@ -0,0 +1,62 @@ +package tests + +import ( + "context" + "testing" + + "floci-sdk-test-go/internal/testutil" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCognitoDescribeUserPoolStandardAttributes(t *testing.T) { + ctx := context.Background() + svc := testutil.CognitoClient() + + poolName := "go-test-cognito-standard-attrs" + created, err := svc.CreateUserPool(ctx, &cognitoidentityprovider.CreateUserPoolInput{ + PoolName: aws.String(poolName), + }) + require.NoError(t, err) + poolID := created.UserPool.Id + + t.Cleanup(func() { + svc.DeleteUserPool(ctx, &cognitoidentityprovider.DeleteUserPoolInput{ + UserPoolId: poolID, + }) + }) + + resp, err := svc.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{ + UserPoolId: poolID, + }) + require.NoError(t, err) + + schema := resp.UserPool.SchemaAttributes + assert.Len(t, schema, 20, "DescribeUserPool must return all 20 standard Cognito attributes") + + names := make(map[string]bool, len(schema)) + for _, attr := range schema { + names[aws.ToString(attr.Name)] = true + } + + expected := []string{ + "sub", "name", "given_name", "family_name", "middle_name", "nickname", + "preferred_username", "profile", "picture", "website", "email", + "email_verified", "gender", "birthdate", "zoneinfo", "locale", + "phone_number", "phone_number_verified", "address", "updated_at", + } + for _, attr := range expected { + assert.True(t, names[attr], "missing standard attribute: %s", attr) + } + + // spot-check sub + for _, attr := range schema { + if aws.ToString(attr.Name) == "sub" { + assert.True(t, aws.ToBool(attr.Required), "sub must be Required") + assert.False(t, aws.ToBool(attr.Mutable), "sub must not be Mutable") + } + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java index f6b321e27b..cb78069353 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoFeaturesTest.java @@ -382,6 +382,24 @@ class CognitoFeaturesTest { assertThat(resp.users()).isEmpty(); } + @Test + @Order(55) + void describeUserPoolReturnsAllTwentyStandardAttributes() { + DescribeUserPoolResponse resp = cognito.describeUserPool(b -> b.userPoolId(poolId)); + List schema = resp.userPool().schemaAttributes(); + assertThat(schema).hasSize(20); + List names = schema.stream().map(SchemaAttributeType::name).toList(); + assertThat(names).contains( + "sub", "name", "given_name", "family_name", "middle_name", "nickname", + "preferred_username", "profile", "picture", "website", "email", + "email_verified", "gender", "birthdate", "zoneinfo", "locale", + "phone_number", "phone_number_verified", "address", "updated_at"); + + SchemaAttributeType sub = schema.stream().filter(a -> "sub".equals(a.name())).findFirst().orElseThrow(); + assertThat(sub.required()).isTrue(); + assertThat(sub.mutable()).isFalse(); + } + // ── Issue #234 note ─────────────────────────────────────────────────────── // GetTokensFromRefreshToken is tested in sdk-test-node/tests/cognito-features.test.ts // because GetTokensFromRefreshTokenCommand is not available in Java SDK 2.31.8. diff --git a/compatibility-tests/sdk-test-node/tests/cognito-features.test.ts b/compatibility-tests/sdk-test-node/tests/cognito-features.test.ts index 18f396b8f8..47e01e6438 100644 --- a/compatibility-tests/sdk-test-node/tests/cognito-features.test.ts +++ b/compatibility-tests/sdk-test-node/tests/cognito-features.test.ts @@ -21,6 +21,7 @@ import { InitiateAuthCommand, ListUsersCommand, GetTokensFromRefreshTokenCommand, + DescribeUserPoolCommand, DeleteUserPoolCommand, MessageActionType, ExplicitAuthFlowsType, @@ -415,6 +416,25 @@ describe('Cognito features (#218 #220 #228 #229 #233 #234 #235)', () => { ).rejects.toThrow(); }); + it('DescribeUserPool returns all 20 standard SchemaAttributes', async () => { + const resp = await cognito.send(new DescribeUserPoolCommand({ UserPoolId: poolId })); + const schema = resp.UserPool?.SchemaAttributes ?? []; + expect(schema).toHaveLength(20); + const names = schema.map((a) => a.Name); + const expected = [ + 'sub', 'name', 'given_name', 'family_name', 'middle_name', 'nickname', + 'preferred_username', 'profile', 'picture', 'website', 'email', + 'email_verified', 'gender', 'birthdate', 'zoneinfo', 'locale', + 'phone_number', 'phone_number_verified', 'address', 'updated_at', + ]; + for (const attr of expected) { + expect(names).toContain(attr); + } + const sub = schema.find((a) => a.Name === 'sub'); + expect(sub?.Required).toBe(true); + expect(sub?.Mutable).toBe(false); + }); + it('#234: REFRESH_TOKEN_AUTH flow also works with structured token', async () => { const loginResp = await cognito.send( new InitiateAuthCommand({ diff --git a/compatibility-tests/sdk-test-python/tests/test_cognito.py b/compatibility-tests/sdk-test-python/tests/test_cognito.py index 0c9b176ad5..07e452d7e5 100644 --- a/compatibility-tests/sdk-test-python/tests/test_cognito.py +++ b/compatibility-tests/sdk-test-python/tests/test_cognito.py @@ -189,3 +189,33 @@ class TestCognitoAuth: UserPoolId=pool_id, ClientId=client_id ) cognito_client.delete_user_pool(UserPoolId=pool_id) + + +class TestCognitoDescribeUserPoolStandardAttributes: + """DescribeUserPool must return all 20 standard OIDC attributes.""" + + STANDARD_ATTRIBUTES = [ + "sub", "name", "given_name", "family_name", "middle_name", "nickname", + "preferred_username", "profile", "picture", "website", "email", + "email_verified", "gender", "birthdate", "zoneinfo", "locale", + "phone_number", "phone_number_verified", "address", "updated_at", + ] + + def test_describe_user_pool_returns_all_standard_schema_attributes(self, cognito_client, unique_name): + response = cognito_client.create_user_pool(PoolName=f"pytest-schema-{unique_name}") + pool_id = response["UserPool"]["Id"] + + try: + described = cognito_client.describe_user_pool(UserPoolId=pool_id) + schema = described["UserPool"]["SchemaAttributes"] + names = [a["Name"] for a in schema] + + assert len(schema) == 20 + for attr in self.STANDARD_ATTRIBUTES: + assert attr in names, f"Missing standard attribute: {attr}" + + sub = next(a for a in schema if a["Name"] == "sub") + assert sub["Required"] is True + assert sub["Mutable"] is False + finally: + cognito_client.delete_user_pool(UserPoolId=pool_id) diff --git a/compatibility-tests/sdk-test-rust/tests/cognito_test.rs b/compatibility-tests/sdk-test-rust/tests/cognito_test.rs new file mode 100644 index 0000000000..0d11ab60e5 --- /dev/null +++ b/compatibility-tests/sdk-test-rust/tests/cognito_test.rs @@ -0,0 +1,63 @@ +mod common; + +#[tokio::test(flavor = "multi_thread")] +async fn test_cognito_describe_user_pool_returns_all_standard_attributes() { + let cognito = common::cognito_client().await; + let pool_name = "rust-test-cognito-standard-attrs"; + + let created = cognito + .create_user_pool() + .pool_name(pool_name) + .send() + .await + .expect("CreateUserPool failed"); + + let pool_id = created + .user_pool() + .and_then(|p| p.id()) + .expect("pool id missing") + .to_string(); + + let _guard = common::CleanupGuard::new({ + let cognito = cognito.clone(); + let pool_id = pool_id.clone(); + async move { + let _ = cognito + .delete_user_pool() + .user_pool_id(pool_id) + .send() + .await; + } + }); + + let resp = cognito + .describe_user_pool() + .user_pool_id(&pool_id) + .send() + .await + .expect("DescribeUserPool failed"); + + let schema = resp + .user_pool() + .and_then(|p| Some(p.schema_attributes())) + .unwrap_or_default(); + + assert_eq!(schema.len(), 20, "DescribeUserPool must return all 20 standard Cognito attributes"); + + let names: Vec<&str> = schema.iter().filter_map(|a| a.name()).collect(); + + let expected = [ + "sub", "name", "given_name", "family_name", "middle_name", "nickname", + "preferred_username", "profile", "picture", "website", "email", + "email_verified", "gender", "birthdate", "zoneinfo", "locale", + "phone_number", "phone_number_verified", "address", "updated_at", + ]; + for attr in &expected { + assert!(names.contains(attr), "missing standard attribute: {attr}"); + } + + // spot-check sub + let sub = schema.iter().find(|a| a.name() == Some("sub")).expect("sub not found"); + assert_eq!(sub.required(), Some(true), "sub must be Required"); + assert_eq!(sub.mutable(), Some(false), "sub must not be Mutable"); +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java index ed7c156259..48dcea2a65 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandler.java @@ -495,7 +495,7 @@ public class CognitoJsonHandler { node.set("Policies", objectMapper.valueToTree(p.getPolicies() != null ? p.getPolicies() : new HashMap<>())); node.put("DeletionProtection", p.getDeletionProtection() != null ? p.getDeletionProtection() : "INACTIVE"); node.set("LambdaConfig", objectMapper.valueToTree(p.getLambdaConfig() != null ? p.getLambdaConfig() : new HashMap<>())); - node.set("SchemaAttributes", objectMapper.valueToTree(p.getSchemaAttributes() != null ? p.getSchemaAttributes() : new java.util.ArrayList<>())); + node.set("SchemaAttributes", objectMapper.valueToTree(CognitoStandardAttributes.merge(p.getSchemaAttributes()))); node.set("AutoVerifiedAttributes", objectMapper.valueToTree(p.getAutoVerifiedAttributes() != null ? p.getAutoVerifiedAttributes() : new java.util.ArrayList<>())); node.set("AliasAttributes", objectMapper.valueToTree(p.getAliasAttributes() != null ? p.getAliasAttributes() : new java.util.ArrayList<>())); node.set("UsernameAttributes", objectMapper.valueToTree(p.getUsernameAttributes() != null ? p.getUsernameAttributes() : new java.util.ArrayList<>())); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoStandardAttributes.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoStandardAttributes.java new file mode 100644 index 0000000000..115a70a25a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoStandardAttributes.java @@ -0,0 +1,105 @@ +package io.github.hectorvent.floci.services.cognito; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +final class CognitoStandardAttributes { + + private CognitoStandardAttributes() {} + + static final List> DEFAULTS = buildDefaults(); + + private static List> buildDefaults() { + List> attrs = new ArrayList<>(); + + attrs.add(stringAttr("sub", "1", "2048", false, true)); + attrs.add(stringAttr("name", "0", "2048", true, false)); + attrs.add(stringAttr("given_name", "0", "2048", true, false)); + attrs.add(stringAttr("family_name", "0", "2048", true, false)); + attrs.add(stringAttr("middle_name", "0", "2048", true, false)); + attrs.add(stringAttr("nickname", "0", "2048", true, false)); + attrs.add(stringAttr("preferred_username", "0", "2048", true, false)); + attrs.add(stringAttr("profile", "0", "2048", true, false)); + attrs.add(stringAttr("picture", "0", "2048", true, false)); + attrs.add(stringAttr("website", "0", "2048", true, false)); + attrs.add(stringAttr("email", "0", "2048", true, false)); + attrs.add(booleanAttr("email_verified")); + attrs.add(stringAttr("gender", "0", "2048", true, false)); + attrs.add(stringAttr("birthdate", "10", "10", true, false)); + attrs.add(stringAttr("zoneinfo", "0", "2048", true, false)); + attrs.add(stringAttr("locale", "0", "2048", true, false)); + attrs.add(stringAttr("phone_number", "0", "2048", true, false)); + attrs.add(booleanAttr("phone_number_verified")); + attrs.add(stringAttr("address", "0", "2048", true, false)); + attrs.add(numberAttr("updated_at")); + + return List.copyOf(attrs); + } + + private static Map stringAttr(String name, String minLength, String maxLength, + boolean mutable, boolean required) { + Map attr = new LinkedHashMap<>(); + attr.put("Name", name); + attr.put("AttributeDataType", "String"); + attr.put("DeveloperOnlyAttribute", false); + attr.put("Mutable", mutable); + attr.put("Required", required); + attr.put("StringAttributeConstraints", Map.of("MinLength", minLength, "MaxLength", maxLength)); + return attr; + } + + private static Map booleanAttr(String name) { + Map attr = new LinkedHashMap<>(); + attr.put("Name", name); + attr.put("AttributeDataType", "Boolean"); + attr.put("DeveloperOnlyAttribute", false); + attr.put("Mutable", true); + attr.put("Required", false); + return attr; + } + + private static Map numberAttr(String name) { + Map attr = new LinkedHashMap<>(); + attr.put("Name", name); + attr.put("AttributeDataType", "Number"); + attr.put("DeveloperOnlyAttribute", false); + attr.put("Mutable", true); + attr.put("Required", false); + attr.put("NumberAttributeConstraints", Map.of("MinValue", "0")); + return attr; + } + + /** + * Merges standard attributes with any pool-defined schema. + * Custom attributes (name starts with "custom:") are appended after standard ones. + * Standard attributes explicitly included in the schema override the defaults. + */ + static List> merge(List> poolSchema) { + if (poolSchema == null || poolSchema.isEmpty()) { + return DEFAULTS; + } + + Map> byName = new LinkedHashMap<>(); + for (Map attr : DEFAULTS) { + byName.put((String) attr.get("Name"), attr); + } + + List> custom = new ArrayList<>(); + for (Map attr : poolSchema) { + String name = (String) attr.get("Name"); + if (name != null && name.startsWith("custom:")) { + custom.add(attr); + } else if (name != null && byName.containsKey(name)) { + byName.put(name, attr); + } else if (name != null) { + custom.add(attr); + } + } + + List> result = new ArrayList<>(byName.values()); + result.addAll(custom); + return result; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java index 607b539c5b..1a6f2e5fb4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java @@ -24,11 +24,15 @@ import java.security.PublicKey; import java.security.Signature; import java.security.spec.RSAPublicKeySpec; import java.util.Base64; +import java.util.List; +import java.util.Spliterators; import java.util.UUID; import java.util.stream.Stream; +import java.util.stream.StreamSupport; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -176,6 +180,36 @@ class CognitoIntegrationTest { assertEquals("RS256", document.path("id_token_signing_alg_values_supported").get(0).asText()); } + @Test + @Order(5) + void describeUserPoolReturnsAllTwentyStandardAttributes() throws Exception { + JsonNode body = cognitoJson("DescribeUserPool", """ + { "UserPoolId": "%s" } + """.formatted(poolId)); + + JsonNode schema = body.path("UserPool").path("SchemaAttributes"); + assertEquals(20, schema.size(), "DescribeUserPool must include all 20 Cognito standard attributes"); + + java.util.Set names = new java.util.HashSet<>(); + schema.forEach(attr -> names.add(attr.path("Name").asText())); + + for (String expected : List.of("sub", "name", "given_name", "family_name", "middle_name", + "nickname", "preferred_username", "profile", "picture", "website", + "email", "email_verified", "gender", "birthdate", "zoneinfo", + "locale", "phone_number", "phone_number_verified", "address", "updated_at")) { + assertTrue(names.contains(expected), "Missing standard attribute in DescribeUserPool response: " + expected); + } + + // spot-check: sub must be required and immutable + JsonNode sub = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(schema.elements(), 0), false) + .filter(n -> "sub".equals(n.path("Name").asText())) + .findFirst() + .orElseThrow(); + assertTrue(sub.path("Required").asBoolean(), "sub must be Required"); + assertFalse(sub.path("Mutable").asBoolean(), "sub must not be Mutable"); + } + // ── Groups ──────────────────────────────────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java index 8d6db53e15..4f5c517c76 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoJsonHandlerTest.java @@ -15,6 +15,10 @@ import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.Spliterators; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; import static org.junit.jupiter.api.Assertions.*; @@ -93,8 +97,9 @@ class CognitoJsonHandlerTest { // Check mandatory blocks for Terraform assertNotNull(pool.get("SchemaAttributes")); - assertEquals(1, pool.get("SchemaAttributes").size()); - assertEquals("email", pool.get("SchemaAttributes").get(0).get("Name").asText()); + assertEquals(20, pool.get("SchemaAttributes").size(), + "DescribeUserPool must always return all 20 Cognito standard attributes"); + assertTrue(schemaNames(pool).contains("email")); assertNotNull(pool.get("Policies")); assertNotNull(pool.get("LambdaConfig")); @@ -190,6 +195,80 @@ class CognitoJsonHandlerTest { assertFalse(afterUntag.has("team")); } + @Test + void describeUserPoolWithNoSchemaReturnsAllTwentyStandardAttributes() { + ObjectNode create = mapper.createObjectNode(); + create.put("PoolName", "no-schema-pool"); + JsonNode created = (JsonNode) handler.handle("CreateUserPool", create, "us-east-1").getEntity(); + String poolId = created.get("UserPool").get("Id").asText(); + + ObjectNode describe = mapper.createObjectNode(); + describe.put("UserPoolId", poolId); + JsonNode body = (JsonNode) handler.handle("DescribeUserPool", describe, "us-east-1").getEntity(); + JsonNode schema = body.get("UserPool").get("SchemaAttributes"); + + assertEquals(20, schema.size()); + Set names = schemaNames(body.get("UserPool")); + List.of("sub", "name", "given_name", "family_name", "middle_name", "nickname", + "preferred_username", "profile", "picture", "website", "email", + "email_verified", "gender", "birthdate", "zoneinfo", "locale", + "phone_number", "phone_number_verified", "address", "updated_at") + .forEach(n -> assertTrue(names.contains(n), "missing standard attribute: " + n)); + } + + @Test + void describeUserPoolMergesCustomAttributeAfterStandardOnes() { + ObjectNode create = mapper.createObjectNode(); + create.put("PoolName", "custom-attr-pool"); + ArrayNode schema = create.putArray("Schema"); + ObjectNode custom = schema.addObject(); + custom.put("Name", "custom:tenant_id"); + custom.put("AttributeDataType", "String"); + + JsonNode created = (JsonNode) handler.handle("CreateUserPool", create, "us-east-1").getEntity(); + String poolId = created.get("UserPool").get("Id").asText(); + + ObjectNode describe = mapper.createObjectNode(); + describe.put("UserPoolId", poolId); + JsonNode body = (JsonNode) handler.handle("DescribeUserPool", describe, "us-east-1").getEntity(); + JsonNode schemaNode = body.get("UserPool").get("SchemaAttributes"); + + assertEquals(21, schemaNode.size(), "20 standard + 1 custom"); + Set names = schemaNames(body.get("UserPool")); + assertTrue(names.contains("custom:tenant_id")); + assertTrue(names.contains("sub")); + assertTrue(names.contains("email")); + // custom attribute must be last (after all standard ones) + assertEquals("custom:tenant_id", schemaNode.get(20).get("Name").asText()); + } + + @Test + void describeUserPoolExplicitStandardAttributeOverridesDefault() { + ObjectNode create = mapper.createObjectNode(); + create.put("PoolName", "override-attr-pool"); + ArrayNode schema = create.putArray("Schema"); + ObjectNode emailOverride = schema.addObject(); + emailOverride.put("Name", "email"); + emailOverride.put("AttributeDataType", "String"); + emailOverride.put("Required", true); + + JsonNode created = (JsonNode) handler.handle("CreateUserPool", create, "us-east-1").getEntity(); + String poolId = created.get("UserPool").get("Id").asText(); + + ObjectNode describe = mapper.createObjectNode(); + describe.put("UserPoolId", poolId); + JsonNode body = (JsonNode) handler.handle("DescribeUserPool", describe, "us-east-1").getEntity(); + JsonNode schemaNode = body.get("UserPool").get("SchemaAttributes"); + + assertEquals(20, schemaNode.size(), "override should not add a duplicate entry"); + JsonNode emailAttr = StreamSupport.stream(Spliterators.spliteratorUnknownSize( + schemaNode.elements(), 0), false) + .filter(n -> "email".equals(n.get("Name").asText())) + .findFirst() + .orElseThrow(); + assertTrue(emailAttr.get("Required").asBoolean(), "email must be required per the override"); + } + @Test void tagResourceRejectsReservedKey() { ObjectNode createRequest = mapper.createObjectNode(); @@ -207,4 +286,11 @@ class CognitoJsonHandlerTest { ); assertEquals("ValidationException", exception.getErrorCode()); } + + private Set schemaNames(JsonNode pool) { + return StreamSupport.stream( + Spliterators.spliteratorUnknownSize(pool.get("SchemaAttributes").elements(), 0), false) + .map(n -> n.get("Name").asText()) + .collect(Collectors.toSet()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoStandardAttributesTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoStandardAttributesTest.java new file mode 100644 index 0000000000..9a84da1f02 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoStandardAttributesTest.java @@ -0,0 +1,168 @@ +package io.github.hectorvent.floci.services.cognito; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +class CognitoStandardAttributesTest { + + private static final Set EXPECTED_NAMES = Set.of( + "sub", "name", "given_name", "family_name", "middle_name", "nickname", + "preferred_username", "profile", "picture", "website", "email", + "email_verified", "gender", "birthdate", "zoneinfo", "locale", + "phone_number", "phone_number_verified", "address", "updated_at"); + + @Test + void defaultsContainsAllTwentyStandardAttributes() { + assertEquals(20, CognitoStandardAttributes.DEFAULTS.size()); + Set names = names(CognitoStandardAttributes.DEFAULTS); + assertEquals(EXPECTED_NAMES, names); + } + + @Test + void subIsRequiredAndImmutable() { + Map sub = findByName(CognitoStandardAttributes.DEFAULTS, "sub"); + assertEquals("String", sub.get("AttributeDataType")); + assertEquals(Boolean.TRUE, sub.get("Required")); + assertEquals(Boolean.FALSE, sub.get("Mutable")); + @SuppressWarnings("unchecked") + Map constraints = (Map) sub.get("StringAttributeConstraints"); + assertEquals("1", constraints.get("MinLength")); + assertEquals("2048", constraints.get("MaxLength")); + } + + @Test + void emailHasStringConstraints() { + Map email = findByName(CognitoStandardAttributes.DEFAULTS, "email"); + assertEquals("String", email.get("AttributeDataType")); + assertEquals(Boolean.FALSE, email.get("Required")); + assertEquals(Boolean.TRUE, email.get("Mutable")); + @SuppressWarnings("unchecked") + Map constraints = (Map) email.get("StringAttributeConstraints"); + assertEquals("0", constraints.get("MinLength")); + assertEquals("2048", constraints.get("MaxLength")); + } + + @Test + void birthdateHasTenCharacterConstraint() { + Map birthdate = findByName(CognitoStandardAttributes.DEFAULTS, "birthdate"); + @SuppressWarnings("unchecked") + Map constraints = (Map) birthdate.get("StringAttributeConstraints"); + assertEquals("10", constraints.get("MinLength")); + assertEquals("10", constraints.get("MaxLength")); + } + + @Test + void updatedAtIsNumberType() { + Map updatedAt = findByName(CognitoStandardAttributes.DEFAULTS, "updated_at"); + assertEquals("Number", updatedAt.get("AttributeDataType")); + @SuppressWarnings("unchecked") + Map constraints = (Map) updatedAt.get("NumberAttributeConstraints"); + assertNotNull(constraints); + assertEquals("0", constraints.get("MinValue")); + } + + @Test + void emailVerifiedAndPhoneVerifiedAreBooleanType() { + for (String name : List.of("email_verified", "phone_number_verified")) { + Map attr = findByName(CognitoStandardAttributes.DEFAULTS, name); + assertEquals("Boolean", attr.get("AttributeDataType"), name + " should be Boolean"); + assertFalse(attr.containsKey("StringAttributeConstraints"), name + " should have no string constraints"); + } + } + + @Test + void noDeveloperOnlyAttributeInStandardAttrs() { + for (Map attr : CognitoStandardAttributes.DEFAULTS) { + assertEquals(Boolean.FALSE, attr.get("DeveloperOnlyAttribute"), + attr.get("Name") + " should not be developer-only"); + } + } + + // ── merge() ────────────────────────────────────────────────────────────── + + @Test + void mergeWithNullReturnsAllDefaults() { + List> result = CognitoStandardAttributes.merge(null); + assertEquals(20, result.size()); + assertEquals(EXPECTED_NAMES, names(result)); + } + + @Test + void mergeWithEmptyListReturnsAllDefaults() { + List> result = CognitoStandardAttributes.merge(List.of()); + assertEquals(20, result.size()); + assertEquals(EXPECTED_NAMES, names(result)); + } + + @Test + void mergeAppendsCustomAttributeAfterStandardOnes() { + List> schema = List.of( + Map.of("Name", "custom:department", "AttributeDataType", "String")); + + List> result = CognitoStandardAttributes.merge(schema); + + assertEquals(21, result.size()); + assertTrue(names(result).contains("custom:department")); + assertTrue(names(result).containsAll(EXPECTED_NAMES)); + assertEquals("custom:department", result.get(20).get("Name"), + "custom attribute must come after all standard ones"); + } + + @Test + void mergeWithMultipleCustomAttributesAppendsAllInOrder() { + List> schema = List.of( + Map.of("Name", "custom:tenant_id", "AttributeDataType", "String"), + Map.of("Name", "custom:role", "AttributeDataType", "String")); + + List> result = CognitoStandardAttributes.merge(schema); + + assertEquals(22, result.size()); + assertEquals("custom:tenant_id", result.get(20).get("Name")); + assertEquals("custom:role", result.get(21).get("Name")); + } + + @Test + void mergeWithExplicitStandardAttributeOverridesDefault() { + Map override = Map.of( + "Name", "email", + "AttributeDataType", "String", + "Required", Boolean.TRUE, + "Mutable", Boolean.TRUE); + + List> result = CognitoStandardAttributes.merge(List.of(override)); + + assertEquals(20, result.size(), "override must not create a duplicate"); + Map emailAttr = findByName(result, "email"); + assertEquals(Boolean.TRUE, emailAttr.get("Required"), + "email Required should reflect the override"); + } + + @Test + void mergePreservesStandardAttributeOrder() { + List> result = CognitoStandardAttributes.merge(null); + // sub must be first + assertEquals("sub", result.get(0).get("Name")); + // updated_at must be last among standard attrs (index 19) + assertEquals("updated_at", result.get(19).get("Name")); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private static Set names(List> attrs) { + return attrs.stream().map(a -> (String) a.get("Name")).collect(Collectors.toSet()); + } + + private static Map findByName(List> attrs, String name) { + return attrs.stream() + .filter(a -> name.equals(a.get("Name"))) + .findFirst() + .orElseThrow(() -> new AssertionError("attribute not found: " + name)); + } +}