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

@@ -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;