From 2201c70ef160ab0ecfcccbb3adfb04e37e5b180c Mon Sep 17 00:00:00 2001 From: TiM Date: Thu, 23 Apr 2026 15:52:42 +1200 Subject: [PATCH] feat(cognito,kms): allow caller-pinned resource IDs via reserved tag prefix (#568) Allow KMS CreateKey and Cognito CreateUserPool to accept a reserved floci:override-id tag at creation time so tests can pin deterministic resource IDs without a lookup round trip. Strip reserved floci:* tags from stored metadata and responses, reject reserved tags on KMS TagResource, wire KMS CloudFormation provisioning through tagged key creation, and add focused unit, handler, integration, and AWS CLI bats coverage for the new behavior. --- CHANGELOG.md | 1 + .../sdk-test-awscli/test/cognito.bats | 32 +++++ .../sdk-test-awscli/test/kms.bats | 40 ++++++ docs/services/cognito.md | 2 + docs/services/kms.md | 3 +- .../floci/core/common/ReservedTags.java | 55 ++++++++ .../CloudFormationResourceProvisioner.java | 3 +- .../services/cognito/CognitoService.java | 37 +++++- .../floci/services/kms/KmsJsonHandler.java | 2 + .../floci/services/kms/KmsService.java | 27 +++- .../floci/core/common/ReservedTagsTest.java | 86 +++++++++++++ .../CloudFormationIntegrationTest.java | 59 +++++++++ .../cognito/CognitoJsonHandlerTest.java | 51 ++++++++ .../services/cognito/CognitoServiceTest.java | 120 ++++++++++++++++++ .../floci/services/kms/KmsServiceTest.java | 62 +++++++++ 15 files changed, 572 insertions(+), 8 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 70047a7768..e83425c521 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * **bedrock-runtime:** add stub for Converse and InvokeModel ([#87](https://github.com/floci-io/floci/issues/87)) * **s3:** preserve explicit object server-side-encryption headers on PutObject, GetObject, HeadObject, CopyObject, and multipart uploads +* **cognito,kms:** allow caller-pinned resource IDs via the reserved `floci:override-id` tag channel ([#460](https://github.com/floci-io/floci/issues/460)) ### Bug Fixes diff --git a/compatibility-tests/sdk-test-awscli/test/cognito.bats b/compatibility-tests/sdk-test-awscli/test/cognito.bats index ba0eb942c2..b8f8ade3b5 100644 --- a/compatibility-tests/sdk-test-awscli/test/cognito.bats +++ b/compatibility-tests/sdk-test-awscli/test/cognito.bats @@ -155,3 +155,35 @@ teardown() { assert_success POOL_ID="" } + +@test "Cognito: create user pool with reserved override tag uses pinned ID and strips reserved tag" { + run aws_cmd cognito-idp create-user-pool \ + --pool-name "bats-test-pool-$(unique_name)" \ + --user-pool-tags floci:override-id=us-east-1_batspool1,env=test + assert_success + POOL_ID=$(json_get "$output" '.UserPool.Id') + [ "$POOL_ID" = "us-east-1_batspool1" ] + + has_reserved=$(echo "$output" | jq '.UserPool.UserPoolTags | has("floci:override-id")') + [ "$has_reserved" = "false" ] + + run aws_cmd cognito-idp describe-user-pool --user-pool-id "$POOL_ID" + assert_success + has_reserved=$(echo "$output" | jq '.UserPool.UserPoolTags | has("floci:override-id")') + [ "$has_reserved" = "false" ] + env_value=$(json_get "$output" '.UserPool.UserPoolTags.env') + [ "$env_value" = "test" ] +} + +@test "Cognito: duplicate reserved override tag fails with ResourceConflictException" { + out=$(aws_cmd cognito-idp create-user-pool \ + --pool-name "bats-test-pool-$(unique_name)" \ + --user-pool-tags floci:override-id=us-east-1_batsdup01) + POOL_ID=$(json_get "$out" '.UserPool.Id') + + run aws_cmd cognito-idp create-user-pool \ + --pool-name "bats-test-pool-$(unique_name)" \ + --user-pool-tags floci:override-id=us-east-1_batsdup01 + assert_failure + [[ "$output" == *"ResourceConflictException"* ]] +} diff --git a/compatibility-tests/sdk-test-awscli/test/kms.bats b/compatibility-tests/sdk-test-awscli/test/kms.bats index 8a462744a2..a693981400 100644 --- a/compatibility-tests/sdk-test-awscli/test/kms.bats +++ b/compatibility-tests/sdk-test-awscli/test/kms.bats @@ -145,3 +145,43 @@ teardown() { found=$(echo "$output" | jq --arg name "$alias_name" '.Aliases | any(.AliasName == $name)') [ "$found" = "false" ] } + +@test "KMS: create key with reserved override tag uses pinned ID and strips reserved tag" { + run aws_cmd kms create-key \ + --description "override-key" \ + --tags TagKey=floci:override-id,TagValue=bats-pinned-key TagKey=env,TagValue=test + assert_success + KEY_ID=$(json_get "$output" '.KeyMetadata.KeyId') + [ "$KEY_ID" = "bats-pinned-key" ] + + run aws_cmd kms list-resource-tags --key-id "$KEY_ID" + assert_success + has_reserved=$(echo "$output" | jq 'any(.Tags[]?; .TagKey == "floci:override-id")') + [ "$has_reserved" = "false" ] + env_value=$(echo "$output" | jq -r '.Tags[] | select(.TagKey == "env") | .TagValue') + [ "$env_value" = "test" ] +} + +@test "KMS: duplicate reserved override tag fails with AlreadyExistsException" { + out=$(aws_cmd kms create-key \ + --description "override-key" \ + --tags TagKey=floci:override-id,TagValue=bats-duplicate-key) + KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId') + + run aws_cmd kms create-key \ + --description "override-key-2" \ + --tags TagKey=floci:override-id,TagValue=bats-duplicate-key + assert_failure + [[ "$output" == *"AlreadyExistsException"* ]] +} + +@test "KMS: tag-resource rejects reserved override tag after creation" { + out=$(aws_cmd kms create-key --description "bats-test-key") + KEY_ID=$(json_get "$out" '.KeyMetadata.KeyId') + + run aws_cmd kms tag-resource \ + --key-id "$KEY_ID" \ + --tags TagKey=floci:override-id,TagValue=late-id + assert_failure + [[ "$output" == *"ValidationException"* ]] +} diff --git a/docs/services/cognito.md b/docs/services/cognito.md index e9acaf9c09..c849cc55a4 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -5,6 +5,8 @@ Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys. +`CreateUserPool` accepts a reserved user-pool tag, `floci:override-id`, to pin the resulting `UserPool.Id` at creation time. Floci strips reserved `floci:*` tags from stored and returned `UserPoolTags` on both create and update paths, so the tag namespace acts as an input-only control channel and is never persisted as user-visible metadata. + ## Supported Actions | Category | Actions | diff --git a/docs/services/kms.md b/docs/services/kms.md index 11f7bccff8..6956e530ea 100644 --- a/docs/services/kms.md +++ b/docs/services/kms.md @@ -66,4 +66,5 @@ aws kms generate-data-key \ --key-id alias/my-key \ --key-spec AES_256 \ --endpoint-url $AWS_ENDPOINT_URL -``` \ No newline at end of file +``` +`CreateKey` also accepts a reserved creation-time tag key, `floci:override-id`, when tests need a deterministic `KeyId`. Floci uses the tag value as the created key id, strips the reserved tag from stored resource tags, and rejects attempts to add `floci:*` tags later via `TagResource`. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java b/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java new file mode 100644 index 0000000000..8123b95a7a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ReservedTags.java @@ -0,0 +1,55 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.HashMap; +import java.util.Map; + +@RegisterForReflection +public final class ReservedTags { + + public static final String RESERVED_PREFIX = "floci:"; + public static final String OVERRIDE_ID_KEY = RESERVED_PREFIX + "override-id"; + + private ReservedTags() { + } + + public static String extractOverrideId(Map tags) { + if (tags == null) { + return null; + } + return tags.get(OVERRIDE_ID_KEY); + } + + public static Map stripReservedTags(Map tags) { + Map stripped = new HashMap<>(); + if (tags == null) { + return stripped; + } + tags.forEach((key, value) -> { + if (!isReserved(key)) { + stripped.put(key, value); + } + }); + return stripped; + } + + public static void rejectReservedTagsOnUpdate(Map tags) { + if (tags == null) { + return; + } + for (String key : tags.keySet()) { + if (isReserved(key)) { + throw new AwsException( + "ValidationException", + "Reserved tag keys with prefix " + RESERVED_PREFIX + " can only be supplied during resource creation.", + 400 + ); + } + } + } + + private static boolean isReserved(String key) { + return key != null && key.startsWith(RESERVED_PREFIX); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index be468bfc0a..dc19d2e43f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -543,7 +543,8 @@ public class CloudFormationResourceProvisioner { private void provisionKmsKey(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region, String accountId) { String description = resolveOptional(props, "Description", engine); - var key = kmsService.createKey(description, region); + Map tags = parseCfnTags(props != null ? props.get("Tags") : null, engine); + var key = kmsService.createKey(description, null, tags, region); r.setPhysicalId(key.getKeyId()); r.getAttributes().put("Arn", key.getArn()); r.getAttributes().put("KeyId", key.getKeyId()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 539220c776..3709846975 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.cognito.model.*; @@ -78,7 +79,11 @@ public class CognitoService { @SuppressWarnings("unchecked") public UserPool createUserPool(Map request, String region) { String name = (String) request.get("PoolName"); - String id = region + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9); + Map userPoolTags = (Map) request.get("UserPoolTags"); + String id = resolveUserPoolId(region, userPoolTags); + if (poolStore.get(id).isPresent()) { + throw new AwsException("ResourceConflictException", "User pool already exists", 400); + } UserPool pool = new UserPool(); pool.setId(id); pool.setName(name); @@ -122,7 +127,9 @@ public class CognitoService { if (request.containsKey("DeviceConfiguration")) pool.setDeviceConfiguration((Map) request.get("DeviceConfiguration")); if (request.containsKey("EmailConfiguration")) pool.setEmailConfiguration((Map) request.get("EmailConfiguration")); if (request.containsKey("SmsConfiguration")) pool.setSmsConfiguration((Map) request.get("SmsConfiguration")); - if (request.containsKey("UserPoolTags")) pool.setUserPoolTags((Map) request.get("UserPoolTags")); + if (request.containsKey("UserPoolTags")) { + pool.setUserPoolTags(ReservedTags.stripReservedTags((Map) request.get("UserPoolTags"))); + } if (request.containsKey("AdminCreateUserConfig")) pool.setAdminCreateUserConfig((Map) request.get("AdminCreateUserConfig")); if (request.containsKey("UserPoolAddOns")) pool.setUserPoolAddOns((Map) request.get("UserPoolAddOns")); if (request.containsKey("UsernameConfiguration")) pool.setUsernameConfiguration((Map) request.get("UsernameConfiguration")); @@ -872,6 +879,32 @@ public class CognitoService { return baseUrl + "/" + poolId; } + private String resolveUserPoolId(String region, Map tags) { + String overrideId = ReservedTags.extractOverrideId(tags); + if (overrideId == null) { + return region + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 9); + } + validateOverridePoolId(overrideId); + return overrideId.trim(); + } + + private void validateOverridePoolId(String overrideId) { + if (overrideId == null || overrideId.trim().isEmpty()) { + throw new AwsException("ValidationException", "Override resource ID must not be blank.", 400); + } + + String normalized = overrideId.trim(); + if (normalized.chars().anyMatch(Character::isWhitespace)) { + throw new AwsException("ValidationException", "Override resource ID must not contain whitespace.", 400); + } + if (normalized.indexOf('/') >= 0 || normalized.indexOf('?') >= 0 || normalized.indexOf('#') >= 0) { + throw new AwsException("ValidationException", "Override resource ID contains unsupported characters.", 400); + } + if (normalized.chars().anyMatch(Character::isISOControl)) { + throw new AwsException("ValidationException", "Override resource ID must not contain control characters.", 400); + } + } + public String getJwksUri(String poolId) { return getIssuer(poolId) + "/.well-known/jwks.json"; } diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java index 3eb3ad6b23..d7d276af20 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.kms; import io.github.hectorvent.floci.core.common.AwsErrorResponse; +import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.services.kms.model.KmsAlias; import io.github.hectorvent.floci.services.kms.model.KmsKey; import com.fasterxml.jackson.databind.JsonNode; @@ -279,6 +280,7 @@ public class KmsJsonHandler { String keyId = request.path("KeyId").asText(); Map tags = new HashMap<>(); request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText())); + ReservedTags.rejectReservedTagsOnUpdate(tags); service.tagResource(keyId, tags, region); return Response.ok(objectMapper.createObjectNode()).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 1424ea9d62..c0bbd1519a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kms; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.kms.model.KmsAlias; @@ -78,7 +79,10 @@ public class KmsService { } public KmsKey createKey(String description, String keyUsage, String customerMasterKeySpec, String policy, Map tags, String region) { - String keyId = UUID.randomUUID().toString(); + String keyId = resolveKeyId(tags); + if (keyStore.get(region + "::" + keyId).isPresent()) { + throw new AwsException("AlreadyExistsException", "Key already exists", 400); + } String arn = regionResolver.buildArn("kms", region, "key/" + keyId); String effectiveUsage = keyUsage != null ? keyUsage : "ENCRYPT_DECRYPT"; @@ -92,9 +96,7 @@ public class KmsService { key.setKeyUsage(effectiveUsage); key.setCustomerMasterKeySpec(effectiveSpec); key.setPolicy(policy != null ? policy : DEFAULT_KEY_POLICY); - if (tags != null) { - key.getTags().putAll(tags); - } + key.getTags().putAll(ReservedTags.stripReservedTags(tags)); generateKeyMaterial(key); @@ -103,6 +105,22 @@ public class KmsService { return key; } + private String resolveKeyId(Map tags) { + String overrideId = ReservedTags.extractOverrideId(tags); + if (overrideId == null) { + return UUID.randomUUID().toString(); + } + + String normalized = overrideId.trim(); + if (normalized.isEmpty()) { + throw new AwsException("ValidationException", "Override resource ID must not be blank.", 400); + } + if (normalized.length() > 256) { + throw new AwsException("ValidationException", "Override resource ID must be 256 characters or fewer.", 400); + } + return normalized; + } + private void generateKeyMaterial(KmsKey key) { String spec = key.getCustomerMasterKeySpec(); if ("SYMMETRIC_DEFAULT".equals(spec)) { @@ -448,6 +466,7 @@ public class KmsService { public void tagResource(String keyId, Map tags, String region) { KmsKey key = resolveKey(keyId, region); + ReservedTags.rejectReservedTagsOnUpdate(tags); key.getTags().putAll(tags); keyStore.put(region + "::" + key.getKeyId(), key); } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java new file mode 100644 index 0000000000..d0f64e65f3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/ReservedTagsTest.java @@ -0,0 +1,86 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ReservedTagsTest { + + @Test + void stripReservedTagsReturnsEmptyMapForNullInput() { + assertTrue(ReservedTags.stripReservedTags(null).isEmpty()); + } + + @Test + void stripReservedTagsReturnsEmptyMapForEmptyInput() { + assertTrue(ReservedTags.stripReservedTags(Map.of()).isEmpty()); + } + + @Test + void stripReservedTagsKeepsNonReservedTags() { + Map tags = Map.of("env", "test", "team", "platform"); + + assertEquals(tags, ReservedTags.stripReservedTags(tags)); + } + + @Test + void stripReservedTagsRemovesOnlyReservedTags() { + Map tags = new LinkedHashMap<>(); + tags.put("env", "test"); + tags.put(ReservedTags.OVERRIDE_ID_KEY, "my-id"); + tags.put("floci:internal", "hidden"); + tags.put("team", "platform"); + + Map stripped = ReservedTags.stripReservedTags(tags); + + assertEquals(Map.of("env", "test", "team", "platform"), stripped); + } + + @Test + void stripReservedTagsRemovesAllReservedTags() { + Map tags = Map.of( + ReservedTags.OVERRIDE_ID_KEY, "my-id", + "floci:internal", "hidden" + ); + + assertTrue(ReservedTags.stripReservedTags(tags).isEmpty()); + } + + @Test + void extractOverrideIdReturnsNullForNullInput() { + assertNull(ReservedTags.extractOverrideId(null)); + } + + @Test + void extractOverrideIdReturnsReservedOverrideOnly() { + Map tags = Map.of( + ReservedTags.OVERRIDE_ID_KEY, "my-id", + "floci:internal", "hidden", + "env", "test" + ); + + assertEquals("my-id", ReservedTags.extractOverrideId(tags)); + } + + @Test + void rejectReservedTagsOnUpdateAllowsNormalTags() { + assertDoesNotThrow(() -> ReservedTags.rejectReservedTagsOnUpdate(Map.of("env", "test"))); + } + + @Test + void rejectReservedTagsOnUpdateRejectsReservedTags() { + AwsException exception = assertThrows( + AwsException.class, + () -> ReservedTags.rejectReservedTagsOnUpdate(Map.of(ReservedTags.OVERRIDE_ID_KEY, "my-id")) + ); + + assertEquals("ValidationException", exception.getErrorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index 3017b72d1e..6b1325ee75 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -17,9 +17,11 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.matchesRegex; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; @QuarkusTest @@ -244,6 +246,63 @@ class CloudFormationIntegrationTest { .body("Configuration.FunctionName", equalTo("cfn-nocode-func")); } + @Test + void createStack_kmsKeyWithOverrideTagUsesPinnedId() { + String template = """ + { + "Resources": { + "MyKey": { + "Type": "AWS::KMS::Key", + "Properties": { + "Description": "cfn override key", + "Tags": [ + { "Key": "floci:override-id", "Value": "cfn-pinned-key" }, + { "Key": "env", "Value": "test" } + ] + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-kms-override-stack") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "TrentService.DescribeKey") + .body(""" + {"KeyId":"cfn-pinned-key"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("KeyMetadata.KeyId", equalTo("cfn-pinned-key")); + + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "TrentService.ListResourceTags") + .body(""" + {"KeyId":"cfn-pinned-key"} + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("Tags.TagKey", hasItem("env")) + .body("Tags.find { it.TagKey == 'env' }.TagValue", equalTo("test")) + .body("Tags.find { it.TagKey == 'floci:override-id' }", nullValue()); + } + @Test void createStack_lambdaWithEnvironmentVariables() { String template = """ 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 5788026dd5..c99c33486e 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 @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.cognito.model.UserPool; @@ -100,4 +101,54 @@ class CognitoJsonHandlerTest { assertNotNull(pool.get("AccountRecoverySetting")); assertEquals("ESSENTIALS", pool.get("UserPoolTier").asText()); } + + @Test + void createUserPoolResponseDoesNotLeakReservedTag() { + ObjectNode request = mapper.createObjectNode(); + request.put("PoolName", "pinned-pool"); + ObjectNode tags = request.putObject("UserPoolTags"); + tags.put(ReservedTags.OVERRIDE_ID_KEY, "us-east-1_testpool1"); + tags.put("env", "test"); + + Response response = handler.handle("CreateUserPool", request, "us-east-1"); + assertEquals(200, response.getStatus()); + + JsonNode body = (JsonNode) response.getEntity(); + JsonNode pool = body.get("UserPool"); + assertEquals("us-east-1_testpool1", pool.get("Id").asText()); + assertEquals("test", pool.get("UserPoolTags").get("env").asText()); + assertFalse(pool.get("UserPoolTags").has(ReservedTags.OVERRIDE_ID_KEY)); + } + + @Test + void updateAndDescribeUserPoolResponsesDoNotLeakReservedTag() { + ObjectNode createRequest = mapper.createObjectNode(); + createRequest.put("PoolName", "update-pool"); + JsonNode createBody = (JsonNode) handler.handle("CreateUserPool", createRequest, "us-east-1").getEntity(); + String poolId = createBody.get("UserPool").get("Id").asText(); + + ObjectNode updateRequest = mapper.createObjectNode(); + updateRequest.put("UserPoolId", poolId); + ObjectNode tags = updateRequest.putObject("UserPoolTags"); + tags.put(ReservedTags.OVERRIDE_ID_KEY, "late-id"); + tags.put("env", "test"); + + Response updateResponse = handler.handle("UpdateUserPool", updateRequest, "us-east-1"); + assertEquals(200, updateResponse.getStatus()); + + JsonNode updateBody = (JsonNode) updateResponse.getEntity(); + JsonNode updatedPool = updateBody.get("UserPool"); + assertEquals("test", updatedPool.get("UserPoolTags").get("env").asText()); + assertFalse(updatedPool.get("UserPoolTags").has(ReservedTags.OVERRIDE_ID_KEY)); + + ObjectNode describeRequest = mapper.createObjectNode(); + describeRequest.put("UserPoolId", poolId); + Response describeResponse = handler.handle("DescribeUserPool", describeRequest, "us-east-1"); + assertEquals(200, describeResponse.getStatus()); + + JsonNode describeBody = (JsonNode) describeResponse.getEntity(); + JsonNode describedPool = describeBody.get("UserPool"); + assertEquals("test", describedPool.get("UserPoolTags").get("env").asText()); + assertFalse(describedPool.get("UserPoolTags").has(ReservedTags.OVERRIDE_ID_KEY)); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index 4a1ff43d07..776d5bcad3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.cognito.model.CognitoGroup; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; @@ -72,6 +73,125 @@ class CognitoServiceTest { assertEquals(List.of("email"), pool.getUsernameAttributes()); } + @Test + void createUserPoolWithOverrideIdUsesProvidedId() { + UserPool pool = service.createUserPool( + Map.of( + "PoolName", "PinnedPool", + "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "us-east-1_testpool1") + ), + "us-east-1" + ); + + assertEquals("us-east-1_testpool1", pool.getId()); + assertEquals("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_testpool1", pool.getArn()); + } + + @Test + void createUserPoolWithOverrideIdStripsReservedTagOnCreate() { + UserPool pool = service.createUserPool( + Map.of( + "PoolName", "PinnedPool", + "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "us-east-1_testpool1", "env", "test") + ), + "us-east-1" + ); + + assertEquals(Map.of("env", "test"), pool.getUserPoolTags()); + assertFalse(pool.getUserPoolTags().containsKey(ReservedTags.OVERRIDE_ID_KEY)); + } + + @Test + void createUserPoolWithDuplicateOverrideIdThrowsResourceConflict() { + service.createUserPool( + Map.of("PoolName", "PinnedPool", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "us-east-1_testpool1")), + "us-east-1" + ); + + AwsException exception = assertThrows( + AwsException.class, + () -> service.createUserPool( + Map.of("PoolName", "PinnedPool2", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "us-east-1_testpool1")), + "us-east-1" + ) + ); + + assertEquals("ResourceConflictException", exception.getErrorCode()); + } + + @Test + void createUserPoolWithBlankOverrideIdThrowsValidation() { + AwsException exception = assertThrows( + AwsException.class, + () -> service.createUserPool( + Map.of("PoolName", "PinnedPool", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, " ")), + "us-east-1" + ) + ); + + assertEquals("ValidationException", exception.getErrorCode()); + } + + @Test + void createUserPoolWithSlashInOverrideThrowsValidation() { + AwsException exception = assertThrows( + AwsException.class, + () -> service.createUserPool( + Map.of("PoolName", "PinnedPool", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "bad/pool")), + "us-east-1" + ) + ); + + assertEquals("ValidationException", exception.getErrorCode()); + } + + @Test + void createUserPoolWithQuestionMarkOrHashInOverrideThrowsValidation() { + AwsException questionMarkException = assertThrows( + AwsException.class, + () -> service.createUserPool( + Map.of("PoolName", "PinnedPool", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "bad?pool")), + "us-east-1" + ) + ); + assertEquals("ValidationException", questionMarkException.getErrorCode()); + + AwsException hashException = assertThrows( + AwsException.class, + () -> service.createUserPool( + Map.of("PoolName", "PinnedPool", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "bad#pool")), + "us-east-1" + ) + ); + assertEquals("ValidationException", hashException.getErrorCode()); + } + + @Test + void updateUserPoolWithReservedTagStripsIt() { + UserPool pool = service.createUserPool(Map.of("PoolName", "PinnedPool"), "us-east-1"); + + service.updateUserPool( + Map.of( + "UserPoolId", pool.getId(), + "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "late-id", "env", "test") + ), + "us-east-1" + ); + + UserPool updated = service.describeUserPool(pool.getId()); + assertEquals(Map.of("env", "test"), updated.getUserPoolTags()); + } + + @Test + void issuerUrlForPinnedPoolResolvesAsBaseUrlSlashPoolId() { + UserPool pool = service.createUserPool( + Map.of("PoolName", "PinnedPool", "UserPoolTags", Map.of(ReservedTags.OVERRIDE_ID_KEY, "custompool")), + "us-east-1" + ); + + assertEquals("http://localhost:4566/custompool", service.getIssuer(pool.getId())); + } + // ========================================================================= // Groups // ========================================================================= diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index 8025e081fc..7cdd77bf9f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kms; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.ReservedTags; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.kms.model.KmsAlias; import io.github.hectorvent.floci.services.kms.model.KmsKey; @@ -288,6 +289,67 @@ class KmsServiceTest { assertTrue(key.getTags().isEmpty()); } + @Test + void createKeyWithOverrideIdUsesProvidedId() { + KmsKey key = kmsService.createKey( + "tagged-key", + null, + Map.of(ReservedTags.OVERRIDE_ID_KEY, "my-test-key"), + REGION + ); + + assertEquals("my-test-key", key.getKeyId()); + assertEquals("arn:aws:kms:us-east-1:000000000000:key/my-test-key", key.getArn()); + } + + @Test + void createKeyWithOverrideIdStripsReservedTagFromStoredKey() { + KmsKey key = kmsService.createKey( + "tagged-key", + null, + Map.of(ReservedTags.OVERRIDE_ID_KEY, "my-test-key", "env", "test"), + REGION + ); + + KmsKey found = kmsService.describeKey(key.getKeyId(), REGION); + assertEquals("test", found.getTags().get("env")); + assertFalse(found.getTags().containsKey(ReservedTags.OVERRIDE_ID_KEY)); + } + + @Test + void createKeyWithDuplicateOverrideIdThrowsAlreadyExists() { + kmsService.createKey("first", null, Map.of(ReservedTags.OVERRIDE_ID_KEY, "my-test-key"), REGION); + + AwsException exception = assertThrows( + AwsException.class, + () -> kmsService.createKey("second", null, Map.of(ReservedTags.OVERRIDE_ID_KEY, "my-test-key"), REGION) + ); + + assertEquals("AlreadyExistsException", exception.getErrorCode()); + } + + @Test + void createKeyWithBlankOverrideIdThrowsValidation() { + AwsException exception = assertThrows( + AwsException.class, + () -> kmsService.createKey("bad", null, Map.of(ReservedTags.OVERRIDE_ID_KEY, " "), REGION) + ); + + assertEquals("ValidationException", exception.getErrorCode()); + } + + @Test + void tagResourceWithReservedKeyThrowsValidation() { + KmsKey key = kmsService.createKey(null, REGION); + + AwsException exception = assertThrows( + AwsException.class, + () -> kmsService.tagResource(key.getKeyId(), Map.of(ReservedTags.OVERRIDE_ID_KEY, "late-id"), REGION) + ); + + assertEquals("ValidationException", exception.getErrorCode()); + } + // ── Issue #258 — GetKeyPolicy ──────────────────────────────────────────── @Test