fix(lambda): attach code signing configs to functions (#6857)

* feat(lambda): attach code signing configs to functions

* fix(lambda): align code-signing IAM function names

* fix(lambda): preserve code-signing config on CreateFunction

* fix(lambda): align code-signing attachment response paths
This commit is contained in:
Jimmy Liu Jia authored and GitHub committed 2026-10-28 23:00:50 -04:00
1 parent 407ac4e210
commit 5ffe6d1123
21 files changed
+1448 -105

No files matched your search

@@ -0,0 +1,97 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.CreateCodeSigningConfigResponse;
import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse;
import software.amazon.awssdk.services.lambda.model.FunctionCode;
import software.amazon.awssdk.services.lambda.model.GetFunctionCodeSigningConfigResponse;
import software.amazon.awssdk.services.lambda.model.ListFunctionsByCodeSigningConfigResponse;
import software.amazon.awssdk.services.lambda.model.PutFunctionCodeSigningConfigResponse;
import software.amazon.awssdk.services.lambda.model.ResourceConflictException;
import software.amazon.awssdk.services.lambda.model.Runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Lambda - code signing attachment lifecycle through AWS SDK v2")
class LambdaCodeSigningAttachmentSdkTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String ROLE = TestFixtures.globalArn("iam", ACCOUNT_ID, "role/lambda-role");
private static final String PROFILE = TestFixtures.arn("signer", ACCOUNT_ID,
"/signing-profiles/prof/AbCdEfGhIj");
@Test
void createAttachReadListDetachAndDelete() {
String functionName = TestFixtures.uniqueName("sdk-code-signing");
try (LambdaClient lambda = TestFixtures.lambdaClient()) {
String configArn = null;
boolean functionCreated = false;
try {
CreateCodeSigningConfigResponse createdConfig = lambda.createCodeSigningConfig(request -> request
.description("SDK lifecycle")
.allowedPublishers(publishers -> publishers.signingProfileVersionArns(PROFILE)));
configArn = createdConfig.codeSigningConfig().codeSigningConfigArn();
String createdConfigArn = configArn;
assertThat(configArn).startsWith(TestFixtures.arn("lambda", ACCOUNT_ID,
"code-signing-config:csc-"));
assertThat(lambda.getCodeSigningConfig(request -> request.codeSigningConfigArn(createdConfigArn))
.codeSigningConfig().allowedPublishers().signingProfileVersionArns())
.containsExactly(PROFILE);
CreateFunctionResponse createdFunction = lambda.createFunction(CreateFunctionRequest.builder()
.functionName(functionName)
.runtime(Runtime.NODEJS20_X)
.role(ROLE)
.handler("index.handler")
.code(FunctionCode.builder()
.zipFile(SdkBytes.fromByteArray(LambdaUtils.minimalZip()))
.build())
.build());
functionCreated = true;
PutFunctionCodeSigningConfigResponse attached = lambda.putFunctionCodeSigningConfig(request -> request
.functionName(functionName).codeSigningConfigArn(createdConfigArn));
assertThat(attached.functionName()).isEqualTo(functionName);
assertThat(attached.codeSigningConfigArn()).isEqualTo(configArn);
GetFunctionCodeSigningConfigResponse read = lambda.getFunctionCodeSigningConfig(
request -> request.functionName(functionName));
assertThat(read.functionName()).isEqualTo(functionName);
assertThat(read.codeSigningConfigArn()).isEqualTo(configArn);
ListFunctionsByCodeSigningConfigResponse listed = lambda.listFunctionsByCodeSigningConfig(
request -> request.codeSigningConfigArn(createdConfigArn).maxItems(1));
assertThat(listed.functionArns()).containsExactly(createdFunction.functionArn());
assertThat(listed.nextMarker()).isNull();
assertThatThrownBy(() -> lambda.deleteCodeSigningConfig(
request -> request.codeSigningConfigArn(createdConfigArn)))
.isInstanceOf(ResourceConflictException.class);
lambda.deleteFunctionCodeSigningConfig(request -> request.functionName(functionName));
assertThat(lambda.getFunctionCodeSigningConfig(request -> request.functionName(functionName))
.codeSigningConfigArn()).isNullOrEmpty();
assertThat(lambda.listFunctionsByCodeSigningConfig(request -> request.codeSigningConfigArn(createdConfigArn))
.functionArns()).isEmpty();
lambda.deleteCodeSigningConfig(request -> request.codeSigningConfigArn(createdConfigArn));
configArn = null;
} finally {
try {
if (functionCreated) {
lambda.deleteFunction(request -> request.functionName(functionName));
}
} finally {
if (configArn != null) {
String remainingConfigArn = configArn;
lambda.deleteCodeSigningConfig(request -> request.codeSigningConfigArn(remainingConfigArn));
}
}
}
}
}
}
+12 -9
View File
@@ -32,8 +32,10 @@ Floci Lambda runs your function code locally inside real Docker containers - clo
| `AddPermission` | Add a resource-policy statement |
| `GetPolicy` | Get the function resource policy |
| `RemovePermission` | Remove a resource-policy statement |
| `GetFunctionCodeSigningConfig` | Return code-signing config (always empty) |
| `ListFunctionsByCodeSigningConfig` | List functions carrying a config. Always empty, since nothing can attach one |
| `GetFunctionCodeSigningConfig` | Return the code-signing config attached to `$LATEST` (or an empty ARN) |
| `PutFunctionCodeSigningConfig` | Attach or replace a code-signing config on `$LATEST` |
| `DeleteFunctionCodeSigningConfig` | Detach the code-signing config from `$LATEST` |
| `ListFunctionsByCodeSigningConfig` | List functions carrying a config, with marker pagination |
| `CreateCodeSigningConfig` | Create a code signing configuration |
| `GetCodeSigningConfig` | Read a code signing configuration |
| `UpdateCodeSigningConfig` | Update the members the request names |
@@ -586,13 +588,14 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or
- Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`)
- `InvokeWithResponseStream`
- 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
Code signing enforcement is not emulated: an attached configuration never gates a deployment.
The attachment lifecycle is supported for `$LATEST`: `PutFunctionCodeSigningConfig` attaches or
replaces a configuration, `GetFunctionCodeSigningConfig` reads it,
`DeleteFunctionCodeSigningConfig` detaches it, and `ListFunctionsByCodeSigningConfig` returns
attached functions with marker pagination. An unknown configuration is
`ResourceNotFoundException`; a malformed ARN or out-of-range `MaxItems` is rejected with
`InvalidParameterValueException` first.
## Configuration
@@ -895,6 +895,9 @@ public class ResourceArnBuilder {
if (name == null) {
return createdFunctionArn(path, ctx, region, accountId);
}
if (path.endsWith("/code-signing-config")) {
return codeSigningFunctionArn(name, region, accountId);
}
boolean qualifiedTarget = path.endsWith("/functions/" + name + "/invocations")
|| path.endsWith("/functions/" + name + "/response-streaming-invocations")
|| path.endsWith("/functions/" + name + "/provisioned-concurrency");
@@ -922,6 +925,17 @@ public class ResourceArnBuilder {
}
}
/** Code-signing attachment routes use Lambda's broader NamespacedFunctionName shape. */
private static String codeSigningFunctionArn(String name, String region, String accountId) {
try {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolveNamespacedFunctionName(name);
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + ref.name()).toString();
} catch (AwsException e) {
// A reference Lambda refuses, which its handler answers with a 400 before acting on anything.
return AwsArnUtils.Arn.of("lambda", region, accountId, "function:" + name).toString();
}
}
/**
* The function {@code CreateFunction} makes, which its body names, in the caller's account and Region, as
* every route but an invoke acts there: the Service Reference gives it the {@code function} resource, so
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
@@ -24,6 +25,11 @@ public final class LambdaArnUtils {
private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_]+");
private static final int MAX_NAME_LENGTH = 64;
private static final int MAX_TOTAL_LENGTH = 140;
/** The NamespacedFunctionName shape used by Lambda's attachment and mapping APIs. */
public static final Pattern NAMESPACED_FUNCTION_NAME_PATTERN = Pattern.compile(
"^(arn:(aws[a-zA-Z-]*)?:lambda:)?(?<region>(eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}:)?"
+ "(?<account>\\d{12}:)?(function:)?(?<name>[a-zA-Z0-9-_\\.]+)"
+ "(?::(?<qualifier>\\$LATEST(\\.PUBLISHED)?|[a-zA-Z0-9-_]+))?$");
/** The model's {@code FunctionName} pattern, quoted in the ValidationException a bad name gets. */
private static final String NAME_REGEX = "(arn:(aws[a-zA-Z-]*)?:lambda:)?"
+ "((eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}:)?"
@@ -91,6 +97,50 @@ public final class LambdaArnUtils {
*/
public record ResolvedFunctionRef(String name, String qualifier, String region, String account) {}
/**
* Parses Lambda's broader {@code NamespacedFunctionName} shape. Unlike {@link #resolve}, this
* accepts dotted names, optional region/account prefixes without {@code function:}, and the
* {@code function:NAME} namespace used by the code-signing attachment APIs.
*/
public static ResolvedFunctionRef resolveNamespacedFunctionName(String input) {
if (input == null || input.isEmpty() || input.length() > 256) {
throw namespacedValidationFailure(input);
}
Matcher matcher = NAMESPACED_FUNCTION_NAME_PATTERN.matcher(input);
if (!matcher.matches()) {
throw namespacedValidationFailure(input);
}
if (matcher.group(1) != null) {
if (!AwsArnUtils.isArn(input)) {
throw invalid("Invalid ARN: " + input);
}
AwsArnUtils.Arn arn;
try {
arn = AwsArnUtils.parse(input);
} catch (IllegalArgumentException e) {
throw invalid("Invalid ARN: " + input);
}
if (!"lambda".equals(arn.service())) {
throw invalid("Invalid ARN: " + input);
}
return new ResolvedFunctionRef(matcher.group("name"), matcher.group("qualifier"),
arn.region(), arn.accountId());
}
return new ResolvedFunctionRef(matcher.group("name"), matcher.group("qualifier"),
stripTrailingColon(matcher.group("region")), stripTrailingColon(matcher.group("account")));
}
private static String stripTrailingColon(String value) {
return value == null ? null : value.substring(0, value.length() - 1);
}
private static AwsException namespacedValidationFailure(String input) {
return SmithyValidationErrors.validationException(
"Value '" + input + "' at 'functionName' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: "
+ NAMESPACED_FUNCTION_NAME_PATTERN.pattern());
}
/**
* Parses a {@code FunctionName} path parameter. Throws {@link AwsException}, HTTP 400,
* on any malformed input: {@code ValidationException} when the name fails the
@@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
@@ -23,8 +22,6 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import java.util.regex.Pattern;
/**
* The code signing configuration resource, all under /2020-04-22/code-signing-configs.
*
@@ -35,11 +32,9 @@ import java.util.regex.Pattern;
* instead of matching here.</p>
*
* <p>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.</p>
* ListFunctionsByCodeSigningConfig derives its results from the function records carrying the
* configuration ARN. 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.</p>
*
* <p>Nothing here verifies a signature. Lambda's own code signing checks are not emulated, so a
* configuration never gates a deployment.</p>
@@ -49,29 +44,21 @@ import java.util.regex.Pattern;
@Consumes(MediaType.APPLICATION_JSON)
public class LambdaCodeSigningConfigFunctionsController {
/**
* botocore's {@code CodeSigningConfigArn} shape pattern, verbatim. Applied with
* {@link String#matches(String)} so it is anchored whole-string, which is the
* right semantics for an ARN; the shape's {@code max: 200} is checked separately
* because the pattern itself does not bound the partition suffix.
*/
private static final Pattern CODE_SIGNING_CONFIG_ARN = Pattern.compile(
"arn:(aws[a-zA-Z-]*)?:lambda:(eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}"
+ ":\\d{12}:code-signing-config:csc-[a-z0-9]{17}");
private static final int ARN_MAX_LENGTH = 200;
private static final int MAX_ITEMS_MIN = 1;
private static final int MAX_ITEMS_MAX = 10000;
private final LambdaCodeSigningConfigService service;
private final LambdaService lambdaService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public LambdaCodeSigningConfigFunctionsController(LambdaCodeSigningConfigService service,
LambdaService lambdaService,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.lambdaService = lambdaService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@@ -88,15 +75,19 @@ public class LambdaCodeSigningConfigFunctionsController {
@PathParam("codeSigningConfigArn") String codeSigningConfigArn,
@QueryParam("Marker") String marker,
@QueryParam("MaxItems") String maxItems) {
requireValidArn(codeSigningConfigArn);
parseMaxItems(maxItems);
// 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);
LambdaCodeSigningConfigService.validateArn(codeSigningConfigArn);
Integer requested = maxItems == null || maxItems.isBlank() ? null : parseMaxItems(maxItems);
String region = regionResolver.resolveRegion(headers);
String accountId = regionResolver.getAccountId();
service.get(region, accountId, codeSigningConfigArn);
PaginatedResult<String> page = lambdaService.listFunctionsByCodeSigningConfig(
region, accountId, codeSigningConfigArn, requested, marker);
ObjectNode root = objectMapper.createObjectNode();
root.putArray("FunctionArns");
root.set("FunctionArns", objectMapper.valueToTree(page.items()));
if (page.nextToken() != null) {
root.put("NextMarker", page.nextToken());
}
return Response.ok(root).build();
}
@@ -113,8 +104,9 @@ public class LambdaCodeSigningConfigFunctionsController {
@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();
LambdaCodeSigningConfigService.validateArn(codeSigningConfigArn);
String region = regionResolver.resolveRegion(headers);
return Response.ok(wrap(service.get(region, regionResolver.getAccountId(), codeSigningConfigArn))).build();
}
@PUT
@@ -122,19 +114,34 @@ public class LambdaCodeSigningConfigFunctionsController {
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();
LambdaCodeSigningConfigService.validateArn(codeSigningConfigArn);
String region = regionResolver.resolveRegion(headers);
return service.withConfigLock(codeSigningConfigArn, () -> {
service.get(region, regionResolver.getAccountId(), codeSigningConfigArn);
CodeSigningConfig config = service.update(region, 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();
LambdaCodeSigningConfigService.validateArn(codeSigningConfigArn);
String region = regionResolver.resolveRegion(headers);
String accountId = regionResolver.getAccountId();
return service.withConfigLock(codeSigningConfigArn, () -> {
service.get(region, accountId, codeSigningConfigArn);
PaginatedResult<String> 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();
});
}
@GET
@@ -180,17 +187,6 @@ public class LambdaCodeSigningConfigFunctionsController {
CodeSigningConfig.CodeSigningPolicies.class);
}
private void requireValidArn(String arn) {
if (arn == null || arn.isBlank()
|| arn.length() > ARN_MAX_LENGTH
|| !CODE_SIGNING_CONFIG_ARN.matcher(arn).matches()) {
throw SmithyValidationErrors.exception("InvalidParameterValueException",
"Value '" + arn + "' at 'codeSigningConfigArn' "
+ "failed to satisfy constraint: Member must satisfy regular expression pattern: "
+ CODE_SIGNING_CONFIG_ARN.pattern());
}
}
private int parseMaxItems(String maxItems) {
if (maxItems == null || maxItems.isBlank()) {
return MAX_ITEMS_MAX;
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SignedMarkers;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
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;
@@ -16,9 +17,12 @@ import java.security.SecureRandom;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
* Code signing configurations, the resource CreateCodeSigningConfig manages.
@@ -40,6 +44,10 @@ public class LambdaCodeSigningConfigService {
private static final int MAX_DESCRIPTION = 256;
private static final int MAX_SIGNING_PROFILE_ARNS = 20;
private static final int LIST_PAGE_SIZE = 10000;
private static final Pattern CODE_SIGNING_CONFIG_ARN = Pattern.compile(
"arn:(aws[a-zA-Z-]*)?:lambda:(eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}"
+ ":\\d{12}:code-signing-config:csc-[a-z0-9]{17}");
private static final int ARN_MAX_LENGTH = 200;
/** The model documents Warn as the default when the request names no policy. */
static final String DEFAULT_UNTRUSTED_ARTIFACT_POLICY = "Warn";
@@ -52,12 +60,21 @@ public class LambdaCodeSigningConfigService {
private final RegionResolver regionResolver;
private final SignedMarkers markers = new SignedMarkers();
private final SecureRandom random = new SecureRandom();
private final Object[] configLocks = new Object[64];
@Inject
public LambdaCodeSigningConfigService(StorageFactory storageFactory, RegionResolver regionResolver) {
this.regionResolver = regionResolver;
this.store = storageFactory.create("lambda", "lambda-code-signing-configs.json",
new TypeReference<Map<String, CodeSigningConfig>>() {});
Arrays.setAll(configLocks, ignored -> new Object());
}
/** Serializes attachment and config deletion so neither can commit against stale state. */
public <T> T withConfigLock(String arn, Supplier<T> operation) {
synchronized (configLocks[Math.floorMod(arn.hashCode(), configLocks.length)]) {
return operation.get();
}
}
public CodeSigningConfig create(String region, String accountId, String description,
@@ -85,6 +102,38 @@ public class LambdaCodeSigningConfigService {
.orElseThrow(() -> notFound(arn));
}
/**
* Resolves a configuration for an API request and rejects an ARN from another account or
* region, even when its trailing id happens to match a local record.
*/
public CodeSigningConfig get(String region, String accountId, String arn) {
CodeSigningConfig config = get(region, arn);
AwsArnUtils.Arn requested = AwsArnUtils.parse(arn);
if (!region.equals(requested.region())
|| !accountId.equals(requested.accountId())
|| !arn.equals(config.getCodeSigningConfigArn())) {
throw notFound(arn);
}
return config;
}
/**
* Validates and resolves a configuration named by a function attachment request. The Lambda
* APIs use a distinct error code when the requested configuration does not exist, while the
* configuration resource APIs keep {@code ResourceNotFoundException}.
*/
public CodeSigningConfig requireForAttachment(String region, String accountId, String arn) {
validateArn(arn);
try {
return get(region, accountId, arn);
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
throw new AwsException("CodeSigningConfigNotFoundException", e.getMessage(), 404);
}
}
/**
* 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.
@@ -200,6 +249,15 @@ public class LambdaCodeSigningConfigService {
return colon < 0 ? arn : arn.substring(colon + 1);
}
static void validateArn(String arn) {
if (arn == null || arn.isBlank()
|| arn.length() > ARN_MAX_LENGTH
|| !CODE_SIGNING_CONFIG_ARN.matcher(arn).matches()) {
throw SmithyValidationErrors.exception("InvalidParameterValueException",
SmithyValidationErrors.pattern("codeSigningConfigArn", arn, CODE_SIGNING_CONFIG_ARN.pattern()));
}
}
private static String key(String region, String id) {
return "csc::" + region + "::" + id;
}
@@ -6,7 +6,9 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
@@ -18,13 +20,11 @@ import jakarta.ws.rs.core.Response;
/**
* Lambda code-signing endpoints — use the /2020-06-30 API version prefix.
*
* GetFunctionCodeSigningConfig: GET /2020-06-30/functions/{FunctionName}/code-signing-config
* GET, PUT and DELETE /2020-06-30/functions/{FunctionName}/code-signing-config manage the
* function's code-signing attachment.
*
* Floci does not implement code signing config management, so this always returns
* an empty CodeSigningConfigArn for existing functions (matching real AWS behaviour
* when no signing config is attached). Non-existent functions surface a 404 via
* LambdaService, unblocking Terraform and other tools that call this endpoint as
* part of their normal Lambda resource lifecycle.
* The attachment is stored on the function's {@code $LATEST} record. Lambda's code-signing
* enforcement is not emulated, but the attachment lifecycle and readback are supported.
*
* The class-level prefix matters: without it, requests here fall through to a more
* general catch-all route elsewhere (S3's bucket-path matcher) instead of this
@@ -37,14 +37,17 @@ 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;
}
@@ -54,11 +57,41 @@ public class LambdaCodeSigningController {
public Response getFunctionCodeSigningConfig(@Context HttpHeaders headers,
@PathParam("functionName") String functionName) {
String region = regionResolver.resolveRegion(headers);
LambdaFunction fn = lambdaService.getFunction(region, functionName);
LambdaFunction fn = lambdaService.getFunctionForCodeSigningConfig(region, functionName);
ObjectNode root = objectMapper.createObjectNode();
root.put("CodeSigningConfigArn", "");
root.put("CodeSigningConfigArn", fn.getCodeSigningConfigArn() == null
? "" : fn.getCodeSigningConfigArn());
root.put("FunctionName", fn.getFunctionName());
return Response.ok(root).build();
}
@PUT
@Path("/functions/{functionName}/code-signing-config")
public Response putFunctionCodeSigningConfig(@Context HttpHeaders headers,
@PathParam("functionName") String functionName,
ObjectNode body) {
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);
ObjectNode root = objectMapper.createObjectNode();
root.put("CodeSigningConfigArn", arn);
root.put("FunctionName", fn.getFunctionName());
return Response.ok(root).build();
});
}
@DELETE
@Path("/functions/{functionName}/code-signing-config")
public Response deleteFunctionCodeSigningConfig(@Context HttpHeaders headers,
@PathParam("functionName") String functionName) {
String region = regionResolver.resolveRegion(headers);
lambdaService.deleteFunctionCodeSigningConfig(region, functionName);
return Response.noContent().build();
}
}
@@ -227,22 +227,6 @@ public class LambdaController {
return Response.noContent().build();
}
// ──────────────────────────── GetFunctionCodeSigningConfig ────────────────────────────
@GET
@Path("/functions/{functionName}/code-signing-config")
public Response getFunctionCodeSigningConfig(@Context HttpHeaders headers,
@PathParam("functionName") String functionName) {
String region = regionResolver.resolveRegion(headers);
// Verify the function exists
lambdaService.getFunction(region, functionName);
// Return empty code signing config — floci does not enforce code signing
ObjectNode root = objectMapper.createObjectNode();
root.put("CodeSigningConfigArn", "");
root.put("FunctionName", functionName);
return Response.ok(root).build();
}
// ──────────────────────────── Invoke ────────────────────────────
private static final int SYNC_REQUEST_LIMIT = 6 * 1024 * 1024;
@@ -146,6 +146,18 @@ public class LambdaFunctionStore implements Resettable {
return backend.scan(key -> key.startsWith(prefix) && key.endsWith("::$LATEST"));
}
/** Lists the caller's {@code $LATEST} functions without relying on request context. */
public List<LambdaFunction> listForAccount(String accountId, String region) {
String prefix = "lambda::" + region + "::";
if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
return aware.scanForAccount(accountId,
key -> key.startsWith(prefix) && key.endsWith("::$LATEST"));
}
return list(region).stream()
.filter(function -> belongsToAccount(function, accountId))
.toList();
}
public List<LambdaFunction> listVersions(String region, String functionName) {
String prefix = "lambda::" + region + "::" + functionName + "::";
List<LambdaFunction> versions = new ArrayList<>(backend.scan(key -> key.startsWith(prefix)));
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CustomResourceLiveness;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.SignedMarkers;
@@ -138,9 +139,8 @@ public class LambdaService implements ResourceProvider {
private static final Pattern FUNCTION_URL_QUALIFIER_PATTERN = Pattern.compile("^(?!^\\d+$)[0-9a-zA-Z-_]+$");
private static final Pattern EVENT_SOURCE_ARN_PATTERN = Pattern.compile(
"^arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9-])+:((eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)$");
private static final Pattern LIST_ESM_FUNCTION_NAME_PATTERN = Pattern.compile(
"^(arn:(aws[a-zA-Z-]*)?:lambda:)?((eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{1}:)?(\\d{12}:)?"
+ "(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST(\\.PUBLISHED)?|[a-zA-Z0-9-_]+))?$");
private static final Pattern LIST_ESM_FUNCTION_NAME_PATTERN =
LambdaArnUtils.NAMESPACED_FUNCTION_NAME_PATTERN;
// AddPermission members: botocore's PrincipalOrgID, SourceOwner and EventSourceToken shapes.
private static final Pattern PRINCIPAL_ORG_ID_PATTERN = Pattern.compile("o-[a-z0-9]{10,32}");
private static final Pattern ACCOUNT_ID_PATTERN = Pattern.compile("\\d{12}");
@@ -194,6 +194,7 @@ public class LambdaService implements ResourceProvider {
private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;
private final StorageFactory storageFactory;
private final LambdaLayerService layerService;
private final LambdaCodeSigningConfigService codeSigningConfigService;
private final Map<String, PendingReactiveSync> pendingReactiveSyncs = new ConcurrentHashMap<>();
private final Map<String, Integer> runningReactiveSyncs = new ConcurrentHashMap<>();
private final Map<String, String> failedReactiveSyncs = new ConcurrentHashMap<>();
@@ -207,6 +208,7 @@ public class LambdaService implements ResourceProvider {
private final ConcurrentHashMap<String, Object> policyMutationLocks = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Object> versionCounterLocks = new ConcurrentHashMap<>();
private final SignedMarkers listFunctionMarkers = new SignedMarkers();
private final SignedMarkers codeSigningFunctionMarkers = new SignedMarkers();
/**
* Package-private constructor for testing without CDI. Config defaults
@@ -262,32 +264,63 @@ public class LambdaService implements ResourceProvider {
this.ec2Service = null;
this.customResourceLiveness = null;
this.durableExecutionService = null;
this.codeSigningConfigService = storageFactory == null
? null : new LambdaCodeSigningConfigService(storageFactory, regionResolver);
this.objectMapper = new ObjectMapper();
}
LambdaService(LambdaFunctionStore functionStore,
LambdaExecutorService executorService,
LambdaConcurrencyLimiter concurrencyLimiter,
WarmPool warmPool,
CodeStore codeStore,
ZipExtractor zipExtractor,
EmulatorConfig config,
RegionResolver regionResolver,
EsmStore esmStore,
LambdaAliasStore aliasStore,
LambdaTargetResolver targetResolver,
S3Service s3Service,
SqsService sqsService,
SqsEventSourcePoller poller,
KinesisEventSourcePoller kinesisPoller,
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,
StorageFactory storageFactory,
LambdaLayerService layerService,
Ec2Service ec2Service,
CustomResourceLiveness customResourceLiveness,
DurableExecutionService durableExecutionService,
ObjectMapper objectMapper) {
this(functionStore, executorService, concurrencyLimiter, warmPool, codeStore, zipExtractor, config,
regionResolver, esmStore, aliasStore, targetResolver, s3Service, sqsService, poller,
kinesisPoller, dynamodbStreamsPoller, storageFactory, layerService, ec2Service,
customResourceLiveness, durableExecutionService, objectMapper, null);
}
@Inject
public LambdaService(LambdaFunctionStore functionStore,
LambdaExecutorService executorService,
LambdaConcurrencyLimiter concurrencyLimiter,
WarmPool warmPool,
CodeStore codeStore,
ZipExtractor zipExtractor,
EmulatorConfig config,
RegionResolver regionResolver,
EsmStore esmStore,
LambdaAliasStore aliasStore,
LambdaTargetResolver targetResolver,
S3Service s3Service,
SqsService sqsService,
SqsEventSourcePoller poller,
KinesisEventSourcePoller kinesisPoller,
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,
StorageFactory storageFactory,
LambdaLayerService layerService,
Ec2Service ec2Service,
CustomResourceLiveness customResourceLiveness,
DurableExecutionService durableExecutionService,
ObjectMapper objectMapper) {
LambdaExecutorService executorService,
LambdaConcurrencyLimiter concurrencyLimiter,
WarmPool warmPool,
CodeStore codeStore,
ZipExtractor zipExtractor,
EmulatorConfig config,
RegionResolver regionResolver,
EsmStore esmStore,
LambdaAliasStore aliasStore,
LambdaTargetResolver targetResolver,
S3Service s3Service,
SqsService sqsService,
SqsEventSourcePoller poller,
KinesisEventSourcePoller kinesisPoller,
DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller,
StorageFactory storageFactory,
LambdaLayerService layerService,
Ec2Service ec2Service,
CustomResourceLiveness customResourceLiveness,
DurableExecutionService durableExecutionService,
ObjectMapper objectMapper,
LambdaCodeSigningConfigService codeSigningConfigService) {
this.customResourceLiveness = customResourceLiveness;
this.durableExecutionService = durableExecutionService;
this.functionStore = functionStore;
@@ -309,6 +342,7 @@ public class LambdaService implements ResourceProvider {
this.storageFactory = storageFactory;
this.layerService = layerService;
this.ec2Service = ec2Service;
this.codeSigningConfigService = codeSigningConfigService;
this.objectMapper = objectMapper;
}
@@ -439,6 +473,22 @@ public class LambdaService implements ResourceProvider {
}
public LambdaFunction createFunction(String region, Map<String, Object> request) {
Object codeSigningConfigValue = request.get("CodeSigningConfigArn");
if (codeSigningConfigValue == null) {
return createFunctionInternal(region, request);
}
if (codeSigningConfigService == null) {
throw new IllegalStateException("Lambda code-signing configuration service is unavailable");
}
String codeSigningConfigArn = codeSigningConfigValue.toString();
// Keep the configuration alive until the function record is stored. DeleteCodeSigningConfig
// uses the same lock while checking attached functions, so a concurrent create cannot
// validate a configuration and then leave a dangling attachment after deletion.
return codeSigningConfigService.withConfigLock(codeSigningConfigArn,
() -> createFunctionInternal(region, request));
}
private LambdaFunction createFunctionInternal(String region, Map<String, Object> request) {
Map<String, Object> environment = structureMember(request, "Environment");
Map<String, String> environmentVariables = environmentVariables(environment);
Map<String, Object> ephemeralStorage = structureMember(request, "EphemeralStorage");
@@ -458,6 +508,8 @@ public class LambdaService implements ResourceProvider {
validateEnum(request.get("PackageType"), "packageType", List.of("Zip", "Image"));
String packageType = request.getOrDefault("PackageType", "Zip").toString();
String description = (String) request.get("Description");
String codeSigningConfigArn = request.get("CodeSigningConfigArn") == null
? null : request.get("CodeSigningConfigArn").toString();
DurableConfigRequest durable = durableConfigRequest(durableConfig);
int defaultTimeout = config != null ? config.services().lambda().defaultTimeoutSeconds() : 3;
if (durable != null) {
@@ -491,6 +543,13 @@ public class LambdaService implements ResourceProvider {
}
validateEnum(runtime, "runtime", RUNTIME_VALUES);
validateMaxLength(description, "description", 256);
if (codeSigningConfigArn != null) {
if (codeSigningConfigService == null) {
throw new IllegalStateException("Lambda code-signing configuration service is unavailable");
}
codeSigningConfigService.requireForAttachment(
region, regionResolver.getAccountId(), codeSigningConfigArn);
}
@SuppressWarnings("unchecked")
Map<String, String> tags = (Map<String, String>) request.get("Tags");
@@ -515,6 +574,7 @@ public class LambdaService implements ResourceProvider {
fn.setState("Active");
fn.setLastModified(System.currentTimeMillis());
fn.setRevisionId(UUID.randomUUID().toString());
fn.setCodeSigningConfigArn(codeSigningConfigArn);
// Handle environment variables
if (environment != null) {
@@ -624,6 +684,89 @@ public class LambdaService implements ResourceProvider {
"Function not found: " + functionName, 404));
}
/** Resolves the $LATEST record that owns the code-signing attachment. */
public LambdaFunction getFunctionForCodeSigningConfig(String region, String functionName) {
String name = codeSigningFunctionName(region, functionName);
Optional<LambdaFunction> function = functionStore.getForAccount(
regionResolver.getAccountId(), region, name);
return function.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"Function not found: " + functionName, 404));
}
private String codeSigningFunctionName(String region, String functionName) {
// Code-signing attachment APIs use botocore's NamespacedFunctionName
// (max 256, dots allowed), not the narrower shape used by other routes.
LambdaArnUtils.ResolvedFunctionRef reference =
LambdaArnUtils.resolveNamespacedFunctionName(functionName);
if (AwsArnUtils.isArn(functionName)) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(functionName);
if (!region.equals(arn.region())
|| !regionResolver.getAccountId().equals(arn.accountId())
|| !AwsRegions.partitionFor(region).equals(arn.partition())) {
throw new AwsException("ResourceNotFoundException", "Function not found: " + functionName, 404);
}
return reference.name();
}
// The shape matcher backtracks when a would-be prefix is actually a bare name or
// a qualified name (for example, "us-east-1:$LATEST").
if ((reference.region() != null && !region.equals(reference.region()))
|| (reference.account() != null && !regionResolver.getAccountId().equals(reference.account()))) {
throw new AwsException("ResourceNotFoundException", "Function not found: " + functionName, 404);
}
return reference.name();
}
/** Attaches or replaces a code-signing configuration on the function's {@code $LATEST}. */
public LambdaFunction putFunctionCodeSigningConfig(String region, String functionName,
String codeSigningConfigArn) {
return updateFunctionCodeSigningConfig(region, functionName, codeSigningConfigArn);
}
/** Removes a code-signing configuration from the function's {@code $LATEST}. */
public void deleteFunctionCodeSigningConfig(String region, String functionName) {
updateFunctionCodeSigningConfig(region, functionName, null);
}
private LambdaFunction updateFunctionCodeSigningConfig(String region, String functionName,
String codeSigningConfigArn) {
String name = codeSigningFunctionName(region, functionName);
String functionArn = regionResolver.buildArn("lambda", region, "function:" + name);
synchronized (lockForConcurrencyOp(functionArn)) {
LambdaFunction function = getFunctionForCodeSigningConfig(region, functionName);
function.setAccountId(regionResolver.getAccountId());
function.setCodeSigningConfigArn(codeSigningConfigArn);
function.setLastModified(System.currentTimeMillis());
function.setRevisionId(UUID.randomUUID().toString());
// The account-aware lookup may have migrated a legacy record whose model predates
// accountId. The lookup already proved ownership from the ARN, so keep the write in
// the caller's partition instead of falling back to the default account.
functionStore.saveForAccount(regionResolver.getAccountId(), region, function);
return function;
}
}
/** Lists the full function ARNs that use a configuration in the caller's account and region. */
public PaginatedResult<String> listFunctionsByCodeSigningConfig(String region, String accountId,
String codeSigningConfigArn,
Integer maxItems, String marker) {
if (maxItems != null && (maxItems < 1 || maxItems > 10_000)) {
throw new AwsException("InvalidParameterValueException",
"Value '" + maxItems + "' at 'maxItems' failed to satisfy constraint: "
+ "Member must be between 1 and 10000", 400);
}
String scope = accountId + "\n" + region + "\n" + codeSigningConfigArn + "\n";
List<String> functionArns = functionStore.listForAccount(accountId, region).stream()
.filter(function -> codeSigningConfigArn.equals(function.getCodeSigningConfigArn()))
.map(LambdaFunction::getFunctionArn)
.filter(Objects::nonNull)
.toList();
int limit = maxItems == null ? 50 : maxItems;
return Pagination.paginate(functionArns, value -> value, limit, marker,
codeSigningFunctionMarkers, scope,
ignored -> new AwsException("InvalidParameterValueException",
"Invalid pagination key.", 400));
}
public boolean functionExists(String region, String functionName) {
try {
// The qualifier-aware read resolves an embedded alias/version and enforces the ARN's
@@ -2453,6 +2596,7 @@ public class LambdaService implements ResourceProvider {
// point is that its bind-mounted directory tracks the developer's working tree.
snapshot.setCodeLocalPath(versionCodePath(region, fn, String.valueOf(version)));
snapshot.setCodeSha256(fn.getCodeSha256());
snapshot.setCodeSigningConfigArn(fn.getCodeSigningConfigArn());
snapshot.setS3Bucket(fn.getS3Bucket());
snapshot.setS3Key(fn.getS3Key());
snapshot.setHotReloadHostPath(fn.getHotReloadHostPath());
@@ -69,6 +69,8 @@ public class LambdaFunction {
private String logGroup;
private List<LambdaFileSystemConfig> fileSystemConfigs = new ArrayList<>();
private String codeSha256;
/** ARN of the code signing configuration attached to this function's $LATEST, if any. */
private String codeSigningConfigArn;
/** Non-null only for durable functions: AWS requires ExecutionTimeout whenever DurableConfig is given. */
private Integer durableExecutionTimeout;
private Integer durableRetentionPeriodInDays;
@@ -230,6 +232,11 @@ public class LambdaFunction {
public String getCodeSha256() { return codeSha256; }
public void setCodeSha256(String codeSha256) { this.codeSha256 = codeSha256; }
public String getCodeSigningConfigArn() { return codeSigningConfigArn; }
public void setCodeSigningConfigArn(String codeSigningConfigArn) {
this.codeSigningConfigArn = codeSigningConfigArn;
}
public Integer getDurableExecutionTimeout() { return durableExecutionTimeout; }
public void setDurableExecutionTimeout(Integer durableExecutionTimeout) {
this.durableExecutionTimeout = durableExecutionTimeout;
@@ -357,6 +357,19 @@ class IamRestRouteEnforcementIntegrationTest {
}
}
@Test
void lambdaCodeSigningNamespacedFunctionIsCheckedAgainstItsTarget() {
String user = user("route-lambda-code-signing-namespace");
String name = "route-protected-" + suffix();
String function = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:" + name;
String path = "/2020-06-30/functions/function:" + name + "/code-signing-config";
policy(user, allow("lambda:GetFunctionCodeSigningConfig", function + "-other"));
refused(send(user, "GET", path), "lambda:GetFunctionCodeSigningConfig");
policy(user, allow("lambda:GetFunctionCodeSigningConfig", function));
send(user, "GET", path).statusCode(not(403));
}
@Test
void lambdaMappingConfigAndLayerRoutesAreCheckedAgainstWhatTheyName() {
// A grant on the same resource in another account does not cover the caller's own.
@@ -1653,6 +1653,14 @@ class ResourceArnBuilderTest {
builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaCodeSigningUsesTheNamespacedFunctionTarget() {
when(uriInfo.getPath()).thenReturn(
"/2020-06-30/functions/function:protected/code-signing-config");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:protected",
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
}
@Test
void lambdaInvokeKeepsTheQualifierItRuns() {
when(uriInfo.getPath()).thenReturn(
@@ -57,6 +57,20 @@ class LambdaArnUtilsTest {
assertEquals(emptyToNull(expectedAccount), ref.account());
}
@Test
void resolveNamespacedFunctionNameUsesTheAttachmentTargetAcrossPrefixes() {
LambdaArnUtils.ResolvedFunctionRef namespaced =
LambdaArnUtils.resolveNamespacedFunctionName("function:protected:$LATEST");
assertEquals("protected", namespaced.name());
assertEquals("$LATEST", namespaced.qualifier());
LambdaArnUtils.ResolvedFunctionRef partial =
LambdaArnUtils.resolveNamespacedFunctionName("us-east-1:111111111111:protected");
assertEquals("protected", partial.name());
assertEquals("us-east-1", partial.region());
assertEquals("111111111111", partial.account());
}
@ParameterizedTest
@ValueSource(strings = {
"",
@@ -0,0 +1,295 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
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 {
private static final String REGION = "us-east-1";
private static final String CALLER_ACCOUNT = "111111111111";
private static final String ARN_ACCOUNT = "222222222222";
private static final String FUNCTION_NAME = "same-name";
private static final String CONFIG_ARN =
"arn:aws:lambda:us-east-1:111111111111:code-signing-config:csc-0123456789abcdef0";
@Test
void foreignFullArnCannotMutateSameNamedCallerFunction(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(CALLER_ACCOUNT, REGION, function(CALLER_ACCOUNT));
store.saveForAccount(ARN_ACCOUNT, REGION, function(ARN_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
String foreignArn = "arn:aws:lambda:" + REGION + ":" + ARN_ACCOUNT
+ ":function:" + FUNCTION_NAME;
AwsException putError = assertThrows(AwsException.class,
() -> service.putFunctionCodeSigningConfig(REGION, foreignArn, CONFIG_ARN));
assertEquals("ResourceNotFoundException", putError.getErrorCode());
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
assertNull(store.getForAccount(ARN_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
AwsException deleteError = assertThrows(AwsException.class,
() -> service.deleteFunctionCodeSigningConfig(REGION, foreignArn));
assertEquals("ResourceNotFoundException", deleteError.getErrorCode());
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
assertNull(store.getForAccount(ARN_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void foreignPartialArnCannotMutateSameNamedCallerFunction(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(CALLER_ACCOUNT, REGION, function(CALLER_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
String foreignArn = ARN_ACCOUNT + ":function:" + FUNCTION_NAME;
AwsException error = assertThrows(AwsException.class,
() -> service.putFunctionCodeSigningConfig(REGION, foreignArn, CONFIG_ARN));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void namespacedFunctionNameAcceptsAllPartialFormsForAttachmentLifecycle(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(CALLER_ACCOUNT, REGION, function(CALLER_ACCOUNT));
RegionResolver regions = new RegionResolver(REGION, CALLER_ACCOUNT);
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), regions);
LambdaCodeSigningController controller = new LambdaCodeSigningController(
service, mock(LambdaCodeSigningConfigService.class), regions, new ObjectMapper());
List<String> references = List.of(
REGION + ":" + CALLER_ACCOUNT + ":function:" + FUNCTION_NAME,
REGION + ":" + CALLER_ACCOUNT + ":" + FUNCTION_NAME,
REGION + ":function:" + FUNCTION_NAME,
REGION + ":" + FUNCTION_NAME,
CALLER_ACCOUNT + ":function:" + FUNCTION_NAME,
CALLER_ACCOUNT + ":" + FUNCTION_NAME,
"function:" + FUNCTION_NAME,
FUNCTION_NAME,
CALLER_ACCOUNT + ":function:" + FUNCTION_NAME + ":$LATEST");
for (String reference : references) {
service.putFunctionCodeSigningConfig(REGION, reference, CONFIG_ARN);
Response response = controller.getFunctionCodeSigningConfig(null, reference);
assertEquals(200, response.getStatus(), reference);
assertEquals(CONFIG_ARN, store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn(), reference);
service.deleteFunctionCodeSigningConfig(REGION, reference);
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn(), reference);
}
}
@Test
void namespacedFunctionNameAllowsFunctionAsTheFunctionName(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
LambdaFunction function = function(CALLER_ACCOUNT);
function.setFunctionName("function");
function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + CALLER_ACCOUNT
+ ":function:function");
store.saveForAccount(CALLER_ACCOUNT, REGION, function);
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
service.putFunctionCodeSigningConfig(REGION,
REGION + ":" + CALLER_ACCOUNT + ":function", CONFIG_ARN);
assertEquals(CONFIG_ARN, store.getForAccount(CALLER_ACCOUNT, REGION, "function")
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void namespacedFunctionNameKeepsPrefixShapedBareNames(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
for (String name : List.of(REGION, CALLER_ACCOUNT, "function")) {
LambdaFunction function = function(CALLER_ACCOUNT);
function.setFunctionName(name);
function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + CALLER_ACCOUNT + ":function:" + name);
store.saveForAccount(CALLER_ACCOUNT, REGION, function);
service.putFunctionCodeSigningConfig(REGION, name, CONFIG_ARN);
assertEquals(CONFIG_ARN, service.getFunctionForCodeSigningConfig(REGION, name + ":$LATEST")
.getCodeSigningConfigArn(), name);
service.deleteFunctionCodeSigningConfig(REGION, name + ":$LATEST");
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, name)
.orElseThrow().getCodeSigningConfigArn(), name);
}
}
@Test
void foreignPartitionArnCannotSelectCallerFunction(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(CALLER_ACCOUNT, REGION, function(CALLER_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
String foreignArn = "arn:aws-us-gov:lambda:" + REGION + ":" + CALLER_ACCOUNT
+ ":function:" + FUNCTION_NAME;
AwsException error = assertThrows(AwsException.class,
() -> service.putFunctionCodeSigningConfig(REGION, foreignArn, CONFIG_ARN));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void foreignPartialRegionAndAccountReferencesCannotMutateCallerFunction(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(CALLER_ACCOUNT, REGION, function(CALLER_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
List<String> references = List.of(
"us-west-2:" + CALLER_ACCOUNT + ":function:" + FUNCTION_NAME,
"us-west-2:" + CALLER_ACCOUNT + ":" + FUNCTION_NAME,
"us-west-2:function:" + FUNCTION_NAME,
"us-west-2:" + FUNCTION_NAME,
ARN_ACCOUNT + ":function:" + FUNCTION_NAME,
ARN_ACCOUNT + ":" + FUNCTION_NAME,
REGION + ":" + ARN_ACCOUNT + ":function:" + FUNCTION_NAME,
REGION + ":" + ARN_ACCOUNT + ":" + FUNCTION_NAME);
for (String reference : references) {
AwsException error = assertThrows(AwsException.class,
() -> service.putFunctionCodeSigningConfig(REGION, reference, CONFIG_ARN), reference);
assertEquals("ResourceNotFoundException", error.getErrorCode(), reference);
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn(), reference);
}
}
@Test
void foreignFullArnCannotReadCodeSigningConfigThroughController(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
LambdaFunction callerFunction = function(CALLER_ACCOUNT);
callerFunction.setCodeSigningConfigArn(CONFIG_ARN);
store.saveForAccount(CALLER_ACCOUNT, REGION, callerFunction);
RegionResolver regions = new RegionResolver(REGION, CALLER_ACCOUNT);
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), regions);
ObjectMapper mapper = new ObjectMapper();
LambdaCodeSigningController controller = new LambdaCodeSigningController(
service, mock(LambdaCodeSigningConfigService.class), regions, mapper);
String foreignArn = "arn:aws:lambda:" + REGION + ":" + ARN_ACCOUNT
+ ":function:" + FUNCTION_NAME;
AwsException error = assertThrows(AwsException.class,
() -> controller.getFunctionCodeSigningConfig(null, foreignArn));
assertEquals("ResourceNotFoundException", error.getErrorCode());
}
@Test
void foreignRegionArnCannotMutateCallerFunction(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(CALLER_ACCOUNT, REGION, function(CALLER_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
String foreignArn = "arn:aws:lambda:us-west-2:" + CALLER_ACCOUNT
+ ":function:" + FUNCTION_NAME;
AwsException error = assertThrows(AwsException.class,
() -> service.putFunctionCodeSigningConfig(REGION, foreignArn, CONFIG_ARN));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertNull(store.getForAccount(CALLER_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void namespacedFunctionNameAcceptsQualifiedAndDottedReferences(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
LambdaFunction function = function(CALLER_ACCOUNT);
function.setFunctionName("same.name");
function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + CALLER_ACCOUNT
+ ":function:same.name");
store.saveForAccount(CALLER_ACCOUNT, REGION, function);
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
service.putFunctionCodeSigningConfig(REGION, "same.name:$LATEST", CONFIG_ARN);
assertEquals(CONFIG_ARN, store.getForAccount(CALLER_ACCOUNT, REGION, "same.name")
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void foreignArnCannotSelectAFunctionAbsentFromTheCallerAccount(@TempDir Path codePath) {
LambdaFunctionStore store = new LambdaFunctionStore(
AccountAwareStorageBackend.inMemory(CALLER_ACCOUNT));
store.saveForAccount(ARN_ACCOUNT, REGION, function(ARN_ACCOUNT));
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, CALLER_ACCOUNT));
String foreignArn = "arn:aws:lambda:" + REGION + ":" + ARN_ACCOUNT
+ ":function:" + FUNCTION_NAME;
AwsException error = assertThrows(AwsException.class,
() -> service.putFunctionCodeSigningConfig(REGION, foreignArn, CONFIG_ARN));
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertNull(store.getForAccount(ARN_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
}
@Test
void legacyArnOwnedFunctionIsWrittenBackToTheVerifiedAccount(@TempDir Path codePath) {
InMemoryStorage<String, LambdaFunction> raw = new InMemoryStorage<>();
AccountAwareStorageBackend<LambdaFunction> backend =
new AccountAwareStorageBackend<>(raw, null, ARN_ACCOUNT);
LambdaFunctionStore store = new LambdaFunctionStore(backend);
LambdaFunction legacy = function(ARN_ACCOUNT);
legacy.setAccountId(null);
raw.put("lambda::" + REGION + "::" + FUNCTION_NAME + "::$LATEST", legacy);
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, ARN_ACCOUNT));
service.putFunctionCodeSigningConfig(REGION, FUNCTION_NAME, CONFIG_ARN);
assertEquals(CONFIG_ARN, store.getForAccount(ARN_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getCodeSigningConfigArn());
assertEquals(ARN_ACCOUNT, store.getForAccount(ARN_ACCOUNT, REGION, FUNCTION_NAME)
.orElseThrow().getAccountId());
assertTrue(store.getForAccount("000000000000", REGION, FUNCTION_NAME).isEmpty());
}
private static LambdaFunction function(String account) {
LambdaFunction function = new LambdaFunction();
function.setAccountId(account);
function.setFunctionName(FUNCTION_NAME);
function.setVersion("$LATEST");
function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + account
+ ":function:" + FUNCTION_NAME);
return function;
}
}
@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.lambda;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LambdaCodeSigningAttachmentDeleteRaceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "111111111111";
private static final String NAME = "attachment-delete-race";
private static final String ARN = "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + NAME;
private static final String CONFIG_ARN = "arn:aws:lambda:" + REGION + ":" + ACCOUNT
+ ":code-signing-config:csc-0123456789abcdef0";
@Test
void putCannotRestoreFunctionDeletedWhileMutationWaitsForLock(@TempDir Path codePath) throws Exception {
assertDeletedFunctionIsNotRestored(codePath, null,
service -> service.putFunctionCodeSigningConfig(REGION, NAME, CONFIG_ARN));
}
@Test
void detachCannotRestoreFunctionDeletedWhileMutationWaitsForLock(@TempDir Path codePath) throws Exception {
assertDeletedFunctionIsNotRestored(codePath, CONFIG_ARN,
service -> service.deleteFunctionCodeSigningConfig(REGION, NAME));
}
private void assertDeletedFunctionIsNotRestored(Path codePath, String initialConfigArn,
Consumer<LambdaService> mutation) throws Exception {
LambdaFunctionStore store = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT));
LambdaFunction function = new LambdaFunction();
function.setAccountId(ACCOUNT);
function.setFunctionName(NAME);
function.setFunctionArn(ARN);
function.setVersion("$LATEST");
function.setCodeSigningConfigArn(initialConfigArn);
store.saveForAccount(ACCOUNT, REGION, function);
LambdaService service = new LambdaService(store, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), new RegionResolver(REGION, ACCOUNT));
ExecutorService workerPool = Executors.newSingleThreadExecutor();
CountDownLatch started = new CountDownLatch(1);
AtomicReference<Thread> worker = new AtomicReference<>();
try {
Future<?> future;
synchronized (service.lockForConcurrencyOp(ARN)) {
future = workerPool.submit(() -> {
worker.set(Thread.currentThread());
started.countDown();
mutation.accept(service);
});
assertTrue(started.await(5, TimeUnit.SECONDS));
awaitBlockedOrDone(worker.get());
service.deleteFunction(REGION, NAME);
assertFalse(store.getForAccount(ACCOUNT, REGION, NAME).isPresent());
}
ExecutionException failure = assertThrows(ExecutionException.class,
() -> future.get(5, TimeUnit.SECONDS));
AwsException error = assertInstanceOf(AwsException.class, failure.getCause());
assertEquals("ResourceNotFoundException", error.getErrorCode());
assertFalse(store.getForAccount(ACCOUNT, REGION, NAME).isPresent());
} finally {
workerPool.shutdownNow();
}
}
}
@@ -0,0 +1,222 @@
package io.github.hectorvent.floci.services.lambda;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/** Wire-level lifecycle and error coverage for function code-signing attachments. */
@QuarkusTest
class LambdaCodeSigningAttachmentIntegrationTest {
private static final String CONFIGS = "/2020-04-22/code-signing-configs";
private static final String SIGNING = "/2020-06-30";
private static final String LEGACY_FUNCTIONS = "/2015-03-31/functions";
private static final String PROFILE =
"arn:aws:signer:us-east-1:000000000000:/signing-profiles/prof/AbCdEfGhIj";
@Test
void attachReadListDetachAndDeleteConfiguration() {
String functionName = "signing-lifecycle-" + System.nanoTime();
String functionPath = LEGACY_FUNCTIONS + "/" + functionName;
String arn = createConfig();
try {
createFunction(functionName);
given().contentType("application/json")
.body("{\"CodeSigningConfigArn\":\"" + arn + "\"}")
.when().put(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(200)
.body("CodeSigningConfigArn", is(arn))
.body("FunctionName", is(functionName));
given().when().get(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(200)
.body("CodeSigningConfigArn", is(arn))
.body("FunctionName", is(functionName));
given().when().get(functionPath + "/code-signing-config")
.then().statusCode(404);
given().queryParam("MaxItems", 1)
.when().get(CONFIGS + "/" + arn + "/functions")
.then().statusCode(200)
.body("FunctionArns", contains(
"arn:aws:lambda:us-east-1:000000000000:function:" + functionName))
.body("NextMarker", nullValue());
given().when().delete(CONFIGS + "/" + arn).then().statusCode(409)
.body("__type", is("ResourceConflictException"));
given().when().delete(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(204);
given().when().get(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(200)
.body("CodeSigningConfigArn", is(""));
given().when().delete(CONFIGS + "/" + arn).then().statusCode(204);
} finally {
try {
given().when().delete(functionPath);
} finally {
given().when().delete(CONFIGS + "/" + arn);
}
}
}
@Test
void putRejectsMalformedAndUnknownConfigurations() {
String functionName = "signing-negative-" + System.nanoTime();
String functionPath = LEGACY_FUNCTIONS + "/" + functionName;
createFunction(functionName);
try {
given().contentType("application/json")
.body("{\"CodeSigningConfigArn\":\"not-an-arn\"}")
.when().put(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(400)
.body("__type", is("InvalidParameterValueException"));
given().contentType("application/json")
.body("{\"CodeSigningConfigArn\":\""
+ "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-abcdefghij1234567"
+ "\"}")
.when().put(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(404)
.body("__type", is("CodeSigningConfigNotFoundException"));
} finally {
given().when().delete(functionPath).then().statusCode(204);
}
}
@Test
void createFunctionAttachesExistingConfiguration() {
String functionName = "signing-create-" + System.nanoTime();
String functionPath = LEGACY_FUNCTIONS + "/" + functionName;
String arn = createConfig();
try {
given().contentType("application/json")
.body("{\"FunctionName\":\"" + functionName + "\",\"Runtime\":\"nodejs20.x\","
+ "\"Role\":\"arn:aws:iam::000000000000:role/lambda-role\","
+ "\"Handler\":\"index.handler\",\"CodeSigningConfigArn\":\"" + arn + "\"}")
.when().post(LEGACY_FUNCTIONS)
.then().statusCode(201)
.body("CodeSigningConfigArn", nullValue());
given().when().get(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(200)
.body("CodeSigningConfigArn", is(arn));
given().when().get(LEGACY_FUNCTIONS + "/" + functionName + "/configuration")
.then().statusCode(200)
.body("CodeSigningConfigArn", nullValue());
given().when().get(functionPath)
.then().statusCode(200)
.body("Configuration.CodeSigningConfigArn", nullValue());
given().when().get(LEGACY_FUNCTIONS)
.then().statusCode(200)
.body("Functions.FunctionName", hasItem(functionName))
.body("Functions.find { it.FunctionName == '" + functionName
+ "' }.CodeSigningConfigArn", nullValue());
} finally {
given().when().delete(functionPath).then().statusCode(204);
given().when().delete(CONFIGS + "/" + arn).then().statusCode(204);
}
}
@Test
void createFunctionRejectsUnknownCodeSigningConfiguration() {
String functionName = "signing-create-missing-" + System.nanoTime();
String unknownArn = "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-abcdefghij1234567";
given().contentType("application/json")
.body("{\"FunctionName\":\"" + functionName + "\",\"Runtime\":\"nodejs20.x\","
+ "\"Role\":\"arn:aws:iam::000000000000:role/lambda-role\","
+ "\"Handler\":\"index.handler\",\"CodeSigningConfigArn\":\"" + unknownArn + "\"}")
.when().post(LEGACY_FUNCTIONS)
.then().statusCode(404)
.body("__type", is("CodeSigningConfigNotFoundException"));
}
@Test
void listFunctionsByCodeSigningConfigPaginatesAttachedFunctions() {
String suffix = String.valueOf(System.nanoTime());
String firstFunction = "signing-page-a-" + suffix;
String secondFunction = "signing-page-b-" + suffix;
String firstPath = LEGACY_FUNCTIONS + "/" + firstFunction;
String secondPath = LEGACY_FUNCTIONS + "/" + secondFunction;
String arn = createConfig();
try {
createFunction(firstFunction);
createFunction(secondFunction);
attach(firstFunction, arn);
attach(secondFunction, arn);
Response firstPage = given().queryParam("MaxItems", 1)
.when().get(CONFIGS + "/" + arn + "/functions")
.then().statusCode(200)
.extract().response();
String firstArn = firstPage.path("FunctionArns[0]");
String marker = firstPage.path("NextMarker");
assertNotNull(firstArn);
assertNotNull(marker);
Response secondPage = given().queryParam("MaxItems", 1).queryParam("Marker", marker)
.when().get(CONFIGS + "/" + arn + "/functions")
.then().statusCode(200)
.extract().response();
String secondArn = secondPage.path("FunctionArns[0]");
assertNotNull(secondArn);
assertNotEquals(firstArn, secondArn);
assertThat(secondPage.path("FunctionArns"), hasSize(1));
assertThat(secondPage.path("NextMarker"), nullValue());
} finally {
try {
detach(firstFunction);
} finally {
try {
detach(secondFunction);
} finally {
try {
given().when().delete(firstPath);
} finally {
try {
given().when().delete(secondPath);
} finally {
given().when().delete(CONFIGS + "/" + arn);
}
}
}
}
}
}
private static String createConfig() {
return given().contentType("application/json")
.body("{\"AllowedPublishers\":{\"SigningProfileVersionArns\":[\"" + PROFILE + "\"]}}")
.when().post(CONFIGS)
.then().statusCode(201)
.extract().path("CodeSigningConfig.CodeSigningConfigArn");
}
private static void createFunction(String functionName) {
given().contentType("application/json")
.body("{\"FunctionName\":\"" + functionName + "\",\"Runtime\":\"nodejs20.x\","
+ "\"Role\":\"arn:aws:iam::000000000000:role/lambda-role\","
+ "\"Handler\":\"index.handler\"}")
.when().post(LEGACY_FUNCTIONS)
.then().statusCode(201);
}
private static void attach(String functionName, String arn) {
given().contentType("application/json")
.body("{\"CodeSigningConfigArn\":\"" + arn + "\"}")
.when().put(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(200);
}
private static void detach(String functionName) {
given().when().delete(SIGNING + "/functions/" + functionName + "/code-signing-config")
.then().statusCode(204);
}
}
@@ -0,0 +1,187 @@
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.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
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.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class LambdaCodeSigningConfigDeleteRaceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "111111111111";
private static final String NAME = "config-delete-race";
@Test
void deleteWaitsForValidatedPutAndRejectsAttachedConfig(@TempDir Path codePath) throws Exception {
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
RegionResolver regions = new RegionResolver(REGION, ACCOUNT);
LambdaCodeSigningConfigService configs = spy(new LambdaCodeSigningConfigService(factory, regions));
CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers();
publishers.setSigningProfileVersionArns(List.of(
"arn:aws:signer:us-east-1:111111111111:/signing-profiles/prof/AbCdEfGhIj"));
String configArn = configs.create(REGION, ACCOUNT, null, publishers, null).getCodeSigningConfigArn();
LambdaFunctionStore functions = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT));
LambdaFunction function = new LambdaFunction();
function.setAccountId(ACCOUNT);
function.setFunctionName(NAME);
function.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + NAME);
function.setVersion("$LATEST");
functions.saveForAccount(ACCOUNT, REGION, function);
LambdaService lambda = new LambdaService(functions, new WarmPool(), new CodeStore(codePath),
new ZipExtractor(), regions);
ObjectMapper mapper = new ObjectMapper();
LambdaCodeSigningController attachments = new LambdaCodeSigningController(lambda, configs, regions, mapper);
LambdaCodeSigningConfigFunctionsController configController =
new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, mapper);
CountDownLatch validated = new CountDownLatch(1);
CountDownLatch releasePut = new CountDownLatch(1);
AtomicReference<Thread> putThread = new AtomicReference<>();
doAnswer(invocation -> {
CodeSigningConfig result = (CodeSigningConfig) invocation.callRealMethod();
if (Thread.currentThread() == putThread.get()) {
validated.countDown();
assertTrue(releasePut.await(15, TimeUnit.SECONDS));
}
return result;
}).when(configs).get(REGION, ACCOUNT, configArn);
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
ObjectNode body = mapper.createObjectNode().put("CodeSigningConfigArn", configArn);
Future<Response> put = workers.submit(() -> {
putThread.set(Thread.currentThread());
return attachments.putFunctionCodeSigningConfig(null, NAME, body);
});
assertTrue(validated.await(5, TimeUnit.SECONDS));
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<Response> delete = workers.submit(() -> {
deleteThread.set(Thread.currentThread());
return configController.deleteCodeSigningConfig(null, configArn);
});
awaitBlockedOrDone(deleteThread, delete);
assertFalse(delete.isDone(), "config deletion must wait for the validated attachment");
releasePut.countDown();
assertEquals(200, put.get(5, TimeUnit.SECONDS).getStatus());
ExecutionException failure = assertThrows(ExecutionException.class,
() -> delete.get(5, TimeUnit.SECONDS));
AwsException conflict = assertInstanceOf(AwsException.class, failure.getCause());
assertEquals("ResourceConflictException", conflict.getErrorCode());
assertEquals(409, conflict.getHttpStatus());
assertEquals(configArn, configs.get(REGION, ACCOUNT, configArn).getCodeSigningConfigArn());
assertEquals(configArn, functions.getForAccount(ACCOUNT, REGION, NAME)
.orElseThrow().getCodeSigningConfigArn());
} finally {
releasePut.countDown();
workers.shutdownNow();
}
}
@Test
void deleteWaitsForValidatedCreateAndRejectsAttachedConfig(@TempDir Path codePath) throws Exception {
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
RegionResolver regions = new RegionResolver(REGION, ACCOUNT);
LambdaCodeSigningConfigService configs = spy(new LambdaCodeSigningConfigService(factory, regions));
CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers();
publishers.setSigningProfileVersionArns(List.of(
"arn:aws:signer:us-east-1:111111111111:/signing-profiles/prof/AbCdEfGhIj"));
String configArn = configs.create(REGION, ACCOUNT, null, publishers, null).getCodeSigningConfigArn();
LambdaFunctionStore functions = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT));
LambdaService lambda = new LambdaService(functions, null, new LambdaConcurrencyLimiter(),
new WarmPool(), new CodeStore(codePath), new ZipExtractor(), null, regions, null, null,
new LambdaTargetResolver(functions, null), null, null, null, null, null, factory,
null, null, null, null, new ObjectMapper(), configs);
LambdaCodeSigningConfigFunctionsController configController =
new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, new ObjectMapper());
CountDownLatch validated = new CountDownLatch(1);
CountDownLatch releaseCreate = new CountDownLatch(1);
AtomicReference<Thread> createThread = new AtomicReference<>();
doAnswer(invocation -> {
CodeSigningConfig result = (CodeSigningConfig) invocation.callRealMethod();
if (Thread.currentThread() == createThread.get()) {
validated.countDown();
assertTrue(releaseCreate.await(15, TimeUnit.SECONDS));
}
return result;
}).when(configs).requireForAttachment(REGION, ACCOUNT, configArn);
String functionName = "create-config-delete-race";
Map<String, Object> request = Map.of(
"FunctionName", functionName,
"Runtime", "nodejs20.x",
"Role", "arn:aws:iam::111111111111:role/lambda-role",
"Handler", "index.handler",
"CodeSigningConfigArn", configArn);
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
Future<LambdaFunction> create = workers.submit(() -> {
createThread.set(Thread.currentThread());
return lambda.createFunction(REGION, request);
});
assertTrue(validated.await(5, TimeUnit.SECONDS));
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<Response> delete = workers.submit(() -> {
deleteThread.set(Thread.currentThread());
return configController.deleteCodeSigningConfig(null, configArn);
});
awaitBlockedOrDone(deleteThread, delete);
assertFalse(delete.isDone(), "config deletion must wait for the validated create");
releaseCreate.countDown();
assertEquals(configArn, create.get(5, TimeUnit.SECONDS).getCodeSigningConfigArn());
ExecutionException failure = assertThrows(ExecutionException.class,
() -> delete.get(5, TimeUnit.SECONDS));
AwsException conflict = assertInstanceOf(AwsException.class, failure.getCause());
assertEquals("ResourceConflictException", conflict.getErrorCode());
assertEquals(409, conflict.getHttpStatus());
assertEquals(configArn, functions.getForAccount(ACCOUNT, REGION, functionName)
.orElseThrow().getCodeSigningConfigArn());
} finally {
releaseCreate.countDown();
workers.shutdownNow();
}
}
}
@@ -14,6 +14,7 @@ import static org.hamcrest.Matchers.*;
class LambdaCodeSigningConfigIntegrationTest {
private static final String BASE_PATH = "/2015-03-31";
private static final String CODE_SIGNING_PATH = "/2020-06-30";
private static final String FUNCTION_NAME = "code-signing-test-function";
@Test
@@ -42,7 +43,7 @@ class LambdaCodeSigningConfigIntegrationTest {
void getFunctionCodeSigningConfig() {
given()
.when()
.get(BASE_PATH + "/functions/" + FUNCTION_NAME + "/code-signing-config")
.get(CODE_SIGNING_PATH + "/functions/" + FUNCTION_NAME + "/code-signing-config")
.then()
.statusCode(200)
.body("FunctionName", equalTo(FUNCTION_NAME))
@@ -54,7 +55,7 @@ class LambdaCodeSigningConfigIntegrationTest {
void getFunctionCodeSigningConfigNotFound() {
given()
.when()
.get(BASE_PATH + "/functions/nonexistent-function/code-signing-config")
.get(CODE_SIGNING_PATH + "/functions/nonexistent-function/code-signing-config")
.then()
.statusCode(404);
}
@@ -0,0 +1,103 @@
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.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.lambda.model.CodeSigningConfig;
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
class LambdaCodeSigningConfigUpdateDeleteRaceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "111111111111";
@Test
void deleteWaitsForUpdateAndCannotBeUndoneByStaleSave(@TempDir Path codePath) throws Exception {
StorageFactory factory = mock(StorageFactory.class);
when(factory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
RegionResolver regions = new RegionResolver(REGION, ACCOUNT);
LambdaCodeSigningConfigService configs = spy(new LambdaCodeSigningConfigService(factory, regions));
CodeSigningConfig.AllowedPublishers publishers = new CodeSigningConfig.AllowedPublishers();
publishers.setSigningProfileVersionArns(List.of(
"arn:aws:signer:us-east-1:111111111111:/signing-profiles/prof/AbCdEfGhIj"));
String 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);
ObjectMapper mapper = new ObjectMapper();
LambdaCodeSigningConfigFunctionsController controller =
new LambdaCodeSigningConfigFunctionsController(configs, lambda, regions, mapper);
CountDownLatch readForUpdate = new CountDownLatch(1);
CountDownLatch releaseUpdate = new CountDownLatch(1);
AtomicReference<Thread> updateThread = new AtomicReference<>();
AtomicInteger updateReads = new AtomicInteger();
doAnswer(invocation -> {
CodeSigningConfig result = (CodeSigningConfig) invocation.callRealMethod();
if (Thread.currentThread() == updateThread.get() && updateReads.incrementAndGet() == 2) {
readForUpdate.countDown();
assertTrue(releaseUpdate.await(15, TimeUnit.SECONDS));
}
return result;
}).when(configs).get(REGION, arn);
ExecutorService workers = Executors.newFixedThreadPool(2);
try {
ObjectNode body = mapper.createObjectNode().put("Description", "updated");
Future<Response> update = workers.submit(() -> {
updateThread.set(Thread.currentThread());
return controller.updateCodeSigningConfig(null, arn, body);
});
assertTrue(readForUpdate.await(5, TimeUnit.SECONDS));
AtomicReference<Thread> deleteThread = new AtomicReference<>();
Future<Response> delete = workers.submit(() -> {
deleteThread.set(Thread.currentThread());
return controller.deleteCodeSigningConfig(null, arn);
});
awaitBlockedOrDone(deleteThread, delete);
assertFalse(delete.isDone(), "delete must wait until the update finishes");
releaseUpdate.countDown();
assertEquals(200, update.get(5, TimeUnit.SECONDS).getStatus());
assertEquals(204, delete.get(5, TimeUnit.SECONDS).getStatus());
AwsException notFound = assertThrows(AwsException.class,
() -> configs.get(REGION, ACCOUNT, arn));
assertEquals("ResourceNotFoundException", notFound.getErrorCode());
} finally {
releaseUpdate.countDown();
workers.shutdownNow();
}
}
}
@@ -31,6 +31,18 @@ class LambdaFunctionStoreAccountScopeTest {
assertEquals("other-fn", all.get(0).getFunctionName());
}
@Test
void listForAccountStaysWithinTheRequestedPartition() {
LambdaFunctionStore store = accountAwareStore();
store.saveForAccount(DEFAULT_ACCOUNT, REGION, function("default-fn", DEFAULT_ACCOUNT));
store.saveForAccount(OTHER_ACCOUNT, REGION, function("other-fn", OTHER_ACCOUNT));
assertEquals(List.of("default-fn"), store.listForAccount(DEFAULT_ACCOUNT, REGION).stream()
.map(LambdaFunction::getFunctionName).toList());
assertEquals(List.of("other-fn"), store.listForAccount(OTHER_ACCOUNT, REGION).stream()
.map(LambdaFunction::getFunctionName).toList());
}
@Test
void listAllAccountsKeepsTheRegionAndLatestFilter() {
LambdaFunctionStore store = accountAwareStore();