diff --git a/docs/services/iam.md b/docs/services/iam.md index 1a02b90e38..558139ea64 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1298,6 +1298,26 @@ An S3 object operation is checked as the action the S3 documentation gives it: A request naming several of these sub-resources is checked as the one S3 runs. `GET ?acl&tagging` returns the tags, so it needs `s3:GetObjectTagging`. +A request that passes a role to a service also needs `iam:PassRole` on that role, as the IAM user +guide requires: "To pass a role (and its permissions) to an AWS service, a user must have +permissions to pass the role to the service." It is checked with `iam:PassedToService` naming the +service the role goes to, the value AWS's Service Reference gives for the operation, so a grant to +pass a role to EC2 does not let the same role be passed to Lambda. The operations checked, and the +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`. +- **EC2:** `RunInstances`, `RequestSpotInstances`, `AssociateIamInstanceProfile`, + `ReplaceIamInstanceProfileAssociation`, `CreateLaunchTemplate` and `CreateLaunchTemplateVersion` + pass the roles of the instance profile they name, to `ec2.amazonaws.com`. `CreateFlowLogs` passes + `DeliverLogsPermissionArn` to `vpc-flow-logs.amazonaws.com`. A profile that does not exist + passes nothing, and EC2 refuses it as without enforcement. + +Launching from a launch template does not check the template's role, as on AWS: the EC2 user guide +warns that a user who can create launch template versions "can potentially update a launch template +to pass an IAM role to an instance even if they don't have the iam:PassRole permission". The role +parameters of other services are not checked yet. + A request that names its operation, in a Query `Action`, an `X-Amz-Target` header or a Smithy RPC v2 path (`/service//operation/`), is authorized as the action AWS checks for that operation, which is usually the operation's own name. An RPC v2 call is checked as the service and @@ -1644,6 +1664,8 @@ floci populates: N days. - An object creation offers its tag and Object Lock keys to each action it is checked as: its `s3:PutObject` and the extra actions its settings need. +- `iam:PassedToService`: the service principal a request passes a role to, for the + `iam:PassRole` check described above. - A `PutObject` carrying `If-Match` is authorized as `s3:GetObject` as well, and that second check is made without the object's tags in the context, as measured on AWS. `CopyObject` and `CompleteMultipartUpload`, the other operations the S3 user guide lists for `If-Match`, get the diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index 5e1fe9a887..88b8fafcfd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -61,7 +61,7 @@ public class IamConditionContextResolver { private static final Logger LOG = Logger.getLogger(IamConditionContextResolver.class); /** Set by {@code ResourceArnBuilder.readJsonBody}, which runs earlier in the same filter pass. */ - private static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody"; + static final String BUFFERED_JSON_BODY = "floci.bufferedJsonBody"; private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody"; private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/"; private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/"; @@ -657,7 +657,7 @@ public class IamConditionContextResolver { * resource this context describes is the resource the handler acts on. */ @SuppressWarnings("unchecked") - private static Map formParameters(ContainerRequestContext ctx) { + static Map formParameters(ContainerRequestContext ctx) { Object cached = ctx.getProperty(BUFFERED_FORM_BODY); if (cached instanceof Map map) { return (Map) map; @@ -688,7 +688,7 @@ public class IamConditionContextResolver { } /** Reads the entity fully and puts an equivalent stream back for downstream readers. */ - private static byte[] bufferEntity(ContainerRequestContext ctx) { + static byte[] bufferEntity(ContainerRequestContext ctx) { InputStream in = ctx.getEntityStream(); if (in == null) { return null; diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index b3682d5a28..e937ff77ef 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.iam.model.CallerContext; +import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.services.s3.S3ObjectActions; import io.quarkus.vertx.http.runtime.CurrentVertxRequest; import io.vertx.core.http.HttpServerRequest; @@ -521,6 +522,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter { region, accountId, akid)) { return; } + if (abortIfRolePassDenied(ctx, caller, principal, callerArns.orElse(null), action, credentialScope, + region, accountId, akid)) { + return; + } // Tagged group creation requires either tagging permission, using the same resolved // caller (including session, boundary and SCP ceilings) as the primary operation. @@ -861,6 +866,44 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return CallerArns.accountRoot(rootArn, accountId); } + /** + * A request that passes a role to a service also needs {@code iam:PassRole} on that role (see + * {@link PassedRoles}), checked as the caller with {@code iam:PassedToService} naming the + * service and the keys that say who is calling, which {@code callerArns} writes when it is known. + * An instance profile is looked up in the request's account, as EC2 resolves it; one that does + * not exist passes nothing, and the operation reports it. Returns true when the request was + * aborted. + */ + private boolean abortIfRolePassDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal, + CallerArns callerArns, String action, String credentialScope, + String region, String accountId, String akid) { + for (PassedRoles.PassedRole passed : PassedRoles.of(action, ctx, + (name, arn) -> instanceProfileRoleArns(accountId, name, arn))) { + Map> context = new HashMap<>(); + if (callerArns != null) { + callerArns.putPrincipalKeys(context); + } + context.put("iam:PassedToService", List.of(passed.passedToService())); + if (abortIfDenied(ctx, caller, principal, "iam:PassRole", action, credentialScope, + List.of(passed.roleArn()), List.of(context), region, accountId, akid)) { + return true; + } + } + return false; + } + + /** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */ + private List instanceProfileRoleArns(String accountId, String name, String arn) { + String profileName = arn != null ? arn.substring(arn.lastIndexOf('/') + 1) : name; + return iamService.findInstanceProfile(accountId, profileName) + .filter(profile -> arn == null || arn.equals(profile.getArn())) + .map(profile -> profile.getRoleNames().stream() + .flatMap(roleName -> iamService.findRole(accountId, roleName).stream()) + .map(IamRole::getArn) + .toList()) + .orElse(List.of()); + } + /** * Evaluates one action against every resource and target context, aborting the request with * AccessDenied on the first DENY. Returns true when the request was aborted. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java new file mode 100644 index 0000000000..6d7437e5e8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java @@ -0,0 +1,129 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.ws.rs.container.ContainerRequestContext; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * The IAM roles a request passes to a service, which the caller also needs {@code iam:PassRole} on. + * The IAM user guide: "To pass a role (and its permissions) to an AWS service, a user must have + * permissions to pass the role to the service." AWS's Service Reference names, for each operation + * that passes one, the service the role goes to, which the check offers as {@code iam:PassedToService}; + * where the request carries the role differs per operation and is listed here. + * + *

An EC2 request names an instance profile rather than a role, and passes the roles the profile + * holds. Launching from a launch template passes nothing here: the EC2 user guide warns that a user + * who can create launch template versions "can potentially update a launch template to pass an IAM + * role to an instance even if they don't have the iam:PassRole permission", so the role is checked + * where the template is created. + */ +final class PassedRoles { + + private static final Logger LOG = Logger.getLogger(PassedRoles.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** An IAM role ARN, the only resource {@code iam:PassRole} acts on. */ + private static final Pattern ROLE_ARN = Pattern.compile("^arn:[a-z0-9-]+:iam::\\d{12}:role/.+"); + + private static final String LAMBDA = ServicePrincipals.of("lambda"); + private static final String EC2 = ServicePrincipals.of("ec2"); + private static final String VPC_FLOW_LOGS = ServicePrincipals.of("vpc-flow-logs"); + + /** A role a request passes, and the service principal it is passed to. */ + record PassedRole(String roleArn, String passedToService) { + } + + /** The ARNs of the roles an EC2 instance profile holds, looked up by its name or its ARN. */ + @FunctionalInterface + interface InstanceProfileRoles { + List roleArns(String profileName, String profileArn); + } + + private PassedRoles() { + } + + /** The roles a request for {@code action} passes; empty when the operation passes none or the request names none. */ + static List of(String action, ContainerRequestContext ctx, InstanceProfileRoles profiles) { + return switch (action) { + case "lambda:CreateFunction", "lambda:UpdateFunctionConfiguration" -> fromJson(ctx, LAMBDA, "Role"); + case "lambda:CreateWebFunction" -> + fromJson(ctx, LAMBDA, "revisionConfig", "serviceConfig", "executionRoleArn"); + case "lambda:CreateWebFunctionRevision" -> fromJson(ctx, LAMBDA, "serviceConfig", "executionRoleArn"); + case "ec2:RunInstances", "ec2:AssociateIamInstanceProfile", "ec2:ReplaceIamInstanceProfileAssociation" -> + fromInstanceProfile(ctx, profiles, "IamInstanceProfile"); + case "ec2:RequestSpotInstances" -> + fromInstanceProfile(ctx, profiles, "LaunchSpecification.IamInstanceProfile"); + case "ec2:CreateLaunchTemplate", "ec2:CreateLaunchTemplateVersion" -> + fromInstanceProfile(ctx, profiles, "LaunchTemplateData.IamInstanceProfile"); + case "ec2:CreateFlowLogs" -> fromForm(ctx, VPC_FLOW_LOGS, "DeliverLogsPermissionArn"); + default -> List.of(); + }; + } + + private static List fromJson(ContainerRequestContext ctx, String service, String... path) { + JsonNode node = jsonBody(ctx); + for (String member : path) { + node = node == null ? null : node.get(member); + } + return node != null && node.isTextual() ? passed(List.of(node.asText()), service) : List.of(); + } + + private static List fromForm(ContainerRequestContext ctx, String service, String parameter) { + String roleArn = IamConditionContextResolver.formParameters(ctx).get(parameter); + return roleArn == null ? List.of() : passed(List.of(roleArn), service); + } + + /** The roles of the instance profile named by {@code prefix}.Name or {@code prefix}.Arn. */ + private static List fromInstanceProfile(ContainerRequestContext ctx, InstanceProfileRoles profiles, + String prefix) { + Map form = IamConditionContextResolver.formParameters(ctx); + String name = blankToNull(form.get(prefix + ".Name")); + String arn = blankToNull(form.get(prefix + ".Arn")); + if (name == null && arn == null) { + return List.of(); + } + return passed(profiles.roleArns(name, arn), EC2); + } + + /** The roles that are IAM role ARNs; anything else is left for the operation to refuse. */ + private static List passed(List roleArns, String service) { + List passed = new ArrayList<>(); + for (String roleArn : roleArns) { + if (roleArn != null && ROLE_ARN.matcher(roleArn).matches()) { + passed.add(new PassedRole(roleArn, service)); + } + } + return passed; + } + + /** The request's JSON body, read once and kept where the other request readers look for it. */ + private static JsonNode jsonBody(ContainerRequestContext ctx) { + if (ctx.getProperty(IamConditionContextResolver.BUFFERED_JSON_BODY) instanceof JsonNode cached) { + return cached; + } + byte[] body = IamConditionContextResolver.bufferEntity(ctx); + if (body == null || body.length == 0) { + return null; + } + try { + JsonNode node = MAPPER.readTree(body); + ctx.setProperty(IamConditionContextResolver.BUFFERED_JSON_BODY, node); + return node; + } catch (IOException e) { + // The operation answers a body it cannot parse itself; nothing here names a role. + LOG.debugv(e, "Request body is not JSON, so it passes no role"); + return null; + } + } + + private static String blankToNull(String value) { + return value == null || value.isBlank() ? null : value; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index d38c780745..6c09e94cae 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -6308,10 +6308,11 @@ public class Ec2QueryHandler { userDataEncoded = null; } String userData = Ec2UserDataDecoder.decode(userDataEncoded); - String iamInstanceProfileArn = p.getFirst("LaunchSpecification.IamInstanceProfile.Arn"); List spotRequestTags = parseTagsForResource(p, "spot-instances-request"); List instanceTags = parseTagsForResource(p, "instance"); + // The profile is named by ARN or by name, as for RunInstances. + String iamInstanceProfileArn = resolveIamInstanceProfileArn(p, "LaunchSpecification.IamInstanceProfile"); List requests = service.requestSpotInstances(region, spotPrice, instanceCount, type, productDescription, imageId, instanceType, keyName, subnetId, securityGroupIds, userData, iamInstanceProfileArn, diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java new file mode 100644 index 0000000000..3b58184d14 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -0,0 +1,314 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A request that passes a role to Lambda or EC2 also needs {@code iam:PassRole} on that role, with + * {@code iam:PassedToService} naming the service, as the IAM user guide requires: "To pass a role + * (and its permissions) to an AWS service, a user must have permissions to pass the role to the + * service." Without it a user allowed only to create functions or launch instances could hand them + * any role in the account and act with its permissions. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class IamPassRoleEnforcementIntegrationTest { + + private static final String ADMIN = "test"; + private static final String ACCOUNT = "000000000000"; + private static final String IMAGE = "ami-0abcdef1234567890"; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void creatingAFunctionNeedsPassRoleOnItsExecutionRoleForLambda() { + String role = role("fn-exec"); + User user = user("passrole-create-fn"); + String name = "passrole-fn-" + suffix(); + String body = """ + {"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler","Role":"%s"}""" + .formatted(name, role); + + user.policy(allow("lambda:CreateFunction", "*")); + denied(user.lambda().body(body).post("/2015-03-31/functions").then()); + + // The permission names the service the role is passed to: one for EC2 does not cover Lambda. + user.policy(allow("lambda:CreateFunction", "*") + "," + passRole(role, "ec2.amazonaws.com")); + denied(user.lambda().body(body).post("/2015-03-31/functions").then()); + + user.policy(allow("lambda:CreateFunction", "*") + "," + passRole(role, "lambda.amazonaws.com")); + user.lambda().body(body).post("/2015-03-31/functions").then().statusCode(201); + cleanup.register(() -> admin("lambda").contentType("application/json") + .delete("/2015-03-31/functions/{name}", name)); + } + + @Test + void updatingAFunctionNeedsPassRoleOnlyWhenItSetsTheRole() { + String first = role("fn-first"); + String second = role("fn-second"); + String name = "passrole-update-" + suffix(); + admin("lambda").contentType("application/json") + .body(""" + {"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler","Role":"%s"}""" + .formatted(name, first)) + .post("/2015-03-31/functions").then().statusCode(201); + cleanup.register(() -> admin("lambda").contentType("application/json") + .delete("/2015-03-31/functions/{name}", name)); + User user = user("passrole-update-fn"); + String configuration = "/2015-03-31/functions/" + name + "/configuration"; + + user.policy(allow("lambda:UpdateFunctionConfiguration", "*")); + user.lambda().body("{\"Timeout\":10}").put(configuration).then().statusCode(200); + denied(user.lambda().body("{\"Role\":\"" + second + "\"}").put(configuration).then()); + + user.policy(allow("lambda:UpdateFunctionConfiguration", "*") + "," + + passRole(second, "lambda.amazonaws.com")); + user.lambda().body("{\"Role\":\"" + second + "\"}").put(configuration).then().statusCode(200); + } + + @Test + void aWebFunctionNeedsPassRoleOnItsExecutionRole() { + String role = role("web-exec"); + User user = user("passrole-web-fn"); + String name = "passrole-web-" + suffix(); + String function = """ + {"functionName":"%s","revisionConfig":{"serviceConfig":{"executionRoleArn":"%s"}}}""" + .formatted(name, role); + String revision = "{\"serviceConfig\":{\"executionRoleArn\":\"" + role + "\"}}"; + + user.policy(allow("lambda:CreateWebFunction", "*") + "," + allow("lambda:CreateWebFunctionRevision", "*")); + denied(user.lambda().body(function).put("/2025-03-07/web-functions").then()); + denied(user.lambda().body(revision).post("/2025-03-07/web-functions/" + name + "/revisions").then()); + + // With the permission the request reaches Lambda, which answers it on its own terms. + user.policy(allow("lambda:CreateWebFunction", "*") + "," + allow("lambda:CreateWebFunctionRevision", "*") + + "," + passRole(role, "lambda.amazonaws.com")); + user.lambda().body(function).put("/2025-03-07/web-functions").then().statusCode(not(403)); + user.lambda().body(revision).post("/2025-03-07/web-functions/" + name + "/revisions").then() + .statusCode(not(403)); + cleanup.register(() -> admin("lambda").delete("/2025-03-07/web-functions/{name}", name)); + } + + @Test + void anInstanceProfileNeedsPassRoleOnItsRoleWhenAnInstanceIsLaunchedOrAssociated() { + String role = role("ec2-instance"); + String roleName = role.substring(role.lastIndexOf('/') + 1); + String profile = instanceProfile(roleName); + String profileArn = "arn:aws:iam::" + ACCOUNT + ":instance-profile/" + profile; + User user = user("passrole-ec2"); + + user.policy(allow("ec2:RunInstances", "*") + "," + allow("ec2:AssociateIamInstanceProfile", "*")); + denied(user.ec2("RunInstances").formParam("ImageId", IMAGE).formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1").formParam("MaxCount", "1") + .formParam("IamInstanceProfile.Name", profile).post("/").then()); + String instanceId = user.ec2("RunInstances").formParam("ImageId", IMAGE).formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1").formParam("MaxCount", "1").post("/").then().statusCode(200) + .extract().xmlPath().getString("RunInstancesResponse.instancesSet.item.instanceId"); + terminateLater(instanceId); + denied(user.ec2("AssociateIamInstanceProfile").formParam("InstanceId", instanceId) + .formParam("IamInstanceProfile.Arn", profileArn).post("/").then()); + // A profile that does not exist passes no role; EC2 refuses it as it would without enforcement. + user.ec2("RunInstances").formParam("ImageId", IMAGE).formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1").formParam("MaxCount", "1") + .formParam("IamInstanceProfile.Name", "no-such-profile").post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + + user.policy(allow("ec2:RunInstances", "*") + "," + allow("ec2:AssociateIamInstanceProfile", "*") + "," + + passRole(role, "ec2.amazonaws.com")); + terminateLater(user.ec2("RunInstances").formParam("ImageId", IMAGE).formParam("InstanceType", "t3.micro") + .formParam("MinCount", "1").formParam("MaxCount", "1") + .formParam("IamInstanceProfile.Name", profile).post("/").then().statusCode(200) + .extract().xmlPath().getString("RunInstancesResponse.instancesSet.item.instanceId")); + String associationId = user.ec2("AssociateIamInstanceProfile").formParam("InstanceId", instanceId) + .formParam("IamInstanceProfile.Arn", profileArn).post("/").then().statusCode(200) + .extract().xmlPath().getString( + "AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.associationId"); + + // Replacing the association passes the new profile's role. + String other = role("ec2-replacement"); + String otherProfile = instanceProfile(other.substring(other.lastIndexOf('/') + 1)); + user.policy(allow("ec2:ReplaceIamInstanceProfileAssociation", "*") + "," + passRole(role, "ec2.amazonaws.com")); + denied(user.ec2("ReplaceIamInstanceProfileAssociation").formParam("AssociationId", associationId) + .formParam("IamInstanceProfile.Name", otherProfile).post("/").then()); + user.policy(allow("ec2:ReplaceIamInstanceProfileAssociation", "*") + "," + passRole(other, "ec2.amazonaws.com")); + user.ec2("ReplaceIamInstanceProfileAssociation").formParam("AssociationId", associationId) + .formParam("IamInstanceProfile.Name", otherProfile).post("/").then().statusCode(200); + } + + @Test + void aSpotInstanceRequestNeedsPassRoleOnItsInstanceProfilesRole() { + String role = role("ec2-spot"); + String profile = instanceProfile(role.substring(role.lastIndexOf('/') + 1)); + String profileArn = "arn:aws:iam::" + ACCOUNT + ":instance-profile/" + profile; + User user = user("passrole-spot"); + + user.policy(allow("ec2:RequestSpotInstances", "*")); + denied(spotRequest(user, "Arn", profileArn).then()); + denied(spotRequest(user, "Name", profile).then()); + + user.policy(allow("ec2:RequestSpotInstances", "*") + "," + passRole(role, "ec2.amazonaws.com")); + assertEquals(profileArn, spotProfileArn(user, "Arn", profileArn)); + // A profile named rather than given by ARN is the same profile, and the instance gets it. + assertEquals(profileArn, spotProfileArn(user, "Name", profile)); + } + + @Test + void aLaunchTemplateWithAnInstanceProfileNeedsPassRoleOnItsRole() { + String role = role("ec2-template"); + String profile = instanceProfile(role.substring(role.lastIndexOf('/') + 1)); + User user = user("passrole-template"); + String name = "passrole-template-" + suffix(); + + user.policy(allow("ec2:CreateLaunchTemplate", "*")); + denied(user.ec2("CreateLaunchTemplate").formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", IMAGE) + .formParam("LaunchTemplateData.IamInstanceProfile.Name", profile).post("/").then()); + + user.policy(allow("ec2:CreateLaunchTemplate", "*") + "," + passRole(role, "ec2.amazonaws.com")); + user.ec2("CreateLaunchTemplate").formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", IMAGE) + .formParam("LaunchTemplateData.IamInstanceProfile.Name", profile).post("/").then().statusCode(200); + cleanup.register(() -> admin("ec2").formParam("Action", "DeleteLaunchTemplate") + .formParam("LaunchTemplateName", name).post("/")); + + // A new version of the template passes its profile's role too. + user.policy(allow("ec2:CreateLaunchTemplateVersion", "*")); + denied(user.ec2("CreateLaunchTemplateVersion").formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", IMAGE) + .formParam("LaunchTemplateData.IamInstanceProfile.Name", profile).post("/").then()); + user.policy(allow("ec2:CreateLaunchTemplateVersion", "*") + "," + passRole(role, "ec2.amazonaws.com")); + user.ec2("CreateLaunchTemplateVersion").formParam("LaunchTemplateName", name) + .formParam("LaunchTemplateData.ImageId", IMAGE) + .formParam("LaunchTemplateData.IamInstanceProfile.Name", profile).post("/").then().statusCode(200); + } + + @Test + void aFlowLogNeedsPassRoleOnItsDeliveryRoleForFlowLogs() { + String role = role("flow-logs"); + String vpcId = admin("ec2").formParam("Action", "DescribeVpcs").post("/").then().statusCode(200) + .extract().xmlPath().getString("DescribeVpcsResponse.vpcSet.item[0].vpcId"); + User user = user("passrole-flow-logs"); + + user.policy(allow("ec2:CreateFlowLogs", "*")); + denied(flowLog(user, vpcId, role).then()); + + user.policy(allow("ec2:CreateFlowLogs", "*") + "," + passRole(role, "vpc-flow-logs.amazonaws.com")); + String flowLogId = flowLog(user, vpcId, role).then().statusCode(200) + .extract().xmlPath().getString("CreateFlowLogsResponse.flowLogIdSet.item"); + cleanup.register(() -> admin("ec2").formParam("Action", "DeleteFlowLogs") + .formParam("FlowLogId.1", flowLogId).post("/")); + } + + /** Requests a Spot Instance, removes it afterwards, and returns the profile ARN it was launched with. */ + private String spotProfileArn(User user, String selector, String profile) { + String item = "RequestSpotInstancesResponse.spotInstanceRequestSet.item."; + XmlPath request = spotRequest(user, selector, profile).then().statusCode(200).extract().xmlPath(); + String requestId = request.getString(item + "spotInstanceRequestId"); + cleanup.register(() -> admin("ec2").formParam("Action", "CancelSpotInstanceRequests") + .formParam("SpotInstanceRequestId.1", requestId).post("/")); + terminateLater(request.getString(item + "instanceId")); + return request.getString(item + "launchSpecification.iamInstanceProfile.arn"); + } + + /** A Spot Instance request naming its instance profile by {@code selector}, {@code Arn} or {@code Name}. */ + private static Response spotRequest(User user, String selector, String profile) { + return user.ec2("RequestSpotInstances").formParam("SpotPrice", "0.05").formParam("InstanceCount", "1") + .formParam("LaunchSpecification.ImageId", IMAGE).formParam("LaunchSpecification.InstanceType", "t3.micro") + .formParam("LaunchSpecification.IamInstanceProfile." + selector, profile).post("/"); + } + + private static Response flowLog(User user, String vpcId, String role) { + return user.ec2("CreateFlowLogs").formParam("ResourceId.1", vpcId).formParam("ResourceType", "VPC") + .formParam("TrafficType", "ALL").formParam("LogGroupName", "passrole-flow-logs") + .formParam("DeliverLogsPermissionArn", role).post("/"); + } + + private static void denied(ValidatableResponse response) { + response.statusCode(403).body(containsString("iam:PassRole")); + } + + private static String allow(String action, String resource) { + return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}"; + } + + private static String passRole(String role, String service) { + return "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"" + role + "\"," + + "\"Condition\":{\"StringEquals\":{\"iam:PassedToService\":\"" + service + "\"}}}"; + } + + private String role(String name) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", name + "-" + suffix(), + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:*\"," + + "\"Resource\":\"*\"}]}"); + } + + private String instanceProfile(String roleName) { + String name = "passrole-profile-" + suffix(); + cleanup.register(() -> EnforcementFixtures.removeInstanceProfile(baseUri.getPort(), auth(ADMIN, "iam"), name)); + admin("iam").formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", name) + .post("/").then().statusCode(200); + admin("iam").formParam("Action", "AddRoleToInstanceProfile").formParam("InstanceProfileName", name) + .formParam("RoleName", roleName).post("/").then().statusCode(200); + return name; + } + + private void terminateLater(String instanceId) { + cleanup.register(() -> admin("ec2").formParam("Action", "TerminateInstances") + .formParam("InstanceId.1", instanceId).post("/")); + } + + private User user(String name) { + String userName = name + "-" + suffix(); + return new User(userName, EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"), + userName).accessKeyId()); + } + + private static RequestSpecification admin(String service) { + return given().header("Authorization", auth(ADMIN, service)); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } + + /** An IAM user whose one inline policy each test replaces. */ + private record User(String name, String accessKeyId) { + + void policy(String statements) { + admin("iam").formParam("Action", "PutUserPolicy").formParam("UserName", name) + .formParam("PolicyName", "p") + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}") + .post("/").then().statusCode(200); + } + + RequestSpecification lambda() { + return given().header("Authorization", auth(accessKeyId, "lambda")).contentType("application/json"); + } + + RequestSpecification ec2(String action) { + return given().header("Authorization", auth(accessKeyId, "ec2")).formParam("Action", action); + } + } +}