fix(iam): check the Lambda MicroVM and network connector routes (#6122)

Under IAM enforcement no Lambda MicroVM or network connector route was
mapped to an IAM action, so every call went unchecked, and the roles
they take with it.

- Every MicroVM route (2025-09-09) and network connector route
  (2026-04-04) is mapped, and IamRestRouteCoverageTest now checks every
  operation of both models. An image or connector request is checked
  against microvm-image:<name> or network-connector:<id> in the
  request's account and Region, an identifier given as an ARN taken for
  its name, as the service looks it up. RunMicrovm is checked against
  the image its imageIdentifier names, an action on a running MicroVM
  against the image it runs, and a managed image's versions against
  that image, which aws owns. Creating an image or a connector and the
  list operations name no resource, so they are checked against *.
- Lambda's own tag routes, /2017-03-31/tags/<arn>, which MicroVM images
  share with functions, are mapped and checked against the resource
  they tag: the caller's own function, image or connector of the ARN's
  Region and name, whatever account the ARN names, as Lambda looks it
  up, a target without the arn: prefix read as the MicroVM tag handler
  reads it, and an event source mapping's ARN as written.
- iam:PassRole, to lambda.amazonaws.com as the Service Reference gives:
  CreateMicrovmImage and UpdateMicrovmImage (buildRoleArn), RunMicrovm
  (executionRoleArn), and CreateNetworkConnector and
  UpdateNetworkConnector (OperatorRole). This finishes the Lambda half
  of the follow-up on #5938.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-21 18:37:24 -05:00
1 parent 4eea01741f
commit 29384867cf
12 files changed
+474 -22

No files matched your search

+20 -10
View File
@@ -1253,18 +1253,26 @@ the route's rule miss.
The REST routes mapped to an action are those of S3, Lambda, API Gateway, SES v2, RDS Data,
Kinesis, EventBridge Scheduler and EventBridge Pipes. In Lambda they are the function, alias,
event source mapping, function URL, durable execution and Web Function routes,
`InvokeWithResponseStream` (checked as `lambda:InvokeFunction`) and `GetLayerVersionByArn`
(`lambda:GetLayerVersion`); the other Lambda routes, such as layers, versions, concurrency and
MicroVMs, are not mapped yet. API Gateway's management API, v1 and v2, is checked as `apigateway:`
and the HTTP method, `apigateway:GET`, `apigateway:POST` and so on, except
`RejectDomainNameAccessAssociation` (`apigateway:RejectAccessAssociation`) and `PutRoutingRule`
(`apigateway:UpdateRoutingRule`); the v2 routing rule, portal and portal product operations, which
AWS checks as actions of their own names, are not served.
event source mapping, function URL, durable execution, Web Function, MicroVM and network connector
routes, `InvokeWithResponseStream` (checked as `lambda:InvokeFunction`) and `GetLayerVersionByArn`
(`lambda:GetLayerVersion`); the other Lambda routes, such as layers, versions and concurrency, are
not mapped yet. API Gateway's management API, v1 and v2, is checked as `apigateway:` and the HTTP
method, `apigateway:GET`, `apigateway:POST` and so on, except `RejectDomainNameAccessAssociation`
(`apigateway:RejectAccessAssociation`) and `PutRoutingRule` (`apigateway:UpdateRoutingRule`); the
v2 routing rule, portal and portal product operations, which AWS checks as actions of their own
names, are not served.
A Scheduler request is checked against `schedule/<group>/<name>`, the group from the body's
`GroupName` on a create or an update, from `groupName` otherwise, and `default` when neither names
one, or `schedule-group/<name>`. A Pipes request is checked against `pipe/<name>`.
one, or `schedule-group/<name>`. A Pipes request is checked against `pipe/<name>`. A MicroVM image
or network connector request is checked against `microvm-image:<name>` or `network-connector:<id>`
in the request's account and Region, an identifier given as an ARN taken for its name, as the
service looks it up. `RunMicrovm` is checked against the image its `imageIdentifier` names, an
action on a running MicroVM against the image that MicroVM runs, and a managed image's versions
against that image, which `aws` owns. A Lambda tagging request, at `/2017-03-31/tags/<arn>`, is
checked against the caller's own function, MicroVM image or network connector of that ARN's Region
and name, whatever account the ARN names, as Lambda looks it up, and an event source mapping's ARN
as written.
The shared tagging routes, `/tags` and `/v1/tags`, hand a request to the service its ARN names,
and it is checked as that service, against that ARN, whatever scope it is signed with. The ARN is
@@ -1353,7 +1361,9 @@ pass a role to EC2 does not let the same role be passed to Lambda. The operation
role each passes:
- **Lambda:** `CreateFunction` and `UpdateFunctionConfiguration` (`Role`, when the request sets
it), `CreateWebFunction` and `CreateWebFunctionRevision` (the service configuration's
`executionRoleArn`), passed to `lambda.amazonaws.com`.
`executionRoleArn`), `CreateMicrovmImage` and `UpdateMicrovmImage` (`buildRoleArn`),
`RunMicrovm` (`executionRoleArn`), and `CreateNetworkConnector` and `UpdateNetworkConnector`
(`OperatorRole`), passed to `lambda.amazonaws.com`.
- **EC2:** `RunInstances`, `RequestSpotInstances`, `AssociateIamInstanceProfile`,
`ReplaceIamInstanceProfileAssociation`, `CreateLaunchTemplate` and `CreateLaunchTemplateVersion`
pass the roles of the instance profile they name, to `ec2.amazonaws.com`. `CreateFlowLogs` passes
@@ -148,6 +148,9 @@ final class PassedRoles {
case "events:PutTargets" -> fromJson(ctx, EVENTS, "Targets", "[]", "RoleArn");
case "scheduler:CreateSchedule", "scheduler:UpdateSchedule" -> fromJson(ctx, SCHEDULER, "Target", "RoleArn");
case "pipes:CreatePipe", "pipes:UpdatePipe" -> fromJson(ctx, PIPES, "RoleArn");
case "lambda:CreateMicrovmImage", "lambda:UpdateMicrovmImage" -> fromJson(ctx, LAMBDA, "buildRoleArn");
case "lambda:RunMicrovm" -> fromJson(ctx, LAMBDA, "executionRoleArn");
case "lambda:CreateNetworkConnector", "lambda:UpdateNetworkConnector" -> fromJson(ctx, LAMBDA, "OperatorRole");
case "cloudformation:CreateStack", "cloudformation:UpdateStack", "cloudformation:DeleteStack",
"cloudformation:CreateChangeSet", "cloudformation:ContinueUpdateRollback" ->
fromForm(ctx, CLOUDFORMATION, "RoleARN");
@@ -116,6 +116,40 @@ public class IamActionRegistry {
// Invoke and GetLayerVersion (iam-authorized-actions.json).
rule("lambda", "POST", ".*/functions/[^/]+/response-streaming-invocations$", "lambda:InvokeFunction"),
rule("lambda", "GET", "^/2018-10-31/layers$", "find", "LayerVersion", "lambda:GetLayerVersion"),
// Lambda MicroVMs (2025-09-09) and their tags, and network connectors (2026-04-04).
rule("lambda", "POST", "^/2025-09-09/microvms/[^/]+/auth-token$", "lambda:CreateMicrovmAuthToken"),
rule("lambda", "POST", "^/2025-09-09/microvms/[^/]+/shell-auth-token$", "lambda:CreateMicrovmShellAuthToken"),
rule("lambda", "POST", "^/2025-09-09/microvms/[^/]+/resume$", "lambda:ResumeMicrovm"),
rule("lambda", "POST", "^/2025-09-09/microvms/[^/]+/suspend$", "lambda:SuspendMicrovm"),
rule("lambda", "GET", "^/2025-09-09/microvms/[^/]+$", "lambda:GetMicrovm"),
rule("lambda", "DELETE", "^/2025-09-09/microvms/[^/]+$", "lambda:TerminateMicrovm"),
rule("lambda", "GET", "^/2025-09-09/microvms$", "lambda:ListMicrovms"),
rule("lambda", "POST", "^/2025-09-09/microvms$", "lambda:RunMicrovm"),
rule("lambda", "GET", "^/2025-09-09/microvm-images/[^/]+/versions/[^/]+/builds/[^/]+$",
"lambda:GetMicrovmImageBuild"),
rule("lambda", "GET", "^/2025-09-09/microvm-images/[^/]+/versions/[^/]+/builds$",
"lambda:ListMicrovmImageBuilds"),
rule("lambda", "GET", "^/2025-09-09/microvm-images/[^/]+/versions/[^/]+$", "lambda:GetMicrovmImageVersion"),
rule("lambda", "PATCH", "^/2025-09-09/microvm-images/[^/]+/versions/[^/]+$", "lambda:UpdateMicrovmImageVersion"),
rule("lambda", "DELETE", "^/2025-09-09/microvm-images/[^/]+/versions/[^/]+$", "lambda:DeleteMicrovmImageVersion"),
rule("lambda", "GET", "^/2025-09-09/microvm-images/[^/]+/versions$", "lambda:ListMicrovmImageVersions"),
rule("lambda", "GET", "^/2025-09-09/microvm-images/[^/]+$", "lambda:GetMicrovmImage"),
rule("lambda", "PUT", "^/2025-09-09/microvm-images/[^/]+$", "lambda:UpdateMicrovmImage"),
rule("lambda", "DELETE", "^/2025-09-09/microvm-images/[^/]+$", "lambda:DeleteMicrovmImage"),
rule("lambda", "GET", "^/2025-09-09/microvm-images$", "lambda:ListMicrovmImages"),
rule("lambda", "POST", "^/2025-09-09/microvm-images$", "lambda:CreateMicrovmImage"),
rule("lambda", "GET", "^/2025-09-09/managed-microvm-images/[^/]+/versions$",
"lambda:ListManagedMicrovmImageVersions"),
rule("lambda", "GET", "^/2025-09-09/managed-microvm-images$", "lambda:ListManagedMicrovmImages"),
rule("lambda", "GET", "^/2017-03-31/tags/.+", "lambda:ListTags"),
rule("lambda", "POST", "^/2017-03-31/tags/.+", "lambda:TagResource"),
rule("lambda", "DELETE", "^/2017-03-31/tags/.+", "lambda:UntagResource"),
rule("lambda", "GET", "^/2026-04-04/network-connectors/[^/]+/versions$", "lambda:ListNetworkConnectorVersions"),
rule("lambda", "GET", "^/2026-04-04/network-connectors/[^/]+$", "lambda:GetNetworkConnector"),
rule("lambda", "PUT", "^/2026-04-04/network-connectors/[^/]+$", "lambda:UpdateNetworkConnector"),
rule("lambda", "DELETE", "^/2026-04-04/network-connectors/[^/]+$", "lambda:DeleteNetworkConnector"),
rule("lambda", "GET", "^/2026-04-04/network-connectors$", "lambda:ListNetworkConnectors"),
rule("lambda", "POST", "^/2026-04-04/network-connectors$", "lambda:CreateNetworkConnector"),
// ── DynamoDB (JSON 1.1, action from X-Amz-Target handled separately) ──
// Handled via Query-style action extraction in the filter
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget;
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
@@ -65,13 +66,22 @@ public class ResourceArnBuilder {
private final Instance<IamService> iamService;
/** Looked up lazily for the same reason, to resolve a secret named by its name or a partial ARN. */
private final Instance<SecretsManagerService> secretsManagerService;
/** Looked up lazily for the same reason, to read the image a MicroVM runs. */
private final Instance<LambdaMicrovmsService> microvmsService;
@Inject
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<SecretsManagerService> secretsManagerService) {
Instance<SecretsManagerService> secretsManagerService,
Instance<LambdaMicrovmsService> microvmsService) {
this.objectMapper = objectMapper;
this.iamService = iamService;
this.secretsManagerService = secretsManagerService;
this.microvmsService = microvmsService;
}
public ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService,
Instance<SecretsManagerService> secretsManagerService) {
this(objectMapper, iamService, secretsManagerService, null);
}
ResourceArnBuilder(ObjectMapper objectMapper, Instance<IamService> iamService) {
@@ -679,6 +689,14 @@ public class ResourceArnBuilder {
if (webFunctionArn != null) {
return webFunctionArn;
}
String microvmArn = microvmArn(path, ctx, region, accountId);
if (microvmArn != null) {
return microvmArn;
}
// TagResource, ListTags and UntagResource name the tagged function, image or other resource by its ARN.
if (path.startsWith("/2017-03-31/tags/")) {
return lambdaTaggedArn(path.substring("/2017-03-31/tags/".length()), accountId);
}
String executionArn = durableExecutionArn(path);
if (executionArn == null) {
executionArn = durableCallbackExecutionArn(path);
@@ -715,6 +733,103 @@ public class ResourceArnBuilder {
}
}
/**
* The resource of a Lambda MicroVM or network connector route, as the Service Reference gives it:
* {@code microvm-image:<name>} for an action on an image, its versions and builds, and
* {@code network-connector:<id>} for one on a connector. An identifier given as an ARN is taken for
* its trailing name, in the request's account and Region, since that is the resource the service
* looks up and acts on, whatever account or Region the ARN names. {@code RunMicrovm} is checked
* against the image its {@code imageIdentifier} names, read the same way, an action on a running
* MicroVM against the image that MicroVM runs, and a managed image's versions against the managed
* image. Creating an image or a connector, listing them and listing MicroVMs name no resource, so
* they are {@code *}, as is a MicroVM the account does not hold. Null for every other Lambda route.
*/
private String microvmArn(String path, ContainerRequestContext ctx, String region, String accountId) {
if (path.startsWith("/2025-09-09/")) {
String image = segmentAfterPrefix(path, "/2025-09-09/microvm-images/");
if (image != null) {
return microvmImageArn(region, accountId, image);
}
String managed = segmentAfterPrefix(path, "/2025-09-09/managed-microvm-images/");
if (managed != null) {
return LambdaMicrovmsService.namesManagedImage(managed)
? LambdaMicrovmsService.managedImageArn(region) : "*";
}
String microvm = segmentAfterPrefix(path, "/2025-09-09/microvms/");
if (microvm != null) {
return runningMicrovmImageArn(region, microvm);
}
if (path.equals("/2025-09-09/microvms") && "POST".equalsIgnoreCase(ctx.getMethod())) {
JsonNode body = readJsonBody(ctx);
String identifier = body == null ? null : body.path("imageIdentifier").asText(null);
return identifier == null || identifier.isBlank() ? "*" : microvmImageArn(region, accountId, identifier);
}
return "*";
}
if (path.startsWith("/2026-04-04/")) {
String connector = segmentAfterPrefix(path, "/2026-04-04/network-connectors/");
return connector == null ? "*"
: AwsArnUtils.Arn.of("lambda", region, accountId,
"network-connector:" + trailingName(connector)).toString();
}
return null;
}
private static String microvmImageArn(String region, String accountId, String identifier) {
return AwsArnUtils.Arn.of("lambda", region, accountId, "microvm-image:" + trailingName(identifier)).toString();
}
/** The image the caller's MicroVM runs, or {@code *} when the account holds no such MicroVM to act on. */
private String runningMicrovmImageArn(String region, String microvmId) {
if (microvmsService == null) {
return "*";
}
return microvmsService.get().findMicrovm(region, microvmId)
.map(vm -> vm.imageArn)
.filter(arn -> arn != null && !arn.isBlank())
.orElse("*");
}
/** An identifier's name: an ARN's part after its last {@code :}, as the MicroVM service unwraps it. */
private static String trailingName(String identifier) {
return identifier.startsWith("arn:") ? identifier.substring(identifier.lastIndexOf(':') + 1) : identifier;
}
/**
* The resource a Lambda tag route acts on, from the ARN it names. Tagging looks a function up by the
* ARN's Region and name, and a MicroVM image or network connector by the ARN's Region and trailing
* name, in the caller's own account whatever account the ARN names, so that resource is the one
* checked. The MicroVM tag handler takes any target holding {@code :microvm-image:} or
* {@code :network-connector:}, an {@code arn:} prefix or not, so the target is read as it reads it.
* Any other ARN, an event source mapping's included, has to name its resource exactly or is
* refused, so it is checked as written.
*/
private static String lambdaTaggedArn(String tagged, String accountId) {
if (LambdaMicrovmsService.ownsArn(tagged)) {
// Read as LambdaTagController and LambdaMicrovmsService read it: the Region is the fourth field,
// the name what follows the last colon.
String[] fields = tagged.split(":");
String region = fields.length > 3 ? fields[3] : "";
String type = tagged.contains(":microvm-image:") ? "microvm-image:"
: tagged.contains(":network-connector:") ? "network-connector:" : null;
if (type != null && !region.isBlank()) {
return AwsArnUtils.Arn.of("lambda", region, accountId,
type + tagged.substring(tagged.lastIndexOf(':') + 1)).toString();
}
}
if (!tagged.startsWith("arn:")) {
return "*";
}
try {
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(tagged);
return ref.qualifier() != null ? tagged
: AwsArnUtils.Arn.of("lambda", ref.region(), accountId, "function:" + ref.name()).toString();
} catch (AwsException e) {
// Not a function ARN Lambda takes, which it tags only when the ARN names the resource exactly.
return tagged;
}
}
/**
* The resource of an EventBridge Scheduler route: {@code schedule/<group>/<name>}, the group read where
* Scheduler reads it, the body's {@code GroupName} on a create or an update and {@code groupName}
@@ -17,6 +17,7 @@ import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
@@ -46,6 +47,8 @@ public class LambdaMicrovmsService {
private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z0-9-_]{1,64}");
private static final int MAX_CONNECTOR_SUBNETS = 16;
/** The one AWS-managed base image the catalog serves. */
private static final String MANAGED_IMAGE = "al2023-1";
private final RegionResolver regionResolver;
private final StorageFactory storageFactory;
@@ -293,16 +296,26 @@ public class LambdaMicrovmsService {
}
public List<Map<String, Object>> listManagedImageVersions(String region, String identifier) {
if (!identifier.contains("al2023-1")) {
if (!namesManagedImage(identifier)) {
throw new AwsException("ResourceNotFoundException",
"Managed MicroVM image not found: " + identifier, 404);
}
return List.of(managedImage(region));
}
/** True when {@code identifier} names the managed image, as {@link #listManagedImageVersions} reads it. */
public static boolean namesManagedImage(String identifier) {
return identifier.contains(MANAGED_IMAGE);
}
/** The managed image's ARN in {@code region}, owned by {@code aws} rather than the caller's account. */
public static String managedImageArn(String region) {
return AwsArnUtils.Arn.of("lambda", region, "aws", "microvm-image:" + MANAGED_IMAGE).toString();
}
private Map<String, Object> managedImage(String region) {
Map<String, Object> entry = new LinkedHashMap<>();
entry.put("imageArn", AwsArnUtils.Arn.of("lambda", region, "aws", "microvm-image:al2023-1").toString());
entry.put("imageArn", managedImageArn(region));
entry.put("createdAt", 1781833144.754d);
entry.put("updatedAt", 1784165932.388d);
return entry;
@@ -351,12 +364,13 @@ public class LambdaMicrovmsService {
}
public Microvm getMicrovm(String region, String microvmId) {
Microvm vm = microvms.get(key(region, unwrap(microvmId)));
if (vm == null) {
throw new AwsException("ResourceNotFoundException",
"MicroVM not found: " + microvmId, 404);
}
return vm;
return findMicrovm(region, microvmId).orElseThrow(() -> new AwsException("ResourceNotFoundException",
"MicroVM not found: " + microvmId, 404));
}
/** The MicroVM of the caller's account that {@code microvmId} names in {@code region}, looked up as every route does. */
public Optional<Microvm> findMicrovm(String region, String microvmId) {
return Optional.ofNullable(microvms.get(key(region, unwrap(microvmId))));
}
public List<Microvm> listMicrovms(String region) {
@@ -176,7 +176,7 @@ class PassedRolesTest {
}
@Test
void schedulerAndPipesPassTheRoleTheyName() {
void schedulerPipesAndLambdaMicrovmsPassTheRoleTheyName() {
String target = "{\"Target\":{\"RoleArn\":\"" + ROLES + "schedule\"}}";
assertEquals(List.of(passed("schedule", "scheduler.amazonaws.com")),
PassedRoles.of("scheduler:CreateSchedule", json(target), LOOKUPS));
@@ -185,6 +185,18 @@ class PassedRolesTest {
String pipe = "{\"RoleArn\":\"" + ROLES + "pipe\"}";
assertEquals(List.of(passed("pipe", "pipes.amazonaws.com")), PassedRoles.of("pipes:CreatePipe", json(pipe), LOOKUPS));
assertEquals(List.of(passed("pipe", "pipes.amazonaws.com")), PassedRoles.of("pipes:UpdatePipe", json(pipe), LOOKUPS));
String build = "{\"buildRoleArn\":\"" + ROLES + "build\"}";
assertEquals(List.of(passed("build", "lambda.amazonaws.com")),
PassedRoles.of("lambda:CreateMicrovmImage", json(build), LOOKUPS));
assertEquals(List.of(passed("build", "lambda.amazonaws.com")),
PassedRoles.of("lambda:UpdateMicrovmImage", json(build), LOOKUPS));
assertEquals(List.of(passed("vm", "lambda.amazonaws.com")), PassedRoles.of("lambda:RunMicrovm",
json("{\"executionRoleArn\":\"" + ROLES + "vm\"}"), LOOKUPS));
String operator = "{\"OperatorRole\":\"" + ROLES + "operator\"}";
assertEquals(List.of(passed("operator", "lambda.amazonaws.com")),
PassedRoles.of("lambda:CreateNetworkConnector", json(operator), LOOKUPS));
assertEquals(List.of(passed("operator", "lambda.amazonaws.com")),
PassedRoles.of("lambda:UpdateNetworkConnector", json(operator), LOOKUPS));
}
@Test
@@ -47,6 +47,7 @@ class IamPassRoleEnforcementIntegrationTest {
private static final String ECS_TASKS = "ecs-tasks.amazonaws.com";
private static final String ECS = "ecs.amazonaws.com";
private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:" + ACCOUNT + ":passrole-queue";
private static final String LAMBDA = "lambda.amazonaws.com";
private static final String SCHEDULER = "scheduler.amazonaws.com";
private static final String PIPES = "pipes.amazonaws.com";
private static final String AUTOSCALING = "autoscaling.amazonaws.com";
@@ -447,6 +448,42 @@ class IamPassRoleEnforcementIntegrationTest {
user.rest("pipes").body(update).put(path).then().statusCode(200);
}
@Test
void aMicrovmImageAndANetworkConnectorNeedPassRoleOnTheRolesTheyName() {
String build = role("microvm-build");
String operator = role("connector-operator");
User user = user("passrole-microvm");
String image = "passrole-image-" + suffix();
String createImage = """
{"name":"%s","baseImageArn":"arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
"buildRoleArn":"%s","codeArtifact":{"uri":"s3://bucket/code.zip"}}""".formatted(image, build);
user.policy(allow("lambda:CreateMicrovmImage", "*"));
denied(user.rest("lambda").body(createImage).post("/2025-09-09/microvm-images").then());
user.policy(allow("lambda:CreateMicrovmImage", "*") + "," + passRole(build, LAMBDA));
user.rest("lambda").body(createImage).post("/2025-09-09/microvm-images").then().statusCode(201);
cleanup.register(() -> admin("lambda").delete("/2025-09-09/microvm-images/" + image));
// Reading it is checked against the image's ARN.
String imageArn = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":microvm-image:" + image;
user.policy(allow("lambda:GetMicrovmImage", imageArn + "-other"));
refused(user.rest("lambda").get("/2025-09-09/microvm-images/" + image).then(), "lambda:GetMicrovmImage");
user.policy(allow("lambda:GetMicrovmImage", imageArn));
user.rest("lambda").get("/2025-09-09/microvm-images/" + image).then().statusCode(200);
String createConnector = """
{"Name":"passrole-connector-%1$s","ClientToken":"passrole-token-%1$s","OperatorRole":"%2$s",
"Configuration":{"VpcEgressConfiguration":{"AssociatedComputeResourceTypes":["MicroVm"],
"NetworkProtocol":"IPv4","SubnetIds":["subnet-0000000000000it01"],
"SecurityGroupIds":["sg-0000000000000it01"]}}}"""
.formatted(suffix(), operator);
user.policy(allow("lambda:CreateNetworkConnector", "*"));
denied(user.rest("lambda").body(createConnector).post("/2026-04-04/network-connectors").then());
user.policy(allow("lambda:CreateNetworkConnector", "*") + "," + passRole(operator, LAMBDA));
String connector = user.rest("lambda").body(createConnector).post("/2026-04-04/network-connectors").then()
.statusCode(202).extract().path("Id");
cleanup.register(() -> admin("lambda").delete("/2026-04-04/network-connectors/" + connector));
}
@Test
void aStackNeedsPassRoleOnAServiceRoleTheRequestNames() {
String role = role("cloudformation");
@@ -52,7 +52,7 @@ class IamRestRouteCoverageTest {
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket");
/** Models every operation of which is checked: the services whose routes the registry maps in full. */
private static final Set<String> FULLY_ROUTED_MODELS = Set.of("scheduler", "pipes");
private static final Set<String> FULLY_ROUTED_MODELS = Set.of("scheduler", "pipes", "lambda-microvms", "lambda-core");
private final IamActionRegistry registry = new IamActionRegistry();
@@ -126,6 +126,92 @@ class IamRestRouteEnforcementIntegrationTest {
return "{\"resourceArn\":\"" + arn + "\",\"tags\":[{\"key\":\"team\",\"value\":\"a\"}]}";
}
@Test
void lambdaTaggingIsCheckedAgainstTheTaggedFunction() {
String user = user("route-lambda-tags");
String function = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:route-fn-" + suffix();
String path = "/2017-03-31/tags/" + function;
String body = "{\"Tags\":{\"team\":\"a\"}}";
policy(user, allow("lambda:TagResource", function + "-other"));
refused(as(user, "lambda").body(body).post(path).then(), "lambda:TagResource");
// A grant on the function itself covers it; the request reaches Lambda, which has no such function.
policy(user, allow("lambda:TagResource", function));
as(user, "lambda").body(body).post(path).then().statusCode(not(403));
}
@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.
String user = user("route-lambda-tags-account");
String name = "route-tagged-" + suffix();
String body = "{\"Tags\":{\"team\":\"a\"}}";
for (String type : new String[] {"function:", "microvm-image:"}) {
String own = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":" + type + name;
String foreign = "arn:aws:lambda:us-east-1:111122223333:" + type + name;
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));
}
}
@Test
void aMicrovmIsCheckedAgainstTheImageItRuns() {
// RunMicrovm and the actions on a running MicroVM act on its image, so a Deny on the image applies to
// them even where the action is allowed on every resource, and a grant on the image alone covers them.
String user = user("route-microvm-image");
String image = microvmImage("route-image-" + suffix());
String run = "{\"imageIdentifier\":\"" + image.substring(image.lastIndexOf(':') + 1) + "\"}";
policy(user, allow("lambda:RunMicrovm", "*") + "," + deny("lambda:RunMicrovm", image));
refused(as(user, "lambda").body(run).post("/2025-09-09/microvms").then(), "lambda:RunMicrovm");
policy(user, allow("lambda:RunMicrovm", image));
String microvm = as(user, "lambda").body(run).post("/2025-09-09/microvms").then().statusCode(200)
.extract().path("microvmId");
cleanup.register(() -> admin().delete("/2025-09-09/microvms/" + microvm));
policy(user, allow("lambda:GetMicrovm", "*") + "," + deny("lambda:GetMicrovm", image));
refused(as(user, "lambda").get("/2025-09-09/microvms/" + microvm).then(), "lambda:GetMicrovm");
policy(user, allow("lambda:GetMicrovm", image));
as(user, "lambda").get("/2025-09-09/microvms/" + microvm).then().statusCode(200);
}
@Test
void aMicrovmImageTaggedThroughATargetWithoutTheArnPrefixIsCheckedAsTheImage() {
// Lambda tags the image any target holding :microvm-image: names, read by its fourth field and
// its last, so a Deny on the image applies however the target is spelled.
String user = user("route-image-tags");
String image = microvmImage("route-tagged-image-" + suffix());
String target = "/2017-03-31/tags/x:y:z:us-east-1:microvm-image:" + image.substring(image.lastIndexOf(':') + 1);
String body = "{\"Tags\":{\"team\":\"a\"}}";
policy(user, allow("lambda:TagResource", "*") + "," + deny("lambda:TagResource", image));
refused(as(user, "lambda").body(body).post(target).then(), "lambda:TagResource");
policy(user, allow("lambda:TagResource", "*"));
as(user, "lambda").body(body).post(target).then().statusCode(204);
}
/** Creates a MicroVM image as the account's admin, removed afterwards, and returns its ARN. */
private String microvmImage(String name) {
admin().body("""
{"name":"%s","baseImageArn":"arn:aws:lambda:us-east-1:aws:microvm-image:al2023-1",
"buildRoleArn":"arn:aws:iam::%s:role/route-build","codeArtifact":{"uri":"s3://bucket/code.zip"}}"""
.formatted(name, ACCOUNT)).post("/2025-09-09/microvm-images").then().statusCode(201);
cleanup.register(() -> admin().delete("/2025-09-09/microvm-images/" + name));
return "arn:aws:lambda:us-east-1:" + ACCOUNT + ":microvm-image:" + name;
}
private static RequestSpecification admin() {
return given().header("Authorization", auth(ADMIN, "lambda")).contentType("application/json");
}
private static String deny(String action, String resource) {
return "{\"Effect\":\"Deny\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
}
private static void refused(ValidatableResponse response, String action) {
response.statusCode(403).body(containsString(action)).body(not(containsString("iam:PassRole")));
}
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.ServerCertificate;
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.container.ContainerRequestContext;
@@ -110,6 +111,14 @@ 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, null, instance);
}
/** A builder reading {@code secrets}, for a secret named by its name. */
private static ResourceArnBuilder backedBy(SecretsManagerService secrets) {
@SuppressWarnings("unchecked")
@@ -1207,6 +1216,66 @@ class ResourceArnBuilderTest {
assertEquals("*", builder.build("lambda", ctx, "us-east-1", "000000000000"));
}
@Test
void lambdaMicrovmAndNetworkConnectorRoutesResolveTheImageOrConnectorTheyName() {
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");
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"));
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 anActionOnARunningMicrovmIsCheckedAgainstTheImageItRuns() {
String image = "arn:aws:lambda:us-east-1:000000000000:microvm-image:img";
LambdaMicrovmsService.Microvm vm = new LambdaMicrovmsService.Microvm();
vm.microvmId = "microvm-1";
vm.imageArn = image;
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);
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"));
}
@Test
void schedulerRoutesResolveTheScheduleInItsGroupTheGroupOrTheTaggedArn() {
when(uriInfo.getPath()).thenReturn("/schedules/nightly");
@@ -1295,7 +1364,35 @@ class ResourceArnBuilderTest {
}
@Test
void aStreamingInvokeResolvesItsQualifiedFunctionAsAnInvokeDoes() {
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);
}
// The MicroVM tag handler takes a target without the arn: prefix too, and reads it the same way.
when(uriInfo.getPath()).thenReturn("/2017-03-31/tags/x:y:z:eu-west-1: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/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");
+42
View File
@@ -334,6 +334,48 @@
"UpdateFunctionUrlConfig": {"method": "PUT", "requestUri": "/2021-10-31/functions/{FunctionName}/url"}
}
},
"lambda-core": {
"credentialScope": "lambda",
"apiVersion": "2026-04-30",
"operations": {
"CreateNetworkConnector": {"method": "POST", "requestUri": "/2026-04-04/network-connectors"},
"DeleteNetworkConnector": {"method": "DELETE", "requestUri": "/2026-04-04/network-connectors/{Identifier}"},
"GetNetworkConnector": {"method": "GET", "requestUri": "/2026-04-04/network-connectors/{Identifier}"},
"ListNetworkConnectorVersions": {"method": "GET", "requestUri": "/2026-04-04/network-connectors/{Identifier}/versions"},
"ListNetworkConnectors": {"method": "GET", "requestUri": "/2026-04-04/network-connectors"},
"UpdateNetworkConnector": {"method": "PUT", "requestUri": "/2026-04-04/network-connectors/{Identifier}"}
}
},
"lambda-microvms": {
"credentialScope": "lambda",
"apiVersion": "2025-09-09",
"operations": {
"CreateMicrovmAuthToken": {"method": "POST", "requestUri": "/2025-09-09/microvms/{microvmIdentifier}/auth-token"},
"CreateMicrovmImage": {"method": "POST", "requestUri": "/2025-09-09/microvm-images"},
"CreateMicrovmShellAuthToken": {"method": "POST", "requestUri": "/2025-09-09/microvms/{microvmIdentifier}/shell-auth-token"},
"DeleteMicrovmImage": {"method": "DELETE", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}"},
"DeleteMicrovmImageVersion": {"method": "DELETE", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}"},
"GetMicrovm": {"method": "GET", "requestUri": "/2025-09-09/microvms/{microvmIdentifier}"},
"GetMicrovmImage": {"method": "GET", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}"},
"GetMicrovmImageBuild": {"method": "GET", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds/{buildId}"},
"GetMicrovmImageVersion": {"method": "GET", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}"},
"ListManagedMicrovmImageVersions": {"method": "GET", "requestUri": "/2025-09-09/managed-microvm-images/{imageIdentifier}/versions"},
"ListManagedMicrovmImages": {"method": "GET", "requestUri": "/2025-09-09/managed-microvm-images"},
"ListMicrovmImageBuilds": {"method": "GET", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}/builds"},
"ListMicrovmImageVersions": {"method": "GET", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions"},
"ListMicrovmImages": {"method": "GET", "requestUri": "/2025-09-09/microvm-images"},
"ListMicrovms": {"method": "GET", "requestUri": "/2025-09-09/microvms"},
"ListTags": {"method": "GET", "requestUri": "/2017-03-31/tags/{Resource}"},
"ResumeMicrovm": {"method": "POST", "requestUri": "/2025-09-09/microvms/{microvmIdentifier}/resume"},
"RunMicrovm": {"method": "POST", "requestUri": "/2025-09-09/microvms"},
"SuspendMicrovm": {"method": "POST", "requestUri": "/2025-09-09/microvms/{microvmIdentifier}/suspend"},
"TagResource": {"method": "POST", "requestUri": "/2017-03-31/tags/{Resource}"},
"TerminateMicrovm": {"method": "DELETE", "requestUri": "/2025-09-09/microvms/{microvmIdentifier}"},
"UntagResource": {"method": "DELETE", "requestUri": "/2017-03-31/tags/{Resource}"},
"UpdateMicrovmImage": {"method": "PUT", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}"},
"UpdateMicrovmImageVersion": {"method": "PATCH", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}"}
}
},
"pipes": {
"credentialScope": "pipes",
"apiVersion": "2015-10-07",
+2
View File
@@ -35,6 +35,8 @@ MODELS: dict[str, str] = {
"apigateway": "apigateway",
"apigatewayv2": "apigateway",
"lambda": "lambda",
"lambda-core": "lambda",
"lambda-microvms": "lambda",
"pipes": "pipes",
"s3": "s3",
"scheduler": "scheduler",