From 2e1f9d2ffc5d6fff76393d7d5711f54774cd3c3e Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:49:10 -0400 Subject: [PATCH] feat(iam): build access denied messages from the decision record (#9964) The last step of #7887. A request a policy refused was answered with "User is not authorized to perform: " for every service but S3, and the services that did name the policy type (S3, Athena's statements, Lambda's network connectors) asked a second path, firstRefusal, which re-ran the evaluation one policy type at a time. The evaluator's DecisionRecord now carries the refusal an access denied message names, worked out in the same decide() pass: the first policy type that refuses, by its explicit deny or the allow it lacks, in the order AWS was recorded naming them for lambda:PassNetworkConnector (#6699): organization levels, identity policies, permissions boundary, session policy. A resource policy's explicit deny comes first and its missing allow across accounts last, as S3 names them (#9281). The SCP walk keeps the first level that refuses. AccessDeniedMessages.reason builds the phrase from that refusal, naming the managed policy that holds the denying statement, or the boundary, by its ARN. firstRefusal is gone. The enforcement filter explains each decision instead of only evaluating it, and every policy refusal now answers in the IAM User Guide's format, "User: is not authorized to perform: on resource: because no identity-based policy allows the action", in each protocol's envelope. Refusals no policy made keep the old sentence. Closes #7887 --- docs/services/iam.md | 16 ++ docs/services/sts.md | 3 +- .../aws/core/common/IamEnforcementFilter.java | 114 +++++++----- .../services/iam/AccessDeniedMessages.java | 90 +++++----- .../aws/services/iam/IamPolicyEvaluator.java | 122 ++++++++++++- .../core/common/IamEnforcementFilterTest.java | 25 ++- .../iam/AccessDeniedMessagesTest.java | 136 +++++++++++++-- .../iam/IamDenialMessageIntegrationTest.java | 164 ++++++++++++++++++ ...ationCallerEnforcementIntegrationTest.java | 14 +- 9 files changed, 567 insertions(+), 117 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/iam/IamDenialMessageIntegrationTest.java diff --git a/docs/services/iam.md b/docs/services/iam.md index 6045d79414..aca9212eb9 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2610,6 +2610,22 @@ requests retain HTTP 403 XML `AccessDenied` responses, except SNS's, which retur `AuthorizationError`, the error every SNS operation lists for a caller denied access, whichever action is denied. The routed protocol determines the status, not just the request's content type. +The message names the caller, the action, the resource and the policy type that refused the request, +in the format the IAM User Guide gives most denials ("Access denied error message examples"): +`User: is not authorized to perform: on resource: because no +identity-based policy allows the action`, or `... with an explicit deny in an identity-based +policy: ` for an explicit deny, with no ARN when an inline policy denies. The caller is an +IAM user, the account root, or an assumed role's session (`assumed-role//`). The policy +type is the first that refuses, by its explicit deny or by the allow it lacks, in the order AWS was +recorded naming them: service control policies, identity-based policies, the permissions boundary, +then the session policy. A resource-based policy's explicit deny is named first, and its missing allow +across accounts last, as S3 names them. The policy evaluator's decision record says which, so the message comes from the same +evaluation that refused the request. The guide notes that some services word their denials otherwise; +Floci gives this format for every service, except that S3 answers `Access Denied` alone to a caller +outside the bucket owner's organization and EC2's `UnauthorizedOperation` puts `You are not authorized to +perform this operation.` before it. A refusal no policy made, such as a presigned URL used for another +object, keeps `User is not authorized to perform: `. + A request is checked against the resources it names. For S3, DynamoDB, SSM, KMS, IAM, API Gateway, Secrets Manager, Elastic Load Balancing, ECR, Step Functions, EventBridge, EventBridge Scheduler, Amazon Cognito user pools and identity pools, Amazon Data Firehose, Cloud diff --git a/docs/services/sts.md b/docs/services/sts.md index 423d74bf59..a9e0f14e99 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -522,7 +522,8 @@ list of values holds, the NOR of no values. The caller's own policy is read for it as well, and that half was already here: the generated tagging table has `sts:AssumeRole` and `sts:GetFederationToken` requiring `sts:TagSession` of a request that carries `Tags`, which [enforcement](iam.md#iam-enforcement-mode) reads before the -operation runs, answering `User is not authorized to perform: sts:TagSession`. So a tagged +operation runs, answering `User: is not authorized to perform: sts:TagSession on resource: +` with the policy type that refused it. So a tagged `AssumeRole` is held to both permissions, the caller's and the role's, and a tagged `GetFederationToken` to the caller's alone, having no trust policy to read. The two operations that take their tags from an assertion or a token carry no `Tags` member, so nothing asks their caller's diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index f9d2660387..942ad9f854 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -7,13 +7,13 @@ import io.floci.aws.services.cloudtrail.CloudTrailService; import io.floci.aws.services.cloudtrail.S3DataEvents; import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController; import io.floci.aws.services.iam.AccessDeniedMessages; -import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType; import io.floci.aws.services.iam.IamActionRegistry; import io.floci.aws.services.iam.IamAuthorizedActions; import io.floci.aws.services.iam.IamAuthorizedActions.Companion; import io.floci.aws.services.iam.IamCloudTrailEvents; import io.floci.aws.services.iam.IamPolicyEvaluator; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; +import io.floci.aws.services.iam.IamPolicyEvaluator.DecisionRecord; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.floci.aws.services.iam.IamService; @@ -688,7 +688,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { && conditionContext.containsKey(companion.carried())); if (sets && roleSession && companion.callerPolicyWhenChained() && abortIfOwnPolicyDenies(ctx, caller, companion.action(), credentialScope, checkedOn, - targetContexts, akid)) { + targetContexts, accountId, akid)) { return; } if (sets && abortIfDenied(ctx, caller, principal, companion.action(), action, credentialScope, checkedOn, @@ -706,12 +706,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter { String taggingResource = checkedOn.getFirst(); Map> taggingContext = IamConditionContextResolver.withGlobalContext( conditionContext, taggingResource, region, accountId, accountId); - if (evaluator.evaluate(caller, null, "logs:TagResource", taggingResource, taggingContext) == Decision.DENY + DecisionRecord tagResource = evaluator.explain(caller, "logs:TagResource", taggingResource, + taggingContext); + if (tagResource.decision() == Decision.DENY && evaluator.evaluate(caller, null, "logs:TagLogGroup", taggingResource, taggingContext) == Decision.DENY) { LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, "logs:TagResource", taggingResource); - ctx.abortWith(accessDeniedForRequest("logs:TagResource", credentialScope, ctx, taggingResource)); + ctx.abortWith(accessDeniedForRequest("logs:TagResource", credentialScope, ctx, taggingResource, + policyRefusal(caller, akid, accountId, "logs:TagResource", taggingResource, tagResource))); return; } } @@ -1059,14 +1062,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } Map> effectiveContext = IamConditionContextResolver.withGlobalContext( context, connector, region, accountId, accountId); - if (evaluator.evaluate(caller, null, action, connector, effectiveContext) != Decision.DENY) { + DecisionRecord decided = evaluator.explain(caller, action, connector, effectiveContext); + if (decided.decision() != Decision.DENY) { continue; } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, connector); String user = callerArns != null ? callerArns.callerArn() : keyUserArn(accountId, akid); - String reason = AccessDeniedMessages.firstRefusal(evaluator, caller, - iamService.heldPolicies(akid).orElse(null), action, connector, effectiveContext); + String reason = AccessDeniedMessages.reason(decided.refusal(), caller, + iamService.heldPolicies(akid).orElse(null), action); ctx.abortWith(Response.status(403).type(MediaType.APPLICATION_JSON) .header("X-Amzn-Errortype", "AccessDeniedException") .entity(Map.of("Message", AccessDeniedMessages.notAuthorized(user, action, connector, reason))) @@ -1176,12 +1180,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter { */ private boolean abortIfOwnPolicyDenies(ContainerRequestContext ctx, CallerContext caller, String action, String credentialScope, List resources, - List>> targetContexts, String akid) { + List>> targetContexts, String accountId, + String akid) { for (String resource : resources) { for (Map> context : targetContexts) { - if (evaluator.evaluate(caller, null, action, resource, context) == Decision.DENY) { + DecisionRecord decided = evaluator.explain(caller, action, resource, context); + if (decided.decision() == Decision.DENY) { LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); - ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx, resource)); + ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx, resource, + policyRefusal(caller, akid, accountId, action, resource, decided))); return true; } } @@ -1273,26 +1280,27 @@ public class IamEnforcementFilter implements ContainerRequestFilter { taggedContext, resource, region, accountId, resourceOwnerAccountId, action); ResourcePolicyDecision resourcePolicyDecision = evaluator.evaluateResourcePolicyFor( effectiveResourcePolicies, principal, action, resource, effectiveContext); - Decision decision = evaluator.evaluateResolvedResourcePolicy( + DecisionRecord decided = evaluator.explain( caller, resourcePolicyDecision, accountRelationship, action, resource, effectiveContext); - if (decision != Decision.DENY) { + if (decided.decision() != Decision.DENY) { continue; } LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); // S3 answers the refusal with the caller, the resource and the policy that refused it, and - // CloudTrail records the message S3 answered; S3 Control keeps its own envelope and wording. + // CloudTrail records the message S3 answered; S3 Control keeps its own envelope. boolean s3Request = "s3".equals(credentialScope) && !IamActionRegistry.isS3ControlRequest(credentialScope, ctx); String s3Message = s3Request ? refusalMessage(caller, caller.principalArn(), akid, accountId, resourceOwnerAccountId, action, - resource, resourcePolicyDecision, effectiveContext) + resource, decided) : null; if (s3Request) { emitS3DenialIfApplicable(akid, resource, ctx, region, s3Message); } abortIamAware(ctx, s3Message != null ? s3XmlAccessDenied(s3Message, formatS3ResourcePath(resource)) - : accessDeniedForRequest(action, credentialScope, ctx, resource), + : accessDeniedForRequest(action, credentialScope, ctx, resource, + policyRefusal(caller, akid, accountId, action, resource, decided)), akid, action, credentialScope, region); return true; } @@ -1545,8 +1553,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { // The owner and the resource policy decision as the decision resolved them: a presigned POST names // neither, and a caller outside the owner's organization is told Access Denied alone. String denyMessage = refusalMessage(caller.context(), caller.arns().map(CallerArns::callerArn).orElse(null), - akid, accountId, decided.resourceOwnerAccountId(), action, resource, - decided.resourcePolicyDecision(), decided.context()); + akid, accountId, decided.resourceOwnerAccountId(), action, resource, decided.explained()); if (deniedEvent != null) { emitS3Denial(akid, deniedEvent.name(), resource, deniedEvent.region(), denyMessage); } @@ -1594,9 +1601,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { akid, request.action(), request.resource()); String user = caller.arns().map(CallerArns::callerArn).orElseGet(() -> keyUserArn(accountId, akid)); - String reason = AccessDeniedMessages.firstRefusal(evaluator, caller.context(), - iamService.heldPolicies(akid).orElse(null), request.action(), request.resource(), - decided.context()); + String reason = AccessDeniedMessages.reason(decided.explained().refusal(), caller.context(), + iamService.heldPolicies(akid).orElse(null), request.action()); return Optional.of(AccessDeniedMessages.notAuthorized(user, request.action(), request.resource(), reason)); } return Optional.empty(); @@ -1606,13 +1612,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private record Caller(CallerContext context, Optional arns) { } - /** A decision and the condition context it was made in. */ /** - * A decision, the context it was made in, and the resource's owner and resource policy decision as the decision - * resolved them, which a refusal names. + * A decision as its record explains it, and the resource's owner as the decision resolved it, which a refusal + * names. */ - private record Decided(Decision decision, Map> context, String resourceOwnerAccountId, - ResourcePolicyDecision resourcePolicyDecision) { + private record Decided(DecisionRecord explained, String resourceOwnerAccountId) { + + private Decision decision() { + return explained.decision(); + } } /** @@ -1621,23 +1629,34 @@ public class IamEnforcementFilter implements ContainerRequestFilter { * ("This context includes the type of policy that denied access, the reason for denial, and information about * the IAM user or role that requested access to the resource", S3 User Guide, "Troubleshoot access denied (403 * Forbidden) errors"). Across organizations S3 answers {@code Access Denied} alone: "Cross-account requests - * outside of the same organization return a generic Access Denied message". A bucket policy's explicit deny is - * named as a resource-based policy's; otherwise the caller's own policies name the refusal, and a refusal none - * of them makes is the resource-based policy's missing allow. + * outside of the same organization return a generic Access Denied message". The decision record names the policy + * type that refused it ({@link DecisionRecord#refusal}). */ private String refusalMessage(CallerContext caller, String callerArn, String akid, String accountId, String resourceOwnerAccountId, String action, String resource, - ResourcePolicyDecision resourcePolicyDecision, Map> context) { + DecisionRecord decided) { if (action.startsWith("s3:") && resourceOwnerAccountId != null && !resourceOwnerAccountId.equals(accountId) && !sameOrganization(accountId, resourceOwnerAccountId)) { return "Access Denied"; } - String reason = resourcePolicyDecision == ResourcePolicyDecision.EXPLICIT_DENY - ? PolicyType.RESOURCE_BASED_POLICY.explicitDeny() - : AccessDeniedMessages.firstRefusal(evaluator, caller, iamService.heldPolicies(akid).orElse(null), - action, resource, context); return AccessDeniedMessages.notAuthorized(callerArn != null ? callerArn : keyUserArn(accountId, akid), action, - "\"" + resource + "\"", reason != null ? reason : PolicyType.RESOURCE_BASED_POLICY.noAllow(action)); + "\"" + resource + "\"", + AccessDeniedMessages.reason(decided.refusal(), caller, iamService.heldPolicies(akid).orElse(null), + action)); + } + + /** + * The access denied message for a request a policy refused: the caller, the action, the resource and the policy + * type that refused it, as the decision record names it ({@link DecisionRecord#refusal}). "Most access denied + * error messages appear in the format User: user is not authorized to perform: action on resource: resource + * because context" (IAM User Guide, "Access denied error message examples"). + */ + private String policyRefusal(CallerContext caller, String akid, String accountId, String action, String resource, + DecisionRecord decided) { + String callerArn = caller.principalArn() != null ? caller.principalArn() : keyUserArn(accountId, akid); + return AccessDeniedMessages.notAuthorized(callerArn, action, resource, + AccessDeniedMessages.reason(decided.refusal(), caller, iamService.heldPolicies(akid).orElse(null), + action)); } /** Whether both accounts belong to one organization. */ @@ -1721,10 +1740,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { || accountId.equals(effectiveOwnerAccountId) ? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT; - Decision decision = evaluator.evaluateResolvedResourcePolicy( - caller.context(), effectiveDecision, accountRelationship, - action, resource, effectiveContext); - return new Decided(decision, effectiveContext, effectiveOwnerAccountId, effectiveDecision); + return new Decided(evaluator.explain(caller.context(), effectiveDecision, accountRelationship, + action, resource, effectiveContext), effectiveOwnerAccountId); } /** @@ -1957,20 +1974,27 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private Response accessDeniedForRequest(String action, String credentialScope, ContainerRequestContext ctx, String resourceArn) { + return accessDeniedForRequest(action, credentialScope, ctx, resourceArn, accessDeniedMessage(action)); + } + + /** As above, answering {@code message}, such as one naming the policy type that refused the request. */ + private Response accessDeniedForRequest(String action, String credentialScope, + ContainerRequestContext ctx, String resourceArn, String message) { WireProtocol protocol = claimedProtocol(ctx); if (ProtocolErrorResponses.isCbor(protocol)) { // 403, the status the Kinesis and CloudWatch common errors give AccessDeniedException. - return ProtocolErrorResponses.cbor(ctx, "AccessDeniedException", accessDeniedMessage(action), 403); + return ProtocolErrorResponses.cbor(ctx, "AccessDeniedException", message, 403); } // The route decides the envelope, not the resolved action: a request on an S3 Control // route is S3 Control's however its action reads, and only its ErrorResponse wrapper // reaches the s3control SDK deserializers (issue #557). if (IamActionRegistry.isS3ControlRequest(credentialScope, ctx)) { - return s3ControlXmlAccessDenied(accessDeniedMessage(action)); + return s3ControlXmlAccessDenied(message); } boolean restXml = catalog.byCredentialScope(credentialScope) .filter(descriptor -> descriptor.supportsProtocol(ServiceProtocol.REST_XML)).isPresent(); - return accessDeniedResponse(action, credentialScope, ResteasyRequests.mediaType(ctx), resourceArn, protocol, restXml); + return accessDeniedResponse(credentialScope, ResteasyRequests.mediaType(ctx), resourceArn, protocol, restXml, + message); } private static String accessDeniedMessage(String action) { @@ -1984,7 +2008,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType, String resourceArn, WireProtocol protocol, boolean restXml) { - String message = accessDeniedMessage(action); + return accessDeniedResponse(credentialScope, requestMediaType, resourceArn, protocol, restXml, + accessDeniedMessage(action)); + } + + private static Response accessDeniedResponse(String credentialScope, MediaType requestMediaType, + String resourceArn, WireProtocol protocol, boolean restXml, + String message) { if ("ec2".equals(credentialScope)) { return Ec2ErrorResponses.of("UnauthorizedOperation", "You are not authorized to perform this operation. " + message, 403); diff --git a/src/main/java/io/floci/aws/services/iam/AccessDeniedMessages.java b/src/main/java/io/floci/aws/services/iam/AccessDeniedMessages.java index 3a6fcb0694..ef874a9323 100644 --- a/src/main/java/io/floci/aws/services/iam/AccessDeniedMessages.java +++ b/src/main/java/io/floci/aws/services/iam/AccessDeniedMessages.java @@ -1,12 +1,13 @@ package io.floci.aws.services.iam; +import io.floci.aws.services.iam.IamPolicyEvaluator.Outcome; +import io.floci.aws.services.iam.IamPolicyEvaluator.Refusal; import io.floci.aws.services.iam.IamPolicyEvaluator.SimulationDecision; import io.floci.aws.services.iam.IamService.HeldPolicies; import io.floci.aws.services.iam.IamService.HeldPolicy; import io.floci.aws.services.iam.model.CallerContext; import java.util.List; -import java.util.Map; /** * The access denied message AWS returns when a policy refuses a call, and the end of it that names the @@ -59,56 +60,49 @@ public final class AccessDeniedMessages { } /** - * Why {@code caller} may not perform {@code action} on {@code resource}, or null when it may, for a - * resource with no policy of its own. Each policy type is checked in turn, service control policies, - * identity policies, permissions boundary, then session policy, and the first that refuses names the - * reason, by its explicit deny or by the allow it lacks. So identity policies with no allow win over - * an explicit deny in the boundary (measured for {@code lambda:PassNetworkConnector}). AWS names one - * of several denying identity policies at random, and this names the first in {@code held}, which is - * null when the caller holds no policies by ARN. + * The end of the message naming {@code refusal}, the policy type that refused {@code action} as the decision + * record gives it ({@link IamPolicyEvaluator.DecisionRecord#refusal}), by its explicit deny or by the allow it + * lacks; null for no refusal. An identity policy's explicit deny names the managed policy that holds the denying + * statement by its ARN, and a boundary's names the boundary's, as AWS does; an inline policy, and a document + * {@code held} does not hold by ARN, name none. AWS names one of several denying identity policies at random, and + * this names the one the record's statement is in. */ - public static String firstRefusal(IamPolicyEvaluator evaluator, CallerContext caller, - HeldPolicies held, String action, String resource, - Map> context) { - for (List level : caller.scpLevels() == null ? List.>of() : caller.scpLevels()) { - SimulationDecision decision = level.isEmpty() - ? SimulationDecision.ALLOWED : simulate(evaluator, level, action, resource, context); - if (decision != SimulationDecision.ALLOWED) { - return PolicyType.SERVICE_CONTROL_POLICY.refusal(decision, action, null); - } + public static String reason(Refusal refusal, CallerContext caller, HeldPolicies held, String action) { + if (refusal == null) { + return null; } - SimulationDecision identity = simulate(evaluator, caller.identityPolicies(), action, resource, context); - if (identity != SimulationDecision.ALLOWED) { - String denying = identity == SimulationDecision.EXPLICIT_DENY && held != null - ? held.identity().stream() - .filter(policy -> simulate(evaluator, List.of(policy.document()), action, resource, - context) == SimulationDecision.EXPLICIT_DENY) - .findFirst() - .map(HeldPolicy::arn) - .orElse(null) - : null; - return PolicyType.IDENTITY_BASED_POLICY.refusal(identity, action, denying); - } - if (caller.boundaryPolicyDocument() != null) { - SimulationDecision boundary = simulate(evaluator, List.of(caller.boundaryPolicyDocument()), action, - resource, context); - if (boundary != SimulationDecision.ALLOWED) { - return PolicyType.PERMISSIONS_BOUNDARY.refusal(boundary, action, - held == null ? null : held.permissionsBoundaryArn()); - } - } - if (caller.sessionPolicyDocument() != null) { - SimulationDecision session = simulate(evaluator, List.of(caller.sessionPolicyDocument()), action, - resource, context); - if (session != SimulationDecision.ALLOWED) { - return PolicyType.SESSION_POLICY.refusal(session, action, null); - } - } - return null; + SimulationDecision decision = refusal.outcome() == Outcome.EXPLICIT_DENY + ? SimulationDecision.EXPLICIT_DENY : SimulationDecision.IMPLICIT_DENY; + return switch (refusal.layer()) { + case SERVICE_CONTROL -> PolicyType.SERVICE_CONTROL_POLICY.refusal(decision, action, null); + case IDENTITY -> PolicyType.IDENTITY_BASED_POLICY.refusal(decision, action, + decision == SimulationDecision.EXPLICIT_DENY ? heldArn(refusal, caller, held) : null); + case RESOURCE -> PolicyType.RESOURCE_BASED_POLICY.refusal(decision, action, null); + case PERMISSIONS_BOUNDARY -> PolicyType.PERMISSIONS_BOUNDARY.refusal(decision, action, + held == null ? null : held.permissionsBoundaryArn()); + case SESSION -> PolicyType.SESSION_POLICY.refusal(decision, action, null); + }; } - private static SimulationDecision simulate(IamPolicyEvaluator evaluator, List documents, String action, - String resource, Map> context) { - return evaluator.simulatePrincipalPolicy(CallerContext.of(documents), action, resource, context); + /** + * The ARN of the held policy whose document holds the refusal's statement, or null for none held by ARN: the one + * at the statement's position, as a user's or role's policies are collected in the order {@code held} lists them, + * and otherwise the first held with the same document, for a caller whose documents are collected differently. + */ + private static String heldArn(Refusal refusal, CallerContext caller, HeldPolicies held) { + int document = refusal.statement() == null ? -1 : refusal.statement().document(); + List documents = caller.identityPolicies(); + if (held == null || documents == null || document < 0 || document >= documents.size()) { + return null; + } + String denying = documents.get(document); + if (document < held.identity().size() && denying.equals(held.identity().get(document).document())) { + return held.identity().get(document).arn(); + } + return held.identity().stream() + .filter(policy -> denying.equals(policy.document())) + .findFirst() + .map(HeldPolicy::arn) + .orElse(null); } } diff --git a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java index 1c75ae4393..bc111115ce 100644 --- a/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/IamPolicyEvaluator.java @@ -111,14 +111,35 @@ public class IamPolicyEvaluator { /** * Why a request was decided as it was. {@code statement} is null for an implicit deny, which no - * statement caused. + * statement caused. {@code refusal} is what an access denied message names for a refused request, + * null for an allowed one. */ - public record DecisionRecord(Outcome outcome, PolicyLayer layer, DecidingStatement statement) { + public record DecisionRecord(Outcome outcome, PolicyLayer layer, DecidingStatement statement, Refusal refusal) { + + public DecisionRecord(Outcome outcome, PolicyLayer layer, DecidingStatement statement) { + this(outcome, layer, statement, null); + } + public Decision decision() { return outcome == Outcome.ALLOW ? Decision.ALLOW : Decision.DENY; } } + /** + * The policy family an access denied message names, and how it refused: by an explicit deny, whose + * statement it gives, or by the allow it lacks, when {@code statement} is null. + */ + public record Refusal(Outcome outcome, PolicyLayer layer, DecidingStatement statement) { + + private static Refusal explicitDeny(DecidingStatement statement) { + return new Refusal(Outcome.EXPLICIT_DENY, statement.layer(), statement); + } + + private static Refusal noAllow(PolicyLayer layer) { + return new Refusal(Outcome.IMPLICIT_DENY, layer, null); + } + } + /** How a resource policy statement's principal names a caller: itself, only its account, or not at all. */ private enum PrincipalMatch { NONE, ACCOUNT, CALLER } @@ -280,10 +301,89 @@ public class IamPolicyEvaluator { accountRelationship, loweredAction, resource, ctx); } - /** The decision over documents parsed and organization levels walked once by the caller. */ + /** As {@link #explain} for a resource with no policy of its own, as {@link #evaluate} decides it. */ + public DecisionRecord explain(CallerContext caller, String action, String resource, + Map> conditionCtx) { + return explain(caller, ResourcePolicyDecision.NEUTRAL, ResourceAccountRelationship.SAME_ACCOUNT, action, + resource, conditionCtx); + } + + /** + * The decision over documents parsed and organization levels walked once by the caller, with what an access + * denied message names when it is a refusal. + */ private DecisionRecord decide(SimulatedPolicies policies, ResourcePolicyDecision resourcePolicyDecision, ResourceAccountRelationship accountRelationship, String loweredAction, String resource, Map> ctx) { + DecisionRecord decided = decideOutcome(policies, resourcePolicyDecision, accountRelationship, loweredAction, + resource, ctx); + return decided.outcome() == Outcome.ALLOW ? decided + : new DecisionRecord(decided.outcome(), decided.layer(), decided.statement(), + refusal(policies, decided, resourcePolicyDecision, accountRelationship, loweredAction, + resource, ctx)); + } + + /** + * What an access denied message names for a refused request: the first policy family that refuses it, by its + * explicit deny or by the allow it lacks, in the order AWS was recorded naming them for + * {@code lambda:PassNetworkConnector} (#6699): the organization levels, identity policies, the permissions + * boundary, then the session policy. So identity policies with no allow are named before an explicit deny in the + * boundary, which the decision itself puts first. A resource policy's explicit deny is named before the rest, and + * its missing allow across accounts after them, as S3 names them (S3 User Guide, "Troubleshoot access denied (403 + * Forbidden) errors"). + */ + private Refusal refusal(SimulatedPolicies policies, DecisionRecord decided, + ResourcePolicyDecision resourcePolicyDecision, + ResourceAccountRelationship accountRelationship, String loweredAction, String resource, + Map> ctx) { + ResourcePolicyDecision resolvedDecision = resourcePolicyDecision == null + ? ResourcePolicyDecision.NEUTRAL : resourcePolicyDecision; + boolean crossAccount = accountRelationship == null + || accountRelationship == ResourceAccountRelationship.CROSS_ACCOUNT; + if (resolvedDecision == ResourcePolicyDecision.EXPLICIT_DENY) { + return Refusal.explicitDeny(resourceStatement()); + } + if (policies.scp().refusal() != null) { + return policies.scp().refusal(); + } + DecidingStatement identityDeny = firstMatch(PolicyLayer.IDENTITY, -1, policies.identity(), true, + loweredAction, resource, ctx); + if (identityDeny != null) { + return Refusal.explicitDeny(identityDeny); + } + if (firstMatch(PolicyLayer.IDENTITY, -1, policies.identity(), false, loweredAction, resource, ctx) == null) { + return Refusal.noAllow(PolicyLayer.IDENTITY); + } + if (policies.boundary() != null) { + DecidingStatement boundaryDeny = firstMatch(PolicyLayer.PERMISSIONS_BOUNDARY, -1, policies.boundary(), + true, loweredAction, resource, ctx); + if (boundaryDeny != null) { + return Refusal.explicitDeny(boundaryDeny); + } + boolean directSameAccountUserGrant = !crossAccount + && resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER; + if (!directSameAccountUserGrant && firstMatch(PolicyLayer.PERMISSIONS_BOUNDARY, -1, + policies.boundary(), false, loweredAction, resource, ctx) == null) { + return Refusal.noAllow(PolicyLayer.PERMISSIONS_BOUNDARY); + } + } + if (policies.session() != null) { + DecidingStatement sessionDeny = firstMatch(PolicyLayer.SESSION, -1, policies.session(), true, + loweredAction, resource, ctx); + if (sessionDeny != null) { + return Refusal.explicitDeny(sessionDeny); + } + if (firstMatch(PolicyLayer.SESSION, -1, policies.session(), false, loweredAction, resource, ctx) == null) { + return Refusal.noAllow(PolicyLayer.SESSION); + } + } + // What is left is the decision's own: a resource policy that grants nothing across accounts. + return new Refusal(decided.outcome(), decided.layer(), decided.statement()); + } + + private DecisionRecord decideOutcome(SimulatedPolicies policies, ResourcePolicyDecision resourcePolicyDecision, + ResourceAccountRelationship accountRelationship, String loweredAction, + String resource, Map> ctx) { List identityDocs = policies.identity(); List sessionDocs = policies.session(); List boundaryDocs = policies.boundary(); @@ -1209,15 +1309,16 @@ public class IamPolicyEvaluator { private ScpWalk scpWalk(List> scpLevels, String action, String resource, Map> ctx) { if (scpLevels == null) { - return new ScpWalk(null, true); + return new ScpWalk(null, true, null); } boolean allows = true; + Refusal refusal = null; for (int level = 0; level < scpLevels.size(); level++) { ParsedDocuments parsed = parseAllTracked(scpLevels.get(level)); DecidingStatement deny = firstMatch(PolicyLayer.SERVICE_CONTROL, level, parsed.documents(), true, action, resource, ctx); if (deny != null) { - return new ScpWalk(deny, false); + return new ScpWalk(deny, false, refusal != null ? refusal : Refusal.explicitDeny(deny)); } if (!allows) { continue; @@ -1226,13 +1327,18 @@ public class IamPolicyEvaluator { if (parsed.anyFailed() || (!levelStmts.isEmpty() && !anyExplicitAllow(levelStmts, action, resource, ctx))) { allows = false; + refusal = Refusal.noAllow(PolicyLayer.SERVICE_CONTROL); } } - return new ScpWalk(null, allows); + return new ScpWalk(null, allows, refusal); } - /** What {@link #scpWalk} found: the first explicit Deny or null, and whether every level passes. */ - private record ScpWalk(DecidingStatement firstDeny, boolean allows) { + /** + * What {@link #scpWalk} found: the first explicit Deny or null, whether every level passes, and the first level + * that refuses, by its explicit deny or the allow it lacks, which an access denied message names; null when none + * does. + */ + private record ScpWalk(DecidingStatement firstDeny, boolean allows, Refusal refusal) { } // ----------------------------------------------------------------------- diff --git a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java index b2ea60e8f4..440d3d33a4 100644 --- a/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/floci/aws/core/common/IamEnforcementFilterTest.java @@ -7,6 +7,10 @@ import io.floci.aws.services.apigateway.ApiGatewayController; import io.floci.aws.services.cloudtrail.CloudTrailService; import io.floci.aws.services.iam.IamActionRegistry; import io.floci.aws.services.iam.IamPolicyEvaluator; +import io.floci.aws.services.iam.IamPolicyEvaluator.DecisionRecord; +import io.floci.aws.services.iam.IamPolicyEvaluator.Outcome; +import io.floci.aws.services.iam.IamPolicyEvaluator.PolicyLayer; +import io.floci.aws.services.iam.IamPolicyEvaluator.Refusal; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.floci.aws.services.iam.IamService; @@ -97,6 +101,13 @@ class IamEnforcementFilterTest { accountResolver = mock(AccountResolver.class); iamService = mock(IamService.class); evaluator = mock(IamPolicyEvaluator.class); + // The filter reads the decision record, which explains whatever the decision stubs of each test decide. + lenient().when(evaluator.explain(any(), any(), any(), any(), any(), any())).thenAnswer(call -> recordOf( + evaluator.evaluateResolvedResourcePolicy(call.getArgument(0), call.getArgument(1), call.getArgument(2), + call.getArgument(3), call.getArgument(4), call.getArgument(5)))); + lenient().when(evaluator.explain(any(), anyString(), any(), any())).thenAnswer(call -> recordOf( + evaluator.evaluate(call.getArgument(0), (List) null, call.getArgument(1), + call.getArgument(2), call.getArgument(3)))); actionRegistry = mock(IamActionRegistry.class); when(actionRegistry.operationForRoute(any(), any(), any())).thenAnswer(inv -> inv.getArgument(1)); when(actionRegistry.routedScope(any())).thenAnswer(inv -> inv.getArgument(0)); @@ -364,7 +375,11 @@ class IamEnforcementFilterTest { assertEquals(expectedStatus, denied.getValue().getStatus()); assertEquals(MediaType.APPLICATION_JSON_TYPE, denied.getValue().getMediaType()); assertTrue(entityString(denied.getValue()).contains("\"__type\":\"AccessDeniedException\"")); - assertTrue(entityString(denied.getValue()).contains("User is not authorized to perform: dynamodb:PutItem")); + // A caller IAM resolves no ARN for is named by its key in a user's place; the reason is the record's. + assertTrue(entityString(denied.getValue()).contains("User: arn:aws:iam::000000000000:user/AKIAUSER is not " + + "authorized to perform: dynamodb:PutItem on resource: "), entityString(denied.getValue())); + assertTrue(entityString(denied.getValue()) + .contains("because no identity-based policy allows the dynamodb:PutItem action")); } @Test @@ -2696,4 +2711,12 @@ class IamEnforcementFilterTest { mock(CurrentVertxRequest.class), catalog, scpProvider, sessionAccountLookup, providers); } + + /** The record of a stubbed decision: a refusal is the identity policies' missing allow, as most are. */ + private static DecisionRecord recordOf(IamPolicyEvaluator.Decision decision) { + return decision == IamPolicyEvaluator.Decision.DENY + ? new DecisionRecord(Outcome.IMPLICIT_DENY, PolicyLayer.IDENTITY, null, + new Refusal(Outcome.IMPLICIT_DENY, PolicyLayer.IDENTITY, null)) + : new DecisionRecord(Outcome.ALLOW, PolicyLayer.IDENTITY, null); + } } diff --git a/src/test/java/io/floci/aws/services/iam/AccessDeniedMessagesTest.java b/src/test/java/io/floci/aws/services/iam/AccessDeniedMessagesTest.java index 9c187e6999..7333ed6fb6 100644 --- a/src/test/java/io/floci/aws/services/iam/AccessDeniedMessagesTest.java +++ b/src/test/java/io/floci/aws/services/iam/AccessDeniedMessagesTest.java @@ -2,6 +2,9 @@ package io.floci.aws.services.iam; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType; +import io.floci.aws.services.iam.IamPolicyEvaluator.DecisionRecord; +import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; +import io.floci.aws.services.iam.IamPolicyEvaluator.ResourcePolicyDecision; import io.floci.aws.services.iam.IamPolicyEvaluator.SimulationDecision; import io.floci.aws.services.iam.IamService.HeldPolicies; import io.floci.aws.services.iam.IamService.HeldPolicy; @@ -52,14 +55,33 @@ class AccessDeniedMessagesTest { HeldPolicies held = new HeldPolicies(List.of(new HeldPolicy(null, policy(allow("*"))), new HeldPolicy(MANAGED, policy(deny("*")))), null); assertEquals("with an explicit deny in an identity-based policy: " + MANAGED, - AccessDeniedMessages.firstRefusal(evaluator, caller(held, null, null), held, ACTION, CONNECTOR, Map.of())); + reason(caller(held, null, null), held, CONNECTOR)); HeldPolicies inlineFirst = new HeldPolicies(List.of(new HeldPolicy(null, policy(allow("*"), deny("*"))), new HeldPolicy(MANAGED, policy(deny("*")))), null); - assertEquals("with an explicit deny in an identity-based policy", AccessDeniedMessages.firstRefusal( - evaluator, caller(inlineFirst, null, null), inlineFirst, ACTION, CONNECTOR, Map.of())); - assertEquals("with an explicit deny in an identity-based policy", AccessDeniedMessages.firstRefusal( - evaluator, caller(held, null, null), null, ACTION, CONNECTOR, Map.of())); + assertEquals("with an explicit deny in an identity-based policy", + reason(caller(inlineFirst, null, null), inlineFirst, CONNECTOR)); + assertEquals("with an explicit deny in an identity-based policy", reason(caller(held, null, null), null, + CONNECTOR)); + } + + @Test + void anInlinePolicyAndAManagedOneWithTheSameDocumentAreToldApartByPosition() { + String denying = policy(deny("*")); + HeldPolicies held = new HeldPolicies(List.of(new HeldPolicy(null, policy(allow("*"))), + new HeldPolicy(MANAGED, denying), new HeldPolicy(null, denying)), null); + + assertEquals("with an explicit deny in an identity-based policy: " + MANAGED, + reason(caller(held, null, null), held, CONNECTOR)); + } + + @Test + void aDenyingDocumentAtAnotherPositionThanItsHeldPolicyIsFoundByItsText() { + String denying = policy(deny("*")); + HeldPolicies held = new HeldPolicies(List.of(new HeldPolicy(MANAGED, denying)), null); + CallerContext caller = CallerContext.of(List.of(policy(allow("*")), denying)); + + assertEquals("with an explicit deny in an identity-based policy: " + MANAGED, reason(caller, held, CONNECTOR)); } @Test @@ -81,23 +103,109 @@ class AccessDeniedMessagesTest { @Test void serviceControlPoliciesComeFirstAndAnEmptyLevelIsSkipped() { CallerContext caller = CallerContext.of(List.of(policy(allowCreate()))); - assertEquals("with an explicit deny in a service control policy", AccessDeniedMessages.firstRefusal(evaluator, - caller.withScpLevels(List.of(List.of(), List.of(policy(allow("*"), deny("*"))))), null, ACTION, - CONNECTOR, Map.of())); + assertEquals("with an explicit deny in a service control policy", reason( + caller.withScpLevels(List.of(List.of(), List.of(policy(allow("*"), deny("*"))))), null, CONNECTOR)); assertEquals("because no service control policy allows the lambda:PassNetworkConnector action", - AccessDeniedMessages.firstRefusal(evaluator, caller.withScpLevels(List.of(List.of(policy(allowCreate())))), - null, ACTION, CONNECTOR, Map.of())); + reason(caller.withScpLevels(List.of(List.of(policy(allowCreate())))), null, CONNECTOR)); + } + + @Test + void theFirstLevelThatRefusesNamesTheReasonEvenBeforeAnExplicitDenyBelowIt() { + CallerContext caller = CallerContext.of(List.of(policy(allow("*")))).withScpLevels(List.of( + List.of(policy(allowCreate())), List.of(policy(allow("*"), deny("*"))))); + + assertEquals("because no service control policy allows the lambda:PassNetworkConnector action", + reason(caller, null, CONNECTOR)); + } + + @Test + void aResourcePolicysExplicitDenyIsNamedFirstAndItsMissingAllowAcrossAccountsLast() { + CallerContext allowed = CallerContext.of(List.of(policy(allow("*")))); + CallerContext unallowed = CallerContext.of(List.of(policy(allowCreate()))); + + assertEquals("with an explicit deny in a resource-based policy", reason(evaluator.explain(unallowed, + ResourcePolicyDecision.EXPLICIT_DENY, + ResourceAccountRelationship.SAME_ACCOUNT, ACTION, CONNECTOR, Map.of()), unallowed)); + assertEquals("because no resource-based policy allows the lambda:PassNetworkConnector action", + reason(evaluator.explain(allowed, ResourcePolicyDecision.NEUTRAL, + ResourceAccountRelationship.CROSS_ACCOUNT, ACTION, CONNECTOR, Map.of()), + allowed)); + assertEquals(NO_IDENTITY_ALLOW, reason(evaluator.explain(unallowed, + ResourcePolicyDecision.ALLOW, + ResourceAccountRelationship.CROSS_ACCOUNT, ACTION, CONNECTOR, Map.of()), unallowed)); + } + + @Test + void identityPoliciesWithNoAllowAreNamedEvenWhereAResourcePolicyGrantsWithinTheAccount() { + CallerContext caller = new CallerContext(List.of(policy(allowCreate())), null, policy(allowCreate())); + + assertEquals(NO_IDENTITY_ALLOW, + reason(evaluator.explain(caller, ResourcePolicyDecision.ALLOW, + ResourceAccountRelationship.SAME_ACCOUNT, ACTION, CONNECTOR, Map.of()), + caller)); + assertNull(evaluator.explain(caller, ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, + ResourceAccountRelationship.SAME_ACCOUNT, ACTION, CONNECTOR, Map.of()).refusal()); + } + + @Test + void aGrantToTheUserItselfIsNotCappedByTheBoundarySoTheSessionPolicyNamesTheReason() { + CallerContext caller = new CallerContext(List.of(policy(allow("*"))), policy(allowCreate()), + policy(allowCreate())); + + assertEquals("because no session policy allows the lambda:PassNetworkConnector action", + reason(evaluator.explain(caller, ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER, + ResourceAccountRelationship.SAME_ACCOUNT, ACTION, CONNECTOR, Map.of()), + caller)); + } + + @Test + void anIdentityPolicysExplicitDenyIsNamedBeforeTheBoundarysAndASessionDenyNeedsNoAllowBesideIt() { + String allowAndDeny = policy(allow("*"), deny("*")); + String denyOnly = policy(deny("*")); + + assertEquals("with an explicit deny in an identity-based policy", refusal(allowAndDeny, allowAndDeny, null)); + assertEquals("with an explicit deny in a session policy", refusal(policy(allow("*")), null, denyOnly)); + } + + @Test + void acrossAccountsTheCallersOwnPoliciesAreNamedBeforeTheResourcePolicysMissingAllow() { + CallerContext noIdentityAllow = new CallerContext(List.of(policy(allowCreate())), policy(allowCreate()), + null); + CallerContext noSessionAllow = new CallerContext(List.of(policy(allow("*"))), policy(allowCreate()), null); + + assertEquals(NO_IDENTITY_ALLOW, reason(evaluator.explain(noIdentityAllow, + ResourcePolicyDecision.ALLOW, + ResourceAccountRelationship.CROSS_ACCOUNT, ACTION, CONNECTOR, Map.of()), + noIdentityAllow)); + assertEquals("because no session policy allows the lambda:PassNetworkConnector action", + reason(evaluator.explain(noSessionAllow, ResourcePolicyDecision.NEUTRAL, + ResourceAccountRelationship.CROSS_ACCOUNT, ACTION, CONNECTOR, Map.of()), + noSessionAllow)); + } + + @Test + void anAllowedRequestHasNoRefusal() { + assertNull(evaluator.explain(CallerContext.of(List.of(policy(allow("*")))), ACTION, CONNECTOR, Map.of()) + .refusal()); } private String refusal(String identity, String resource) { - return AccessDeniedMessages.firstRefusal(evaluator, CallerContext.of(List.of(identity)), null, ACTION, resource, - Map.of()); + return reason(CallerContext.of(List.of(identity)), null, resource); } private String refusal(String identity, String boundary, String session) { HeldPolicies held = new HeldPolicies(List.of(new HeldPolicy(null, identity)), boundary == null ? null : BOUNDARY); - return AccessDeniedMessages.firstRefusal(evaluator, caller(held, boundary, session), held, ACTION, CONNECTOR, - Map.of()); + return reason(caller(held, boundary, session), held, CONNECTOR); + } + + /** The reason the decision record names for {@link #ACTION} on {@code resource}, a resource with no policy. */ + private String reason(CallerContext caller, HeldPolicies held, String resource) { + return AccessDeniedMessages.reason(evaluator.explain(caller, ACTION, resource, Map.of()).refusal(), caller, + held, ACTION); + } + + private static String reason(DecisionRecord decided, CallerContext caller) { + return AccessDeniedMessages.reason(decided.refusal(), caller, null, ACTION); } private static CallerContext caller(HeldPolicies held, String boundary, String session) { diff --git a/src/test/java/io/floci/aws/services/iam/IamDenialMessageIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamDenialMessageIntegrationTest.java new file mode 100644 index 0000000000..de43085d7c --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamDenialMessageIntegrationTest.java @@ -0,0 +1,164 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.dynamodb.DynamoDbClient; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.model.Credentials; + +import java.net.URI; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * #7887: a request a policy refuses is answered with the caller, the action, the resource and the policy type that + * refused it, as the decision record names it, in the format the IAM User Guide gives most access denied messages + * ("User: user is not authorized to perform: action on resource: resource because context"), over each protocol. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class IamDenialMessageIntegrationTest { + + private static final String ACCOUNT = "111111111111"; + + @TestHTTPResource("/") + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aMissingIdentityAllowIsNamedOverQuery() { + String name = "denial-query-" + suffix(); + UserCredentials keys = user(name, policy("Allow", "sts:GetCallerIdentity", "*")); + try (IamClient caller = AwsTestClients.create(IamClient.builder(), keys.accessKeyId(), keys.secretAccessKey(), + Region.US_EAST_1)) { + AwsServiceException denied = assertThrows(AwsServiceException.class, + () -> caller.getUser(r -> r.userName("absent"))); + + assertEquals(403, denied.statusCode()); + assertEquals("AccessDenied", denied.awsErrorDetails().errorCode()); + assertEquals("User: arn:aws:iam::" + ACCOUNT + ":user/" + name + " is not authorized to perform: " + + "iam:GetUser on resource: arn:aws:iam::" + ACCOUNT + ":user/absent because no identity-based " + + "policy allows the iam:GetUser action", denied.awsErrorDetails().errorMessage()); + } + } + + @Test + void anExplicitDenyInAManagedPolicyIsNamedWithItsArnOverJson() { + String name = "denial-json-" + suffix(); + // The policy first, so the cleanup, last in first out, removes the user it is attached to before it. + String denying = managedPolicy(name, policy("Deny", "dynamodb:DescribeTable", "*")); + UserCredentials keys = user(name, policy("Allow", "dynamodb:*", "*")); + try (IamClient admin = admin(); + DynamoDbClient caller = AwsTestClients.create(DynamoDbClient.builder(), keys.accessKeyId(), + keys.secretAccessKey(), Region.US_EAST_1)) { + admin.attachUserPolicy(r -> r.userName(name).policyArn(denying)); + + AwsServiceException denied = assertThrows(AwsServiceException.class, + () -> caller.describeTable(r -> r.tableName("orders"))); + + assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode()); + assertEquals("User: arn:aws:iam::" + ACCOUNT + ":user/" + name + " is not authorized to perform: " + + "dynamodb:DescribeTable on resource: arn:aws:dynamodb:us-east-1:" + ACCOUNT + ":table/orders " + + "with an explicit deny in an identity-based policy: " + denying, + denied.awsErrorDetails().errorMessage()); + } + } + + @Test + void anExplicitDenyInThePermissionsBoundaryIsNamedWithItsArnOverRestJson() { + String name = "denial-rest-" + suffix(); + String boundary = managedPolicy(name, """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"*","Resource":"*"}, + {"Effect":"Deny","Action":"lambda:GetFunction","Resource":"*"}]}"""); + UserCredentials keys = user(name, policy("Allow", "lambda:*", "*")); + try (IamClient admin = admin(); + LambdaClient caller = AwsTestClients.create(LambdaClient.builder(), keys.accessKeyId(), + keys.secretAccessKey(), Region.US_EAST_1)) { + admin.putUserPermissionsBoundary(r -> r.userName(name).permissionsBoundary(boundary)); + + AwsServiceException denied = assertThrows(AwsServiceException.class, + () -> caller.getFunction(r -> r.functionName("worker"))); + + assertEquals(403, denied.statusCode()); + assertEquals("User: arn:aws:iam::" + ACCOUNT + ":user/" + name + " is not authorized to perform: " + + "lambda:GetFunction on resource: arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:worker " + + "with an explicit deny in a permissions boundary: " + boundary, + denied.awsErrorDetails().errorMessage()); + } + } + + @Test + void aSessionPolicyThatAllowsLessIsNamedForTheAssumedRolesSession() { + String roleName = "denial-session-" + suffix(); + try (IamClient admin = admin(); + StsClient sts = AwsTestClients.create(StsClient.builder(), ACCOUNT, Region.US_EAST_1)) { + String roleArn = admin.createRole(r -> r.roleName(roleName).assumeRolePolicyDocument(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}""".formatted(ACCOUNT))) + .role().arn(); + cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth(ACCOUNT, "iam"), roleName)); + admin.putRolePolicy(r -> r.roleName(roleName).policyName("all") + .policyDocument(policy("Allow", "dynamodb:*", "*"))); + Credentials session = sts.assumeRole(r -> r.roleArn(roleArn).roleSessionName("s1") + .policy(policy("Allow", "dynamodb:ListTables", "*"))).credentials(); + + try (DynamoDbClient caller = AwsTestClients.create(DynamoDbClient.builder(), + AwsSessionCredentials.create(session.accessKeyId(), session.secretAccessKey(), + session.sessionToken()), Region.US_EAST_1, baseUri)) { + AwsServiceException denied = assertThrows(AwsServiceException.class, + () -> caller.describeTable(r -> r.tableName("orders"))); + + assertEquals("User: arn:aws:sts::" + ACCOUNT + ":assumed-role/" + roleName + "/s1 is not authorized " + + "to perform: dynamodb:DescribeTable on resource: arn:aws:dynamodb:us-east-1:" + ACCOUNT + + ":table/orders because no session policy allows the dynamodb:DescribeTable action", + denied.awsErrorDetails().errorMessage()); + } + } + } + + private UserCredentials user(String name, String policy) { + UserCredentials keys = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), name); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), name, "grant", policy); + return keys; + } + + private String managedPolicy(String name, String document) { + try (IamClient admin = admin()) { + String arn = admin.createPolicy(r -> r.policyName(name).policyDocument(document)).policy().arn(); + cleanup.register(() -> EnforcementFixtures.removePolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), arn)); + return arn; + } + } + + private static IamClient admin() { + return AwsTestClients.create(IamClient.builder(), ACCOUNT, Region.US_EAST_1); + } + + private static String policy(String effect, String action, String resource) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[" + EnforcementFixtures.statement(effect, action, resource) + + "]}"; + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/StsFederationCallerEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsFederationCallerEnforcementIntegrationTest.java index 6ed3a33ca0..8f608012e1 100644 --- a/src/test/java/io/floci/aws/services/iam/StsFederationCallerEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsFederationCallerEnforcementIntegrationTest.java @@ -19,7 +19,10 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; import static org.junit.jupiter.api.Assertions.assertNotNull; /** @@ -91,7 +94,10 @@ class StsFederationCallerEnforcementIntegrationTest { remember(result, "GetFederationToken"); } else { result.then().statusCode(403).body("ErrorResponse.Error.Code", equalTo("AccessDenied")) - .body("ErrorResponse.Error.Message", equalTo("User is not authorized to perform: sts:GetFederationToken")); + .body("ErrorResponse.Error.Message", allOf(startsWith("User: arn:aws:iam::" + ACCOUNT + ":user/"), + endsWith(" is not authorized to perform: sts:GetFederationToken on resource: " + + "arn:aws:sts::" + ACCOUNT + ":federated-user/longterm because no identity-based " + + "policy allows the sts:GetFederationToken action"))); } } @@ -112,8 +118,10 @@ class StsFederationCallerEnforcementIntegrationTest { Credentials user = userWithPolicy(ALLOW_STS_DENY_FEDERATION_TOKEN); request(user, "GetFederationToken", Map.of("Name", "still-denied")).then().statusCode(403) .body("ErrorResponse.Error.Code", equalTo("AccessDenied")) - .body("ErrorResponse.Error.Message", - equalTo("User is not authorized to perform: sts:GetFederationToken")); + .body("ErrorResponse.Error.Message", allOf(startsWith("User: arn:aws:iam::" + ACCOUNT + ":user/"), + endsWith(" is not authorized to perform: sts:GetFederationToken on resource: arn:aws:sts::" + + ACCOUNT + ":federated-user/still-denied with an explicit deny in an identity-based " + + "policy"))); } @Test