Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): check iam:PassRole for EC2 Auto Scaling and Application Auto Scaling (#6186)
Priamo Germosenf731951c53a4
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex c3678bf129..1b686eb815 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -1379,10 +1379,27 @@ role each passes:`ContinueUpdateRollback` pass `RoleARN` to `cloudformation.amazonaws.com` when the request namesone. `CreateStackSet` and `UpdateStackSet` pass `AdministrationRoleARN`, or, for a self-managedStackSet, the default `AWSCloudFormationStackSetAdministrationRole`.--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". A+- **EC2 Auto Scaling:** `CreateLaunchConfiguration` passes the roles of its `IamInstanceProfile`,+ given by name or ARN, or else of the profile of the instance it is made from (`InstanceId`), to+ `ec2.amazonaws.com`. `CreateAutoScalingGroup`, `UpdateAutoScalingGroup` and `StartInstanceRefresh`+ (its desired configuration) pass the roles of the instance profile in each launch template they+ name, at the version the group launches from, there too: the group's own, its mixed instances+ policy's and each override's. A refresh's desired configuration counts as the group will have it+ applied: one naming only a version passes that version of the group's template, and one naming a+ template without a version passes the group's version of it. A `ServiceLinkedRoleARN` other than+ the default `AWSServiceRoleForAutoScaling` (`CreateAutoScalingGroup`, `UpdateAutoScalingGroup`)+ and a lifecycle hook's `RoleARN` (`PutLifecycleHook`, and the hooks `CreateAutoScalingGroup`+ names) go to `autoscaling.amazonaws.com`.+- **Application Auto Scaling:** `RegisterScalableTarget` passes `RoleARN` to+ `application-autoscaling.amazonaws.com` when the request names one.++Launching an instance 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". An+Auto Scaling group does check it: the EC2 Auto Scaling user guide has the permission "needed on the+IAM identity (user or role) that creates or updates an Auto Scaling group using a launch template+that specifies an instance profile", while a group using a launch configuration passes nothing, its+role having been checked when the configuration was created. ACloudFormation operation that names no role uses the stack's own without checking it, as theCloudFormation API reference says the service does "even if the users don't have permission to passit". The CloudFormation user guide has the default StackSet administration role checked "Even whendiff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.javaindex fccaf84bc7..31c2d42849 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@@ -48,6 +48,7 @@ import java.util.Map;import java.util.Optional;import java.util.Set;import java.util.UUID;+import java.util.function.Function;import java.util.regex.Matcher;import java.util.regex.Pattern;@@ -919,9 +920,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {* 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.- * What a request names that holds roles, an instance profile or a task definition, is looked up- * in the request's account, as the service resolves it; one that does not exist passes nothing,- * and the operation reports it. Returns true when the request was aborted.+ * What a request names that holds roles, an instance profile, a launch template or a task+ * definition, is looked up in the request's account, as the service 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,@@ -959,13 +960,26 @@ public class IamEnforcementFilter implements ContainerRequestFilter {@Overridepublic Optional<String> stackSetPermissionModel(String stackSetName) {- for (PassedRoleLookup lookup : roleLookups()) {- Optional<String> model = lookup.stackSetPermissionModel(stackSetName);- if (model.isPresent()) {- return model;- }- }- return Optional.empty();+ return firstFound(lookup -> lookup.stackSetPermissionModel(stackSetName));+ }++ @Override+ public Optional<String> launchTemplateInstanceProfile(String templateId, String templateName,+ String version) {+ return firstFound(lookup -> lookup.launchTemplateInstanceProfile(templateId, templateName, version,+ region));+ }++ @Override+ public Optional<String> launchConfigurationInstanceProfile(String instanceId) {+ return firstFound(lookup -> lookup.launchConfigurationInstanceProfile(instanceId, region));+ }++ @Override+ public Optional<String> instanceRefreshInstanceProfile(String groupName, String templateId,+ String templateName, String version) {+ return firstFound(lookup -> lookup.instanceRefreshInstanceProfile(groupName, templateId, templateName,+ version, region));}@Override@@ -979,6 +993,17 @@ public class IamEnforcementFilter implements ContainerRequestFilter {return passedRoleLookups == null || passedRoleLookups.isUnsatisfied() ? List.of() : passedRoleLookups;}+ /** The first answer a {@link PassedRoleLookup} gives, each answering only for what its service owns. */+ private Optional<String> firstFound(Function<PassedRoleLookup, Optional<String>> question) {+ for (PassedRoleLookup lookup : roleLookups()) {+ Optional<String> answer = question.apply(lookup);+ if (answer.isPresent()) {+ return answer;+ }+ }+ return Optional.empty();+ }+/** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */private List<String> instanceProfileRoleArns(String accountId, String name, String arn) {String profileName = arn != null ? arn.substring(arn.lastIndexOf('/') + 1) : name;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.javaindex 53c8e1b79c..c480c3a06c 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java@@ -28,6 +28,18 @@ import java.util.regex.Pattern;* role to an instance even if they don't have the iam:PassRole permission", so the role is checked* where the template is created.*+ * <p>An Auto Scaling group is different: the EC2 Auto Scaling user guide has the permission "needed on+ * the IAM identity (user or role) that creates or updates an Auto Scaling group using a launch template+ * that specifies an instance profile", and an instance refresh to a desired configuration needs it+ * the same way. A group request passes the roles of the instance profile in each launch template it+ * names, at the version the group launches from, to {@code ec2.amazonaws.com}; a refresh's desired+ * configuration is read merged with the group, as Auto Scaling applies it. A launch configuration+ * passes its profile's roles where it is created, the one it names or else the one of the instance it+ * is made from. A service-linked role the request names and a lifecycle hook's role go+ * to {@code autoscaling.amazonaws.com}, except the default service-linked role: the permission is+ * "Needed when a nondefault service-linked role, an IAM role for a lifecycle hook, or a launch+ * template that specifies an instance profile ... is provided".+ ** <p>An ECS request that starts tasks from a task definition passes the definition's task role and* task execution role: the ECS developer guide has the role EventBridge runs scheduled tasks with* hold {@code iam:PassRole} "for each task execution role, task role, or task role override". A role@@ -63,9 +75,14 @@ final class PassedRoles {private static final String SCHEDULER = ServicePrincipals.of("scheduler");private static final String PIPES = ServicePrincipals.of("pipes");private static final String CLOUDFORMATION = ServicePrincipals.of("cloudformation");+ private static final String AUTOSCALING = ServicePrincipals.of("autoscaling");+ private static final String APPLICATION_AUTOSCALING = ServicePrincipals.of("application-autoscaling");private static final String STACK_SET_ADMINISTRATION_ROLE = "AWSCloudFormationStackSetAdministrationRole";private static final String SERVICE_MANAGED = "SERVICE_MANAGED";+ /** The end of the default Auto Scaling service-linked role's ARN; passing that role needs no permission. */+ private static final String DEFAULT_AUTOSCALING_ROLE =+ ":role/aws-service-role/" + AUTOSCALING + "/AWSServiceRoleForAutoScaling";/** A role a request passes, and the service principal it is passed to. */record PassedRole(String roleArn, String passedToService) {@@ -83,6 +100,22 @@ final class PassedRoles {/** The permission model of the StackSet named {@code stackSetName}; empty when there is none. */Optional<String> stackSetPermissionModel(String stackSetName);+ /**+ * The instance profile, by its ARN or else its name, of the launch template version an Auto Scaling+ * group launches from when it names this template and version; empty when there is none.+ */+ Optional<String> launchTemplateInstanceProfile(String templateId, String templateName, String version);++ /** The instance profile, by its ARN, a launch configuration made from this EC2 instance takes from it. */+ Optional<String> launchConfigurationInstanceProfile(String instanceId);++ /**+ * The instance profile of the launch template version the group launches from once an instance+ * refresh applies this desired configuration, each part as the request gives it or null.+ */+ Optional<String> instanceRefreshInstanceProfile(String groupName, String templateId, String templateName,+ String version);+/** The ARN of the role {@code roleName}, a name with any path, names in the request's account. */String roleArn(String roleName);}@@ -120,6 +153,12 @@ final class PassedRoles {fromForm(ctx, CLOUDFORMATION, "RoleARN");case "cloudformation:CreateStackSet", "cloudformation:UpdateStackSet" ->stackSetAdministrationRole(ctx, lookups, "cloudformation:UpdateStackSet".equals(action));+ case "autoscaling:CreateLaunchConfiguration" -> launchConfiguration(ctx, lookups);+ case "autoscaling:CreateAutoScalingGroup", "autoscaling:UpdateAutoScalingGroup" ->+ autoScalingGroup(ctx, lookups);+ case "autoscaling:StartInstanceRefresh" -> instanceRefresh(ctx, lookups);+ case "autoscaling:PutLifecycleHook" -> fromForm(ctx, AUTOSCALING, "RoleARN");+ case "application-autoscaling:RegisterScalableTarget" -> fromJson(ctx, APPLICATION_AUTOSCALING, "RoleARN");default -> List.of();};}@@ -204,6 +243,95 @@ final class PassedRoles {? List.of() : passed(List.of(lookups.roleArn(STACK_SET_ADMINISTRATION_ROLE)), CLOUDFORMATION);}+ /** The roles of the profile a launch configuration names, or else takes from the instance it is made from. */+ private static List<PassedRole> launchConfiguration(ContainerRequestContext ctx, Lookups lookups) {+ Map<String, String> form = IamConditionContextResolver.formParameters(ctx);+ String profile = blankToNull(form.get("IamInstanceProfile"));+ String instanceId = blankToNull(form.get("InstanceId"));+ if (profile == null && instanceId != null) {+ profile = lookups.launchConfigurationInstanceProfile(instanceId).orElse(null);+ }+ return fromInstanceProfile(lookups, profile);+ }++ /**+ * StartInstanceRefresh: the roles of the launch template the group launches from once the desired+ * configuration is applied to it, which may name only a version of the group's template or keep the+ * group's version for a template it names, and those of its mixed instances policy's templates.+ */+ private static List<PassedRole> instanceRefresh(ContainerRequestContext ctx, Lookups lookups) {+ Map<String, String> form = IamConditionContextResolver.formParameters(ctx);+ String desired = "DesiredConfiguration.LaunchTemplate.";+ List<PassedRole> passed = new ArrayList<>();+ String group = blankToNull(form.get("AutoScalingGroupName"));+ if (group != null) {+ lookups.instanceRefreshInstanceProfile(group, form.get(desired + "LaunchTemplateId"),+ form.get(desired + "LaunchTemplateName"), form.get(desired + "Version"))+ .ifPresent(profile -> passed.addAll(fromInstanceProfile(lookups, profile)));+ }+ passed.addAll(mixedInstancesPolicyRoles(form, "DesiredConfiguration.", lookups));+ return passed;+ }++ /**+ * CreateAutoScalingGroup and UpdateAutoScalingGroup: the roles of the launch templates' instance+ * profiles, and a service-linked role and the lifecycle hooks' roles.+ */+ private static List<PassedRole> autoScalingGroup(ContainerRequestContext ctx, Lookups lookups) {+ Map<String, String> form = IamConditionContextResolver.formParameters(ctx);+ List<String> roles = new ArrayList<>();+ String serviceLinkedRole = blankToNull(form.get("ServiceLinkedRoleARN"));+ if (serviceLinkedRole != null && !serviceLinkedRole.endsWith(DEFAULT_AUTOSCALING_ROLE)) {+ roles.add(serviceLinkedRole);+ }+ for (String hook : members(form, "LifecycleHookSpecificationList")) {+ roles.add(form.get(hook + "RoleARN"));+ }+ List<PassedRole> passed = new ArrayList<>(launchTemplateRoles(form, "LaunchTemplate.", lookups));+ passed.addAll(mixedInstancesPolicyRoles(form, "", lookups));+ passed.addAll(passed(roles, AUTOSCALING));+ return passed;+ }++ /** The roles of the mixed instances policy's launch template under {@code prefix}, and of each override's. */+ private static List<PassedRole> mixedInstancesPolicyRoles(Map<String, String> form, String prefix,+ Lookups lookups) {+ String mixed = prefix + "MixedInstancesPolicy.LaunchTemplate.";+ List<PassedRole> passed = new ArrayList<>(launchTemplateRoles(form, mixed + "LaunchTemplateSpecification.",+ lookups));+ for (String override : members(form, mixed + "Overrides")) {+ passed.addAll(launchTemplateRoles(form, override + "LaunchTemplateSpecification.", lookups));+ }+ return passed;+ }++ /** The roles of the instance profile in the launch template a request names under {@code template}. */+ private static List<PassedRole> launchTemplateRoles(Map<String, String> form, String template, Lookups lookups) {+ String id = blankToNull(form.get(template + "LaunchTemplateId"));+ String name = blankToNull(form.get(template + "LaunchTemplateName"));+ if (id == null && name == null) {+ return List.of();+ }+ return lookups.launchTemplateInstanceProfile(id, name, blankToNull(form.get(template + "Version")))+ .map(profile -> fromInstanceProfile(lookups, profile))+ .orElse(List.of());+ }++ /**+ * The prefix of each {@code list}.member.N, from 1 up to the first N the form holds nothing under,+ * as the handlers read numbered members.+ */+ private static List<String> members(Map<String, String> form, String list) {+ List<String> members = new ArrayList<>();+ for (int i = 1; ; i++) {+ String member = list + ".member." + i + ".";+ if (form.keySet().stream().noneMatch(key -> key.startsWith(member))) {+ return members;+ }+ members.add(member);+ }+ }+private static List<PassedRole> fromJson(ContainerRequestContext ctx, String service, String... path) {return passed(values(jsonBody(ctx), path), service);}@@ -252,6 +380,15 @@ final class PassedRoles {return passed(lookups.instanceProfileRoleArns(name, arn), EC2);}+ /** The roles of the instance profile {@code profile}, given by its name or its ARN. */+ private static List<PassedRole> fromInstanceProfile(Lookups lookups, String profile) {+ if (profile == null || profile.isBlank()) {+ return List.of();+ }+ boolean arn = AwsArnUtils.isArn(profile);+ return passed(lookups.instanceProfileRoleArns(arn ? null : profile, arn ? profile : null), EC2);+ }+/** The roles that are IAM role ARNs; anything else is left for the operation to refuse. */private static List<PassedRole> passed(List<String> roleArns, String service) {List<PassedRole> passed = new ArrayList<>();diff --git a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.javaindex bd274cf70d..d5680924a9 100644--- a/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java+++ b/src/main/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingService.java@@ -16,9 +16,11 @@ import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;+import io.github.hectorvent.floci.services.iam.PassedRoleLookup;import jakarta.annotation.PostConstruct;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import org.jboss.logging.Logger;import java.nio.charset.StandardCharsets;import java.time.Instant;@@ -31,8 +33,9 @@ import java.util.regex.Pattern;import java.util.stream.Collectors;@ApplicationScoped-public class AutoScalingService {+public class AutoScalingService implements PassedRoleLookup {+ private static final Logger LOG = Logger.getLogger(AutoScalingService.class);private static final String FULLY_FORMED_LAUNCH_TEMPLATE = "You must use a valid fully-formed launch template. ";static final String MISSING_LAUNCH_TEMPLATE_IMAGE_ID_MESSAGE =FULLY_FORMED_LAUNCH_TEMPLATE + "The request must contain the parameter ImageId";@@ -195,12 +198,9 @@ public class AutoScalingService {throw new AwsException("ValidationError", INVALID_LAUNCH_CONFIGURATION_PARAMETERS_MESSAGE, 400);}if (notBlank(instanceId) && ec2Service != null) {- List<Instance> sourceInstances = ec2Service.describeInstances(region, List.of(instanceId), Map.of())- .stream()- .flatMap(reservation -> reservation.getInstances().stream())- .collect(Collectors.toList());- if (!sourceInstances.isEmpty()) {- Instance source = sourceInstances.getFirst();+ Optional<Instance> sourceInstance = sourceInstance(region, instanceId);+ if (sourceInstance.isPresent()) {+ Instance source = sourceInstance.get();if (isBlank(imageId)) {imageId = source.getImageId();}@@ -285,6 +285,29 @@ public class AutoScalingService {}}+ /** The EC2 instance a launch configuration is made from, which it derives what the request leaves out from. */+ private Optional<Instance> sourceInstance(String region, String instanceId) {+ return ec2Service.describeInstances(region, List.of(instanceId), Map.of()).stream()+ .flatMap(reservation -> reservation.getInstances().stream())+ .findFirst();+ }++ /** The instance profile a launch configuration made from the instance takes, for the {@code iam:PassRole} check. */+ @Override+ public Optional<String> launchConfigurationInstanceProfile(String instanceId, String region) {+ if (ec2Service == null || isBlank(instanceId)) {+ return Optional.empty();+ }+ try {+ return sourceInstance(region, instanceId).map(Instance::getIamInstanceProfileArn)+ .filter(profile -> !isBlank(profile));+ } catch (AwsException e) {+ // An instance that does not exist is the operation's to refuse, and passes no role.+ LOG.debugv("Instance {0} passes no role: {1}", instanceId, e.getMessage());+ return Optional.empty();+ }+ }+String resolveLaunchConfigurationProfile(String profile) {if (isBlank(profile)) {return null;@@ -1730,6 +1753,37 @@ public class AutoScalingService {}}+ /**+ * The instance profile a group's instances get from the launch template version, resolved as the+ * group's own validation resolves it, for the {@code iam:PassRole} check of the operations naming it.+ */+ @Override+ public Optional<String> launchTemplateInstanceProfile(String templateId, String templateName, String version,+ String region) {+ if (ec2Service == null || (isBlank(templateId) && isBlank(templateName))) {+ return Optional.empty();+ }+ List<LaunchTemplate> versions;+ try {+ versions = ec2Service.describeLaunchTemplateVersions(region, templateId, templateName,+ isBlank(version) ? List.of() : List.of(version));+ } catch (AwsException e) {+ // A version that does not exist is the operation's to refuse, and passes no role.+ LOG.debugv("Launch template {0} has no version {1}, so it passes no role: {2}",+ isBlank(templateId) ? templateName : templateId, version, e.getMessage());+ return Optional.empty();+ }+ LaunchTemplateData.IamInstanceProfile profile =+ versions.isEmpty() ? null : versions.getFirst().getData().getIamInstanceProfile();+ if (profile == null) {+ return Optional.empty();+ }+ if (!isBlank(profile.getArn())) {+ return Optional.of(profile.getArn());+ }+ return isBlank(profile.getName()) ? Optional.empty() : Optional.of(profile.getName());+ }+private static MixedInstancesPolicy.LaunchTemplateSpecification mixedInstancesLaunchTemplateSpecification(MixedInstancesPolicy policy) {if (policy == null || policy.getLaunchTemplate() == null) {@@ -1857,14 +1911,47 @@ public class AutoScalingService {if (!refresh.hasDesiredConfiguration()) {return;}- if (refresh.getDesiredLaunchTemplateId() != null || refresh.getDesiredLaunchTemplateName() != null) {- asg.setLaunchTemplateId(refresh.getDesiredLaunchTemplateId());- asg.setLaunchTemplateName(refresh.getDesiredLaunchTemplateName());+ DesiredLaunchTemplate desired = desiredLaunchTemplate(asg, refresh.getDesiredLaunchTemplateId(),+ refresh.getDesiredLaunchTemplateName(), refresh.getDesiredLaunchTemplateVersion());+ if (desired.replacesTemplate()) {asg.setLaunchConfigurationName(null);}- if (refresh.getDesiredLaunchTemplateVersion() != null) {- asg.setLaunchTemplateVersion(refresh.getDesiredLaunchTemplateVersion());- }+ asg.setLaunchTemplateId(desired.id());+ asg.setLaunchTemplateName(desired.name());+ asg.setLaunchTemplateVersion(desired.version());+ }++ /** The launch template a group launches from once a refresh's desired configuration is applied to it. */+ private record DesiredLaunchTemplate(String id, String name, String version, boolean replacesTemplate) {+ }++ /**+ * A desired configuration naming a template replaces the group's, and one naming a version replaces+ * its version, so a template named without a version keeps the group's version number.+ */+ private static DesiredLaunchTemplate desiredLaunchTemplate(AutoScalingGroup asg, String templateId,+ String templateName, String version) {+ boolean replacesTemplate = templateId != null || templateName != null;+ return new DesiredLaunchTemplate(+ replacesTemplate ? templateId : asg.getLaunchTemplateId(),+ replacesTemplate ? templateName : asg.getLaunchTemplateName(),+ version != null ? version : asg.getLaunchTemplateVersion(),+ replacesTemplate);+ }++ /**+ * The instance profile the group launches with once the refresh applies its desired configuration,+ * merged with the group as {@link #applyDesiredConfiguration} merges it, for the {@code iam:PassRole} check.+ */+ @Override+ public Optional<String> instanceRefreshInstanceProfile(String groupName, String templateId, String templateName,+ String version, String region) {+ AutoScalingGroup asg = isBlank(groupName) ? null : groups.get(asgKey(region, groupName));+ if (asg == null || (templateId == null && templateName == null && version == null)) {+ return Optional.empty();+ }+ DesiredLaunchTemplate desired = desiredLaunchTemplate(asg, templateId, templateName, version);+ return launchTemplateInstanceProfile(desired.id(), desired.name(), desired.version(), region);}private static List<String> markInstancesForRefresh(AutoScalingGroup asg, InstanceRefresh refresh) {diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java b/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.javaindex e4549f3f35..a93aef47bf 100644--- a/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java+++ b/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java@@ -6,8 +6,9 @@ import java.util.Optional;/*** Looks up what a stored resource holds that the {@code iam:PassRole} check of a request needs, for* the operations that pass a role the request does not name itself: an ECS task started from a task- * definition runs with the definition's roles, and a self-managed StackSet that names no- * administration role uses the default one.+ * definition runs with the definition's roles, a self-managed StackSet that names no+ * administration role uses the default one, and an Auto Scaling group launches its instances with+ * the instance profile of its launch template, or of the instance its launch configuration was made from.** <p>Implemented by the services that own those resources, each answering for its own and leaving* the default for the rest; consumed lazily by {@code IamEnforcementFilter} via@@ -29,4 +30,35 @@ public interface PassedRoleLookup {default Optional<String> stackSetPermissionModel(String stackSetName) {return Optional.empty();}++ /**+ * The instance profile, by its ARN or else its name, of the launch template version an Auto Scaling+ * group launches from when it names the template {@code templateId} or {@code templateName} and+ * {@code version} in {@code region}; empty when there is no such template or version, or it names+ * no instance profile.+ */+ default Optional<String> launchTemplateInstanceProfile(String templateId, String templateName, String version,+ String region) {+ return Optional.empty();+ }++ /**+ * The instance profile, by its ARN, that a launch configuration made from the EC2 instance+ * {@code instanceId} in {@code region} takes from it; empty when there is no such instance or it has none.+ */+ default Optional<String> launchConfigurationInstanceProfile(String instanceId, String region) {+ return Optional.empty();+ }++ /**+ * The instance profile, by its ARN or else its name, of the launch template version the group+ * {@code groupName} in {@code region} launches from once an instance refresh applies a desired+ * configuration naming {@code templateId}, {@code templateName} and {@code version}, each as the+ * request gives it or null; empty when there is no such group, it then launches from no launch+ * template, or that version names no instance profile.+ */+ default Optional<String> instanceRefreshInstanceProfile(String groupName, String templateId, String templateName,+ String version, String region) {+ return Optional.empty();+ }}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.javaindex 418964a03f..63f0479da7 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java@@ -30,12 +30,51 @@ class PassedRolesTest {private static final String ECS_TASKS = "ecs-tasks.amazonaws.com";private static final String CLOUDFORMATION = "cloudformation.amazonaws.com";private static final String DEFAULT_ADMINISTRATION = ROLES + "AWSCloudFormationStackSetAdministrationRole";+ private static final String EC2 = "ec2.amazonaws.com";+ private static final String AUTOSCALING = "autoscaling.amazonaws.com";+ private static final String PROFILE_ARN = "arn:aws:iam::111122223333:instance-profile/arn-profile";- /** A task definition {@code web:3} holding a task role by ARN and an execution role by name, and two StackSets. */+ /**+ * A task definition {@code web:3} holding a task role by ARN and an execution role by name, two+ * StackSets, two instance profiles, and the launch templates {@code lt-web}, whose every version+ * names one profile by name, and {@code arn-template}, whose version 2 names the other by ARN. The+ * instance {@code i-arn} runs with that other profile, and the group {@code g} launches from+ * {@code lt-web} once a refresh names only a version, or from {@code arn-template} at the group's+ * version 2 once a refresh names that template alone.+ */private static final PassedRoles.Lookups LOOKUPS = new PassedRoles.Lookups() {@Overridepublic List<String> instanceProfileRoleArns(String profileName, String profileArn) {- return List.of();+ if ("web-profile".equals(profileName)) {+ return List.of(ROLES + "web-instance");+ }+ return PROFILE_ARN.equals(profileArn) ? List.of(ROLES + "arn-instance") : List.of();+ }++ @Override+ public Optional<String> launchTemplateInstanceProfile(String templateId, String templateName, String version) {+ if ("lt-web".equals(templateId)) {+ return Optional.of("web-profile");+ }+ return "arn-template".equals(templateName) && "2".equals(version)+ ? Optional.of(PROFILE_ARN) : Optional.empty();+ }++ @Override+ public Optional<String> launchConfigurationInstanceProfile(String instanceId) {+ return "i-arn".equals(instanceId) ? Optional.of(PROFILE_ARN) : Optional.empty();+ }++ @Override+ public Optional<String> instanceRefreshInstanceProfile(String groupName, String templateId,+ String templateName, String version) {+ if (!"g".equals(groupName)) {+ return Optional.empty();+ }+ if (templateId == null && templateName == null && "2".equals(version)) {+ return Optional.of("web-profile");+ }+ return "arn-template".equals(templateName) && version == null ? Optional.of(PROFILE_ARN) : Optional.empty();}@Override@@ -184,6 +223,99 @@ class PassedRolesTest {form("StackSetName=org-set&AdministrationRoleARN=" + ROLES + "admin"), LOOKUPS));}+ @Test+ void aLaunchConfigurationPassesItsInstanceProfilesRolesToEc2ByNameOrArn() {+ assertEquals(List.of(passed("web-instance", EC2)), PassedRoles.of("autoscaling:CreateLaunchConfiguration",+ form("LaunchConfigurationName=c&IamInstanceProfile=web-profile"), LOOKUPS));+ assertEquals(List.of(passed("arn-instance", EC2)), PassedRoles.of("autoscaling:CreateLaunchConfiguration",+ form("LaunchConfigurationName=c&IamInstanceProfile=" + PROFILE_ARN), LOOKUPS));+ assertEquals(List.of(), PassedRoles.of("autoscaling:CreateLaunchConfiguration",+ form("LaunchConfigurationName=c&IamInstanceProfile=missing"), LOOKUPS));+ }++ @Test+ void aLaunchConfigurationMadeFromAnInstancePassesTheInstancesProfileUnlessItNamesOne() {+ assertEquals(List.of(passed("arn-instance", EC2)), PassedRoles.of("autoscaling:CreateLaunchConfiguration",+ form("LaunchConfigurationName=c&InstanceId=i-arn"), LOOKUPS));+ assertEquals(List.of(passed("web-instance", EC2)), PassedRoles.of("autoscaling:CreateLaunchConfiguration",+ form("LaunchConfigurationName=c&InstanceId=i-arn&IamInstanceProfile=web-profile"), LOOKUPS));+ assertEquals(List.of(), PassedRoles.of("autoscaling:CreateLaunchConfiguration",+ form("LaunchConfigurationName=c&InstanceId=i-none"), LOOKUPS));+ }++ @Test+ void aGroupPassesTheRolesOfEachLaunchTemplatesInstanceProfileToEc2AtTheVersionItNames() {+ for (String action : List.of("CreateAutoScalingGroup", "UpdateAutoScalingGroup")) {+ assertEquals(List.of(passed("web-instance", EC2)), PassedRoles.of("autoscaling:" + action,+ form("LaunchTemplate.LaunchTemplateId=lt-web"), LOOKUPS), action);+ assertEquals(List.of(passed("arn-instance", EC2)), PassedRoles.of("autoscaling:" + action,+ form("LaunchTemplate.LaunchTemplateName=arn-template&LaunchTemplate.Version=2"), LOOKUPS), action);+ // A version whose data names no profile passes nothing, nor does a launch configuration.+ assertEquals(List.of(), PassedRoles.of("autoscaling:" + action,+ form("LaunchTemplate.LaunchTemplateName=arn-template&LaunchTemplate.Version=1"), LOOKUPS), action);+ assertEquals(List.of(), PassedRoles.of("autoscaling:" + action,+ form("LaunchConfigurationName=c"), LOOKUPS), action);++ // A mixed instances policy names its template, and each override may name another.+ String mixed = "MixedInstancesPolicy.LaunchTemplate.";+ String policy = mixed + "LaunchTemplateSpecification.LaunchTemplateName=arn-template&"+ + mixed + "LaunchTemplateSpecification.Version=2&"+ + mixed + "Overrides.member.1.InstanceType=t3.micro&"+ + mixed + "Overrides.member.2.LaunchTemplateSpecification.LaunchTemplateId=lt-web";+ assertEquals(List.of(passed("arn-instance", EC2), passed("web-instance", EC2)),+ PassedRoles.of("autoscaling:" + action, form(policy), LOOKUPS), action);+ }+ }++ @Test+ void aGroupPassesAServiceLinkedRoleOtherThanTheDefaultAndItsHooksRolesToAutoScaling() {+ String serviceLinked = "aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling";+ assertEquals(List.of(passed(serviceLinked + "_custom", AUTOSCALING)),+ PassedRoles.of("autoscaling:UpdateAutoScalingGroup",+ form("ServiceLinkedRoleARN=" + ROLES + serviceLinked + "_custom"), LOOKUPS));+ assertEquals(List.of(), PassedRoles.of("autoscaling:UpdateAutoScalingGroup",+ form("ServiceLinkedRoleARN=" + ROLES + serviceLinked), LOOKUPS));++ String hooks = "LifecycleHookSpecificationList.member.";+ assertEquals(List.of(passed("web-instance", EC2), passed(serviceLinked + "_custom", AUTOSCALING),+ passed("hook", AUTOSCALING), passed("other-hook", AUTOSCALING)),+ PassedRoles.of("autoscaling:CreateAutoScalingGroup", form("LaunchTemplate.LaunchTemplateId=lt-web"+ + "&ServiceLinkedRoleARN=" + ROLES + serviceLinked + "_custom"+ + "&" + hooks + "1.RoleARN=" + ROLES + "hook&" + hooks + "2.LifecycleHookName=no-role"+ + "&" + hooks + "3.RoleARN=" + ROLES + "other-hook"+ + "&" + hooks + "5.RoleARN=" + ROLES + "after-a-gap"), LOOKUPS));+ }++ @Test+ void anInstanceRefreshPassesTheRolesOfTheTemplateItsGroupLaunchesFromOnceTheDesiredConfigurationApplies() {+ // The desired configuration goes to the group's own lookup as given, a version alone or a template alone.+ assertEquals(List.of(passed("web-instance", EC2)), PassedRoles.of("autoscaling:StartInstanceRefresh",+ form("AutoScalingGroupName=g&DesiredConfiguration.LaunchTemplate.Version=2"), LOOKUPS));+ assertEquals(List.of(passed("arn-instance", EC2)), PassedRoles.of("autoscaling:StartInstanceRefresh",+ form("AutoScalingGroupName=g&DesiredConfiguration.LaunchTemplate.LaunchTemplateName=arn-template"),+ LOOKUPS));+ String desired = "DesiredConfiguration.MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.";+ assertEquals(List.of(passed("arn-instance", EC2)), PassedRoles.of("autoscaling:StartInstanceRefresh",+ form("AutoScalingGroupName=g&" + desired + "LaunchTemplateName=arn-template&" + desired + "Version=2"),+ LOOKUPS));+ // Without a desired configuration the refresh uses the group's own template, checked when the group named it.+ assertEquals(List.of(), PassedRoles.of("autoscaling:StartInstanceRefresh",+ form("AutoScalingGroupName=g"), LOOKUPS));+ }++ @Test+ void aLifecycleHookAndAScalableTargetPassTheRoleTheyName() {+ assertEquals(List.of(passed("hook", AUTOSCALING)), PassedRoles.of("autoscaling:PutLifecycleHook",+ form("AutoScalingGroupName=g&LifecycleHookName=h&RoleARN=" + ROLES + "hook"), LOOKUPS));+ assertEquals(List.of(), PassedRoles.of("autoscaling:PutLifecycleHook",+ form("AutoScalingGroupName=g&LifecycleHookName=h"), LOOKUPS));+ assertEquals(List.of(passed("scaling", "application-autoscaling.amazonaws.com")),+ PassedRoles.of("application-autoscaling:RegisterScalableTarget",+ json("{\"ServiceNamespace\":\"ecs\",\"RoleARN\":\"" + ROLES + "scaling\"}"), LOOKUPS));+ assertEquals(List.of(), PassedRoles.of("application-autoscaling:RegisterScalableTarget",+ json("{\"ServiceNamespace\":\"ecs\"}"), LOOKUPS));+ }+private static PassedRole passed(String roleName, String service) {return new PassedRole(ROLES + roleName, service);}diff --git a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.javaindex 54fe56bc0d..e4019fcb3a 100644--- a/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/autoscaling/AutoScalingServiceTest.java@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;import io.github.hectorvent.floci.services.ec2.model.Instance;import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;+import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;import io.github.hectorvent.floci.services.ec2.model.Reservation;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -32,6 +33,7 @@ import java.util.Base64;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.Set;import java.util.stream.Stream;import java.util.zip.GZIPOutputStream;@@ -40,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.*;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.verifyNoInteractions;import static org.mockito.Mockito.when;class AutoScalingServiceTest {@@ -132,6 +135,43 @@ class AutoScalingServiceTest {assertNull(group.getLaunchConfigurationName());}+ @Test+ void anInstanceRefreshResolvesTheProfileOfTheTemplateItsGroupLaunchesFromOnceItApplies() {+ Ec2Service ec2Service = mock(Ec2Service.class);+ service.ec2Service = ec2Service;+ when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-original", null, List.of("1")))+ .thenReturn(List.of(withProfile("version-one")));+ when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-original", null, List.of("2")))+ .thenReturn(List.of(withProfile("version-two")));+ when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-other", null, List.of("1")))+ .thenReturn(List.of(withProfile("other-at-one")));++ // The group launches from lt-original version 1: a version alone moves it, a template alone keeps it.+ assertEquals(Optional.of("version-two"),+ service.instanceRefreshInstanceProfile("test-asg", null, null, "2", REGION));+ assertEquals(Optional.of("other-at-one"),+ service.instanceRefreshInstanceProfile("test-asg", "lt-other", null, null, REGION));+ // Without a desired configuration the group keeps the template it was checked for when it named it.+ assertEquals(Optional.empty(), service.instanceRefreshInstanceProfile("test-asg", null, null, null, REGION));+ assertEquals(Optional.empty(),+ service.instanceRefreshInstanceProfile("no-such-group", null, null, "2", REGION));+ }++ @Test+ void aLaunchTemplateLookupNamingNoTemplateFindsNoProfileRatherThanAnyTemplatesProfile() {+ Ec2Service ec2Service = mock(Ec2Service.class);+ service.ec2Service = ec2Service;++ assertEquals(Optional.empty(), service.launchTemplateInstanceProfile(null, " ", "2", REGION));+ verifyNoInteractions(ec2Service);+ }++ private static LaunchTemplate withProfile(String profileName) {+ LaunchTemplate version = new LaunchTemplate();+ version.getData().setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(null, profileName));+ return version;+ }+@Testvoid createAutoScalingGroupRejectsResolvedLaunchTemplateWithoutImageId() {Ec2Service ec2Service = mock(Ec2Service.class);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.javaindex 3e62e2251f..1a1ae1613d 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java@@ -49,6 +49,9 @@ class IamPassRoleEnforcementIntegrationTest {private static final String QUEUE_ARN = "arn:aws:sqs:us-east-1:" + ACCOUNT + ":passrole-queue";private static final String SCHEDULER = "scheduler.amazonaws.com";private static final String PIPES = "pipes.amazonaws.com";+ private static final String AUTOSCALING = "autoscaling.amazonaws.com";+ private static final String SERVICE_LINKED_ROLES =+ "arn:aws:iam::" + ACCOUNT + ":role/aws-service-role/autoscaling.amazonaws.com/";private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());@TestHTTPResource("/")@@ -498,6 +501,215 @@ class IamPassRoleEnforcementIntegrationTest {}/** Requests a Spot Instance, removes it afterwards, and returns the profile ARN it was launched with. */+ @Test+ void aLaunchConfigurationNeedsPassRoleOnItsInstanceProfilesRoleForEc2() {+ String role = role("asg-config");+ String profile = instanceProfile(roleName(role));+ String profileArn = "arn:aws:iam::" + ACCOUNT + ":instance-profile/" + profile;+ User user = user("passrole-launch-config");+ String name = "passrole-config-" + suffix();++ // The role goes to the instances, so a grant to pass it to Auto Scaling does not cover it.+ user.policy(allow("autoscaling:CreateLaunchConfiguration", "*") + "," + passRole(role, AUTOSCALING));+ denied(launchConfiguration(user, name, profile).then());+ denied(launchConfiguration(user, name, profileArn).then());++ user.policy(allow("autoscaling:CreateLaunchConfiguration", "*") + "," + passRole(role, "ec2.amazonaws.com"));+ launchConfiguration(user, name, profileArn).then().statusCode(200);+ cleanup.register(() -> admin("autoscaling").formParam("Action", "DeleteLaunchConfiguration")+ .formParam("LaunchConfigurationName", name).post("/"));+ }++ @Test+ void aLaunchConfigurationMadeFromAnInstanceNeedsPassRoleOnTheRoleOfTheProfileItTakes() {+ String role = role("asg-from-instance");+ String profile = instanceProfile(roleName(role));+ String instanceId = admin("ec2").formParam("Action", "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");+ terminateLater(instanceId);+ User user = user("passrole-config-instance");+ String name = "passrole-instance-config-" + suffix();++ user.policy(allow("autoscaling:CreateLaunchConfiguration", "*"));+ denied(user.autoscaling("CreateLaunchConfiguration").formParam("LaunchConfigurationName", name)+ .formParam("InstanceId", instanceId).post("/").then());++ user.policy(allow("autoscaling:CreateLaunchConfiguration", "*") + "," + passRole(role, "ec2.amazonaws.com"));+ user.autoscaling("CreateLaunchConfiguration").formParam("LaunchConfigurationName", name)+ .formParam("InstanceId", instanceId).post("/").then().statusCode(200);+ cleanup.register(() -> admin("autoscaling").formParam("Action", "DeleteLaunchConfiguration")+ .formParam("LaunchConfigurationName", name).post("/"));+ }++ @Test+ void aGroupNeedsPassRoleOnTheRoleOfItsLaunchTemplatesInstanceProfileAtTheVersionItLaunches() {+ String role = role("asg-template");+ String templateId = launchTemplate(null, instanceProfile(roleName(role)));+ User user = user("passrole-asg");+ String group = "passrole-asg-" + suffix();+ String actions = allow("autoscaling:CreateAutoScalingGroup", "*") + ","+ + allow("autoscaling:UpdateAutoScalingGroup", "*") + ","+ + allow("autoscaling:StartInstanceRefresh", "*");++ user.policy(actions);+ denied(group(user, "CreateAutoScalingGroup", group).formParam("LaunchTemplate.LaunchTemplateId", templateId)+ .formParam("LaunchTemplate.Version", "$Latest").post("/").then());+ String mixed = "MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification.";+ denied(group(user, "CreateAutoScalingGroup", group).formParam(mixed + "LaunchTemplateId", templateId)+ .formParam(mixed + "Version", "2").post("/").then());+ // Version 1 names no instance profile, so a group launching from it passes no role.+ group(user, "CreateAutoScalingGroup", group).formParam("LaunchTemplate.LaunchTemplateId", templateId)+ .formParam("LaunchTemplate.Version", "1").post("/").then().statusCode(200);+ cleanup.register(() -> admin("autoscaling").formParam("Action", "DeleteAutoScalingGroup")+ .formParam("AutoScalingGroupName", group).formParam("ForceDelete", "true").post("/"));++ denied(group(user, "UpdateAutoScalingGroup", group).formParam("LaunchTemplate.LaunchTemplateId", templateId)+ .formParam("LaunchTemplate.Version", "2").post("/").then());+ denied(user.autoscaling("StartInstanceRefresh").formParam("AutoScalingGroupName", group)+ .formParam("DesiredConfiguration.LaunchTemplate.LaunchTemplateId", templateId)+ .formParam("DesiredConfiguration.LaunchTemplate.Version", "2").post("/").then());++ user.policy(actions + "," + passRole(role, "ec2.amazonaws.com"));+ group(user, "UpdateAutoScalingGroup", group).formParam("LaunchTemplate.LaunchTemplateId", templateId)+ .formParam("LaunchTemplate.Version", "2").post("/").then().statusCode(200);+ }++ @Test+ void anInstanceRefreshNeedsPassRoleOnTheTemplateVersionItsGroupLaunchesFromOnceItApplies() {+ String role = role("asg-refresh");+ String profile = instanceProfile(roleName(role));+ String plain = launchTemplate(null, null);+ // Version 2 names the profile; the latest, version 3, names none.+ String privileged = launchTemplate(null, profile, null);+ String group = "passrole-refresh-" + suffix();+ admin("autoscaling").formParam("Action", "CreateAutoScalingGroup").formParam("AutoScalingGroupName", group)+ .formParam("LaunchTemplate.LaunchTemplateId", plain).formParam("LaunchTemplate.Version", "2")+ .formParam("MinSize", "0").formParam("MaxSize", "0").formParam("DesiredCapacity", "0")+ .formParam("AvailabilityZones.member.1", "us-east-1a").post("/").then().statusCode(200);+ cleanup.register(() -> admin("autoscaling").formParam("Action", "DeleteAutoScalingGroup")+ .formParam("AutoScalingGroupName", group).formParam("ForceDelete", "true").post("/"));+ User user = user("passrole-refresh");++ // A template named without a version keeps the group's version 2, not the template's latest.+ user.policy(allow("autoscaling:StartInstanceRefresh", "*"));+ denied(user.autoscaling("StartInstanceRefresh").formParam("AutoScalingGroupName", group)+ .formParam("DesiredConfiguration.LaunchTemplate.LaunchTemplateId", privileged).post("/").then());++ // A version named alone moves the group's own template to it.+ admin("autoscaling").formParam("Action", "UpdateAutoScalingGroup").formParam("AutoScalingGroupName", group)+ .formParam("LaunchTemplate.LaunchTemplateId", privileged).formParam("LaunchTemplate.Version", "1")+ .post("/").then().statusCode(200);+ denied(user.autoscaling("StartInstanceRefresh").formParam("AutoScalingGroupName", group)+ .formParam("DesiredConfiguration.LaunchTemplate.Version", "2").post("/").then());++ user.policy(allow("autoscaling:StartInstanceRefresh", "*") + "," + passRole(role, "ec2.amazonaws.com"));+ user.autoscaling("StartInstanceRefresh").formParam("AutoScalingGroupName", group)+ .formParam("DesiredConfiguration.LaunchTemplate.Version", "2").post("/").then().statusCode(200);+ }++ @Test+ void aServiceLinkedRoleOtherThanTheDefaultAndALifecycleHooksRoleNeedPassRoleForAutoScaling() {+ String hookRole = role("asg-hook");+ String configuration = "passrole-plain-config-" + suffix();+ admin("autoscaling").formParam("Action", "CreateLaunchConfiguration")+ .formParam("LaunchConfigurationName", configuration).formParam("ImageId", IMAGE)+ .formParam("InstanceType", "t3.micro").post("/").then().statusCode(200);+ cleanup.register(() -> admin("autoscaling").formParam("Action", "DeleteLaunchConfiguration")+ .formParam("LaunchConfigurationName", configuration).post("/"));+ User user = user("passrole-asg-roles");+ String group = "passrole-asg-roles-" + suffix();+ String hooks = "LifecycleHookSpecificationList.member.1.";++ user.policy(allow("autoscaling:CreateAutoScalingGroup", "*") + ","+ + allow("autoscaling:PutLifecycleHook", "*"));+ denied(group(user, "CreateAutoScalingGroup", group).formParam("LaunchConfigurationName", configuration)+ .formParam("ServiceLinkedRoleARN", SERVICE_LINKED_ROLES + "AWSServiceRoleForAutoScaling_passrole")+ .post("/").then());+ denied(group(user, "CreateAutoScalingGroup", group).formParam("LaunchConfigurationName", configuration)+ .formParam(hooks + "LifecycleHookName", "launch")+ .formParam(hooks + "LifecycleTransition", "autoscaling:EC2_INSTANCE_LAUNCHING")+ .formParam(hooks + "NotificationTargetARN", QUEUE_ARN).formParam(hooks + "RoleARN", hookRole)+ .post("/").then());+ // The default service-linked role needs no permission to pass, nor does a launch configuration's group.+ group(user, "CreateAutoScalingGroup", group).formParam("LaunchConfigurationName", configuration)+ .formParam("ServiceLinkedRoleARN", SERVICE_LINKED_ROLES + "AWSServiceRoleForAutoScaling")+ .post("/").then().statusCode(200);+ cleanup.register(() -> admin("autoscaling").formParam("Action", "DeleteAutoScalingGroup")+ .formParam("AutoScalingGroupName", group).formParam("ForceDelete", "true").post("/"));++ denied(lifecycleHook(user, group, hookRole).then());+ user.policy(allow("autoscaling:PutLifecycleHook", "*") + "," + passRole(hookRole, AUTOSCALING));+ lifecycleHook(user, group, hookRole).then().statusCode(200);+ }++ @Test+ void aScalableTargetNeedsPassRoleOnTheRoleItNamesForApplicationAutoScaling() {+ String role = role("scalable-target");+ String table = "table/passrole-" + suffix();+ String target = "AnyScaleFrontendService.RegisterScalableTarget";+ String body = """+ {"ServiceNamespace":"dynamodb","ResourceId":"%s","ScalableDimension":"dynamodb:table:ReadCapacityUnits",+ "MinCapacity":1,"MaxCapacity":5,"RoleARN":"%s"}""".formatted(table, role);+ User user = user("passrole-scaling");++ user.policy(allow("application-autoscaling:RegisterScalableTarget", "*") + "," + passRole(role, AUTOSCALING));+ deniedJson(user.json("application-autoscaling", target).body(body).post("/").then());++ user.policy(allow("application-autoscaling:RegisterScalableTarget", "*") + ","+ + passRole(role, "application-autoscaling.amazonaws.com"));+ user.json("application-autoscaling", target).body(body).post("/").then().statusCode(200);+ cleanup.register(() -> given().header("Authorization", auth(ADMIN, "application-autoscaling"))+ .header("X-Amz-Target", "AnyScaleFrontendService.DeregisterScalableTarget")+ .contentType("application/x-amz-json-1.1")+ .body("{\"ServiceNamespace\":\"dynamodb\",\"ResourceId\":\"" + table+ + "\",\"ScalableDimension\":\"dynamodb:table:ReadCapacityUnits\"}").post("/"));+ }++ private static Response launchConfiguration(User user, String name, String profile) {+ return user.autoscaling("CreateLaunchConfiguration").formParam("LaunchConfigurationName", name)+ .formParam("ImageId", IMAGE).formParam("InstanceType", "t3.micro")+ .formParam("IamInstanceProfile", profile).post("/");+ }++ /**+ * A launch template, removed afterwards, with a version for each of {@code profiles} in order, each+ * naming that instance profile or, for null, none; returns its ID.+ */+ private String launchTemplate(String... profiles) {+ String name = "passrole-asg-template-" + suffix();+ String templateId = withProfile(admin("ec2").formParam("Action", "CreateLaunchTemplate")+ .formParam("LaunchTemplateName", name), profiles[0]).post("/").then().statusCode(200)+ .extract().xmlPath().getString("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId");+ cleanup.register(() -> admin("ec2").formParam("Action", "DeleteLaunchTemplate")+ .formParam("LaunchTemplateId", templateId).post("/"));+ for (int i = 1; i < profiles.length; i++) {+ withProfile(admin("ec2").formParam("Action", "CreateLaunchTemplateVersion")+ .formParam("LaunchTemplateId", templateId), profiles[i]).post("/").then().statusCode(200);+ }+ return templateId;+ }++ private static RequestSpecification withProfile(RequestSpecification request, String profile) {+ request.formParam("LaunchTemplateData.ImageId", IMAGE);+ return profile == null ? request : request.formParam("LaunchTemplateData.IamInstanceProfile.Name", profile);+ }++ /** An empty group's request, which launches nothing. */+ private static RequestSpecification group(User user, String action, String name) {+ return user.autoscaling(action).formParam("AutoScalingGroupName", name).formParam("MinSize", "0")+ .formParam("MaxSize", "0").formParam("DesiredCapacity", "0")+ .formParam("AvailabilityZones.member.1", "us-east-1a");+ }++ private static Response lifecycleHook(User user, String group, String role) {+ return user.autoscaling("PutLifecycleHook").formParam("AutoScalingGroupName", group)+ .formParam("LifecycleHookName", "launch")+ .formParam("LifecycleTransition", "autoscaling:EC2_INSTANCE_LAUNCHING")+ .formParam("NotificationTargetARN", QUEUE_ARN).formParam("RoleARN", role).post("/");+ }+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();@@ -687,6 +899,10 @@ class IamPassRoleEnforcementIntegrationTest {return given().header("Authorization", auth(accessKeyId, "ec2")).formParam("Action", action);}+ RequestSpecification autoscaling(String action) {+ return given().header("Authorization", auth(accessKeyId, "autoscaling")).formParam("Action", action);+ }+RequestSpecification ecs(String action) {return json("ecs", "AmazonEC2ContainerServiceV20141113." + action);}