From 501e15205cfa1042c495ee22bf5ca4221dc8d6a2 Mon Sep 17 00:00:00 2001 From: soreavis <263610811+soreavis@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:18:55 +0100 Subject: [PATCH] fix(lambda): keep code signing config tags and support tagging configs (#10066) CreateCodeSigningConfig ignored its Tags, and TagResource, UntagResource and ListTags refused a code-signing-config ARN. Create now checks the tag keys as TagResource does and keeps the tags in their own store, so the CodeSigningConfig the reads return still has no Tags. The tag operations serve a configuration ARN from that store, answer ResourceNotFoundException for one the caller doesn't hold, and write under the configuration lock, so a tag write can't outlive a concurrent delete. Delete drops the tags, and storedTags returns them for aws:ResourceTag conditions. --- docs/services/iam.md | 5 +- docs/services/lambda.md | 6 +- ...aCodeSigningConfigFunctionsController.java | 10 +- .../LambdaCodeSigningConfigService.java | 70 ++++++++++ .../aws/services/lambda/LambdaService.java | 21 ++- .../lambda/LambdaStoredResourceArns.java | 5 +- ...LambdaCodeSigningConfigDeleteRaceTest.java | 129 ++++++++++++------ ...SigningConfigLifecycleIntegrationTest.java | 119 +++++++++++++++- .../LambdaResourceTagIamIntegrationTest.java | 50 +++++++ .../services/lambda/LambdaStoredTagsTest.java | 36 ++++- 10 files changed, 394 insertions(+), 57 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index 2d19299b5c..714a1dc3cc 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4057,8 +4057,9 @@ floci populates: Secrets Manager answers for its secrets, S3 Tables for its table buckets and tables, EventBridge Scheduler for its schedule groups, EventBridge for its event buses and rules, RDS for its resources and DocumentDB's, CloudFormation for its stacks, stack sets and change sets, Lambda for its functions, their versions and aliases - (the function's tags), event source mappings, web functions, their revisions and endpoints (the web function's - tags), MicroVM images and network connectors, Glue for its schema registries and schemas and for the jobs, + (the function's tags), event source mappings, code signing configurations, web functions, their revisions and + endpoints (the web function's tags), MicroVM images and network connectors, Glue for its schema registries and + schemas and for the jobs, crawlers, triggers, workflows, connections, databases, tables and other resources it tags, Step Functions for its state machines, their versions and executions (the state machine's tags) and activities, CodeBuild for its projects and report groups, Athena for its workgroups and data catalogs, Redshift Serverless for its namespaces, diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 880786643c..f8983b8657 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -56,9 +56,9 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `AddLayerVersionPermission` | Grant an account, an organization or everyone `lambda:GetLayerVersion` on a layer version | | `GetLayerVersionPolicy` | Get a layer version's resource-based policy and its revision | | `RemoveLayerVersionPermission` | Remove a statement from a layer version's policy | -| `ListTags` | List tags on a function or event source mapping | -| `TagResource` | Tag a function or event source mapping | -| `UntagResource` | Untag a function or event source mapping | +| `ListTags` | List tags on a function, event source mapping or code signing configuration | +| `TagResource` | Tag a function, event source mapping or code signing configuration | +| `UntagResource` | Untag a function, event source mapping or code signing configuration | | `PutFunctionConcurrency` | Set reserved concurrent executions | | `GetFunctionConcurrency` | Get reserved concurrent executions | | `DeleteFunctionConcurrency` | Clear reserved concurrent executions | diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigFunctionsController.java b/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigFunctionsController.java index 9bd903d4ec..456db629a0 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigFunctionsController.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigFunctionsController.java @@ -21,9 +21,12 @@ import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; +import tools.jackson.core.type.TypeReference; import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; +import java.util.Map; + /** * The code signing configuration resource, all under /2020-04-22/code-signing-configs. * @@ -48,6 +51,7 @@ public class LambdaCodeSigningConfigFunctionsController { private static final int MAX_ITEMS_MIN = 1; private static final int MAX_ITEMS_MAX = 10000; + private static final TypeReference> MAP_TYPE = new TypeReference<>() {}; private final LambdaCodeSigningConfigService service; private final LambdaService lambdaService; @@ -98,7 +102,7 @@ public class LambdaCodeSigningConfigFunctionsController { public Response createCodeSigningConfig(@Context HttpHeaders headers, ObjectNode body) { String region = regionResolver.resolveRegion(headers); CodeSigningConfig config = service.create(region, regionResolver.getAccountId(), - text(body, "Description"), allowedPublishers(body), policies(body)); + text(body, "Description"), allowedPublishers(body), policies(body), tags(body)); return Response.status(Response.Status.CREATED).entity(wrap(config)).build(); } @@ -179,6 +183,10 @@ public class LambdaCodeSigningConfigFunctionsController { CodeSigningConfig.CodeSigningPolicies.class); } + private Map tags(ObjectNode body) { + return body == null ? null : LambdaService.requestTags(objectMapper.convertValue(body, MAP_TYPE)); + } + private int parseMaxItems(String maxItems) { if (maxItems == null || maxItems.isBlank()) { return MAX_ITEMS_MAX; diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigService.java b/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigService.java index 6169adc477..97da7b709f 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigService.java @@ -6,6 +6,7 @@ import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.SignedMarkers; import io.floci.aws.core.common.SmithyValidationErrors; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.lambda.model.CodeSigningConfig; @@ -19,8 +20,10 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Consumer; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -57,6 +60,8 @@ public class LambdaCodeSigningConfigService { DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").withZone(ZoneOffset.UTC); private final StorageBackend store; + /** Apart from the configurations, which the responses serialize as stored: AWS's CodeSigningConfig has no Tags. */ + private final StorageBackend> tagStore; private final RegionResolver regionResolver; private final SignedMarkers markers = new SignedMarkers(); private final SecureRandom random = new SecureRandom(); @@ -67,6 +72,8 @@ public class LambdaCodeSigningConfigService { this.regionResolver = regionResolver; this.store = storageFactory.create("lambda", "lambda-code-signing-configs.json", new TypeReference>() {}); + this.tagStore = storageFactory.create("lambda", "lambda-code-signing-config-tags.json", + new TypeReference>>() {}); Arrays.setAll(configLocks, ignored -> new Object()); } @@ -80,9 +87,16 @@ public class LambdaCodeSigningConfigService { public CodeSigningConfig create(String region, String accountId, String description, CodeSigningConfig.AllowedPublishers allowedPublishers, CodeSigningConfig.CodeSigningPolicies policies) { + return create(region, accountId, description, allowedPublishers, policies, null); + } + + public CodeSigningConfig create(String region, String accountId, String description, + CodeSigningConfig.AllowedPublishers allowedPublishers, + CodeSigningConfig.CodeSigningPolicies policies, Map tags) { validateDescription(description); validateAllowedPublishers(allowedPublishers); validatePolicies(policies); + LambdaService.validateTagKeys(tags); String id = "csc-" + randomId(); CodeSigningConfig config = new CodeSigningConfig(); @@ -93,6 +107,9 @@ public class LambdaCodeSigningConfigService { config.setAllowedPublishers(allowedPublishers); config.setCodeSigningPolicies(policies != null ? policies : defaultPolicies()); config.setLastModified(now()); + if (tags != null) { + tagStore.put(key(region, id), new HashMap<>(tags)); + } store.put(key(region, id), config); return config; } @@ -174,6 +191,50 @@ public class LambdaCodeSigningConfigService { throw notFound(arn); } store.delete(key(region, id)); + tagStore.delete(key(region, id)); + } + + /** The tags of the configuration {@code arn} names in the caller's account and its own Region. */ + public Map listTags(String accountId, String arn) { + String region = AwsArnUtils.parse(arn).region(); + return tagStore.get(key(region, get(region, accountId, arn).getCodeSigningConfigId())).orElse(Map.of()); + } + + public void tagResource(String accountId, String arn, Map tags) { + retag(accountId, arn, next -> next.putAll(tags)); + } + + public void untagResource(String accountId, String arn, List tagKeys) { + retag(accountId, arn, next -> tagKeys.forEach(next::remove)); + } + + /** + * Writes a changed copy of the tags under the configuration lock, so a tag request cannot store tags for a + * configuration a concurrent delete has removed. + */ + private void retag(String accountId, String arn, Consumer> change) { + String region = AwsArnUtils.parse(arn).region(); + withConfigLock(arn, () -> { + String key = key(region, get(region, accountId, arn).getCodeSigningConfigId()); + Map next = new HashMap<>(tagStore.get(key).orElse(Map.of())); + change.accept(next); + tagStore.put(key, next); + return null; + }); + } + + /** + * The tags of the configuration stored under {@code arn} in the account and Region it names, matched on the whole + * ARN, for a reader outside the owner's request; empty when nothing is stored there. + */ + public Map storedTags(String arn) { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String key = key(parsed.region(), idFromArn(arn)); + return AccountAwareStorageBackend.readInAccount(store, parsed.accountId(), key) + .filter(config -> arn.equals(config.getCodeSigningConfigArn())) + .flatMap(config -> AccountAwareStorageBackend.readInAccount(tagStore, parsed.accountId(), key)) + .map(Map::copyOf) + .orElse(Map.of()); } public List list(String region) { @@ -249,6 +310,15 @@ public class LambdaCodeSigningConfigService { return colon < 0 ? arn : arn.substring(colon + 1); } + /** + * True when {@code arn} is a code signing configuration ARN the tag operations take: the configuration ARN's + * pattern, with the partition their Resource pattern requires. + */ + static boolean ownsArn(String arn) { + return arn != null && arn.length() <= ARN_MAX_LENGTH && CODE_SIGNING_CONFIG_ARN.matcher(arn).matches() + && !AwsArnUtils.parse(arn).partition().isEmpty(); + } + static void validateArn(String arn) { if (arn == null || arn.isBlank() || arn.length() > ARN_MAX_LENGTH diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaService.java b/src/main/java/io/floci/aws/services/lambda/LambdaService.java index 26fd403c00..134be812cb 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaService.java @@ -4484,6 +4484,9 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { // ──────────────────────────── Tags ──────────────────────────── public Map listTags(String functionArn) { + if (LambdaCodeSigningConfigService.ownsArn(functionArn)) { + return codeSigningConfigService.listTags(regionResolver.getAccountId(), functionArn); + } EventSourceMapping esm = taggedEventSourceMapping(functionArn); if (esm != null) { return esm.getTags(); @@ -4495,6 +4498,10 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { public void tagResource(String functionArn, Map tags) { validateTagKeys(tags); + if (LambdaCodeSigningConfigService.ownsArn(functionArn)) { + codeSigningConfigService.tagResource(regionResolver.getAccountId(), functionArn, tags); + return; + } EventSourceMapping esm = taggedEventSourceMapping(functionArn); if (esm != null) { synchronized (esm) { @@ -4530,6 +4537,10 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { } public void untagResource(String functionArn, List tagKeys) { + if (LambdaCodeSigningConfigService.ownsArn(functionArn)) { + codeSigningConfigService.untagResource(regionResolver.getAccountId(), functionArn, tagKeys); + return; + } EventSourceMapping esm = taggedEventSourceMapping(functionArn); if (esm != null) { synchronized (esm) { @@ -4564,11 +4575,15 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider { } /** - * The tags of the function, or the event source mapping, stored under {@code arn} in the account and Region it - * names, matched on the whole ARN and left as they are; a version or alias ARN has its function's, as Lambda keeps - * tags on the function alone. Empty for an ARN naming nothing stored, or any other Lambda resource. + * The tags of the function, the event source mapping or the code signing configuration stored under {@code arn} + * in the account and Region it names, matched on the whole ARN and left as they are; a version or alias ARN has + * its function's, as Lambda keeps tags on the function alone. Empty for an ARN naming nothing stored, or any other + * Lambda resource. */ public Map storedTags(String arn) { + if (LambdaCodeSigningConfigService.ownsArn(arn)) { + return codeSigningConfigService.storedTags(arn); + } AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); String uuid = LambdaArnUtils.eventSourceMappingUuid(parsed); if (uuid != null) { diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaStoredResourceArns.java b/src/main/java/io/floci/aws/services/lambda/LambdaStoredResourceArns.java index 774d749251..2776183112 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaStoredResourceArns.java @@ -18,7 +18,8 @@ import java.util.Optional; * another account's layer version is read in that account alone, the * image the caller's MicroVM runs, which the Service Reference checks an action on a running MicroVM on, the * durable execution a callback belongs to, which Lambda authorizes a callback request against, and the tags of a - * function, an event source mapping, a web function, a MicroVM image or a network connector. + * function, an event source mapping, a code signing configuration, a web function, a MicroVM image or a network + * connector. */ @ApplicationScoped public class LambdaStoredResourceArns implements StoredResourceArns { @@ -79,7 +80,7 @@ public class LambdaStoredResourceArns implements StoredResourceArns { /** * The tags of the resource the ARN names, from the service holding it: a web function's, its revisions' and its * endpoints' from Lambda Web, a MicroVM image's or a network connector's from Lambda MicroVMs, and a function's, - * its versions' and aliases', or an event source mapping's from Lambda. + * its versions' and aliases', an event source mapping's or a code signing configuration's from Lambda. */ @Override public Map storedTags(String arn) { diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java index c5c6f3e19e..d71cb4000b 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java @@ -16,6 +16,7 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.node.ObjectNode; import java.nio.file.Path; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -47,31 +48,19 @@ class LambdaCodeSigningConfigDeleteRaceTest { @Test void deleteWaitsForValidatedPutAndRejectsAttachedConfig(@TempDir Path codePath) throws Exception { - StorageFactory factory = mock(StorageFactory.class); - when(factory.create(anyString(), anyString(), any())) - .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT)); - RegionResolver regions = new RegionResolver(REGION, ACCOUNT); - LambdaCodeSigningConfigService configs = spy(new LambdaCodeSigningConfigService(factory, regions)); - CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers(); - publishers.setSigningProfileVersionArns(List.of( - "arn:aws:signer:us-east-1:111111111111:/signing-profiles/prof/AbCdEfGhIj")); - String configArn = configs.create(REGION, ACCOUNT, null, publishers, null).getCodeSigningConfigArn(); - - LambdaFunctionStore functions = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT)); + Fixture fixture = fixture(codePath); + String configArn = fixture.configArn(); LambdaFunction function = new LambdaFunction(); function.setAccountId(ACCOUNT); function.setFunctionName(NAME); function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + NAME); function.setVersion("$LATEST"); - functions.saveForAccount(ACCOUNT, REGION, function); - LambdaService lambda = new LambdaService(functions, null, new LambdaConcurrencyLimiter(), - new WarmPool(), new CodeStore(codePath), new ZipExtractor(), null, regions, null, null, - new LambdaTargetResolver(functions, null), null, null, null, null, null, factory, - null, null, null, null, JacksonConfig.jsonMapper(), configs); + fixture.functions().saveForAccount(ACCOUNT, REGION, function); ObjectMapper mapper = JacksonConfig.jsonMapper(); - LambdaCodeSigningController attachments = new LambdaCodeSigningController(lambda, regions, mapper); - LambdaCodeSigningConfigFunctionsController configController = - new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, mapper); + LambdaCodeSigningController attachments = + new LambdaCodeSigningController(fixture.lambda(), fixture.regions(), mapper); + LambdaCodeSigningConfigFunctionsController configController = new LambdaCodeSigningConfigFunctionsController( + fixture.configs(), fixture.lambda(), fixture.regions(), mapper); CountDownLatch validated = new CountDownLatch(1); CountDownLatch releasePut = new CountDownLatch(1); @@ -83,7 +72,7 @@ class LambdaCodeSigningConfigDeleteRaceTest { assertTrue(releasePut.await(15, TimeUnit.SECONDS)); } return result; - }).when(configs).get(REGION, ACCOUNT, configArn); + }).when(fixture.configs()).get(REGION, ACCOUNT, configArn); ExecutorService workers = Executors.newFixedThreadPool(2); try { @@ -109,8 +98,8 @@ class LambdaCodeSigningConfigDeleteRaceTest { AwsException conflict = assertInstanceOf(AwsException.class, failure.getCause()); assertEquals("ResourceConflictException", conflict.getErrorCode()); assertEquals(409, conflict.getHttpStatus()); - assertEquals(configArn, configs.get(REGION, ACCOUNT, configArn).getCodeSigningConfigArn()); - assertEquals(configArn, functions.getForAccount(ACCOUNT, REGION, NAME) + assertEquals(configArn, fixture.configs().get(REGION, ACCOUNT, configArn).getCodeSigningConfigArn()); + assertEquals(configArn, fixture.functions().getForAccount(ACCOUNT, REGION, NAME) .orElseThrow().getCodeSigningConfigArn()); } finally { releasePut.countDown(); @@ -120,23 +109,10 @@ class LambdaCodeSigningConfigDeleteRaceTest { @Test void deleteWaitsForValidatedCreateAndRejectsAttachedConfig(@TempDir Path codePath) throws Exception { - StorageFactory factory = mock(StorageFactory.class); - when(factory.create(anyString(), anyString(), any())) - .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT)); - RegionResolver regions = new RegionResolver(REGION, ACCOUNT); - LambdaCodeSigningConfigService configs = spy(new LambdaCodeSigningConfigService(factory, regions)); - CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers(); - publishers.setSigningProfileVersionArns(List.of( - "arn:aws:signer:us-east-1:111111111111:/signing-profiles/prof/AbCdEfGhIj")); - String configArn = configs.create(REGION, ACCOUNT, null, publishers, null).getCodeSigningConfigArn(); - - LambdaFunctionStore functions = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT)); - LambdaService lambda = new LambdaService(functions, null, new LambdaConcurrencyLimiter(), - new WarmPool(), new CodeStore(codePath), new ZipExtractor(), null, regions, null, null, - new LambdaTargetResolver(functions, null), null, null, null, null, null, factory, - null, null, null, null, JacksonConfig.jsonMapper(), configs); - LambdaCodeSigningConfigFunctionsController configController = - new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, JacksonConfig.jsonMapper()); + Fixture fixture = fixture(codePath); + String configArn = fixture.configArn(); + LambdaCodeSigningConfigFunctionsController configController = new LambdaCodeSigningConfigFunctionsController( + fixture.configs(), fixture.lambda(), fixture.regions(), JacksonConfig.jsonMapper()); CountDownLatch validated = new CountDownLatch(1); CountDownLatch releaseCreate = new CountDownLatch(1); @@ -148,7 +124,7 @@ class LambdaCodeSigningConfigDeleteRaceTest { assertTrue(releaseCreate.await(15, TimeUnit.SECONDS)); } return result; - }).when(configs).requireForAttachment(REGION, ACCOUNT, configArn); + }).when(fixture.configs()).requireForAttachment(REGION, ACCOUNT, configArn); String functionName = "create-config-delete-race"; Map request = Map.of( @@ -161,7 +137,7 @@ class LambdaCodeSigningConfigDeleteRaceTest { try { Future create = workers.submit(() -> { createThread.set(Thread.currentThread()); - return lambda.createFunction(REGION, request); + return fixture.lambda().createFunction(REGION, request); }); assertTrue(validated.await(5, TimeUnit.SECONDS)); @@ -180,11 +156,80 @@ class LambdaCodeSigningConfigDeleteRaceTest { AwsException conflict = assertInstanceOf(AwsException.class, failure.getCause()); assertEquals("ResourceConflictException", conflict.getErrorCode()); assertEquals(409, conflict.getHttpStatus()); - assertEquals(configArn, functions.getForAccount(ACCOUNT, REGION, functionName) + assertEquals(configArn, fixture.functions().getForAccount(ACCOUNT, REGION, functionName) .orElseThrow().getCodeSigningConfigArn()); } finally { releaseCreate.countDown(); workers.shutdownNow(); } } + + @Test + void deleteWaitsForAValidatedTagWriteAndDropsItsTags(@TempDir Path codePath) throws Exception { + Fixture fixture = fixture(codePath); + String configArn = fixture.configArn(); + + CountDownLatch validated = new CountDownLatch(1); + CountDownLatch releaseTag = new CountDownLatch(1); + AtomicReference tagThread = new AtomicReference<>(); + doAnswer(invocation -> { + CodeSigningConfig result = (CodeSigningConfig) invocation.callRealMethod(); + if (Thread.currentThread() == tagThread.get()) { + validated.countDown(); + assertTrue(releaseTag.await(15, TimeUnit.SECONDS)); + } + return result; + }).when(fixture.configs()).get(REGION, ACCOUNT, configArn); + + ExecutorService workers = Executors.newFixedThreadPool(2); + try { + Future tag = workers.submit(() -> { + tagThread.set(Thread.currentThread()); + fixture.lambda().tagResource(configArn, Map.of("team", "data")); + }); + assertTrue(validated.await(5, TimeUnit.SECONDS)); + + AtomicReference deleteThread = new AtomicReference<>(); + Future delete = workers.submit(() -> { + deleteThread.set(Thread.currentThread()); + fixture.lambda().deleteCodeSigningConfig(REGION, ACCOUNT, configArn); + }); + awaitBlockedOrDone(deleteThread, delete); + assertFalse(delete.isDone(), "config deletion must wait for the validated tag write"); + + releaseTag.countDown(); + tag.get(5, TimeUnit.SECONDS); + delete.get(5, TimeUnit.SECONDS); + assertTrue(fixture.stores().get("lambda-code-signing-config-tags.json").isEmptyInAllAccounts(), + "the deleted config's tags must not stay behind"); + } finally { + releaseTag.countDown(); + workers.shutdownNow(); + } + } + + private static Fixture fixture(Path codePath) { + Map> stores = new HashMap<>(); + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(anyString(), anyString(), any())).thenAnswer(invocation -> stores.computeIfAbsent( + invocation.getArgument(1), file -> AccountAwareStorageBackend.inMemory(ACCOUNT))); + RegionResolver regions = new RegionResolver(REGION, ACCOUNT); + LambdaCodeSigningConfigService configs = spy(new LambdaCodeSigningConfigService(factory, regions)); + CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers(); + publishers.setSigningProfileVersionArns(List.of( + "arn:aws:signer:us-east-1:111111111111:/signing-profiles/prof/AbCdEfGhIj")); + String configArn = configs.create(REGION, ACCOUNT, null, publishers, null).getCodeSigningConfigArn(); + + LambdaFunctionStore functions = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT)); + LambdaService lambda = new LambdaService(functions, null, new LambdaConcurrencyLimiter(), + new WarmPool(), new CodeStore(codePath), new ZipExtractor(), null, regions, null, null, + new LambdaTargetResolver(functions, null), null, null, null, null, null, factory, + null, null, null, null, JacksonConfig.jsonMapper(), configs); + return new Fixture(stores, regions, configs, configArn, functions, lambda); + } + + private record Fixture(Map> stores, RegionResolver regions, + LambdaCodeSigningConfigService configs, String configArn, + LambdaFunctionStore functions, LambdaService lambda) { + } } diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java index c38fa925bc..34592aeea2 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java @@ -4,19 +4,23 @@ import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Map; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.matchesRegex; +import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; -/** Create, Get, Update, Delete and List for a code signing configuration. */ +/** Create, Get, Update, Delete and List for a code signing configuration, and its tags. */ @QuarkusTest class LambdaCodeSigningConfigLifecycleIntegrationTest { private static final String BASE = "/2020-04-22/code-signing-configs"; + private static final String TAGS = "/2017-03-31/tags/"; private static final String PROFILE = "arn:aws:signer:us-east-1:000000000000:/signing-profiles/prof/AbCdEfGhIj"; @@ -155,4 +159,117 @@ class LambdaCodeSigningConfigLifecycleIntegrationTest { .when().post(BASE).then().statusCode(400) .body("__type", is("InvalidParameterValueException")); } + + @Test + void createKeepsTheTagsForListTagsAndOutOfTheConfig() { + String arn = given() + .contentType("application/json") + .body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"Tags\":{\"team\":\"data\"}}") + .when() + .post(BASE) + .then() + .statusCode(201) + .body("CodeSigningConfig", not(hasKey("Tags"))) + .extract().path("CodeSigningConfig.CodeSigningConfigArn"); + + given().when().get(BASE + "/" + arn).then() + .statusCode(200) + .body("CodeSigningConfig", not(hasKey("Tags"))); + given().when().get(TAGS + arn).then() + .statusCode(200) + .body("Tags", is(Map.of("team", "data"))); + + given().contentType("application/json").body("{\"Tags\":{\"stage\":\"prod\"}}") + .when().post(TAGS + arn).then().statusCode(204); + given().when().get(TAGS + arn).then() + .statusCode(200) + .body("Tags", is(Map.of("team", "data", "stage", "prod"))); + } + + @Test + void aCreateWithAnInvalidTagKeyStoresNothing() { + given().contentType("application/json") + .body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"Description\":\"bad tag key\",\"Tags\":{\"\":\"empty key\"}}") + .when().post(BASE).then().statusCode(400) + .body("__type", is("ValidationException")); + + given().when().get(BASE).then().statusCode(200) + .body("CodeSigningConfigs.Description", not(hasItem("bad tag key"))); + } + + @Test + void tagResourceAndUntagResourceChangeTheTagsUntilTheConfigIsDeleted() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}}"); + + given().when().get(TAGS + arn).then().statusCode(200).body("Tags", is(Map.of())); + + given().contentType("application/json").body("{\"Tags\":{\"team\":\"data\",\"stage\":\"prod\"}}") + .when().post(TAGS + arn).then().statusCode(204); + given().queryParam("tagKeys", "team") + .when().delete(TAGS + arn).then().statusCode(204); + given().when().get(TAGS + arn).then() + .statusCode(200) + .body("Tags", is(Map.of("stage", "prod"))); + + given().when().delete(BASE + "/" + arn).then().statusCode(204); + given().when().get(TAGS + arn).then().statusCode(404) + .body("__type", is("ResourceNotFoundException")); + given().contentType("application/json").body("{\"Tags\":{\"team\":\"data\"}}") + .when().post(TAGS + arn).then().statusCode(404); + given().queryParam("tagKeys", "stage") + .when().delete(TAGS + arn).then().statusCode(404); + } + + @Test + void tagOperationsReportAConfigTheCallerDoesNotHoldAsNotFound() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}}"); + + for (String other : List.of( + "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-abcdefghij1234567", + arn.replace(":000000000000:", ":111111111111:"), + arn.replace(":us-east-1:", ":us-west-2:"), + arn.replaceFirst("^arn:aws:", "arn:aws-cn:"))) { + given().when().get(TAGS + other).then().statusCode(404) + .body("__type", is("ResourceNotFoundException")); + given().contentType("application/json").body("{\"Tags\":{\"team\":\"data\"}}") + .when().post(TAGS + other).then().statusCode(404); + given().queryParam("tagKeys", "team") + .when().delete(TAGS + other).then().statusCode(404); + } + given().when().get(TAGS + arn).then().statusCode(200).body("Tags", is(Map.of())); + } + + @Test + void aMalformedCodeSigningConfigArnIsStillRefusedByTheTagOperations() { + String malformed = "arn:aws:lambda:us-east-1:000000000000:code-signing-config:bogus"; + + given().when().get(TAGS + malformed).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + given().contentType("application/json").body("{\"Tags\":{\"team\":\"data\"}}") + .when().post(TAGS + malformed).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + given().queryParam("tagKeys", "team") + .when().delete(TAGS + malformed).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + + // The configuration ARN's pattern allows an empty partition; the tag operations' Resource pattern does not. + String noPartition = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}}") + .replaceFirst("^arn:aws:", "arn::"); + given().when().get(TAGS + noPartition).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + given().contentType("application/json").body("{\"Tags\":{\"team\":\"data\"}}") + .when().post(TAGS + noPartition).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + given().queryParam("tagKeys", "team") + .when().delete(TAGS + noPartition).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + + // Past the ARN's 200 characters, though the pattern alone would take the long partition. + String tooLong = "arn:aws-" + "a".repeat(150) + + ":lambda:us-east-1:000000000000:code-signing-config:csc-abcdefghij1234567"; + given().when().get(TAGS + tooLong).then().statusCode(400) + .body("__type", is("ValidationException")); + } } diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaResourceTagIamIntegrationTest.java index 587bc311b6..6ce3f7d400 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaResourceTagIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaResourceTagIamIntegrationTest.java @@ -81,6 +81,56 @@ class LambdaResourceTagIamIntegrationTest { } } + @Test + void aResourceTagConditionReadsTheTagsOfACodeSigningConfig() throws Exception { + Region region = Region.US_EAST_1; + try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, region, endpoint)) { + String taggedOnCreate = codeSigningConfig(owner, Map.of("team", "data")); + String taggedLater = codeSigningConfig(owner, Map.of("team", "web")); + owner.tagResource(request -> request.resource(taggedLater).tags(Map.of("team", "data"))); + String otherTeam = codeSigningConfig(owner, Map.of("team", "web")); + assertEquals(Map.of("team", "data"), owner.listTags(request -> request.resource(taggedOnCreate)).tags()); + + String authorization = auth(ACCOUNT, region.id(), "iam"); + String user = "csc-tag-reader-" + UUID.randomUUID(); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, user); + EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, user, "team-data", + """ + { + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "lambda:GetCodeSigningConfig", + "Resource": "*", + "Condition": {"StringEquals": {"aws:ResourceTag/team": "data"}} + }] + } + """); + try (LambdaClient reader = AwsTestClients.create(LambdaClient.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), region, endpoint)) { + for (String arn : List.of(taggedOnCreate, taggedLater)) { + assertEquals(arn, reader.getCodeSigningConfig(request -> request.codeSigningConfigArn(arn)) + .codeSigningConfig().codeSigningConfigArn()); + } + denied(() -> reader.getCodeSigningConfig(request -> request.codeSigningConfigArn(otherTeam))); + } + } + } + + private String codeSigningConfig(LambdaClient owner, Map tags) { + String arn = owner.createCodeSigningConfig(request -> request.tags(tags).allowedPublishers(publishers -> + publishers.signingProfileVersionArns( + "arn:aws:signer:us-east-1:" + ACCOUNT + ":/signing-profiles/prof/AbCdEfGhIj"))) + .codeSigningConfig().codeSigningConfigArn(); + cleanup.register(() -> { + try (LambdaClient client = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.US_EAST_1, + endpoint)) { + client.deleteCodeSigningConfig(request -> request.codeSigningConfigArn(arn)); + } + }); + return arn; + } + /** A disabled self-managed Kafka mapping of the function, so nothing polls the endpoint it names. */ private String mapping(LambdaClient owner, String function, Map tags) { String uuid = owner.createEventSourceMapping(request -> request.functionName(function) diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaStoredTagsTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaStoredTagsTest.java index 853332470a..41b9377aa1 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaStoredTagsTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaStoredTagsTest.java @@ -4,6 +4,7 @@ import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.lambda.model.CodeSigningConfig; import io.floci.aws.services.lambda.model.EventSourceMapping; import io.floci.aws.services.lambda.model.LambdaFunction; import io.floci.aws.services.lambda.zip.CodeStore; @@ -28,15 +29,20 @@ class LambdaStoredTagsTest { private static final String REGION = "us-east-1"; private LambdaService service; + private LambdaCodeSigningConfigService codeSigningConfigs; @BeforeEach void setUp() { + // One store per file, so a configuration created here is the one the service reads. + Map> stores = new HashMap<>(); StorageFactory storageFactory = mock(StorageFactory.class); - when(storageFactory.create(anyString(), anyString(), any())) - .thenAnswer(inv -> AccountAwareStorageBackend.inMemory("000000000000")); + when(storageFactory.create(anyString(), anyString(), any())).thenAnswer(inv -> stores.computeIfAbsent( + inv.getArgument(1), file -> AccountAwareStorageBackend.inMemory("000000000000"))); + RegionResolver regionResolver = new RegionResolver(REGION, "000000000000"); service = new LambdaService(new LambdaFunctionStore(new InMemoryStorage()), new WarmPool(), new CodeStore(Path.of("target/test-data/lambda-code")), new ZipExtractor(), null, - new RegionResolver(REGION, "000000000000"), storageFactory); + regionResolver, storageFactory); + codeSigningConfigs = new LambdaCodeSigningConfigService(storageFactory, regionResolver); } private static Map functionRequest(String name, Map tags) { @@ -93,6 +99,30 @@ class LambdaStoredTagsTest { assertEquals(Map.of(), service.storedTags(arn.replace("000000000000", "111111111111"))); } + @Test + void aCodeSigningConfigHasItsOwnTags() { + CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers(); + publishers.setSigningProfileVersionArns(List.of( + "arn:aws:signer:us-east-1:000000000000:/signing-profiles/prof/AbCdEfGhIj")); + String arn = codeSigningConfigs.create(REGION, "000000000000", null, publishers, null) + .getCodeSigningConfigArn(); + + assertEquals(Map.of(), service.storedTags(arn)); + + service.tagResource(arn, Map.of("team", "data", "stage", "prod")); + service.untagResource(arn, List.of("stage")); + + assertEquals(Map.of("team", "data"), service.listTags(arn)); + assertEquals(Map.of("team", "data"), service.storedTags(arn)); + assertEquals(Map.of(), service.storedTags(arn.replace(":000000000000:", ":111111111111:"))); + assertEquals(Map.of(), service.storedTags(arn.replace(":" + REGION + ":", ":us-west-2:"))); + assertEquals(Map.of(), service.storedTags(arn.replaceFirst("^arn:aws:", "arn:aws-cn:"))); + + service.deleteCodeSigningConfig(REGION, "000000000000", arn); + + assertEquals(Map.of(), service.storedTags(arn)); + } + @Test void taggingPutsANewTagMapInPlaceOfTheOneAReaderHolds() { LambdaFunction fn = service.createFunction(REGION, functionRequest("cow-fn", Map.of("team", "data")));