fix(ec2): authorize launch template names against stored resource ARNs (#8850)

This commit is contained in:
luiseterc authored and GitHub committed 2026-11-18 07:27:48 -04:00
1 parent 9c8734b41f
commit f511cd8a44
8 files changed
+481 -10

No files matched your search

+9
View File
@@ -1088,6 +1088,15 @@ regions, for which AWS publishes no zone id, keep the whole region as the prefix
| DeleteLaunchTemplateVersions | Deletes up to 200 numbered versions by template ID or name, with separate success and error items. The default version is retained, and `DryRun` leaves all versions unchanged. |
Launch templates store versioned launch data. New template versions can be created from an existing source version, and `ModifyLaunchTemplate` updates the default version used by later launches.
With IAM enforcement enabled, `DeleteLaunchTemplate`, `CreateLaunchTemplateVersion`,
`DeleteLaunchTemplateVersions`, and `ModifyLaunchTemplate` resolve a `LaunchTemplateName`
selector in the caller's account and request region before evaluating the template's
ID-based ARN. Exact-resource grants and explicit denies apply to both name and ID selectors.
The request retains that resolved ID, so deleting and recreating a template under the same
name cannot redirect an authorized mutation to the replacement. `CreateLaunchTemplate`
authorizes a new template's ARN and preserves the duplicate-name error for an existing name.
Deleting versions updates `$Latest` to the highest surviving version. New versions receive numbers
above every previously issued version, including deleted versions, and the counter survives restart.
@@ -0,0 +1,29 @@
package io.floci.aws.services.ec2;
import jakarta.enterprise.context.RequestScoped;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
/** Keeps name resolution stable between IAM evaluation and the operation in the same request. */
@RequestScoped
public class Ec2LaunchTemplateSelections {
private record Key(String account, String region, String name) {
}
/** A null id records that the name did not exist when IAM evaluated it. */
record Selection(String id) {
}
private final Map<Key, Selection> selections = new HashMap<>();
Selection resolve(String account, String region, String name, Supplier<String> lookup) {
return selections.computeIfAbsent(new Key(account, region, name), ignored -> new Selection(lookup.get()));
}
Selection get(String account, String region, String name) {
return selections.get(new Key(account, region, name));
}
}
@@ -170,6 +170,9 @@ import static io.floci.aws.services.ec2.Ec2Ids.randomHex;
@ApplicationScoped
public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettable {
// CDI Instance is qualified because EC2 also has an Instance model.
private jakarta.enterprise.inject.Instance<Ec2LaunchTemplateSelections> launchTemplateSelections;
private static final Logger LOG = Logger.getLogger(Ec2Service.class);
/**
@@ -608,7 +611,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
jakarta.enterprise.inject.Instance<Ec2InstanceLaunchListener> instanceLaunchListenersInstance,
Ec2EbsEncryptionService ebsEncryptionService,
jakarta.enterprise.inject.Instance<VpcDependencyProvider> vpcDependencyProviders,
jakarta.enterprise.inject.Instance<ResourceGroupsService> resourceGroupsServices) {
jakarta.enterprise.inject.Instance<ResourceGroupsService> resourceGroupsServices,
jakarta.enterprise.inject.Instance<Ec2LaunchTemplateSelections> launchTemplateSelections) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, storageFactory, requestContextInstance, iamService, volumeBlockDeviceManager);
this.vpcNetworkManager = vpcNetworkManager;
@@ -618,6 +622,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
this.ebsEncryptionService = ebsEncryptionService;
this.vpcDependencyProviders = vpcDependencyProviders;
this.resourceGroupsServices = resourceGroupsServices;
this.launchTemplateSelections = launchTemplateSelections;
}
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
@@ -10408,6 +10413,37 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return matchingLaunchTemplates(region, ids, names, filters);
}
/** The caller's stored launch-template ARN, without creating defaults or changing the template. */
Optional<String> findLaunchTemplateArn(String region, String name) {
String id;
try {
id = launchTemplateSelections == null ? launchTemplateIdByName(region, name)
: launchTemplateSelections.get().resolve(callerAccountId(), region, name,
() -> launchTemplateIdByName(region, name)).id();
} catch (ContextNotActiveException expected) {
LOG.debug("No active request context for launch-template authorization");
id = launchTemplateIdByName(region, name);
}
return Optional.ofNullable(id).map(found -> AwsArnUtils.Arn.of("ec2", region, callerAccountId(),
"launch-template/" + found).toString());
}
private String launchTemplateIdByName(String region, String name) {
return launchTemplates.scan(k -> true).stream()
.filter(template -> region.equals(template.getRegion()) && name.equals(template.getLaunchTemplateName()))
.map(LaunchTemplate::getLaunchTemplateId).findFirst().orElse(null);
}
private Ec2LaunchTemplateSelections.Selection selectedLaunchTemplate(String region, String name) {
try {
return launchTemplateSelections == null ? null
: launchTemplateSelections.get().get(callerAccountId(), region, name);
} catch (ContextNotActiveException expected) {
LOG.debug("No active request context for launch-template selection");
return null;
}
}
private List<LaunchTemplate> matchingLaunchTemplates(String region, List<String> ids, List<String> names,
List<Map.Entry<String, List<String>>> filters) {
ensureDefaultResources(region);
@@ -10620,9 +10656,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return launchTemplate;
}
} else if (name != null && !name.isBlank()) {
return launchTemplates.scan(k -> true).stream()
.filter(lt -> lt.getRegion().equals(region) && name.equals(lt.getLaunchTemplateName()))
.findFirst()
Ec2LaunchTemplateSelections.Selection selected = selectedLaunchTemplate(region, name);
String selectedId = selected == null ? launchTemplateIdByName(region, name) : selected.id();
return (selectedId == null ? Optional.<LaunchTemplate>empty() : launchTemplates.get(key(region, selectedId)))
.orElseThrow(() -> new AwsException("InvalidLaunchTemplateName.NotFoundException",
"The specified launch template does not exist.", 400));
}
@@ -0,0 +1,31 @@
package io.floci.aws.services.ec2;
import io.floci.aws.core.common.StoredResourceArns;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
/** Resolves the caller's launch-template names to their stored ID-based ARNs. */
@ApplicationScoped
public class Ec2StoredResourceArns implements StoredResourceArns {
private final Ec2Service ec2;
@Inject
public Ec2StoredResourceArns(Ec2Service ec2) {
this.ec2 = ec2;
}
@Override
public String namespace() {
return "ec2";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return "launch-template".equals(type) && names.size() == 1
? ec2.findLaunchTemplateArn(region, names.getFirst()) : Optional.empty();
}
}
@@ -1,5 +1,5 @@
{
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-16", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (installed package)", "retrieved": "2026-11-18", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."},
"namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "glue": ["glue"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "quicksight": ["quicksight"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "route53": ["route53"], "s3tables": ["s3tables"], "s3vectors": ["s3vectors"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]},
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "logs", "pipes", "resource-groups", "s3", "sns", "sqs", "sts"],
"notCovered": {"airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rules do not fill a name from, so nearly every operation's resource would be left open", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2-instance-connect": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment/<application>/<name>`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reading it needs the stored environment those find", "elasticfilesystem": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST rLine truncated
@@ -1124,8 +1124,8 @@
"ec2:CreateIpamRoutingPolicyRegistration": {"action": "ec2:CreateIpamRoutingPolicyRegistration", "types": ["ipam-internet-registry-association"], "resources": [{"type": "ipam-internet-registry-association", "fill": {"IpamInternetRegistryAssociationId": "IpamInternetRegistryAssociationId"}}]},
"ec2:CreateIpamScope": {"action": "ec2:CreateIpamScope", "types": ["ipam", "ipam-scope"], "resources": [{"type": "ipam", "fill": {"IpamId": "IpamId"}}, {"type": "ipam-scope", "fill": {}, "made": true}]},
"ec2:CreateKeyPair": {"action": "ec2:CreateKeyPair", "types": ["key-pair"], "resources": [{"type": "key-pair", "fill": {"KeyPairName": "KeyName"}}]},
"ec2:CreateLaunchTemplate": {"action": "ec2:CreateLaunchTemplate", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {}, "find": ["LaunchTemplateName"]}]},
"ec2:CreateLaunchTemplateVersion": {"action": "ec2:CreateLaunchTemplateVersion", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}]},
"ec2:CreateLaunchTemplate": {"action": "ec2:CreateLaunchTemplate", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {}}]},
"ec2:CreateLaunchTemplateVersion": {"action": "ec2:CreateLaunchTemplateVersion", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}, {"type": "launch-template", "fill": {}, "find": ["LaunchTemplateName"], "when": {"LaunchTemplateId": [null]}}]},
"ec2:CreateLocalGatewayRoute": {"action": "ec2:CreateLocalGatewayRoute", "types": ["local-gateway-route-table", "local-gateway-virtual-interface-group", "network-interface", "prefix-list"], "resources": [{"type": "local-gateway-route-table", "fill": {"LocalGatewayRoutetableId": "LocalGatewayRouteTableId"}}, {"type": "local-gateway-virtual-interface-group", "fill": {"LocalGatewayVirtualInterfaceGroupId": "LocalGatewayVirtualInterfaceGroupId"}}, {"type": "network-interface", "fill": {"NetworkInterfaceId": "NetworkInterfaceId"}}, {"type": "prefix-list", "fill": {"PrefixListId": "DestinationPrefixListId"}}]},
"ec2:CreateLocalGatewayRouteTable": {"action": "ec2:CreateLocalGatewayRouteTable", "types": ["local-gateway", "local-gateway-route-table"], "resources": [{"type": "local-gateway", "fill": {"LocalGatewayId": "LocalGatewayId"}}, {"type": "local-gateway-route-table", "fill": {}, "made": true}]},
"ec2:CreateLocalGatewayRouteTableVirtualInterfaceGroupAssociation": {"action": "ec2:CreateLocalGatewayRouteTableVirtualInterfaceGroupAssociation", "types": ["local-gateway-route-table", "local-gateway-route-table-virtual-interface-group-association", "local-gateway-virtual-interface-group"], "resources": [{"type": "local-gateway-route-table", "fill": {"LocalGatewayRoutetableId": "LocalGatewayRouteTableId"}}, {"type": "local-gateway-route-table-virtual-interface-group-association", "fill": {}, "made": true}, {"type": "local-gateway-virtual-interface-group", "fill": {"LocalGatewayVirtualInterfaceGroupId": "LocalGatewayVirtualInterfaceGroupId"}}]},
@@ -1227,8 +1227,8 @@
"ec2:DeleteIpamRoutingPolicyRegistration": {"action": "ec2:DeleteIpamRoutingPolicyRegistration", "types": ["ipam-internet-registry-association"], "resources": [{"type": "ipam-internet-registry-association", "fill": {"IpamInternetRegistryAssociationId": "IpamInternetRegistryAssociationId"}}]},
"ec2:DeleteIpamScope": {"action": "ec2:DeleteIpamScope", "types": ["ipam-scope"], "resources": [{"type": "ipam-scope", "fill": {"IpamScopeId": "IpamScopeId"}}]},
"ec2:DeleteKeyPair": {"action": "ec2:DeleteKeyPair", "types": ["key-pair"], "resources": []},
"ec2:DeleteLaunchTemplate": {"action": "ec2:DeleteLaunchTemplate", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}]},
"ec2:DeleteLaunchTemplateVersions": {"action": "ec2:DeleteLaunchTemplateVersions", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}]},
"ec2:DeleteLaunchTemplate": {"action": "ec2:DeleteLaunchTemplate", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}, {"type": "launch-template", "fill": {}, "find": ["LaunchTemplateName"], "when": {"LaunchTemplateId": [null]}}]},
"ec2:DeleteLaunchTemplateVersions": {"action": "ec2:DeleteLaunchTemplateVersions", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}, {"type": "launch-template", "fill": {}, "find": ["LaunchTemplateName"], "when": {"LaunchTemplateId": [null]}}]},
"ec2:DeleteLocalGatewayRoute": {"action": "ec2:DeleteLocalGatewayRoute", "types": ["local-gateway-route-table", "prefix-list"], "resources": [{"type": "local-gateway-route-table", "fill": {"LocalGatewayRoutetableId": "LocalGatewayRouteTableId"}}, {"type": "prefix-list", "fill": {"PrefixListId": "DestinationPrefixListId"}}]},
"ec2:DeleteLocalGatewayRouteTable": {"action": "ec2:DeleteLocalGatewayRouteTable", "types": ["local-gateway-route-table"], "resources": [{"type": "local-gateway-route-table", "fill": {"LocalGatewayRoutetableId": "LocalGatewayRouteTableId"}}]},
"ec2:DeleteLocalGatewayRouteTableVirtualInterfaceGroupAssociation": {"action": "ec2:DeleteLocalGatewayRouteTableVirtualInterfaceGroupAssociation", "types": ["local-gateway-route-table-virtual-interface-group-association"], "resources": [{"type": "local-gateway-route-table-virtual-interface-group-association", "fill": {"LocalGatewayRouteTableVirtualInterfaceGroupAssociationId": "LocalGatewayRouteTableVirtualInterfaceGroupAssociationId"}}]},
@@ -1714,7 +1714,7 @@
"ec2:ModifyIpamResourceDiscovery": {"action": "ec2:ModifyIpamResourceDiscovery", "types": ["ipam-resource-discovery"], "resources": [{"type": "ipam-resource-discovery", "fill": {"IpamResourceDiscoveryId": "IpamResourceDiscoveryId"}}]},
"ec2:ModifyIpamRoutingPolicyRegistration": {"action": "ec2:ModifyIpamRoutingPolicyRegistration", "types": ["ipam-internet-registry-association"], "resources": [{"type": "ipam-internet-registry-association", "fill": {"IpamInternetRegistryAssociationId": "IpamInternetRegistryAssociationId"}}]},
"ec2:ModifyIpamScope": {"action": "ec2:ModifyIpamScope", "types": ["ipam-scope"], "resources": [{"type": "ipam-scope", "fill": {"IpamScopeId": "IpamScopeId"}}]},
"ec2:ModifyLaunchTemplate": {"action": "ec2:ModifyLaunchTemplate", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}]},
"ec2:ModifyLaunchTemplate": {"action": "ec2:ModifyLaunchTemplate", "types": ["launch-template"], "resources": [{"type": "launch-template", "fill": {"LaunchTemplateId": "LaunchTemplateId"}}, {"type": "launch-template", "fill": {}, "find": ["LaunchTemplateName"], "when": {"LaunchTemplateId": [null]}}]},
"ec2:ModifyLocalGatewayRoute": {"action": "ec2:ModifyLocalGatewayRoute", "types": ["local-gateway-route-table", "local-gateway-virtual-interface-group", "network-interface", "prefix-list"], "resources": [{"type": "local-gateway-route-table", "fill": {"LocalGatewayRoutetableId": "LocalGatewayRouteTableId"}}, {"type": "local-gateway-virtual-interface-group", "fill": {"LocalGatewayVirtualInterfaceGroupId": "LocalGatewayVirtualInterfaceGroupId"}}, {"type": "network-interface", "fill": {"NetworkInterfaceId": "NetworkInterfaceId"}}, {"type": "prefix-list", "fill": {"PrefixListId": "DestinationPrefixListId"}}]},
"ec2:ModifyManagedPrefixList": {"action": "ec2:ModifyManagedPrefixList", "types": ["prefix-list"], "resources": [{"type": "prefix-list", "fill": {"PrefixListId": "PrefixListId"}}]},
"ec2:ModifyManagedResourceVisibility": {"action": "ec2:ModifyManagedResourceVisibility", "types": [], "resources": []},
@@ -0,0 +1,316 @@
package io.floci.aws.services.ec2;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.ec2.model.LaunchTemplateData;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.SignedIamEnforcementProfile;
import io.floci.aws.testing.SignedIamUsers;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.quarkus.test.junit.mockito.InjectSpy;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.LaunchTemplate;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doAnswer;
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class Ec2LaunchTemplateNameIamIntegrationTest {
@TestHTTPResource("/")
URI endpoint;
@Inject
Ec2Service ec2;
@InjectSpy
Ec2StoredResourceArns resources;
@ParameterizedTest
@ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"})
void deletionByNameUsesTheSameScopedPermissionAsDeletionById(String regionName) throws Exception {
Region region = Region.of(regionName);
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", region, endpoint)) {
String prefix = "name-iam-" + UUID.randomUUID();
LaunchTemplate byId = admin.createLaunchTemplate(r -> r.launchTemplateName(prefix + "-id")
.launchTemplateData(d -> d.imageId("ami-12345678"))).launchTemplate();
LaunchTemplate byName = admin.createLaunchTemplate(r -> r.launchTemplateName(prefix + "-name")
.launchTemplateData(d -> d.imageId("ami-12345678"))).launchTemplate();
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"ec2:DeleteLaunchTemplate","Resource":[
"%s", "%s"]}]}
""".formatted(arn(region, byId), arn(region, byName));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-name-", "delete", policy);
Ec2Client caller = AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(),
user.secretAccessKey(), region, endpoint)) {
assertEquals(byId.launchTemplateId(), caller.deleteLaunchTemplate(r ->
r.launchTemplateId(byId.launchTemplateId())).launchTemplate().launchTemplateId());
assertEquals(byName.launchTemplateId(), caller.deleteLaunchTemplate(r ->
r.launchTemplateName(byName.launchTemplateName())).launchTemplate().launchTemplateId());
} finally {
remove(admin, byId.launchTemplateId());
remove(admin, byName.launchTemplateId());
}
}
}
@Test
void versionMutationsByNameUseTheStoredTemplateArn() throws Exception {
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) {
LaunchTemplate template = create(admin, "versions-" + UUID.randomUUID());
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":[
"ec2:CreateLaunchTemplateVersion","ec2:ModifyLaunchTemplate","ec2:DeleteLaunchTemplateVersions"],
"Resource":"%s"}]}
""".formatted(arn(Region.US_EAST_1, template));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-version-", "versions", policy);
Ec2Client caller = client(user)) {
String name = template.launchTemplateName();
assertEquals(2L, caller.createLaunchTemplateVersion(r -> r.launchTemplateName(name)
.launchTemplateData(d -> d.imageId("ami-87654321"))).launchTemplateVersion().versionNumber());
assertEquals(2L, caller.modifyLaunchTemplate(r -> r.launchTemplateName(name).defaultVersion("2"))
.launchTemplate().defaultVersionNumber());
assertEquals(1L, caller.deleteLaunchTemplateVersions(r -> r.launchTemplateName(name).versions("1"))
.successfullyDeletedLaunchTemplateVersions().getFirst().versionNumber());
} finally {
remove(admin, template.launchTemplateId());
}
}
}
@Test
void unrelatedGrantAndExplicitDenyCannotDeleteByName() throws Exception {
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) {
LaunchTemplate target = create(admin, "denied-" + UUID.randomUUID());
LaunchTemplate other = create(admin, "allowed-" + UUID.randomUUID());
try {
assertDenied(admin, target, policy("Allow", arn(Region.US_EAST_1, other)));
String denied = "{\"Version\":\"2012-10-17\",\"Statement\":["
+ statement("Allow", "*") + "," + statement("Deny", arn(Region.US_EAST_1, target)) + "]}";
assertDenied(admin, target, denied);
} finally {
remove(admin, target.launchTemplateId());
remove(admin, other.launchTemplateId());
}
}
}
@Test
void sameNameInAnotherRegionDoesNotSupplyTheAuthorizedId() throws Exception {
try (Ec2Client east = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint);
Ec2Client west = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_WEST_2, endpoint)) {
String name = "regional-" + UUID.randomUUID();
LaunchTemplate remote = create(west, name);
LaunchTemplate local = create(east, name);
try {
assertDenied(east, local, policy("Allow", arn(Region.US_WEST_2, remote)));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-region-", "delete",
policy("Allow", arn(Region.US_EAST_1, local)));
Ec2Client caller = client(user)) {
assertEquals(local.launchTemplateId(), caller.deleteLaunchTemplate(r -> r.launchTemplateName(name))
.launchTemplate().launchTemplateId());
}
assertPresent(west, remote);
} finally {
remove(east, local.launchTemplateId());
remove(west, remote.launchTemplateId());
}
}
}
@Test
void sameNameInAnotherAccountDoesNotSupplyTheAuthorizedId() throws Exception {
String name = "account-" + UUID.randomUUID();
String remoteId = RequestScopes.callAs("111122223333", "us-east-1", () -> ec2.createLaunchTemplate(
"us-east-1", name, new LaunchTemplateData(), List.of()).getLaunchTemplateId());
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) {
LaunchTemplate local = create(admin, name);
try {
assertDenied(admin, local, policy("Allow", AwsArnUtils.Arn.of("ec2", "us-east-1",
"111122223333", "launch-template/" + remoteId).toString()));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-account-", "delete",
policy("Allow", arn(Region.US_EAST_1, local)));
Ec2Client caller = client(user)) {
assertEquals(local.launchTemplateId(), caller.deleteLaunchTemplate(r -> r.launchTemplateName(name))
.launchTemplate().launchTemplateId());
}
assertEquals(remoteId, RequestScopes.callAs("111122223333", "us-east-1", () ->
ec2.describeLaunchTemplates("us-east-1", List.of(remoteId), List.of(), Map.of())
.getFirst().getLaunchTemplateId()));
} finally {
remove(admin, local.launchTemplateId());
}
} finally {
RequestScopes.runAs("111122223333", "us-east-1", () ->
ec2.deleteLaunchTemplate("us-east-1", remoteId, null));
}
}
@Test
void wildcardGrantPreservesMissingNameError() throws Exception {
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-missing-", "delete", policy("Allow", "*"));
Ec2Client caller = client(user)) {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> caller.deleteLaunchTemplate(r ->
r.launchTemplateName("missing-" + UUID.randomUUID())));
assertEquals(400, error.statusCode());
assertEquals("InvalidLaunchTemplateName.NotFoundException", error.awsErrorDetails().errorCode());
}
}
@Test
void duplicateCreateDoesNotAuthorizeAgainstTheExistingTemplate() throws Exception {
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) {
LaunchTemplate template = create(admin, "duplicate-" + UUID.randomUUID());
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"ec2:CreateLaunchTemplate","Resource":"*"},
{"Effect":"Deny","Action":"ec2:CreateLaunchTemplate","Resource":"%s"}]}
""".formatted(arn(Region.US_EAST_1, template));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-duplicate-", "create", policy);
Ec2Client caller = client(user)) {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> create(caller, template.launchTemplateName()));
assertEquals("InvalidLaunchTemplateName.AlreadyExistsException", error.awsErrorDetails().errorCode());
assertPresent(admin, template);
} finally {
remove(admin, template.launchTemplateId());
}
}
}
@ParameterizedTest
@ValueSource(strings = {"DeleteLaunchTemplate", "CreateLaunchTemplateVersion", "ModifyLaunchTemplate",
"DeleteLaunchTemplateVersions"})
void replacementCannotBeMutatedUsingTheOriginalTemplatesGrant(String action) throws Exception {
try (Ec2Client admin = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1, endpoint)) {
String name = "replaced-" + UUID.randomUUID();
LaunchTemplate original = create(admin, name);
CountDownLatch resolved = new CountDownLatch(1);
CountDownLatch replaced = new CountDownLatch(1);
doAnswer(invocation -> {
Object found = invocation.callRealMethod();
resolved.countDown();
assertTrue(replaced.await(15, TimeUnit.SECONDS), "replacement must finish before authorization resumes");
return found;
}).when(resources).find("launch-template", List.of(name), "us-east-1");
String policy = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"ec2:%s","Resource":"%s"}]}
""".formatted(action, arn(Region.US_EAST_1, original));
ExecutorService worker = Executors.newSingleThreadExecutor();
LaunchTemplate replacement = null;
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-race-", "mutate", policy);
Ec2Client caller = client(user)) {
Future<?> mutation = worker.submit(() -> {
if ("DeleteLaunchTemplateVersions".equals(action)) {
assertEquals("launchTemplateNameDoesNotExist", caller.deleteLaunchTemplateVersions(r ->
r.launchTemplateName(name).versions("2")).unsuccessfullyDeletedLaunchTemplateVersions()
.getFirst().responseError().codeAsString());
} else {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> {
switch (action) {
case "DeleteLaunchTemplate" -> caller.deleteLaunchTemplate(r -> r.launchTemplateName(name));
case "CreateLaunchTemplateVersion" -> caller.createLaunchTemplateVersion(r ->
r.launchTemplateName(name).launchTemplateData(d -> d.imageId("ami-87654321")));
case "ModifyLaunchTemplate" -> caller.modifyLaunchTemplate(r ->
r.launchTemplateName(name).defaultVersion("2"));
default -> throw new AssertionError(action);
}
});
assertEquals("InvalidLaunchTemplateName.NotFoundException", error.awsErrorDetails().errorCode());
}
});
assertTrue(resolved.await(15, TimeUnit.SECONDS), "IAM must resolve the original template");
remove(admin, original.launchTemplateId());
replacement = create(admin, name);
admin.createLaunchTemplateVersion(r -> r.launchTemplateName(name)
.launchTemplateData(d -> d.imageId("ami-22222222")));
replaced.countDown();
mutation.get(15, TimeUnit.SECONDS);
assertPresent(admin, replacement);
LaunchTemplate after = admin.describeLaunchTemplates(r -> r.launchTemplateNames(name))
.launchTemplates().getFirst();
assertEquals(1L, after.defaultVersionNumber());
assertEquals(2L, after.latestVersionNumber());
assertEquals(2, admin.describeLaunchTemplateVersions(r -> r.launchTemplateName(name))
.launchTemplateVersions().size());
} finally {
replaced.countDown();
worker.shutdownNow();
assertTrue(worker.awaitTermination(15, TimeUnit.SECONDS));
remove(admin, original.launchTemplateId());
if (replacement != null) {
remove(admin, replacement.launchTemplateId());
}
}
}
}
private void assertDenied(Ec2Client admin, LaunchTemplate template, String policy) throws Exception {
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "lt-deny-", "delete", policy);
Ec2Client caller = client(user)) {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> caller.deleteLaunchTemplate(r ->
r.launchTemplateName(template.launchTemplateName())));
assertEquals(403, error.statusCode());
assertEquals("UnauthorizedOperation", error.awsErrorDetails().errorCode());
assertPresent(admin, template);
}
}
private Ec2Client client(SignedIamUsers.User user) {
return AwsTestClients.create(Ec2Client.builder(), user.accessKeyId(), user.secretAccessKey(),
Region.US_EAST_1, endpoint);
}
private static LaunchTemplate create(Ec2Client admin, String name) {
return admin.createLaunchTemplate(r -> r.launchTemplateName(name)
.launchTemplateData(d -> d.imageId("ami-12345678"))).launchTemplate();
}
private static void assertPresent(Ec2Client admin, LaunchTemplate template) {
assertEquals(template.launchTemplateId(), admin.describeLaunchTemplates(r ->
r.launchTemplateIds(template.launchTemplateId())).launchTemplates().getFirst().launchTemplateId());
}
private static String arn(Region region, LaunchTemplate template) {
return AwsArnUtils.Arn.of("ec2", region.id(), "000000000000",
"launch-template/" + template.launchTemplateId()).toString();
}
private static String statement(String effect, String resource) {
return "{\"Effect\":\"%s\",\"Action\":\"ec2:DeleteLaunchTemplate\",\"Resource\":\"%s\"}"
.formatted(effect, resource);
}
private static String policy(String effect, String resource) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[" + statement(effect, resource) + "]}";
}
private static void remove(Ec2Client admin, String id) {
try {
admin.deleteLaunchTemplate(r -> r.launchTemplateId(id));
} catch (Ec2Exception expected) {
// A successful deletion assertion already removed this fixture.
assertEquals("InvalidLaunchTemplateId.NotFound", expected.awsErrorDetails().errorCode());
}
}
}
+15
View File
@@ -1005,6 +1005,18 @@ def with_documented(operation: str, types: list[str], formats: dict[str, str], m
opened = current is not None and current.get("fill") == {} and "made" not in current
fill = dict(current["fill"]) if current else {}
unfilled = [v for v in variables if v not in fill]
# An optional id and name documented as mutually exclusive selectors name the same stored resource.
# Keep the id path, and resolve the name only when that id is absent (EC2 launch templates).
if not creating and len(variables) == 1 and not unfilled and kind_of(variables[0]) == "id":
selector = fill[variables[0]]
optional = optional_members(models, name)
names = [path for path, fact in facts.items()
if path in optional and not fact["nested"] and not fact["path"].endswith("[]")
and doc_kind(fact["lead"]) == "name" and doc_names(fact["lead"], kind, formats)
and "either" in (_member_documentation(models, name, path) or "").lower()
and "but not both" in (_member_documentation(models, name, path) or "").lower()]
if selector in optional and len(names) == 1:
resources.append({"type": kind, "fill": {}, "find": names, "when": {selector: [None]}})
if len(unfilled) != 1:
continue
variable = unfilled[0]
@@ -1031,6 +1043,9 @@ def with_documented(operation: str, types: list[str], formats: dict[str, str], m
and not (creating and said != kind_of(variable) and kind_of(variable) != "identifier"):
candidates.append(("fill", fact["path"]))
elif len(variables) == 1 and not fact["path"].endswith("[]"):
# A create asking for "A name for" its new resource does not select an existing id.
if creating and made == stem(kind) and fact["lead"].startswith("a name for "):
continue
candidates.append(("find", fact["path"]))
elif aliased != effective and related(aliased, kind_stem) and compatible(field, variable):
candidates.append(("fill", fact["path"]))
@@ -2650,3 +2650,38 @@ def test_the_statements_are_built_checked_offline_and_verified_against_aws_and_t
page["https://example.com/page"] = "a changed page"
assert r.verify_statements(document, documents) == [
"https://example.com/page no longer gives what source.json holds for svc:GetThing: run fetch.py"]
@pytest.mark.parametrize("operation", ["DeleteWidget", "CreateWidgetVersion"])
def test_documented_alternate_name_resolves_an_optional_id(operation):
formats = {"widget": "arn:${Partition}:svc:${Region}:${Account}:widget/${WidgetId}"}
docs = {"WidgetId": "<p>The ID of the widget.</p>",
"WidgetName": "<p>The name of the widget.</p> <p>Specify either the widget ID or the widget name, "
"but not both.</p>"}
resource = {"type": "widget", "fill": {"WidgetId": "WidgetId"}}
models = cluster_model(operation, docs)
assert r.with_documented("svc:" + operation, ["widget"], formats, models, [resource]) == [
resource, {"type": "widget", "fill": {}, "find": ["WidgetName"], "when": {"WidgetId": [None]}}]
# A required id, an ordinary rename, and a create's new name are not alternate selectors.
assert r.with_documented("svc:" + operation, ["widget"], formats,
cluster_model(operation, docs, ("WidgetId",)), [resource]) == [resource]
docs["WidgetName"] = "<p>The name of the widget.</p>"
assert r.with_documented("svc:" + operation, ["widget"], formats,
cluster_model(operation, docs), [resource]) == [resource]
def test_create_name_does_not_look_up_an_existing_id():
formats = {"widget": "arn:${Partition}:svc:${Region}:${Account}:widget/${WidgetId}"}
docs = {"WidgetId": "<p>The ID of the widget.</p>",
"WidgetName": "<p>The name of the widget.</p> <p>Specify either the widget ID or the widget name, "
"but not both.</p>"}
resource = {"type": "widget", "fill": {"WidgetId": "WidgetId"}}
assert r.with_documented("svc:CreateWidget", ["widget"], formats,
cluster_model("CreateWidget", docs), [resource]) == [resource]
def test_a_name_for_a_new_resource_does_not_select_an_existing_id():
formats = {"widget": "arn:${Partition}:svc:${Region}:${Account}:widget/${WidgetId}"}
models = cluster_model("CreateWidget", {"WidgetName": "<p>A name for the widget.</p>"})
resource = {"type": "widget", "fill": {}}
assert r.with_documented("svc:CreateWidget", ["widget"], formats, models, [resource]) == [resource]