fix(dynamodb): authorize ListTables against its regional collection (#7336)

* fix(dynamodb): authorize ListTables against its regional collection

* test(dynamodb): reject ListTables authorization through ignored selectors

* fix: generate the DynamoDB ListTables request resource

Record the measured table collection as a generated correction and dispatch table-owned operations before hand-built fallbacks. Preserve batch, transaction and PartiQL resource extraction.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>

---------

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-02 22:24:56 -04:00
1 parent 2b07f85a71
commit 918c57a64e
10 files changed
+223 -10

No files matched your search

+15
View File
@@ -3,6 +3,21 @@
**Protocol:** JSON 1.0 (`X-Amz-Target: DynamoDB_20120810.*`)
**Endpoint:** `POST http://localhost:4566/`
## ListTables authorization
With IAM enforcement enabled, `ListTables` evaluates the regional table collection
`arn:<partition>:dynamodb:<region>:<account>:table/*`. A matching allow permits listing;
a matching explicit deny overrides it. A grant for one table or a table-name prefix
does not permit listing, and a grant in another account or Region does not apply.
The listing is not filtered to the caller's individually authorized tables.
This resource matching was checked against live AWS with isolated role sessions.
Pagination and ignored table selectors do not change the collection being authorized.
Other DynamoDB operations retain their own authorization resources.
The generated IAM request-resource table records `ListTables` as a measured correction to
the Service Reference. Other DynamoDB operations keep their existing resource builders,
including batch, transaction and PartiQL table extraction.
## Supported Actions
| Action | Description |
@@ -50,6 +50,11 @@ public final class RequestResources {
private RequestResources() {
}
/** Whether the generated table owns this operation, including corrections to hand-built namespaces. */
public static boolean reads(String operation) {
return operation != null && RequestResourceMembers.table().operations().containsKey(operation);
}
/**
* The ARNs of the resources a request names, in the request's partition, Region and account: empty when the
* table does not read the operation or its request names none, so it is checked on {@code *}. The operation,
@@ -190,6 +190,9 @@ public class ResourceArnBuilder {
if (credentialScope == null) {
return List.of("*");
}
if (operation != null && operation.startsWith(credentialScope + ":") && RequestResources.reads(operation)) {
return namedResources(credentialScope, operation, ctx, region, accountId, partition);
}
String path = "s3".equals(credentialScope) ? ctx.getUriInfo().getPath()
: IamActionRegistry.decodedPath(ctx);
return switch (credentialScope) {
@@ -1,11 +1,11 @@
{
"_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.113 (installed package)", "retrieved": "2026-11-02", "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": {"acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "redshift-data": ["redshift-data"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]},
"_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-03", "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": {"acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "dynamodb": ["dynamodb"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "redshift-data": ["redshift-data"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]},
"clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"},
"handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"],
"notCovered": {"access-analyzer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "account": "REST: its requests name their resources in the path, which RequestResources does not read yet", "airflow": "REST: its requests name their resources in the path, which RequestResources does not read yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appsync": "REST: its requests name their resources in the path, which RequestResources does not read yet", "aps": "REST: its requests name their resources in the path, which RequestResources does not read yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources does not read yet", "batch": "REST: its requests name their resources in the path, which RequestResources does not read yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "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 does not read yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources does not read 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 does not read yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources does not read yet", "controltower": "REST: its requests name their resources in the path, which RequestResources does not read yet", "datasync": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "detective": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dlm": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ecs": "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: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticfilesystem": "REST: its requests name their resources in the path, which RequestResources does not read yet", "elasticmapreduce": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "emr-serverless": "REST: its requests name their resources in the path, which RequestResources does not read yet", "es": "REST: its requests name their resources in the path, which RequestResources does not read yet", "execute-api": "REST: its requests name their resources in the path, which RequestResources does not read yet", "fis": "REST: its requests name their resources in the path, which RequestResources does not read yet", "glue": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "guardduty": "REST: its requests name their resources in the path, which RequesLine truncated
"otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "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-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "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", "kinesisvideo", "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", "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", "quicksight", "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", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "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", "xray"],
"arnFormats": {"acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "ecr": {"repository": "arn:${Partition}:ecr:${Region}:${Account}:repository/${RepositoryName}"}, "elasticloadbalancing": {"listener-rule/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener-rule/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/gwy": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/gwy/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/net": "arn:${Partition}:elasticloadbalancing:${Region}:${AccoLine truncated
"arnFormats": {"acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "dynamodb": {"backup": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/backup/${BackupName}", "export": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/export/${ExportName}", "global-table": "arn:${Partition}:dynamodb::${Account}:global-table/${GlobalTableName}", "import": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/import/${ImportName}", "index": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/index/${IndexName}", "stream": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/stream/${StreamLabel}", "table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}, "ecr": {"repository": "arn:${Partition}:ecr:${Region}:${Account}:repository/${RepositoryName}"}, "elasticloadbalancing": {"listener-rule/app":Line truncated
"unqualified": {"states": ["statemachine"]},
"mintedIds": {"events": ["api-destination", "connection"]},
"operations": {
@@ -579,6 +579,7 @@
"cur:PutReportDefinition": {"action": "cur:PutReportDefinition", "types": ["cur"], "resources": [{"type": "cur", "fill": {"ReportName": "ReportDefinition.ReportName"}}]},
"cur:TagResource": {"action": "cur:TagResource", "types": ["cur"], "resources": [{"type": "cur", "fill": {"ReportName": "ReportName"}}]},
"cur:UntagResource": {"action": "cur:UntagResource", "types": ["cur"], "resources": [{"type": "cur", "fill": {"ReportName": "ReportName"}}]},
"dynamodb:ListTables": {"action": "dynamodb:ListTables", "types": [], "resources": [{"type": "table", "fill": {}}]},
"ecr:BatchCheckLayerAvailability": {"action": "ecr:BatchCheckLayerAvailability", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
"ecr:BatchDeleteImage": {"action": "ecr:BatchDeleteImage", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
"ecr:BatchGetImage": {"action": "ecr:BatchGetImage", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
@@ -42,7 +42,11 @@ class RequestResourceMembersTest {
RequestResourceMembers.Table table = RequestResourceMembers.table();
assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states")));
assertTrue(table.handBuilt().contains("lambda"));
assertTrue(table.namespaces().stream().noneMatch(table.handBuilt()::contains));
assertEquals(Set.of("dynamodb"), table.namespaces().stream().filter(table.handBuilt()::contains)
.collect(Collectors.toSet()));
assertEquals(Set.of("dynamodb:ListTables"), table.operations().keySet().stream()
.filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':'))))
.collect(Collectors.toSet()), "only explicit corrections override hand-built operations");
assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains));
assertTrue(table.otherNamespaces().stream().noneMatch(table.notCovered()::contains));
table.operations().forEach((operation, resources) -> {
@@ -16,6 +16,8 @@ import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -25,6 +27,19 @@ class RequestResourcesTest {
private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory());
private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
@Test
void listTablesCorrectionReadsTheCollectionAndLeavesOtherDynamoOperationsHandBuilt() {
assertTrue(RequestResources.reads("dynamodb:ListTables"));
assertFalse(RequestResources.reads("dynamodb:BatchWriteItem"));
assertFalse(RequestResources.reads("dynamodb:ExecuteStatement"));
assertFalse(RequestResources.reads(null));
for (String body : List.of("{}", "{\"TableName\":\"ignored\",\"ExclusiveStartTableName\":\"cursor\"}")) {
assertEquals(List.of("arn:aws-us-gov:dynamodb:us-gov-west-1:111122223333:table/*"),
RequestResources.of("dynamodb:ListTables", json(body), "aws-us-gov", "us-gov-west-1",
"111122223333"));
}
}
@Test
void aMemberHoldingAnArnOfATypeTheActionActsOnNamesThatResource() {
assertEquals(List.of(MACHINE), of("states:DescribeStateMachine",
@@ -0,0 +1,104 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import io.github.hectorvent.floci.testing.SignedIamEnforcementProfile;
import io.github.hectorvent.floci.testing.SignedIamUsers;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.net.URI;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
@TestProfile(SignedIamEnforcementProfile.class)
class DynamoDbListTablesAuthorizationIntegrationTest {
@TestHTTPResource
URI endpoint;
@ParameterizedTest
@CsvSource({
"arn:aws:dynamodb:us-east-1:000000000000:table/*,false,true",
"arn:aws:dynamodb:us-east-1:000000000000:table/*,true,false",
"arn:aws:dynamodb:us-east-1:000000000000:table/orders,false,false",
"arn:aws:dynamodb:us-east-1:000000000000:table/orders,true,true",
"arn:aws:dynamodb:us-east-1:000000000000:table/orders-*,false,false",
"arn:aws:dynamodb:us-east-1:000000000000:table/orders-*,true,true",
"arn:aws:dynamodb:us-east-1:000000000000:table/,false,false",
"arn:aws:dynamodb:us-east-1:000000000000:table/,true,true",
"arn:aws:dynamodb:us-east-1:000000000000:table/?,false,true",
"arn:aws:dynamodb:us-east-1:000000000000:table/?,true,false",
"arn:aws:dynamodb:us-east-1:000000000000:*,false,true",
"arn:aws:dynamodb:us-east-1:000000000000:*,true,false",
"arn:aws:dynamodb:eu-central-1:000000000000:table/*,false,false",
"arn:aws:dynamodb:eu-central-1:000000000000:table/*,true,true",
"arn:aws:dynamodb:us-east-1:123400009876:table/*,false,false",
"arn:aws:dynamodb:us-east-1:123400009876:table/*,true,true",
"arn:aws:dynamodb:*:*:table/*,false,true",
"arn:aws:dynamodb:*:*:table/*,true,false",
"arn:aws:dynamodb:us-east-1:000000000000:table/*/index/*,false,false",
"arn:aws:dynamodb:us-east-1:000000000000:table/*/index/*,true,true",
"*,false,true",
"*,true,false"
})
void signedSdkUsesTheRegionalTableCollection(String resource, boolean explicitDeny, boolean allowed)
throws Exception {
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "list-tables-", "list",
policy(resource, explicitDeny));
DynamoDbClient client = DynamoDbClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(user.accessKeyId(), user.secretAccessKey()))).build()) {
if (allowed) {
assertEquals(200, client.listTables(request -> request.limit(1)).sdkHttpResponse().statusCode());
} else {
DynamoDbException denied = assertThrows(DynamoDbException.class,
() -> client.listTables(request -> request.limit(1)));
assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode());
}
}
}
@ParameterizedTest
@CsvSource({"json,false", "json,true", "cbor,false", "cbor,true"})
void ignoredTableSelectorsCannotRedirectCollectionAuthorization(String protocol, boolean explicitDeny)
throws Exception {
boolean cbor = "cbor".equals(protocol);
ObjectMapper mapper = cbor ? new ObjectMapper(new CBORFactory()) : new ObjectMapper();
URI uri = cbor ? endpoint.resolve("/service/DynamoDB_20120810/operation/ListTables") : endpoint;
String contentType = cbor ? "application/cbor" : "application/x-amz-json-1.0";
Map<String, String> headers = cbor ? Map.of("content-type", contentType, "accept", contentType)
: Map.of("content-type", contentType, "x-amz-target", "DynamoDB_20120810.ListTables");
byte[] body = mapper.writeValueAsBytes(Map.of("Limit", 1, "ExclusiveStartTableName", "page-start",
"TableName", "decoy", "ResourceArn", "arn:aws:dynamodb:us-east-1:000000000000:table/decoy"));
try (SignedIamUsers.User user = SignedIamUsers.createUser(endpoint, "list-selectors-", "list",
policy("arn:aws:dynamodb:us-east-1:000000000000:table/decoy", explicitDeny))) {
Response response = given().filter(user.signer("dynamodb")).headers(headers).body(body).post(uri);
assertEquals(explicitDeny ? 200 : (cbor ? 403 : 400), response.statusCode(), response.asString());
if (!explicitDeny) {
assertTrue(mapper.readTree(response.asByteArray()).path("__type").asText()
.contains("AccessDeniedException"));
}
}
}
private static String policy(String resource, boolean explicitDeny) {
String statement = "{\"Effect\":\"%s\",\"Action\":\"dynamodb:ListTables\",\"Resource\":\"%s\"}";
return "{\"Version\":\"2012-10-17\",\"Statement\":["
+ (explicitDeny ? statement.formatted("Allow", "*") + "," : "")
+ statement.formatted(explicitDeny ? "Deny" : "Allow", resource) + "]}";
}
}
@@ -854,6 +854,28 @@ class ResourceArnBuilderTest {
// ── DynamoDB ─────────────────────────────────────────────────────────────────
@Test
void listTablesUsesTheCollectionInTheRequestPartitionRegionAndAccount() {
for (String body : List.of("{}", "{\"ExclusiveStartTableName\":\"page-start\"}",
"{\"TableName\":\"decoy\",\"ResourceArn\":\"decoy\"}")) {
setJsonBody(body);
assertEquals(List.of("arn:aws-cn:dynamodb:cn-north-1:123456789012:table/*"),
builder.buildResources("dynamodb", "dynamodb:ListTables", ctx,
"cn-north-1", "123456789012", "aws-cn"));
}
}
@Test
void listTablesDoesNotChangeOtherTablelessOperations() {
setJsonBody("{}");
assertEquals(List.of("*"), builder.buildResources("dynamodb", "dynamodb:DescribeLimits",
ctx, "us-east-1", ACCOUNT, "aws"));
setJsonBody("{\"TableName\":\"Orders\"}");
assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/Orders"),
builder.buildResources("dynamodb", "dynamodb:DescribeTable",
ctx, "us-east-1", ACCOUNT, "aws"));
}
@Test
void dynamoDbBuildsArnFromShortTableName() {
setJsonBody("{\"TableName\":\"FgacTable\"}");
+20 -6
View File
@@ -59,8 +59,9 @@ A type nothing names is not checked: an action lists the optional resources its
that covers what it does name. An operation whose action acts on no resource type, or whose request
names none, is checked on `*`, as AWS checks it.
Only the namespaces in `NAMESPACES` are read, and in them every operation, whether Floci serves it
or not. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and
Every operation in `NAMESPACES` is read, whether Floci serves it or not. Explicit `CORRECTIONS`
in `HAND_BUILT` are also read, overriding only those operations while the remaining operations
keep their existing resource builders. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and
`NOT_COVERED` the ones Floci serves that are not read yet, each with its reason;
`RequestResourceNamespacesIntegrationTest` fails for a served namespace in none of the three.
`CORRECTIONS` gives an operation's resources where the rule gets them wrong, each with its reason; a
@@ -261,6 +262,10 @@ NOT_COVERED: dict[str, str] = {
# them apart (EventBridge's `events` and EventBridge V2's `eventsv2`): Floci applies it only to a request the service
# of that endpoint serves, never by a member a caller could add to a request of the other.
CORRECTIONS: dict[str, tuple[list[dict], str]] = {
"dynamodb:ListTables": ([{"type": "table", "fill": {}}],
"AWS policy probes accepted by review #7336 authorize the literal regional table/*: "
"table/? matches while table/ does not, despite the Service Reference listing no "
"resource types; request-body table names and pagination do not select its resource"),
**{f"states:{operation}": ([{"type": kind, "fill": {}, "find": ["taskToken"]}
for kind in ("activity", "statemachine")],
"AWS callback policy probes on 2026-11-02 authorize an activity token against its "
@@ -884,13 +889,14 @@ def with_through(resources: list[dict], namespace: str, types: list[str], member
def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> dict:
upstream = checked_actions(documents)
covered = {operation: value for operation, value in upstream.items() if namespace_of(operation) in NAMESPACES}
covered = {operation: value for operation, value in upstream.items() if reads(operation)}
_check_overrides(covered)
read_namespaces = set(NAMESPACES) | {namespace_of(operation) for operation in covered}
namespaces = {namespace: sorted({client for operation, value in covered.items()
if namespace_of(operation) == namespace for client in value["clients"]
if client not in CLIENTS_NOT_READ})
for namespace in sorted(NAMESPACES)}
formats = arn_formats(documents, set(NAMESPACES))
for namespace in sorted(read_namespaces)}
formats = arn_formats(documents, read_namespaces)
unqualified = unqualified_types()
minted = minted_types()
missing = [f"{name} names {namespace}:{kind}, no resource type with an ARN format of a namespace the file reads"
@@ -963,6 +969,12 @@ def _with_resource_types(documents: list[dict]) -> set[str]:
if any(action.get("Resources") for action in document.get("Actions", []))}
def reads(operation: str) -> bool:
"""Read whole namespaces, or explicit corrections in a namespace otherwise built by hand."""
namespace = namespace_of(operation)
return namespace in NAMESPACES or namespace in HAND_BUILT and operation in CORRECTIONS
def _check_overrides(covered: dict[str, dict]) -> None:
"""Every correction names an operation the file reads, and no namespace is in two places."""
stale = [f"CORRECTIONS names {operation}, which the file does not read" for operation in CORRECTIONS
@@ -1189,7 +1201,9 @@ def verify_against(vendored: dict, upstream: dict[str, dict], formats: dict[str,
if changed:
untrue.append(f"AWS no longer gives {namespace}'s {', '.join(changed)} the ARN format the file does")
added = sorted(operation for operation in upstream
if namespace_of(operation) in vendored["namespaces"] and operation not in vendored["operations"])
if namespace_of(operation) in vendored["namespaces"]
and (namespace_of(operation) not in vendored["handBuilt"] or operation in CORRECTIONS)
and operation not in vendored["operations"])
return untrue, added
@@ -663,6 +663,36 @@ def test_callback_resources_are_resolved_from_the_token(operation):
assert "no resource types" in reason
def test_list_tables_correction_names_the_literal_collection_without_selectors():
resources, reason = r.CORRECTIONS["dynamodb:ListTables"]
assert resources == [{"type": "table", "fill": {}}]
assert "table/?" in reason
formats = {"table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}
assert not r._resource_problems("dynamodb:ListTables", resources[0], [], formats)
assert r._resource_problems("dynamodb:OtherOperation", resources[0], [], formats)
assert r.reads("dynamodb:ListTables")
assert not r.reads("dynamodb:BatchWriteItem")
assert not r.reads("dynamodb:ExecuteStatement")
def test_hand_built_correction_is_generated_without_claiming_other_operations(corrections, tmp_path):
corrections.setattr(r, "CORRECTIONS", {"hand:ListThings": ([{"type": "thing", "fill": {}}], "measured collection")})
documents = DOCUMENTS + [reference("hand", {"ListThings": [], "PutThing": ["thing"]},
{"thing": "arn:${Partition}:hand:${Region}:${Account}:thing/${ThingName}"})]
hand = model({"ListThings": {}, "PutThing": {"ThingName": "String"}})
hand["metadata"]["endpointPrefix"] = "hand"
write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}}), "hand": hand})
document = r.build(documents, "test", tmp_path, "botocore test")
assert document["operations"]["hand:ListThings"] == {
"action": "hand:ListThings", "types": [], "resources": [{"type": "thing", "fill": {}}]}
assert "hand:PutThing" not in document["operations"]
assert document["namespaces"]["hand"] == ["hand"]
assert document["handBuilt"] == ["hand"]
assert r.validate(document) == []
assert r.derive(document, tmp_path) == []
assert r.verify_against(document, r.checked_actions(documents), document["arnFormats"]) == ([], [])
def test_measured_callback_correction_retains_action_metadata_and_rejects_unlisted_resources():
formats = {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}",
"statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}"}