diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index d139df9775..0957c56b10 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -191,7 +191,8 @@ cross-resource references. | SNS | `Topic`, `Subscription`, `TopicPolicy` | | SES | `EmailIdentity` (BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS's region- and identity-specific zone assignment), `ReceiptRule` (stored in an existing SES receipt rule set; Ref and RuleName return the rule name; management plane only, with no inbound mail delivery) | | DynamoDB | `Table` (`TimeToLiveSpecification` applied on create and update; to rename an enabled TTL attribute, disable TTL in one update and enable the new attribute in a later one. `KinesisStreamSpecification` applied on create and update; with the DynamoDB Local backend, `StreamArn` is checked as on AWS but nothing is forwarded), `GlobalTable` | -| Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`, `WebFunction` (control plane only; the endpoint domain does not serve requests yet), `WebFunctionEndpoint`, `WebFunctionRevision` (every property is createOnly, so a change mints a new revision). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. | +| Lambda | `Function` (Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `CodeSigningConfig`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`, `WebFunction` (control plane only; the endpoint domain does not serve requests yet), `WebFunctionEndpoint`, `WebFunctionRevision` (every property is createOnly, so a change mints a new revision). Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. | +| Signer | `SigningProfile` (identifiers only; Floci has no Signer API) | | IAM | `Role`, `User` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` | | Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` | | SSM | `Parameter` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 1dc45654f4..6204d3f9c5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -101,6 +101,9 @@ public final class CfnRollback { */ public static final String EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR = "__FlociEventInvokeConfigSnapshot"; + /** The code signing config an in-place update changed, as stored, so a failed stack update can put it back. */ + public static final String CODE_SIGNING_CONFIG_UPDATE_SNAPSHOT_ATTR = "__FlociCodeSigningConfigUpdateSnapshot"; + /** The prior WAFv2 logging configuration for an in-place update that may need rollback. */ public static final String WAF_LOGGING_UPDATE_SNAPSHOT_ATTR = "__FlociWafLoggingUpdateSnapshot"; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java index 7ed44da1f4..98ff6f9713 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java @@ -141,6 +141,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { } applyLambdaReservedConcurrency(region, func, desired); + applyLambdaCodeSigningConfig(ctx, func, desired); r.setPhysicalId(desired.functionName()); r.getAttributes().put("Arn", func.getFunctionArn()); @@ -281,6 +282,10 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { if (!tags.isEmpty()) { createRequest.put("Tags", tags); } + String codeSigningConfigArn = ctx.resolveOptional(props, "CodeSigningConfigArn"); + if (codeSigningConfigArn != null) { + createRequest.put("CodeSigningConfigArn", codeSigningConfigArn); + } Integer reservedConcurrentExecutions = null; String reserved = ctx.resolveOptional(props, "ReservedConcurrentExecutions"); if (reserved != null) { @@ -459,6 +464,22 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { } } + /** + * Attaches or replaces the template's code signing config, and detaches one only when the previous + * template declared it: a config attached outside the stack stays, as CloudFormation leaves it. + */ + private void applyLambdaCodeSigningConfig(ProvisionContext ctx, LambdaFunction fn, LambdaDesiredState desired) { + Object codeSigningConfigArn = desired.createRequest().get("CodeSigningConfigArn"); + if (codeSigningConfigArn == null) { + if (ctx.previouslyDeclared("CodeSigningConfigArn") && fn.getCodeSigningConfigArn() != null) { + lambdaService.deleteFunctionCodeSigningConfig(ctx.region(), fn.getFunctionName()); + } + } else if (!codeSigningConfigArn.equals(fn.getCodeSigningConfigArn())) { + lambdaService.attachFunctionCodeSigningConfig(ctx.region(), fn.getFunctionName(), + codeSigningConfigArn.toString()); + } + } + /** * The form LambdaService stores a hot-reload host path in: normalized, so {@code /a/../b/} * and {@code /b} are the same mount, and rendered as the POSIX path Docker receives diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCodeSigningConfigCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCodeSigningConfigCfnProvisioner.java new file mode 100644 index 0000000000..77a4bf32fc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCodeSigningConfigCfnProvisioner.java @@ -0,0 +1,120 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.lambda.LambdaCodeSigningConfigService; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Provisions {@code AWS::Lambda::CodeSigningConfig}. {@code Ref} is the config's ARN. Every property + * updates in place, and an update applies the template's whole state, so a dropped description or + * policy returns to its default. A rolled-back update puts the prior settings back. Deleting a config + * a function still uses is refused, as Lambda's DeleteCodeSigningConfig refuses it. + */ +@ApplicationScoped +public class LambdaCodeSigningConfigCfnProvisioner implements CfnResourceProvisioner { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final LambdaCodeSigningConfigService configs; + private final LambdaService lambdaService; + + @Inject + public LambdaCodeSigningConfigCfnProvisioner(LambdaCodeSigningConfigService configs, LambdaService lambdaService) { + this.configs = configs; + this.lambdaService = lambdaService; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::Lambda::CodeSigningConfig"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + r.getAttributes().remove(CfnRollback.CODE_SIGNING_CONFIG_UPDATE_SNAPSHOT_ATTR); + Map attributesBefore = Map.copyOf(r.getAttributes()); + JsonNode properties = props == null ? MAPPER.missingNode() : props; + String description = Objects.requireNonNullElse(ctx.resolveOptional(properties, "Description"), ""); + CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers(); + publishers.setSigningProfileVersionArns(ctx.resolveStringList( + ctx.engine().resolveNode(properties.path("AllowedPublishers")), "SigningProfileVersionArns")); + CodeSigningConfig.CodeSigningPolicies policies = new CodeSigningConfig.CodeSigningPolicies(); + policies.setUntrustedArtifactOnDeployment(Objects.requireNonNullElse(ctx.resolveOptional( + ctx.engine().resolveNode(properties.path("CodeSigningPolicies")), "UntrustedArtifactOnDeployment"), + "Warn")); + + // A dispatcher stub from before this provisioner existed is not an ARN and names no config. + String prior = ctx.priorPhysicalId(); + CodeSigningConfig config = ctx.isUpdate() && AwsArnUtils.isArn(prior) + ? configs.withConfigLock(prior, () -> { + r.getAttributes().put(CfnRollback.CODE_SIGNING_CONFIG_UPDATE_SNAPSHOT_ATTR, + MAPPER.valueToTree(configs.get(ctx.region(), prior)).toString()); + return configs.update(ctx.region(), prior, description, publishers, policies); + }) + : configs.create(ctx.region(), ctx.accountId(), description, publishers, policies); + r.setPhysicalId(config.getCodeSigningConfigArn()); + r.getAttributes().put("CodeSigningConfigArn", config.getCodeSigningConfigArn()); + r.getAttributes().put("CodeSigningConfigId", config.getCodeSigningConfigId()); + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + ReplacementCleanup.clear(resource); + } + + /** A stub migration deletes the config it created; an in-place update puts the prior settings back. */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.CODE_SIGNING_CONFIG_UPDATE_SNAPSHOT_ATTR); + if (snapshot == null) { + return true; + } + CodeSigningConfig prior = MAPPER.convertValue(snapshot, CodeSigningConfig.class); + String arn = resource.getPhysicalId(); + String region = AwsArnUtils.parse(arn).region(); + configs.withConfigLock(arn, () -> configs.update(region, arn, prior.getDescription(), + prior.getAllowedPublishers(), prior.getCodeSigningPolicies())); + resource.getAttributes().remove(CfnRollback.CODE_SIGNING_CONFIG_UPDATE_SNAPSHOT_ATTR); + return true; + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (!AwsArnUtils.isArn(physicalId)) { + return; + } + String accountId = AwsArnUtils.parse(physicalId).accountId(); + CfnDeletes.safeDelete("Lambda code signing config", physicalId, + () -> lambdaService.deleteCodeSigningConfig(region, accountId, physicalId), + "ResourceNotFoundException"); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SignerCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SignerCfnProvisioner.java new file mode 100644 index 0000000000..2e970a2ff3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SignerCfnProvisioner.java @@ -0,0 +1,141 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; +import java.util.regex.Pattern; + +/** + * Provisions {@code AWS::Signer::SigningProfile}. Floci has no Signer API, so a profile is only the + * identifiers CloudFormation hands the template: {@code Ref} is the profile ARN, and the attributes + * carry the name, a version and the version ARN a code signing config lists. Every property but + * {@code Tags} is create-only: an update that keeps them keeps the profile, one that changes them + * mints a new one, and one that would keep an explicit name is refused, as CloudFormation refuses + * replacing any custom-named resource. A replaced or deleted profile leaves nothing behind to clean + * up, and a rolled-back replacement points the resource back to the prior profile. + */ +@ApplicationScoped +public class SignerCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::Signer::SigningProfile"; + private static final List PLATFORMS = List.of("AWSLambda-SHA384-ECDSA", "Notation-OCI-SHA384-ECDSA"); + private static final Pattern PROFILE_NAME = Pattern.compile("[0-9a-zA-Z_]{2,64}"); + private static final Map MAX_VALIDITY = Map.of("DAYS", 4105, "MONTHS", 135, "YEARS", 11); + private static final String ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + /** The create-only properties the profile was minted from, so an update can tell whether it is replaced. */ + private static final String CREATE_ONLY_ATTR = "FlociSigningProfileCreateOnly"; + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + Map attributesBefore = Map.copyOf(r.getAttributes()); + String platformId = ctx.resolveOptional(props, "PlatformId"); + if (platformId == null || !PLATFORMS.contains(platformId)) { + throw new AwsException("ValidationError", + TYPE + " PlatformId must be one of " + PLATFORMS + ", got " + platformId, 400); + } + String explicitName = ctx.resolveOptional(props, "ProfileName"); + if (explicitName != null && !PROFILE_NAME.matcher(explicitName).matches()) { + throw new AwsException("ValidationError", + TYPE + " ProfileName must be 2 to 64 characters from [0-9a-zA-Z_], got " + explicitName, 400); + } + JsonNode period = ctx.engine().resolveNodeOmittingNoValue(props.path("SignatureValidityPeriod")); + validatePeriod(period, ctx); + String createOnly = platformId + "|" + Objects.toString(explicitName, "") + "|" + + period.path("Type").asText() + "|" + period.path("Value").asText(); + if (!createOnly.equals(r.getAttributes().get(CREATE_ONLY_ATTR))) { + if (ctx.isUpdate() && explicitName != null && explicitName.equals(r.getAttributes().get("ProfileName"))) { + throw new AwsException("ValidationError", + "CloudFormation cannot update a stack when a custom-named resource requires " + + "replacing. Rename " + explicitName + " and update the stack again.", 400); + } + mint(r, ctx, explicitName, createOnly); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * Signer's checks on a supplied validity period, in its order and with its messages: a known unit, + * then a value above zero and at most the unit's cap. An omitted period keeps Signer's default. + */ + private static void validatePeriod(JsonNode period, ProvisionContext ctx) { + if (period.isMissingNode()) { + return; + } + String type = period.path("Type").asText(null); + if (type == null || !MAX_VALIDITY.containsKey(type)) { + throw new AwsException("ValidationError", + "Signature validity period type must be one of [DAYS, MONTHS, YEARS]", 400); + } + Integer value = ctx.resolveOptionalInt(period, "Value"); + if (value == null || value < 1) { + throw new AwsException("ValidationError", "Signature validity period value must be greater than 0.", 400); + } + if (value > MAX_VALIDITY.get(type)) { + throw new AwsException("ValidationError", "Signature validity period value for " + type + + " must be less than or equal to " + MAX_VALIDITY.get(type), 400); + } + } + + private static void mint(StackResource r, ProvisionContext ctx, String explicitName, String createOnly) { + String name = explicitName != null ? explicitName + : r.getLogicalId().substring(0, Math.min(r.getLogicalId().length(), 51)) + "_" + random(12); + String arn = AwsArnUtils.Arn.of("signer", ctx.region(), ctx.accountId(), "/signing-profiles/" + name) + .toString(); + String version = random(10); + r.setPhysicalId(arn); + r.getAttributes().put("Arn", arn); + r.getAttributes().put("ProfileName", name); + r.getAttributes().put("ProfileVersion", version); + r.getAttributes().put("ProfileVersionArn", arn + "/" + version); + r.getAttributes().put(CREATE_ONLY_ATTR, createOnly); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + ReplacementCleanup.clear(resource); + } + + /** A replacement points back to the prior profile; a tags-only update changed nothing Floci holds. */ + @Override + public boolean rollbackUpdate(StackResource resource) { + ReplacementCleanup.rollback(resource, this::delete); + return true; + } + + private static String random(int length) { + ThreadLocalRandom random = ThreadLocalRandom.current(); + StringBuilder out = new StringBuilder(length); + for (int i = 0; i < length; i++) { + out.append(ALPHANUMERIC.charAt(random.nextInt(ALPHANUMERIC.length()))); + } + return out.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java index d58e7e0c8c..649aee3be4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigFunctionsController.java @@ -130,18 +130,8 @@ public class LambdaCodeSigningConfigFunctionsController { @PathParam("codeSigningConfigArn") String codeSigningConfigArn) { LambdaCodeSigningConfigService.validateArn(codeSigningConfigArn); String region = regionResolver.resolveRegion(headers); - String accountId = regionResolver.getAccountId(); - return service.withConfigLock(codeSigningConfigArn, () -> { - service.get(region, accountId, codeSigningConfigArn); - PaginatedResult attached = lambdaService.listFunctionsByCodeSigningConfig( - region, accountId, codeSigningConfigArn, 1, null); - if (!attached.items().isEmpty()) { - throw new AwsException("ResourceConflictException", - "The code signing configuration is still attached to a function.", 409); - } - service.delete(region, codeSigningConfigArn); - return Response.noContent().build(); - }); + lambdaService.deleteCodeSigningConfig(region, regionResolver.getAccountId(), codeSigningConfigArn); + return Response.noContent().build(); } @GET diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java index 87476b1746..f6a839a15f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningController.java @@ -37,17 +37,14 @@ import jakarta.ws.rs.core.Response; public class LambdaCodeSigningController { private final LambdaService lambdaService; - private final LambdaCodeSigningConfigService configService; private final RegionResolver regionResolver; private final ObjectMapper objectMapper; @Inject public LambdaCodeSigningController(LambdaService lambdaService, - LambdaCodeSigningConfigService configService, RegionResolver regionResolver, ObjectMapper objectMapper) { this.lambdaService = lambdaService; - this.configService = configService; this.regionResolver = regionResolver; this.objectMapper = objectMapper; } @@ -74,16 +71,12 @@ public class LambdaCodeSigningController { String region = regionResolver.resolveRegion(headers); String arn = body == null || !body.hasNonNull("CodeSigningConfigArn") ? null : body.get("CodeSigningConfigArn").asText(); - LambdaCodeSigningConfigService.validateArn(arn); - return configService.withConfigLock(arn, () -> { - configService.requireForAttachment(region, regionResolver.getAccountId(), arn); - LambdaFunction fn = lambdaService.putFunctionCodeSigningConfig(region, functionName, arn); + LambdaFunction fn = lambdaService.attachFunctionCodeSigningConfig(region, functionName, arn); - ObjectNode root = objectMapper.createObjectNode(); - root.put("CodeSigningConfigArn", arn); - root.put("FunctionName", fn.getFunctionName()); - return Response.ok(root).build(); - }); + ObjectNode root = objectMapper.createObjectNode(); + root.put("CodeSigningConfigArn", arn); + root.put("FunctionName", fn.getFunctionName()); + return Response.ok(root).build(); } @DELETE diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index dfdaf88bd1..6c01f22d3d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -736,6 +736,42 @@ public class LambdaService implements ResourceProvider { return updateFunctionCodeSigningConfig(region, functionName, codeSigningConfigArn); } + /** + * Validates and attaches a code-signing configuration under the configuration's lock, as + * PutFunctionCodeSigningConfig does. + */ + public LambdaFunction attachFunctionCodeSigningConfig(String region, String functionName, + String codeSigningConfigArn) { + if (codeSigningConfigService == null) { + throw new IllegalStateException("Lambda code-signing configuration service is unavailable"); + } + LambdaCodeSigningConfigService.validateArn(codeSigningConfigArn); + return codeSigningConfigService.withConfigLock(codeSigningConfigArn, () -> { + codeSigningConfigService.requireForAttachment(region, regionResolver.getAccountId(), codeSigningConfigArn); + return putFunctionCodeSigningConfig(region, functionName, codeSigningConfigArn); + }); + } + + /** + * Deletes a code-signing configuration under the configuration's lock, refusing one a function + * still uses, as DeleteCodeSigningConfig does. + */ + public void deleteCodeSigningConfig(String region, String accountId, String codeSigningConfigArn) { + if (codeSigningConfigService == null) { + throw new IllegalStateException("Lambda code-signing configuration service is unavailable"); + } + codeSigningConfigService.withConfigLock(codeSigningConfigArn, () -> { + codeSigningConfigService.get(region, accountId, codeSigningConfigArn); + if (!listFunctionsByCodeSigningConfig(region, accountId, codeSigningConfigArn, 1, null) + .items().isEmpty()) { + throw new AwsException("ResourceConflictException", + "The code signing configuration is still attached to a function.", 409); + } + codeSigningConfigService.delete(region, codeSigningConfigArn); + return null; + }); + } + /** Removes a code-signing configuration from the function's {@code $LATEST}. */ public void deleteFunctionCodeSigningConfig(String region, String functionName) { updateFunctionCodeSigningConfig(region, functionName, null); diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index b6609a139f..912efff80c 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -785,6 +785,11 @@ "AWS::SecretsManager::SecretTargetAttachment": [ "SecretId" ], + "AWS::Signer::SigningProfile": [ + "ProfileName", + "PlatformId", + "SignatureValidityPeriod" + ], "AWS::SNS::Subscription": [ "Endpoint", "Protocol", diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java index 38069921cc..59b29d89ad 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java @@ -35,6 +35,14 @@ class CfnCreateOnlyPropertiesTest { assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::IoT::Authorizer", "SigningDisabled")); } + @Test + void signingProfileReplacesForEverythingButTags() { + assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Signer::SigningProfile", "ProfileName")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Signer::SigningProfile", "PlatformId")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Signer::SigningProfile", "SignatureValidityPeriod")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Signer::SigningProfile", "Tags")); + } + @Test void isCreateOnly_returnsFalseForMutableProperties() { assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "VisibilityTimeout")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 2ab8cd1099..96c2b8bb4f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -90,6 +90,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCf import io.github.hectorvent.floci.services.cloudformation.provisioners.KmsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaAddressingCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaCodeSigningConfigCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventInvokeConfigCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventSourceMappingCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaMicrovmsCfnProvisioner; @@ -113,6 +114,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretTar import io.github.hectorvent.floci.services.cloudformation.provisioners.SecretsManagerCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SesCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SesReceiptRuleCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.SignerCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SnsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SqsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.SsmCfnProvisioner; @@ -152,6 +154,7 @@ import io.github.hectorvent.floci.services.iot.IotDomainConfigurationService; import io.github.hectorvent.floci.services.iot.IotService; import io.github.hectorvent.floci.services.kinesis.KinesisService; import io.github.hectorvent.floci.services.kms.KmsService; +import io.github.hectorvent.floci.services.lambda.LambdaCodeSigningConfigService; import io.github.hectorvent.floci.services.lambda.LambdaLayerService; import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService; @@ -213,6 +216,7 @@ final class CfnProvisionerFixture { private SesIdentityService sesIdentityService; private DynamoDbService dynamoDbService; private LambdaService lambdaService; + private LambdaCodeSigningConfigService lambdaCodeSigningConfigService; private AppSyncService appSyncService; private AppConfigService appConfigService; private IamService iamService; @@ -315,6 +319,7 @@ final class CfnProvisionerFixture { ensureDynamicReferences(); List discovered = new ArrayList<>(); discovered.add(new CdkMetadataCfnProvisioner()); + discovered.add(new SignerCfnProvisioner()); if (stepFunctionsService != null) { discovered.add(new StepFunctionsCfnProvisioner(stepFunctionsService, s3Service, objectMapper)); } @@ -440,6 +445,10 @@ final class CfnProvisionerFixture { discovered.add(new LambdaEventInvokeConfigCfnProvisioner(lambdaService)); discovered.add(new LambdaVersionAliasCfnProvisioner(lambdaService)); discovered.add(new LambdaEventSourceMappingCfnProvisioner(lambdaService)); + if (lambdaCodeSigningConfigService != null) { + discovered.add(new LambdaCodeSigningConfigCfnProvisioner(lambdaCodeSigningConfigService, + lambdaService)); + } } if (flowLogService != null) { discovered.add(new Ec2FlowLogCfnProvisioner(flowLogService, ec2Service)); @@ -588,6 +597,11 @@ final class CfnProvisionerFixture { return this; } + public Builder lambdaCodeSigningConfig(LambdaCodeSigningConfigService v) { + this.lambdaCodeSigningConfigService = v; + return this; + } + public Builder appSync(AppSyncService v) { this.appSyncService = v; return this; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaCodeSigningIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaCodeSigningIntegrationTest.java new file mode 100644 index 0000000000..ceb5a2094f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaCodeSigningIntegrationTest.java @@ -0,0 +1,155 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.testing.CfnStackWaits; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.github.hectorvent.floci.testing.CfnRequests.cfn; +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * {@code AWS::Signer::SigningProfile} and {@code AWS::Lambda::CodeSigningConfig} through CloudFormation, + * and a function that attaches the config, drops it and attaches it again, with the identifiers AWS returns. + */ +@QuarkusTest +class CloudFormationLambdaCodeSigningIntegrationTest { + + private static final String MISSING_CSC_ARN = + "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-00000000000000000"; + + @Inject + LambdaService lambdaService; + + @Test + void signingProfileAndCodeSigningConfigAreProvisionedAttachedDetachedAndReattached() { + String stackName = "cfn-lambda-csc-" + Long.toString(System.nanoTime(), 36); + String signed = template("\"CodeSigningConfigArn\": {\"Ref\": \"Csc\"}"); + + cfn("CreateStack", stackName).formParam("TemplateBody", signed).when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE"); + XmlPath stack = describe(stackName); + String profileArn = output(stack, "ProfileArn"); + String version = output(stack, "ProfileVersion"); + String cscArn = output(stack, "CscArn"); + String function = output(stack, "Name"); + + assertEquals(profileArn, output(stack, "ProfileRef")); + assertThat(output(stack, "ProfileName"), matchesPattern("Profile_[A-Za-z0-9]{12}")); + assertEquals("arn:aws:signer:us-east-1:000000000000:/signing-profiles/" + output(stack, "ProfileName"), + profileArn); + assertThat(version, matchesPattern("[A-Za-z0-9]{10}")); + assertEquals(profileArn + "/" + version, output(stack, "ProfileVersionArn")); + assertEquals(cscArn, output(stack, "CscRef")); + assertEquals(cscArn, "arn:aws:lambda:us-east-1:000000000000:code-signing-config:" + output(stack, "CscId")); + given() + .when() + .get("/2020-04-22/code-signing-configs/" + cscArn) + .then() + .statusCode(200) + .body("CodeSigningConfig.Description", equalTo("signed")) + .body("CodeSigningConfig.AllowedPublishers.SigningProfileVersionArns", + contains(profileArn + "/" + version)) + .body("CodeSigningConfig.CodeSigningPolicies.UntrustedArtifactOnDeployment", equalTo("Enforce")); + assertCodeSigningConfig(function, cscArn); + + for (String rejected : List.of(MISSING_CSC_ARN, cscArn.replace(":000000000000:", ":111111111111:"))) { + AwsException error = assertThrows(AwsException.class, + () -> lambdaService.attachFunctionCodeSigningConfig("us-east-1", function, rejected)); + assertEquals("CodeSigningConfigNotFoundException", error.getErrorCode()); + } + assertCodeSigningConfig(function, cscArn); + + cfn("UpdateStack", stackName).formParam("TemplateBody", template("\"Description\": \"unsigned\"")) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE"); + assertEquals(function, output(describe(stackName), "Name"), "dropping the config updates the function in place"); + assertCodeSigningConfig(function, ""); + + cfn("UpdateStack", stackName).formParam("TemplateBody", signed).when().post("/").then().statusCode(200); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE"); + assertEquals(function, output(describe(stackName), "Name"), "adding the config updates the function in place"); + assertCodeSigningConfig(function, cscArn); + + CfnStackWaits.deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + given() + .when() + .get("/2020-04-22/code-signing-configs/" + cscArn) + .then() + .statusCode(404); + } + + private static String template(String functionProperty) { + return """ + { + "Resources": { + "Profile": { + "Type": "AWS::Signer::SigningProfile", + "Properties": {"PlatformId": "AWSLambda-SHA384-ECDSA"} + }, + "Csc": { + "Type": "AWS::Lambda::CodeSigningConfig", + "Properties": { + "Description": "signed", + "AllowedPublishers": { + "SigningProfileVersionArns": [{"Fn::GetAtt": ["Profile", "ProfileVersionArn"]}] + }, + "CodeSigningPolicies": {"UntrustedArtifactOnDeployment": "Enforce"} + } + }, + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Runtime": "python3.14", + "Handler": "index.handler", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Code": {"ZipFile": "def handler(e, c): return 'ok'"}, + %s + } + } + }, + "Outputs": { + "ProfileRef": {"Value": {"Ref": "Profile"}}, + "ProfileArn": {"Value": {"Fn::GetAtt": ["Profile", "Arn"]}}, + "ProfileName": {"Value": {"Fn::GetAtt": ["Profile", "ProfileName"]}}, + "ProfileVersion": {"Value": {"Fn::GetAtt": ["Profile", "ProfileVersion"]}}, + "ProfileVersionArn": {"Value": {"Fn::GetAtt": ["Profile", "ProfileVersionArn"]}}, + "CscRef": {"Value": {"Ref": "Csc"}}, + "CscArn": {"Value": {"Fn::GetAtt": ["Csc", "CodeSigningConfigArn"]}}, + "CscId": {"Value": {"Fn::GetAtt": ["Csc", "CodeSigningConfigId"]}}, + "Name": {"Value": {"Ref": "Fn"}} + } + } + """.formatted(functionProperty); + } + + private static void assertCodeSigningConfig(String function, String expected) { + given() + .when() + .get("/2020-06-30/functions/" + function + "/code-signing-config") + .then() + .statusCode(200) + .body("CodeSigningConfigArn", equalTo(expected)); + } + + private static XmlPath describe(String stackName) { + return cfn("DescribeStacks", stackName).when().post("/").then().statusCode(200).extract().xmlPath(); + } + + private static String output(XmlPath stack, String key) { + return stack.getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member" + + ".Outputs.member.find { it.OutputKey == '" + key + "' }.OutputValue"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java index f868c97790..445dd54ebb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisionerTest.java @@ -42,6 +42,8 @@ class LambdaCfnProvisionerTest { private static final String REGION = "us-east-1"; private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:000000000000:function:"; private static final String TEMPLATE_TAG_KEYS_ATTR = "FlociLambdaTemplateTagKeys"; + private static final String CSC_ARN = + "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0123456789abcdef0"; private final LambdaService lambda = mock(LambdaService.class); private final LambdaCfnProvisioner provisioner = new LambdaCfnProvisioner( @@ -103,12 +105,13 @@ class LambdaCfnProvisionerTest { return fn; } - private void stubInPlaceUpdate(String name, Map currentTags) { + private LambdaFunction stubInPlaceUpdate(String name, Map currentTags) { LambdaFunction existing = lambdaFunction(name); when(lambda.getFunction(REGION, name)).thenReturn(existing); when(lambda.updateFunctionConfiguration(anyString(), anyString(), anyMap())).thenReturn(existing); when(lambda.updateFunctionCode(anyString(), anyString(), anyMap())).thenReturn(existing); when(lambda.listTags(FUNCTION_ARN + name)).thenReturn(new HashMap<>(currentTags)); + return existing; } @Test @@ -275,6 +278,69 @@ class LambdaCfnProvisionerTest { verify(lambda, times(1)).getFunction(REGION, "my-fn"); } + @Test + void codeSigningConfigFromTheTemplateReachesCreateFunction() { + LambdaFunction created = lambdaFunction("my-fn"); + created.setCodeSigningConfigArn(CSC_ARN); + when(lambda.createFunction(eq(REGION), anyMap())).thenReturn(created); + + provisioner.provision(function(null), props("my-fn").put("CodeSigningConfigArn", CSC_ARN), ctx()); + + assertEquals(CSC_ARN, capturedCreateRequest().get("CodeSigningConfigArn")); + verify(lambda, never()).attachFunctionCodeSigningConfig(anyString(), anyString(), anyString()); + } + + @Test + void inPlaceUpdateAttachesANewCodeSigningConfig() { + stubInPlaceUpdate("my-fn", Map.of()); + + provisioner.provision(function("my-fn"), props("my-fn").put("CodeSigningConfigArn", CSC_ARN), + updateCtx("my-fn")); + + verify(lambda).attachFunctionCodeSigningConfig(REGION, "my-fn", CSC_ARN); + } + + @Test + void inPlaceUpdateWithTheSameCodeSigningConfigLeavesItAttached() { + stubInPlaceUpdate("my-fn", Map.of()).setCodeSigningConfigArn(CSC_ARN); + + provisioner.provision(function("my-fn"), props("my-fn").put("CodeSigningConfigArn", CSC_ARN), + updateCtx("my-fn")); + + verify(lambda, never()).attachFunctionCodeSigningConfig(anyString(), anyString(), anyString()); + verify(lambda, never()).deleteFunctionCodeSigningConfig(anyString(), anyString()); + } + + @Test + void blankCodeSigningConfigArnIsLeftForLambdaToReject() { + when(lambda.createFunction(eq(REGION), anyMap())).thenReturn(lambdaFunction("my-fn")); + + provisioner.provision(function(null), props("my-fn").put("CodeSigningConfigArn", " "), ctx()); + + assertEquals(" ", capturedCreateRequest().get("CodeSigningConfigArn")); + } + + @Test + void inPlaceUpdateWithTheCodeSigningConfigGoneDetachesIt() { + stubInPlaceUpdate("my-fn", Map.of()).setCodeSigningConfigArn(CSC_ARN); + ProvisionContext update = updateCtx("my-fn"); + + provisioner.provision(function("my-fn"), props("my-fn"), new ProvisionContext(update.engine(), REGION, + update.accountId(), update.stackName(), "my-fn", event -> {}, + props("my-fn").put("CodeSigningConfigArn", CSC_ARN))); + + verify(lambda).deleteFunctionCodeSigningConfig(REGION, "my-fn"); + } + + @Test + void inPlaceUpdateKeepsACodeSigningConfigTheStackNeverDeclared() { + stubInPlaceUpdate("my-fn", Map.of()).setCodeSigningConfigArn(CSC_ARN); + + provisioner.provision(function("my-fn"), props("my-fn"), updateCtx("my-fn")); + + verify(lambda, never()).deleteFunctionCodeSigningConfig(anyString(), anyString()); + } + @SuppressWarnings("unchecked") private Map capturedCreateRequest() { ArgumentCaptor> request = ArgumentCaptor.forClass(Map.class); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCodeSigningConfigCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCodeSigningConfigCfnProvisionerTest.java new file mode 100644 index 0000000000..64b9e73aad --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCodeSigningConfigCfnProvisionerTest.java @@ -0,0 +1,284 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.lambda.LambdaCodeSigningConfigService; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class LambdaCodeSigningConfigCfnProvisionerTest { + + private static final String REGION = "eu-west-1"; + private static final String ACCOUNT = "000000000000"; + private static final String CSC_ARN = "arn:aws:lambda:eu-west-1:000000000000:code-signing-config:csc-0123456789abcdef0"; + private static final String PROFILE_VERSION_ARN = + "arn:aws:signer:eu-west-1:000000000000:/signing-profiles/my_profile/AbCdEfGhIj"; + + private final LambdaCodeSigningConfigService configs = mock(LambdaCodeSigningConfigService.class); + private final LambdaService lambda = mock(LambdaService.class); + private final LambdaCodeSigningConfigCfnProvisioner provisioner = + new LambdaCodeSigningConfigCfnProvisioner(configs, lambda); + private final ObjectMapper mapper = new ObjectMapper(); + + LambdaCodeSigningConfigCfnProvisionerTest() { + when(configs.withConfigLock(anyString(), any())).thenAnswer(inv -> ((Supplier) inv.getArgument(1)).get()); + } + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null || node.isMissingNode() ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolveStringList(any())).thenAnswer(inv -> { + List values = new ArrayList<>(); + ((JsonNode) inv.getArgument(0)).forEach(node -> values.add(node.asText())); + return values; + }); + return new ProvisionContext(engine, REGION, ACCOUNT, "my-stack", priorPhysicalId); + } + + private static StackResource config() { + StackResource r = new StackResource(); + r.setLogicalId("Csc"); + r.setResourceType("AWS::Lambda::CodeSigningConfig"); + r.setAttributes(new HashMap<>()); + return r; + } + + private ObjectNode props() { + ObjectNode props = mapper.createObjectNode(); + props.putObject("AllowedPublishers").putArray("SigningProfileVersionArns").add(PROFILE_VERSION_ARN); + return props; + } + + private static CodeSigningConfig stored() { + CodeSigningConfig config = new CodeSigningConfig(); + config.setCodeSigningConfigArn(CSC_ARN); + config.setCodeSigningConfigId("csc-0123456789abcdef0"); + return config; + } + + @Test + void createRefsTheArnAndExposesBothAttributes() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + StackResource r = config(); + + provisioner.provision(r, props(), ctx(null)); + + assertEquals(CSC_ARN, r.getPhysicalId()); + assertEquals(CSC_ARN, r.getAttributes().get("CodeSigningConfigArn")); + assertEquals("csc-0123456789abcdef0", r.getAttributes().get("CodeSigningConfigId")); + } + + @Test + void createPassesThePublishersAndTheDefaults() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + ArgumentCaptor publishers = + ArgumentCaptor.forClass(CodeSigningConfig.AllowedPublishers.class); + ArgumentCaptor policies = + ArgumentCaptor.forClass(CodeSigningConfig.CodeSigningPolicies.class); + + provisioner.provision(config(), props(), ctx(null)); + + verify(configs).create(eq(REGION), eq(ACCOUNT), eq(""), publishers.capture(), policies.capture()); + assertEquals(List.of(PROFILE_VERSION_ARN), publishers.getValue().getSigningProfileVersionArns()); + assertEquals("Warn", policies.getValue().getUntrustedArtifactOnDeployment()); + } + + @Test + void absentPropertiesLeaveTheMissingPublishersForLambdaToReject() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + ArgumentCaptor publishers = + ArgumentCaptor.forClass(CodeSigningConfig.AllowedPublishers.class); + + provisioner.provision(config(), null, ctx(null)); + + verify(configs).create(eq(REGION), eq(ACCOUNT), eq(""), publishers.capture(), any()); + assertEquals(List.of(), publishers.getValue().getSigningProfileVersionArns()); + } + + @Test + void updateAppliesTheTemplateInPlace() { + when(configs.get(REGION, CSC_ARN)).thenReturn(stored()); + when(configs.update(eq(REGION), eq(CSC_ARN), any(), any(), any())).thenReturn(stored()); + ObjectNode props = props().put("Description", "signed"); + props.putObject("CodeSigningPolicies").put("UntrustedArtifactOnDeployment", "Enforce"); + ArgumentCaptor policies = + ArgumentCaptor.forClass(CodeSigningConfig.CodeSigningPolicies.class); + StackResource r = config(); + r.setPhysicalId(CSC_ARN); + + provisioner.provision(r, props, ctx(CSC_ARN)); + + verify(configs).withConfigLock(eq(CSC_ARN), any()); + verify(configs).update(eq(REGION), eq(CSC_ARN), eq("signed"), any(), policies.capture()); + verify(configs, never()).create(any(), any(), any(), any(), any()); + assertEquals("Enforce", policies.getValue().getUntrustedArtifactOnDeployment()); + assertEquals(CSC_ARN, r.getPhysicalId()); + } + + @Test + void rollbackRestoresWhatTheUpdateChanged() { + CodeSigningConfig before = stored(); + before.setDescription("before"); + CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers(); + publishers.setSigningProfileVersionArns(List.of(PROFILE_VERSION_ARN)); + before.setAllowedPublishers(publishers); + CodeSigningConfig.CodeSigningPolicies policies = new CodeSigningConfig.CodeSigningPolicies(); + policies.setUntrustedArtifactOnDeployment("Warn"); + before.setCodeSigningPolicies(policies); + when(configs.get(REGION, CSC_ARN)).thenReturn(before); + when(configs.update(eq(REGION), eq(CSC_ARN), any(), any(), any())).thenReturn(stored()); + StackResource r = config(); + r.setPhysicalId(CSC_ARN); + provisioner.provision(r, props().put("Description", "signed"), ctx(CSC_ARN)); + ArgumentCaptor restoredPublishers = + ArgumentCaptor.forClass(CodeSigningConfig.AllowedPublishers.class); + ArgumentCaptor restoredPolicies = + ArgumentCaptor.forClass(CodeSigningConfig.CodeSigningPolicies.class); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(configs).update(eq(REGION), eq(CSC_ARN), eq("before"), restoredPublishers.capture(), + restoredPolicies.capture()); + assertEquals(List.of(PROFILE_VERSION_ARN), restoredPublishers.getValue().getSigningProfileVersionArns()); + assertEquals("Warn", restoredPolicies.getValue().getUntrustedArtifactOnDeployment()); + assertEquals(CSC_ARN, r.getPhysicalId()); + } + + @Test + void rollbackOfAStubMigrationDeletesTheCreatedConfig() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + StackResource r = config(); + r.setPhysicalId("Csc-0a1b2c3d"); + r.getAttributes().put("Arn", "arn:aws:stub:::Csc"); + provisioner.provision(r, props(), ctx("Csc-0a1b2c3d")); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(lambda).deleteCodeSigningConfig(REGION, ACCOUNT, CSC_ARN); + assertEquals("Csc-0a1b2c3d", r.getPhysicalId()); + } + + @Test + void configARollbackCouldNotDeleteIsDeletedByTheNextCleanup() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + doThrow(new AwsException("ResourceConflictException", "attached", 409)).doNothing() + .when(lambda).deleteCodeSigningConfig(REGION, ACCOUNT, CSC_ARN); + StackResource r = config(); + r.setPhysicalId("Csc-0a1b2c3d"); + r.getAttributes().put("Arn", "arn:aws:stub:::Csc"); + provisioner.provision(r, props(), ctx("Csc-0a1b2c3d")); + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals(CSC_ARN, provisioner.updateCleanupPhysicalId(r)); + assertTrue(provisioner.completeUpdate(r).complete()); + verify(lambda, times(2)).deleteCodeSigningConfig(REGION, ACCOUNT, CSC_ARN); + } + + @Test + void whitespaceDescriptionIsKept() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + + provisioner.provision(config(), props().put("Description", " "), ctx(null)); + + verify(configs).create(eq(REGION), eq(ACCOUNT), eq(" "), any(), any()); + } + + @Test + void blankPolicyIsLeftForLambdaToReject() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + ObjectNode props = props(); + props.putObject("CodeSigningPolicies").put("UntrustedArtifactOnDeployment", " "); + ArgumentCaptor policies = + ArgumentCaptor.forClass(CodeSigningConfig.CodeSigningPolicies.class); + + provisioner.provision(config(), props, ctx(null)); + + verify(configs).create(eq(REGION), eq(ACCOUNT), eq(""), any(), policies.capture()); + assertEquals(" ", policies.getValue().getUntrustedArtifactOnDeployment()); + } + + @Test + void updateOfAStubFromBeforeThisProvisionerCreatesTheConfig() { + when(configs.create(eq(REGION), eq(ACCOUNT), any(), any(), any())).thenReturn(stored()); + StackResource r = config(); + r.setPhysicalId("Csc-0a1b2c3d"); + + provisioner.provision(r, props(), ctx("Csc-0a1b2c3d")); + + verify(configs, never()).update(any(), any(), any(), any(), any()); + assertEquals(CSC_ARN, r.getPhysicalId()); + } + + @Test + void deleteOfAStubTouchesNothing() { + provisioner.delete("AWS::Lambda::CodeSigningConfig", "Csc-0a1b2c3d", REGION); + + verify(lambda, never()).deleteCodeSigningConfig(any(), any(), any()); + } + + @Test + void deleteRemovesTheConfigThroughLambda() { + provisioner.delete("AWS::Lambda::CodeSigningConfig", CSC_ARN, REGION); + + verify(lambda).deleteCodeSigningConfig(REGION, ACCOUNT, CSC_ARN); + } + + @Test + void deleteToleratesAConfigAlreadyGone() { + doThrow(new AwsException("ResourceNotFoundException", "gone", 404)) + .when(lambda).deleteCodeSigningConfig(REGION, ACCOUNT, CSC_ARN); + + provisioner.delete("AWS::Lambda::CodeSigningConfig", CSC_ARN, REGION); + } + + @Test + void deleteLooksTheConfigUpInTheArnsOwnAccount() { + String foreign = "arn:aws:lambda:eu-west-1:111111111111:code-signing-config:csc-0123456789abcdef0"; + doThrow(new AwsException("ResourceNotFoundException", "not found", 404)) + .when(lambda).deleteCodeSigningConfig(REGION, "111111111111", foreign); + + provisioner.delete("AWS::Lambda::CodeSigningConfig", foreign, REGION); + + verify(lambda).deleteCodeSigningConfig(REGION, "111111111111", foreign); + } + + @Test + void deleteRefusesAConfigStillAttachedToAFunction() { + doThrow(new AwsException("ResourceConflictException", "attached", 409)) + .when(lambda).deleteCodeSigningConfig(REGION, ACCOUNT, CSC_ARN); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.delete("AWS::Lambda::CodeSigningConfig", CSC_ARN, REGION)); + + assertEquals("ResourceConflictException", e.getErrorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SignerCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SignerCfnProvisionerTest.java new file mode 100644 index 0000000000..26ae5d79ae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SignerCfnProvisionerTest.java @@ -0,0 +1,290 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.DoubleNode; +import com.fasterxml.jackson.databind.node.LongNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SignerCfnProvisionerTest { + + private static final String PROFILE_ARN_PREFIX = "arn:aws:signer:eu-west-1:000000000000:/signing-profiles/"; + + private final SignerCfnProvisioner provisioner = new SignerCfnProvisioner(); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null || node.isMissingNode() ? null : node.asText(); + }); + when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0)); + return new ProvisionContext(engine, "eu-west-1", "000000000000", "my-stack", priorPhysicalId); + } + + private static StackResource profile() { + StackResource r = new StackResource(); + r.setLogicalId("Profile"); + r.setResourceType("AWS::Signer::SigningProfile"); + r.setAttributes(new HashMap<>()); + return r; + } + + private ObjectNode props(String profileName) { + ObjectNode props = mapper.createObjectNode().put("PlatformId", "AWSLambda-SHA384-ECDSA"); + if (profileName != null) { + props.put("ProfileName", profileName); + } + return props; + } + + @Test + void namedProfileRefsItsArnAndExposesEveryAttribute() { + StackResource r = profile(); + + provisioner.provision(r, props("my_profile"), ctx(null)); + + String arn = PROFILE_ARN_PREFIX + "my_profile"; + String version = r.getAttributes().get("ProfileVersion"); + assertEquals(arn, r.getPhysicalId()); + assertEquals(arn, r.getAttributes().get("Arn")); + assertEquals("my_profile", r.getAttributes().get("ProfileName")); + assertTrue(version.matches("[A-Za-z0-9]{10}"), version); + assertEquals(arn + "/" + version, r.getAttributes().get("ProfileVersionArn")); + } + + @Test + void unnamedProfileGetsTheLogicalIdAndARandomSuffix() { + StackResource r = profile(); + + provisioner.provision(r, props(null), ctx(null)); + + String name = r.getAttributes().get("ProfileName"); + assertTrue(name.matches("Profile_[A-Za-z0-9]{12}"), name); + assertEquals(PROFILE_ARN_PREFIX + name, r.getPhysicalId()); + } + + @Test + void generatedNameStaysWithinTheProfileNameLimit() { + StackResource r = profile(); + r.setLogicalId("L".repeat(80)); + + provisioner.provision(r, props(null), ctx(null)); + + String name = r.getAttributes().get("ProfileName"); + assertEquals(64, name.length()); + assertTrue(name.matches("L{51}_[A-Za-z0-9]{12}"), name); + } + + @Test + void updateWithTheSameCreateOnlyPropertiesKeepsTheProfile() { + StackResource r = profile(); + provisioner.provision(r, props(null), ctx(null)); + Map created = new HashMap<>(r.getAttributes()); + String physicalId = r.getPhysicalId(); + + ObjectNode tagged = props(null); + tagged.putArray("Tags").addObject().put("Key", "team").put("Value", "a"); + provisioner.provision(r, tagged, ctx(physicalId)); + + assertEquals(physicalId, r.getPhysicalId()); + assertEquals(created, r.getAttributes()); + } + + @Test + void changedPlatformReplacesAnUnnamedProfile() { + StackResource r = profile(); + provisioner.provision(r, props(null), ctx(null)); + String physicalId = r.getPhysicalId(); + + provisioner.provision(r, props(null).put("PlatformId", "Notation-OCI-SHA384-ECDSA"), ctx(physicalId)); + + assertNotEquals(physicalId, r.getPhysicalId()); + assertTrue(r.getAttributes().get("ProfileName").matches("Profile_[A-Za-z0-9]{12}")); + } + + @Test + void changedValidityPeriodReplacesAnUnnamedProfile() { + StackResource r = profile(); + provisioner.provision(r, props(null), ctx(null)); + String physicalId = r.getPhysicalId(); + + ObjectNode changed = props(null); + changed.putObject("SignatureValidityPeriod").put("Type", "DAYS").put("Value", 30); + provisioner.provision(r, changed, ctx(physicalId)); + + assertNotEquals(physicalId, r.getPhysicalId()); + } + + @Test + void reorderedValidityPeriodKeysKeepTheProfile() { + StackResource r = profile(); + ObjectNode created = props(null); + created.putObject("SignatureValidityPeriod").put("Type", "DAYS").put("Value", 30); + provisioner.provision(r, created, ctx(null)); + String physicalId = r.getPhysicalId(); + + ObjectNode reordered = props(null); + reordered.putObject("SignatureValidityPeriod").put("Value", 30).put("Type", "DAYS"); + reordered.putArray("Tags").addObject().put("Key", "team").put("Value", "a"); + provisioner.provision(r, reordered, ctx(physicalId)); + + assertEquals(physicalId, r.getPhysicalId()); + } + + @Test + void rollbackOfAReplacementRestoresThePriorProfile() { + StackResource r = profile(); + provisioner.provision(r, props(null), ctx(null)); + Map created = new HashMap<>(r.getAttributes()); + String physicalId = r.getPhysicalId(); + provisioner.provision(r, props(null).put("PlatformId", "Notation-OCI-SHA384-ECDSA"), ctx(physicalId)); + + assertTrue(provisioner.rollbackUpdate(r)); + + assertEquals(physicalId, r.getPhysicalId()); + assertEquals(created, r.getAttributes()); + } + + @Test + void rollbackOfAnInPlaceUpdateKeepsTheProfile() { + StackResource r = profile(); + provisioner.provision(r, props(null), ctx(null)); + String physicalId = r.getPhysicalId(); + ObjectNode tagged = props(null); + tagged.putArray("Tags").addObject().put("Key", "team").put("Value", "a"); + provisioner.provision(r, tagged, ctx(physicalId)); + + assertTrue(provisioner.rollbackUpdate(r)); + + assertEquals(physicalId, r.getPhysicalId()); + } + + @Test + void committedReplacementCleansUpTheDisplacedProfile() { + StackResource r = profile(); + provisioner.provision(r, props(null), ctx(null)); + String physicalId = r.getPhysicalId(); + provisioner.provision(r, props(null).put("PlatformId", "Notation-OCI-SHA384-ECDSA"), ctx(physicalId)); + + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals(physicalId, provisioner.updateCleanupPhysicalId(r)); + assertTrue(provisioner.completeUpdate(r).complete()); + provisioner.clearUpdate(r); + + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @Test + void replacingACustomNamedProfileIsRefused() { + StackResource r = profile(); + provisioner.provision(r, props("my_profile"), ctx(null)); + ObjectNode changed = props("my_profile").put("PlatformId", "Notation-OCI-SHA384-ECDSA"); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(r, changed, ctx(r.getPhysicalId()))); + + assertEquals("ValidationError", e.getErrorCode()); + } + + @Test + void missingPlatformIdIsRejected() { + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(profile(), mapper.createObjectNode(), ctx(null))); + + assertEquals("ValidationError", e.getErrorCode()); + } + + @Test + void unknownPlatformIdIsRejected() { + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(profile(), props(null).put("PlatformId", "AWSIoT"), ctx(null))); + + assertEquals("ValidationError", e.getErrorCode()); + } + + @Test + void validityPeriodWithoutAKnownTypeAndAValueIsRejectedAsSignerRejectsIt() throws Exception { + String noType = "Signature validity period type must be one of [DAYS, MONTHS, YEARS]"; + Map cases = Map.of( + "{\"Type\": \"WEEKS\", \"Value\": 30}", noType, + "{}", noType, + "{\"Value\": 999999}", noType, + "{\"Type\": \"DAYS\"}", "Signature validity period value must be greater than 0."); + for (Map.Entry period : cases.entrySet()) { + ObjectNode props = props(null); + props.set("SignatureValidityPeriod", mapper.readTree(period.getKey())); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(profile(), props, ctx(null)), + period.getKey()); + + assertEquals("ValidationError", e.getErrorCode(), period.getKey()); + assertEquals(period.getValue(), e.getMessage(), period.getKey()); + } + } + + @Test + void validityPeriodOutsideTheSignerLimitsIsRejected() { + for (String period : List.of("DAYS:0", "DAYS:4106", "MONTHS:136", "YEARS:12")) { + ObjectNode props = props(null); + props.putObject("SignatureValidityPeriod").put("Type", period.split(":")[0]) + .put("Value", Integer.parseInt(period.split(":")[1])); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(profile(), props, ctx(null)), + period); + + assertEquals("ValidationError", e.getErrorCode(), period); + } + } + + @Test + void validityPeriodValueThatIsNotAnIntegerIsRejected() { + for (JsonNode value : List.of(DoubleNode.valueOf(11.5), BooleanNode.TRUE, + LongNode.valueOf(99_999_999_999L))) { + ObjectNode props = props(null); + props.putObject("SignatureValidityPeriod").put("Type", "YEARS").set("Value", value); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(profile(), props, ctx(null)), + value.toString()); + + assertEquals("ValidationError", e.getErrorCode(), value.toString()); + } + } + + @Test + void validityPeriodAtTheSignerLimitIsAccepted() { + ObjectNode props = props(null); + props.putObject("SignatureValidityPeriod").put("Type", "YEARS").put("Value", 11); + + provisioner.provision(profile(), props, ctx(null)); + } + + @Test + void profileNameOutsideThePatternIsRejected() { + for (String name : List.of("thiink-signing-profile", "", " ")) { + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(profile(), props(name), ctx(null)), "'" + name + "'"); + + assertEquals("ValidationError", e.getErrorCode(), "'" + name + "'"); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningAccountScopeTest.java index 30d728a577..9bd1233c28 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningAccountScopeTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningAccountScopeTest.java @@ -19,7 +19,6 @@ 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; -import static org.mockito.Mockito.mock; /** Code-signing mutations stay in the account selected by the request context. */ class LambdaCodeSigningAccountScopeTest { @@ -84,7 +83,7 @@ class LambdaCodeSigningAccountScopeTest { LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath), new ZipExtractor(), regions); LambdaCodeSigningController controller = new LambdaCodeSigningController( - service, mock(LambdaCodeSigningConfigService.class), regions, new ObjectMapper()); + service, regions, new ObjectMapper()); List references = List.of( REGION + ":" + CALLER_ACCOUNT + ":function:" + FUNCTION_NAME, @@ -234,7 +233,7 @@ class LambdaCodeSigningAccountScopeTest { new ZipExtractor(), regions); ObjectMapper mapper = new ObjectMapper(); LambdaCodeSigningController controller = new LambdaCodeSigningController( - service, mock(LambdaCodeSigningConfigService.class), regions, mapper); + service, regions, mapper); String foreignArn = "arn:aws:lambda:" + REGION + ":" + ARN_ACCOUNT + ":function:" + FUNCTION_NAME; diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java index 094b8006d8..9d66028f26 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigDeleteRaceTest.java @@ -63,10 +63,12 @@ class LambdaCodeSigningConfigDeleteRaceTest { function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + NAME); function.setVersion("$LATEST"); functions.saveForAccount(ACCOUNT, REGION, function); - LambdaService lambda = new LambdaService(functions, new WarmPool(), new CodeStore(codePath), - new ZipExtractor(), regions); + 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, new ObjectMapper(), configs); ObjectMapper mapper = new ObjectMapper(); - LambdaCodeSigningController attachments = new LambdaCodeSigningController(lambda, configs, regions, mapper); + LambdaCodeSigningController attachments = new LambdaCodeSigningController(lambda, regions, mapper); LambdaCodeSigningConfigFunctionsController configController = new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, mapper); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigUpdateDeleteRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigUpdateDeleteRaceTest.java index 8e6c57eec5..24458a8e9a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigUpdateDeleteRaceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigUpdateDeleteRaceTest.java @@ -53,8 +53,10 @@ class LambdaCodeSigningConfigUpdateDeleteRaceTest { String arn = configs.create(REGION, ACCOUNT, null, publishers, null).getCodeSigningConfigArn(); LambdaFunctionStore functions = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT)); - LambdaService lambda = new LambdaService(functions, new WarmPool(), new CodeStore(codePath), - new ZipExtractor(), regions); + 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, new ObjectMapper(), configs); ObjectMapper mapper = new ObjectMapper(); LambdaCodeSigningConfigFunctionsController controller = new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, mapper); diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index d40fb7a14b..841fcf71e1 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -135,6 +135,7 @@ AWS::KMS::Key Arn,KeyId BypassPolicyLockoutSafetyCheck,Description,EnableKeyRota AWS::Kinesis::Stream Arn,WarmThroughputObject DesiredShardLevelMetrics,MaxRecordSizeInKiB,Name,RecordDistributionStrategy,RetentionPeriodHours,ShardCount,StreamEncryption,StreamModeDetails,Tags,WarmThroughputMiBps AWS::KinesisFirehose::DeliveryStream Arn AmazonOpenSearchServerlessDestinationConfiguration,AmazonopensearchserviceDestinationConfiguration,DatabaseSourceConfiguration,DeliveryStreamEncryptionConfigurationInput,DeliveryStreamName,DeliveryStreamType,DirectPutSourceConfiguration,ElasticsearchDestinationConfiguration,ExtendedS3DestinationConfiguration,HttpEndpointDestinationConfiguration,IcebergDestinationConfiguration,KinesisStreamSourceConfiguration,MSKSourceConfiguration,RedshiftDestinationConfiguration,S3DestinationConfiguration,SnowflakeDestinationConfiguration,SplunkDestinationConfiguration,Tags AWS::Lambda::Alias AliasArn Description,FunctionName,FunctionVersion,Name,ProvisionedConcurrencyConfig,RoutingConfig +AWS::Lambda::CodeSigningConfig CodeSigningConfigArn,CodeSigningConfigId AllowedPublishers,CodeSigningPolicies,Description,Tags AWS::Lambda::EventInvokeConfig DestinationConfig,FunctionName,MaximumEventAgeInSeconds,MaximumRetryAttempts,Qualifier AWS::Lambda::EventSourceMapping EventSourceMappingArn,Id AmazonManagedKafkaEventSourceConfig,BatchSize,BisectBatchOnFunctionError,DestinationConfig,DocumentDBEventSourceConfig,Enabled,EventSourceArn,FilterCriteria,FunctionName,FunctionResponseTypes,KmsKeyArn,LoggingConfig,MaximumBatchingWindowInSeconds,MaximumRecordAgeInSeconds,MaximumRetryAttempts,MetricsConfig,ParallelizationFactor,ProvisionedPollerConfig,Queues,ScalingConfig,SelfManagedEventSource,SelfManagedKafkaEventSourceConfig,SourceAccessConfigurations,StartingPosition,StartingPositionTimestamp,Tags,Topics,TumblingWindowInSeconds AWS::Lambda::Function Arn,SnapStartResponse Architectures,CapacityProviderConfig,Code,CodeSigningConfigArn,DeadLetterConfig,Description,DurableConfig,Environment,EphemeralStorage,FileSystemConfigs,FunctionName,FunctionScalingConfig,Handler,ImageConfig,KmsKeyArn,Layers,LoggingConfig,MemorySize,PackageType,PublishToLatestPublished,RecursiveLoop,ReservedConcurrentExecutions,Role,Runtime,RuntimeManagementConfig,SnapStart,Tags,TenancyConfig,Timeout,TracingConfig,VpcConfig @@ -194,6 +195,7 @@ AWS::ServiceDiscovery::HttpNamespace Arn,Id Description,Name,Tags AWS::ServiceDiscovery::PrivateDnsNamespace Arn,HostedZoneId,Id Description,Name,Properties,Tags,Vpc AWS::ServiceDiscovery::PublicDnsNamespace Arn,HostedZoneId,Id Description,Name,Properties,Tags AWS::ServiceDiscovery::Service Arn,Id Description,DnsConfig,HealthCheckConfig,HealthCheckCustomConfig,Name,NamespaceId,ServiceAttributes,Tags,Type +AWS::Signer::SigningProfile Arn,ProfileName,ProfileVersion,ProfileVersionArn PlatformId,SignatureValidityPeriod,Tags AWS::StepFunctions::StateMachine Arn,Name,StateMachineRevisionId Definition,DefinitionS3Location,DefinitionString,DefinitionSubstitutions,EncryptionConfiguration,LoggingConfiguration,RoleArn,StateMachineName,StateMachineType,Tags,TracingConfiguration AWS::Transfer::Server Arn,As2ServiceManagedEgressIpAddresses,ServerId,State Certificate,CreateWithHostKey,Domain,EndpointDetails,EndpointType,IdentityProviderDetails,IdentityProviderType,IpAddressType,LoggingRole,PostAuthenticationLoginBanner,PreAuthenticationLoginBanner,ProtocolDetails,Protocols,S3StorageOptions,SecurityPolicyName,StructuredLogDestinations,Tags,WorkflowDetails AWS::Transfer::User Arn HomeDirectory,HomeDirectoryMappings,HomeDirectoryType,Policy,PosixProfile,Role,ServerId,SshPublicKeys,Tags,UserName diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 49b36eb0ce..4ff0f3b75e 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -136,6 +136,7 @@ AWS::KMS::Key KmsCfnProvisioner AWS::Kinesis::Stream KinesisCfnProvisioner AWS::KinesisFirehose::DeliveryStream FirehoseCfnProvisioner AWS::Lambda::Alias LambdaVersionAliasCfnProvisioner +AWS::Lambda::CodeSigningConfig LambdaCodeSigningConfigCfnProvisioner AWS::Lambda::EventInvokeConfig LambdaEventInvokeConfigCfnProvisioner AWS::Lambda::EventSourceMapping LambdaEventSourceMappingCfnProvisioner AWS::Lambda::Function LambdaCfnProvisioner @@ -195,6 +196,7 @@ AWS::ServiceDiscovery::HttpNamespace CloudMapCfnProvisioner AWS::ServiceDiscovery::PrivateDnsNamespace CloudMapCfnProvisioner AWS::ServiceDiscovery::PublicDnsNamespace CloudMapCfnProvisioner AWS::ServiceDiscovery::Service CloudMapCfnProvisioner +AWS::Signer::SigningProfile SignerCfnProvisioner AWS::StepFunctions::StateMachine StepFunctionsCfnProvisioner AWS::Transfer::Server TransferCfnProvisioner AWS::Transfer::User TransferCfnProvisioner diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 3b484286e2..6f53127a92 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -396,6 +396,7 @@ AWS::KinesisFirehose::DeliveryStream RedshiftDestinationConfiguration documented AWS::KinesisFirehose::DeliveryStream SnowflakeDestinationConfiguration documented as ignored (docs/services/cloudformation.md, Kinesis Data Firehose) AWS::KinesisFirehose::DeliveryStream SplunkDestinationConfiguration documented as ignored (docs/services/cloudformation.md, Kinesis Data Firehose) AWS::Lambda::Alias ProvisionedConcurrencyConfig accepted and ignored +AWS::Lambda::CodeSigningConfig Tags accepted and ignored AWS::Lambda::EventSourceMapping AmazonManagedKafkaEventSourceConfig accepted and ignored AWS::Lambda::EventSourceMapping DocumentDBEventSourceConfig accepted and ignored AWS::Lambda::EventSourceMapping KmsKeyArn accepted and ignored @@ -408,7 +409,6 @@ AWS::Lambda::EventSourceMapping SelfManagedKafkaEventSourceConfig accepted and i AWS::Lambda::EventSourceMapping Tags accepted and ignored AWS::Lambda::EventSourceMapping TumblingWindowInSeconds documented as ignored (docs/services/cloudformation.md, Lambda) AWS::Lambda::Function CapacityProviderConfig accepted and ignored -AWS::Lambda::Function CodeSigningConfigArn accepted and ignored AWS::Lambda::Function FunctionScalingConfig accepted and ignored AWS::Lambda::Function KmsKeyArn accepted and ignored AWS::Lambda::Function PublishToLatestPublished accepted and ignored @@ -648,6 +648,7 @@ AWS::SecretsManager::Secret Type accepted and ignored AWS::ServiceDiscovery::PrivateDnsNamespace Properties accepted and ignored AWS::ServiceDiscovery::PublicDnsNamespace Properties accepted and ignored AWS::ServiceDiscovery::Service ServiceAttributes accepted and ignored +AWS::Signer::SigningProfile Tags accepted and ignored: Floci has no Signer API to tag AWS::Transfer::Server Certificate rejected with a ValidationError, not supported by Floci AWS::Transfer::Server CreateWithHostKey rejected with a ValidationError, not supported by Floci AWS::Transfer::Server IpAddressType rejected with a ValidationError, not supported by Floci diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index cc8ec513e6..80baeeae2e 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -17,6 +17,7 @@ order: - AWS::SES - AWS::DynamoDB - AWS::Lambda + - AWS::Signer - AWS::IAM - AWS::Organizations - AWS::SSM @@ -175,6 +176,7 @@ service_labels: AWS::Scheduler: EventBridge Scheduler AWS::SecretsManager: Secrets Manager AWS::ServiceDiscovery: Cloud Map + AWS::Signer: Signer AWS::StepFunctions: Step Functions AWS::Transfer: Transfer Family AWS::WAFv2: WAFv2 @@ -187,6 +189,7 @@ notes: AWS::Lambda::Function: Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored' AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands into + AWS::Signer::SigningProfile: identifiers only; Floci has no Signer API AWS::Lambda::EventInvokeConfig: also what a SAM function's `EventInvokeConfig` expands into AWS::Lambda::WebFunction: control plane only; the endpoint domain does not serve requests yet AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision