Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): read iam:PermissionsBoundary from the stored role or user an action names (#6897)
lex005a84d08383c0
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex b4cf47ccc9..9b6b67925f 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -2316,10 +2316,15 @@ floci populates:- `iam:OrganizationsPolicyId` from `OrganizationsPolicyId` on`GenerateOrganizationsAccessReport`.+ The table's `fromTarget` entries read `iam:PermissionsBoundary` from the role or user the+ request names in `RoleName` or `UserName`: its stored boundary, on the 15 actions on an+ existing role or user, such as `AttachRolePolicy`, `PutUserPolicy`, `GetRole` and+ `DeleteRolePermissionsBoundary`. A role or user without a boundary, or one that does not+ exist, carries no value for the key.+A request without the parameter carries no value for the key, and the target remains theauthorized resource. Every other pair the reference lists is in the table's `notRead` with- its reason, such as the actions where `iam:PermissionsBoundary` is the target's current- boundary. Regenerate with `make iam-condition-keys-sync`.+ its reason. Regenerate with `make iam-condition-keys-sync`.- `s3:prefix`, `s3:delimiter`, `s3:max-keys`: from the S3 request parameters.- `aws:RequestTag/<key>`: the tags named in the request itself, before they are applied, for`ec2:RunInstances` (`TagSpecification.N`), `ec2:CreateTags` (`Tag.N`) anddiff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.javaindex 14a1dd706d..d3620b19e3 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java@@ -12,7 +12,10 @@ import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.model.Tag;import io.github.hectorvent.floci.services.iam.IamActionRegistry;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;+import io.github.hectorvent.floci.services.iam.model.IamRole;+import io.github.hectorvent.floci.services.iam.model.IamUser;import io.github.hectorvent.floci.services.s3.S3ControlTagConditionKeys;import io.github.hectorvent.floci.services.s3.S3ObjectActions;import io.github.hectorvent.floci.services.s3.S3ObjectKeys;@@ -88,6 +91,7 @@ public class IamConditionContextResolver {private final Instance<Ec2Service> ec2Service;private final Instance<S3Service> s3Service;private final Instance<CloudWatchLogsService> logsService;+ private final Instance<IamService> iamService;private final RequestContext requestContext;private final EmulatorConfig config;private final CurrentVertxRequest currentVertxRequest;@@ -103,11 +107,12 @@ public class IamConditionContextResolver {Instance<Ec2Service> ec2Service,Instance<S3Service> s3Service,Instance<CloudWatchLogsService> logsService,+ Instance<IamService> iamService,RequestContext requestContext,EmulatorConfig config,CurrentVertxRequest currentVertxRequest,ResolvedServiceCatalog serviceCatalog) {- this(dynamoDbFacade, ec2Service, s3Service, logsService, requestContext, config, currentVertxRequest,+ this(dynamoDbFacade, ec2Service, s3Service, logsService, iamService, requestContext, config, currentVertxRequest,serviceCatalog, Clock.systemUTC());}@@ -115,6 +120,7 @@ public class IamConditionContextResolver {Instance<Ec2Service> ec2Service,Instance<S3Service> s3Service,Instance<CloudWatchLogsService> logsService,+ Instance<IamService> iamService,RequestContext requestContext,EmulatorConfig config,CurrentVertxRequest currentVertxRequest,@@ -123,6 +129,7 @@ public class IamConditionContextResolver {this.ec2Service = ec2Service;this.s3Service = s3Service;this.logsService = logsService;+ this.iamService = iamService;this.requestContext = requestContext;this.config = config;this.currentVertxRequest = currentVertxRequest;@@ -209,9 +216,10 @@ public class IamConditionContextResolver {return conditions;}- private static Map<String, List<String>> iamConditionContext(String action, ContainerRequestContext ctx) {+ private Map<String, List<String>> iamConditionContext(String action, ContainerRequestContext ctx) {Map<String, String> members = IamConditionKeys.members(action);- if (members.isEmpty()) {+ Map<String, String> targets = IamConditionKeys.targets(action);+ if (members.isEmpty() && targets.isEmpty()) {return null;}Map<String, String> form = formParameters(ctx);@@ -222,9 +230,28 @@ public class IamConditionContextResolver {conditions.put(key, List.of(value));}});+ // iam:PermissionsBoundary on an existing role or user is the boundary stored on it, left off when it has none.+ targets.forEach((key, target) -> {+ String value = storedPermissionsBoundary(target, form.get(target));+ if (value != null) {+ conditions.put(key, List.of(value));+ }+ });return conditions.isEmpty() ? null : conditions;}+ private String storedPermissionsBoundary(String target, String name) {+ if (name == null || !iamService.isResolvable()) {+ return null;+ }+ String account = requestContext.getAccountId();+ return switch (target) {+ case "RoleName" -> iamService.get().findRole(account, name).map(IamRole::getPermissionsBoundaryArn).orElse(null);+ case "UserName" -> iamService.get().findUser(account, name).map(IamUser::getPermissionsBoundaryArn).orElse(null);+ default -> throw new IllegalStateException("Unknown IAM condition key target: " + target);+ };+ }+public static Map<String, List<String>> withGlobalContext(Map<String, List<String>> serviceContext,String resourceArn, String region,String accountId, String resourceOwnerAccountId) {diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.javaindex 9b2cc8cd8a..b9b8caf82c 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java@@ -7,34 +7,50 @@ import java.util.LinkedHashMap;import java.util.Map;/**- * The {@code iam:} condition keys an IAM request carries in its own members, generated from the- * AWS Service Reference and pinned botocore by {@code tools/aws/regen_iam_condition_keys.py}.+ * The {@code iam:} condition keys an IAM request carries in its own members, and those read from the+ * role or user it names, generated from the AWS Service Reference and pinned botocore by+ * {@code tools/aws/regen_iam_condition_keys.py}.*/final class IamConditionKeys {- private static final Map<String, Map<String, String>> MEMBERS = VendoredResources.read(+ private record Table(Map<String, Map<String, String>> members, Map<String, Map<String, String>> targets) {}++ private static final Table TABLE = VendoredResources.read("aws/iam-condition-keys.json", "IAM condition keys", input -> {- JsonNode read = new ObjectMapper().readTree(input).path("read");- if (!read.isArray() || read.isEmpty()) {- throw new IllegalStateException("Malformed IAM condition key table");- }- Map<String, Map<String, String>> members = new LinkedHashMap<>();- for (JsonNode entry : read) {- if (!entry.path("action").isTextual() || !entry.path("key").isTextual()- || !entry.path("member").isTextual()) {- throw new IllegalStateException("Malformed IAM condition key entry: " + entry);- }- members.computeIfAbsent(entry.get("action").asText(), action -> new LinkedHashMap<>())- .put(entry.get("key").asText(), entry.get("member").asText());- }- members.replaceAll((action, keys) -> Map.copyOf(keys));- return Map.copyOf(members);+ JsonNode document = new ObjectMapper().readTree(input);+ return new Table(section(document.path("read"), "member"),+ section(document.path("fromTarget"), "target"));});private IamConditionKeys() {}+ private static Map<String, Map<String, String>> section(JsonNode entries, String field) {+ if (!entries.isArray() || entries.isEmpty()) {+ throw new IllegalStateException("Malformed IAM condition key table");+ }+ Map<String, Map<String, String>> byAction = new LinkedHashMap<>();+ for (JsonNode entry : entries) {+ if (!entry.path("action").isTextual() || !entry.path("key").isTextual()+ || !entry.path(field).isTextual()) {+ throw new IllegalStateException("Malformed IAM condition key entry: " + entry);+ }+ byAction.computeIfAbsent(entry.get("action").asText(), action -> new LinkedHashMap<>())+ .put(entry.get("key").asText(), entry.get(field).asText());+ }+ byAction.replaceAll((action, keys) -> Map.copyOf(keys));+ return Map.copyOf(byAction);+ }+/** Each condition key a request for {@code action} carries, to the member that holds it; empty when none. */static Map<String, String> members(String action) {- return MEMBERS.getOrDefault(action, Map.of());+ return TABLE.members().getOrDefault(action, Map.of());+ }++ /**+ * Each condition key a request for {@code action} takes from the stored role or user it names, to the+ * member that names it ({@code RoleName} or {@code UserName}); empty when none.+ */+ static Map<String, String> targets(String action) {+ return TABLE.targets().getOrDefault(action, Map.of());}}diff --git a/src/main/resources/aws/iam-condition-keys.json b/src/main/resources/aws/iam-condition-keys.jsonindex 1e2f1f58ea..98412959df 100644--- a/src/main/resources/aws/iam-condition-keys.json+++ b/src/main/resources/aws/iam-condition-keys.json@@ -21,22 +21,30 @@{"action": "iam:PutRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"},{"action": "iam:PutUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"}],+ "fromTarget": [+ {"action": "iam:AttachRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:AttachUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"},+ {"action": "iam:DeleteRole", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:DeleteRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:DeleteRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:DeleteUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "target": "UserName"},+ {"action": "iam:DeleteUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"},+ {"action": "iam:DetachRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:DetachUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"},+ {"action": "iam:GetRole", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:PutRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:PutUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"},+ {"action": "iam:UpdateAssumeRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:UpdateRole", "key": "iam:PermissionsBoundary", "target": "RoleName"},+ {"action": "iam:UpdateRoleDescription", "key": "iam:PermissionsBoundary", "target": "RoleName"}+ ],"notRead": [{"action": "iam:AcceptDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"action": "iam:AssociateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},- {"action": "iam:AttachRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:AttachRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},- {"action": "iam:AttachUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:CreateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"action": "iam:CreateRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},- {"action": "iam:DeleteRole", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:DeleteRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:DeleteRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:DeleteServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"},- {"action": "iam:DeleteUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:DeleteUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:DetachRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:DetachUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:EnableMFADevice", "key": "iam:FIDO-FIPS-140-2-certification", "reason": "the value comes from the FIDO Alliance Metadata Service"},{"action": "iam:EnableMFADevice", "key": "iam:FIDO-FIPS-140-3-certification", "reason": "the value comes from the FIDO Alliance Metadata Service"},{"action": "iam:EnableMFADevice", "key": "iam:FIDO-certification", "reason": "the value comes from the FIDO Alliance Metadata Service"},@@ -44,23 +52,17 @@{"action": "iam:GetAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"},{"action": "iam:GetDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"action": "iam:GetHumanReadableSummary", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},- {"action": "iam:GetRole", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:GetRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},{"action": "iam:ListDelegationRequests", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"action": "iam:PassRole", "key": "iam:AssociatedResourceArn", "reason": "no SDK operation of this name"},{"action": "iam:PassRole", "key": "iam:PassedToService", "reason": "no SDK operation of this name"},{"action": "iam:PutAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"},{"action": "iam:PutRolePermissionsBoundary", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},- {"action": "iam:PutRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:PutRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},- {"action": "iam:PutUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"action": "iam:ResetServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"},{"action": "iam:SendDelegationToken", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"action": "iam:TagRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},- {"action": "iam:UpdateAssumeRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:UpdateRole", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},- {"action": "iam:UpdateRoleDescription", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"},{"action": "iam:UpdateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"}]}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.javaindex 756e99aa80..18e98d5cf7 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java@@ -13,6 +13,9 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;import io.github.hectorvent.floci.services.ec2.model.Tag;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;+import io.github.hectorvent.floci.services.iam.IamService;+import io.github.hectorvent.floci.services.iam.model.IamRole;+import io.github.hectorvent.floci.services.iam.model.IamUser;import io.github.hectorvent.floci.services.s3.S3Service;import jakarta.enterprise.inject.Instance;import jakarta.ws.rs.container.ContainerRequestContext;@@ -60,6 +63,7 @@ class IamConditionContextResolverTest {private Ec2Service ec2Service;private S3Service s3Service;private CloudWatchLogsService logsService;+ private IamService iamService;private RequestContext requestContext;private EmulatorConfig config;private IamConditionContextResolver resolver;@@ -86,7 +90,12 @@ class IamConditionContextResolverTest {Instance<CloudWatchLogsService> logsServiceInstance = mock(Instance.class);when(logsServiceInstance.isResolvable()).thenReturn(true);when(logsServiceInstance.get()).thenReturn(logsService);+ iamService = mock(IamService.class);+ Instance<IamService> iamServiceInstance = mock(Instance.class);+ when(iamServiceInstance.isResolvable()).thenReturn(true);+ when(iamServiceInstance.get()).thenReturn(iamService);requestContext = new RequestContext();+ requestContext.setAccountId("123456789012");requestContext.setRegion("us-east-1");config = mock(EmulatorConfig.class);when(config.defaultRegion()).thenReturn("us-east-1");@@ -98,7 +107,8 @@ class IamConditionContextResolverTest {ServiceCatalog catalog = new ServiceCatalog(List.of(dynamo));when(serviceCatalog.matchTarget(any())).thenAnswer(call -> catalog.matchTarget(call.getArgument(0)));resolver = new IamConditionContextResolver(- dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, requestContext, config,+ dynamoDbFacadeInstance, ec2ServiceInstance, s3ServiceInstance, logsServiceInstance, iamServiceInstance,+ requestContext, config,null, serviceCatalog);}@@ -214,6 +224,47 @@ class IamConditionContextResolverTest {assertNull(resolver.resolve("iam", "iam:GetRole", formRequest("PermissionsBoundary=example")));}+ @Test+ void iamPermissionsBoundaryOfAnExistingRoleOrUserIsTheBoundaryStoredOnIt() {+ IamRole bounded = new IamRole();+ bounded.setPermissionsBoundaryArn("arn:aws:iam::123456789012:policy/Boundary");+ IamUser boundedUser = new IamUser();+ boundedUser.setPermissionsBoundaryArn("arn:aws:iam::123456789012:policy/UserBoundary");+ when(iamService.findRole("123456789012", "bounded")).thenReturn(Optional.of(bounded));+ when(iamService.findRole("123456789012", "open")).thenReturn(Optional.of(new IamRole()));+ when(iamService.findUser("123456789012", "bounded")).thenReturn(Optional.of(boundedUser));+ for (String action : List.of("iam:AttachRolePolicy", "iam:DeleteRole", "iam:DeleteRolePermissionsBoundary",+ "iam:DeleteRolePolicy", "iam:DetachRolePolicy", "iam:GetRole", "iam:PutRolePolicy",+ "iam:UpdateAssumeRolePolicy", "iam:UpdateRole", "iam:UpdateRoleDescription")) {+ assertEquals(List.of("arn:aws:iam::123456789012:policy/Boundary"),+ resolver.resolve("iam", action, formRequest("RoleName=bounded")).get("iam:PermissionsBoundary"),+ action);+ assertNull(resolver.resolve("iam", action, formRequest("RoleName=open")), action);+ assertNull(resolver.resolve("iam", action, formRequest("RoleName=missing")), action);+ }+ for (String action : List.of("iam:AttachUserPolicy", "iam:DeleteUserPermissionsBoundary",+ "iam:DeleteUserPolicy", "iam:DetachUserPolicy", "iam:PutUserPolicy")) {+ assertEquals(List.of("arn:aws:iam::123456789012:policy/UserBoundary"),+ resolver.resolve("iam", action, formRequest("UserName=bounded")).get("iam:PermissionsBoundary"),+ action);+ assertNull(resolver.resolve("iam", action, formRequest("UserName=missing")), action);+ }+ }++ @Test+ void iamPermissionsBoundaryOnAPutBoundaryIsTheRequestedOneAndAttachKeepsItsPolicyArn() {+ IamRole bounded = new IamRole();+ bounded.setPermissionsBoundaryArn("arn:aws:iam::123456789012:policy/Old");+ when(iamService.findRole("123456789012", "bounded")).thenReturn(Optional.of(bounded));+ assertEquals(Map.of("iam:PermissionsBoundary", List.of("arn:aws:iam::123456789012:policy/New")),+ resolver.resolve("iam", "iam:PutRolePermissionsBoundary", formRequest(+ "RoleName=bounded&PermissionsBoundary=arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FNew")));+ assertEquals(Map.of("iam:PolicyARN", List.of("arn:aws:iam::aws:policy/ReadOnlyAccess"),+ "iam:PermissionsBoundary", List.of("arn:aws:iam::123456789012:policy/Old")),+ resolver.resolve("iam", "iam:AttachRolePolicy", formRequest(+ "RoleName=bounded&PolicyArn=arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FReadOnlyAccess")));+ }+@Testvoid iamAwsServiceNameComesFromCreateServiceLinkedRole() {assertEquals(Map.of("iam:AWSServiceName", List.of("replication.ecr.amazonaws.com")),@@ -499,7 +550,8 @@ class IamConditionContextResolverTest {@SuppressWarnings("unchecked")private IamConditionContextResolver resolverAt(Instant now) {return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),- mock(Instance.class), requestContext, config, null, serviceCatalog, Clock.fixed(now, ZoneOffset.UTC));+ mock(Instance.class), mock(Instance.class), requestContext, config, null, serviceCatalog,+ Clock.fixed(now, ZoneOffset.UTC));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.javaindex d11570ab35..4daa616d6a 100644--- a/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/dynamodb/backend/DynamoDbFacadeTest.java@@ -152,7 +152,8 @@ class DynamoDbFacadeTest {RequestContext requestContext = new RequestContext();requestContext.setRegion(OTHER_REGION);IamConditionContextResolver resolver = new IamConditionContextResolver(dynamoDb,- mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext, mock(EmulatorConfig.class),+ mock(Instance.class), mock(Instance.class), mock(Instance.class), mock(Instance.class), requestContext,+ mock(EmulatorConfig.class),null, mock(io.github.hectorvent.floci.core.common.ResolvedServiceCatalog.class));ContainerRequestContext request = mock(ContainerRequestContext.class);JsonNode body = mapper.readTree("""diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.javaindex b0b5bf6548..e1b1d2eb3d 100644--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.java@@ -25,7 +25,8 @@ import static org.hamcrest.Matchers.containsString;* an allow conditioned on {@code StringEquals} {@code iam:PermissionsBoundary}. The Service* Authorization Reference lists the key on {@code CreateRole}, {@code CreateUser},* {@code PutRolePermissionsBoundary} and {@code PutUserPermissionsBoundary}, which carry the boundary- * in their {@code PermissionsBoundary} parameter.+ * in their {@code PermissionsBoundary} parameter. On actions on an existing role or user, such as+ * {@code AttachRolePolicy} and {@code PutUserPolicy}, the key is the boundary stored on it.*/@QuarkusTest@TestProfile(IamEnforcementProfile.class)@@ -93,6 +94,46 @@ class IamPermissionsBoundaryConditionEnforcementIntegrationTest {.formParam("PermissionsBoundary", boundary).post("/").then().statusCode(200);}+ @Test+ void attachRolePolicyIsAllowedOnlyOnARoleThatHasTheBoundary() {+ String boundary = boundaryPolicy("boundary");+ String policy = boundaryPolicy("attached");+ UserCredentials delegated = delegatedAdmin(boundary, "iam:AttachRolePolicy");+ String bounded = "bounded-" + suffix();+ String open = "open-" + suffix();+ cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth(ADMIN, "iam"), bounded));+ cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth(ADMIN, "iam"), open));+ createRole(ADMIN, bounded).formParam("PermissionsBoundary", boundary).post("/").then().statusCode(200);+ createRole(ADMIN, open).post("/").then().statusCode(200);++ denied(iam(delegated.accessKeyId(), "AttachRolePolicy").formParam("RoleName", open)+ .formParam("PolicyArn", policy).post("/").then(), "iam:AttachRolePolicy");+ iam(delegated.accessKeyId(), "AttachRolePolicy").formParam("RoleName", bounded)+ .formParam("PolicyArn", policy).post("/").then().statusCode(200);+ }++ @Test+ void putUserPolicyIsAllowedOnlyOnAUserThatHasTheBoundary() {+ String boundary = boundaryPolicy("boundary");+ UserCredentials delegated = delegatedAdmin(boundary, "iam:PutUserPolicy");+ String bounded = "bounded-" + suffix();+ String open = "open-" + suffix();+ cleanup.register(() -> EnforcementFixtures.removeUser(baseUri.getPort(), auth(ADMIN, "iam"), bounded));+ cleanup.register(() -> EnforcementFixtures.removeUser(baseUri.getPort(), auth(ADMIN, "iam"), open));+ iam(ADMIN, "CreateUser").formParam("UserName", bounded).formParam("PermissionsBoundary", boundary)+ .post("/").then().statusCode(200);+ iam(ADMIN, "CreateUser").formParam("UserName", open).post("/").then().statusCode(200);+ String document = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""";++ denied(iam(delegated.accessKeyId(), "PutUserPolicy").formParam("UserName", open)+ .formParam("PolicyName", "inline").formParam("PolicyDocument", document).post("/").then(),+ "iam:PutUserPolicy");+ iam(delegated.accessKeyId(), "PutUserPolicy").formParam("UserName", bounded)+ .formParam("PolicyName", "inline").formParam("PolicyDocument", document).post("/").then()+ .statusCode(200);+ }+private String boundaryPolicy(String name) {String arn = iam(ADMIN, "CreatePolicy").formParam("PolicyName", name + "-" + suffix())diff --git a/tools/aws/regen_iam_condition_keys.py b/tools/aws/regen_iam_condition_keys.pyindex c193bfbb11..0caff0f5ec 100644--- a/tools/aws/regen_iam_condition_keys.py+++ b/tools/aws/regen_iam_condition_keys.py@@ -6,10 +6,12 @@ For each such action and key, pinned botocore says whether the request carries toperation of the same name has a top-level string member named after the key, ignoring case(iam:PolicyARN is PolicyArn), and the key's type is String or ARN. BY_HAND names the member for apair whose value sits in a member under another name; its type has to fit the key's. Those pairs-are read; every other pair the reference lists is notRead, with the reason. An operation that has the member but-whose action does not list the key is left out, as AWS does not set the key for it.+are read. A FROM_TARGET key the request does not carry is the stored role's or user's value, and its+pair goes in fromTarget with the member that names the target. Every other pair the reference lists+is notRead, with the reason. An operation that has the member but whose action does not list the key+is left out, as AWS does not set the key for it.---check re-derives read and notRead offline from the pairs in the file and pinned botocore, so a+--check re-derives read, fromTarget and notRead offline from the pairs in the file and pinned botocore, so ahand-edited entry fails, as does a BY_HAND member botocore no longer has or a BY_HAND pair thefile does not list. --verify compares every pair and key type with the live reference andfails on any difference, added pairs included: a key missing from the context stops a@@ -39,6 +41,11 @@ BY_HAND = {}# The botocore types a BY_HAND member may have for each key type; the context value is the member's text.BY_HAND_TYPES = {"String": {"string", "integer"}, "ARN": {"string"}, "Numeric": {"integer", "long"}}+# Keys whose value, on an action without the member, is the stored target's: the IAM User Guide's+# iam:PermissionsBoundary "checks that the specified policy is attached as permissions boundary on the+# IAM principal resource". The target is the role or user the request names.+FROM_TARGET = {"iam:PermissionsBoundary"}+TARGET_MEMBERS = ("RoleName", "UserName")# Keys whose value, on an action without the member, does not come from the request.NOT_IN_REQUEST = {"iam:AccountPropertyNamespaces": "the value is the namespaces of the properties read or written",@@ -46,7 +53,6 @@ NOT_IN_REQUEST = {"iam:FIDO-FIPS-140-2-certification": "the value comes from the FIDO Alliance Metadata Service","iam:FIDO-FIPS-140-3-certification": "the value comes from the FIDO Alliance Metadata Service","iam:FIDO-certification": "the value comes from the FIDO Alliance Metadata Service",- "iam:PermissionsBoundary": "the value is the target's current permissions boundary","iam:RegisterSecurityKey": "the value is the MFA device's registration state","iam:RoleTemplateARN": "the value is the role template a service acquires the role from","iam:ServiceSpecificCredentialServiceName": "the value is the named credential's service",@@ -79,8 +85,8 @@ def member_type(model, operation, path):def classify(pairs, types, model):- """The read entries and the notRead entries for the reference's pairs."""- read, not_read = [], []+ """The read, fromTarget and notRead entries for the reference's pairs."""+ read, from_target, not_read = [], [], []for action, key in sorted(pairs):operation = model["operations"].get(action.split(":", 1)[1])if (action, key) in BY_HAND:@@ -98,6 +104,12 @@ def classify(pairs, types, model):member = next((m for m in sorted(members) if m.lower() == local.lower()), None)if operation is None:reason = "no SDK operation of this name"+ elif member is None and key in FROM_TARGET:+ target = next((m for m in TARGET_MEMBERS if m in members), None)+ if target is None:+ raise ValueError(f"{action}: no member names the role or user {key} is read from")+ from_target.append({"action": action, "key": key, "target": target})+ continueelif member is None:reason = NOT_IN_REQUEST.get(key, "no member named after the key")elif not set(types.get(key, [])) <= READ_TYPES:@@ -108,7 +120,7 @@ def classify(pairs, types, model):read.append({"action": action, "key": key, "member": member})continuenot_read.append({"action": action, "key": key, "reason": reason})- return read, not_read+ return read, from_target, not_readdef require_by_hand_listed(pairs):@@ -118,7 +130,8 @@ def require_by_hand_listed(pairs):def pairs_of(document):- return sorted((e["action"], e["key"]) for e in document["read"] + document["notRead"])+ return sorted((e["action"], e["key"])+ for e in document["read"] + document["fromTarget"] + document["notRead"])def render(document):@@ -126,7 +139,7 @@ def render(document):lines = ["{"]for key in ("source", "botocore", "types"):lines.append(f' "{key}": {json.dumps(document[key])},')- for section, tail in (("read", ","), ("notRead", "")):+ for section, tail in (("read", ","), ("fromTarget", ","), ("notRead", "")):entries = document[section]lines.append(f' "{section}": [')lines += [f" {json.dumps(e)}{',' if i < len(entries) - 1 else ''}" for i, e in enumerate(entries)]@@ -149,7 +162,8 @@ def main(argv=None):raise ValueError("an IAM condition key pair is listed twice")require_by_hand_listed(pairs)model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "iam"))- if classify(pairs, document["types"], model) != (document["read"], document["notRead"]):+ if classify(pairs, document["types"], model) != (+ document["read"], document["fromTarget"], document["notRead"]):raise ValueError("IAM condition key members differ from pinned botocore")return 0try:@@ -174,9 +188,9 @@ def main(argv=None):return 0require_by_hand_listed(pairs)data, provenance = resolve_botocore_data(args.botocore_data)- read, not_read = classify(pairs, types, load_model(latest_model_dir(data, "iam")))+ read, from_target, not_read = classify(pairs, types, load_model(latest_model_dir(data, "iam")))OUTPUT.write_text(render({"source": URL, "botocore": provenance, "types": types,- "read": read, "notRead": not_read}))+ "read": read, "fromTarget": from_target, "notRead": not_read}))return 0diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.pyindex c6d52d7943..8018deeddb 100644--- a/tools/aws/test_regen_iam_condition_keys.py+++ b/tools/aws/test_regen_iam_condition_keys.py@@ -13,9 +13,14 @@ MODEL = {"operations": {"GetRole": {"input": {"shape": "GetInput"}},"CreateServiceSpecificCredential": {"input": {"shape": "CredentialInput"}},"CreateDelegationRequest": {"input": {"shape": "DelegationInput"}},+ "DeleteUserPolicy": {"input": {"shape": "UserInput"}},+ "ListRoles": {"input": {"shape": "ListInput"}},}, "shapes": {"AttachInput": {"type": "structure", "members": {"PolicyArn": {"shape": "Arn"}}},"GetInput": {"type": "structure", "members": {"RoleName": {"shape": "Name"}}},+ "UserInput": {"type": "structure", "members": {"UserName": {"shape": "Name"},+ "PolicyName": {"shape": "Name"}}},+ "ListInput": {"type": "structure", "members": {"PathPrefix": {"shape": "Name"}}},"CredentialInput": {"type": "structure", "members": {"CredentialAgeDays": {"shape": "Days"},"ServiceName": {"shape": "Name"}}},"DelegationInput": {"type": "structure", "members": {"Permissions": {"shape": "Permission"},@@ -38,22 +43,35 @@ def test_resource_and_action_keys_are_combined_and_global_keys_dropped():def test_member_is_matched_ignoring_case_only_on_actions_listing_the_key():- read, not_read = classify([("iam:AttachRolePolicy", "iam:PolicyARN")], {"iam:PolicyARN": ["ARN"]}, MODEL)+ read, from_target, not_read = classify([("iam:AttachRolePolicy", "iam:PolicyARN")],+ {"iam:PolicyARN": ["ARN"]}, MODEL)assert read == [{"action": "iam:AttachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}]- assert not_read == []+ assert from_target == not_read == []+++def test_permissions_boundary_without_a_request_member_is_read_from_the_named_role_or_user():+ pairs = [("iam:GetRole", "iam:PermissionsBoundary"), ("iam:DeleteUserPolicy", "iam:PermissionsBoundary")]+ read, from_target, not_read = classify(pairs, {"iam:PermissionsBoundary": ["ARN"]}, MODEL)+ assert read == not_read == []+ assert from_target == [+ {"action": "iam:DeleteUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"},+ {"action": "iam:GetRole", "key": "iam:PermissionsBoundary", "target": "RoleName"}]+++def test_permissions_boundary_on_an_operation_naming_no_role_or_user_fails():+ with pytest.raises(ValueError, match="iam:ListRoles: no member names the role or user"):+ classify([("iam:ListRoles", "iam:PermissionsBoundary")], {"iam:PermissionsBoundary": ["ARN"]}, MODEL)def test_unread_pairs_name_their_reason():- pairs = [("iam:GetRole", "iam:PermissionsBoundary"), ("iam:GetRole", "iam:RoleTemplateARN"),- ("iam:PassRole", "iam:PassedToService"),+ pairs = [("iam:GetRole", "iam:RoleTemplateARN"), ("iam:PassRole", "iam:PassedToService"),("iam:CreateServiceSpecificCredential", "iam:CredentialAgeDays")]- types = {"iam:PermissionsBoundary": ["ARN"], "iam:RoleTemplateARN": ["ARN"],+ types = {"iam:RoleTemplateARN": ["ARN"],"iam:PassedToService": ["String"], "iam:CredentialAgeDays": ["Numeric"]}- read, not_read = classify(pairs, types, MODEL)- assert read == []+ read, from_target, not_read = classify(pairs, types, MODEL)+ assert read == from_target == []assert {(e["action"], e["key"]): e["reason"] for e in not_read} == {("iam:CreateServiceSpecificCredential", "iam:CredentialAgeDays"): "the key's type is Numeric",- ("iam:GetRole", "iam:PermissionsBoundary"): "the value is the target's current permissions boundary",("iam:GetRole", "iam:RoleTemplateARN"): "the value is the role template a service acquires the role from",("iam:PassRole", "iam:PassedToService"): "no SDK operation of this name"}@@ -64,8 +82,8 @@ BY_HAND_TYPES = {"iam:DelegationDuration": ["String"], "iam:TemplateArn": ["ARN"def test_by_hand_pairs_read_their_member_including_a_nested_one():- read, not_read = classify(sorted(regen_iam_condition_keys.BY_HAND), BY_HAND_TYPES, MODEL)- assert not_read == []+ read, from_target, not_read = classify(sorted(regen_iam_condition_keys.BY_HAND), BY_HAND_TYPES, MODEL)+ assert from_target == not_read == []assert {(e["action"], e["key"]): e["member"] for e in read} == regen_iam_condition_keys.BY_HAND@@ -89,7 +107,7 @@ def test_by_hand_pair_the_reference_no_longer_lists_fails():require_by_hand_listed(pairs)-def test_vendored_table_reads_nine_keys_on_fourteen_actions():+def test_vendored_table_reads_nine_keys_on_fourteen_actions_and_the_boundary_of_fifteen_targets():document = json.loads(OUTPUT.read_text())assert {(e["action"], e["key"]) for e in document["read"]} == {*(("iam:" + verb + kind + "Policy", "iam:PolicyARN")@@ -104,8 +122,21 @@ def test_vendored_table_reads_nine_keys_on_fourteen_actions():("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialAgeDays"),("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialServiceName"),("iam:GenerateOrganizationsAccessReport", "iam:OrganizationsPolicyId")}- current = [e["action"] for e in document["notRead"] if e["key"] == "iam:PermissionsBoundary"]- assert len(current) == 15 and "iam:GetRole" in current+ assert not [e for e in document["notRead"] if e["key"] == "iam:PermissionsBoundary"]+ targets = {e["action"]: e["target"] for e in document["fromTarget"]}+ assert len(targets) == 15 and {e["key"] for e in document["fromTarget"]} == {"iam:PermissionsBoundary"}+ assert targets["iam:GetRole"] == "RoleName" and targets["iam:DeleteUserPermissionsBoundary"] == "UserName"+++def test_check_fails_on_a_hand_edited_target(tmp_path, monkeypatch):+ pytest.importorskip("botocore")+ document = json.loads(OUTPUT.read_text())+ document["fromTarget"][0]["target"] = "UserName"+ edited = tmp_path / "iam-condition-keys.json"+ edited.write_text(json.dumps(document))+ monkeypatch.setattr(regen_iam_condition_keys, "OUTPUT", edited)+ with pytest.raises(ValueError, match="differ from pinned botocore"):+ regen_iam_condition_keys.main(["--check"])def test_check_fails_on_a_hand_edited_member(tmp_path, monkeypatch):