mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): derive the AWS managed policy catalog per partition (#4742)
The bundled managed policy catalog is the commercial one, so arn:aws-cn:iam::aws:policy/AdministratorAccess did not resolve and a China deployment listed commercial ARNs. Every other partition's catalog is now derived from the bundled data on first use and cached per partition: every arn:aws: inside a document takes the partition, as AWS's SAM translator does for managed policy ARNs (arn_generator.py), and the region-bearing kms:ViaService hosts (s3.*.amazonaws.com) take the partition's DNS suffix. Bare service principals and service-linked role paths are universal (#4633) and are left alone, as is the ::aws:policy/ owner slot. IamService resolves a managed policy under the partition its ARN names, so a China ARN resolves under any signing scope, and ListPolicies lists the catalog of the caller's partition. Partition literal baseline 4 -> 3. Part of #4272
This commit is contained in:
1 parent
5aad012e78
commit
99c1c4129a
10 files changed
+366
-48
No files matched your search
@@ -4,6 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartition;
|
||||
import io.github.hectorvent.floci.core.common.AwsPartitions;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
@@ -15,6 +18,8 @@ import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -42,12 +47,35 @@ import java.util.regex.Pattern;
|
||||
* managed policy's history down to five versions. A policy missing from the versions file
|
||||
* keeps the {@code v1} default so a partial refresh degrades to the old behaviour instead of
|
||||
* dropping the policy.
|
||||
*
|
||||
* <p>The bundled data is the commercial partition's. Every other partition's catalog is
|
||||
* derived from it on first use ({@link #forPartition}): the ARN prefix and every
|
||||
* {@code arn:aws:} inside a document take the partition ({@code arn:aws-cn:iam::aws:policy/...},
|
||||
* which is what AWS's own SAM translator does, {@code samtranslator/translator/arn_generator.py}),
|
||||
* and the region-bearing hostnames a {@code kms:ViaService} condition names
|
||||
* ({@code s3.*.amazonaws.com}) take the partition's DNS suffix. Bare service principals
|
||||
* ({@code ec2.amazonaws.com}) and service-linked role paths are the same in every partition and
|
||||
* are left alone, as is the {@code ::aws:policy/} owner slot. Whether AWS's China or GovCloud
|
||||
* documents differ in content beyond that is not known; see the open questions in
|
||||
* {@code docs/configuration/partitions.md}.
|
||||
*/
|
||||
final class AwsManagedPolicies {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AwsManagedPolicies.class);
|
||||
|
||||
static final String ARN_PREFIX = "arn:aws:iam::aws:policy";
|
||||
private static final String COMMERCIAL_PARTITION = "aws";
|
||||
/** {@code arn:<partition>:iam::aws:policy/}, the owner slot literally {@code aws} in every partition. */
|
||||
private static final Pattern MANAGED_POLICY_ARN = Pattern.compile(
|
||||
"^arn:(" + AwsArnUtils.PARTITION_REGEX + "):iam::aws:policy/");
|
||||
/** Every commercial ARN inside a document; the whole prefix up to and including the second colon. */
|
||||
private static final Pattern COMMERCIAL_ARN = Pattern.compile("arn:aws:"); // partition-literal: the commercial prefix this rewrites away
|
||||
/**
|
||||
* A hostname whose label before the commercial suffix is a region or the {@code *} that
|
||||
* stands for one ({@code s3.*.amazonaws.com}, {@code s3.us-east-1.amazonaws.com}); a bare
|
||||
* principal has no such label and never matches.
|
||||
*/
|
||||
private static final Pattern REGION_BEARING_HOST = Pattern.compile(
|
||||
"\\.(\\*|[a-z]{2,4}-[a-z-]+-\\d)\\.amazonaws\\.com(?![.\\w-])"); // partition-literal: the commercial suffix this rewrites away
|
||||
|
||||
private static final String CATALOG_RESOURCE_NAME = "iam/managed-policies.yaml";
|
||||
private static final String DOCUMENTS_RESOURCE_NAME = "iam/managed-policy-documents.json";
|
||||
@@ -59,24 +87,73 @@ final class AwsManagedPolicies {
|
||||
/**
|
||||
* One resolvable AWS managed policy.
|
||||
*
|
||||
* @param partition the partition whose catalog holds it, which its ARN names
|
||||
* @param document the document of the policy's current default version
|
||||
* @param defaultVersionId the version id AWS reports for that document, e.g. {@code v3}
|
||||
* @param createDate when AWS first published the policy, or {@code null} if unknown
|
||||
* @param updateDate when AWS published the current default version, or {@code null}
|
||||
* if unknown
|
||||
*/
|
||||
record ManagedPolicyDef(String name, String path, String description, String document,
|
||||
record ManagedPolicyDef(String partition, String name, String path, String description, String document,
|
||||
String defaultVersionId, Instant createDate, Instant updateDate) {
|
||||
String arn() {
|
||||
return ARN_PREFIX + path + name;
|
||||
return arnPrefix(partition) + path + name;
|
||||
}
|
||||
}
|
||||
|
||||
/** The commercial catalog, byte-identical to the bundled data. */
|
||||
static final List<ManagedPolicyDef> POLICIES = load();
|
||||
|
||||
private static final Map<String, List<ManagedPolicyDef>> BY_PARTITION = new ConcurrentHashMap<>();
|
||||
|
||||
private AwsManagedPolicies() {
|
||||
}
|
||||
|
||||
/** {@code arn:<partition>:iam::aws:policy}, without the trailing slash of the path. */
|
||||
static String arnPrefix(String partition) {
|
||||
return "arn:" + partition + ":iam::aws:policy";
|
||||
}
|
||||
|
||||
/** True for an AWS managed policy ARN in any partition ({@code arn:aws-cn:iam::aws:policy/...}). */
|
||||
static boolean isManagedPolicyArn(String arn) {
|
||||
return arn != null && MANAGED_POLICY_ARN.matcher(arn).find();
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog of {@code partition}: the bundled commercial data for {@code aws}, a derived
|
||||
* view otherwise, built once per partition. Bounded by the published partitions.
|
||||
*
|
||||
* @throws IllegalArgumentException when {@code partition} is not a published partition id
|
||||
*/
|
||||
static List<ManagedPolicyDef> forPartition(String partition) {
|
||||
if (COMMERCIAL_PARTITION.equals(partition)) {
|
||||
return POLICIES;
|
||||
}
|
||||
AwsPartition target = AwsPartitions.find(partition).orElseThrow(() ->
|
||||
new IllegalArgumentException("Not a published AWS partition: " + partition));
|
||||
return BY_PARTITION.computeIfAbsent(target.id(), id -> derive(target));
|
||||
}
|
||||
|
||||
private static List<ManagedPolicyDef> derive(AwsPartition partition) {
|
||||
long started = System.nanoTime();
|
||||
String arnPrefix = "arn:" + partition.id() + ":";
|
||||
List<ManagedPolicyDef> derived = new ArrayList<>(POLICIES.size());
|
||||
for (ManagedPolicyDef def : POLICIES) {
|
||||
derived.add(new ManagedPolicyDef(partition.id(), def.name(), def.path(), def.description(),
|
||||
rewriteDocument(def.document(), arnPrefix, partition.dnsSuffix()),
|
||||
def.defaultVersionId(), def.createDate(), def.updateDate()));
|
||||
}
|
||||
LOG.debugv("Derived the {0} managed policy catalog ({1} policies) in {2} ms",
|
||||
partition.id(), derived.size(), (System.nanoTime() - started) / 1_000_000);
|
||||
return List.copyOf(derived);
|
||||
}
|
||||
|
||||
static String rewriteDocument(String document, String arnPrefix, String dnsSuffix) {
|
||||
String rewritten = COMMERCIAL_ARN.matcher(document).replaceAll(Matcher.quoteReplacement(arnPrefix));
|
||||
Matcher hosts = REGION_BEARING_HOST.matcher(rewritten);
|
||||
return hosts.replaceAll(match -> Matcher.quoteReplacement("." + match.group(1) + "." + dnsSuffix));
|
||||
}
|
||||
|
||||
private static List<ManagedPolicyDef> load() {
|
||||
try (InputStream in = Thread.currentThread().getContextClassLoader()
|
||||
.getResourceAsStream(CATALOG_RESOURCE_NAME)) {
|
||||
@@ -100,7 +177,8 @@ final class AwsManagedPolicies {
|
||||
continue;
|
||||
}
|
||||
VersionEntry version = versions.get(entry.name);
|
||||
defs.add(new ManagedPolicyDef(entry.name, entry.path, entry.description, document.toString(),
|
||||
defs.add(new ManagedPolicyDef(COMMERCIAL_PARTITION, entry.name, entry.path, entry.description,
|
||||
document.toString(),
|
||||
defaultVersionId(entry.name, version),
|
||||
parseDate(entry.name, "createDate", version == null ? null : version.createDate),
|
||||
parseDate(entry.name, "updateDate", version == null ? null : version.updateDate)));
|
||||
|
||||
@@ -43,6 +43,7 @@ import java.time.format.DateTimeFormatter;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -176,11 +177,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
private final Object resourceNameLock = new Object();
|
||||
|
||||
/**
|
||||
* AWS-managed policies (arn:aws:iam::aws:policy/...), keyed by ARN. These are global —
|
||||
* not owned by any account — so they live here rather than in the account-partitioned
|
||||
* {@link #policies} store, and {@link #getPolicy} resolves them for any caller.
|
||||
* AWS-managed policies ({@code arn:<partition>:iam::aws:policy/...}), keyed by ARN, one map
|
||||
* per partition and built on first use. These are global: not owned by any account, so they
|
||||
* live here rather than in the account-partitioned {@link #policies} store, and
|
||||
* {@link #getPolicy} resolves them for any caller. The partition comes from the ARN a
|
||||
* caller names, so a China ARN resolves under any signing scope and lists in China scope.
|
||||
*/
|
||||
private final Map<String, IamPolicy> awsManagedPolicies = buildAwsManagedPolicies();
|
||||
private final Map<String, Map<String, IamPolicy>> awsManagedPoliciesByPartition = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) {
|
||||
@@ -317,9 +320,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
seedConfiguredAccountAlias();
|
||||
}
|
||||
|
||||
private static Map<String, IamPolicy> buildAwsManagedPolicies() {
|
||||
private Map<String, IamPolicy> awsManagedPolicies(String partition) {
|
||||
return awsManagedPoliciesByPartition.computeIfAbsent(partition, IamService::buildAwsManagedPolicies);
|
||||
}
|
||||
|
||||
/** The managed policy catalog of the partition an ARN names, or empty for an unpublished one. */
|
||||
private Map<String, IamPolicy> awsManagedPoliciesFor(String managedPolicyArn) {
|
||||
try {
|
||||
return awsManagedPolicies(AwsArnUtils.parse(managedPolicyArn).partition());
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// Only reached for an ARN that already matched the managed-policy pattern but names a
|
||||
// partition AWS does not publish: no catalog exists there, so no policy resolves.
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, IamPolicy> buildAwsManagedPolicies(String partition) {
|
||||
Map<String, IamPolicy> catalog = new LinkedHashMap<>();
|
||||
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) {
|
||||
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.forPartition(partition)) {
|
||||
String arn = def.arn();
|
||||
// The bundled document is the policy's current default version, served under the
|
||||
// version id AWS actually reports for it (v3 for AmazonS3ReadOnlyAccess, v1 for
|
||||
@@ -348,7 +366,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* megabyte of persisted state and several seconds of startup for nothing.
|
||||
*/
|
||||
void seedAwsManagedPolicies() {
|
||||
LOG.debugv("AWS managed policy catalog available: {0} policies", awsManagedPolicies.size());
|
||||
LOG.debugv("AWS managed policy catalog available: {0} policies",
|
||||
awsManagedPolicies(regionResolver.getDefaultPartition()).size());
|
||||
}
|
||||
|
||||
private void seedConfiguredAccountAlias() {
|
||||
@@ -369,7 +388,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private void seedDefaultDeployerPrincipal() {
|
||||
String adminPolicyArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";
|
||||
String adminPolicyArn = AwsManagedPolicies.arnPrefix(regionResolver.getDefaultPartition())
|
||||
+ "/AdministratorAccess";
|
||||
IamUser user = users.get(DEFAULT_DEPLOYER_USER)
|
||||
.orElseGet(() -> {
|
||||
String userId = "AIDA" + randomId(16);
|
||||
@@ -921,7 +941,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
String arn = iamArn("policy", normalizedPath, policyName);
|
||||
boolean nameTaken = resourcesInCurrentAccount(policies)
|
||||
.filter(existing -> existing.getArn() == null
|
||||
|| !existing.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX))
|
||||
|| !AwsManagedPolicies.isManagedPolicyArn(existing.getArn()))
|
||||
.map(IamPolicy::getPolicyName)
|
||||
.anyMatch(existingName -> existingName != null && existingName.equalsIgnoreCase(policyName));
|
||||
if (nameTaken) {
|
||||
@@ -939,7 +959,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
public IamPolicy getPolicy(String policyArn) {
|
||||
IamPolicy policy = requirePolicy(policyArn);
|
||||
if (policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(policyArn)) {
|
||||
return managedPolicySnapshot(policy, managedPolicyAttachmentCount(policyArn));
|
||||
}
|
||||
return policy;
|
||||
@@ -959,9 +979,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* that account's {@link #policies} partition and would otherwise be silently dropped.
|
||||
*/
|
||||
private Optional<IamPolicy> resolvePolicy(String arn) {
|
||||
if (arn != null && arn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(arn)) {
|
||||
// Authorization and ListAttached* need policy documents or names, not attachment counts.
|
||||
return Optional.ofNullable(awsManagedPolicies.get(arn));
|
||||
return Optional.ofNullable(awsManagedPoliciesFor(arn).get(arn));
|
||||
}
|
||||
return policies.get(arn);
|
||||
}
|
||||
@@ -980,7 +1000,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
private void tallyManagedPolicyAttachments(List<String> policyArns, Map<String, Integer> counts) {
|
||||
for (String policyArn : policyArns) {
|
||||
if (policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(policyArn)) {
|
||||
counts.merge(policyArn, 1, Integer::sum);
|
||||
}
|
||||
}
|
||||
@@ -1012,7 +1032,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private void incrementCustomerManagedPolicyAttachmentCount(IamPolicy policy) {
|
||||
if (policy.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(policy.getArn())) {
|
||||
return;
|
||||
}
|
||||
policy.setAttachmentCount(policy.getAttachmentCount() + 1);
|
||||
@@ -1020,7 +1040,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private void decrementCustomerManagedPolicyAttachmentCount(String policyArn) {
|
||||
if (policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(policyArn)) {
|
||||
return;
|
||||
}
|
||||
policies.get(policyArn).ifPresent(policy -> {
|
||||
@@ -1030,7 +1050,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
}
|
||||
|
||||
private void rejectIfAwsManaged(String policyArn) {
|
||||
if (policyArn != null && policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(policyArn)) {
|
||||
throw new AwsException("AccessDenied",
|
||||
"Cannot modify or delete AWS managed policy: " + policyArn, 403);
|
||||
}
|
||||
@@ -1089,7 +1109,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
// AWS-managed ARNs mirrored into the default account at seed time — those are
|
||||
// served from the global catalog below so the default account does not see them twice.
|
||||
policies.scan(k -> true).stream()
|
||||
.filter(p -> !p.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX))
|
||||
.filter(p -> !AwsManagedPolicies.isManagedPolicyArn(p.getArn()))
|
||||
.filter(p -> p.getPath().startsWith(prefix))
|
||||
.forEach(result::add);
|
||||
}
|
||||
@@ -1098,7 +1118,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
// every caller sees the full set regardless of the request account — mirroring the
|
||||
// getPolicy fix, and keeping the ListPolicies and GetPolicy read paths consistent.
|
||||
Map<String, Integer> attachmentCounts = managedPolicyAttachmentCounts();
|
||||
awsManagedPolicies.values().stream()
|
||||
awsManagedPolicies(regionResolver.getPartition()).values().stream()
|
||||
.filter(p -> p.getPath().startsWith(prefix))
|
||||
.map(p -> managedPolicySnapshot(p, attachmentCounts.getOrDefault(p.getArn(), 0)))
|
||||
.forEach(result::add);
|
||||
@@ -1119,7 +1139,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
long localPolicyCount = 0;
|
||||
long policyVersionsInUse = 0;
|
||||
for (IamPolicy policy : policies.scan(k -> true)) {
|
||||
if (policy.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(policy.getArn())) {
|
||||
continue;
|
||||
}
|
||||
localPolicyCount++;
|
||||
@@ -2996,7 +3016,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
Set<String> referencedAwsManagedArns) {
|
||||
for (String arn : attachedPolicyArns) {
|
||||
attachmentCounts.merge(arn, 1, Integer::sum);
|
||||
if (arn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(arn)) {
|
||||
referencedAwsManagedArns.add(arn);
|
||||
}
|
||||
}
|
||||
@@ -3008,7 +3028,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return;
|
||||
}
|
||||
boundaryUsageCounts.merge(permissionsBoundaryArn, 1, Integer::sum);
|
||||
if (permissionsBoundaryArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) {
|
||||
if (AwsManagedPolicies.isManagedPolicyArn(permissionsBoundaryArn)) {
|
||||
referencedAwsManagedArns.add(permissionsBoundaryArn);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user