fix(iam): use AWS-managed policy documents (#3237)

* fix(iam): use AWS-managed policy documents

* fix(iam): include managed policy documents in native images
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-08 09:10:18 -04:00
1 parent 8a122d2b8c
commit 379910b008
7 files changed
+120 -22

No files matched your search

@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iam;
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.quarkus.runtime.annotations.RegisterForReflection;
@@ -11,6 +12,7 @@ import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Catalog of AWS managed policies, loaded from {@code iam/managed-policies.yaml}.
@@ -22,8 +24,9 @@ import java.util.List;
* subset would reject valid configurations; resolving every well-formed ARN would accept
* invalid ones.
*
* <p>Policy documents are not modelled. Floci does not evaluate IAM by default, so every
* entry shares {@link #PERMISSIVE_DOCUMENT} and only the name, path and description matter.
* <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.
*/
final class AwsManagedPolicies {
@@ -32,12 +35,9 @@ final class AwsManagedPolicies {
static final String ARN_PREFIX = "arn:aws:iam::aws:policy";
private static final String CATALOG_RESOURCE_NAME = "iam/managed-policies.yaml";
private static final String DOCUMENTS_RESOURCE_NAME = "iam/managed-policy-documents.json";
static final String PERMISSIVE_DOCUMENT =
"{\"Version\":\"2012-10-17\",\"Statement\":"
+ "[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
record ManagedPolicyDef(String name, String path, String description) {
record ManagedPolicyDef(String name, String path, String description, String document) {
String arn() {
return ARN_PREFIX + path + name;
}
@@ -55,15 +55,24 @@ final class AwsManagedPolicies {
throw new IllegalStateException(
"AWS managed policy catalog not found on the classpath: " + CATALOG_RESOURCE_NAME);
}
Catalog catalog = new ObjectMapper(new YAMLFactory()).readValue(in, Catalog.class);
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Catalog catalog = mapper.readValue(in, Catalog.class);
Map<String, JsonNode> documents = loadDocuments();
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()) {
continue;
}
defs.add(new ManagedPolicyDef(entry.name, entry.path, entry.description));
JsonNode document = documents.get(entry.name);
if (document == null || document.isNull()) {
LOG.warnv("No AWS managed policy document available for {0}; omitting it from the resolvable catalog",
entry.name);
continue;
}
defs.add(new ManagedPolicyDef(entry.name, entry.path, entry.description, document.toString()));
}
LOG.debugv("Loaded {0} AWS managed policies from {1}", defs.size(), CATALOG_RESOURCE_NAME);
LOG.debugv("Loaded {0} AWS managed policies from {1} and {2}",
defs.size(), CATALOG_RESOURCE_NAME, DOCUMENTS_RESOURCE_NAME);
return List.copyOf(defs);
} catch (IOException e) {
throw new UncheckedIOException(
@@ -71,6 +80,19 @@ final class AwsManagedPolicies {
}
}
private static Map<String, JsonNode> loadDocuments() throws IOException {
try (InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(DOCUMENTS_RESOURCE_NAME)) {
if (in == null) {
throw new IllegalStateException(
"AWS managed policy documents not found on the classpath: " + DOCUMENTS_RESOURCE_NAME);
}
ObjectMapper jsonMapper = new ObjectMapper();
return jsonMapper.readValue(in, jsonMapper.getTypeFactory()
.constructMapType(Map.class, String.class, JsonNode.class));
}
}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
static final class Catalog {
@@ -276,7 +276,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) {
String arn = def.arn();
catalog.put(arn, new IamPolicy("ANPA" + randomId(16), def.name(), def.path(), arn,
def.description(), AwsManagedPolicies.PERMISSIVE_DOCUMENT));
def.description(), def.document()));
}
return catalog;
}
+2 -1
View File
@@ -38,7 +38,7 @@ 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), AppSync's GraphQL parser reads its
# catalog (iam/managed-policies.yaml and iam/managed-policy-documents.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
@@ -49,6 +49,7 @@ quarkus:
- ui/*.html
- ec2/*.yaml
- iam/*.yaml
- iam/*.json
- i18n/*.properties
- org/apache/velocity/runtime/defaults/*.properties
# snappy-java registers 27 JNI libraries, one per platform. Only the one
+2 -2
View File
@@ -5,8 +5,8 @@
# keeps that check faithful in both directions: policies AWS publishes attach cleanly, and
# typos are still rejected.
#
# Policy documents are not modelled. Floci does not evaluate IAM by default and every entry
# resolves to the same permissive document, so only name, path and description are needed.
# 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.
#
# 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:
@@ -0,0 +1 @@
{"AIDevOpsAgentAccessPolicy":{"Statement":[{"Action":["cloudtrail:StartQuery","support:CreateCase"],"Effect":"Allow","Resource":"*","Sid":"AIOPSServiceWriteAccess"},{"Action":["access-analyzer:GetAnalyzer","access-analyzer:List*","acm-pca:Describe*","acm-pca:GetCertificate","acm-pca:GetCertificateAuthorityCertificate","acm-pca:GetCertificateAuthorityCsr","acm-pca:List*","acm:DescribeCertificate","acm:GetAccountConfiguration","acm:GetCertificate","acm:ListCertificates","aidevops:GetAsset","aidevops:GetAssetContent","aidevops:GetAssetFile","aidevops:GetKnowledgeItem","aidevops:ListAssetFiles","aidevops:ListAssets","aidevops:ListAssetTypes","aidevops:ListAssetVersions","aidevops:ListKnowledgeItems","airflow:List*","amplify:GetApp","amplify:GetBranch","amplify:GetDomainAssociation","amplify:List*","aoss:BatchGetCollection","aoss:BatchGetLifecyclePolicy","aoss:BatchGetVpcEndpoint","aoss:GetAccessPolicy","aoss:GetSecurityConfig","aoss:GetSecurityPolicy","aoss:List*","appconfig:GetApplication","appconfig:GetConfigurationProfile","appconfig:GetEnvironment","appconfig:GetHostedConfigurationVersion","appconfig:List*","appflow:Describe*","appflow:List*","application-autoscaling:Describe*","application-signals:BatchGetServiceLevelObjectiveBudgetReport","application-signals:GetService","application-signals:GetServiceLevelObjective","application-signals:List*","applicationinsights:Describe*","applicationinsights:List*","apprunner:Describe*","apprunner:List*","appstream:Describe*","appstream:List*","appsync:GetApiAssociation","appsync:GetDataSource","appsync:GetDomainName","appsync:GetFunction","appsync:GetGraphqlApi","appsync:GetGraphqlApiEnvironmentVariables","appsync:GetIntrospectionSchema","appsync:GetResolver","appsync:GetSourceApiAssociation","appsync:List*","aps:Describe*","aps:List*","arc-zonal-shift:GetManagedResource","arc-zonal-shift:List*","athena:GetCapacityAssignmentConfiguration","athena:GetCapacityReservation","athena:GetDataCatalog","athena:GetNamedQuery","athena:GetPreparedStatement","athena:GetWorkGroup","athena:List*","auditmanager:GetAssessment","auditmanager:List*","autoscaling:Describe*","backup-gateway:GetHypervisor","backup-gateway:List*","backup:Describe*","backup:GetBackupPlan","backup:GetBackupSelection","backup:GetBackupVaultAccessPolicy","backup:GetBackupVaultNotifications","backup:GetRestoreTestingPlan","backup:GetRestoreTestingSelection","backup:List*","batch:DescribeComputeEnvironments","batch:DescribeJobQueues","batch:DescribeSchedulingPolicies","batch:List*","bcm-data-exports:Get*","bcm-data-exports:List*","bedrock:GetAgent","bedrock:GetAgentActionGroup","bedrock:GetAgentAlias","bedrock:GetAgentKnowledgeBase","bedrock:GetCustomModel","bedrock:GetDataSource","bedrock:GetFoundationModel","bedrock:GetGuardrail","bedrock:GetInferenceProfile","bedrock:GetKnowledgeBase","bedrock:GetModelInvocationLoggingConfiguration","bedrock:GetProvisionedModelThroughput","bedrock:List*","budgets:Describe*","budgets:List*","budgets:ViewBudget","ce:Describe*","ce:Get*","ce:List*","chatbot:Describe*","chatbot:GetMicrosoftTeamsChannelConfiguration","chatbot:List*","cleanrooms-ml:GetTrainingDataset","cleanrooms-ml:List*","cleanrooms:GetAnalysisTemplate","cleanrooms:GetCollaboration","cleanrooms:GetConfiguredTable","cleanrooms:GetConfiguredTableAnalysisRule","cleanrooms:GetConfiguredTableAssociation","cleanrooms:GetMembership","cleanrooms:List*","cloudformation:Describe*","cloudformation:GetResource","cloudformation:GetStackPolicy","cloudformation:GetTemplate","cloudformation:List*","cloudfront:Describe*","cloudfront:GetCachePolicy","cloudfront:GetCloudFrontOriginAccessIdentity","cloudfront:GetContinuousDeploymentPolicy","cloudfront:GetDistribution","cloudfront:GetDistributionConfig","cloudfront:GetFunction","cloudfront:GetKeyGroup","cloudfront:GetMonitoringSubscription","cloudfront:GetOriginAccessControl","cloudfront:GetOriginRequestPolicy","cloudfront:GetPublicKey","cloudfront:GetRealtimeLogConfig","cloudfront:GetResponseHeadersPolicy","cloudfront:List*","cloudtrail:Describe*","cloudtrail:GetChannel","cloudtrail:GetEventConfiguration","cloudtrail:GetEventDataStore","cloudtrail:GetEventSelectors","cloudtrail:GetInsightSelectors","cloudtrail:GetQueryResults","cloudtrail:GetResourcePolicy","cloudtrail:GetTrail","cloudtrail:GetTrailStatus","cloudtrail:List*","cloudtrail:LookupEvents","cloudwatch:Describe*","cloudwatch:GenerateQuery","cloudwatch:GetDashboard","cloudwatch:GetInsightRuleReport","cloudwatch:GetMetricData","cloudwatch:GetMetricStatistics","cloudwatch:GetMetricStream","cloudwatch:GetService","cloudwatch:GetServiceLevelObjective","cloudwatch:List*","codeartifact:Describe*","codeartifact:GetDomainPermissionsPolicy","codeartifact:GetRepositoryPermissionsPolicy","codeartifact:List*","codebuild:BatchGetFleets","codebuild:List*","codecommit:BatchDescribe*","codecommit:BatchGet*","codecommit:Describe*","codecommit:EvaluatePullRequestApprovalRules","codecommit:GetApprovalRuleTemplate","codecommit:GetBranch","coLine truncated
@@ -35,6 +35,8 @@ class IamManagedPolicyAccountScopeTest {
private static final String DEFAULT_ACCT = "000000000000";
private static final String REQUEST_ACCT = "111111111111";
private static final String OTHER_ACCT = "222222222222";
private static final String CUSTOMER_DOCUMENT =
"{\"Version\":\"2012-10-17\",\"Statement\":[]}";
@SuppressWarnings("unchecked")
private static Instance<RequestContext> requestContextFor(String accountId) {
@@ -56,7 +58,7 @@ class IamManagedPolicyAccountScopeTest {
String customerArn = "arn:aws:iam::" + DEFAULT_ACCT + ":policy/customer-policy";
policies.putForAccount(DEFAULT_ACCT, customerArn,
new IamPolicy("ANPACUSTOMER0001", "customer-policy", "/", customerArn,
"customer", AwsManagedPolicies.PERMISSIVE_DOCUMENT));
"customer", CUSTOMER_DOCUMENT));
IamService service = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
@@ -129,13 +131,13 @@ class IamManagedPolicyAccountScopeTest {
String customerArn = "arn:aws:iam::" + REQUEST_ACCT + ":policy/app-policy";
reqPolicies.putForAccount(REQUEST_ACCT, customerArn,
new IamPolicy("ANPAAPP000000001", "app-policy", "/", customerArn,
"app", AwsManagedPolicies.PERMISSIVE_DOCUMENT));
"app", CUSTOMER_DOCUMENT));
// Simulate the seed-time mirror: a managed policy copied into the default account store.
String mirroredManagedArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";
reqPolicies.putForAccount(DEFAULT_ACCT, mirroredManagedArn,
new IamPolicy("ANPAADMIN0000001", "AdministratorAccess", "/", mirroredManagedArn,
"admin", AwsManagedPolicies.PERMISSIVE_DOCUMENT));
"admin", CUSTOMER_DOCUMENT));
IamService reqService = new IamService(
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
@@ -180,7 +182,7 @@ class IamManagedPolicyAccountScopeTest {
String customerArn = "arn:aws:iam::" + REQUEST_ACCT + ":policy/app-policy";
policies.putForAccount(REQUEST_ACCT, customerArn,
new IamPolicy("ANPAAPP000000001", "app-policy", "/", customerArn,
"app", AwsManagedPolicies.PERMISSIVE_DOCUMENT));
"app", CUSTOMER_DOCUMENT));
IamUser user = new IamUser("AIDAUSER00000001", "app-user", "/",
"arn:aws:iam::" + REQUEST_ACCT + ":user/app-user");
@@ -204,7 +206,7 @@ class IamManagedPolicyAccountScopeTest {
// the attached managed policy's document for a non-default-account principal.
CallerContext caller = service.resolvePrincipalContext(
"arn:aws:iam::" + REQUEST_ACCT + ":user/app-user");
assertTrue(caller.identityPolicies().contains(AwsManagedPolicies.PERMISSIVE_DOCUMENT));
assertTrue(caller.identityPolicies().contains(CUSTOMER_DOCUMENT));
// Control: the customer policy is genuinely account-scoped — invisible from another account.
Instance<RequestContext> otherCtx = requestContextFor("222222222222");
@@ -238,7 +240,7 @@ class IamManagedPolicyAccountScopeTest {
String customerArn = "arn:aws:iam::" + REQUEST_ACCT + ":policy/group-policy";
policies.putForAccount(REQUEST_ACCT, customerArn,
new IamPolicy("ANPAGRP000000001", "group-policy", "/", customerArn,
"grp", AwsManagedPolicies.PERMISSIVE_DOCUMENT));
"grp", CUSTOMER_DOCUMENT));
IamGroup group = new IamGroup("AGPAGROUP0000001", "app-group", "/",
"arn:aws:iam::" + REQUEST_ACCT + ":group/app-group");
@@ -291,8 +293,10 @@ class IamManagedPolicyAccountScopeTest {
// the attached managed policy and the managed permissions boundary for a non-default account.
CallerContext caller = service.resolvePrincipalContext(
"arn:aws:iam::" + REQUEST_ACCT + ":role/task-role");
assertTrue(caller.identityPolicies().contains(AwsManagedPolicies.PERMISSIVE_DOCUMENT));
assertEquals(AwsManagedPolicies.PERMISSIVE_DOCUMENT, caller.boundaryPolicyDocument());
assertTrue(caller.identityPolicies().stream()
.anyMatch(document -> document.contains("logs:CreateLogGroup")));
assertTrue(caller.boundaryPolicyDocument().contains("NotAction"));
assertFalse(caller.boundaryPolicyDocument().contains("\"Action\":\"*\""));
}
/**
* The alias is the only IAM entity keyed by a constant rather than a caller-supplied name, so
@@ -1,11 +1,13 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
@@ -348,6 +350,74 @@ class IamServiceTest {
assertEquals(doc, policy.getDefaultDocument());
}
@Test
void awsManagedReadOnlyPolicyAllowsReadsButDeniesWrites() {
String arn = AwsManagedPolicies.ARN_PREFIX + "/AmazonS3ReadOnlyAccess";
IamPolicy policy = iamService.getPolicy(arn);
assertEquals("AmazonS3ReadOnlyAccess", policy.getPolicyName());
assertEquals("v1", 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"));
assertEquals(IamPolicyEvaluator.Decision.DENY,
new IamPolicyEvaluator(new com.fasterxml.jackson.databind.ObjectMapper())
.evaluate(List.of(policy.getDefaultDocument()), "s3:PutObject", "arn:aws:s3:::bucket/key"));
}
@Test
void serviceScopedAndAdministratorManagedPoliciesUseTheirDocumentedScopes() {
IamPolicy s3ReadOnly = iamService.getPolicy(
AwsManagedPolicies.ARN_PREFIX + "/AmazonS3ReadOnlyAccess");
IamPolicy administrator = iamService.getPolicy(
AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess");
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
assertEquals(IamPolicyEvaluator.Decision.DENY,
evaluator.evaluate(List.of(s3ReadOnly.getDefaultDocument()),
"ec2:RunInstances", "*"));
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
evaluator.evaluate(List.of(administrator.getDefaultDocument()),
"s3:PutObject", "arn:aws:s3:::bucket/key"));
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
evaluator.evaluate(List.of(administrator.getDefaultDocument()),
"ec2:RunInstances", "*"));
}
@Test
void managedPolicyActsAsPermissionsBoundary() {
IamUser user = iamService.createUser("boundary-user", "/");
String adminArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";
String boundaryArn = AwsManagedPolicies.ARN_PREFIX + "/AmazonS3ReadOnlyAccess";
iamService.attachUserPolicy(user.getUserName(), adminArn);
iamService.putUserPermissionsBoundary(user.getUserName(), boundaryArn);
CallerContext caller = iamService.resolvePrincipalContext(user.getArn());
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(new ObjectMapper());
assertEquals(IamPolicyEvaluator.Decision.ALLOW,
evaluator.evaluate(caller, null, "s3:GetObject", "arn:aws:s3:::bucket/key", null));
assertEquals(IamPolicyEvaluator.Decision.DENY,
evaluator.evaluate(caller, null, "s3:PutObject", "arn:aws:s3:::bucket/key", null));
assertEquals(IamPolicyEvaluator.Decision.DENY,
evaluator.evaluate(caller, null, "ec2:RunInstances", "*", null));
}
@Test
void managedPolicyRetrievalPreservesFieldsAndUnavailableVersionFailsWithNoSuchEntity() {
String arn = AwsManagedPolicies.ARN_PREFIX + "/AmazonS3ReadOnlyAccess";
IamPolicy policy = iamService.getPolicy(arn);
assertEquals("AmazonS3ReadOnlyAccess", policy.getPolicyName());
assertEquals(arn, policy.getArn());
assertEquals("v1", 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());
}
@Test
void createPolicyVersionAndSetDefault() {
String doc1 = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"}]}";