diff --git a/docs/services/lambda.md b/docs/services/lambda.md index acfee960a9..8b22263bf2 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -33,7 +33,12 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `GetPolicy` | Get the function resource policy | | `RemovePermission` | Remove a resource-policy statement | | `GetFunctionCodeSigningConfig` | Return code-signing config (always empty) | -| `ListFunctionsByCodeSigningConfig` | Validates the ARN; no code-signing config can exist, so every well-formed ARN returns `ResourceNotFoundException` | +| `ListFunctionsByCodeSigningConfig` | List functions carrying a config. Always empty, since nothing can attach one | +| `CreateCodeSigningConfig` | Create a code signing configuration | +| `GetCodeSigningConfig` | Read a code signing configuration | +| `UpdateCodeSigningConfig` | Update the members the request names | +| `DeleteCodeSigningConfig` | Delete a code signing configuration | +| `ListCodeSigningConfigs` | List the configurations in the region | | `CreateFunctionUrlConfig` | Provision a function URL | | `GetFunctionUrlConfig` | Read function URL config | | `UpdateFunctionUrlConfig` | Update function URL config | @@ -305,7 +310,13 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or - Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`) - Provisioned concurrency (`PutProvisionedConcurrencyConfig`, `GetProvisionedConcurrencyConfig`, `ListProvisionedConcurrencyConfigs`, `DeleteProvisionedConcurrencyConfig`) - `InvokeWithResponseStream` -- Code signing management (only `GetFunctionCodeSigningConfig` and `ListFunctionsByCodeSigningConfig` are wired; there is no `PutFunctionCodeSigningConfig` or `CreateCodeSigningConfig`, so no code-signing config can exist and `ListFunctionsByCodeSigningConfig` reports every well-formed ARN as `ResourceNotFoundException` — a malformed ARN or an out-of-range `MaxItems` is rejected with `InvalidParameterValueException` first) +- Code signing enforcement. A configuration is created, read, updated, deleted and listed, and + nothing verifies a signature against it, so it never gates a deployment. Attaching one to a + function is not wired either: there is no `PutFunctionCodeSigningConfig`, so + `GetFunctionCodeSigningConfig` still reports an empty ARN and `ListFunctionsByCodeSigningConfig` + always reports no functions. An unknown configuration is `ResourceNotFoundException`, and a + malformed ARN or an out-of-range `MaxItems` is rejected with `InvalidParameterValueException` + first ## Configuration 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 2d2697e54c..2140856640 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 @@ -1,19 +1,30 @@ package io.github.hectorvent.floci.services.lambda; +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.core.common.RegionResolver; +import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig; +import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.util.List; import java.util.regex.Pattern; /** - * ListFunctionsByCodeSigningConfig: GET /2020-04-22/code-signing-configs/{CodeSigningConfigArn}/functions. + * The code signing configuration resource, all under /2020-04-22/code-signing-configs. * *

A separate class from {@link LambdaCodeSigningController} because it lives * under a different API version prefix (/2020-04-22 vs /2020-06-30) — JAX-RS @@ -21,16 +32,15 @@ import java.util.regex.Pattern; * one falls through to a more general catch-all route (S3's bucket-path matcher) * instead of matching here.

* - *

Floci does not implement code signing config management — there is no - * CreateCodeSigningConfig / PutFunctionCodeSigningConfig, so no code signing - * config can ever exist. That does not make an unconditional empty list - * the right answer: botocore models both {@code InvalidParameterValueException} - * and {@code ResourceNotFoundException} for this operation, and the only resource - * the path parameter can name is a code signing config. A malformed ARN is - * therefore a 400 and a well-formed ARN is a 404, because every well-formed ARN - * necessarily names a config that does not exist here. Returning 200 with an - * empty list would tell a caller that the config exists and simply has no - * functions attached, which is a different — and false — statement.

+ *

Create, Get, Update, Delete and List manage the configuration itself. + * ListFunctionsByCodeSigningConfig reports which functions carry one, and always reports none: + * attaching a configuration to a function is PutFunctionCodeSigningConfig, which is not + * implemented, so nothing can be attached. It answers a configuration that does not exist with a + * 404 rather than an empty list, because an empty list would say the configuration exists and + * simply has no functions.

+ * + *

Nothing here verifies a signature. Lambda's own code signing checks are not emulated, so a + * configuration never gates a deployment.

*/ @Path("/2020-04-22") @Produces(MediaType.APPLICATION_JSON) @@ -51,6 +61,19 @@ public class LambdaCodeSigningConfigFunctionsController { private static final int MAX_ITEMS_MIN = 1; private static final int MAX_ITEMS_MAX = 10000; + private final LambdaCodeSigningConfigService service; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public LambdaCodeSigningConfigFunctionsController(LambdaCodeSigningConfigService service, + RegionResolver regionResolver, + ObjectMapper objectMapper) { + this.service = service; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + /** * Validation order matches AWS: request parameters are rejected before the * resource is resolved, so a bad {@code MaxItems} is reported as such rather @@ -59,16 +82,95 @@ public class LambdaCodeSigningConfigFunctionsController { @GET @Path("/code-signing-configs/{codeSigningConfigArn}/functions") public Response listFunctionsByCodeSigningConfig( + @Context HttpHeaders headers, @PathParam("codeSigningConfigArn") String codeSigningConfigArn, @QueryParam("Marker") String marker, @QueryParam("MaxItems") String maxItems) { requireValidArn(codeSigningConfigArn); parseMaxItems(maxItems); - // Marker is accepted and carries no state: the result set is always empty, - // so any marker addresses a page past the end and NextMarker is never emitted. + // Resolving the config is what turns an unknown ARN into the 404. A known one has no + // functions, since PutFunctionCodeSigningConfig is not implemented, so Marker addresses a + // page past the end and NextMarker is never emitted. + service.get(regionResolver.resolveRegion(headers), codeSigningConfigArn); - throw new AwsException("ResourceNotFoundException", - "The code signing configuration " + codeSigningConfigArn + " does not exist.", 404); + ObjectNode root = objectMapper.createObjectNode(); + root.putArray("FunctionArns"); + return Response.ok(root).build(); + } + + @POST + @Path("/code-signing-configs") + 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)); + return Response.status(Response.Status.CREATED).entity(wrap(config)).build(); + } + + @GET + @Path("/code-signing-configs/{codeSigningConfigArn}") + public Response getCodeSigningConfig(@Context HttpHeaders headers, + @PathParam("codeSigningConfigArn") String codeSigningConfigArn) { + requireValidArn(codeSigningConfigArn); + return Response.ok(wrap(service.get(regionResolver.resolveRegion(headers), codeSigningConfigArn))).build(); + } + + @PUT + @Path("/code-signing-configs/{codeSigningConfigArn}") + public Response updateCodeSigningConfig(@Context HttpHeaders headers, + @PathParam("codeSigningConfigArn") String codeSigningConfigArn, + ObjectNode body) { + requireValidArn(codeSigningConfigArn); + CodeSigningConfig config = service.update(regionResolver.resolveRegion(headers), codeSigningConfigArn, + text(body, "Description"), allowedPublishers(body), policies(body)); + return Response.ok(wrap(config)).build(); + } + + @DELETE + @Path("/code-signing-configs/{codeSigningConfigArn}") + public Response deleteCodeSigningConfig(@Context HttpHeaders headers, + @PathParam("codeSigningConfigArn") String codeSigningConfigArn) { + requireValidArn(codeSigningConfigArn); + service.delete(regionResolver.resolveRegion(headers), codeSigningConfigArn); + return Response.noContent().build(); + } + + @GET + @Path("/code-signing-configs") + public Response listCodeSigningConfigs(@Context HttpHeaders headers, + @QueryParam("Marker") String marker, + @QueryParam("MaxItems") String maxItems) { + parseMaxItems(maxItems); + List configs = service.list(regionResolver.resolveRegion(headers)); + ObjectNode root = objectMapper.createObjectNode(); + root.set("CodeSigningConfigs", objectMapper.valueToTree(configs)); + return Response.ok(root).build(); + } + + private ObjectNode wrap(CodeSigningConfig config) { + ObjectNode root = objectMapper.createObjectNode(); + root.set("CodeSigningConfig", objectMapper.valueToTree(config)); + return root; + } + + private static String text(ObjectNode body, String field) { + return body == null || !body.hasNonNull(field) ? null : body.get(field).asText(); + } + + private CodeSigningConfig.AllowedPublishers allowedPublishers(ObjectNode body) { + if (body == null || !body.hasNonNull("AllowedPublishers")) { + return null; + } + return objectMapper.convertValue(body.get("AllowedPublishers"), + CodeSigningConfig.AllowedPublishers.class); + } + + private CodeSigningConfig.CodeSigningPolicies policies(ObjectNode body) { + if (body == null || !body.hasNonNull("CodeSigningPolicies")) { + return null; + } + return objectMapper.convertValue(body.get("CodeSigningPolicies"), + CodeSigningConfig.CodeSigningPolicies.class); } private void requireValidArn(String arn) { diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigService.java new file mode 100644 index 0000000000..0e2d4400b8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigService.java @@ -0,0 +1,205 @@ +package io.github.hectorvent.floci.services.lambda; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.security.SecureRandom; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +/** + * Code signing configurations, the resource CreateCodeSigningConfig manages. + * + *

Nothing is verified against these. Lambda's own signature checking is not emulated, so a + * configuration is stored and reported back and never gates a deployment. + */ +@ApplicationScoped +public class LambdaCodeSigningConfigService { + + /** + * Lowercase alphanumerics because the ARN is the stricter of the two patterns, not the id. + * CodeSigningConfigId allows {@code csc-[a-zA-Z0-9-_\.]{17}}, while CodeSigningConfigArn ends + * in {@code csc-[a-z0-9]{17}}. Widening this alphabet to match the id pattern would still mint + * a conforming id and an ARN that no longer conforms. + */ + private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static final int ID_LENGTH = 17; + private static final int MAX_DESCRIPTION = 256; + private static final int MAX_SIGNING_PROFILE_ARNS = 20; + + /** The model documents Warn as the default when the request names no policy. */ + static final String DEFAULT_UNTRUSTED_ARTIFACT_POLICY = "Warn"; + private static final List POLICIES = List.of("Warn", "Enforce"); + + private static final DateTimeFormatter LAST_MODIFIED = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").withZone(ZoneOffset.UTC); + + private final StorageBackend store; + private final SecureRandom random = new SecureRandom(); + + @Inject + public LambdaCodeSigningConfigService(StorageFactory storageFactory) { + this.store = storageFactory.create("lambda", "lambda-code-signing-configs.json", + new TypeReference>() {}); + } + + public CodeSigningConfig create(String region, String accountId, String description, + CodeSigningConfig.AllowedPublishers allowedPublishers, + CodeSigningConfig.CodeSigningPolicies policies) { + validateDescription(description); + validateAllowedPublishers(allowedPublishers); + validatePolicies(policies); + + String id = "csc-" + randomId(); + CodeSigningConfig config = new CodeSigningConfig(); + config.setCodeSigningConfigId(id); + config.setCodeSigningConfigArn( + AwsArnUtils.Arn.of("lambda", region, accountId, "code-signing-config:" + id).toString()); + config.setDescription(description); + config.setAllowedPublishers(allowedPublishers); + config.setCodeSigningPolicies(policies != null ? policies : defaultPolicies()); + config.setLastModified(now()); + store.put(key(region, id), config); + return config; + } + + public CodeSigningConfig get(String region, String arn) { + return store.get(key(region, idFromArn(arn))) + .orElseThrow(() -> notFound(arn)); + } + + /** + * Applies only the members the request names. A member the request omits keeps its stored + * value, which is what UpdateCodeSigningConfig does: every one of its inputs is optional. + */ + public CodeSigningConfig update(String region, String arn, String description, + CodeSigningConfig.AllowedPublishers allowedPublishers, + CodeSigningConfig.CodeSigningPolicies policies) { + CodeSigningConfig config = get(region, arn); + // Every member is validated before any is applied. The store hands back the live instance, + // so validating and setting in turn would leave an earlier member written when a later one + // is rejected, and the request would have changed the configuration while answering 400. + if (description != null) { + validateDescription(description); + } + if (allowedPublishers != null) { + validateAllowedPublishers(allowedPublishers); + } + if (policies != null) { + validatePolicies(policies); + } + if (description != null) { + config.setDescription(description); + } + if (allowedPublishers != null) { + config.setAllowedPublishers(allowedPublishers); + } + if (policies != null) { + config.setCodeSigningPolicies(policies); + } + config.setLastModified(now()); + store.put(key(region, config.getCodeSigningConfigId()), config); + return config; + } + + public void delete(String region, String arn) { + String id = idFromArn(arn); + if (store.get(key(region, id)).isEmpty()) { + throw notFound(arn); + } + store.delete(key(region, id)); + } + + public List list(String region) { + String prefix = "csc::" + region + "::"; + return store.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(CodeSigningConfig::getCodeSigningConfigId)) + .toList(); + } + + private static AwsException notFound(String arn) { + return new AwsException("ResourceNotFoundException", + "The code signing configuration " + arn + " does not exist.", 404); + } + + private static void validateDescription(String description) { + if (description != null && description.length() > MAX_DESCRIPTION) { + throw new AwsException("InvalidParameterValueException", + "Description must be at most " + MAX_DESCRIPTION + " characters.", 400); + } + } + + /** + * AllowedPublishers is required and carries between one and twenty signing profile ARNs. An + * empty list is refused rather than stored: a configuration that allows no publisher at all is + * not a shape the API accepts. + */ + private static void validateAllowedPublishers(CodeSigningConfig.AllowedPublishers publishers) { + List arns = publishers == null ? null : publishers.getSigningProfileVersionArns(); + if (arns == null || arns.isEmpty()) { + throw new AwsException("InvalidParameterValueException", + "AllowedPublishers must name at least one signing profile version ARN.", 400); + } + if (arns.size() > MAX_SIGNING_PROFILE_ARNS) { + throw new AwsException("InvalidParameterValueException", + "AllowedPublishers accepts at most " + MAX_SIGNING_PROFILE_ARNS + + " signing profile version ARNs.", 400); + } + } + + private static void validatePolicies(CodeSigningConfig.CodeSigningPolicies policies) { + if (policies == null) { + return; + } + String policy = policies.getUntrustedArtifactOnDeployment(); + if (policy != null && !POLICIES.contains(policy)) { + throw new AwsException("InvalidParameterValueException", + "UntrustedArtifactOnDeployment must be one of " + POLICIES + ".", 400); + } + if (policy == null) { + policies.setUntrustedArtifactOnDeployment(DEFAULT_UNTRUSTED_ARTIFACT_POLICY); + } + } + + private static CodeSigningConfig.CodeSigningPolicies defaultPolicies() { + CodeSigningConfig.CodeSigningPolicies policies = new CodeSigningConfig.CodeSigningPolicies(); + policies.setUntrustedArtifactOnDeployment(DEFAULT_UNTRUSTED_ARTIFACT_POLICY); + return policies; + } + + /** The trailing segment of a code-signing-config ARN, or the value itself when it is an id. */ + static String idFromArn(String arn) { + if (arn == null || arn.isBlank()) { + throw new AwsException("InvalidParameterValueException", + "CodeSigningConfigArn is required.", 400); + } + int colon = arn.lastIndexOf(':'); + return colon < 0 ? arn : arn.substring(colon + 1); + } + + private static String key(String region, String id) { + return "csc::" + region + "::" + id; + } + + private static String now() { + return LAST_MODIFIED.format(Instant.now()); + } + + private String randomId() { + StringBuilder id = new StringBuilder(ID_LENGTH); + for (int i = 0; i < ID_LENGTH; i++) { + id.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length()))); + } + return id.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/CodeSigningConfig.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/CodeSigningConfig.java new file mode 100644 index 0000000000..fad399fca0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/CodeSigningConfig.java @@ -0,0 +1,69 @@ +package io.github.hectorvent.floci.services.lambda.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.ArrayList; +import java.util.List; + +/** A Lambda code signing configuration, as CreateCodeSigningConfig returns it. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CodeSigningConfig { + + @JsonProperty("CodeSigningConfigId") + private String codeSigningConfigId; + + @JsonProperty("CodeSigningConfigArn") + private String codeSigningConfigArn; + + @JsonProperty("Description") + private String description; + + @JsonProperty("AllowedPublishers") + private AllowedPublishers allowedPublishers; + + @JsonProperty("CodeSigningPolicies") + private CodeSigningPolicies codeSigningPolicies; + + @JsonProperty("LastModified") + private String lastModified; + + public String getCodeSigningConfigId() { return codeSigningConfigId; } + public void setCodeSigningConfigId(String codeSigningConfigId) { this.codeSigningConfigId = codeSigningConfigId; } + public String getCodeSigningConfigArn() { return codeSigningConfigArn; } + public void setCodeSigningConfigArn(String codeSigningConfigArn) { this.codeSigningConfigArn = codeSigningConfigArn; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public AllowedPublishers getAllowedPublishers() { return allowedPublishers; } + public void setAllowedPublishers(AllowedPublishers allowedPublishers) { this.allowedPublishers = allowedPublishers; } + public CodeSigningPolicies getCodeSigningPolicies() { return codeSigningPolicies; } + public void setCodeSigningPolicies(CodeSigningPolicies codeSigningPolicies) { this.codeSigningPolicies = codeSigningPolicies; } + public String getLastModified() { return lastModified; } + public void setLastModified(String lastModified) { this.lastModified = lastModified; } + + @RegisterForReflection + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class AllowedPublishers { + @JsonProperty("SigningProfileVersionArns") + private List signingProfileVersionArns = new ArrayList<>(); + + public List getSigningProfileVersionArns() { return signingProfileVersionArns; } + public void setSigningProfileVersionArns(List signingProfileVersionArns) { + this.signingProfileVersionArns = signingProfileVersionArns; + } + } + + @RegisterForReflection + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class CodeSigningPolicies { + @JsonProperty("UntrustedArtifactOnDeployment") + private String untrustedArtifactOnDeployment; + + public String getUntrustedArtifactOnDeployment() { return untrustedArtifactOnDeployment; } + public void setUntrustedArtifactOnDeployment(String untrustedArtifactOnDeployment) { + this.untrustedArtifactOnDeployment = untrustedArtifactOnDeployment; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java new file mode 100644 index 0000000000..c34cef124c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaCodeSigningConfigLifecycleIntegrationTest.java @@ -0,0 +1,158 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.matchesRegex; +import static org.hamcrest.Matchers.nullValue; + +/** Create, Get, Update, Delete and List for a code signing configuration. */ +@QuarkusTest +class LambdaCodeSigningConfigLifecycleIntegrationTest { + + private static final String BASE = "/2020-04-22/code-signing-configs"; + private static final String PROFILE = + "arn:aws:signer:us-east-1:000000000000:/signing-profiles/prof/AbCdEfGhIj"; + + private static String create(String body) { + return given().contentType("application/json").body(body) + .when().post(BASE) + .then().statusCode(201) + .extract().path("CodeSigningConfig.CodeSigningConfigArn"); + } + + @Test + void createReportsTheModelsIdAndArnShapeAndDefaultsThePolicy() { + given() + .contentType("application/json") + .body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"Description\":\"release artifacts\"}") + .when() + .post(BASE) + .then() + .statusCode(201) + .body("CodeSigningConfig.CodeSigningConfigId", matchesRegex("csc-[a-z0-9]{17}")) + .body("CodeSigningConfig.CodeSigningConfigArn", + matchesRegex("arn:aws:lambda:us-east-1:\\d{12}:code-signing-config:csc-[a-z0-9]{17}")) + .body("CodeSigningConfig.Description", is("release artifacts")) + .body("CodeSigningConfig.AllowedPublishers.SigningProfileVersionArns", contains(PROFILE)) + // The model documents Warn as the default when the request names no policy. + .body("CodeSigningConfig.CodeSigningPolicies.UntrustedArtifactOnDeployment", is("Warn")) + .body("CodeSigningConfig.LastModified", + matchesRegex("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z")); + } + + @Test + void getReadsBackWhatCreateStored() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"CodeSigningPolicies\":{\"UntrustedArtifactOnDeployment\":\"Enforce\"}}"); + + given().when().get(BASE + "/" + arn).then() + .statusCode(200) + .body("CodeSigningConfig.CodeSigningConfigArn", is(arn)) + .body("CodeSigningConfig.CodeSigningPolicies.UntrustedArtifactOnDeployment", is("Enforce")); + } + + @Test + void updateAppliesOnlyTheMembersTheRequestNames() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"Description\":\"first\"}"); + + // Description alone. AllowedPublishers is omitted and must survive. + given().contentType("application/json").body("{\"Description\":\"second\"}") + .when().put(BASE + "/" + arn) + .then().statusCode(200) + .body("CodeSigningConfig.Description", is("second")) + .body("CodeSigningConfig.AllowedPublishers.SigningProfileVersionArns", contains(PROFILE)); + } + + @Test + void aRejectedUpdateChangesNothing() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"Description\":\"before\"}"); + + // Valid Description, invalid AllowedPublishers. The description must not survive the 400. + given().contentType("application/json") + .body("{\"Description\":\"after\",\"AllowedPublishers\":{\"SigningProfileVersionArns\":[]}}") + .when().put(BASE + "/" + arn) + .then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + + given().when().get(BASE + "/" + arn).then() + .statusCode(200) + .body("CodeSigningConfig.Description", is("before")); + + // The same shape with the policy as the rejected member. + given().contentType("application/json") + .body("{\"Description\":\"after\"," + + "\"CodeSigningPolicies\":{\"UntrustedArtifactOnDeployment\":\"Ignore\"}}") + .when().put(BASE + "/" + arn) + .then().statusCode(400); + + given().when().get(BASE + "/" + arn).then() + .statusCode(200) + .body("CodeSigningConfig.Description", is("before")); + } + + @Test + void listReturnsTheConfigsAndDeleteRemovesOne() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}}"); + + given().when().get(BASE).then().statusCode(200) + .body("CodeSigningConfigs.CodeSigningConfigArn", hasItem(arn)); + + given().when().delete(BASE + "/" + arn).then().statusCode(204); + given().when().get(BASE + "/" + arn).then().statusCode(404) + .body("__type", is("ResourceNotFoundException")); + given().when().delete(BASE + "/" + arn).then().statusCode(404); + } + + @Test + void anUnknownConfigIsNotFoundAndAKnownOneListsNoFunctions() { + String arn = create("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}}"); + + // A config now exists, so the functions route reports an empty attachment list rather than + // the 404 it had to give when no config could exist at all. + given().when().get(BASE + "/" + arn + "/functions").then() + .statusCode(200) + .body("FunctionArns", is(List.of())) + .body("NextMarker", nullValue()); + + String missing = "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-abcdefghij1234567"; + given().when().get(BASE + "/" + missing + "/functions").then().statusCode(404); + } + + @Test + void allowedPublishersIsRequiredAndBounded() { + given().contentType("application/json").body("{\"Description\":\"no publishers\"}") + .when().post(BASE).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + + given().contentType("application/json") + .body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[]}}") + .when().post(BASE).then().statusCode(400); + + StringBuilder many = new StringBuilder(); + for (int i = 0; i < 21; i++) { + many.append(i > 0 ? "," : "").append('"').append(PROFILE).append('"'); + } + given().contentType("application/json") + .body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[" + many + "]}}") + .when().post(BASE).then().statusCode(400); + } + + @Test + void anUnmodelledPolicyValueIsRejected() { + given().contentType("application/json") + .body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}," + + "\"CodeSigningPolicies\":{\"UntrustedArtifactOnDeployment\":\"Ignore\"}}") + .when().post(BASE).then().statusCode(400) + .body("__type", is("InvalidParameterValueException")); + } +}