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

@@ -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();