From f511cd8a44ace7c83196be9827eb2078f8052ae6 Mon Sep 17 00:00:00 2001 From: luiseterc Date: Wed, 18 Nov 2026 12:27:48 +0100 Subject: [PATCH] fix(ec2): authorize launch template names against stored resource ARNs (#8850) --- docs/services/ec2.md | 9 + .../ec2/Ec2LaunchTemplateSelections.java | 29 ++ .../io/floci/aws/services/ec2/Ec2Service.java | 44 ++- .../services/ec2/Ec2StoredResourceArns.java | 31 ++ .../resources/aws/iam-request-resources.json | 12 +- ...2LaunchTemplateNameIamIntegrationTest.java | 316 ++++++++++++++++++ tools/aws/regen_iam_request_resources.py | 15 + tools/aws/test_regen_iam_request_resources.py | 35 ++ 8 files changed, 481 insertions(+), 10 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/ec2/Ec2LaunchTemplateSelections.java create mode 100644 src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java create mode 100644 src/test/java/io/floci/aws/services/ec2/Ec2LaunchTemplateNameIamIntegrationTest.java diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 9109156c80..9f89637b2c 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -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. diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2LaunchTemplateSelections.java b/src/main/java/io/floci/aws/services/ec2/Ec2LaunchTemplateSelections.java new file mode 100644 index 0000000000..5f0aaaa8d3 --- /dev/null +++ b/src/main/java/io/floci/aws/services/ec2/Ec2LaunchTemplateSelections.java @@ -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 selections = new HashMap<>(); + + Selection resolve(String account, String region, String name, Supplier 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)); + } +} diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index bd489db04f..638de8a38f 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -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 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 instanceLaunchListenersInstance, Ec2EbsEncryptionService ebsEncryptionService, jakarta.enterprise.inject.Instance vpcDependencyProviders, - jakarta.enterprise.inject.Instance resourceGroupsServices) { + jakarta.enterprise.inject.Instance resourceGroupsServices, + jakarta.enterprise.inject.Instance 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 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 matchingLaunchTemplates(String region, List ids, List names, List>> 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.empty() : launchTemplates.get(key(region, selectedId))) .orElseThrow(() -> new AwsException("InvalidLaunchTemplateName.NotFoundException", "The specified launch template does not exist.", 400)); } diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java b/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java new file mode 100644 index 0000000000..f3ae1c7572 --- /dev/null +++ b/src/main/java/io/floci/aws/services/ec2/Ec2StoredResourceArns.java @@ -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 find(String type, List names, String region) { + return "launch-template".equals(type) && names.size() == 1 + ? ec2.findLaunchTemplateArn(region, names.getFirst()) : Optional.empty(); + } +} diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index 2bb52eb68c..9bd38c25e6 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -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::autoScalingGroupName/`, while Floci mints `autoScalingGroup:`, 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/_, 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//`, 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 routes (regen_rest_routes.MODELS), which do not have its model yet", "execute-api": "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", "identitystore": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "iot": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "kafka": "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", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "memorydb": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "mq": "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", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "organizations": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rds-data": "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", "route53resolver": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rum": "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", "sagemaker": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "servicecatalog": "not read yet: CreatePortfolioShare, UpdatePortfolioShare and DeletePortfolioShare give in AccountId the account a portfolio is shared with, which the rule reads as the portfolio's; a portfolio or product imported from another account keeps its owner's account in its ARN while requests name it by its id alone; and AppRegistry's applications and attribute groups are named in the path", "ses": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "signin": "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", "sso-oauth": "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", "swf": "not read yet: the Service Reference gives a domain's ARN no Region, `swf:::/domain/`, while the SWF Developer Guide gives it as arn:aws:swf:Region:AccountID:/domain/DomainName, as Floci mints it; reading it needs that format corrected", "transcribe": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "transfer": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "verifiedpermissions": "not read yet: a policyStoreId may name its store by an alias, `policy-store-alias/`, which AWS authorizes as the action on the store the alias points to and GetPolicyStoreAlias on the alias, and an aliasName carries the `policy-store-alias/` its format already gives; reading it needs both", "wafv2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"}, @@ -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": []}, diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2LaunchTemplateNameIamIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2LaunchTemplateNameIamIntegrationTest.java new file mode 100644 index 0000000000..e42878d113 --- /dev/null +++ b/src/test/java/io/floci/aws/services/ec2/Ec2LaunchTemplateNameIamIntegrationTest.java @@ -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()); + } + } +} diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 99d3b573c9..15d246a53a 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -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"])) diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index 37dd995564..f93a9e1937 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -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": "

The ID of the widget.

", + "WidgetName": "

The name of the widget.

Specify either the widget ID or the widget name, " + "but not both.

"} + 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"] = "

The name of the widget.

" + 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": "

The ID of the widget.

", + "WidgetName": "

The name of the widget.

Specify either the widget ID or the widget name, " + "but not both.

"} + 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": "

A name for the widget.

"}) + resource = {"type": "widget", "fill": {}} + assert r.with_documented("svc:CreateWidget", ["widget"], formats, models, [resource]) == [resource]