mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
fix(iam): read which ARN formats lie within others from the request-resources table (#9881)
An ARN a request member names may fit the formats of two types of its namespace: an endpoint group's ARN,
accelerator/<id>/listener/<id>/endpoint-group/<id>, fits its accelerator's accelerator/${ResourceId} too, the id
taking any character. The reader took such an ARN as the other type's when that type's format was the longer as
text, variable names counted, so a format with long variable names won over one that fixes more of the ARN.
The generator now gives each type the types of its namespace whose formats lie within its own and not the other way
(narrowerFormats), read from the formats as they stand, each variable matched as the reader matches it: the
partition takes no colon, the Region and the account none or more characters but a colon, any other variable one
or more of any. The reader takes an ARN as a type the resource does not read only when the table gives that type as
lying within every one of the resource's own that the ARN fits. make iam-request-resources-check derives the nesting
again from the formats.
Two readings change for real ARNs, each to the narrower type the action does not list: an AWS-managed RAM
permission (arn:aws:ram::aws:permission/...) named to an action on customer-managed permissions, and a multi-Region
access point's ARN named to S3 Control's tag operations, which no longer pass as an access point's.
test_regen_iam_request_resources.py checks the nesting of formats and that the check reports a table giving
another; RequestResourceMembersTest checks the reader reads and refuses narrowerFormats.
This commit is contained in:
1 parent
98f49a91c7
commit
b13e8aa9cd
7 files changed
+252
-15
No files matched your search
@@ -134,13 +134,14 @@ final class RequestResourceMembers {
|
||||
* follows the one variable the format ends in with an id it mints, {@code /<id>}, which the format leaves out
|
||||
* (EventBridge's {@code connection/<name>/<id>}); {@code mintedSuffix} the characters its service follows the
|
||||
* name that variable takes with, as IAM matches them, one {@code ?} each after the separator (a Secrets Manager
|
||||
* secret's {@code -??????}), or null.
|
||||
* secret's {@code -??????}), or null; {@code narrower} the types of its namespace whose formats lie within it, an
|
||||
* ARN of which fits it too and is theirs (an accelerator's endpoint groups and listeners).
|
||||
*/
|
||||
record ArnFormat(String format, Pattern pattern, boolean unqualified, boolean minted, Pattern integers,
|
||||
String mintedSuffix) {
|
||||
String mintedSuffix, Set<String> narrower) {
|
||||
|
||||
ArnFormat(String format, Pattern pattern, boolean unqualified, boolean minted) {
|
||||
this(format, pattern, unqualified, minted, null, null);
|
||||
this(format, pattern, unqualified, minted, null, null, Set.of());
|
||||
}
|
||||
|
||||
ArnFormat(String format, Pattern pattern, boolean unqualified) {
|
||||
@@ -466,7 +467,8 @@ final class RequestResourceMembers {
|
||||
.path(type.getKey()));
|
||||
types.put(type.getKey(), new ArnFormat(format, pattern(format), unqualified.contains(type.getKey()),
|
||||
minted.contains(type.getKey()), integers.isEmpty() ? null : pattern(format, integers),
|
||||
suffixes.path(type.getKey()).asText(null)));
|
||||
suffixes.path(type.getKey()).asText(null),
|
||||
names(document.path("narrowerFormats").path(namespace.getKey()).path(type.getKey()))));
|
||||
});
|
||||
formats.put(namespace.getKey(), Map.copyOf(types));
|
||||
});
|
||||
@@ -478,6 +480,18 @@ final class RequestResourceMembers {
|
||||
+ namespace.getValue() + " without a qualifier, no types with an ARN format");
|
||||
}
|
||||
});
|
||||
document.path("narrowerFormats").properties().forEach(namespace -> {
|
||||
Set<String> types = formats.getOrDefault(namespace.getKey(), Map.of()).keySet();
|
||||
namespace.getValue().properties().forEach(type -> {
|
||||
Set<String> narrower = names(type.getValue());
|
||||
if (!types.contains(type.getKey()) || !type.getValue().isArray() || narrower.isEmpty()
|
||||
|| !types.containsAll(narrower) || narrower.contains(type.getKey())) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + "'s "
|
||||
+ type.getKey() + " the narrower formats " + type.getValue()
|
||||
+ ", no other types of its namespace with an ARN format");
|
||||
}
|
||||
});
|
||||
});
|
||||
document.path("mintedIds").properties().forEach(namespace -> {
|
||||
Map<String, ArnFormat> types = formats.getOrDefault(namespace.getKey(), Map.of());
|
||||
if (!namespace.getValue().isArray() || !names(namespace.getValue()).stream().allMatch(type ->
|
||||
|
||||
@@ -529,7 +529,7 @@ public final class RequestResources {
|
||||
}
|
||||
if (resource.arn() != null) {
|
||||
for (String named : values(form, body, resource.arn())) {
|
||||
if (longerFormat(named, resource.types(), formats)) {
|
||||
if (narrowerFormat(named, resource.types(), formats)) {
|
||||
continue;
|
||||
}
|
||||
// An ARN fitting a customer's format and one AWS owns is AWS's: the account `aws` tells them apart.
|
||||
@@ -828,21 +828,21 @@ public final class RequestResources {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an ARN fits the format of a type of the namespace the resource does not read, longer than every one of
|
||||
* its own that it fits: an endpoint group's ARN under its accelerator's, {@code accelerator/<id>/listener/...},
|
||||
* is the endpoint group's, not the accelerator's.
|
||||
* Whether an ARN fits the format of a type of the namespace the resource does not read, which the table gives as
|
||||
* lying within every one of its own that it fits ({@code narrowerFormats}): an endpoint group's ARN under its
|
||||
* accelerator's, {@code accelerator/<id>/listener/...}, is the endpoint group's, not the accelerator's.
|
||||
*/
|
||||
private static boolean longerFormat(String arn, List<String> types,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats) {
|
||||
private static boolean narrowerFormat(String arn, List<String> types,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats) {
|
||||
List<RequestResourceMembers.ArnFormat> fits = types.stream().map(formats::get)
|
||||
.filter(format -> format != null && format.pattern().matcher(arn).matches()).toList();
|
||||
// A type checked without its qualifier takes the longer ARNs of its versions and aliases on purpose.
|
||||
if (fits.stream().anyMatch(RequestResourceMembers.ArnFormat::unqualified)) {
|
||||
if (fits.isEmpty() || fits.stream().anyMatch(RequestResourceMembers.ArnFormat::unqualified)) {
|
||||
return false;
|
||||
}
|
||||
int own = fits.stream().mapToInt(format -> format.format().length()).max().orElse(Integer.MAX_VALUE);
|
||||
return formats.entrySet().stream().anyMatch(other -> !types.contains(other.getKey())
|
||||
&& other.getValue().format().length() > own && other.getValue().pattern().matcher(arn).matches());
|
||||
&& fits.stream().allMatch(own -> own.narrower().contains(other.getKey()))
|
||||
&& other.getValue().pattern().matcher(arn).matches());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.44.14 (installed package)", "retrieved": "2026-11-30", "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.44.14 (installed package)", "retrieved": "2026-12-01", "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"], "apigateway": ["apigateway", "apigatewayv2"], "appconfig": ["appconfig", "appconfigcloudextension", "appconfigdata"], "application-autoscaling": ["application-autoscaling"], "appsync": ["appsync"], "aps": ["amp"], "athena": ["athena"], "backup": ["backup"], "batch": ["batch"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "bedrock": ["bedrock", "bedrock-agent", "bedrock-agent-runtime", "bedrock-data-automation", "bedrock-data-automation-runtime", "bedrock-runtime"], "budgets": ["budgets"], "ce": ["ce"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "cloudwatch": ["cloudwatch", "cloudwatchomni"], "codeartifact": ["codeartifact"], "codebuild": ["codebuild"], "codeguru-reviewer": ["codeguru-reviewer"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "comprehend": ["comprehend"], "config": ["config"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dms": ["dms"], "dsql": ["dsql"], "dynamodb": ["dynamodb", "dynamodbstreams"], "ec2": ["ec2"], "ec2-instance-connect": ["ec2-instance-connect"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticache": ["elasticache"], "elasticfilesystem": ["efs"], "elasticloadbalancing": ["elb", "elb-proxy", "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"], "iam": ["iam", "iam-toolbox"], "identitystore": ["identitystore"], "inspector2": ["inspector2"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "kinesisvideo": ["kinesis-video-archived-media", "kinesis-video-media", "kinesis-video-signaling", "kinesis-video-webrtc-storage", "kinesisvideo"], "kms": ["kms"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "macie2": ["macie2"], "memorydb": ["memorydb"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "pipes": ["pipes"], "quicksight": ["quicksight"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "rds-data": ["rds-data"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "resource-groups": ["resource-groups"], "route53": ["route53"], "route53resolver": ["route53resolver"], "s3": ["s3", "s3control"], "s3tables": ["s3tables"], "s3vectors": ["s3vectors"], "sagemaker": ["sagemaker", "sagemaker-a2i-runtime", "sagemaker-edge", "sagemaker-featurestore-runtime", "sagemaker-gateway-runtime", "sagemaker-inference-router-runtime", "sagemaker-metrics", "sagemaker-runtime", "sagemakerjobruntime", "sagemakertrainingsessionruntime"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "ses": ["mailmanager", "pinpoint-email", "ses", "sesv2"], "signer": ["signer", "signer-data"], "sns": ["sns"], "sqs": ["sqs"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "sts": ["sts"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "transcribe": ["transcribe"], "transfer": ["transfer"], "translate": ["translate"], "xray": ["xray"]},
|
||||
"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", "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", "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", "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", "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", "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", "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", "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", "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", "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", "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", "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", "ssmmessages": "channel routes authorise agent and client resources directly rather than through generated request mappings", "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:Line truncated
|
||||
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifygen3", "amplifyuibuilder", "aoss", "apiportal", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-external", "backup-gateway", "backup-search", "bcm-data-hub", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "credentialbroker", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elasticfilesystem-endpoint", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "end-user-messaging", "entityresolution", "evs", "finops-agent", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "osm", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "s3files-endpoint", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"],
|
||||
@@ -11,6 +11,7 @@
|
||||
"mintedIds": {"events": ["api-destination", "connection"]},
|
||||
"mintedSuffixes": {"secretsmanager": {"Secret": "-??????"}},
|
||||
"integerVariables": {"lambda": {"layerVersion": ["LayerVersion"]}},
|
||||
"narrowerFormats": {"access-analyzer": {"Analyzer": ["ArchiveRule"]}, "acm": {"acme-endpoint": ["acme-domain-validation", "acme-external-account-binding"]}, "apigateway": {"/usageplans/{usageplanId}/usage (resource-path-specifier)": ["/usageplans/{usageplanId}/keys/{keyId}/usage (resource-path-specifier)"], "Api": ["AccessLogSettings", "Authorizer", "Authorizers", "AuthorizersCache", "Cors", "Deployment", "Deployments", "ExportedAPI", "Integration", "IntegrationResponse", "IntegrationResponses", "Integrations", "Model", "ModelTemplate", "Models", "Route", "RouteRequestParameter", "RouteResponse", "RouteResponses", "RouteSettings", "Routes", "Stage", "Stages"], "Authorizers": ["AuthorizersCache"], "Authorizers (REST API resources)": ["/restapis/{restapi_id}/stages/{stage_name}/cache/authorizers (resource-path-specifier)"], "BasePathMapping": ["PrivateBasePathMapping"], "BasePathMappings": ["PrivateBasePathMappings"], "DomainName": ["ApiMapping", "ApiMappings", "BasePathMapping", "BasePathMappings", "PrivateBasePathMapping", "PrivateBasePathMappings"], "Integration": ["IntegrationResponse", "IntegrationResponses"], "Method": ["Integration (REST API resources)", "IntegrationResponse (REST API resources)", "MethodResponse"], "MethodResponse": ["IntegrationResponse (REST API resources)"], "Model": ["ModelTemplate"], "Model (REST API resources)": ["/restapis/{restapi_id}/models/{model_name}/default_template (resource-path-specifier)"], "PortalProduct": ["ProductPage", "ProductRestEndpointPage"], "PrivateDomainName": ["PrivateBasePathMapping", "PrivateBasePathMappings"], "Resource": ["Integration (REST API resources)", "IntegrationResponse (REST API resources)", "Method", "MethodResponse"], "RestApi": ["/restapis/{restapi_id}/models/{model_name}/default_template (resource-path-specifier)", "/restapis/{restapi_id}/stages/{stage_name}/cache/authorizers (resource-path-specifier)", "/restapis/{restapi_id}/stages/{stage_name}/cache/data (resource-path-specifier)", "/restapis/{restapi_id}/stages/{stage_name}/exports/{export_type} (resource-path-specifier)", "Authorizer (REST API resources)", "Authorizers (REST API resources)", "Deployment (REST API resources)", "Deployments (REST API resources)", "DocumentationPart", "DocumentationParts", "DocumentationVersion", "DocumentationVersions", "GatewayResponse", "GatewayResponses", "Integration (REST API resources)", "IntegrationResponse (REST API resources)", "Method", "MethodResponse", "Model (REST API resources)", "Models (REST API resources)", "RequestValidator", "RequestValidators", "Resource", "Resources", "Sdk", "Stage (REST API resources)", "Stages (REST API resources)", "Template"], "Route": ["RouteRequestParameter", "RouteResponse", "RouteResponses"], "Stage": ["AccessLogSettings", "AuthorizersCache", "RouteSettings"], "Stage (REST API resources)": ["/restapis/{restapi_id}/stages/{stage_name}/cache/authorizers (resource-path-specifier)", "/restapis/{restapi_id}/stages/{stage_name}/cache/data (resource-path-specifier)", "/restapis/{restapi_id}/stages/{stage_name}/exports/{export_type} (resource-path-specifier)", "Sdk"], "UsagePlan": ["/usageplans/{usageplanId}/keys/{keyId}/usage (resource-path-specifier)", "/usageplans/{usageplanId}/usage (resource-path-specifier)", "UsagePlanKey", "UsagePlanKeys"], "UsagePlanKey": ["/usageplans/{usageplanId}/keys/{keyId}/usage (resource-path-specifier)"]}, "appconfig": {"application": ["configuration", "configurationprofile", "deployment", "environment", "experimentdefinition", "experimentrun", "hostedconfigurationversion"], "environment": ["configuration", "deployment"], "experimentdefinition": ["experimentrun"]}, "appsync": {"api": ["channelNamespace", "datasource", "field", "function", "mergedApiAssociation", "sourceApiAssociation", "type"], "graphqlapi": ["channelNamespace", "datasource", "field", "function", "mergedApiAssociation", "sourceApiAssociation", "type"], "type": ["field"]}, "athena": {"workgroup": ["session"]}, "batch": {"job-definition": ["job-definition-revision"], "job-queue": ["quota-share"]}, "bedrock": {"automated-reasoning-policy": ["automated-reasoning-policy-version"], "flow": ["flow-alias", "flow-execution"], "flow-alias": ["flow-execution"], "prompt": ["prompt-version"]}, "budgets": {"budget": ["budgetAction"]}, "codeguru-reviewer": {"association": ["codereview"]}, "codepipeline": {"action": ["actiontype"], "pipeline": ["action", "actiontype", "stage", "webhook"], "stage": ["action", "actiontype"]}, "comprehend": {"flywheel": ["flywheel-dataset"]}, "datasync": {"storagesystem": ["discoveryjob"], "task": ["taskexecution"]}, "dsql": {"Cluster": ["Stream"]}, "dynamodb": {"table": ["backup", "export", "import", "index", "stream"]}, "elasticloadbalancing": {"loadbalancer": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"]}, "elasticmapreduce": {"cluster": ["session"]}, "emr-containers": {"virtualCluster": ["jobRun", "managedEndpoint"]}, "emr-serverless": {"application": ["jobRun", "session"]}, "eLine truncated
|
||||
"forwardedActions": {"kms:Decrypt": {"type": "key", "format": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "viaService": "kms:ViaService"}},
|
||||
"statementActions": {"glue:BatchCreatePartition": ["catalog", "database", "rootcatalog", "table"], "glue:CreateDatabase": ["catalog", "database", "rootcatalog"], "glue:CreateTable": ["catalog", "database", "rootcatalog", "table"], "glue:DeleteDatabase": ["catalog", "database", "rootcatalog", "table", "userdefinedfunction"], "glue:DeletePartition": ["catalog", "database", "rootcatalog", "table"], "glue:DeleteTable": ["catalog", "database", "rootcatalog", "table"], "glue:GetDatabase": ["catalog", "database", "rootcatalog"], "glue:GetDatabases": ["catalog", "database", "rootcatalog"], "glue:GetPartition": ["catalog", "database", "rootcatalog", "table"], "glue:GetPartitions": ["catalog", "database", "rootcatalog", "table"], "glue:GetTable": ["catalog", "database", "rootcatalog", "table"], "glue:GetTables": ["catalog", "database", "rootcatalog", "table"], "glue:UpdateDatabase": ["catalog", "database", "rootcatalog"]},
|
||||
"statements": {"athena:StartQueryExecution": {"ALTER DATABASE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:UpdateDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}], "CREATE DATABASE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:CreateDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}], "CREATE TABLE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetDatabases", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTables", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetPartitions", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:CreateTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}], "DROP DATABASE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:DeleteDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}, {"type": "userdefinedfunction", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTables", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:DeleteTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database"}}]}], "DROP TABLE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:DeleteTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetPartitions", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}], "partitioned": true}, {"action": "glue:GetPartition", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}], "partitioned": true}, {"action": "glue:DeletePartition", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}], "partitioned": true}], "MSCK REPAIR TABLE": [{"action": "glue:GetDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:CreateDatabase", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}]}, {"action": "glue:GetTable", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}]}, {"action": "glue:GetPartitions", "resources": [{"type": "rootcatalog", "fill": {}}, {"type": "database", "fill": {"DatabaseName": "database"}}, {"type": "table", "fill": {"DatabaseName": "database", "TableName": "table"}}Line truncated
|
||||
|
||||
@@ -44,6 +44,37 @@ class RequestResourceMembersTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The types the table gives as lying within a type's format are its narrower ones, which an ARN fitting both is
|
||||
* read as; a list naming a type its namespace has no format for, the type itself, or nothing, is refused.
|
||||
*/
|
||||
@Test
|
||||
void theNarrowerFormatsOfATypeAreReadAndChecked() throws Exception {
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree("""
|
||||
{
|
||||
"namespaces": {"example": ["example"]},
|
||||
"arnFormats": {"example": {
|
||||
"accelerator": "arn:${Partition}:example::${Account}:accelerator/${Id}",
|
||||
"listener": "arn:${Partition}:example::${Account}:accelerator/${Id}/listener/${ListenerId}"
|
||||
}},
|
||||
"narrowerFormats": {"example": {"accelerator": ["listener"]}},
|
||||
"operations": {"example:Read": {"resources": []}}
|
||||
}
|
||||
""");
|
||||
Map<String, ArnFormat> formats = parse(document.toString()).formats().get("example");
|
||||
assertEquals(Set.of("listener"), formats.get("accelerator").narrower());
|
||||
assertEquals(Set.of(), formats.get("listener").narrower());
|
||||
for (String invalid : List.of("{\"example\":{\"accelerator\":[\"unknown\"]}}",
|
||||
"{\"example\":{\"unknown\":[\"listener\"]}}", "{\"example\":{\"accelerator\":[\"accelerator\"]}}",
|
||||
"{\"example\":{\"accelerator\":[]}}", "{\"example\":{\"accelerator\":\"listener\"}}",
|
||||
"{\"unknown\":{\"accelerator\":[\"listener\"]}}")) {
|
||||
ObjectNode changed = document.deepCopy();
|
||||
changed.set("narrowerFormats", MAPPER.readTree(invalid));
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> parse(changed.toString()));
|
||||
assertTrue(failure.getMessage().contains("narrower formats"), failure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void modeledIntegerArnVariablesNormalizeOnlyTheirOwnValues() throws Exception {
|
||||
ObjectNode document = (ObjectNode) MAPPER.readTree("""
|
||||
|
||||
@@ -1937,6 +1937,35 @@ class ResourceArnBuilderTest {
|
||||
return builder.buildResources("config", "config:" + operation, ctx, "us-east-1", ACCOUNT, "aws");
|
||||
}
|
||||
|
||||
// ── ARN formats within others ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* An ARN a member names that fits its own type's format and a narrower one the table gives as lying within it is
|
||||
* the narrower type's, not checked as the member's own: an endpoint group's ARN named as an accelerator, and an AWS
|
||||
* managed RAM permission's named as a customer managed one, leave the request checked on {@code *}, while the
|
||||
* member's own type's ARN is checked on itself.
|
||||
*/
|
||||
@Test
|
||||
void anArnOfANarrowerTypeIsNotCheckedAsTheMembersOwn() {
|
||||
String accelerator = "arn:aws:globalaccelerator::000000000000:accelerator/1234abcd";
|
||||
setJsonBody("{\"AcceleratorArn\":\"" + accelerator + "\"}");
|
||||
assertEquals(List.of(accelerator), builder.buildResources("globalaccelerator",
|
||||
"globalaccelerator:DescribeAccelerator", ctx, "us-west-2", ACCOUNT, "aws"));
|
||||
setJsonBody("{\"AcceleratorArn\":\"" + accelerator + "/listener/0123abcd/endpoint-group/0123456789ab\"}");
|
||||
assertEquals(List.of("*"), builder.buildResources("globalaccelerator",
|
||||
"globalaccelerator:DescribeAccelerator", ctx, "us-west-2", ACCOUNT, "aws"));
|
||||
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
request("/updatepermission");
|
||||
String permission = "arn:aws:ram:us-east-1:000000000000:permission/mine";
|
||||
setJsonBody("{\"permissionArn\":\"" + permission + "\"}");
|
||||
assertEquals(List.of(permission),
|
||||
builder.buildResources("ram", "ram:UpdatePermission", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
setJsonBody("{\"permissionArn\":\"arn:aws:ram::aws:permission/AWSRAMDefaultPermissionSubnet\"}");
|
||||
assertEquals(List.of("*"),
|
||||
builder.buildResources("ram", "ram:UpdatePermission", ctx, "us-east-1", ACCOUNT, "aws"));
|
||||
}
|
||||
|
||||
// ── AWS DMS ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -996,6 +996,104 @@ def with_vendored_formats(namespace: str, formats: dict[str, str], source: dict)
|
||||
return {kind: vendored.get(kind, written) for kind, written in formats.items()}
|
||||
|
||||
|
||||
# What each ARN format variable matches, as the reader matches it (`RequestResourceMembers.pattern`): the partition one
|
||||
# or more characters but a colon, the Region and the account none or more of them, any other variable one or more of
|
||||
# any character. A variable is `(colon, least)`: whether it takes a colon and the fewest characters it takes.
|
||||
FORMAT_VARIABLE_CLASSES = {"Partition": (False, 1), "Region": (False, 0), "Account": (False, 0)}
|
||||
ANY_VARIABLE_CLASS = (True, 1)
|
||||
|
||||
|
||||
def _format_steps(format_: str) -> list:
|
||||
"""The format as the steps its pattern takes: each literal character, and each variable as its class."""
|
||||
steps: list = []
|
||||
at = 0
|
||||
for variable in VARIABLE_RE.finditer(format_):
|
||||
steps += format_[at:variable.start()]
|
||||
steps.append(FORMAT_VARIABLE_CLASSES.get(variable.group(1), ANY_VARIABLE_CLASS))
|
||||
at = variable.end()
|
||||
return steps + list(format_[at:])
|
||||
|
||||
|
||||
def _format_states(steps: list, states: frozenset[int], character: str | None) -> frozenset[int]:
|
||||
"""The positions in `steps` the pattern may be at after reading `character` from `states`, each position taken past
|
||||
the variables that may match nothing; `character` None takes the starting states only that far."""
|
||||
moved: set[int] = set()
|
||||
for at in states:
|
||||
if character is None:
|
||||
moved.add(at)
|
||||
elif at < len(steps):
|
||||
step = steps[at]
|
||||
if isinstance(step, str):
|
||||
if step == character:
|
||||
moved.add(at + 1)
|
||||
elif step[0] or character != ":":
|
||||
# A variable takes the character and either ends there or stays at `at` to take more.
|
||||
moved.update((at, at + 1))
|
||||
reached = set(moved)
|
||||
for at in sorted(moved):
|
||||
while at < len(steps) and not isinstance(steps[at], str) and steps[at][1] == 0:
|
||||
at += 1
|
||||
reached.add(at)
|
||||
return frozenset(reached)
|
||||
|
||||
|
||||
def format_within(inner: str, outer: str) -> bool:
|
||||
"""Whether every ARN `inner`'s pattern matches, `outer`'s matches too, the formats read as the reader reads them:
|
||||
an endpoint group's `accelerator/${ResourceId}/listener/${ListenerId}/endpoint-group/${EndpointGroupId}` lies within
|
||||
its accelerator's `accelerator/${ResourceId}`, the accelerator's id taking any character."""
|
||||
if not format_pattern(outer).fullmatch(format_sample(inner)):
|
||||
return False
|
||||
steps_in, steps_out = _format_steps(inner), _format_steps(outer)
|
||||
# Every character either format writes, a colon, and one standing for any other.
|
||||
alphabet = set(VARIABLE_RE.sub("", inner + outer)) | {":", "\0"}
|
||||
start = (_format_states(steps_in, frozenset({0}), None), _format_states(steps_out, frozenset({0}), None))
|
||||
seen, pending = {start}, [start]
|
||||
while pending:
|
||||
states_in, states_out = pending.pop()
|
||||
if len(steps_in) in states_in and len(steps_out) not in states_out:
|
||||
return False
|
||||
for character in alphabet:
|
||||
reached_in = _format_states(steps_in, states_in, character)
|
||||
if reached_in:
|
||||
reached = (reached_in, _format_states(steps_out, states_out, character))
|
||||
if reached not in seen:
|
||||
seen.add(reached)
|
||||
pending.append(reached)
|
||||
return True
|
||||
|
||||
|
||||
def format_pattern(format_: str) -> re.Pattern:
|
||||
"""The format's pattern as the reader builds it (`RequestResourceMembers.pattern`)."""
|
||||
parts, at = [], 0
|
||||
for variable in VARIABLE_RE.finditer(format_):
|
||||
colon, least = FORMAT_VARIABLE_CLASSES.get(variable.group(1), ANY_VARIABLE_CLASS)
|
||||
parts += [re.escape(format_[at:variable.start()]), ("." if colon else "[^:]") + ("+" if least else "*")]
|
||||
at = variable.end()
|
||||
return re.compile("".join(parts) + re.escape(format_[at:]))
|
||||
|
||||
|
||||
def format_sample(format_: str) -> str:
|
||||
"""An ARN the format's pattern matches, each variable one character but a colon."""
|
||||
return VARIABLE_RE.sub("x", format_)
|
||||
|
||||
|
||||
def narrower_formats(formats: dict[str, dict[str, str]],
|
||||
path_formats: dict[str, dict[str, str]]) -> dict[str, dict[str, list[str]]]:
|
||||
"""Each namespace's types, with the types of its own whose formats lie within theirs and not the other way
|
||||
(`format_within`): an ARN of such a type fits the wider format too, and is the narrower type's, an endpoint group's
|
||||
ARN under its accelerator's. The reader takes an ARN a member names as the type it fits only when no narrower type
|
||||
the resource does not read fits it as well. Read from the formats as they stand, route types' among them."""
|
||||
narrower: dict[str, dict[str, list[str]]] = {}
|
||||
for namespace in sorted(set(formats) | set(path_formats)):
|
||||
kinds = {**formats.get(namespace, {}), **path_formats.get(namespace, {})}
|
||||
for outer, wide in sorted(kinds.items()):
|
||||
inner = sorted(kind for kind, narrow in kinds.items()
|
||||
if kind != outer and format_within(narrow, wide) and not format_within(wide, narrow))
|
||||
if inner:
|
||||
narrower.setdefault(namespace, {})[outer] = inner
|
||||
return narrower
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# botocore
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -5445,6 +5543,7 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
|
||||
"mintedIds": minted,
|
||||
"mintedSuffixes": suffixes,
|
||||
"integerVariables": integer_variables(operations, namespaces, data),
|
||||
"narrowerFormats": narrower_formats(formats, path_formats),
|
||||
"forwardedActions": forwarded,
|
||||
"statementActions": statement_types,
|
||||
"statements": statements_for(sources, statement_types, formats),
|
||||
@@ -5608,7 +5707,8 @@ def render(document: dict) -> str:
|
||||
lines = ["{"]
|
||||
for key in ("_source", "namespaces", "notCovered", "otherNamespaces", "arnFormats", "pathFormats",
|
||||
"resourceTagKeys",
|
||||
"resourceKeys", "unqualified", "mintedIds", "mintedSuffixes", "integerVariables", "forwardedActions",
|
||||
"resourceKeys", "unqualified", "mintedIds", "mintedSuffixes", "integerVariables", "narrowerFormats",
|
||||
"forwardedActions",
|
||||
"statementActions", "statements"):
|
||||
lines.append(f' "{key}": {json.dumps(document[key])},')
|
||||
lines.append(' "operations": {')
|
||||
@@ -6046,6 +6146,9 @@ def derive(document: dict, data: Path) -> list[str]:
|
||||
integers = integer_variables(document["operations"], document["namespaces"], data)
|
||||
if document.get("integerVariables", {}) != integers:
|
||||
problems.append(f"integerVariables differ from botocore: expected {json.dumps(integers)}")
|
||||
narrower = narrower_formats(document["arnFormats"], document.get("pathFormats", {}))
|
||||
if document.get("narrowerFormats", {}) != narrower:
|
||||
problems.append(f"narrowerFormats differ from the formats: expected {json.dumps(narrower)}")
|
||||
unqualified = unqualified_types(document["arnFormats"], document["operations"], document["namespaces"], data)
|
||||
if document["unqualified"] != unqualified:
|
||||
problems.append(f"the file checks {json.dumps(document['unqualified'])} without a qualifier, the reference "
|
||||
|
||||
@@ -4282,6 +4282,65 @@ def test_an_example_arn_with_a_variable_empty_names_it_empty_for_a_request_leavi
|
||||
REPOSITORIES) == [package]
|
||||
|
||||
|
||||
ACCELERATOR = "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}"
|
||||
LISTENER = "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}"
|
||||
ENDPOINT_GROUP = ("arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}"
|
||||
"/endpoint-group/${EndpointGroupId}")
|
||||
|
||||
|
||||
def test_a_format_lies_within_another_when_every_arn_of_it_fits_the_other():
|
||||
"""A format lies within another when the other's pattern matches every ARN its own does, each variable read as the
|
||||
reader reads it: an id takes any character, so an endpoint group's format lies within its accelerator's and its
|
||||
listener's; the Region and the account take none or any but a colon, so an empty Region, or the account `aws`,
|
||||
lies within a variable one; an id takes a colon too; a literal takes itself alone, and a variable may not
|
||||
stand for one."""
|
||||
assert r.format_within(ENDPOINT_GROUP, ACCELERATOR)
|
||||
assert r.format_within(ENDPOINT_GROUP, LISTENER)
|
||||
assert r.format_within(LISTENER, ACCELERATOR)
|
||||
assert not r.format_within(ACCELERATOR, LISTENER)
|
||||
assert r.format_within("arn:${Partition}:s3::${Account}:accesspoint/${AccessPointAlias}",
|
||||
"arn:${Partition}:s3:${Region}:${Account}:accesspoint/${AccessPointName}")
|
||||
assert not r.format_within("arn:${Partition}:s3:${Region}:${Account}:accesspoint/${AccessPointName}",
|
||||
"arn:${Partition}:s3::${Account}:accesspoint/${AccessPointAlias}")
|
||||
assert r.format_within("arn:${Partition}:ram::aws:permission/${ResourcePath}",
|
||||
"arn:${Partition}:ram:${Region}:${Account}:permission/${ResourcePath}")
|
||||
assert not r.format_within("arn:${Partition}:svc:${Region}:${Account}:a:${Id}",
|
||||
"arn:${Partition}:svc:${Region}:${Account}:a:b${Id}")
|
||||
assert r.format_within("arn:${Partition}:svc:${Region}:${Account}:a:b:${Id}",
|
||||
"arn:${Partition}:svc:${Region}:${Account}:a:${Id}")
|
||||
assert not r.format_within("arn:${Partition}:svc:${Region}:${Account}:a:${Id}",
|
||||
"arn:${Partition}:svc:${Region}:${Account}:${Kind}/${Id}")
|
||||
|
||||
|
||||
def test_a_namespace_gives_each_format_the_ones_strictly_within_it():
|
||||
"""Each type is given the types of its namespace whose formats lie within its own and not the other way, route types
|
||||
among them; formats that only overlap, or match the same ARNs, give nothing."""
|
||||
formats = {"globalaccelerator": {"accelerator": ACCELERATOR, "listener": LISTENER, "endpointgroup": ENDPOINT_GROUP,
|
||||
"attachment": "arn:${Partition}:globalaccelerator::${Account}:attachment/${Id}"},
|
||||
"svc": {"one": "arn:${Partition}:svc:${Region}:${Account}:thing/${Name}",
|
||||
"same": "arn:${Partition}:svc:${Region}:${Account}:thing/${Other}",
|
||||
"left": "arn:${Partition}:svc:${Region}:${Account}:a/${Id}",
|
||||
"right": "arn:${Partition}:svc:${Region}:${Account}:${Id}/b"}}
|
||||
assert r.narrower_formats(formats, {"svc": {"route": "arn:${Partition}:svc:${Region}:${Account}:thing/x/y"}}) == {
|
||||
"globalaccelerator": {"accelerator": ["endpointgroup", "listener"], "listener": ["endpointgroup"]},
|
||||
"svc": {"one": ["route"], "same": ["route"]}}
|
||||
|
||||
|
||||
def test_a_built_document_gives_the_nested_formats_and_the_check_derives_them_again(isolated, tmp_path):
|
||||
"""The table gives each type the types whose formats lie within its own, and the check derives them again from
|
||||
the formats, reporting a file that gives others."""
|
||||
write_models(tmp_path, {"svc": model({"DescribeListener": {"ListenerArn": "String"}})})
|
||||
formats = {kind: written.replace("globalaccelerator", "svc") for kind, written in
|
||||
(("accelerator", ACCELERATOR), ("listener", LISTENER), ("endpointgroup", ENDPOINT_GROUP))}
|
||||
document = r.build([reference("svc", {"DescribeListener": ["listener"]}, formats)], "test", tmp_path,
|
||||
"botocore test")
|
||||
assert document["narrowerFormats"] == {"svc": {"accelerator": ["endpointgroup", "listener"],
|
||||
"listener": ["endpointgroup"]}}
|
||||
assert r.validate(with_apis_named(document)) == [] and r.derive(document, tmp_path) == []
|
||||
document["narrowerFormats"] = {"svc": {"accelerator": ["listener"]}}
|
||||
assert any("narrowerFormats differ from the formats" in problem for problem in r.derive(document, tmp_path))
|
||||
|
||||
|
||||
def test_a_vendored_arn_format_replaces_the_reference_wildcard_alone(tmp_path, monkeypatch):
|
||||
"""A namespace's vendored ARN format takes the place of the Service Reference's where the reference ends the format
|
||||
in a wildcard, the vendored one having a variable there; one differing anywhere else is refused, the source being
|
||||
|
||||
Reference in new issue
Block a user