fix(iam): report the real default version of AWS-managed policies (#3275)

Signed-off-by: Matheus André <matheusandr2@gmail.com>
This commit is contained in:
Matheus André authored and GitHub committed 2026-09-09 22:55:17 -05:00
1 parent 460aa0718e
commit abfa8e949e
10 files changed
+8082 -21

No files matched your search

+17 -1
View File
@@ -274,7 +274,23 @@ Floci seeds a catalog of commonly-used AWS managed policies at startup. These ar
**Other execution roles**
`AmazonS3ObjectLambdaExecutionRolePolicy` · `CloudWatchLambdaInsightsExecutionRolePolicy` · `CloudWatchLambdaApplicationSignalsExecutionRolePolicy` · `AWSConfigRulesExecutionRole` · `AWSMSKReplicatorExecutionRole` · `AWS-SSM-DiagnosisAutomation-ExecutionRolePolicy` · `AWS-SSM-RemediationAutomation-ExecutionRolePolicy` · `AmazonSageMakerGeospatialExecutionRole` · `AmazonSageMakerCanvasEMRServerlessExecutionRolePolicy` · `SageMakerStudioBedrockFunctionExecutionRolePolicy` · `SageMakerStudioDomainExecutionRolePolicy` · `SageMakerStudioQueryExecutionRolePolicy` · `AmazonDataZoneDomainExecutionRolePolicy` · `AmazonBedrockAgentCoreMemoryBedrockModelInferenceExecutionRolePolicy` · `AWSPartnerCentralSellingResourceSnapshotJobExecutionRolePolicy`
All seeded policies use a permissive wildcard document since Floci does not enforce IAM policy evaluation by default.
Every catalog entry carries the real policy document of its current default version, generated from the public [iam-dataset](https://github.com/iann0036/iam-dataset), so `GetPolicyVersion` returns the same statements a real account would and enforcement mode evaluates them faithfully.
### Version numbers
AWS revises its managed policies in place, so their default version is rarely `v1`: `AmazonS3ReadOnlyAccess` is on `v3`, `ReadOnlyAccess` far beyond that, while `AdministratorAccess` has never been revised. Floci reports the version id AWS publishes for each policy, the date the policy was first created as `CreateDate`, and the date of its current default version as `UpdateDate`:
```bash
aws --endpoint-url http://localhost:4566 iam get-policy \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# -> DefaultVersionId: "v3", CreateDate: 2015-02-06T18:40:00Z, UpdateDate: 2023-08-10T21:31:39Z
aws --endpoint-url http://localhost:4566 iam list-policy-versions \
--policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# -> a single entry, v3, IsDefaultVersion: true
```
Only the default version's document is bundled. Requesting a superseded version (`v1` or `v2` of `AmazonS3ReadOnlyAccess`) returns `NoSuchEntity`, the same answer AWS gives once it has pruned a managed policy's history, and `ListPolicyVersions` lists only the default. AWS managed policies remain read-only: `CreatePolicyVersion`, `SetDefaultPolicyVersion` and `DeletePolicyVersion` are rejected with `AccessDenied`.
## Optional Local Deployer Principal
@@ -10,15 +10,18 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Catalog of AWS managed policies, loaded from {@code iam/managed-policies.yaml}.
*
* <p>Floci resolves {@code arn:aws:iam::aws:policy/*} ARNs against this catalog, so an ARN
* that is absent returns {@code NoSuchEntity} — the same as real AWS. Carrying the full
* that is absent returns {@code NoSuchEntity}, the same as real AWS. Carrying the full
* published list is what keeps that faithful in both directions: policies AWS actually
* publishes attach cleanly, while typos and invented names are still rejected. A curated
* subset would reject valid configurations; resolving every well-formed ARN would accept
@@ -27,6 +30,18 @@ import java.util.Map;
* <p>Policy documents are loaded from the versioned data generated from the public AWS managed
* policy dataset. Entries without a document are omitted so an unavailable policy fails closed
* through the normal {@code NoSuchEntity} path rather than receiving broader permissions.
*
* <p>Each document is the policy's <em>current default version</em>, and the version id it is
* served under comes from {@code iam/managed-policy-versions.json} rather than being assumed to
* be {@code v1}: AWS revises its managed policies in place, so {@code AmazonS3ReadOnlyAccess}
* is on {@code v3} while {@code AdministratorAccess} is still {@code v1}. That file also carries
* the policy's own creation date and the date of its current version, which back the
* {@code CreateDate} and {@code UpdateDate} of {@code GetPolicy} respectively. Only the default
* version's document is bundled, since the dataset does not carry superseded documents, so an
* older version id is reported as {@code NoSuchEntity}, as AWS itself does once it prunes a
* 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.
*/
final class AwsManagedPolicies {
@@ -36,8 +51,22 @@ final class AwsManagedPolicies {
private static final String CATALOG_RESOURCE_NAME = "iam/managed-policies.yaml";
private static final String DOCUMENTS_RESOURCE_NAME = "iam/managed-policy-documents.json";
private static final String VERSIONS_RESOURCE_NAME = "iam/managed-policy-versions.json";
record ManagedPolicyDef(String name, String path, String description, String document) {
private static final String FALLBACK_VERSION_ID = "v1";
private static final Pattern VERSION_ID = Pattern.compile("v[1-9][0-9]*");
/**
* One resolvable AWS managed policy.
*
* @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,
String defaultVersionId, Instant createDate, Instant updateDate) {
String arn() {
return ARN_PREFIX + path + name;
}
@@ -58,6 +87,7 @@ final class AwsManagedPolicies {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Catalog catalog = mapper.readValue(in, Catalog.class);
Map<String, JsonNode> documents = loadDocuments();
Map<String, VersionEntry> versions = loadVersions();
List<ManagedPolicyDef> defs = new ArrayList<>();
for (CatalogEntry entry : catalog.policies == null ? List.<CatalogEntry>of() : catalog.policies) {
if (entry.name == null || entry.name.isBlank() || entry.path == null || entry.path.isBlank()) {
@@ -69,10 +99,14 @@ final class AwsManagedPolicies {
entry.name);
continue;
}
defs.add(new ManagedPolicyDef(entry.name, entry.path, entry.description, document.toString()));
VersionEntry version = versions.get(entry.name);
defs.add(new ManagedPolicyDef(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)));
}
LOG.debugv("Loaded {0} AWS managed policies from {1} and {2}",
defs.size(), CATALOG_RESOURCE_NAME, DOCUMENTS_RESOURCE_NAME);
LOG.debugv("Loaded {0} AWS managed policies from {1}, {2} and {3}",
defs.size(), CATALOG_RESOURCE_NAME, DOCUMENTS_RESOURCE_NAME, VERSIONS_RESOURCE_NAME);
return List.copyOf(defs);
} catch (IOException e) {
throw new UncheckedIOException(
@@ -80,6 +114,32 @@ final class AwsManagedPolicies {
}
}
private static String defaultVersionId(String name, VersionEntry version) {
if (version == null || version.defaultVersionId == null || version.defaultVersionId.isBlank()) {
LOG.debugv("No AWS managed policy version recorded for {0}; reporting it as {1}",
name, FALLBACK_VERSION_ID);
return FALLBACK_VERSION_ID;
}
if (!VERSION_ID.matcher(version.defaultVersionId).matches()) {
LOG.warnv("Ignoring malformed AWS managed policy version {0} for {1}; reporting it as {2}",
version.defaultVersionId, name, FALLBACK_VERSION_ID);
return FALLBACK_VERSION_ID;
}
return version.defaultVersionId;
}
private static Instant parseDate(String name, String field, String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Instant.parse(value);
} catch (DateTimeParseException e) {
LOG.warnv("Ignoring malformed AWS managed policy {0} {1} for {2}", field, value, name);
return null;
}
}
private static Map<String, JsonNode> loadDocuments() throws IOException {
try (InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(DOCUMENTS_RESOURCE_NAME)) {
@@ -93,6 +153,19 @@ final class AwsManagedPolicies {
}
}
private static Map<String, VersionEntry> loadVersions() throws IOException {
try (InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(VERSIONS_RESOURCE_NAME)) {
if (in == null) {
throw new IllegalStateException(
"AWS managed policy versions not found on the classpath: " + VERSIONS_RESOURCE_NAME);
}
ObjectMapper jsonMapper = new ObjectMapper();
return jsonMapper.readValue(in, jsonMapper.getTypeFactory()
.constructMapType(Map.class, String.class, VersionEntry.class));
}
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
static final class Catalog {
@@ -106,4 +179,15 @@ final class AwsManagedPolicies {
public String path;
public String description;
}
/** The version metadata AWS publishes for one policy. */
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
static final class VersionEntry {
public String defaultVersionId;
/** ISO-8601 instant at which AWS created the policy. */
public String createDate;
/** ISO-8601 instant at which AWS created the current default version. */
public String updateDate;
}
}
@@ -276,8 +276,17 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Map<String, IamPolicy> catalog = new LinkedHashMap<>();
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) {
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
// AdministratorAccess) so GetPolicy/ListPolicyVersions match a real account.
// Superseded versions are not bundled, so they resolve to NoSuchEntity.
Instant now = Instant.now();
Instant updateDate = def.updateDate() != null ? def.updateDate() : now;
Instant createDate = def.createDate() != null ? def.createDate() : updateDate;
PolicyVersion defaultVersion = new PolicyVersion(
def.defaultVersionId(), def.document(), true, updateDate);
catalog.put(arn, new IamPolicy("ANPA" + randomId(16), def.name(), def.path(), arn,
def.description(), def.document()));
def.description(), defaultVersion, createDate, updateDate));
}
return catalog;
}
@@ -40,16 +40,36 @@ public class IamPolicy {
public IamPolicy(String policyId, String policyName, String path, String arn,
String description, String document) {
this(policyId, policyName, path, arn, description, new PolicyVersion("v1", document, true));
}
private IamPolicy(String policyId, String policyName, String path, String arn,
String description, PolicyVersion v1) {
this(policyId, policyName, path, arn, description, v1, v1.getCreateDate(), v1.getCreateDate());
}
/**
* Creates a policy whose single stored version is {@code defaultVersion}, which need not
* be {@code v1}. AWS-managed policies are bundled at whatever version AWS has revised them
* to (for example {@code v3}), with only that version's document available, so the version
* counter starts just past it. {@code createDate} is when the policy itself was first
* published and {@code updateDate} when its current default version was, the two dates
* {@code GetPolicy} reports separately.
*/
public IamPolicy(String policyId, String policyName, String path, String arn,
String description, PolicyVersion defaultVersion,
Instant createDate, Instant updateDate) {
this.policyId = policyId;
this.policyName = policyName;
this.path = path;
this.arn = arn;
this.description = description;
this.createDate = Instant.now();
this.updateDate = Instant.now();
PolicyVersion v1 = new PolicyVersion("v1", document, true);
this.versions.put("v1", v1);
this.nextVersionNumber = 2;
this.createDate = createDate;
this.updateDate = updateDate;
defaultVersion.setDefaultVersion(true);
this.defaultVersionId = defaultVersion.getVersionId();
this.versions.put(defaultVersion.getVersionId(), defaultVersion);
this.nextVersionNumber = Integer.parseInt(defaultVersion.getVersionId().substring(1)) + 1;
}
public String getDefaultDocument() {
@@ -17,10 +17,14 @@ public class PolicyVersion {
public PolicyVersion() {}
public PolicyVersion(String versionId, String document, boolean defaultVersion) {
this(versionId, document, defaultVersion, Instant.now());
}
public PolicyVersion(String versionId, String document, boolean defaultVersion, Instant createDate) {
this.versionId = versionId;
this.document = document;
this.defaultVersion = defaultVersion;
this.createDate = Instant.now();
this.createDate = createDate;
}
public String getVersionId() { return versionId; }
+2 -1
View File
@@ -38,7 +38,8 @@ quarkus:
resources:
# The Pricing service reads its bundled snapshot, EC2 reads its image
# catalog (ec2/image-catalog.yaml), IAM reads its AWS managed-policy
# catalog (iam/managed-policies.yaml and iam/managed-policy-documents.json), AppSync's GraphQL parser reads its
# catalog (iam/managed-policies.yaml, iam/managed-policy-documents.json and
# iam/managed-policy-versions.json), AppSync's GraphQL parser reads its
# message bundles, and API Gateway's Velocity engine reads its default
# properties at runtime via
# ClassLoader#getResourceAsStream. Quarkus's static resource analysis
@@ -8,6 +8,17 @@
# Policy documents are stored in iam/managed-policy-documents.json, keyed by policy name.
# The documents are generated from the public AWS managed policy dataset cited below.
#
# Each document is the policy's current default version. The version id AWS reports for it
# (e.g. v3 for AmazonS3ReadOnlyAccess) is stored in iam/managed-policy-versions.json, also
# keyed by policy name, together with the policy's creation date (createDate) and the date
# of its current default version (updateDate), the two dates GetPolicy reports. The version
# id and updateDate come from the same dataset (the "version" and "updatedate" fields of
# aws/managed_policies.json); createDate comes from the "Creation time" published on each
# policy's page of the AWS managed policy reference,
# https://docs.aws.amazon.com/aws-managed-policy/latest/reference/, which is minute-precise,
# and falls back to the dataset's date for policies that no longer have a page. Only the
# default version's document is bundled, so superseded version ids resolve to NoSuchEntity.
#
# Names and paths derive from the public AWS managed policy list, via
# https://github.com/iann0036/iam-dataset (MIT). To refresh against a real account:
# aws iam list-policies --scope AWS
File diff suppressed because it is too large. Load diff
@@ -4,13 +4,19 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -19,7 +25,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
* subset, so that attaching a real policy succeeds and attaching an invented one still
* fails the way it does on AWS.
*
* <p>A subset produced false negatives — {@code AttachRolePolicy} returned
* <p>A subset produced false negatives: {@code AttachRolePolicy} returned
* {@code NoSuchEntity} for policies AWS genuinely publishes, breaking valid Terraform and
* CloudFormation configurations. Resolving every well-formed ARN instead would produce
* false positives, silently accepting typos that real AWS rejects and defeating stack
@@ -97,6 +103,77 @@ class IamManagedPolicyCatalogTest {
assertDoesNotThrow(() -> iamService.getPolicy("arn:aws:iam::aws:policy/AWSLambdaFullAccess"));
}
/**
* AWS revises managed policies in place, so their default version reflects that history
* rather than being {@code v1} for everything: {@code AmazonS3ReadOnlyAccess} is on
* {@code v3} (last revised August 2023) while {@code AdministratorAccess} genuinely never
* left {@code v1}. Reporting {@code v1} across the board only matched real AWS by accident.
*/
@Test
void defaultVersionReflectsAwsRevisionHistory() {
IamPolicy s3ReadOnly = iamService.getPolicy("arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess");
IamPolicy administrator = iamService.getPolicy("arn:aws:iam::aws:policy/AdministratorAccess");
assertEquals("v3", s3ReadOnly.getDefaultVersionId());
// A revised policy keeps its original creation date; only UpdateDate moves with v3.
assertEquals(Instant.parse("2015-02-06T18:40:00Z"), s3ReadOnly.getCreateDate());
assertEquals(Instant.parse("2023-08-10T21:31:39Z"), s3ReadOnly.getUpdateDate());
assertEquals("v1", administrator.getDefaultVersionId());
assertEquals(Instant.parse("2015-02-06T18:39:46Z"), administrator.getCreateDate());
assertEquals(administrator.getCreateDate(), administrator.getUpdateDate());
}
@Test
void listedVersionsCarryTheDefaultVersionIdAndItsDocument() {
String arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess";
IamPolicy policy = iamService.getPolicy(arn);
List<PolicyVersion> versions = iamService.listPolicyVersions(arn);
assertEquals(1, versions.size(), "only the default version's document is bundled");
PolicyVersion listed = versions.get(0);
assertEquals("v3", listed.getVersionId());
assertTrue(listed.isDefaultVersion());
assertEquals(policy.getDefaultDocument(), listed.getDocument());
assertEquals(policy.getUpdateDate(), listed.getCreateDate());
PolicyVersion fetched = iamService.getPolicyVersion(arn, "v3");
assertEquals(listed.getDocument(), fetched.getDocument());
assertTrue(fetched.isDefaultVersion());
}
/**
* The dataset only carries each policy's current document, so a superseded version cannot
* be served. Answering {@code NoSuchEntity} matches what AWS returns for a version it has
* pruned, and is preferable to serving the current document under an old id.
*/
@Test
void supersededVersionOfARevisedPolicyIsNotServedUnderTheWrongId() {
AwsException e = assertThrows(AwsException.class, () -> iamService.getPolicyVersion(
"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess", "v1"));
assertEquals("NoSuchEntity", e.getErrorCode());
assertEquals(404, e.getHttpStatus());
}
@Test
void everyCatalogEntryHasAWellFormedVersionIdAndDates() {
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) {
assertTrue(def.defaultVersionId().matches("v[1-9][0-9]*"),
def.name() + " has version id " + def.defaultVersionId());
assertNotNull(def.updateDate(), def.name() + " has no version date");
if (def.createDate() != null) {
assertFalse(def.createDate().isAfter(def.updateDate()),
def.name() + " was created after its current version");
}
}
for (IamPolicy policy : iamService.listPolicies("AWS", null)) {
assertFalse(policy.getCreateDate().isAfter(policy.getUpdateDate()),
policy.getPolicyName() + " reports CreateDate after UpdateDate");
}
assertTrue(AwsManagedPolicies.POLICIES.stream().anyMatch(p -> !"v1".equals(p.defaultVersionId())),
"the catalog should carry revised policies, not v1 everywhere");
}
@Test
void inventedManagedPolicyIsRejectedTheWayAwsRejectsIt() {
AwsException e = assertThrows(AwsException.class,
@@ -356,7 +356,7 @@ class IamServiceTest {
IamPolicy policy = iamService.getPolicy(arn);
assertEquals("AmazonS3ReadOnlyAccess", policy.getPolicyName());
assertEquals("v1", policy.getDefaultVersionId());
assertEquals("v3", policy.getDefaultVersionId());
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
new IamPolicyEvaluator(new com.fasterxml.jackson.databind.ObjectMapper())
.evaluate(List.of(policy.getDefaultDocument()), "s3:GetObject", "arn:aws:s3:::bucket/key"));
@@ -409,13 +409,21 @@ class IamServiceTest {
IamPolicy policy = iamService.getPolicy(arn);
assertEquals("AmazonS3ReadOnlyAccess", policy.getPolicyName());
assertEquals(arn, policy.getArn());
assertEquals("v1", policy.getDefaultVersionId());
// AWS revised this policy twice; a real account reports v3, not v1.
assertEquals("v3", policy.getDefaultVersionId());
assertTrue(policy.getDefaultDocument().contains("s3:Get*"));
AwsException error = assertThrows(AwsException.class,
() -> iamService.getPolicyVersion(arn, "v9"));
assertEquals("NoSuchEntity", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
PolicyVersion current = iamService.getPolicyVersion(arn, "v3");
assertTrue(current.isDefaultVersion());
assertEquals(policy.getDefaultDocument(), current.getDocument());
// Neither a future version nor a superseded one whose document is not bundled resolves.
for (String versionId : new String[] {"v9", "v1"}) {
AwsException error = assertThrows(AwsException.class,
() -> iamService.getPolicyVersion(arn, versionId));
assertEquals("NoSuchEntity", error.getErrorCode());
assertEquals(404, error.getHttpStatus());
}
}
@Test