diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java b/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java index efdaadc885..997c829f36 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/AwsManagedPolicies.java @@ -53,6 +53,12 @@ final class AwsManagedPolicies { "Provides permissions required to use the CloudWatch agent on servers."), new ManagedPolicyDef("AWSLambdaFullAccess", "/", "Provides full access to Lambda, S3, DynamoDB, CloudWatch Metrics and Logs."), + new ManagedPolicyDef("AWSCloudFormationFullAccess", "/", + "Provides full access to AWS CloudFormation."), + new ManagedPolicyDef("AWSXRayDaemonWriteAccess", "/", + "Allows write permissions to the AWS X-Ray daemon."), + new ManagedPolicyDef("AmazonElasticFileSystemClientFullAccess", "/", + "Provides root client access to an Amazon EFS file system."), // Lambda execution role policies new ManagedPolicyDef("AWSLambdaBasicExecutionRole", "/service-role/", diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 03a6fb0a41..a412b46652 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -25,6 +25,7 @@ import java.time.Instant; import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -51,6 +52,13 @@ public class IamService { private final RegionResolver regionResolver; private final boolean seedDeployerPrincipal; + /** + * 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. + */ + private final Map awsManagedPolicies = buildAwsManagedPolicies(); + @Inject public IamService(StorageFactory storageFactory, EmulatorConfig config, RegionResolver regionResolver) { this( @@ -105,17 +113,25 @@ public class IamService { } } - void seedAwsManagedPolicies() { - int seeded = 0; + private static Map buildAwsManagedPolicies() { + Map catalog = new LinkedHashMap<>(); for (AwsManagedPolicies.ManagedPolicyDef def : AwsManagedPolicies.POLICIES) { String arn = def.arn(); - if (policies.get(arn).isPresent()) { + catalog.put(arn, new IamPolicy("ANPA" + randomId(16), def.name(), def.path(), arn, + def.description(), AwsManagedPolicies.PERMISSIVE_DOCUMENT)); + } + return catalog; + } + + void seedAwsManagedPolicies() { + // Managed policies are served globally from the catalog (see getPolicy); this also + // mirrors them into the default-account store so ListPolicies(Scope=AWS) lists them. + int seeded = 0; + for (Map.Entry entry : awsManagedPolicies.entrySet()) { + if (policies.get(entry.getKey()).isPresent()) { continue; } - String policyId = "ANPA" + randomId(16); - IamPolicy policy = new IamPolicy(policyId, def.name(), def.path(), arn, - def.description(), AwsManagedPolicies.PERMISSIVE_DOCUMENT); - policies.put(arn, policy); + policies.put(entry.getKey(), entry.getValue()); seeded++; } if (seeded > 0) { @@ -398,6 +414,16 @@ public class IamService { } public IamPolicy getPolicy(String policyArn) { + // AWS-managed policies (arn:aws:iam::aws:policy/...) are global — not owned by any + // account — so they are served from the catalog rather than the account-partitioned + // store, which would otherwise make them visible only to the default account. + if (policyArn != null && policyArn.startsWith(AwsManagedPolicies.ARN_PREFIX)) { + IamPolicy managed = awsManagedPolicies.get(policyArn); + if (managed != null) { + return managed; + } + throw new AwsException("NoSuchEntity", "Policy " + policyArn + " does not exist.", 404); + } return policies.get(policyArn) .orElseThrow(() -> new AwsException("NoSuchEntity", "Policy " + policyArn + " does not exist.", 404)); @@ -431,17 +457,29 @@ public class IamService { + "Member must satisfy enum value set: [All, AWS, Local]", 400); } String prefix = pathPrefix != null ? pathPrefix : "/"; - return policies.scan(k -> true).stream() - .filter(p -> p.getPath().startsWith(prefix)) - .filter(p -> { - if ("AWS".equalsIgnoreCase(scope)) { - return p.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX); - } else if ("Local".equalsIgnoreCase(scope)) { - return !p.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX); - } - return true; - }) - .toList(); + boolean blankScope = scope == null || scope.isBlank(); + boolean includeAws = blankScope || "All".equalsIgnoreCase(scope) || "AWS".equalsIgnoreCase(scope); + boolean includeLocal = blankScope || "All".equalsIgnoreCase(scope) || "Local".equalsIgnoreCase(scope); + + List result = new ArrayList<>(); + if (includeLocal) { + // Customer-managed policies live in the account-partitioned store. Exclude any + // 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 -> p.getPath().startsWith(prefix)) + .forEach(result::add); + } + if (includeAws) { + // AWS-managed policies are global (account-less arn:aws:iam::aws:policy/... ARN), so + // every caller sees the full set regardless of the request account — mirroring the + // getPolicy fix, and keeping the ListPolicies and GetPolicy read paths consistent. + awsManagedPolicies.values().stream() + .filter(p -> p.getPath().startsWith(prefix)) + .forEach(result::add); + } + return result; } public PolicyVersion createPolicyVersion(String policyArn, String document, boolean setAsDefault) { diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java new file mode 100644 index 0000000000..e6bde34e55 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamManagedPolicyAccountScopeTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.iam.model.IamPolicy; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * AWS-managed policies (arn:aws:iam::aws:policy/...) are global in AWS: seeded once under the + * default account at startup, they must still resolve for callers in any other account. + * Regression guard for the account-scoping bug where {@code data.aws_iam_policy} / GetPolicy + * returned NoSuchEntity for a seeded managed policy when the request ran under a non-default + * account (e.g. an assumed-role / 12-digit access-key credential). + */ +class IamManagedPolicyAccountScopeTest { + + private static final String DEFAULT_ACCT = "000000000000"; + private static final String REQUEST_ACCT = "111111111111"; + + @SuppressWarnings("unchecked") + private static Instance requestContextFor(String accountId) { + RequestContext rc = mock(RequestContext.class); + when(rc.getAccountId()).thenReturn(accountId); + Instance inst = mock(Instance.class); + when(inst.get()).thenReturn(rc); + return inst; + } + + @Test + void managedPolicyResolvesFromAnyAccountWhileCustomerPolicyStaysScoped() { + // The policies store sees the current request as account 111..., default is 000... + InMemoryStorage raw = new InMemoryStorage<>(); + AccountAwareStorageBackend policies = + new AccountAwareStorageBackend<>(raw, requestContextFor(REQUEST_ACCT), DEFAULT_ACCT); + + // A customer policy stored under the default account (control for account isolation). + 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)); + + IamService service = new IamService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + policies, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", DEFAULT_ACCT)); + + // A managed policy resolves from any account context (served from the global catalog, + // not the account-partitioned store) — the request runs as account 111... + String managedArn = AwsManagedPolicies.ARN_PREFIX + "/service-role/AWSLambdaBasicExecutionRole"; + IamPolicy managed = service.getPolicy(managedArn); + assertEquals(managedArn, managed.getArn()); + // GetPolicyVersion routes through getPolicy, so the document is reachable too. + assertNotNull(service.getPolicyVersion(managedArn, "v1")); + + // Control: a customer (account-scoped) policy under the default account is NOT visible + // from account 111... — only managed policies cross the account boundary. + assertThrows(AwsException.class, () -> service.getPolicy(customerArn)); + } + + @Test + void catalogIncludesPoliciesNeededByCommonExecutionRoles() { + List arns = AwsManagedPolicies.POLICIES.stream() + .map(AwsManagedPolicies.ManagedPolicyDef::arn) + .toList(); + assertTrue(arns.contains(AwsManagedPolicies.ARN_PREFIX + "/AWSXRayDaemonWriteAccess")); + assertTrue(arns.contains(AwsManagedPolicies.ARN_PREFIX + "/AWSCloudFormationFullAccess")); + assertTrue(arns.contains(AwsManagedPolicies.ARN_PREFIX + "/AmazonElasticFileSystemClientFullAccess")); + } + + @Test + void listPoliciesScopeAwsAndAllReturnManagedCatalogFromAnyAccount() { + // Request runs as account 111..., default is 000... Managed policies are only mirrored + // into the default account at seed time, so a Scope=AWS scan of the request account's + // partition was empty before this fix — the same account-scoping bug GetPolicy had. + AccountAwareStorageBackend policies = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), requestContextFor(REQUEST_ACCT), DEFAULT_ACCT); + IamService service = new IamService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + policies, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", DEFAULT_ACCT)); + + int catalogSize = AwsManagedPolicies.POLICIES.size(); + String lambdaBasicArn = AwsManagedPolicies.ARN_PREFIX + "/service-role/AWSLambdaBasicExecutionRole"; + + // Scope=AWS now serves the full global catalog from a non-default account. + List aws = service.listPolicies("AWS", null); + assertEquals(catalogSize, aws.size()); + assertTrue(aws.stream().anyMatch(p -> lambdaBasicArn.equals(p.getArn()))); + + // The data.aws_iam_policy name-lookup path (ListPolicies + name filter) now resolves + // managed policies for a caller outside the default account. + assertTrue(aws.stream().anyMatch(p -> "AWSLambdaBasicExecutionRole".equals(p.getPolicyName()))); + + // Scope=All and the default (blank) scope also include the managed catalog. + assertEquals(catalogSize, service.listPolicies("All", null).size()); + assertEquals(catalogSize, service.listPolicies(null, null).size()); + } + + @Test + void listPoliciesScopesLocalToCallerAndDoesNotDuplicateMirroredManaged() { + InMemoryStorage raw = new InMemoryStorage<>(); + + // A customer policy owned by the request account 111... + AccountAwareStorageBackend reqPolicies = + new AccountAwareStorageBackend<>(raw, requestContextFor(REQUEST_ACCT), DEFAULT_ACCT); + 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)); + + // 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)); + + IamService reqService = new IamService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + reqPolicies, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", DEFAULT_ACCT)); + + // Scope=Local returns only the caller's customer policy — never AWS-managed policies. + List local = reqService.listPolicies("Local", null); + assertEquals(1, local.size()); + assertEquals(customerArn, local.get(0).getArn()); + + // From the default account, the mirrored managed policy must appear once, not twice + // (once from the account store and again from the catalog). + AccountAwareStorageBackend defPolicies = + new AccountAwareStorageBackend<>(raw, requestContextFor(DEFAULT_ACCT), DEFAULT_ACCT); + IamService defService = new IamService( + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + defPolicies, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new RegionResolver("us-east-1", DEFAULT_ACCT)); + List defAll = defService.listPolicies("All", null); + assertEquals(AwsManagedPolicies.POLICIES.size(), defAll.size()); + assertEquals(1L, defAll.stream().filter(p -> mirroredManagedArn.equals(p.getArn())).count()); + } +}