diff --git a/docs/services/ses.md b/docs/services/ses.md index 4940a070cb..289d543979 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -583,7 +583,9 @@ an ARN member by the ARN it holds; an operation naming none of the types its act that names a role `iam:PassRole` for it. A v2 `SendEmail` is authorized as `ses:SendEmail` whatever its content: `ses:SendRawEmail` is a v1 action. v1 and v2 share the operation in that table, and a request is read for its own API's members alone: a v1 `SendEmail` names its identity by its `SourceArn`, a v2 one by its -`FromEmailAddressIdentityArn`, and neither is read for the other's. `ListConfigurationSets` and `ListEmailIdentities` are +`FromEmailAddressIdentityArn`, and neither is read for the other's. A v2 templated send is checked on the +template its `Content.Template` (`DefaultContent.Template` for `SendBulkEmail`) names by `TemplateName` or +`TemplateArn`; one with inline `TemplateContent` names none. `ListConfigurationSets` and `ListEmailIdentities` are `POST /v2/email/list-configuration-sets` and `POST /v2/email/list-identities` in the model; the `GET` routes an SDK built before that still sends are served but match no route of the model, so they are not checked. diff --git a/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java b/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java index 5b62fad7ec..953cd062b3 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java +++ b/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java @@ -42,13 +42,15 @@ final class RequestResourceMembers { /** An ARN may be nested in structures, array elements or map values. */ private static final Pattern ARN_MEMBER = Pattern.compile( "[A-Za-z][A-Za-z0-9_]*(\\[])?(\\.[A-Za-z][A-Za-z0-9_]*(\\[])?)?" + + "|[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*){2}" + "|[A-Za-z][A-Za-z0-9_]*\\{\\}(\\.[A-Za-z][A-Za-z0-9_]*){1,2}"); /** - * A member filling a variable may also be a field of a structure, or of each of a list's structures, or of a field - * of each of them, or of a map's structure values, one value for each, or a map's keys ({@code Name{}}). + * A member filling a variable may also be a field of a structure or of a structure inside one, or of each of a + * list's structures, or of a field of each of them, or of a map's structure values, one value for each, or a map's + * keys ({@code Name{}}). */ private static final Pattern FILL_MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*(\\[]|\\[]\\.[A-Za-z][A-Za-z0-9_]*" - + "(\\.[A-Za-z][A-Za-z0-9_]*)?|\\{}|\\{}\\.[A-Za-z][A-Za-z0-9_]*|\\.[A-Za-z][A-Za-z0-9_]*)?"); + + "(\\.[A-Za-z][A-Za-z0-9_]*)?|\\{}|\\{}\\.[A-Za-z][A-Za-z0-9_]*|(\\.[A-Za-z][A-Za-z0-9_]*){1,2})?"); /** * A member a service finds a resource by: one list, or a value at any depth of structures, as a lookup's request * gives it ({@code AlternateIdentifier.ExternalId.Id}). diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index b243ef5b47..558dc80309 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.44.9 (local/aws/botocore)", "retrieved": "2026-11-26", "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.9 (installed package)", "retrieved": "2026-11-27", "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", "appconfigdata"], "application-autoscaling": ["application-autoscaling"], "aps": ["amp"], "athena": ["athena"], "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"], "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"], "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", "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", "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", "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", "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//`, 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", "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", "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:::/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", "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"}, "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-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", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "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", "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", "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", "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"], @@ -7344,10 +7344,10 @@ "ses:RegisterMemberToAddressList": {"action": "ses:RegisterMemberToAddressList", "types": ["mailmanager-address-list"], "resources": [{"type": "mailmanager-address-list", "fill": {"AddressListId": "AddressListId"}, "apis": ["json/2023-10-17", "smithy-rpc-v2-cbor/2023-10-17"]}]}, "ses:ReorderReceiptRuleSet": {"action": "ses:ReorderReceiptRuleSet", "types": [], "resources": []}, "ses:SendBounce": {"action": "ses:SendBounce", "types": ["identity"], "resources": [{"types": ["identity"], "arn": "BounceSenderArn", "apis": ["query/2010-12-01"]}, {"types": ["identity"], "arn": "BouncedRecipientInfoList[].RecipientArn", "apis": ["query/2010-12-01"]}]}, - "ses:SendBulkEmail": {"action": "ses:SendBulkEmail", "types": ["configuration-set", "identity", "template"], "resources": [{"types": ["configuration-set", "identity", "template"], "arn": "FeedbackForwardingEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "FromEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["rest-json/2019-09-27"]}, {"type": "identity", "fill": {}, "when": {"FeedbackForwardingEmailAddressIdentityArn": [null]}, "default": true, "apis": ["rest-json/2019-09-27"]}]}, + "ses:SendBulkEmail": {"action": "ses:SendBulkEmail", "types": ["configuration-set", "identity", "template"], "resources": [{"types": ["configuration-set", "identity", "template"], "arn": "FeedbackForwardingEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "FromEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["rest-json/2019-09-27"]}, {"type": "identity", "fill": {}, "when": {"FeedbackForwardingEmailAddressIdentityArn": [null]}, "default": true, "apis": ["rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "DefaultContent.Template.TemplateArn", "apis": ["rest-json/2019-09-27"]}, {"type": "template", "fill": {"TemplateName": "DefaultContent.Template.TemplateName"}, "apis": ["rest-json/2019-09-27"]}]}, "ses:SendBulkTemplatedEmail": {"action": "ses:SendBulkTemplatedEmail", "types": ["configuration-set", "identity", "template"], "resources": [{"types": ["configuration-set", "identity", "template"], "arn": "ReturnPathArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "SourceArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "TemplateArn", "apis": ["query/2010-12-01"]}, {"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["query/2010-12-01"]}, {"type": "template", "fill": {"TemplateName": "Template"}, "apis": ["query/2010-12-01"]}]}, "ses:SendCustomVerificationEmail": {"action": "ses:SendCustomVerificationEmail", "types": ["custom-verification-email-template", "identity"], "resources": [{"type": "custom-verification-email-template", "fill": {"TemplateName": "TemplateName"}, "apis": ["query/2010-12-01", "rest-json/2019-09-27"]}]}, - "ses:SendEmail": {"action": "ses:SendEmail", "types": ["configuration-set", "identity", "template"], "resources": [{"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["query/2010-12-01", "rest-json/2018-07-26", "rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "ReturnPathArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "SourceArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "FeedbackForwardingEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "FromEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"type": "identity", "fill": {}, "when": {"FeedbackForwardingEmailAddressIdentityArn": [null]}, "default": true, "apis": ["rest-json/2019-09-27"]}]}, + "ses:SendEmail": {"action": "ses:SendEmail", "types": ["configuration-set", "identity", "template"], "resources": [{"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["query/2010-12-01", "rest-json/2018-07-26", "rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "Content.Template.TemplateArn", "apis": ["rest-json/2018-07-26", "rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "ReturnPathArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "SourceArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "FeedbackForwardingEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"types": ["configuration-set", "identity", "template"], "arn": "FromEmailAddressIdentityArn", "apis": ["rest-json/2019-09-27"]}, {"type": "identity", "fill": {}, "when": {"FeedbackForwardingEmailAddressIdentityArn": [null]}, "default": true, "apis": ["rest-json/2019-09-27"]}, {"type": "template", "fill": {"TemplateName": "Content.Template.TemplateName"}, "apis": ["rest-json/2019-09-27"]}]}, "ses:SendRawEmail": {"action": "ses:SendRawEmail", "types": ["configuration-set", "identity"], "resources": [{"types": ["configuration-set", "identity"], "arn": "FromArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity"], "arn": "ReturnPathArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity"], "arn": "SourceArn", "apis": ["query/2010-12-01"]}, {"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["query/2010-12-01"]}]}, "ses:SendTemplatedEmail": {"action": "ses:SendTemplatedEmail", "types": ["configuration-set", "identity", "template"], "resources": [{"types": ["configuration-set", "identity", "template"], "arn": "ReturnPathArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "SourceArn", "apis": ["query/2010-12-01"]}, {"types": ["configuration-set", "identity", "template"], "arn": "TemplateArn", "apis": ["query/2010-12-01"]}, {"type": "configuration-set", "fill": {"ConfigurationSetName": "ConfigurationSetName"}, "apis": ["query/2010-12-01"]}, {"type": "template", "fill": {"TemplateName": "Template"}, "apis": ["query/2010-12-01"]}]}, "ses:SetActiveReceiptRuleSet": {"action": "ses:SetActiveReceiptRuleSet", "types": [], "resources": []}, diff --git a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java index 6b37004612..97f2d13efc 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java @@ -336,7 +336,7 @@ class RequestResourceMembersTest { // No types, a type with no format, no member, or beside members reading it otherwise. for (String bad : List.of("\"types\":[],\"through\":\"SessionId\"", "\"types\":[\"pool\"],\"through\":\"SessionId\"", "\"types\":[\"group\"],\"through\":\"Ids[][]\"", - "\"types\":[\"group\"],\"through\":\"Session.Id.Part\"", + "\"types\":[\"group\"],\"through\":\"Session.Id.Part.Name\"", "\"types\":[\"group\"],\"through\":\"SessionId\",\"unless\":{\"GroupId\":[null]}", "\"types\":[\"group\"],\"through\":\"SessionId\",\"when\":{\"Ids[]\":[\"a\"]}", "\"types\":[\"group\"],\"through\":\"SessionId\",\"arn\":\"GroupArn\"", @@ -356,7 +356,7 @@ class RequestResourceMembersTest { String formats = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\"}}"; assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"other\"],\"arn\":\"Arn\"}"))); assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"type\":\"thing\",\"fill\":{\"Other\":\"Name\"}}"))); - assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"thing\"],\"arn\":\"a.b.c\"}"))); + assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"thing\"],\"arn\":\"a.b.c.d\"}"))); assertThrows(IllegalStateException.class, () -> parse( "{\"namespaces\":{\"a\":[]},\"arnFormats\":{\"a\":{\"thing\":\"*\"}},\"operations\":{\"a:Op\":{\"resources\":[]}}}")); // A type made under a parent whose format it does not extend by one id. diff --git a/src/test/java/io/floci/aws/services/iam/SesV2IamEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/SesV2IamEnforcementIntegrationTest.java index aeb86e9331..eb36fa1780 100644 --- a/src/test/java/io/floci/aws/services/iam/SesV2IamEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/SesV2IamEnforcementIntegrationTest.java @@ -164,6 +164,90 @@ class SesV2IamEnforcementIntegrationTest { .when().post("/v2/email/outbound-emails")); } + /** + * A v2 templated send is checked on the template its {@code Content.Template} names, by name or by ARN: a grant on + * one template reaches a send with that template and no other. + */ + @Test + void aV2TemplatedSendIsCheckedOnTheTemplateItNames() { + String sender = identity(); + String allowed = template(); + String other = template(); + String accessKeyId = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"ses:SendEmail", + "Resource":"arn:aws:ses:us-east-1:%s:template/%s"}]}""".formatted(ACCOUNT, allowed)); + + templatedSend(accessKeyId, sender, "\"TemplateName\":\"" + allowed + "\"").then().statusCode(200); + templatedSend(accessKeyId, sender, "\"TemplateArn\":\"arn:aws:ses:us-east-1:" + ACCOUNT + ":template/" + + allowed + "\"").then().statusCode(200); + assertAccessDenied(templatedSend(accessKeyId, sender, "\"TemplateName\":\"" + other + "\"")); + } + + /** A deny on one template stops a v2 send with that template, by name or by ARN, and no other. */ + @Test + void aDenyOnATemplateStopsAV2SendWithIt() { + String sender = identity(); + String denied = template(); + String other = template(); + String accessKeyId = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"*","Resource":"*"}, + {"Effect":"Deny","Action":"ses:SendEmail","Resource":"arn:aws:ses:us-east-1:%s:template/%s"}]}""" + .formatted(ACCOUNT, denied)); + + assertAccessDenied(templatedSend(accessKeyId, sender, "\"TemplateName\":\"" + denied + "\"")); + assertAccessDenied(templatedSend(accessKeyId, sender, "\"TemplateArn\":\"arn:aws:ses:us-east-1:" + ACCOUNT + + ":template/" + denied + "\"")); + templatedSend(accessKeyId, sender, "\"TemplateName\":\"" + other + "\"").then().statusCode(200); + } + + /** A v2 bulk send is checked on the template its {@code DefaultContent.Template} names. */ + @Test + void aV2BulkSendIsCheckedOnTheTemplateItsDefaultContentNames() { + String sender = identity(); + String allowed = template(); + String other = template(); + String accessKeyId = userWithPolicy(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"ses:SendBulkEmail", + "Resource":"arn:aws:ses:us-east-1:%s:template/%s"}]}""".formatted(ACCOUNT, allowed)); + + bulkSend(accessKeyId, sender, "\"TemplateName\":\"" + allowed + "\"").then().statusCode(200); + bulkSend(accessKeyId, sender, "\"TemplateArn\":\"arn:aws:ses:us-east-1:" + ACCOUNT + ":template/" + + allowed + "\"").then().statusCode(200); + assertAccessDenied(bulkSend(accessKeyId, sender, "\"TemplateName\":\"" + other + "\"")); + } + + private static Response bulkSend(String accessKeyId, String from, String selector) { + return given() + .contentType("application/json") + .header("Authorization", auth(accessKeyId, "ses")) + .body(""" + {"FromEmailAddress":"%s","DefaultContent":{"Template":{%s,"TemplateData":"{}"}}, + "BulkEmailEntries":[{"Destination":{"ToAddresses":["to@example.com"]}}]}""".formatted(from, selector)) + .when().post("/v2/email/outbound-bulk-emails"); + } + + private static Response templatedSend(String accessKeyId, String from, String selector) { + return given() + .contentType("application/json") + .header("Authorization", auth(accessKeyId, "ses")) + .body(""" + {"FromEmailAddress":"%s","Destination":{"ToAddresses":["to@example.com"]}, + "Content":{"Template":{%s,"TemplateData":"{}"}}}""".formatted(from, selector)) + .when().post("/v2/email/outbound-emails"); + } + + private static String template() { + String name = "sesv2-iam-" + UUID.randomUUID().toString().substring(0, 8); + given() + .contentType("application/json") + .header("Authorization", auth(ACCOUNT, "ses")) + .body("{\"TemplateName\":\"" + name + "\",\"TemplateContent\":{\"Subject\":\"s\",\"Text\":\"t\"}}") + .when().post("/v2/email/templates") + .then().statusCode(200); + return name; + } + private static String identity() { String identity = "sesv2-iam-" + UUID.randomUUID().toString().substring(0, 8) + "@example.com"; given() diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 801d0df4f5..3c2d4a876d 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -2266,6 +2266,52 @@ def with_structure_names(resources: list[dict], formats: dict[str, str], names: return found +def nested_type_selectors(models: dict[str, dict], operation: str, types: list[str]) -> dict[str, dict[str, str]]: + """By type, the members selecting it in a structure named after the type that a top-level structure of the + operation's request holds, the one ending `Name` and the one ending `Arn` named after the type too, each by its + kind: SES v2 `SendEmail` names its template in `Content.Template.TemplateName` or `Content.Template.TemplateArn`. + A type two such structures name is left out.""" + found: dict[str, set[tuple[str, str]]] = {} + for model in models.values(): + spec = model["operations"].get(operation) + if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model): + continue + for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items(): + shape = model["shapes"][member["shape"]] + if member.get("location") not in BODY_LOCATIONS or shape["type"] != "structure": + continue + for field, ref in shape.get("members", {}).items(): + inner = model["shapes"][ref["shape"]] + kinds = [kind for kind in types if stem(field) == stem(kind)] + if inner["type"] != "structure" or len(kinds) != 1: + continue + selectors = tuple(sorted((suffix, f"{name}.{field}.{sub}") + for sub, nested in inner.get("members", {}).items() + for suffix in ("Name", "Arn") + if sub == field + suffix + and model["shapes"][nested["shape"]]["type"] == "string")) + if selectors: + found.setdefault(kinds[0], set()).add(selectors) + return {kind: dict(next(iter(paths))) for kind, paths in sorted(found.items()) if len(paths) == 1} + + +def with_nested_type_selectors(resources: list[dict], types: list[str], formats: dict[str, str], + selectors: dict[str, dict[str, str]]) -> list[dict]: + """The resources, and each type `nested_type_selectors` finds selected in a nested structure: its ARN from the + member ending `Arn`, and its format's one name variable filled from the member ending `Name`.""" + found = list(resources) + for kind, paths in selectors.items(): + variables = [variable for variable in VARIABLE_RE.findall(formats.get(kind, "")) if variable.endswith("Name") + and variable not in KNOWN_VARIABLES] + entries = [] + if "Arn" in paths: + entries.append({"types": types, "arn": paths["Arn"]}) + if "Name" in paths and len(variables) == 1: + entries.append({"type": kind, "fill": {variables[0]: paths["Name"]}}) + found += [entry for entry in entries if entry not in found] + return found + + def structure_account_members(models: dict[str, dict], operation: str, types: list[str]) -> dict[str, str]: """The top-level members of the operation's request whose name ends in `Account`, by the type whose botocore structure (the one named after the type, `Snapshot` for `snapshot`) has a member of that same name; a type @@ -4201,6 +4247,7 @@ def read_resources(operation: str, types: list[str], formats: dict[str, str], mo resources = with_account(resources, formats, account_members(models, name)) resources = with_structure_account(resources, formats, structure_account_members(models, name, types)) resources = with_structure_names(resources, formats, structure_name_fields(models, name, types)) + resources = with_nested_type_selectors(resources, types, formats, nested_type_selectors(models, name, types)) resources = with_change_lists(resources, types, formats, members) resources = with_type_named_members(resources, types, formats, members, stem(SUBJECT_RE.sub("", name))) resources = with_arn_of(resources, formats, name_or_arn_members(models, name), @@ -5215,12 +5262,13 @@ PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?$") FIND_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[]|(\.[A-Za-z][A-Za-z0-9_]*)*)$") # A member of a request's body at any depth, as `body_only_identifiers` writes it: `Delete.Objects[].Key`. BODY_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?(\.[A-Za-z][A-Za-z0-9_]*(\[])?)*$") -# A member filling a variable may also be a field of a structure, or of each element of a list of structures, one -# value for each. +# A member filling a variable may also be a field of a structure, or of a structure inside one, or of each element of +# a list of structures, one value for each. FILL_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[]|\[]\.[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)?|\{}" - r"|\{}\.[A-Za-z][A-Za-z0-9_]*|\.[A-Za-z][A-Za-z0-9_]*)?$") + r"|\{}\.[A-Za-z][A-Za-z0-9_]*|(\.[A-Za-z][A-Za-z0-9_]*){1,2})?$") # ARN paths can traverse structures, array elements ([]) and map values ({}). ARN_PATH_RE = re.compile(r"^(?:[A-Za-z][A-Za-z0-9_]*(\[])?(\.[A-Za-z][A-Za-z0-9_]*(\[])?)?" + r"|[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*){2}" r"|[A-Za-z][A-Za-z0-9_]*\{\}(\.[A-Za-z][A-Za-z0-9_]*){1,2})$") # A format's resource that is a literal and one variable, at its end. ONE_VARIABLE_RE = re.compile(r"^[^$]*\$\{\w+}$") diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index 0f31619dba..99fc379e33 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -843,6 +843,33 @@ def test_a_structure_named_after_the_type_gives_its_name_to_a_type_named_by_noth {"type": "recorder", "fill": {}}] +def test_a_structure_named_after_the_type_inside_a_request_structure_selects_it_by_its_name_or_arn(tmp_path): + # SES v2's SendEmail names its template in Content.Template.TemplateName or Content.Template.TemplateArn. + service = model({"SendThing": {"Content": "Content", "Other": "Content"}}) + service["shapes"]["Content"] = {"type": "structure", "members": {"Template": {"shape": "Template"}, + "Simple": {"shape": "Template"}}} + service["shapes"]["Template"] = {"type": "structure", "members": {"TemplateName": {"shape": "String"}, + "TemplateArn": {"shape": "String"}, + "TemplateData": {"shape": "String"}}} + write_models(tmp_path, {"svc": service}) + models = r.load_models(tmp_path, {"svc"}) + # Two request structures holding it say nothing about which one selects it. + assert r.nested_type_selectors(models, "SendThing", ["template", "pool"]) == {} + del service["shapes"]["SendThingIn"]["members"]["Other"] + write_models(tmp_path / "one", {"svc": service}) + models = r.load_models(tmp_path / "one", {"svc"}) + selectors = r.nested_type_selectors(models, "SendThing", ["template", "pool"]) + assert selectors == {"template": {"Name": "Content.Template.TemplateName", "Arn": "Content.Template.TemplateArn"}} + formats = {"template": "arn:${Partition}:svc:${Region}:${Account}:template/${TemplateName}", + "pool": "arn:${Partition}:svc:${Region}:${Account}:pool/${PoolName}"} + given = [{"type": "pool", "fill": {"PoolName": "Pool"}}] + assert r.with_nested_type_selectors(given, ["template", "pool"], formats, selectors) == given + [ + {"types": ["template", "pool"], "arn": "Content.Template.TemplateArn"}, + {"type": "template", "fill": {"TemplateName": "Content.Template.TemplateName"}}] + assert r.FILL_PATH_RE.match("Content.Template.TemplateName") + assert r.ARN_PATH_RE.match("Content.Template.TemplateArn") + + def test_an_account_member_of_a_types_own_structure_gives_that_types_account_alone(tmp_path): service = model({"RestoreThing": {"ThingName": "String", "PoolId": "String", "OwnerAccount": "String"}}) service["shapes"]["Thing"] = {"type": "structure", "members": {"OwnerAccount": {"shape": "String"}}} @@ -1347,11 +1374,11 @@ def with_a_create() -> dict: @pytest.mark.parametrize("change, problem", [ (lambda d: d["operations"]["svc:A"]["resources"][0].update(types=["pool"]), "not resource types"), - (lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a.b.c"), "no member"), + (lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a.b.c.d"), "no member"), (lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a[][]"), "no member"), (lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "Ids[][]"}), "no member"), - (lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "a.b.c"}), + (lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "a.b.c.d"}), "no member"), (lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "SessionId", "when": {"Ids[]": ["a"]}}), "no member's values"), @@ -1362,7 +1389,7 @@ def with_a_create() -> dict: (lambda d: d["operations"]["svc:A"]["resources"].__setitem__(0, {"types": ["thing"], "through": "SessionId", "before": "#"}), "neither an ARN member"), (lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="Group.Names[]"), "no variables"), - (lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="A.B.Name"), "no variables"), + (lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupName="A.B.C.Name"), "no variables"), (lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"Other": "x"}), "fixes"), (lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"GroupName": "x"}), "fixes"), (lambda d: d["operations"]["svc:B"]["resources"][0].update(fixed={"GroupId": 1}), "fixes"),