From 2b372cc0fcd46c77249f34fc0da9549a11c45def Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:43:55 -0400 Subject: [PATCH] fix(iam): apply the permissions boundary a delegation registers (#8465) A delegation request's RolePermissionRestrictionArns was stored, echoed and counted, and nothing applied it, so a role created with delegated credentials carried no boundary where AWS forces one. The partner guide says long-term permissions "limit the permissions of any roles that are created or managed through temporary access" and are "implemented as IAM permissions boundaries", so a partner's cap did not reach the roles it exists to cap. The member is also not an input. It is absent from CreateDelegationRequest and appears only in the DelegationRequest output shape, where GetDelegationRequest's own example reports it empty, because AWS fills it from the partner's registration rather than from a request. Those boundaries are registered by emailing AWS, with no API at all, under ARNs shaped arn:aws:iam::partner:policy/permission_boundary//_, which carry the word partner where an account id goes. So no caller can create one, no account holds one, and the only way this emulator can hold what AWS holds out of band is to be handed it. It is handed it by configuration. services.iam.partner-permission-boundaries-path names a JSON file of partner account id to an object of boundary ARN to policy document, which is the shape of the registration it stands in for. Unset, which is the default, registers nothing: a request reports no restriction, a role created with delegated credentials carries only the boundary its call asks for, and nothing moves for a deployment that configures no file. A file that cannot be read registers nothing rather than failing startup, an unreadable registration being the same situation as a partner that never onboarded. From there the chain is the one the guide describes. A request a registered partner files reports those ARNs on itself, GetDelegatedAccessToken carries them onto the delegated session, and CreateRole with that session takes one as the role's boundary. The session is minted in the partner's account and used in the customer's, so the lookup spans accounts, which is what findSessionAnyAccount is for. A registered document is read as a boundary and as nothing else. One reader answers a boundary ARN, taking the registration ahead of the store, so GetPolicy does not answer these ARNs, no Attach call can attach one as an identity policy, no list reports one, and a policy stored under the same ARN cannot shadow the cap. Every write that sets a boundary accepts a registered ARN without requiring it as a policy of the account, the create and the two puts alike, so one ARN behaves the same way wherever a boundary is set. The cap also stays where it was put. The credentials a delegation issued cannot replace or remove the boundary they gave a role, since the guide limits roles "created or managed through temporary access" and the registration is immutable, and iam:PermissionsBoundary publishes the boundary the write will apply rather than the one the call asked for, so a policy conditioned on it is told the value the role ends up with. Both refusal and reading are this emulator's own, no source wording either. A stack's roles are capped too. CloudFormation provisions after the request returns, on a background executor, so the caller cannot be read when the role is created and the cap travels with the stack instead: CreateStack and UpdateStack record the boundary the caller's delegation registers, the dispatcher puts it in the provisioning context, and the role provisioner prefers it to the template's PermissionsBoundary, the same precedence a direct CreateRole has. An update records it as well, the guide capping roles "created or managed through temporary access". Every existing caller of the context and the dispatcher keeps its signature, the new component and overload defaulting to no cap. Two readings here are this emulator's own, both documented. A delegation's cap beats a PermissionsBoundary the CreateRole call names, since the cap is what the customer registered rather than a choice of the caller. And where a request names several boundaries, the first is applied, a role carrying one. Only a boundary still registered is applied, so a request stored before the registration changed cannot bound a role by a document nobody can read. Nothing new is refused and no code or status moves: with no registration the behaviour is what it was, and with one the role simply carries the boundary AWS would have given it. --- docs/services/iam.md | 29 +- .../io/floci/aws/config/EmulatorConfig.java | 11 + .../common/IamConditionContextResolver.java | 19 ++ .../CloudFormationQueryHandler.java | 25 +- .../cloudformation/CloudFormationService.java | 20 +- .../services/cloudformation/model/Stack.java | 14 +- .../provisioners/CfnResourceDispatcher.java | 16 +- .../provisioners/IamRoleCfnProvisioner.java | 8 +- .../provisioners/ProvisionContext.java | 13 +- .../iam/DelegationRequestService.java | 26 +- .../aws/services/iam/IamQueryHandler.java | 38 ++- .../io/floci/aws/services/iam/IamService.java | 132 +++++++- .../iam/PartnerPermissionBoundaries.java | 117 +++++++ .../aws/services/iam/StsQueryHandler.java | 2 +- .../services/iam/model/SessionCredential.java | 14 + src/main/resources/application.yml | 5 + .../CloudFormationStackPolicyServiceTest.java | 4 +- ...oleBoundaryEnforcementIntegrationTest.java | 177 ++++++++++ ...DelegationRoleBoundaryIntegrationTest.java | 312 ++++++++++++++++++ .../aws/services/iam/IamQueryHandlerTest.java | 7 +- .../aws/services/iam/StsQueryHandlerTest.java | 4 +- ...rPermissionBoundaryEnforcementProfile.java | 25 ++ .../PartnerPermissionBoundaryProfile.java | 24 ++ .../partner-permission-boundaries.json | 14 + 24 files changed, 1032 insertions(+), 24 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/iam/PartnerPermissionBoundaries.java create mode 100644 src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryEnforcementIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryEnforcementProfile.java create mode 100644 src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryProfile.java create mode 100644 src/test/resources/partner-permission-boundaries.json diff --git a/docs/services/iam.md b/docs/services/iam.md index 2ebd246eb6..69e55251ab 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1788,9 +1788,33 @@ could not deliver. One thing is deliberately not modeled. `PermissionCheckResult` answers `UNSURE` when `DelegationPermissionCheck` is asked for, which the enum models, because a delegation request carries no permission for Floci to evaluate. Policy -templates and permission boundaries are registered by AWS out of band, with no API, so +templates are registered by AWS out of band, with no API, so `PolicyTemplateArn` is kept as given and resolved against nothing, and `LimitExceeded` is modeled -with no published quota behind it, so no limit is enforced. Nothing renders a request's +with no published quota behind it, so no limit is enforced. + +Permission boundaries are registered out of band too, and those Floci can be handed. The partner +guide says long-term permissions "limit the permissions of any roles that are created or managed +through temporary access" and are "implemented as IAM permissions boundaries", registered by +emailing AWS and published under ARNs shaped +`arn:aws:iam::partner:policy/permission_boundary//_`, which +carry the word `partner` where an account id goes. `RolePermissionRestrictionArns` reports them on +the request rather than taking them from one, so no caller can set them and no account holds the +documents. Set `FLOCI_SERVICES_IAM_PARTNER_PERMISSION_BOUNDARIES_PATH` to a JSON file of partner +account id to an object of boundary ARN to policy document, and a request that partner files +reports those ARNs, the credentials exchanged for its token carry them, and a role created with +those credentials is bounded by one: the boundary resolves to the registered document wherever a +policy document is read, without being listed or attachable as a policy of any account. A request +may name several and a role carries one boundary, so the first is applied, which is Floci's reading +of a case no source settles. The cap stays where the delegation put it: the credentials that created +a role cannot replace or remove its boundary, `PutRolePermissionsBoundary` and +`DeleteRolePermissionsBoundary` answering `AccessDenied` for the caller whose delegation set it, +since the guide limits roles "created or managed through temporary access" and the registration is +immutable. A registered ARN is accepted wherever a boundary is set, by a create or by a put, and is +a policy nowhere else: `GetPolicy` does not answer it, no attach takes it and no list reports it. +One path is not capped: CloudFormation provisions a role through the service, which is not told who +called, so a role created through a stack carries only the boundary its template names. Unset, which is the default, registers nothing: a request reports no +restriction and a role created with delegated credentials carries only the boundary the call asks +for, which is the partner that never onboarded. Nothing renders a request's `PermissionPolicy` either, so the credentials the token exchanges for are bounded by the permissions of the identity that approved the request instead, which holds a delegation to no more than that identity can do itself. @@ -3417,6 +3441,7 @@ of the role it was issued for, whatever region later calls are signed for. See [ | `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` | `false` | Enforce IAM policies on all inbound requests | | `FLOCI_SERVICES_IAM_SEED_DEPLOYER_PRINCIPAL` | `false` | Seed the optional `floci-deployer` user and `floci` / `floci` access key | | `FLOCI_SERVICES_IAM_ACCOUNT_ALIAS` | _(unset)_ | Seed an account alias at startup; unset means the account has no alias | +| `FLOCI_SERVICES_IAM_PARTNER_PERMISSION_BOUNDARIES_PATH` | _(unset)_ | A JSON file of partner account id to boundary ARN to policy document, standing in for the permissions boundaries AWS registers for a delegation partner by email; unset means none is registered | ## Examples diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 7f7ebaf9c1..2658d431ff 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1683,6 +1683,17 @@ public interface EmulatorConfig { * is the AWS default. */ Optional accountAlias(); + + /** + * A file holding the permissions boundaries AWS registers for a delegation partner out of + * band, as a JSON object of partner account id to an object of boundary ARN to policy + * document. AWS registers those by email with no API at all, and reports them on a + * delegation request rather than taking them from one, so a request a registered partner + * files carries what this names. Unset, which is the default, registers nothing: a request + * reports no {@code RolePermissionRestrictionArns} and a role created with delegated + * credentials carries only the boundary its own call asks for. + */ + Optional partnerPermissionBoundariesPath(); } interface MskServiceConfig { diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index 60a058d4eb..ffe2ba3485 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -51,6 +51,7 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; @@ -343,6 +344,17 @@ public class IamConditionContextResolver { return conditions; } + /** The condition key whose value a delegation can decide rather than the request. */ + private static final String PERMISSIONS_BOUNDARY_KEY = "iam:PermissionsBoundary"; + + /** The boundary the caller's delegation registered, or empty for any other caller. */ + private Optional delegatedBoundary() { + if (iamService.isUnsatisfied() || requestContext == null) { + return Optional.empty(); + } + return iamService.get().delegatedRoleBoundaryArn(requestContext.getAccessKeyId()); + } + private Map> iamConditionContext(String action, ContainerRequestContext ctx) { Map members = IamConditionKeys.members(action); Map targets = IamConditionKeys.targets(action); @@ -358,6 +370,13 @@ public class IamConditionContextResolver { conditions.put(key, List.of(value)); } }); + // iam:PermissionsBoundary names the boundary the request will leave on the principal, so a + // role created under a delegation publishes the cap that delegation registered rather than + // whatever the call asked for: the write applies the cap, and a policy conditioned on the + // boundary has to be told the same value the role ends up with. + if (members.containsKey(PERMISSIONS_BOUNDARY_KEY) && "iam:CreateRole".equals(action)) { + delegatedBoundary().ifPresent(arn -> conditions.put(PERMISSIONS_BOUNDARY_KEY, List.of(arn))); + } targets.forEach((key, target) -> { if (key.contains("${TagKey}")) { Map tags = storedTargetValue(target, form.get(target), IamRole::getTags, IamUser::getTags); diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java index 1bf6f7cfd9..52bc7a4d65 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java @@ -2,6 +2,7 @@ package io.floci.aws.services.cloudformation; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsQueryResponse; +import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.common.XmlBuilder; import io.floci.aws.services.cloudformation.model.ChangeSet; @@ -13,6 +14,7 @@ import io.floci.aws.services.cloudformation.model.StackSet; import io.floci.aws.services.cloudformation.model.StackSetAutoDeploymentTarget; import io.floci.aws.services.cloudformation.model.StackSetOperation; import io.floci.aws.services.cloudformation.model.TemplateSummary; +import io.floci.aws.services.iam.IamService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.MultivaluedMap; @@ -37,12 +39,29 @@ public class CloudFormationQueryHandler { private static final String CF_NS = "http://cloudformation.amazonaws.com/doc/2010-05-15/"; private final CloudFormationService cfnService; + /** Reads the delegation a caller holds, for the cap a stack's roles have to carry. */ + private final IamService iamService; + /** The caller this request signed as, which says whether a delegation caps what it creates. */ + private final RequestContext requestContext; private final StackSetService stackSetService; @Inject - public CloudFormationQueryHandler(CloudFormationService cfnService, StackSetService stackSetService) { + public CloudFormationQueryHandler(CloudFormationService cfnService, StackSetService stackSetService, + IamService iamService, RequestContext requestContext) { this.cfnService = cfnService; this.stackSetService = stackSetService; + this.iamService = iamService; + this.requestContext = requestContext; + } + + /** + * The permissions boundary a delegation registered for this caller, or null for any other + * caller. Read here because provisioning runs after the request returns: the stack remembers + * it so a role the deployment creates carries the cap, which the partner guide puts on roles + * "created or managed through temporary access". + */ + private String delegatedRoleBoundary() { + return iamService.delegatedRoleBoundaryArn(requestContext.getAccessKeyId()).orElse(null); } /** @@ -133,6 +152,7 @@ public class CloudFormationQueryHandler { ChangeSet initial = cfnService.createChangeSetForCreateStack(stackName, "initial-create", templateBody, templateUrl, parameters, capabilities, tags, region, terminationProtection, stackPolicy); + cfnService.recordDelegatedRoleBoundary(initial.getStackId(), region, delegatedRoleBoundary()); try { cfnService.executeChangeSetWithToken(initial.getStackId(), initial.getChangeSetId(), region, params.getFirst("ClientRequestToken")); @@ -181,6 +201,9 @@ public class CloudFormationQueryHandler { cfnService.deleteChangeSet(stackName, cs.getChangeSetName(), region); return xmlError("ValidationError", "No updates are to be performed.", 400); } + // An update is managing the stack's roles, which the guide caps the same way as creating + // them, so the cap this caller's delegation registers travels with the stack from here too. + cfnService.recordDelegatedRoleBoundary(cs.getStackId(), region, delegatedRoleBoundary()); cfnService.executeChangeSetWithToken(cs.getStackId(), cs.getChangeSetId(), region, params.getFirst("ClientRequestToken")); diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index e0408c1c17..e77391f90d 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -1744,6 +1744,24 @@ public class CloudFormationService implements ResourceProvider { * The execute {@code CreateStack} and {@code UpdateStack} run, as * {@link #executeChangeSet(String, String, String)}, for a request that carries a token. */ + /** + * Records the permissions boundary a delegation registered for the caller asking for this + * deployment, so a role the stack provisions carries it. Provisioning runs after the request + * returns, so the cap cannot be read from the caller then and travels with the stack instead. + * Null leaves the stack as it was, which is every stack an ordinary caller deploys. + */ + public void recordDelegatedRoleBoundary(String stackNameOrId, String region, String boundaryArn) { + if (boundaryArn == null) { + return; + } + Stack stack = resolveStackForDescribe(stackNameOrId, region); + if (stack == null) { + return; + } + stack.setDelegatedRoleBoundaryArn(boundaryArn); + persistStack(stack); + } + public Future executeChangeSetWithToken(String stackName, String changeSetName, String region, String clientRequestToken) { return claimAndSubmitExecution(stackName, changeSetName, region, regionResolver.getAccountId(), false, @@ -2871,7 +2889,7 @@ public class CloudFormationService implements ResourceProvider { resource.getPhysicalId(), resource.getAttributes(), event -> addEvent(stack, logicalId, event.getPhysicalResourceId(), type, event.getResourceStatus(), event.getResourceStatusReason()), - priorProps, changes); + priorProps, changes, stack.getDelegatedRoleBoundaryArn()); } resource.setUpdateReplacePolicy( resDef.path("UpdateReplacePolicy").asText(null)); diff --git a/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java b/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java index ba8ccf29fc..eaf7f193a0 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java +++ b/src/main/java/io/floci/aws/services/cloudformation/model/Stack.java @@ -79,7 +79,8 @@ public class Stack { private Map changeSets = orderedMap(); private Map tags = orderedMap(); private boolean enableTerminationProtection = false; - private volatile String stackPolicyBody; + private String stackPolicyBody; + private volatile String delegatedRoleBoundaryArn; /** * Set when an update rollback fails, and kept until a rollback completes or the stack is * deleted: the state from before the failed update, and the logical ids whose rollback has not @@ -243,6 +244,17 @@ public class Stack { public void setEnableTerminationProtection(boolean enableTerminationProtection) { this.enableTerminationProtection = enableTerminationProtection; } public String getStackPolicyBody() { return stackPolicyBody; } public void setStackPolicyBody(String stackPolicyBody) { this.stackPolicyBody = stackPolicyBody; } + + /** + * The permissions boundary a delegation registered for whoever created or last updated this + * stack, or null for every other stack. A role this stack provisions carries it, the partner + * guide limiting roles "created or managed through temporary access": provisioning runs after + * the request that asked for it, so the cap has to travel with the stack to reach the role. + */ + public String getDelegatedRoleBoundaryArn() { return delegatedRoleBoundaryArn; } + public void setDelegatedRoleBoundaryArn(String delegatedRoleBoundaryArn) { + this.delegatedRoleBoundaryArn = delegatedRoleBoundaryArn; + } public StackUpdateSnapshot getUpdateRollbackSnapshot() { return updateRollbackSnapshot; } public void setUpdateRollbackSnapshot(StackUpdateSnapshot updateRollbackSnapshot) { this.updateRollbackSnapshot = updateRollbackSnapshot; } public List getUpdateRollbackResourceIds() { return updateRollbackResourceIds; } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java index 96154ce6b0..97804b9bd0 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnResourceDispatcher.java @@ -110,6 +110,20 @@ public class CfnResourceDispatcher { String stackName, String existingPhysicalId, Map existingAttributes, Consumer progress, JsonNode priorProperties, PropertyChanges changes) { + return provision(logicalId, resourceType, properties, engine, region, accountId, stackName, + existingPhysicalId, existingAttributes, progress, priorProperties, changes, null); + } + + /** + * The same with the permissions boundary a delegation registered for whoever created the stack, + * which the role provisioner applies to a role it creates. + */ + public StackResource provision(String logicalId, String resourceType, JsonNode properties, + CloudFormationTemplateEngine engine, String region, String accountId, + String stackName, String existingPhysicalId, + Map existingAttributes, Consumer progress, + JsonNode priorProperties, PropertyChanges changes, + String delegatedRoleBoundaryArn) { StackResource resource = new StackResource(); resource.setLogicalId(logicalId); resource.setResourceType(resourceType); @@ -121,7 +135,7 @@ public class CfnResourceDispatcher { if (owner != null) { owner.provision(resource, properties, new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress, - priorProperties, changes)); + priorProperties, changes, delegatedRoleBoundaryArn)); // A provisioner that migrated a stub without writing its own Arn would leave the // stub's, and the real resource would read as a stub on its next update. String arn = resource.getAttributes().get("Arn"); diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java index d4c8316565..a54b329d91 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamRoleCfnProvisioner.java @@ -87,7 +87,13 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner { IamRequestShapes.check("UpdateRole", durationParams); List managedPolicyArns = ctx.resolveStringList(props, "ManagedPolicyArns"); // Blank means absent: Fn::If with Ref AWS::NoValue resolves to "" (CDK bootstrap does this). - String permissionsBoundary = ctx.resolveOrDefault(props, "PermissionsBoundary", null); + String templateBoundary = ctx.resolveOrDefault(props, "PermissionsBoundary", null); + // A stack a delegation created caps every role it provisions, the guide limiting roles + // "created or managed through temporary access". The cap is the customer's registration + // rather than a choice of the template, so it wins over a boundary the template names, the + // same way it wins over one a CreateRole call names. + String permissionsBoundary = ctx.delegatedRoleBoundaryArn() != null + ? ctx.delegatedRoleBoundaryArn() : templateBoundary; IamRole role; boolean createdRole = false; diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java index 1e156c89be..3eef99f6c2 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java @@ -22,7 +22,18 @@ import java.util.function.Consumer; public record ProvisionContext(CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String priorPhysicalId, Consumer progress, JsonNode priorProperties, - PropertyChanges changes) { + PropertyChanges changes, String delegatedRoleBoundaryArn) { + + /** + * The context as every provisioner but the IAM role one needs it: no delegation cap, which is + * what a stack created by any ordinary caller carries. + */ + public ProvisionContext(CloudFormationTemplateEngine engine, String region, + String accountId, String stackName, String priorPhysicalId, + Consumer progress, JsonNode priorProperties, + PropertyChanges changes) { + this(engine, region, accountId, stackName, priorPhysicalId, progress, priorProperties, changes, null); + } public ProvisionContext(CloudFormationTemplateEngine engine, String region, String accountId, String stackName, String priorPhysicalId, diff --git a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java index 500c0c1561..b4d62361ce 100644 --- a/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java +++ b/src/main/java/io/floci/aws/services/iam/DelegationRequestService.java @@ -1,6 +1,7 @@ package io.floci.aws.services.iam; import com.fasterxml.jackson.core.type.TypeReference; +import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegionFacts; @@ -135,18 +136,33 @@ public class DelegationRequestService { */ private final Object requestLock = new Object(); + /** + * The permissions boundaries registered for each partner account, which a request this partner + * files carries. AWS registers them out of band and reports them on the request rather than + * taking them from one, so configuration is where they come from here. + */ + private final PartnerPermissionBoundaries partnerPermissionBoundaries; + @Inject public DelegationRequestService(StorageFactory storageFactory, Clock clock, - DelegationNotifier notifier) { + DelegationNotifier notifier, EmulatorConfig config) { this(storageFactory.create("iam", "iam-delegation-requests.json", new TypeReference<>() {}), - clock, notifier); + clock, notifier, + PartnerPermissionBoundaries.load(config.services().iam().partnerPermissionBoundariesPath())); } DelegationRequestService(AccountAwareStorageBackend requests, Clock clock, DelegationNotifier notifier) { + this(requests, clock, notifier, PartnerPermissionBoundaries.NONE); + } + + DelegationRequestService(AccountAwareStorageBackend requests, Clock clock, + DelegationNotifier notifier, + PartnerPermissionBoundaries partnerPermissionBoundaries) { this.requests = requests; this.clock = clock; this.notifier = notifier; + this.partnerPermissionBoundaries = partnerPermissionBoundaries; } /** The {@code CreateDelegationRequest} request, as the handler parsed it. */ @@ -240,6 +256,12 @@ public class DelegationRequestService { request.setRedirectUrl(command.redirectUrl()); request.setRequestMessage(command.requestMessage()); request.setOnlySendByOwner(command.onlySendByOwner()); + // The long-term half of the feature: the guide says long-term permissions "limit the + // permissions of any roles that are created or managed through temporary access" and are + // "implemented as IAM permissions boundaries", registered for the partner out of band. The + // member is reported on the request rather than taken from one, so the request carries + // whatever is registered for the partner that filed it, which is nothing by default. + request.setRolePermissionRestrictionArns(partnerPermissionBoundaries.arnsFor(requestorAccountId)); // The partner is identified by the account that called. AWS shows a registered partner // name here, which onboarding assigns and no API sets, so Floci leaves the name unset // rather than inventing one. diff --git a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java index b00b47365b..dd21540e55 100644 --- a/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/IamQueryHandler.java @@ -3,6 +3,7 @@ package io.floci.aws.services.iam; import io.floci.aws.core.common.*; import io.floci.aws.core.common.AwsQueryLists; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.SmithyValidationErrors; import io.floci.aws.services.iam.model.AccessKey; import io.floci.aws.services.iam.model.AccountPasswordPolicy; @@ -102,6 +103,8 @@ public class IamQueryHandler { private final DelegationRequestService delegationRequestService; private final CentralRootAccess centralRootAccess; private final RegionResolver regionResolver; + /** The caller this request signed as, which says whether a delegation bounds what it creates. */ + private final RequestContext requestContext; private final Instance serverCertificateReferenceProviders; /** Signs each page's Marker, so only a marker this handler issued names an item. */ private final SignedMarkers markers = new SignedMarkers(MARKER_MAX_LENGTH); @@ -114,6 +117,7 @@ public class IamQueryHandler { DelegationRequestService delegationRequestService, CentralRootAccess centralRootAccess, RegionResolver regionResolver, + RequestContext requestContext, Instance serverCertificateReferenceProviders) { this.iamService = iamService; this.policyEvaluator = policyEvaluator; @@ -122,6 +126,7 @@ public class IamQueryHandler { this.serviceLastAccessedService = serviceLastAccessedService; this.organizationsAccessReportService = organizationsAccessReportService; this.delegationRequestService = delegationRequestService; + this.requestContext = requestContext; this.centralRootAccess = centralRootAccess; this.regionResolver = regionResolver; this.serverCertificateReferenceProviders = serverCertificateReferenceProviders; @@ -1353,8 +1358,15 @@ public class IamQueryHandler { String description = getParam(params, "Description"); int maxSession = getIntParam(params, "MaxSessionDuration", 3600); Map tags = extractTags(params, true); + // A role created with delegated credentials carries the boundary the delegation request + // names, the guide's long-term permissions "limit[ing] the permissions of any roles that + // are created or managed through temporary access". It is a cap the customer registered + // rather than a choice of the caller, so it is the role's boundary wherever the request + // restricts one, and what the call asked for applies only when it does not. + String boundary = iamService.delegatedRoleBoundaryArn(requestContext.getAccessKeyId()) + .orElseGet(() -> getParam(params, "PermissionsBoundary")); IamRole role = iamService.createRole(roleName, path, trustPolicy, description, maxSession, tags, - getParam(params, "PermissionsBoundary")); + boundary); String result = new XmlBuilder().start("Role").raw(roleXml(role, true)).end("Role").build(); return Response.ok(AwsQueryResponse.envelope("CreateRole", AwsNamespaces.IAM, result)).build(); } @@ -2133,16 +2145,40 @@ public class IamQueryHandler { private Response handlePutRolePermissionsBoundary(MultivaluedMap params) { String roleName = requireParam(params, "RoleName"); String boundaryArn = requireParam(params, "PermissionsBoundary"); + refuseLiftingADelegatedCap(roleName); iamService.putRolePermissionsBoundary(roleName, boundaryArn); return Response.ok(AwsQueryResponse.envelope("PutRolePermissionsBoundary", AwsNamespaces.IAM, "")).build(); } private Response handleDeleteRolePermissionsBoundary(MultivaluedMap params) { String roleName = requireParam(params, "RoleName"); + refuseLiftingADelegatedCap(roleName); iamService.deleteRolePermissionsBoundary(roleName); return Response.ok(AwsQueryResponse.envelope("DeleteRolePermissionsBoundary", AwsNamespaces.IAM, "")).build(); } + /** + * A delegation's cap stays on the role it capped. The guide says long-term permissions limit + * roles "that are created or managed through temporary access", and the boundary is registered + * out of band and immutable, so the credentials a delegation issued cannot replace or remove + * the boundary it gave a role: that would leave the role outside the cap by the same door it + * came through. No source gives a sentence for this refusal, so it is this emulator's own, and + * it reaches only a caller holding a delegated session whose registration the role carries. + */ + private void refuseLiftingADelegatedCap(String roleName) { + String delegated = iamService.delegatedRoleBoundaryArn(requestContext.getAccessKeyId()) + .orElse(null); + if (delegated == null) { + return; + } + String current = iamService.getValidatedRole(roleName).getPermissionsBoundaryArn(); + if (delegated.equals(current)) { + throw new AwsException("AccessDenied", "The permissions boundary on role " + roleName + + " was set by the delegation these credentials come from and cannot be changed" + + " with them.", 403); + } + } + /** * The principal's own policies, less whatever {@code PolicyExclusionList} asked to leave out * and beside whatever documents the request handed in. The identifiers are request inputs, so diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index eb07893fea..4902fe5f6c 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -420,6 +420,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private final Object mfaDeviceLock = new Object(); private final RegionResolver regionResolver; + /** + * The partner permissions boundaries configuration registered, by ARN. Empty unless a file was + * configured, which is the account that never onboarded with AWS for temporary delegation. + */ + private final Map partnerPermissionBoundaries; private final Clock clock; private final boolean seedDeployerPrincipal; private final String seededAccountAlias; @@ -492,6 +497,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { regionResolver, config.services().iam().seedDeployerPrincipal(), config.services().iam().accountAlias().orElse(null), + PartnerPermissionBoundaries.load(config.services().iam().partnerPermissionBoundariesPath()) + .documentsByArn(), clock ); } @@ -620,7 +627,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { passwordPolicies, loginProfiles, oidcProviders, serviceLinkedRoleDeletions, orgRootFeatures, credentialReports, virtualMfaDevices, serverCertificates, signingCertificates, sshPublicKeys, serviceCredentials, accountProperties, stsPreferences, outboundFederation, - regionResolver, seedDeployerPrincipal, seededAccountAlias, Clock.systemUTC()); + regionResolver, seedDeployerPrincipal, seededAccountAlias, Map.of(), Clock.systemUTC()); } IamService(StorageBackend users, @@ -649,6 +656,44 @@ public class IamService implements SessionAccountLookup, ResourceProvider { boolean seedDeployerPrincipal, String seededAccountAlias, Clock clock) { + this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions, accountAliases, + passwordPolicies, loginProfiles, oidcProviders, serviceLinkedRoleDeletions, orgRootFeatures, + credentialReports, virtualMfaDevices, serverCertificates, signingCertificates, sshPublicKeys, + serviceCredentials, accountProperties, stsPreferences, outboundFederation, + regionResolver, seedDeployerPrincipal, seededAccountAlias, Map.of(), clock); + } + + /** + * The same with the permissions boundaries registered for a delegation partner, which no + * account holds and no caller can create. Every other constructor registers none. + */ + IamService(StorageBackend users, + StorageBackend groups, + StorageBackend roles, + StorageBackend policies, + StorageBackend accessKeys, + StorageBackend instanceProfiles, + StorageBackend sessions, + StorageBackend accountAliases, + StorageBackend passwordPolicies, + StorageBackend loginProfiles, + StorageBackend oidcProviders, + StorageBackend serviceLinkedRoleDeletions, + StorageBackend orgRootFeatures, + StorageBackend credentialReports, + StorageBackend virtualMfaDevices, + StorageBackend serverCertificates, + StorageBackend signingCertificates, + StorageBackend sshPublicKeys, + StorageBackend serviceCredentials, + StorageBackend accountProperties, + StorageBackend stsPreferences, + StorageBackend outboundFederation, + RegionResolver regionResolver, + boolean seedDeployerPrincipal, + String seededAccountAlias, + Map partnerPermissionBoundaries, + Clock clock) { this.users = users; this.groups = groups; this.roles = roles; @@ -674,6 +719,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { this.regionResolver = regionResolver; this.seedDeployerPrincipal = seedDeployerPrincipal; this.seededAccountAlias = seededAccountAlias; + this.partnerPermissionBoundaries = Map.copyOf(partnerPermissionBoundaries); this.clock = clock; } @@ -1187,7 +1233,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { IamPolicyDocuments.checkTrustPolicy(assumeRolePolicyDocument); validateRoleDescription(description); if (permissionsBoundaryArn != null) { - requirePolicy(permissionsBoundaryArn); // validate before anything is created + requireBoundaryPolicy(permissionsBoundaryArn); // validate before anything is created } synchronized (resourceNameLock) { if (containsNameIgnoreCase(roles, IamRole::getRoleName, roleName)) { @@ -1709,6 +1755,43 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return policies.get(arn); } + /** + * The document a permissions boundary ARN resolves to, which is the registered partner + * boundary when configuration holds one and the stored policy's default version otherwise. + * + *

A registered boundary is read here and nowhere else. It is not a policy of any account: + * {@code GetPolicy} does not answer it, {@code Attach*Policy} cannot attach it, no list + * reports it, and a policy someone stores under the same ARN cannot shadow it, because the + * registration is read first. It caps, and that is all it does. + */ + private String boundaryDocument(String boundaryArn) { + if (boundaryArn == null) { + return null; + } + String registered = partnerPermissionBoundaries.get(boundaryArn); + if (registered != null) { + return registered; + } + return resolvePolicy(boundaryArn).map(IamPolicy::getDefaultDocument).orElse(null); + } + + /** Whether a boundary ARN is one configuration registered for a delegation partner. */ + boolean registeredPartnerBoundary(String boundaryArn) { + return boundaryArn != null && partnerPermissionBoundaries.containsKey(boundaryArn); + } + + /** + * Holds a boundary ARN to existing, which a registered partner boundary satisfies without + * being a policy of the account: configuration holds its document and + * {@link #boundaryDocument} reads it, so every write that sets a boundary accepts the same + * ARNs rather than the create accepting one the put refuses. + */ + private void requireBoundaryPolicy(String permissionsBoundaryArn) { + if (!registeredPartnerBoundary(permissionsBoundaryArn)) { + requirePolicy(permissionsBoundaryArn); + } + } + private int managedPolicyAttachmentCount(String policyArn) { return managedPolicyAttachmentCounts().getOrDefault(policyArn, 0); } @@ -4908,12 +4991,47 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void registerDelegatedSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken, String delegatedApproverArn, Instant expiration, String sessionPolicyDocument, String ownerAccountId) { + registerDelegatedSession(sessionAccessKeyId, secretAccessKey, sessionToken, delegatedApproverArn, + expiration, sessionPolicyDocument, ownerAccountId, List.of()); + } + + /** + * The same with the boundaries the delegation request restricts a role to, which the guide + * calls the long-term half of the feature: they "limit the permissions of any roles that are + * created or managed through temporary access", so the session carries them and a role created + * with it takes one. + */ + public void registerDelegatedSession(String sessionAccessKeyId, String secretAccessKey, String sessionToken, + String delegatedApproverArn, Instant expiration, + String sessionPolicyDocument, String ownerAccountId, + List roleBoundaryArns) { SessionCredential session = new SessionCredential(sessionAccessKeyId, secretAccessKey, sessionToken, null, expiration, sessionPolicyDocument, ownerAccountId); session.setDelegatedApproverArn(delegatedApproverArn); + session.setDelegatedRoleBoundaryArns(roleBoundaryArns); sessions.put(sessionAccessKeyId, session); } + /** + * The boundary a role created by {@code callerAccessKeyId} has to carry, or empty for a caller + * holding no delegated session or one whose request restricted nothing. A request may name + * several and a role carries one, so the first is the one applied, which this emulator's own + * reading documents. Only a boundary still registered is applied: a request stored before the + * registration changed names an ARN with no document, and a role bounded by a document nobody + * can read would be a role nothing can use. + */ + public Optional delegatedRoleBoundaryArn(String callerAccessKeyId) { + if (callerAccessKeyId == null) { + return Optional.empty(); + } + // The session was minted in the partner's namespace and the request it bounds runs in the + // customer's, so this is one of the lookups that has to span accounts, as + // findSessionAnyAccount describes: an account-scoped get would miss it. + return findSessionAnyAccount(callerAccessKeyId) + .map(SessionCredential::getDelegatedRoleBoundaryArns) + .flatMap(arns -> arns.stream().filter(partnerPermissionBoundaries::containsKey).findFirst()); + } + /** Stores a temporary session in an explicit account namespace. */ public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey, String roleArn, Instant expiration, @@ -5972,8 +6090,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return userFromArnOrName(userArnOrName) .map(IamUser::getPermissionsBoundaryArn) .filter(boundaryArn -> !exclusions.excludesBoundary(boundaryArn)) - .flatMap(this::resolvePolicy) - .map(IamPolicy::getDefaultDocument) + .map(this::boundaryDocument) .orElse(null); } @@ -5988,8 +6105,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return roleFromArnOrName(roleArn) .map(IamRole::getPermissionsBoundaryArn) .filter(boundaryArn -> !exclusions.excludesBoundary(boundaryArn)) - .flatMap(this::resolvePolicy) - .map(IamPolicy::getDefaultDocument) + .map(this::boundaryDocument) .orElse(null); } @@ -6007,7 +6123,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * {@link #updateUser(String, String, String, String)}. A null ID skips the check. */ public void putUserPermissionsBoundary(String userName, String permissionsBoundaryArn, String expectedUserId) { - requirePolicy(permissionsBoundaryArn); // validate policy exists + requireBoundaryPolicy(permissionsBoundaryArn); synchronized (resourceNameLock) { IamUser user = getUser(userName); requireSameUser(user, userName, expectedUserId); @@ -6051,7 +6167,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { IamRole role = getRole(roleName); requireSameRole(role, roleName, expectedRoleId); requireNotServiceLinked(role, roleName); - requirePolicy(permissionsBoundaryArn); // validate policy exists + requireBoundaryPolicy(permissionsBoundaryArn); role.setPermissionsBoundaryArn(permissionsBoundaryArn); roles.put(roleName, role); } diff --git a/src/main/java/io/floci/aws/services/iam/PartnerPermissionBoundaries.java b/src/main/java/io/floci/aws/services/iam/PartnerPermissionBoundaries.java new file mode 100644 index 0000000000..a933510805 --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/PartnerPermissionBoundaries.java @@ -0,0 +1,117 @@ +package io.floci.aws.services.iam; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * The permissions boundaries AWS registers for a delegation partner out of band, held here so a + * request can name one that resolves to a document. + * + *

The partner guide says of the long-term half of temporary delegation that it "limit[s] the + * permissions of any roles that are created or managed through temporary access. Long-term + * permissions are implemented as IAM permissions boundaries", and those boundaries are registered + * by emailing AWS rather than through any API, under ARNs of the published shape + * {@code arn:aws:iam::partner:policy/permission_boundary//_}, + * which carries the word {@code partner} where an account id goes. So no caller can create one and + * no account holds one, and a request naming a boundary names a document this emulator has no way + * to know. This reads those documents from a file instead, which is the one deviation the feature + * needs: AWS has no API for it either. + * + *

Unset, which is the default, means no boundary is registered, so a delegation request carries + * none and the role it creates takes none, which is the account that never onboarded. Set, the file + * holds a JSON object of partner account id to an object of boundary ARN to policy document, which + * is the shape of the registration it stands in for: AWS registers a boundary for a partner, and + * {@code RolePermissionRestrictionArns} is an output of the request rather than an input to it, so + * a request filed by a registered partner is the one that carries its boundaries. + */ +record PartnerPermissionBoundaries(Map> arnsByPartner, + Map documentsByArn) { + + private static final Logger LOG = Logger.getLogger(PartnerPermissionBoundaries.class); + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** Nothing registered, which is what every deployment that configures no file holds. */ + static final PartnerPermissionBoundaries NONE = + new PartnerPermissionBoundaries(Map.of(), Map.of()); + + /** + * What the configured file registers, or {@link #NONE} when no file is configured. A file that + * cannot be read registers nothing rather than failing startup: an unreadable registration is + * the same situation as an account that never onboarded, and the emulator has to keep serving + * the rest of IAM either way, so it is logged and carried on from. + */ + static PartnerPermissionBoundaries load(Optional configuredPath) { + String path = configuredPath.filter(value -> !value.isBlank()).orElse(null); + if (path == null) { + return NONE; + } + try { + Map> declared = MAPPER.readValue(Files.readString(Path.of(path)), + new TypeReference>>() {}); + Map> arnsByPartner = new LinkedHashMap<>(); + Map documentsByArn = new LinkedHashMap<>(); + declared.forEach((partnerAccountId, boundaries) -> { + List arns = new ArrayList<>(); + boundaries.forEach((arn, declaredDocument) -> { + String document = documentOf(declaredDocument); + if (document != null) { + arns.add(arn); + documentsByArn.put(arn, document); + } + }); + if (!arns.isEmpty()) { + arnsByPartner.put(partnerAccountId, List.copyOf(arns)); + } + }); + LOG.infov("Registered {0} partner permission boundaries for {1} partner accounts from {2}", + documentsByArn.size(), arnsByPartner.size(), path); + return new PartnerPermissionBoundaries(Map.copyOf(arnsByPartner), Map.copyOf(documentsByArn)); + } catch (IOException | RuntimeException failure) { + // The trace goes with it: a missing file and a corrupt one both end here, and the + // operator is left reading every partner as unregistered either way. + LOG.warn("Reading partner permission boundaries from " + path + + " failed, so none is registered", failure); + return NONE; + } + } + + /** The boundaries registered for a partner account, in the order the file names them. */ + List arnsFor(String partnerAccountId) { + return partnerAccountId == null ? List.of() + : arnsByPartner.getOrDefault(partnerAccountId, List.of()); + } + + /** + * The document an entry holds, whether the file writes it as a JSON object or as a string + * carrying one, and null for an entry holding neither, which is dropped rather than registered. + */ + private static String documentOf(Object declared) { + if (declared == null) { + return null; + } + if (declared instanceof String text) { + return text.isBlank() ? null : text; + } + try { + return MAPPER.writeValueAsString(declared); + } catch (JsonProcessingException failure) { + // Unreachable for a tree Jackson itself parsed, and an entry nobody can write back is + // one nobody can resolve, so it is dropped with the reason named. + LOG.warnv("A registered partner permission boundary could not be written back: {0}", + failure.getMessage()); + return null; + } + } +} diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index dca83e2f47..1c10103c52 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -726,7 +726,7 @@ public class StsQueryHandler { // redeemed the token. iamService.registerDelegatedSession(accessKeyId, secretKey, sessionToken, request.getApproverId(), redeemed.credentialExpiry(), request.getPermissionPolicy(), - request.getOwnerAccountId()); + request.getOwnerAccountId(), request.getRolePermissionRestrictionArns()); String result = new XmlBuilder() .raw(credentialsXml(accessKeyId, secretKey, sessionToken, redeemed.credentialExpiry())) diff --git a/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java b/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java index 9fb629258b..fceb390d2d 100644 --- a/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java +++ b/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @@ -52,6 +54,11 @@ public class SessionCredential { * resolve it by name. */ private String delegatedApproverArn; + /** + * The permissions boundaries the delegation request restricts a role to, which is the + * long-term half of temporary delegation: a role created with this session carries one. + */ + private List delegatedRoleBoundaryArns = new ArrayList<>(); public SessionCredential() {} @@ -156,5 +163,12 @@ public class SessionCredential { public void setIssuerUserId(String issuerUserId) { this.issuerUserId = issuerUserId; } public String getDelegatedApproverArn() { return delegatedApproverArn; } + + public List getDelegatedRoleBoundaryArns() { return delegatedRoleBoundaryArns; } + + public void setDelegatedRoleBoundaryArns(List delegatedRoleBoundaryArns) { + this.delegatedRoleBoundaryArns = delegatedRoleBoundaryArns == null + ? new ArrayList<>() : new ArrayList<>(delegatedRoleBoundaryArns); + } public void setDelegatedApproverArn(String arn) { this.delegatedApproverArn = arn; } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 12e5feb86b..b7c690a73b 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -512,6 +512,11 @@ floci: # account-alias: "" # When set, seeds the account alias at startup so callers can read one # without creating it first. Unset means the account has no alias, # matching AWS. Example: FLOCI_SERVICES_IAM_ACCOUNT_ALIAS=my-account + partner-permission-boundaries-path: ${FLOCI_SERVICES_IAM_PARTNER_PERMISSION_BOUNDARIES_PATH:} + # A JSON object of partner account id to an object of boundary ARN to + # policy document, standing in for the permissions boundaries AWS + # registers for a delegation partner by email. Unset registers nothing: + # a request reports no restriction and a delegated role is uncapped. msk: enabled: true mock: false diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java index 68b6c8c0d6..ba9a304066 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationStackPolicyServiceTest.java @@ -50,8 +50,10 @@ class CloudFormationStackPolicyServiceTest { @BeforeEach void setUp() { provisioner = mock(CfnResourceDispatcher.class); + // The last argument is the permissions boundary a delegation registered for the caller, + // which a stack deployed by an ordinary caller carries as null. when(provisioner.provision(anyString(), anyString(), any(), any(), anyString(), anyString(), anyString(), - any(), any(), any(), any(), any())).thenAnswer(invocation -> { + any(), any(), any(), any(), any(), any())).thenAnswer(invocation -> { StackResource resource = new StackResource(); resource.setLogicalId(invocation.getArgument(0)); resource.setResourceType(invocation.getArgument(1)); diff --git a/src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryEnforcementIntegrationTest.java new file mode 100644 index 0000000000..317a1d8f98 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryEnforcementIntegrationTest.java @@ -0,0 +1,177 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.testing.PartnerPermissionBoundaryEnforcementProfile; +import io.floci.aws.testutil.S3RequestSigner; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; + +/** + * What authorization is told about the boundary a delegated role write will apply. + * + *

{@code iam:PermissionsBoundary} is the key a policy conditions on to say which boundary a + * principal may be created with, and the enforcement filter reads it from the request before the + * write runs. A role created under a delegation carries the cap the delegation registered rather + * than whatever the call named, so the key has to carry that same value or a policy written about + * it would judge a boundary the role never ends up with. + * + *

The caller here is a delegated session, which acts as the identity that approved the request, + * so the approver's own policy is what authorizes the write and what the condition is read against. + */ +@QuarkusTest +@TestProfile(PartnerPermissionBoundaryEnforcementProfile.class) +class DelegationRoleBoundaryEnforcementIntegrationTest { + + private static final String CUSTOMER = "222233334444"; + private static final String PARTNER = "000000000001"; + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications"; + private static final String TEMPLATE = "arn:aws:iam::partner:policy/template/example"; + private static final String BOUNDARY = + "arn:aws:iam::partner:policy/permission_boundary/example.com/ReadOnlyAccess_20261101"; + private static final String OTHER_BOUNDARY = "arn:aws:iam::222233334444:policy/SomethingElse"; + private static final String TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}"""; + private static final String DELEGATION_ACCESS = """ + {"Effect":"Allow","Action":["iam:AssociateDelegationRequest","iam:AcceptDelegationRequest", + "iam:SendDelegationToken"],"Resource":"*"}"""; + + @Inject + DelegationRequestService delegationRequests; + + @Test + void aPolicyConditionedOnTheRegisteredCapAllowsTheRoleItCaps() { + S3RequestSigner approver = approverAllowedToCreateRolesBoundedBy(BOUNDARY); + String[] credentials = delegatedCredentials(approvedBy(approver)); + + // No PermissionsBoundary member: the cap comes from the delegation, and the condition is + // told that value, so the approver's policy allows the write. + createRole(credentials).statusCode(200) + .body("CreateRoleResponse.CreateRoleResult.Role.PermissionsBoundary" + + ".PermissionsBoundaryArn", equalTo(BOUNDARY)); + } + + @Test + void aPolicyConditionedOnAnotherBoundaryRefusesItEvenWhenTheCallNamesThatOne() { + S3RequestSigner approver = approverAllowedToCreateRolesBoundedBy(OTHER_BOUNDARY); + String[] credentials = delegatedCredentials(approvedBy(approver)); + + // The call names the boundary the approver's policy allows, and the delegation's cap is + // what the role will carry instead, so the key carries the cap and the condition fails. + // Naming it is what makes this a guard: were the key still read from the request member, + // the condition would match the name and the write would be authorized for a boundary the + // role never ends up with. + createRole(credentials, OTHER_BOUNDARY).statusCode(403); + } + + private static ValidatableResponse createRole(String[] credentials) { + return createRole(credentials, null); + } + + /** The same write, naming {@code boundaryArn} when it is not null, which the cap overrides. */ + private static ValidatableResponse createRole(String[] credentials, String boundaryArn) { + RequestSpecification request = given().header("Authorization", auth(credentials[0], "iam")) + .header("X-Amz-Security-Token", credentials[2]) + .formParam("Action", "CreateRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", "delegated-" + UUID.randomUUID().toString().substring(0, 8)) + .formParam("AssumeRolePolicyDocument", TRUST); + if (boundaryArn != null) { + request = request.formParam("PermissionsBoundary", boundaryArn); + } + return request.when().post("/").then(); + } + + /** A customer identity that may create a role only when its boundary is {@code boundaryArn}. */ + private static S3RequestSigner approverAllowedToCreateRolesBoundedBy(String boundaryArn) { + String userName = "approver-" + UUID.randomUUID().toString().substring(0, 8); + String policy = """ + {"Version":"2012-10-17","Statement":[%s, + {"Effect":"Allow","Action":"iam:CreateRole","Resource":"*", + "Condition":{"StringEquals":{"iam:PermissionsBoundary":"%s"}}}]}""" + .formatted(DELEGATION_ACCESS, boundaryArn); + return userWithPolicy(userName, policy); + } + + private String approvedBy(S3RequestSigner approver) { + String id = partnerCreate(); + byUser(approver, "AssociateDelegationRequest", id); + byUser(approver, "AcceptDelegationRequest", id); + byUser(approver, "SendDelegationToken", id); + return id; + } + + /** The access key, secret and session token the partner gets for the released token. */ + private String[] delegatedCredentials(String id) { + String token = RequestScopes.callAs(CUSTOMER, + () -> delegationRequests.get(CUSTOMER, id).getExchangeToken()); + ExtractableResponse exchanged = given().header("Authorization", auth(PARTNER, "sts")) + .formParam("Action", "GetDelegatedAccessToken") + .formParam("Version", "2011-06-15") + .formParam("TradeInToken", token) + .when().post("/").then().statusCode(200).extract(); + String result = "GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult.Credentials."; + return new String[] { + exchanged.path(result + "AccessKeyId"), + exchanged.path(result + "SecretAccessKey"), + exchanged.path(result + "SessionToken"), + }; + } + + private static String partnerCreate() { + return given().header("Authorization", auth(PARTNER, "iam")) + .formParam("Action", "CreateDelegationRequest") + .formParam("Version", "2010-05-08") + .formParam("Description", "Set up the integration") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", "workflow-" + Long.toString(System.nanoTime(), 36)) + .formParam("SessionDuration", "3600") + .formParam("OwnerAccountId", CUSTOMER) + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + } + + private static S3RequestSigner userWithPolicy(String userName, String policy) { + iam("CreateUser", "UserName", userName); + iam("PutUserPolicy", "UserName", userName, "PolicyName", "inline", "PolicyDocument", policy); + ExtractableResponse key = given().formParam("Action", "CreateAccessKey") + .formParam("UserName", userName) + .header("Authorization", auth(CUSTOMER, "iam")).when().post("/") + .then().statusCode(200).extract(); + return S3RequestSigner.signedAs( + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"), + key.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")); + } + + private static void byUser(S3RequestSigner caller, String action, String id) { + given().filter(caller).formParam("Action", action).formParam("Version", "2010-05-08") + .formParam("DelegationRequestId", id).when().post("/").then().statusCode(200); + } + + private static void iam(String action, String... params) { + RequestSpecification request = given().formParam("Action", action) + .header("Authorization", auth(CUSTOMER, "iam")); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + request.when().post("/").then().statusCode(200); + } + + private static String auth(String accessKeyId, String service) { + return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261002/us-east-1/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } +} diff --git a/src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryIntegrationTest.java new file mode 100644 index 0000000000..06628ecdd5 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/DelegationRoleBoundaryIntegrationTest.java @@ -0,0 +1,312 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.PartnerPermissionBoundaryProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ExtractableResponse; +import io.restassured.response.Response; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The long-term half of temporary delegation: the partner guide says long-term permissions "limit + * the permissions of any roles that are created or managed through temporary access" and are + * "implemented as IAM permissions boundaries", registered for the partner out of band, by email, + * with no API at all. + * + *

So the boundaries come from configuration here, keyed by the partner account AWS registered + * them for, and the chain is the one AWS describes: a request a registered partner files reports + * the boundaries on itself, which is where {@code RolePermissionRestrictionArns} comes from on AWS + * rather than from any input, the credentials exchanged for that request's token carry them, and a + * role created with those credentials is bounded by one. Without a registration nothing carries + * anything, which is the partner that never onboarded. + */ +@QuarkusTest +@TestProfile(PartnerPermissionBoundaryProfile.class) +class DelegationRoleBoundaryIntegrationTest { + + /** One double quote, so a template can be written without escaping every quote twice. */ + private static final String Q = "\""; + + private static final String CUSTOMER = "222233334444"; + private static final String PARTNER = "000000000001"; + private static final String UNREGISTERED_PARTNER = "000000000002"; + private static final String TOPIC = "arn:aws:sns:us-east-1:000000000001:partner-notifications"; + private static final String TEMPLATE = "arn:aws:iam::partner:policy/template/example"; + private static final String BOUNDARY = + "arn:aws:iam::partner:policy/permission_boundary/example.com/ReadOnlyAccess_20261101"; + private static final String CODE = "ErrorResponse.Error.Code"; + private static final String ALLOW_NOTHING = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"*","Resource":"*"}]}"""; + private static final String TRUST_JSON = + "{" + Q + "Version" + Q + ":" + Q + "2012-10-17" + Q + "," + + Q + "Statement" + Q + ":[{" + Q + "Effect" + Q + ":" + Q + "Allow" + Q + "," + + Q + "Principal" + Q + ":{" + Q + "Service" + Q + ":" + Q + "ec2.amazonaws.com" + Q + "}," + + Q + "Action" + Q + ":" + Q + "sts:AssumeRole" + Q + "}]}"; + private static final String TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}"""; + + @Inject + DelegationRequestService delegationRequests; + + @Inject + IamService iamService; + + @Test + void aRequestFiledByARegisteredPartnerReportsTheBoundariesRegisteredForIt() { + String id = partnerCreate(PARTNER); + + assertEquals(List.of(BOUNDARY), RequestScopes.callAs(CUSTOMER, + () -> delegationRequests.get(CUSTOMER, id).getRolePermissionRestrictionArns())); + } + + @Test + void aRequestFiledByAPartnerWithNoRegistrationReportsNone() { + String id = partnerCreate(UNREGISTERED_PARTNER); + + assertEquals(List.of(), RequestScopes.callAs(CUSTOMER, + () -> delegationRequests.get(CUSTOMER, id).getRolePermissionRestrictionArns())); + } + + @Test + void aRoleCreatedWithDelegatedCredentialsCarriesTheRegisteredBoundary() { + String id = approved(partnerCreate(PARTNER)); + String[] credentials = delegatedCredentials(PARTNER, id); + + // The session is where the cap travels: the request named it and the exchange carried it. + assertEquals(Optional.of(BOUNDARY), RequestScopes.callAs(CUSTOMER, + () -> iamService.delegatedRoleBoundaryArn(credentials[0]))); + + given().header("Authorization", sessionAuth(credentials[0])) + .header("X-Amz-Security-Token", credentials[2]) + .formParam("Action", "CreateRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", unique("delegated")) + .formParam("AssumeRolePolicyDocument", TRUST) + .when().post("/").then().statusCode(200) + .body("CreateRoleResponse.CreateRoleResult.Role.PermissionsBoundary" + + ".PermissionsBoundaryArn", equalTo(BOUNDARY)); + } + + @Test + void aRoleCreatedByAnyoneElseCarriesOnlyTheBoundaryTheCallAsksFor() { + given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", "CreateRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", unique("undelegated")) + .formParam("AssumeRolePolicyDocument", TRUST) + .when().post("/").then().statusCode(200) + .body(not(containsString("PermissionsBoundary"))); + } + + + @Test + void theCapCannotBeLiftedWithTheCredentialsThatSetIt() { + String id = approved(partnerCreate(PARTNER)); + String[] credentials = delegatedCredentials(PARTNER, id); + String roleName = createdRole(credentials); + String other = managedPolicy(); + + // The guide limits roles "created or managed through temporary access", and a registered + // boundary is immutable, so these credentials cannot move the cap they were given. + delegated(credentials, "PutRolePermissionsBoundary", "RoleName", roleName, + "PermissionsBoundary", other).statusCode(403) + .body(CODE, equalTo("AccessDenied")); + delegated(credentials, "DeleteRolePermissionsBoundary", "RoleName", roleName) + .statusCode(403).body(CODE, equalTo("AccessDenied")); + + // And the role still carries it. + delegated(credentials, "GetRole", "RoleName", roleName).statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.PermissionsBoundary.PermissionsBoundaryArn", + equalTo(BOUNDARY)); + } + + @Test + void theRegisteredCapWinsOverABoundaryTheCallNames() { + String id = approved(partnerCreate(PARTNER)); + String[] credentials = delegatedCredentials(PARTNER, id); + String other = managedPolicy(); + + delegated(credentials, "CreateRole", + "RoleName", unique("delegated-other"), + "AssumeRolePolicyDocument", TRUST, + "PermissionsBoundary", other).statusCode(200) + .body("CreateRoleResponse.CreateRoleResult.Role.PermissionsBoundary" + + ".PermissionsBoundaryArn", equalTo(BOUNDARY)); + } + + @Test + void aRegisteredBoundaryIsAPolicyNowhere() { + // It caps and does nothing else: no read, no attach and no version of it exists, so no + // document stored under its ARN can shadow the registration either. + String userName = unique("boundary-reader"); + byCustomer2("CreateUser", "UserName", userName); + + byCustomer2Expecting("GetPolicy", 404, "PolicyArn", BOUNDARY); + byCustomer2Expecting("AttachUserPolicy", 404, "UserName", userName, "PolicyArn", BOUNDARY); + // An identity document, so the write's own reading of the document cannot answer first: + // what is under test is that the ARN resolves to no policy of this account. + byCustomer2Expecting("CreatePolicyVersion", 404, "PolicyArn", BOUNDARY, + "PolicyDocument", ALLOW_NOTHING, "SetAsDefault", "true"); + + byCustomer2("DeleteUser", "UserName", userName); + } + + /** A managed policy of the customer's own, for the cases that need a second boundary ARN. */ + private String managedPolicy() { + return given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", "CreatePolicy") + .formParam("Version", "2010-05-08") + .formParam("PolicyName", unique("other-boundary")) + .formParam("PolicyDocument", ALLOW_NOTHING) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + } + + /** A role created with the delegated credentials, which the cap is applied to. */ + private String createdRole(String[] credentials) { + String roleName = unique("delegated"); + delegated(credentials, "CreateRole", "RoleName", roleName, + "AssumeRolePolicyDocument", TRUST).statusCode(200); + return roleName; + } + + private static ValidatableResponse delegated(String[] credentials, + String action, + String... params) { + RequestSpecification request = given().header("Authorization", sessionAuth(credentials[0])) + .header("X-Amz-Security-Token", credentials[2]) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + return request.when().post("/").then(); + } + + private static void byCustomer2(String action, String... params) { + byCustomer2Expecting(action, 200, params); + } + + private static void byCustomer2Expecting(String action, int status, String... params) { + RequestSpecification request = given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + for (int i = 0; i < params.length; i += 2) { + request = request.formParam(params[i], params[i + 1]); + } + request.when().post("/").then().statusCode(status); + } + + private static String unique(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + @Test + void aRoleAStackProvisionsForADelegatedCallerCarriesTheCapToo() { + String id = approved(partnerCreate(PARTNER)); + String[] credentials = delegatedCredentials(PARTNER, id); + String stackName = unique("delegated-stack"); + String roleName = unique("stack-role"); + String template = "{\"Resources\":{\"R\":{\"Type\":\"AWS::IAM::Role\",\"Properties\":{" + + "\"RoleName\":\"" + roleName + "\",\"AssumeRolePolicyDocument\":" + TRUST_JSON + "}}}}"; + + // The stack is created with the delegated credentials, so the roles it provisions are + // created through temporary access and the guide caps them. + // The router dispatches on the service the credential scope names, so a stack call signs + // for cloudformation while the same session's IAM calls sign for iam. + given().header("Authorization", auth(credentials[0], "cloudformation")) + .header("X-Amz-Security-Token", credentials[2]) + .formParam("Action", "CreateStack") + .formParam("Version", "2010-05-15") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + + // The session acts in the customer's account, so that is where the stack and its role live. + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", auth(CUSTOMER, "cloudformation")); + try { + given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", "GetRole") + .formParam("Version", "2010-05-08") + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.PermissionsBoundary.PermissionsBoundaryArn", + equalTo(BOUNDARY)); + } finally { + CfnStackWaits.deleteStack(stackName, auth(CUSTOMER, "cloudformation")); + } + } + + private String approved(String id) { + byCustomer("AssociateDelegationRequest", id); + byCustomer("AcceptDelegationRequest", id); + byCustomer("SendDelegationToken", id); + return id; + } + + /** The access key, secret and session token the partner gets for the released token. */ + private String[] delegatedCredentials(String partnerAccountId, String id) { + String token = RequestScopes.callAs(CUSTOMER, + () -> delegationRequests.get(CUSTOMER, id).getExchangeToken()); + ExtractableResponse exchanged = given() + .header("Authorization", auth(partnerAccountId, "sts")) + .formParam("Action", "GetDelegatedAccessToken") + .formParam("Version", "2011-06-15") + .formParam("TradeInToken", token) + .when().post("/").then().statusCode(200).extract(); + String result = "GetDelegatedAccessTokenResponse.GetDelegatedAccessTokenResult.Credentials."; + return new String[] { + exchanged.path(result + "AccessKeyId"), + exchanged.path(result + "SecretAccessKey"), + exchanged.path(result + "SessionToken"), + }; + } + + private static String partnerCreate(String partnerAccountId) { + return given().header("Authorization", auth(partnerAccountId, "iam")) + .formParam("Action", "CreateDelegationRequest") + .formParam("Version", "2010-05-08") + .formParam("Description", "Set up the integration") + .formParam("NotificationChannel", TOPIC) + .formParam("RequestorWorkflowId", "workflow-" + Long.toString(System.nanoTime(), 36)) + .formParam("SessionDuration", "3600") + .formParam("OwnerAccountId", CUSTOMER) + .formParam("Permissions.PolicyTemplateArn", TEMPLATE) + .when().post("/").then().statusCode(200) + .extract().path("CreateDelegationRequestResponse.CreateDelegationRequestResult" + + ".DelegationRequestId"); + } + + private static void byCustomer(String action, String id) { + given().header("Authorization", auth(CUSTOMER, "iam")) + .formParam("Action", action) + .formParam("Version", "2010-05-08") + .formParam("DelegationRequestId", id) + .when().post("/").then().statusCode(200); + } + + private static String auth(String accessKeyId, String service) { + return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261002/us-east-1/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } + + private static String sessionAuth(String accessKeyId) { + return auth(accessKeyId, "iam"); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/IamQueryHandlerTest.java b/src/test/java/io/floci/aws/services/iam/IamQueryHandlerTest.java index 9092d4bc36..e82df43e95 100644 --- a/src/test/java/io/floci/aws/services/iam/IamQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamQueryHandlerTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.iam; +import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.XmlParser; import io.floci.aws.services.iam.model.IamRole; import io.floci.aws.services.iam.model.ServerCertificate; @@ -62,7 +63,8 @@ class IamQueryHandlerTest { "fabricated-key", null, Map.of())).thenReturn(certificate); when(service.getServerCertificate(CERTIFICATE_NAME)).thenReturn(certificate); when(service.listServerCertificates(null)).thenReturn(List.of(certificate)); - IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, null); + IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, + new RequestContext(), null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("ServerCertificateName", CERTIFICATE_NAME); @@ -91,7 +93,8 @@ class IamQueryHandlerTest { IamService service = mock(IamService.class); when(service.createRole(ROLE_NAME, "/", EMPTY_POLICY_DOCUMENT, null, 3600, Map.of(), null)).thenReturn(role); when(service.getValidatedRole(ROLE_NAME)).thenReturn(role); - IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, null); + IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null, null, + new RequestContext(), null); MultivaluedMap params = new MultivaluedHashMap<>(); params.putSingle("RoleName", ROLE_NAME); diff --git a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java index e71a49a304..0ea62bab2d 100644 --- a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java @@ -1143,9 +1143,11 @@ class StsQueryHandlerTest { assertTrue(((String) response.getEntity()).contains( "arn:aws:iam::000000000002:user/admin"), (String) response.getEntity()); + // The eighth argument is what the request restricts a role to, which is nothing here: no + // partner boundary is registered in this fixture. verify(iamService).registerDelegatedSession(anyString(), anyString(), anyString(), eq("arn:aws:iam::000000000002:user/admin"), eq(expiry), isNull(), - eq("000000000002")); + eq("000000000002"), eq(List.of())); verify(iamService, never()).registerIssuedSession(anyString(), anyString(), anyString(), anyString(), any(), any(), anyString(), any()); } diff --git a/src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryEnforcementProfile.java b/src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryEnforcementProfile.java new file mode 100644 index 0000000000..1b1f6f8b79 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryEnforcementProfile.java @@ -0,0 +1,25 @@ +package io.floci.aws.testing; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Map; + +/** + * A deployment that enforces IAM policies and has registered permissions boundaries for a + * delegation partner, which is what it takes to see the condition key a delegated role write + * publishes: without enforcement nothing reads it, and without a registration there is no cap to + * publish. + * + *

Both overrides are inert for every class that does not ask for this profile, and + * {@link PartnerPermissionBoundaryProfile} covers the cases that need the registration alone. + */ +public class PartnerPermissionBoundaryEnforcementProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.iam.enforcement-enabled", "true", + "floci.services.iam.partner-permission-boundaries-path", + "src/test/resources/partner-permission-boundaries.json"); + } +} diff --git a/src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryProfile.java b/src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryProfile.java new file mode 100644 index 0000000000..53bbd3f38a --- /dev/null +++ b/src/test/java/io/floci/aws/testing/PartnerPermissionBoundaryProfile.java @@ -0,0 +1,24 @@ +package io.floci.aws.testing; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.Map; + +/** + * A deployment that has registered permissions boundaries for a delegation partner, which AWS does + * by email and this emulator reads from a file. + * + *

The one override, {@code floci.services.iam.partner-permission-boundaries-path}, names + * {@code src/test/resources/partner-permission-boundaries.json}, which registers one read-only + * boundary for partner account {@code 000000000001}. Unset, which every other profile leaves it, + * registers nothing and a delegation request carries no boundary, so this is inert for every class + * that does not ask for it. + */ +public class PartnerPermissionBoundaryProfile implements QuarkusTestProfile { + + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.partner-permission-boundaries-path", + "src/test/resources/partner-permission-boundaries.json"); + } +} diff --git a/src/test/resources/partner-permission-boundaries.json b/src/test/resources/partner-permission-boundaries.json new file mode 100644 index 0000000000..6d538bceb2 --- /dev/null +++ b/src/test/resources/partner-permission-boundaries.json @@ -0,0 +1,14 @@ +{ + "000000000001": { + "arn:aws:iam::partner:policy/permission_boundary/example.com/ReadOnlyAccess_20261101": { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": ["s3:GetObject", "s3:ListBucket"], + "Resource": "*" + } + ] + } + } +}