fix(lambda): accept layer ARNs when deleting versions (#8409)

* fix(lambda): accept layer ARNs when deleting versions
* test(lambda): share layer publication cleanup
* test(iam): include layer deletion in the resource inventory
* fix(lambda): read Lambda's IAM resources whole from the generated table
This commit is contained in:
Jackson Price authored and GitHub committed 2026-11-15 01:56:37 -04:00
1 parent ce25aa0247
commit b8014cbd4e
22 files changed
+1219 -906

No files matched your search

@@ -36,6 +36,7 @@ import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
@@ -170,29 +171,33 @@ class IamConditionContextResolverTest {
String resource = "lambda:Resource/WebFunctionAuthType";
assertEquals(Map.of(request, List.of("IamAuth")), resolver.resolve("lambda", "lambda:CreateWebFunction",
webRequest("/2025-03-07/web-functions", "{\"endpointConfig\":{\"authType\":\"IamAuth\"}}")));
webRequest("PUT", "/2025-03-07/web-functions", "{\"endpointConfig\":{\"authType\":\"IamAuth\"}}")));
assertEquals(Map.of(request, List.of("IamAuth")), resolver.resolve("lambda",
"lambda:CreateWebFunctionEndpoint", webRequest("/2025-03-07/web-functions/app/endpoints",
"lambda:CreateWebFunctionEndpoint", webRequest("PUT", "/2025-03-07/web-functions/app/endpoints",
"{\"authType\":\"IamAuth\"}")));
assertEquals(Map.of(request, List.of("IamAuth"), resource, List.of("ApplicationManaged")),
resolver.resolve("lambda", "lambda:UpdateWebFunctionEndpoint",
webRequest("/2025-03-07/web-functions/app/endpoints/dev", "{\"authType\":\"IamAuth\"}")));
webRequest("PATCH", "/2025-03-07/web-functions/app/endpoints/dev", "{\"authType\":\"IamAuth\"}")));
assertEquals(Map.of(resource, List.of("ApplicationManaged")), resolver.resolve("lambda",
"lambda:UpdateWebFunctionEndpoint", webRequest("/2025-03-07/web-functions/app/endpoints/dev",
"lambda:UpdateWebFunctionEndpoint", webRequest("PATCH", "/2025-03-07/web-functions/app/endpoints/dev",
"{\"description\":\"d\"}")), "an update without authType names none");
for (String action : List.of("lambda:GetWebFunctionEndpoint", "lambda:DeleteWebFunctionEndpoint")) {
assertEquals(Map.of(resource, List.of("ApplicationManaged")), resolver.resolve("lambda", action,
webRequest("/2025-03-07/web-functions/" + function + "/endpoints/" + function + "/endpoint/dev",
"")));
assertNull(resolver.resolve("lambda", action,
webRequest("/2025-03-07/web-functions/app/endpoints/gone", "")), "a missing endpoint has none");
// A function and an endpoint named by their ARNs, which a client sends encoded.
String encoded = function.replace("/", "%2F");
for (String[] action : new String[][] {{"lambda:GetWebFunctionEndpoint", "GET"},
{"lambda:DeleteWebFunctionEndpoint", "DELETE"}}) {
assertEquals(Map.of(resource, List.of("ApplicationManaged")), resolver.resolve("lambda", action[0],
webRequest(action[1], "/2025-03-07/web-functions/" + encoded + "/endpoints/" + encoded
+ "%2Fendpoint%2Fdev", "")));
assertNull(resolver.resolve("lambda", action[0],
webRequest(action[1], "/2025-03-07/web-functions/app/endpoints/gone", "")),
"a missing endpoint has none");
}
assertNull(resolver.resolve("lambda", "lambda:GetWebFunctionEndpoint",
webRequest("/2025-03-07/web-functions/arn:bad/endpoints/dev", "")), "a malformed ARN has none");
webRequest("GET", "/2025-03-07/web-functions/arn:bad/endpoints/dev", "")), "a malformed ARN has none");
assertNull(resolver.resolve("lambda", "lambda:GetWebFunction",
webRequest("/2025-03-07/web-functions/app", "")));
webRequest("GET", "/2025-03-07/web-functions/app", "")));
assertNull(resolver.resolve("lambda", "lambda:ListWebFunctionEndpoints",
webRequest("/2025-03-07/web-functions/app/list-endpoints", "{}")));
webRequest("POST", "/2025-03-07/web-functions/app/list-endpoints", "{}")));
}
/**
@@ -309,11 +314,15 @@ class IamConditionContextResolverTest {
}
}
private ContainerRequestContext webRequest(String path, String body) throws Exception {
private ContainerRequestContext webRequest(String method, String path, String body) throws Exception {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(uriInfo.getPath()).thenReturn(path);
when(containerRequest.getMethod()).thenReturn(method);
when(uriInfo.getPath()).thenReturn(URI.create(path).getPath());
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + path));
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(containerRequest.getProperty("floci.bufferedJsonBody"))
.thenReturn(body.isEmpty() ? null : mapper.readTree(body));
return containerRequest;
@@ -158,8 +158,9 @@ class RequestResourceMembersTest {
void theTableReadsItsNamespacesAndGivesEachTypeItNamesAnArnFormat() {
RequestResourceMembers.Table table = RequestResourceMembers.table();
assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states")));
assertTrue(table.handBuilt().contains("lambda"));
assertEquals(Set.of("dynamodb", "lambda", "logs"), table.namespaces().stream().filter(table.handBuilt()::contains)
assertTrue(table.namespaces().contains("lambda"));
assertFalse(table.handBuilt().contains("lambda"));
assertEquals(Set.of("dynamodb", "logs"), table.namespaces().stream().filter(table.handBuilt()::contains)
.collect(Collectors.toSet()));
Set<String> logsDelivery = Stream.of("PutDeliverySource", "GetDeliverySource", "DeleteDeliverySource",
"DescribeDeliverySources", "PutDeliveryDestination", "GetDeliveryDestination",
@@ -168,8 +169,6 @@ class RequestResourceMembersTest {
.map(operation -> "logs:" + operation).collect(Collectors.toSet());
Set<String> expected = new HashSet<>(logsDelivery);
expected.add("logs:PutDestination");
expected.add("lambda:GetLayerVersion");
expected.add("lambda:GetLayerVersionByArn");
// What AWS was measured to check where the Service Reference lists no resource type (MEASURED).
expected.add("dynamodb:ListTables");
assertEquals(expected, table.operations().keySet().stream()
@@ -415,9 +415,10 @@ class IamRestRouteEnforcementIntegrationTest {
}
@Test
void lambdaTaggingIsCheckedAgainstTheCallersOwnResourceWhateverAccountTheArnNames() {
// Lambda tags the caller's own function or MicroVM image of the ARN's name, so a grant on another
// account's ARN of that name does not cover it, and a grant on the caller's own does.
void lambdaTaggingByAnotherAccountsArnIsCheckedOnThatArnAndTheCallersOwnResourceOfItsName() {
// The ARN names another account's function or MicroVM image, which is checked, and Lambda tags the caller's
// own of that name, which is checked too, so a grant on either alone does not cover it; one on the caller's
// own covers a request naming its own ARN.
String user = user("route-lambda-tags-account");
String name = "route-tagged-" + suffix();
String body = "{\"Tags\":{\"team\":\"a\"}}";
@@ -428,7 +429,8 @@ class IamRestRouteEnforcementIntegrationTest {
policy(user, allow("lambda:TagResource", foreign));
refused(as(user, "lambda").body(body).post("/2017-03-31/tags/" + foreign).then(), "lambda:TagResource");
policy(user, allow("lambda:TagResource", own));
as(user, "lambda").body(body).post("/2017-03-31/tags/" + foreign).then().statusCode(not(403));
refused(as(user, "lambda").body(body).post("/2017-03-31/tags/" + foreign).then(), "lambda:TagResource");
as(user, "lambda").body(body).post("/2017-03-31/tags/" + own).then().statusCode(not(403));
}
}
@@ -22,6 +22,7 @@ import io.floci.aws.services.iam.model.IamUser;
import io.floci.aws.services.iam.model.InstanceProfile;
import io.floci.aws.services.iam.model.ServerCertificate;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.lambda.LambdaStoredResourceArns;
import io.floci.aws.services.lambdamicrovms.LambdaMicrovmsService;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpServerRequest;
@@ -49,6 +50,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -147,20 +149,12 @@ class ResourceArnBuilderTest {
return new ResourceArnBuilder(new ObjectMapper(), instance);
}
/** A builder reading {@code microvms}, for an action on a running MicroVM. */
private static ResourceArnBuilder backedBy(LambdaMicrovmsService microvms) {
@SuppressWarnings("unchecked")
Instance<LambdaMicrovmsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(microvms);
return new ResourceArnBuilder(new ObjectMapper(), null, instance);
}
/** A builder reading {@code eks}, for an EKS route naming a cluster or what it holds. */
private static ResourceArnBuilder backedBy(EksService eks) {
@SuppressWarnings("unchecked")
Instance<EksService> instance = mock(Instance.class);
when(instance.get()).thenReturn(eks);
return new ResourceArnBuilder(new ObjectMapper(), null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, instance);
}
private static IamService storeHolding(String userName, String path, String arn) {
@@ -1408,7 +1402,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<KmsService> instance = mock(Instance.class);
when(instance.get()).thenReturn(kms);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, null, instance);
}
/** A builder reading the stored ARNs of a namespace, for every request of that namespace. */
@@ -1416,7 +1410,7 @@ class ResourceArnBuilderTest {
@SuppressWarnings("unchecked")
Instance<StoredResourceArns> instance = mock(Instance.class);
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, null, instance);
return new ResourceArnBuilder(new ObjectMapper(), null, null, null, instance);
}
/** The finder of the stored ARNs of a namespace, answering one name of one type with one ARN. */
@@ -2013,270 +2007,130 @@ class ResourceArnBuilderTest {
// ── Lambda ──────────────────────────────────────────────────────────────────
@Test
void lambdaBuildsFunctionArn() {
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/my-function/invocations");
String arn = builder.build("lambda", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function", arn);
private static final String FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function:my-function";
private static final String OTHER_FUNCTION = "arn:aws:lambda:us-east-1:111122223333:function:my-function";
/** The resources a Lambda request names, read from the generated table for the operation it is dispatched as. */
private List<String> lambda(String method, String sent, String operation) {
return lambda(builder, method, sent, operation);
}
/** CreateFunction is checked on the function its body names, in the caller's account and Region. */
@Test
void lambdaCreateFunctionIsCheckedOnTheFunctionItsBodyNames() {
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions");
when(ctx.getMethod()).thenReturn("POST");
setJsonBody("{\"FunctionName\":\"my-function\",\"Runtime\":\"nodejs20.x\"}");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
setJsonBody("{\"FunctionName\":\"arn:aws:lambda:us-east-1:111122223333:function:my-function\"}");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
setJsonBody("{\"Runtime\":\"nodejs20.x\"}");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(ctx.getMethod()).thenReturn("GET");
setJsonBody("{\"FunctionName\":\"my-function\"}");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
private List<String> lambda(ResourceArnBuilder from, String method, String sent, String operation) {
when(ctx.getMethod()).thenReturn(method);
request(sent);
return from.buildResources("lambda", "lambda:" + operation, ctx, "us-east-1", ACCOUNT, "aws");
}
/** A function is named by its name, its ARN or a partial ARN, and a whole or partial ARN keeps its account. */
@Test
void lambdaFunctionArnKeepsTheAccountItNames() {
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function/invocations");
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/111122223333:function:my-function/invocations");
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
void aFunctionIsNamedByItsNameOrItsWholeOrPartialArn() {
assertEquals(List.of(FUNCTION), lambda("POST", "/2015-03-31/functions/my-function/invocations", "Invoke"));
assertEquals(Set.of(OTHER_FUNCTION, FUNCTION), Set.copyOf(lambda("POST",
"/2015-03-31/functions/" + OTHER_FUNCTION + "/invocations", "Invoke")));
assertEquals(Set.of(OTHER_FUNCTION, FUNCTION), Set.copyOf(lambda("POST",
"/2015-03-31/functions/111122223333:function:my-function/invocations", "Invoke")));
assertEquals(Set.of("arn:aws:lambda:eu-west-1:111122223333:function:my-function",
"arn:aws:lambda:eu-west-1:000000000000:function:my-function",
"arn:aws:lambda:us-east-1:111122223333:function:my-function", FUNCTION),
Set.copyOf(lambda("GET", "/2015-03-31/functions/eu-west-1:111122223333:function:my-function",
"GetFunction")));
// Code-signing attachment names its function by Lambda's broader shape, the resource part alone included.
assertEquals(List.of("arn:aws:lambda:us-east-1:000000000000:function:protected"),
lambda("GET", "/2020-06-30/functions/function:protected/code-signing-config",
"GetFunctionCodeSigningConfig"));
// A reference Lambda refuses is named as given: its handler answers it with a 400.
assertEquals(List.of("arn:aws:lambda:us-east-1:000000000000:function:not:a:function:ref"),
lambda("POST", "/2015-03-31/functions/not:a:function:ref/invocations", "Invoke"));
}
/**
* A version or alias written into the function's name is part of the name it is checked on; the Qualifier member
* names nothing for an action the Service Reference gives the function alone.
*/
@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(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:live/invocations");
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function:live",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/my-function/invocations");
void aQualifierInTheNameIsPartOfTheFunctionItNames() {
assertEquals(List.of(FUNCTION + ":1"), lambda("DELETE", "/2015-03-31/functions/my-function:1",
"DeleteFunction"));
assertEquals(Set.of(OTHER_FUNCTION + ":live", FUNCTION + ":live"), Set.copyOf(lambda("POST",
"/2015-03-31/functions/" + OTHER_FUNCTION + ":live/invocations", "Invoke")));
queryParams.putSingle("Qualifier", "1");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:1",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
assertEquals(List.of(FUNCTION), lambda("POST", "/2015-03-31/functions/my-function/invocations", "Invoke"));
assertEquals(List.of(FUNCTION), lambda("GET", "/2015-03-31/functions/my-function", "GetFunction"));
assertEquals(List.of(FUNCTION), lambda("POST",
"/2021-11-15/functions/my-function/response-streaming-invocations", "InvokeWithResponseStream"));
}
/** Provisioned concurrency acts on the alias or version its Qualifier names, of the function it names. */
@Test
void provisionedConcurrencyKeepsTheOwnerAndQualifierItConfigures() {
when(uriInfo.getPath()).thenReturn(
"/2019-09-30/functions/arn:aws:lambda:us-east-1:111122223333:function:example/provisioned-concurrency");
void provisionedConcurrencyActsOnTheVersionOrAliasItsQualifierNames() {
queryParams.putSingle("Qualifier", "live");
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:example:live",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2019-09-30/functions/example/provisioned-concurrency");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:example:live",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
assertEquals(List.of(FUNCTION + ":live"), lambda("GET",
"/2019-09-30/functions/my-function/provisioned-concurrency", "GetProvisionedConcurrencyConfig"));
assertEquals(Set.of(OTHER_FUNCTION + ":live", FUNCTION + ":live"), Set.copyOf(lambda("GET",
"/2019-09-30/functions/" + OTHER_FUNCTION + "/provisioned-concurrency",
"GetProvisionedConcurrencyConfig")));
}
/** CreateFunction is checked on the function its body names. */
@Test
void createFunctionIsCheckedOnTheFunctionItsBodyNames() {
setJsonBody("{\"FunctionName\":\"my-function\",\"Runtime\":\"nodejs20.x\"}");
assertEquals(List.of(FUNCTION), lambda("POST", "/2015-03-31/functions", "CreateFunction"));
setJsonBody("{\"FunctionName\":\"" + OTHER_FUNCTION + "\"}");
assertEquals(Set.of(OTHER_FUNCTION, FUNCTION), Set.copyOf(lambda("POST", "/2015-03-31/functions",
"CreateFunction")));
setJsonBody("{\"Runtime\":\"nodejs20.x\"}");
assertEquals(List.of("*"), lambda("POST", "/2015-03-31/functions", "CreateFunction"));
}
@Test
void lambdaWebRoutesResolveTheFunctionRevisionOrEndpointTheyActOn() {
void webFunctionRoutesNameTheFunctionRevisionOrEndpointTheyActOn() {
String fn = "arn:aws:lambda:us-east-1:000000000000:web-function/app";
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app");
assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/revisions");
assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/list-endpoints");
assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/revisions/rev-abcde");
assertEquals(fn + "/revision/rev-abcde", builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/endpoints/prod");
assertEquals(fn + "/endpoint/prod", builder.build("lambda", ctx, "us-east-1", "000000000000"));
// A function named by its ARN keeps the account and region it names.
when(uriInfo.getPath()).thenReturn(
"/2025-03-07/web-functions/arn:aws:lambda:us-east-1:111122223333:web-function/app/endpoints/prod");
assertEquals("arn:aws:lambda:us-east-1:111122223333:web-function/app/endpoint/prod",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
// A revision or endpoint named by its ARN resolves to its id under the path's function.
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/revisions/"
+ "arn:aws:lambda:us-east-1:000000000000:web-function/app/revision/rev-abcde");
assertEquals(fn + "/revision/rev-abcde", builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions/app/endpoints/"
+ "arn:aws:lambda:us-east-1:000000000000:web-function/app/endpoint/prod");
assertEquals(fn + "/endpoint/prod", builder.build("lambda", ctx, "us-east-1", "000000000000"));
// The tag and policy routes carry the function ARN in the path.
when(uriInfo.getPath()).thenReturn("/2025-03-07/tags/" + fn);
assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/resource-policy/" + fn);
assertEquals(fn, builder.build("lambda", ctx, "us-east-1", "000000000000"));
// Listing functions, the account settings and creating a function name no resource.
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-functions");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-03-07/web-account-settings");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
assertEquals(List.of(fn), lambda("GET", "/2025-03-07/web-functions/app", "GetWebFunction"));
assertEquals(List.of(fn), lambda("POST", "/2025-03-07/web-functions/app/list-revisions",
"ListWebFunctionRevisions"));
assertEquals(List.of(fn), lambda("POST", "/2025-03-07/web-functions/app/list-endpoints",
"ListWebFunctionEndpoints"));
assertEquals(List.of(fn + "/revision/rev-abcde"), lambda("GET",
"/2025-03-07/web-functions/app/revisions/rev-abcde", "GetWebFunctionRevision"));
assertEquals(List.of(fn + "/endpoint/prod"), lambda("GET", "/2025-03-07/web-functions/app/endpoints/prod",
"GetWebFunctionEndpoint"));
// The tag and policy routes carry the function's ARN.
assertEquals(List.of(fn), lambda("GET", "/2025-03-07/tags/" + fn.replace("/", "%2F"), "ListTags"));
assertEquals(List.of(fn), lambda("GET", "/2025-03-07/resource-policy/" + fn.replace("/", "%2F"),
"GetResourcePolicy"));
// Listing functions and the account settings name no resource.
assertEquals(List.of("*"), lambda("POST", "/2025-03-07/web-functions", "ListWebFunctions"));
assertEquals(List.of("*"), lambda("GET", "/2025-03-07/web-account-settings", "GetWebAccountSettings"));
}
@Test
void lambdaMicrovmAndNetworkConnectorRoutesResolveTheImageOrConnectorTheyName() {
void microvmImageAndNetworkConnectorRoutesNameTheImageOrConnectorTheyActOn() {
String image = "arn:aws:lambda:us-east-1:000000000000:microvm-image:img";
when(uriInfo.getPath()).thenReturn("/2025-09-09/microvm-images/img");
assertEquals(image, builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-09-09/microvm-images/img/versions/1/builds/b-1");
assertEquals(image, builder.build("lambda", ctx, "us-east-1", "000000000000"));
// An image named by its ARN is looked up by its name in the request's account and Region, so that
// is the resource checked, whatever account or Region the ARN names.
when(uriInfo.getPath()).thenReturn(
"/2025-09-09/microvm-images/arn:aws:lambda:eu-west-1:111122223333:microvm-image:shared/versions");
assertEquals("arn:aws:lambda:us-east-1:000000000000:microvm-image:shared",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2026-04-04/network-connectors/nc-1/versions");
assertEquals("arn:aws:lambda:us-east-1:000000000000:network-connector:nc-1",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
// RunMicrovm runs the image its imageIdentifier names, read as the service reads it.
when(ctx.getMethod()).thenReturn("POST");
when(uriInfo.getPath()).thenReturn("/2025-09-09/microvms");
assertEquals(List.of(image), lambda("GET", "/2025-09-09/microvm-images/img", "GetMicrovmImage"));
assertEquals(List.of(image), lambda("GET", "/2025-09-09/microvm-images/img/versions/1/builds/b-1",
"GetMicrovmImageBuild"));
// An image named by its ARN keeps the account and Region it names, beside the caller's of that name.
String shared = "arn:aws:lambda:eu-west-1:111122223333:microvm-image:shared";
assertEquals(Set.of(shared, "arn:aws:lambda:eu-west-1:000000000000:microvm-image:shared",
"arn:aws:lambda:us-east-1:111122223333:microvm-image:shared",
"arn:aws:lambda:us-east-1:000000000000:microvm-image:shared"),
Set.copyOf(lambda("GET", "/2025-09-09/microvm-images/" + shared + "/versions",
"ListMicrovmImageVersions")));
assertEquals(List.of("arn:aws:lambda:us-east-1:000000000000:network-connector:nc-1"),
lambda("GET", "/2026-04-04/network-connectors/nc-1/versions", "ListNetworkConnectorVersions"));
// RunMicrovm runs the image its imageIdentifier names.
setJsonBody("{\"imageIdentifier\":\"img\"}");
assertEquals(image, builder.build("lambda", ctx, "us-east-1", "000000000000"));
setJsonBody("{\"imageIdentifier\":\"arn:aws:lambda:eu-west-1:111122223333:microvm-image:img\"}");
assertEquals(image, builder.build("lambda", ctx, "us-east-1", "000000000000"));
assertEquals(List.of(image), lambda("POST", "/2025-09-09/microvms", "RunMicrovm"));
setJsonBody("{}");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
// A managed image's versions are checked against the managed image, which aws owns.
when(ctx.getMethod()).thenReturn("GET");
when(uriInfo.getPath()).thenReturn("/2025-09-09/managed-microvm-images/al2023-1/versions");
assertEquals("arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
// Creating or listing either, listing MicroVMs, a managed image there is none of, and a MicroVM the
// account does not hold name no resource here.
for (String path : new String[] {"/2025-09-09/microvm-images", "/2025-09-09/managed-microvm-images",
"/2025-09-09/managed-microvm-images/other/versions", "/2025-09-09/microvms",
"/2025-09-09/microvms/vm-1", "/2026-04-04/network-connectors"}) {
when(uriInfo.getPath()).thenReturn(path);
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"), path);
}
}
@Test
void lambdaMappingConfigAndLayerRoutesResolveTheResourceTheyName() {
when(ctx.getMethod()).thenReturn("GET");
request("/2015-03-31/event-source-mappings/14e0db71-5d35-4eb5-b481-8945cf9d10c2");
assertEquals("arn:aws:lambda:us-east-1:000000000000:event-source-mapping:14e0db71-5d35-4eb5-b481-8945cf9d10c2",
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
// A config is looked up by the id that ends its ARN, in the request's account and Region.
String config = "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0123456789abcdef0";
for (String path : new String[] {"/2020-04-22/code-signing-configs/" + config,
"/2020-04-22/code-signing-configs/" + config + "/functions",
"/2020-04-22/code-signing-configs/arn:aws:lambda:eu-west-1:111122223333:code-signing-config:"
+ "csc-0123456789abcdef0"}) {
request(path);
assertEquals(config, builder.build("lambda", ctx, "us-east-1", ACCOUNT), path);
}
// A layer version, its policy and its permissions.
String version = "arn:aws:lambda:us-east-1:000000000000:layer:my-layer:3";
for (String path : new String[] {"/2018-10-31/layers/my-layer/versions/3",
"/2018-10-31/layers/my-layer/versions/3/policy",
"/2018-10-31/layers/my-layer/versions/3/policy/statement-1"}) {
String operation = path.endsWith("/statement-1") ? "RemoveLayerVersionPermission"
: path.endsWith("/policy") ? "GetLayerVersionPolicy" : "GetLayerVersion";
when(ctx.getMethod()).thenReturn(operation.startsWith("Remove") ? "DELETE" : "GET");
request(path);
assertEquals(version, layerResource(operation, "us-east-1"), path);
}
// GetLayerVersion accepts an unversioned ARN and checks the version that it names.
String named = "arn:aws:lambda:us-east-1:000000000000:layer:my-layer";
when(ctx.getMethod()).thenReturn("GET");
request("/2018-10-31/layers/" + named + "/versions/3");
assertEquals(version, layerResource("GetLayerVersion", "us-east-1"));
// GetLayerVersionByArn reads the version its Arn names.
request("/2018-10-31/layers");
queryParams.putSingle("find", "LayerVersion");
queryParams.putSingle("Arn", version);
assertEquals(version, layerResource("GetLayerVersionByArn", "us-east-1"));
queryParams.clear();
// Listing layers, a layer's versions or configs, and creating a config, name no resource.
for (String path : new String[] {"/2018-10-31/layers", "/2018-10-31/layers/my-layer/versions",
"/2020-04-22/code-signing-configs"}) {
request(path);
String operation = path.endsWith("/versions") ? "ListLayerVersions" : "ListLayers";
assertEquals("*", path.contains("/layers")
? layerResource(operation, "us-east-1")
: builder.build("lambda", ctx, "us-east-1", ACCOUNT), path);
}
when(ctx.getMethod()).thenReturn("POST");
request("/2020-04-22/code-signing-configs");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", ACCOUNT));
// PublishLayerVersion makes a version of the layer, so it is checked against the layer.
request("/2018-10-31/layers/my-layer/versions");
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer",
layerResource("PublishLayerVersion", "us-east-1"));
// A function's own settings, such as its concurrency or versions, are checked against the function.
request("/2015-03-31/functions/my-function/versions");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
when(ctx.getMethod()).thenReturn("PUT");
request("/2017-10-31/functions/my-function/concurrency");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", ACCOUNT));
}
@ParameterizedTest
@CsvSource({"aws,us-west-2,us-east-1", "aws-cn,cn-northwest-1,cn-north-1",
"aws-us-gov,us-gov-east-1,us-gov-west-1"})
void lambdaLayerArnLookupKeepsItsCoordinatesAndNormalizesTheVersion(
String partition, String layerRegion, String requestRegion) {
String layer = "arn:" + partition + ":lambda:" + layerRegion + ":111122223333:layer:shared";
when(ctx.getMethod()).thenReturn("GET");
request("/2018-10-31/layers/" + layer.replace(":", "%3A") + "/versions/01");
assertEquals(layer + ":1", layerResource("GetLayerVersion", requestRegion));
}
@Test
void otherLayerRoutesKeepTheirLiteralNameResource() {
String layer = "arn:aws:lambda:us-west-2:111122223333:layer:shared";
String expected = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":layer:" + layer + ":1";
when(ctx.getMethod()).thenReturn("DELETE");
request("/2018-10-31/layers/" + layer + "/versions/01");
assertEquals(expected, layerResource("DeleteLayerVersion", "us-east-1"));
when(ctx.getMethod()).thenReturn("GET");
request("/2018-10-31/layers/" + layer + "/versions/01/policy");
assertEquals(expected, layerResource("GetLayerVersionPolicy", "us-east-1"));
}
@Test
void aLayerVersionIsReadAsLambdaReadsItsNameAndNumber() {
// Lambda parses the version number, so 01 is version 1, and the router keeps an encoded / inside the
// layer's name, so the layer checked is the one Lambda looks up.
when(ctx.getMethod()).thenReturn("GET");
request("/2018-10-31/layers/my-layer/versions/01");
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer:1",
layerResource("GetLayerVersion", "us-east-1"));
request("/2018-10-31/layers/my%2Flayer/versions/3/policy");
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my/layer:3",
layerResource("GetLayerVersionPolicy", "us-east-1"));
when(ctx.getMethod()).thenReturn("POST");
request("/2018-10-31/layers/my%2Flayer/versions");
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my/layer",
layerResource("PublishLayerVersion", "us-east-1"));
// GetLayerVersionByArn parses the number the same way.
when(ctx.getMethod()).thenReturn("GET");
request("/2018-10-31/layers");
queryParams.putSingle("find", "LayerVersion");
queryParams.putSingle("Arn", "arn:aws:lambda:us-east-1:000000000000:layer:my-layer:01");
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer:1",
layerResource("GetLayerVersionByArn", "us-east-1"));
}
private String layerResource(String operation, String region) {
return builder.buildResources("lambda", "lambda:" + operation, ctx, region, ACCOUNT,
AwsRegions.partitionFor(region)).getFirst();
assertEquals(List.of("*"), lambda("POST", "/2025-09-09/microvms", "RunMicrovm"));
// Listing images, connectors and MicroVMs names no resource.
assertEquals(List.of("*"), lambda("GET", "/2025-09-09/microvm-images", "ListMicrovmImages"));
assertEquals(List.of("*"), lambda("GET", "/2025-09-09/microvms", "ListMicrovms"));
assertEquals(List.of("*"), lambda("GET", "/2026-04-04/network-connectors", "ListNetworkConnectors"));
}
/** An action on a running MicroVM is checked on the image it runs, which Lambda gives for the caller's MicroVM. */
@Test
void anActionOnARunningMicrovmIsCheckedAgainstTheImageItRuns() {
String image = "arn:aws:lambda:us-east-1:000000000000:microvm-image:img";
@@ -2286,15 +2140,92 @@ class ResourceArnBuilderTest {
LambdaMicrovmsService microvms = mock(LambdaMicrovmsService.class);
when(microvms.findMicrovm(any(), any())).thenReturn(Optional.empty());
when(microvms.findMicrovm("us-east-1", "microvm-1")).thenReturn(Optional.of(vm));
ResourceArnBuilder backed = backedBy(microvms);
@SuppressWarnings("unchecked")
Instance<LambdaMicrovmsService> instance = mock(Instance.class);
when(instance.isResolvable()).thenReturn(true);
when(instance.get()).thenReturn(microvms);
ResourceArnBuilder backed = reading(new LambdaStoredResourceArns(null, instance));
for (String path : new String[] {"/2025-09-09/microvms/microvm-1",
"/2025-09-09/microvms/microvm-1/suspend", "/2025-09-09/microvms/microvm-1/auth-token"}) {
when(uriInfo.getPath()).thenReturn(path);
assertEquals(image, backed.build("lambda", ctx, "us-east-1", "000000000000"), path);
}
when(uriInfo.getPath()).thenReturn("/2025-09-09/microvms/microvm-2");
assertEquals("*", backed.build("lambda", ctx, "us-east-1", "000000000000"));
assertEquals(List.of(image), lambda(backed, "GET", "/2025-09-09/microvms/microvm-1", "GetMicrovm"));
assertEquals(List.of(image), lambda(backed, "POST", "/2025-09-09/microvms/microvm-1/suspend",
"SuspendMicrovm"));
assertEquals(List.of(image), lambda(backed, "POST", "/2025-09-09/microvms/microvm-1/auth-token",
"CreateMicrovmAuthToken"));
assertEquals(List.of("*"), lambda(backed, "GET", "/2025-09-09/microvms/microvm-2", "GetMicrovm"));
}
@Test
void mappingConfigAndLayerRoutesNameTheResourceTheyActOn() {
assertEquals(List.of("arn:aws:lambda:us-east-1:000000000000:event-source-mapping:"
+ "14e0db71-5d35-4eb5-b481-8945cf9d10c2"),
lambda("GET", "/2015-03-31/event-source-mappings/14e0db71-5d35-4eb5-b481-8945cf9d10c2",
"GetEventSourceMapping"));
String config = "arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0123456789abcdef0";
assertEquals(List.of(config), lambda("GET", "/2020-04-22/code-signing-configs/" + config,
"GetCodeSigningConfig"));
assertEquals(List.of(config), lambda("GET", "/2020-04-22/code-signing-configs/" + config + "/functions",
"ListFunctionsByCodeSigningConfig"));
// A layer version, its policy and its permissions.
String version = "arn:aws:lambda:us-east-1:000000000000:layer:my-layer:3";
assertEquals(version, layerResource("GetLayerVersion", "us-east-1", "GET",
"/2018-10-31/layers/my-layer/versions/3"));
assertEquals(version, layerResource("GetLayerVersionPolicy", "us-east-1", "GET",
"/2018-10-31/layers/my-layer/versions/3/policy"));
assertEquals(version, layerResource("RemoveLayerVersionPermission", "us-east-1", "DELETE",
"/2018-10-31/layers/my-layer/versions/3/policy/statement-1"));
// GetLayerVersion accepts an unversioned ARN and checks the version that it names.
assertEquals(version, layerResource("GetLayerVersion", "us-east-1", "GET",
"/2018-10-31/layers/arn:aws:lambda:us-east-1:000000000000:layer:my-layer/versions/3"));
// GetLayerVersionByArn reads the version its Arn names.
queryParams.putSingle("find", "LayerVersion");
queryParams.putSingle("Arn", version);
assertEquals(version, layerResource("GetLayerVersionByArn", "us-east-1", "GET", "/2018-10-31/layers"));
queryParams.clear();
// Listing layers, a layer's versions or configs, and creating a config, name no resource.
assertEquals("*", layerResource("ListLayers", "us-east-1", "GET", "/2018-10-31/layers"));
assertEquals("*", layerResource("ListLayerVersions", "us-east-1", "GET", "/2018-10-31/layers/my-layer/versions"));
assertEquals(List.of("*"), lambda("GET", "/2020-04-22/code-signing-configs", "ListCodeSigningConfigs"));
assertEquals(List.of("*"), lambda("POST", "/2020-04-22/code-signing-configs", "CreateCodeSigningConfig"));
// PublishLayerVersion makes a version of the layer, so it is checked against the layer.
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer",
layerResource("PublishLayerVersion", "us-east-1", "POST", "/2018-10-31/layers/my-layer/versions"));
}
@ParameterizedTest
@CsvSource({"aws,us-west-2,us-east-1", "aws-cn,cn-northwest-1,cn-north-1",
"aws-us-gov,us-gov-east-1,us-gov-west-1"})
void lambdaLayerArnLookupKeepsItsCoordinatesAndNormalizesTheVersion(
String partition, String layerRegion, String requestRegion) {
String layer = "arn:" + partition + ":lambda:" + layerRegion + ":111122223333:layer:shared";
String sent = "/2018-10-31/layers/" + layer.replace(":", "%3A") + "/versions/01";
assertEquals(layer + ":1", layerResource("GetLayerVersion", requestRegion, "GET", sent));
assertEquals(layer + ":1", layerResource("DeleteLayerVersion", requestRegion, "DELETE", sent));
}
@Test
void aLayerVersionIsReadAsLambdaReadsItsNameAndNumber() {
// Lambda parses the version number, so 01 is version 1, and the router keeps an encoded / inside the
// layer's name, so the layer checked is the one Lambda looks up.
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer:1",
layerResource("GetLayerVersion", "us-east-1", "GET", "/2018-10-31/layers/my-layer/versions/01"));
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my/layer:3",
layerResource("GetLayerVersionPolicy", "us-east-1", "GET",
"/2018-10-31/layers/my%2Flayer/versions/3/policy"));
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my/layer",
layerResource("PublishLayerVersion", "us-east-1", "POST", "/2018-10-31/layers/my%2Flayer/versions"));
// GetLayerVersionByArn parses the number the same way.
queryParams.putSingle("find", "LayerVersion");
queryParams.putSingle("Arn", "arn:aws:lambda:us-east-1:000000000000:layer:my-layer:01");
assertEquals("arn:aws:lambda:us-east-1:000000000000:layer:my-layer:1",
layerResource("GetLayerVersionByArn", "us-east-1", "GET", "/2018-10-31/layers"));
}
private String layerResource(String operation, String region, String method, String sent) {
when(ctx.getMethod()).thenReturn(method);
request(sent);
return builder.buildResources("lambda", "lambda:" + operation, ctx, region, ACCOUNT,
AwsRegions.partitionFor(region)).getFirst();
}
@Test
@@ -2537,44 +2468,17 @@ class ResourceArnBuilderTest {
assertNull(builder.taggedArn(ctx));
}
/** A tag route names the resource by its ARN, which keeps its account and Region beside the caller's. */
@Test
void lambdaTagRoutesAndAStreamingInvokeResolveTheResourceTheyName() {
// Tagging acts on the caller's own function, image or connector of the ARN's Region and name,
// whatever account the ARN names, so that is the resource checked.
when(uriInfo.getPath()).thenReturn("/2017-03-31/tags/arn:aws:lambda:eu-west-1:111122223333:function:shared");
assertEquals("arn:aws:lambda:eu-west-1:000000000000:function:shared",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn(
"/2017-03-31/tags/arn:aws:lambda:eu-west-1:111122223333:microvm-image:img");
assertEquals("arn:aws:lambda:eu-west-1:000000000000:microvm-image:img",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn(
"/2017-03-31/tags/arn:aws:lambda:eu-west-1:111122223333:network-connector:nc-1");
assertEquals("arn:aws:lambda:eu-west-1:000000000000:network-connector:nc-1",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
// A mapping's ARN has to name it exactly, and Lambda refuses a qualified function, a running MicroVM
// and an image in no Region, so these stay as written.
String mapping = "arn:aws:lambda:us-east-1:111122223333:event-source-mapping:"
+ "14e0db71-5d35-4eb5-b481-8945cf9d10c2";
for (String arn : new String[] {mapping, "arn:aws:lambda:us-east-1:111122223333:function:shared:prod",
"arn:aws:lambda:us-east-1:111122223333:microvm:vm-1", "arn:aws:lambda::111122223333:microvm-image:img"}) {
when(uriInfo.getPath()).thenReturn("/2017-03-31/tags/" + arn);
assertEquals(arn, builder.build("lambda", ctx, "us-east-1", "000000000000"), arn);
}
// A version-qualified connector is no tag target, so it stays as written rather than naming the connector.
String qualified = "arn:aws:lambda:eu-west-1:111122223333:network-connector:nc-1:1";
when(uriInfo.getPath()).thenReturn("/2017-03-31/tags/" + qualified);
assertEquals(qualified, builder.build("lambda", ctx, "us-east-1", "000000000000"));
// A target without the arn: prefix names no resource.
when(uriInfo.getPath()).thenReturn("/2017-03-31/tags/x:y:z:eu-west-1:microvm-image:img");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2017-03-31/tags/shared");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
// A streaming invoke is an invoke: its qualifier and the account its function ARN names count.
when(uriInfo.getPath()).thenReturn("/2021-11-15/functions/my-function/response-streaming-invocations");
queryParams.putSingle("Qualifier", "prod");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:prod",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
void lambdaTagRoutesNameTheResourceTheirArnNames() {
String shared = "arn:aws:lambda:eu-west-1:111122223333:function:shared";
assertTrue(lambda("GET", "/2017-03-31/tags/" + shared, "ListTags").contains(shared));
String image = "arn:aws:lambda:eu-west-1:111122223333:microvm-image:img";
assertTrue(lambda("POST", "/2017-03-31/tags/" + image, "TagResource").contains(image));
String mapping = "arn:aws:lambda:us-east-1:111122223333:event-source-mapping:14e0db71-5d35-4eb5-b481-8945cf9d10c2";
assertTrue(lambda("GET", "/2017-03-31/tags/" + mapping, "ListTags").contains(mapping));
// A target that is no Lambda ARN names no resource.
assertEquals(List.of("*"), lambda("GET", "/2017-03-31/tags/shared", "ListTags"));
}
@Test
@@ -2590,95 +2494,30 @@ class ResourceArnBuilderTest {
assertEquals("*", builder.build("pipes", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaRoutesOtherThanInvokeAreCheckedAgainstTheCallersUnqualifiedFunction() {
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1/code");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/111122223333:function:my-function/policy");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/my-function");
queryParams.putSingle("Qualifier", "1");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaQualifiedReadsByArnAreCheckedInTheAccountTheyRead() {
when(ctx.getMethod()).thenReturn("GET");
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1");
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function/configuration");
queryParams.putSingle("Qualifier", "live");
assertEquals("arn:aws:lambda:us-east-1:111122223333:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaReadsThatDoNotFollowTheArnAreCheckedOnTheCallersFunction() {
when(ctx.getMethod()).thenReturn("GET");
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/111122223333:function:my-function:1");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1/policy");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(ctx.getMethod()).thenReturn("DELETE");
when(uriInfo.getPath()).thenReturn(
"/2015-03-31/functions/arn:aws:lambda:us-east-1:111122223333:function:my-function:1");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaReferenceLambdaRefusesIsNamedAsGiven() {
when(uriInfo.getPath()).thenReturn("/2015-03-31/functions/not:a:function:ref/invocations");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:not:a:function:ref",
builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
/** A durable execution's actions are checked on the execution its ARN names, which a client sends encoded. */
@Test
void lambdaDurableExecutionRoutesNameTheExecution() {
when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-executions/arn:aws:lambda:us-east-1:000000000000:"
+ "function:my-function:$LATEST/durable-execution/run-1/0b1c/stop");
String arn = builder.build("lambda", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:$LATEST/durable-execution/run-1/0b1c",
arn);
String execution = "arn:aws:lambda:us-east-1:000000000000:function:my-function:1/durable-execution/run-1/0b1c";
String sent = execution.replace("/", "%2F");
assertEquals(List.of(execution), lambda("POST", "/2025-12-01/durable-executions/" + sent + "/stop",
"StopDurableExecution"));
assertEquals(List.of(execution), lambda("GET", "/2025-12-01/durable-executions/" + sent,
"GetDurableExecution"));
}
/** Lambda authorizes a callback request against the ARN of the durable execution that created the callback. */
@Test
void lambdaDurableCallbackRoutesNameTheExecutionInTheCallbackId() {
String executionArn = "arn:aws:lambda:us-east-1:000000000000:function:my-function:1/durable-execution/run-1/0b1c";
String callbackId = Base64.getEncoder().encodeToString((executionArn + "|c1|nonce").getBytes(StandardCharsets.UTF_8));
when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-execution-callbacks/" + callbackId + "/succeed");
assertEquals(executionArn, builder.build("lambda", ctx, "us-east-1", "000000000000"));
when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-execution-callbacks/not-a-callback/heartbeat");
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaDurableExecutionGetNamesTheExecution() {
when(uriInfo.getPath()).thenReturn("/2025-12-01/durable-executions/arn:aws:lambda:us-east-1:000000000000:"
+ "function:my-function:1/durable-execution/run-1/0b1c");
String arn = builder.build("lambda", ctx, "us-east-1", "000000000000");
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-function:1/durable-execution/run-1/0b1c", arn);
void lambdaDurableCallbackRoutesNameTheExecutionOfTheCallback() {
String execution = "arn:aws:lambda:us-east-1:000000000000:function:my-function:1/durable-execution/run-1/0b1c";
String callbackId = Base64.getEncoder().encodeToString((execution + "|c1|nonce").getBytes(StandardCharsets.UTF_8));
@SuppressWarnings("unchecked")
Instance<LambdaMicrovmsService> none = mock(Instance.class);
ResourceArnBuilder backed = reading(new LambdaStoredResourceArns(null, none));
assertEquals(List.of(execution), lambda(backed, "POST",
"/2025-12-01/durable-execution-callbacks/" + callbackId.replace("/", "%2F") + "/succeed",
"SendDurableExecutionCallbackSuccess"));
assertEquals(List.of("*"), lambda(backed, "POST", "/2025-12-01/durable-execution-callbacks/not-a-callback/heartbeat",
"SendDurableExecutionCallbackHeartbeat"));
}
// ── EKS ──────────────────────────────────────────────────────────────────────
@@ -154,9 +154,11 @@ class LambdaCrossAccountInvokeIntegrationTest {
String caller = createUser(CALLER, "invoker-" + suffix(), INVOKE_ANYTHING);
invoke(caller, functionArn + ":live").statusCode(200);
invoke(caller, functionArn, "live").statusCode(200);
invoke(caller, functionArn).statusCode(403);
invoke(caller, functionArn + ":1").statusCode(403);
// The Service Reference gives InvokeFunction the function alone, so a Qualifier names nothing for it: the
// call is checked on the function as named, which the alias grant does not cover.
invoke(caller, functionArn, "live").statusCode(403);
}
@Test
@@ -224,17 +226,26 @@ class LambdaCrossAccountInvokeIntegrationTest {
*/
@Test
void aQualifiedReadOfAnotherAccountsFunctionNeedsItsGrant() {
String foreignArn = createFunction(OWNER, "read-" + suffix());
String name = "read-" + suffix();
String foreignArn = createFunction(OWNER, name);
publishVersionAndAlias(OWNER, name, "live");
String user = createUser(CALLER, "reader-" + suffix(), """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"lambda:GetFunction","Resource":"*"}]}""");
lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":$LATEST").then().statusCode(403);
lambda(user).queryParam("Qualifier", "$LATEST").get("/2015-03-31/functions/{name}", foreignArn)
lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":live").then().statusCode(403);
lambda(user).queryParam("Qualifier", "live").get("/2015-03-31/functions/{name}", foreignArn)
.then().statusCode(403);
// An alias in the function's name is part of the function checked, so a grant on the function does not
// cover it, and one on the alias does; a Qualifier names nothing for GetFunction, which the Service
// Reference gives the function alone, so the grant on the function covers that read.
addPermission(OWNER, foreignArn, null, Map.of("Principal", CALLER, "Action", "lambda:GetFunction"));
lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":$LATEST")
lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":live").then().statusCode(403);
lambda(user).queryParam("Qualifier", "live").get("/2015-03-31/functions/{name}", foreignArn)
.then().statusCode(200).body("Configuration.FunctionArn", startsWith(foreignArn));
addPermission(OWNER, foreignArn, "live", Map.of("Principal", CALLER, "Action", "lambda:GetFunction"));
lambda(user).get("/2015-03-31/functions/{name}", foreignArn + ":live")
.then().statusCode(200).body("Configuration.FunctionArn", startsWith(foreignArn));
}
@@ -0,0 +1,103 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.LambdaException;
import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.services.lambda.LambdaLayerFixtures.publishLayerVersion;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class LambdaDeleteLayerArnIamIntegrationTest {
private static final String ACCOUNT = "741681410023";
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@CsvSource({"us-east-1,us-east-1,false", "us-east-1,us-east-1,true",
"cn-north-1,cn-north-1,true", "us-gov-west-1,us-gov-west-1,true", "us-west-2,us-east-1,true"})
void deletionChecksTheVersionNamedByTheSelector(String layerRegion, String requestRegion, boolean arnSelector)
throws Exception {
String name = "layer-delete-iam-" + UUID.randomUUID();
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, Region.of(layerRegion), endpoint)) {
PublishLayerVersionResponse published = publishLayerVersion(
owner, name, ACCOUNT, Region.of(layerRegion), endpoint, cleanup);
String user = "layer-deleter-" + UUID.randomUUID();
String authorization = auth(ACCOUNT, requestRegion, "iam");
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, user);
String selector = arnSelector ? published.layerArn() : name;
String resource = published.layerVersionArn();
try (LambdaClient caller = AwsTestClients.create(LambdaClient.builder(),
credentials.accessKeyId(), credentials.secretAccessKey(), Region.of(requestRegion), endpoint)) {
policy(authorization, user, resource + "-other", null);
denied(caller, selector, published.version());
policy(authorization, user, "*", resource);
denied(caller, selector, published.version());
assertEquals(resource, owner.getLayerVersion(request -> request
.layerName(name).versionNumber(published.version())).layerVersionArn());
policy(authorization, user, resource, null);
assertEquals(204, caller.deleteLayerVersion(request -> request.layerName(selector)
.versionNumber(published.version())).sdkHttpResponse().statusCode());
assertThrows(ResourceNotFoundException.class, () -> owner.getLayerVersion(request -> request
.layerName(name).versionNumber(published.version())));
}
}
}
private void policy(String authorization, String user, String allowed, String denied) {
String statements = """
{
"Effect": "Allow",
"Action": "lambda:DeleteLayerVersion",
"Resource": "%s"
}
""".formatted(allowed);
if (denied != null) {
statements += "," + """
{
"Effect": "Deny",
"Action": "lambda:DeleteLayerVersion",
"Resource": "%s"
}
""".formatted(denied);
}
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, user, "layer-delete",
"""
{
"Version": "2012-10-17",
"Statement": [%s]
}
""".formatted(statements));
}
private static void denied(LambdaClient caller, String selector, long version) {
LambdaException denied = assertThrows(LambdaException.class, () -> caller.deleteLayerVersion(request ->
request.layerName(selector).versionNumber(version)));
assertEquals(403, denied.statusCode());
}
}
@@ -0,0 +1,111 @@
package io.floci.aws.services.lambda;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.LambdaException;
import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.services.lambda.LambdaLayerFixtures.publishLayerVersion;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class LambdaDeleteLayerArnIntegrationTest {
private static final String ACCOUNT = "741681410021";
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@CsvSource({"us-east-1,false", "us-east-1,true", "cn-north-1,false", "cn-north-1,true",
"us-gov-west-1,false", "us-gov-west-1,true"})
void deletesOnlyTheSelectedVersionAndItsArchive(String region, boolean arnSelector) throws Exception {
try (LambdaClient client = client(ACCOUNT, Region.of(region))) {
String name = "layer-delete-" + UUID.randomUUID();
PublishLayerVersionResponse first = publishLayerVersion(
client, name, ACCOUNT, Region.of(region), endpoint, cleanup);
PublishLayerVersionResponse second = publishLayerVersion(
client, name, ACCOUNT, Region.of(region), endpoint, cleanup);
String location = client.getLayerVersion(request -> request.layerName(name)
.versionNumber(first.version())).content().location();
String selector = arnSelector ? first.layerArn() : name;
assertEquals(204, client.deleteLayerVersion(request -> request.layerName(selector)
.versionNumber(first.version())).sdkHttpResponse().statusCode());
assertThrows(ResourceNotFoundException.class, () -> client.getLayerVersion(request -> request
.layerName(name).versionNumber(first.version())));
given().urlEncodingEnabled(false).get(location).then().statusCode(404);
assertEquals(second.layerVersionArn(), client.getLayerVersion(request -> request.layerName(name)
.versionNumber(second.version())).layerVersionArn());
assertEquals(204, client.deleteLayerVersion(request -> request.layerName(selector)
.versionNumber(first.version())).sdkHttpResponse().statusCode());
}
}
@Test
void arnDeletionUsesTheLayerRegionAndPreservesTheRequestRegion() throws Exception {
try (LambdaClient owner = client(ACCOUNT, Region.US_WEST_2);
LambdaClient caller = client(ACCOUNT, Region.US_EAST_1)) {
String name = "layer-regional-delete-" + UUID.randomUUID();
PublishLayerVersionResponse stored = publishLayerVersion(
owner, name, ACCOUNT, Region.US_WEST_2, endpoint, cleanup);
PublishLayerVersionResponse local = publishLayerVersion(
caller, name, ACCOUNT, Region.US_EAST_1, endpoint, cleanup);
String location = owner.getLayerVersion(request -> request.layerName(name)
.versionNumber(stored.version())).content().location();
caller.deleteLayerVersion(request -> request.layerName(stored.layerArn()).versionNumber(stored.version()));
assertThrows(ResourceNotFoundException.class, () -> owner.getLayerVersion(request -> request
.layerName(name).versionNumber(stored.version())));
given().urlEncodingEnabled(false).get(location).then().statusCode(404);
assertEquals(local.layerVersionArn(), caller.getLayerVersion(request -> request
.layerName(name).versionNumber(local.version())).layerVersionArn());
}
}
@Test
void foreignOrMalformedSelectorsCannotDeleteOwnedVersions() throws Exception {
String otherAccount = "741681410022";
try (LambdaClient client = client(ACCOUNT, Region.US_EAST_1);
LambdaClient other = client(otherAccount, Region.US_EAST_1)) {
String name = "layer-isolated-delete-" + UUID.randomUUID();
PublishLayerVersionResponse owned = publishLayerVersion(
client, name, ACCOUNT, Region.US_EAST_1, endpoint, cleanup);
PublishLayerVersionResponse foreign = publishLayerVersion(
other, name, otherAccount, Region.US_EAST_1, endpoint, cleanup);
client.deleteLayerVersion(request -> request.layerName(foreign.layerArn()).versionNumber(foreign.version()));
for (String invalid : new String[] {owned.layerVersionArn(),
owned.layerArn().replace("arn:aws:", "arn:aws-cn:")}) {
LambdaException error = assertThrows(LambdaException.class, () -> client.deleteLayerVersion(request ->
request.layerName(invalid).versionNumber(owned.version())));
assertEquals(400, error.statusCode());
}
assertEquals(owned.layerVersionArn(), client.getLayerVersion(request -> request
.layerName(name).versionNumber(owned.version())).layerVersionArn());
assertEquals(foreign.layerVersionArn(), other.getLayerVersion(request -> request
.layerName(name).versionNumber(foreign.version())).layerVersionArn());
}
}
private LambdaClient client(String account, Region region) {
return AwsTestClients.create(LambdaClient.builder(), account, region, endpoint);
}
}
@@ -3,9 +3,16 @@ package io.floci.aws.services.lambda;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.services.lambda.model.LambdaLayerVersion;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.PartitionCleanup;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.zip.ZipEntry;
@@ -24,6 +31,20 @@ public final class LambdaLayerFixtures {
return bytes.toByteArray();
}
public static PublishLayerVersionResponse publishLayerVersion(
LambdaClient client, String name, String account, Region region, URI endpoint, PartitionCleanup cleanup)
throws IOException {
byte[] archive = layerArchive();
PublishLayerVersionResponse published = client.publishLayerVersion(request -> request.layerName(name)
.content(content -> content.zipFile(SdkBytes.fromByteArray(archive))));
cleanup.register(() -> {
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), account, region, endpoint)) {
owner.deleteLayerVersion(request -> request.layerName(name).versionNumber(published.version()));
}
});
return published;
}
public static LambdaLayerService accountScopedService(
String defaultAccount, String region, Map<String, LambdaLayerVersion> layersByAccount) {
AccountAwareStorageBackend<LambdaLayerVersion> storage = AccountAwareStorageBackend.inMemory(defaultAccount);
@@ -12,7 +12,6 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.LambdaException;
@@ -21,7 +20,7 @@ import software.amazon.awssdk.services.lambda.model.PublishLayerVersionResponse;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.services.lambda.LambdaLayerFixtures.layerArchive;
import static io.floci.aws.services.lambda.LambdaLayerFixtures.publishLayerVersion;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -53,17 +52,10 @@ class LambdaLayerNameArnIamIntegrationTest {
private void verifyLayerPermissions(Region layerRegion, Region requestRegion, boolean arnSelector) throws Exception {
String name = "layer-iam-" + UUID.randomUUID();
byte[] archive = layerArchive();
PublishLayerVersionResponse published;
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, layerRegion, endpoint)) {
published = owner.publishLayerVersion(request -> request.layerName(name)
.content(content -> content.zipFile(SdkBytes.fromByteArray(archive))));
published = publishLayerVersion(owner, name, ACCOUNT, layerRegion, endpoint, cleanup);
}
cleanup.register(() -> {
try (LambdaClient owner = AwsTestClients.create(LambdaClient.builder(), ACCOUNT, layerRegion, endpoint)) {
owner.deleteLayerVersion(request -> request.layerName(name).versionNumber(published.version()));
}
});
String user = "layer-reader-" + UUID.randomUUID();
String authorization = auth(ACCOUNT, requestRegion.id(), "iam");