fix(secretsmanager): resolve stored resource tags for IAM conditions (#8359)

* fix(secretsmanager): resolve stored resource tags for IAM conditions
* fix(secretsmanager): read secret tags through the generated resource-tag keys
This commit is contained in:
luiseterc authored and GitHub committed 2026-11-14 21:33:20 -04:00
1 parent 68f5510ce8
commit 4c7f057072
15 files changed
+403 -34

No files matched your search

+10 -2
View File
@@ -2707,7 +2707,9 @@ after the name left open, so a policy scoped to a name prefix such as `secret:ap
ARN that matches none is evaluated as given and, where it names another Region or account, as the
secret of that name in the request's. An operation acting on no
resource type in the Service Authorization Reference (`ListSecrets`, `GetRandomPassword`,
`BatchGetSecretValue`) is evaluated on `*`.
`BatchGetSecretValue`) is evaluated on `*`. A secret's stored tags fill `aws:ResourceTag/<key>` and
`secretsmanager:ResourceTag/<key>`, the resource-tag keys the Service Reference gives the `Secret` type,
as described under `aws:ResourceTag/<key>` below.
**KMS keys.** A request that names a key by its id, an alias name, an alias ARN or a key ARN is
evaluated against the stored key's ARN, as the KMS API reference resolves the request's key
@@ -3019,7 +3021,13 @@ floci populates:
once per resource and denied when any of them fails the condition, as on AWS.
`logs:CreateLogStream`, `logs:DeleteLogStream`, `logs:TagResource`, `logs:UntagResource`,
`logs:ListTagsForResource`, `logs:DeleteLogGroup`, `logs:PutRetentionPolicy` and
`logs:DeleteRetentionPolicy` use the owning log group's tags.
`logs:DeleteRetentionPolicy` use the owning log group's tags. Any other ARN a request is checked on
takes the resource-tag keys the generated `resourceTagKeys` table in `iam-request-resources.json` gives
its type (`aws:ResourceTag/`, `secretsmanager:ResourceTag/`), which `regen_iam_request_resources.py`
reads from the Service Reference for every namespace it reads, valued from the tags the type's service
holds on that resource (`StoredResourceArns.storedTags`); a service that holds none leaves them absent.
Secrets Manager answers for its secrets. Tag keys differing only in case are one condition key holding
every value.
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
+15
View File
@@ -33,6 +33,21 @@
| `StopReplicationToReplica` | Promote a replica to a standalone primary |
<!-- floci:actions:end -->
## IAM resource tags
With IAM enforcement enabled, secret-scoped operations read current stored tags
for `aws:ResourceTag/<key>` and `secretsmanager:ResourceTag/<key>` conditions.
Names and full ARNs resolve to the same stored secret before authorization.
Retagging or removing a tag affects the next request; request tags cannot replace
the stored tags during a write. Missing secrets contribute no stored tags.
Case-variant tag keys retain all their values in the case-insensitive IAM context,
so set operators such as `ForAnyValue:StringEquals` inspect every stored value.
Bare operators retain the shared evaluator's single-value semantics; use consistent
tag key casing or a set operator for case-variant keys.
The keys are the ones the Service Reference gives the `Secret` resource type, from
the generated `resourceTagKeys` table in `iam-request-resources.json`, regenerated by
`tools/aws/regen_iam_request_resources.py`.
## Secret write events
Successful `PutSecretValue` and `UpdateSecret` API calls emit an EventBridge event with
@@ -51,6 +51,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
/**
@@ -109,6 +110,7 @@ public class IamConditionContextResolver {
private final Instance<IamService> iamService;
private final Instance<LambdaWebService> lambdaWebService;
private final Instance<RequestConditionSpelling> requestConditionSpellings;
private final Instance<StoredResourceArns> storedResourceArns;
private final RequestContext requestContext;
private final RegionResolver regionResolver;
private final EmulatorConfig config;
@@ -129,13 +131,14 @@ public class IamConditionContextResolver {
Instance<IamService> iamService,
Instance<LambdaWebService> lambdaWebService,
Instance<RequestConditionSpelling> requestConditionSpellings,
Instance<StoredResourceArns> storedResourceArns,
RequestContext requestContext,
RegionResolver regionResolver,
EmulatorConfig config,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog serviceCatalog) {
this(dynamoDbFacade, ec2Service, s3Service, logsService, crossAccountService, iamService,
lambdaWebService, requestConditionSpellings, requestContext, regionResolver,
lambdaWebService, requestConditionSpellings, storedResourceArns, requestContext, regionResolver,
config, currentVertxRequest, serviceCatalog, Clock.systemUTC());
}
@@ -147,6 +150,7 @@ public class IamConditionContextResolver {
Instance<IamService> iamService,
Instance<LambdaWebService> lambdaWebService,
Instance<RequestConditionSpelling> requestConditionSpellings,
Instance<StoredResourceArns> storedResourceArns,
RequestContext requestContext,
RegionResolver regionResolver,
EmulatorConfig config,
@@ -160,6 +164,7 @@ public class IamConditionContextResolver {
this.iamService = iamService;
this.lambdaWebService = lambdaWebService;
this.requestConditionSpellings = requestConditionSpellings;
this.storedResourceArns = storedResourceArns;
this.requestContext = requestContext;
this.regionResolver = regionResolver;
this.config = config;
@@ -168,6 +173,85 @@ public class IamConditionContextResolver {
this.serviceCatalog = serviceCatalog;
}
/**
* The condition keys the tags of the resource {@code resource} names give: each resource-tag key the
* request-resources table gives the ARN's type ({@code aws:ResourceTag/<key>},
* {@code secretsmanager:ResourceTag/<key>}) for each tag the service of the ARN's namespace holds on it
* ({@link StoredResourceArns#storedTags}), whatever the namespace; null when the table gives the type no such keys or
* the service holds no tags there. Tag keys differing only in case are one condition key, as IAM's keys are,
* holding every value, so a set operator sees each. Read for each ARN on its own, never borrowed from another
* target in the same request; {@link #withResourceTags} puts them in that ARN's context.
*/
public Map<String, List<String>> resourceTags(String resource) {
if (!AwsArnUtils.isArn(resource)) {
return null;
}
String namespace = AwsArnUtils.parse(resource).service();
Map<String, List<String>> types = RequestResourceMembers.table().resourceTagKeys()
.getOrDefault(namespace, Map.of());
StoredResourceArns stored = types.isEmpty() ? null : storedResourceArns(namespace);
Map<String, String> tags = stored == null ? Map.of() : stored.storedTags(resource);
List<String> prefixes = tags.isEmpty() ? List.of() : resourceTagPrefixes(namespace, resource, types);
if (prefixes.isEmpty()) {
return null;
}
Map<String, List<String>> conditions = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
tags.forEach((key, value) -> prefixes.forEach(prefix ->
conditions.computeIfAbsent(prefix + key, ignored -> new ArrayList<>()).add(value)));
return conditions;
}
/**
* {@code context} with the condition keys {@link #resourceTags} read from a resource's stored tags, each in place of
* any key of the same name, case aside, the context held; {@code context} itself when there are none.
*/
public static Map<String, List<String>> withResourceTags(Map<String, List<String>> context,
Map<String, List<String>> resourceTags) {
if (resourceTags == null || resourceTags.isEmpty()) {
return context;
}
Map<String, List<String>> result = context == null ? new LinkedHashMap<>() : new LinkedHashMap<>(context);
resourceTags.forEach((key, values) -> {
result.keySet().removeIf(key::equalsIgnoreCase);
result.put(key, List.copyOf(values));
});
return result;
}
/**
* The resource-tag key prefixes {@code types} gives the namespace's type whose ARN format {@code resource} fits,
* the longest format where several do (a type whose ARN extends another's is its own); none when it fits none.
*/
private static List<String> resourceTagPrefixes(String namespace, String resource,
Map<String, List<String>> types) {
Map<String, RequestResourceMembers.ArnFormat> formats = RequestResourceMembers.table().formats()
.getOrDefault(namespace, Map.of());
RequestResourceMembers.ArnFormat fitted = null;
List<String> prefixes = List.of();
for (Map.Entry<String, List<String>> type : types.entrySet()) {
RequestResourceMembers.ArnFormat format = formats.get(type.getKey());
if (format != null && format.pattern().matcher(resource).matches()
&& (fitted == null || format.format().length() > fitted.format().length())) {
fitted = format;
prefixes = type.getValue();
}
}
return prefixes;
}
/** The registered finder of the namespace's stored resources; null when there is none. */
private StoredResourceArns storedResourceArns(String namespace) {
if (storedResourceArns == null || storedResourceArns.isUnsatisfied()) {
return null;
}
for (StoredResourceArns stored : storedResourceArns) {
if (stored.namespace().equals(namespace)) {
return stored;
}
}
return null;
}
public Map<String, List<String>> resolve(String credentialScope, String action,
ContainerRequestContext ctx) {
return switch (credentialScope) {
@@ -1343,6 +1343,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
taggedContext = conditionContextResolver.withEc2ResourceContext(
credentialScope, operationAction, resource, region, accountId, targetContext);
}
taggedContext = IamConditionContextResolver.withResourceTags(taggedContext,
conditionContextResolver.resourceTags(resource));
Map<String, List<String>> effectiveContext = IamConditionContextResolver.withGlobalContext(
taggedContext, resource, region, accountId, resourceOwnerAccountId, action);
ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor(
@@ -391,7 +391,7 @@ final class RequestResourceMembers {
}
type.getValue().forEach(key -> {
String prefix = key.asText("");
if (!prefix.matches("[a-z0-9-]+:ResourceTag/") || keys.contains(prefix)) {
if (!prefix.matches("[a-z0-9-]+:(?i:ResourceTag)/") || keys.contains(prefix)) {
throw new IllegalStateException(RESOURCE_NAME + " has malformed resource tag keys");
}
keys.add(prefix);
@@ -1,6 +1,7 @@
package io.floci.aws.core.common;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
@@ -24,11 +25,12 @@ import java.util.Optional;
* the key an alias names; EMR, for the clusters of its instance groups; IAM Identity Center, for the accounts its
* permission sets are provisioned to; Resource Explorer, for its default view; OAM and RAM, for the sinks,
* invitations and shares of other accounts they act on; Secrets Manager, for the secret a name or an ARN names,
* random suffix included); looked up lazily by {@code ResourceArnBuilder} through {@code Instance<StoredResourceArns>}
* for the namespace a request is of, so IAM never depends on that service directly.</p>
* random suffix included, and its tags); looked up lazily by {@code ResourceArnBuilder} and
* {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default, {@code forwarded}): never a fact about what an operation acts on, which the table alone
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
* says, from botocore and the Service Reference, or from what AWS says where neither carries it.</p>
*/
public interface StoredResourceArns {
@@ -77,6 +79,16 @@ public interface StoredResourceArns {
return Optional.empty();
}
/**
* The tags of the resource stored under {@code arn}, in the account and Region the ARN names, by key, which the
* resource-tag keys the table gives the ARN's type take as their values ({@code aws:ResourceTag/<key>}); empty
* when the service holds no such resource or keeps no tags on it. Read on every request checked on such an ARN,
* so it reads the one resource the ARN names and leaves the resource as it is (a secret's last-accessed date).
*/
default Map<String, String> storedTags(String arn) {
return Map.of();
}
/**
* Whether the resource {@code arn} names, one {@link #find} gave, lets every principal of its account have a
* service act on it through that service, as the key policy AWS writes for an AWS managed KMS key does: a request
@@ -62,6 +62,8 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
private static final String AWSCURRENT = "AWSCURRENT";
private static final String AWSPREVIOUS = "AWSPREVIOUS";
private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/** The random characters Secrets Manager adds after a hyphen at the end of a secret's ARN. */
private static final int RANDOM_SUFFIX_LENGTH = 6;
private static final String AWS_MANAGED_KEY = "aws/secretsmanager";
private static final String PENDING_DELETION_STATE = "PendingDeletion";
private static final Pattern SECRET_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9/_+=.@-]+");
@@ -549,13 +551,42 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
return findArnByName(accountId, nameFromArn, arn.region());
}
/**
* The tags of the secret stored under the full ARN {@code arn}, in the account and Region it names; empty when
* there is none. The secret is stored by the ARN's name without the hyphen and random characters Secrets Manager
* adds, so this reads that one entry and matches it on the whole ARN, never scanning the store; it reads no value
* and leaves the secret's last-accessed date as it is.
*/
@Override
public Map<String, String> storedTags(String arn) {
AwsArnUtils.Arn parsed = parseOrNull(arn);
String name = secretNameOrNull(parsed);
int named = name == null ? -1 : name.length() - RANDOM_SUFFIX_LENGTH - 1;
if (named < 1 || name.charAt(named) != '-') {
return Map.of();
}
Secret secret = stored(parsed.accountId(), regionKey(parsed.region(), name.substring(0, named)))
.filter(candidate -> arn.equals(candidate.getArn())).orElse(null);
if (secret == null || secret.getTags() == null) {
return Map.of();
}
Map<String, String> tags = new LinkedHashMap<>();
for (Secret.Tag tag : secret.getTags()) {
tags.put(tag.key(), tag.value() == null ? "" : tag.value());
}
return tags;
}
/** The full ARN of the secret with this name in the given account and region, or empty when there is none. */
Optional<String> findArnByName(String accountId, String name, String region) {
String key = regionKey(region, name);
Optional<Secret> secret = store instanceof AccountAwareStorageBackend<Secret> aware
return stored(accountId, regionKey(region, name)).map(Secret::getArn);
}
/** The secret the account holds under the storage key, a legacy entry included. */
private Optional<Secret> stored(String accountId, String key) {
return store instanceof AccountAwareStorageBackend<Secret> aware
? aware.getForAccount(accountId, key).or(() -> aware.getLegacyForAccount(accountId, key))
: store.get(key);
return secret.map(Secret::getArn);
}
/**
@@ -2275,8 +2306,8 @@ public class SecretsManagerService implements ResourceProvider, StoredResourceAr
private static String randomSuffix() {
ThreadLocalRandom rng = ThreadLocalRandom.current();
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < 6; i++) {
StringBuilder sb = new StringBuilder(RANDOM_SUFFIX_LENGTH);
for (int i = 0; i < RANDOM_SUFFIX_LENGTH; i++) {
sb.append(ALPHABET.charAt(rng.nextInt(ALPHABET.length())));
}
return sb.toString();
@@ -5,7 +5,7 @@
"notCovered": {"airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "aps": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup:<id>:autoScalingGroupName/<name>`, while Floci mints `autoScalingGroup:<name>`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rules do not fill a name from, so nearly every operation's resource would be left open", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/<name>_<id>, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2-instance-connect": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment/<application>/<name>`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reading it needs the stored environment those find", "elasticfilesystem": "REST: its requests namLine 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", "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", "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", "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", "ssmmessages", "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"],
"arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "account": {"account": "arn:${Partition}:account::${Account}:account", "accountInOrganization": "arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}, "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}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "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}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudfront-keyvaluestore": {"key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${ResourceId}"}, "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:${Line truncated
"resourceTagKeys": {"ec2": {"application-status-check": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-block": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-manager-data-export": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-cancellation-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-modification-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "carrier-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "client-vpn-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "coip-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "customer-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "declarative-policies-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dedicated-host": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dhcp-options": ["aws:ResourceTag/", "ec2:ResourceTag/"], "egress-only-internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-gpu": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-ip": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-instance-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fpga-image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "host-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image-usage-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-snapshot-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-connect-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-event-window": ["aws:ResourceTag/", "ec2:ResourceTag/"], "internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-external-resource-verification-token": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-internet-registry-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool-allocation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv4pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv6pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "key-pair": ["aws:ResourceTag/", "ec2:ResourceTag/"], "launch-template": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-virtual-interface-group-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-vpc-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "mac-modification-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "natgateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-acl": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-path": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "outpost-lag": ["aws:ResourceTag/", "ec2:ResourceTag/"], "placement-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "prefix-list": ["aws:ResourceTag/", "ec2:ResourceTag/"], "replace-root-volume-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "reserved-instances": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-peer": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-network": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-subnet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group-rule": ["aws:ResourceTag/", "ec2:ResourceTag/"], "snapshot": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-fleet-request": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-instances-request": ["aws:ResourceTag/", "Line truncated
"resourceTagKeys": {"access-analyzer": {"Analyzer": ["aws:ResourceTag/"]}, "acm": {"acme-domain-validation": ["aws:ResourceTag/"], "acme-endpoint": ["aws:ResourceTag/"], "acme-external-account-binding": ["aws:ResourceTag/"], "certificate": ["aws:ResourceTag/"]}, "application-autoscaling": {"ScalableTarget": ["aws:ResourceTag/"]}, "athena": {"capacity-reservation": ["aws:ResourceTag/"], "datacatalog": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"], "system-table": ["aws:ResourceTag/"], "workgroup": ["aws:ResourceTag/"]}, "bcm-data-exports": {"billingview": ["aws:ResourceTag/"], "export": ["aws:ResourceTag/"]}, "bcm-pricing-calculator": {"bill-scenario": ["aws:ResourceTag/"], "workload-estimate": ["aws:ResourceTag/"]}, "budgets": {"budget": ["aws:ResourceTag/"], "budgetAction": ["aws:ResourceTag/"]}, "ce": {"anomalymonitor": ["aws:ResourceTag/"], "anomalysubscription": ["aws:ResourceTag/"], "billingview": ["aws:ResourceTag/"], "costcategory": ["aws:ResourceTag/"]}, "cloudfront": {"anycast-ip-list": ["aws:ResourceTag/"], "connection-function": ["aws:ResourceTag/"], "connection-group": ["aws:ResourceTag/"], "distribution": ["aws:ResourceTag/"], "distribution-tenant": ["aws:ResourceTag/"], "function": ["aws:ResourceTag/"], "key-value-store": ["aws:ResourceTag/"], "streaming-distribution": ["aws:ResourceTag/"], "trust-store": ["aws:ResourceTag/"], "vpcorigin": ["aws:ResourceTag/"]}, "cloudtrail": {"channel": ["aws:ResourceTag/"], "dashboard": ["aws:ResourceTag/"], "eventdatastore": ["aws:ResourceTag/"], "trail": ["aws:ResourceTag/"]}, "codebuild": {"project": ["aws:ResourceTag/"], "report-group": ["aws:ResourceTag/"]}, "codepipeline": {"action": ["aws:ResourceTag/"], "actiontype": ["aws:ResourceTag/"], "pipeline": ["aws:ResourceTag/"], "stage": ["aws:ResourceTag/"], "webhook": ["aws:ResourceTag/"]}, "cognito-identity": {"identitypool": ["aws:ResourceTag/"]}, "cognito-idp": {"userpool": ["aws:ResourceTag/"]}, "controltower": {"EnabledBaseline": ["aws:ResourceTag/"], "EnabledControl": ["aws:ResourceTag/"], "LandingZone": ["aws:ResourceTag/"]}, "datasync": {"agent": ["aws:ResourceTag/"], "discoveryjob": ["aws:ResourceTag/"], "location": ["aws:ResourceTag/"], "storagesystem": ["aws:ResourceTag/"], "task": ["aws:ResourceTag/"], "taskexecution": ["aws:ResourceTag/"]}, "dynamodb": {"index": ["aws:ResourceTag/"], "stream": ["aws:ResourceTag/"], "table": ["aws:ResourceTag/"]}, "ec2": {"application-status-check": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-block": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-manager-data-export": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-cancellation-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-modification-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "carrier-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "client-vpn-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "coip-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "customer-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "declarative-policies-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dedicated-host": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dhcp-options": ["aws:ResourceTag/", "ec2:ResourceTag/"], "egress-only-internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-gpu": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-ip": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-instance-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fpga-image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "host-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image-usage-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-snapshot-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-connect-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-event-window": ["aws:ResourceTag/", "ec2:ResourceTag/"], "internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-external-resource-verification-token": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-internet-registry-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool-allocation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery-associatioLine truncated
"resourceKeys": {"ec2": {"capacity-reservation": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:CapacityReservationFleet": {"member": "CapacityReservationFleetId", "arn": "capacity-reservation-fleet"}, "ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:EndDateType": {"member": "EndDateType"}, "ec2:EphemeralStorage": {"member": "EphemeralStorage"}, "ec2:InstanceMatchCriteria": {"member": "InstanceMatchCriteria"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:Tenancy": {"member": "Tenancy"}}, "carrier-gateway": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "dhcp-options": {"ec2:DhcpOptionsID": {"member": "DhcpOptionsId"}}, "fpga-image": {"ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}}, "image": {"ec2:ImageID": {"member": "ImageId"}, "ec2:ImageType": {"member": "ImageType"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "instance": {"ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:InstanceID": {"member": "InstanceId"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "internet-gateway": {"ec2:InternetGatewayID": {"member": "InternetGatewayId"}}, "launch-template": {"ec2:LaunchTemplate": {"member": "LaunchTemplateId", "arn": "launch-template"}}, "network-acl": {"ec2:NetworkAclID": {"member": "NetworkAclId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "network-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:NetworkInterfaceID": {"member": "NetworkInterfaceId"}, "ec2:Subnet": {"member": "SubnetId", "arn": "subnet"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "reserved-instances": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:InstanceType": {"member": "InstanceType"}}, "route-table": {"ec2:RouteTableID": {"member": "RouteTableId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "secondary-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}}, "security-group": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "snapshot": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:SnapshotID": {"member": "SnapshotId"}, "ec2:VolumeSize": {"member": "VolumeSize"}}, "subnet": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:SubnetID": {"member": "SubnetId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "transit-gateway": {"ec2:transitGatewayId": {"member": "TransitGatewayId"}}, "transit-gateway-attachment": {"ec2:transitGatewayAttachmentId": {"member": "TransitGatewayAttachmentId"}}, "transit-gateway-connect-peer": {"ec2:transitGatewayConnectPeerId": {"member": "TransitGatewayConnectPeerId"}}, "transit-gateway-metering-policy": {"ec2:transitGatewayMeteringPolicyId": {"member": "TransitGatewayMeteringPolicyId"}}, "transit-gateway-multicast-domain": {"ec2:transitGatewayMulticastDomainId": {"member": "TransitGatewayMulticastDomainId"}}, "transit-gateway-policy-table": {"ec2:transitGatewayPolicyTableId": {"member": "TransitGatewayPolicyTableId"}}, "transit-gateway-route-table": {"ec2:transitGatewayRouteTableId": {"member": "TransitGatewayRouteTableId"}}, "transit-gateway-route-table-announcement": {"ec2:transitGatewayRouteTableAnnouncementId": {"member": "TransitGatewayRouteTableAnnouncementId"}}, "volume": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:KmsKeyId": {"member": "KmsKeyId"}, "ec2:VolumeID": {"member": "VolumeId"}, "ec2:VolumeInitializationRate": {"member": "VolumeInitializationRate"}, "ec2:VolumeType": {"member": "VolumeType"}}, "vpc": {"ec2:VpcID": {"member": "VpcId"}}, "vpc-peering-connection": {"ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}},
"unqualified": {"lambda": ["function"], "ssm": ["parameter"], "states": ["statemachine"]},
"mintedIds": {"events": ["api-destination", "connection"]},
@@ -42,6 +42,7 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -152,7 +153,7 @@ class IamConditionContextResolverTest {
resolver = new IamConditionContextResolver(
dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance,
crossAccountServiceInstance, iamServiceInstance,
lambdaWebServiceInstance, spellings(new ShapeNamingSpelling()),
lambdaWebServiceInstance, spellings(new ShapeNamingSpelling()), mock(Instance.class),
requestContext, new RegionResolver("us-east-1", "123456789012"), config,
null, serviceCatalog);
}
@@ -846,10 +847,64 @@ class IamConditionContextResolverTest {
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
spellings(), requestContext, new RegionResolver("us-east-1", "123456789012"), config, null,
spellings(), mock(Instance.class), requestContext, new RegionResolver("us-east-1", "123456789012"),
config, null,
serviceCatalog, Clock.fixed(now, ZoneOffset.UTC));
}
/** A resolver whose only finder of stored resources is {@code stored}. */
private IamConditionContextResolver resolverReading(StoredResourceArns stored) {
@SuppressWarnings("unchecked")
Instance<StoredResourceArns> instance = mock(Instance.class);
when(instance.iterator()).thenAnswer(invocation -> List.of(stored).iterator());
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
spellings(), instance, requestContext, new RegionResolver("us-east-1", "123456789012"), config,
null, serviceCatalog, Clock.systemUTC());
}
@Test
void resourceTagsAreTheGeneratedKeysOfTheArnsTypeValuedFromItsServicesStoredTags() {
String secret = "arn:aws:secretsmanager:eu-west-1:123456789012:secret:app-AbCdEf";
Map<String, String> held = new LinkedHashMap<>();
held.put("Environment", "prod");
held.put("environment", "dev");
IamConditionContextResolver reading = resolverReading(new StoredResourceArns() {
@Override
public String namespace() {
return "secretsmanager";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public Map<String, String> storedTags(String arn) {
return secret.equals(arn) ? held : Map.of();
}
});
Map<String, List<String>> tags = reading.resourceTags(secret);
assertEquals(2, tags.size());
assertEquals(List.of("prod", "dev"), tags.get("aws:ResourceTag/Environment"));
assertEquals(List.of("prod", "dev"), tags.get("secretsmanager:resourcetag/environment"));
assertNull(reading.resourceTags(secret.replace("AbCdEf", "ZyXwVu")));
assertNull(reading.resourceTags("*"));
// Events' types have resource-tag keys too, but no finder of its stored resources is registered here.
assertNull(reading.resourceTags("arn:aws:events:eu-west-1:123456789012:rule/nightly"));
Map<String, List<String>> context = new LinkedHashMap<>();
context.put("AWS:ResourceTag/environment", List.of("forged"));
context.put("aws:RequestTag/Owner", List.of("me"));
Map<String, List<String>> checked = IamConditionContextResolver.withResourceTags(context, tags);
assertEquals(List.of("prod", "dev"), checked.get("aws:ResourceTag/Environment"));
assertFalse(checked.containsKey("AWS:ResourceTag/environment"));
assertEquals(List.of("me"), checked.get("aws:RequestTag/Owner"));
assertSame(context, IamConditionContextResolver.withResourceTags(context, null));
}
@Test
void resolvesDynamoDbLeadingKeysForGetItem() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -99,6 +99,11 @@ class RequestResourceMembersTest {
void generatedResourceTagKeysValidateTheirPrefixesAndResourceTypes() throws Exception {
assertEquals(List.of("aws:ResourceTag/", "ec2:ResourceTag/"),
RequestResourceMembers.table().resourceTagKeys().get("ec2").get("instance"));
// Secrets Manager writes its key `secretsmanager:ResourceTag/tag-key`, SSM spells the word `resourceTag`.
assertEquals(List.of("aws:ResourceTag/", "secretsmanager:ResourceTag/"),
RequestResourceMembers.table().resourceTagKeys().get("secretsmanager").get("Secret"));
assertEquals(List.of("aws:ResourceTag/", "ssm:resourceTag/"),
RequestResourceMembers.table().resourceTagKeys().get("ssm").get("parameter"));
ObjectNode document = (ObjectNode) MAPPER.readTree("""
{"namespaces":{"example":["example"]},"arnFormats":{"example":{
"thing":"arn:${Partition}:example:${Region}:${Account}:thing/${ThingId}"}},
@@ -0,0 +1,121 @@
package io.floci.aws.core.common;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;
import software.amazon.awssdk.services.secretsmanager.model.Tag;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class SecretsManagerResourceTagsIntegrationTest {
private static final String ACCOUNT = "000000000000";
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@CsvSource({"eu-west-1,aws", "us-gov-west-1,aws", "cn-north-1,aws",
"eu-west-1,secretsmanager", "us-gov-west-1,secretsmanager", "cn-north-1,secretsmanager"})
void readsAndWritesUseCurrentStoredTagsForNamesAndArns(String region, String prefix) {
String name = "secret-tag-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth(ACCOUNT, "iam"), name);
try (SecretsManagerClient admin = AwsTestClients.create(SecretsManagerClient.builder(), ACCOUNT,
Region.of(region), endpoint);
SecretsManagerClient client = AwsTestClients.create(SecretsManagerClient.builder(),
credentials.accessKeyId(), credentials.secretAccessKey(), Region.of(region), endpoint)) {
String arn = admin.createSecret(r -> r.name(name).secretString("initial")
.tags(Tag.builder().key("Access").value("allowed").build())).arn();
try {
policy(name, """
{"Effect":"Allow","Action":["secretsmanager:GetSecretValue",
"secretsmanager:DescribeSecret","secretsmanager:PutSecretValue"],"Resource":"%s",
"Condition":{"StringEquals":{"%s:ResourceTag/Access":"allowed"}}}
""".formatted(arn, prefix));
for (String reference : new String[]{name, arn, arn.substring(0, arn.length() - 7)}) {
assertEquals("initial", client.getSecretValue(r -> r.secretId(reference)).secretString());
assertEquals(arn, client.describeSecret(r -> r.secretId(reference)).arn());
}
client.putSecretValue(r -> r.secretId(name).secretString("updated"));
admin.tagResource(r -> r.secretId(arn).tags(Tag.builder().key("Access").value("other").build()));
for (String reference : new String[]{name, arn, arn.substring(0, arn.length() - 7)}) {
denied(() -> client.getSecretValue(r -> r.secretId(reference)));
denied(() -> client.describeSecret(r -> r.secretId(reference)));
denied(() -> client.putSecretValue(r -> r.secretId(reference).secretString("must-not-write")));
}
assertEquals("updated", admin.getSecretValue(r -> r.secretId(arn)).secretString());
admin.untagResource(r -> r.secretId(arn).tagKeys("Access"));
denied(() -> client.getSecretValue(r -> r.secretId(name)));
admin.tagResource(r -> r.secretId(arn).tags(Tag.builder().key("Access").value("allowed").build()));
assertEquals("updated", client.getSecretValue(r -> r.secretId(name)).secretString());
policy(name, """
{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"%s"},
{"Effect":"Deny","Action":"secretsmanager:GetSecretValue","Resource":"%s",
"Condition":{"StringEquals":{"%s:ResourceTag/Access":"allowed"}}}
""".formatted(arn, arn, prefix));
denied(() -> client.getSecretValue(r -> r.secretId(arn)));
} finally {
admin.deleteSecret(r -> r.secretId(arn).forceDeleteWithoutRecovery(true));
}
}
}
@ParameterizedTest
@CsvSource({"aws,false", "aws,true", "secretsmanager,false", "secretsmanager,true"})
void caseVariantTagsCannotHideAnExplicitDeny(String prefix, boolean reverse) {
String name = "secret-tag-case-" + UUID.randomUUID();
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(),
auth(ACCOUNT, "iam"), name);
try (SecretsManagerClient admin = AwsTestClients.create(SecretsManagerClient.builder(), ACCOUNT,
Region.EU_WEST_1, endpoint);
SecretsManagerClient client = AwsTestClients.create(SecretsManagerClient.builder(),
credentials.accessKeyId(), credentials.secretAccessKey(), Region.EU_WEST_1, endpoint)) {
Tag dev = Tag.builder().key("environment").value("dev").build();
Tag prod = Tag.builder().key("Environment").value("prod").build();
String arn = admin.createSecret(r -> r.name(name).secretString("value")
.tags(reverse ? prod : dev, reverse ? dev : prod)).arn();
try {
policy(name, """
{"Effect":"Allow","Action":"secretsmanager:GetSecretValue","Resource":"%s"},
{"Effect":"Deny","Action":"secretsmanager:GetSecretValue","Resource":"%s",
"Condition":{"ForAnyValue:StringEquals":{"%s:ResourceTag/Environment":"prod"}}}
""".formatted(arn, arn, prefix));
denied(() -> client.getSecretValue(r -> r.secretId(name)));
denied(() -> client.getSecretValue(r -> r.secretId(arn)));
admin.untagResource(r -> r.secretId(arn).tagKeys("Environment"));
assertEquals("value", client.getSecretValue(r -> r.secretId(name)).secretString());
} finally {
admin.deleteSecret(r -> r.secretId(arn).forceDeleteWithoutRecovery(true));
}
}
}
private void policy(String user, String statements) {
EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(ACCOUNT, "iam"), user, "tags",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
}
private static void denied(Runnable call) {
SecretsManagerException error = assertThrows(SecretsManagerException.class, call::run);
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
}
}
@@ -154,7 +154,7 @@ class DynamoDbFacadeTest {
IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb,
mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), mock(Instance.class), mock(Instance.class),
requestContext,
mock(Instance.class), requestContext,
new RegionResolver(OTHER_REGION, "000000000000"),
mock(EmulatorConfig.class),
null, mock(io.floci.aws.core.common.ResolvedServiceCatalog.class));
@@ -42,6 +42,21 @@ class SecretsManagerServiceTest {
service = new SecretsManagerService(new InMemoryStorage<>(), 30);
}
@Test
void storedTagsUseExactIndexedArnWithoutScanningOrReadingValues() {
InMemoryStorage<String, Secret> storage = Mockito.spy(new InMemoryStorage<>());
SecretsManagerService indexed = new SecretsManagerService(storage, 30);
Secret secret = indexed.createSecret("path/name-ABCDEF", "value", null, null, null,
List.of(new Secret.Tag("Access", "allowed")), REGION);
Mockito.clearInvocations(storage);
assertEquals(Map.of("Access", "allowed"), indexed.storedTags(secret.getArn()));
assertNull(secret.getLastAccessedDate());
assertEquals(Map.of(), indexed.storedTags(secret.getArn().substring(0, secret.getArn().length() - 7)));
assertEquals(Map.of(), indexed.storedTags(secret.getArn() + "x"));
assertEquals(Map.of(), indexed.storedTags("not-an-arn"));
Mockito.verify(storage, Mockito.never()).scan(ArgumentMatchers.any());
}
@Test
void createSecret() {
Secret secret = service.createSecret("my-secret", "super-secret-value",
+20 -13
View File
@@ -102,9 +102,10 @@ and capitalization), and the id prefix botocore gives each type, in its document
example, i-0123456789abcdef0)") or its examples (`"GroupId": "sg-903004f8"`), distinguishes them. Each generated
`targets` entry preserves the request's order and duplicates, including a wildcard for each unsupported id; only
resolved ARNs use the corresponding target's condition context. Every other request of those namespaces is read by
the ordinary rules, its EC2 Query wire names (`ec2Query`) from botocore. `resourceTagKeys` gives every type of those
namespaces its Service Reference resource-tag condition keys, as their service keeps tags by resource id, and
`resourceKeys` the type's other condition keys that name a member of its botocore shape (`ec2:Vpc` a network
the ordinary rules, its EC2 Query wire names (`ec2Query`) from botocore. `resourceTagKeys` gives every type of the
namespaces read its Service Reference resource-tag condition keys (`aws:ResourceTag/`, `secretsmanager:ResourceTag/`),
which the condition resolver fills with the tags the type's service holds on the resource an ARN names, and, for those
id-list namespaces, `resourceKeys` the type's other condition keys that name a member of its botocore shape (`ec2:Vpc` a network
interface's `VpcId`), which its service answers from the resource it holds, as an ARN where the reference types the
key as one.
Beyond the members' names, botocore's shapes and documentation say what a member names, and the rule reads them:
@@ -455,6 +456,11 @@ ID_TARGETS = {"ec2": ("instance", "network-acl", "network-interface", "route-tab
# An ARN format's account given as `${AccountId}`, the account `${Account}` gives in every other format.
ACCOUNT_ID_SLOT_RE = re.compile(r"^(arn:[^:]*:[^:]*:[^:]*:)\$\{AccountId}:")
VARIABLE_RE = re.compile(r"\$\{(\w+)}")
# A resource-tag condition key the reference gives a type, named after the tag key it compares, which it writes as the
# variable `${TagKey}` or as `tag-key`, as the IAM User Guide writes `aws:ResourceTag/tag-key` ("There is one context
# key for each tag key-value pair"): Secrets Manager's `secretsmanager:ResourceTag/tag-key`. SSM spells the word
# `resourceTag`; condition key names are not case-sensitive.
RESOURCE_TAG_KEY_RE = re.compile(r"(?P<prefix>[a-z0-9-]+:(?i:ResourceTag)/)(?:\$\{TagKey}|tag-key)")
# A type's id with the example botocore documents it by: "the instance ID (for example, i-0123456789abcdef0)".
ID_EXAMPLE_RE = re.compile(r"\b([a-z][a-z ]*?) ID \(for example, ([a-z0-9]+-)[0-9a-f]{8,}\)")
# An id one of botocore's request or response examples gives a member: "GroupId": "sg-903004f8".
@@ -536,17 +542,18 @@ def checked_actions(documents: list[dict]) -> dict[str, dict]:
return found
def resource_tag_keys(documents: list[dict]) -> dict[str, dict[str, list[str]]]:
"""Stored-tag key prefixes for every resource type of the id-target namespaces, as the Service Reference gives each
type's resource-tag condition keys: their service keeps a resource's tags by its id, whatever its type."""
def resource_tag_keys(documents: list[dict], formats: dict[str, dict[str, str]]) -> dict[str, dict[str, list[str]]]:
"""Stored-tag key prefixes for every resource type of the namespaces read that has an ARN format (`formats`), as
the Service Reference gives each type's resource-tag condition keys: one key per tag the resource holds, named
after its tag key (`RESOURCE_TAG_KEY_RE`). A key naming one tag key of its own is not a prefix."""
result = {}
for document in documents:
namespace = document["Name"]
if namespace not in ID_TARGETS:
if namespace not in formats:
continue
types = {resource["Name"]: sorted(key.removesuffix("${TagKey}")
for key in resource.get("ConditionKeys", []) if key.endswith(":ResourceTag/${TagKey}"))
for resource in document.get("Resources", [])}
types = {resource["Name"]: sorted({match.group("prefix") for match in map(
RESOURCE_TAG_KEY_RE.fullmatch, resource.get("ConditionKeys", [])) if match})
for resource in document.get("Resources", []) if resource["Name"] in formats[namespace]}
types = {kind: keys for kind, keys in types.items() if keys}
if types:
result[namespace] = dict(sorted(types.items()))
@@ -2743,7 +2750,7 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) ->
if namespace not in NAMESPACES and namespace not in HAND_BUILT
and namespace not in NOT_COVERED),
"arnFormats": formats,
"resourceTagKeys": resource_tag_keys(documents),
"resourceTagKeys": resource_tag_keys(documents, formats),
"resourceKeys": resource_keys(documents, data, namespaces),
"unqualified": unqualified,
"mintedIds": minted,
@@ -2978,7 +2985,7 @@ def validate(document: dict) -> list[str]:
if not isinstance(tag_keys, dict) or any(
not isinstance(kinds, dict) or any(kind not in formats.get(namespace, {})
or not isinstance(keys, list) or not all(isinstance(key, str) for key in keys) or keys != sorted(set(keys))
or any(not isinstance(key, str) or not re.fullmatch(r"[a-z0-9-]+:ResourceTag/", key) for key in keys)
or any(not isinstance(key, str) or not re.fullmatch(r"[a-z0-9-]+:(?i:ResourceTag)/", key) for key in keys)
for kind, keys in kinds.items()) for namespace, kinds in tag_keys.items()):
problems.append("resourceTagKeys is not stored-tag prefixes for supported resource types")
resource_keys_document = document.get("resourceKeys", {})
@@ -3336,7 +3343,7 @@ def main(argv: list[str] | None = None) -> int:
print(f"error: could not read the Service Reference ({e})", file=sys.stderr)
return 2
untrue, added = verify_against(document, upstream, formats)
if document.get("resourceTagKeys", {}) != resource_tag_keys(documents):
if document.get("resourceTagKeys", {}) != resource_tag_keys(documents, formats):
untrue.append("resourceTagKeys differ from AWS Service Reference")
if document.get("resourceKeys", {}) != resource_keys(documents, resolve_botocore_data(args.botocore_data)[0],
document["namespaces"]):
+19 -5
View File
@@ -1443,16 +1443,30 @@ def test_instance_target_member_is_derived_from_the_arn_variable_not_the_action_
renamed_formats, {"ec2": renamed})["targets"]["member"] == "MachineIds[]"
def test_resource_tag_prefixes_cover_every_type_of_an_id_target_namespace_from_the_reference():
def test_resource_tag_prefixes_cover_every_type_with_a_format_of_the_namespaces_read_from_the_reference():
documents = [{"Name": "ec2", "Resources": [
{"Name": "instance", "ConditionKeys": ["vendor:ResourceTag/${TagKey}", "aws:RequestTag/${TagKey}",
"aws:ResourceTag/${TagKey}", "ec2:Region"]},
{"Name": "volume", "ConditionKeys": ["volume:ResourceTag/${TagKey}"]},
{"Name": "unformatted", "ConditionKeys": ["aws:ResourceTag/${TagKey}"]},
{"Name": "untaggable", "ConditionKeys": ["ec2:Region"]}]},
{"Name": "secretsmanager", "Resources": [{"Name": "Secret", "ConditionKeys": [
"aws:ResourceTag/${TagKey}", "secretsmanager:ResourceTag/tag-key", "secretsmanager:SecretPrimaryRegion"]}]},
{"Name": "ssm", "Resources": [{"Name": "parameter", "ConditionKeys": [
"aws:ResourceTag/${TagKey}", "ssm:resourceTag/${TagKey}", "ssm:resourceTag/tag-key",
"ssm:resourceTag/aws:ssmmessages:session-id"]}]},
{"Name": "other", "Resources": [{"Name": "thing", "ConditionKeys": ["aws:ResourceTag/${TagKey}"]}]}]
assert r.resource_tag_keys(documents) == {"ec2": {"instance": ["aws:ResourceTag/", "vendor:ResourceTag/"],
"volume": ["volume:ResourceTag/"]}}
assert r.resource_tag_keys([]) == {}
formats = {"ec2": {kind: f"arn:${{Partition}}:ec2:${{Region}}:${{Account}}:{kind}/${{Id}}"
for kind in ("instance", "volume", "untaggable")},
"secretsmanager": {"Secret": "arn:${Partition}:secretsmanager:${Region}:${Account}:secret:${SecretId}"},
"ssm": {"parameter": "arn:${Partition}:ssm:${Region}:${Account}:parameter/${ParameterNameWithoutLeadingSlash}"}}
# A key naming one tag key of its own (`aws:ssmmessages:session-id`) is not a prefix; a namespace not read, or a
# type without an ARN format, has none.
assert r.resource_tag_keys(documents, formats) == {
"ec2": {"instance": ["aws:ResourceTag/", "vendor:ResourceTag/"], "volume": ["volume:ResourceTag/"]},
"secretsmanager": {"Secret": ["aws:ResourceTag/", "secretsmanager:ResourceTag/"]},
"ssm": {"parameter": ["aws:ResourceTag/", "ssm:resourceTag/"]}}
assert r.resource_tag_keys([], formats) == {}
def test_resource_keys_are_the_reference_keys_a_member_of_the_types_shape_names(monkeypatch):
@@ -1988,7 +2002,7 @@ def test_vpc_operations_read_vpc_ids_and_stored_tag_keys():
assert r.entry_for("ec2:ModifyVpcAttribute", {"action": "ec2:ModifyVpcAttribute", "types": ["vpc"]},
formats, {"ec2": ec2})["resources"] == [{"type": "vpc", "fill": {"VpcId": "VpcId"}}]
assert r.resource_tag_keys([{"Name": "ec2", "Resources": [{"Name": "vpc", "ConditionKeys": [
"aws:ResourceTag/${TagKey}", "ec2:ResourceTag/${TagKey}", "ec2:Region"]}]}]) == {
"aws:ResourceTag/${TagKey}", "ec2:ResourceTag/${TagKey}", "ec2:Region"]}]}], {"ec2": formats}) == {
"ec2": {"vpc": ["aws:ResourceTag/", "ec2:ResourceTag/"]}}