From f76de9c4635aced5ec2334b13ae431f5eeb64a72 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:35:09 -0400 Subject: [PATCH] refactor(iam): move request operation resolution out of the enforcement filter (#8785) IamEnforcementFilter works out which service a request reaches, the operation it calls there and the IAM action that operation is authorized as, for Query, Smithy RPC v2, JSON and REST requests alike. That lives in private methods of the filter and runs only while IAM enforcement is on. The fault-injection half of #4623 needs the same answer for every request, enforcement on or off, to match FIS inject-api actions against the operations they name. Move it, unchanged, into RequestOperationResolver: - ResolvedAuthorization becomes the public ResolvedOperation record. - The resolver is an application-scoped bean rather than a JAX-RS provider, so it takes the matched ResourceInfo as a parameter. - The filter builds its own instance from the four collaborators it already holds, so none of its constructors change. RequestOperationResolverTest covers each protocol against the real service catalog and action rules, with no Quarkus boot. Refs #4623 --- .../aws/core/common/IamEnforcementFilter.java | 208 ++-------------- .../core/common/RequestOperationResolver.java | 228 ++++++++++++++++++ .../common/RequestOperationResolverTest.java | 122 ++++++++++ 3 files changed, 365 insertions(+), 193 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/RequestOperationResolver.java create mode 100644 src/test/java/io/floci/aws/core/common/RequestOperationResolverTest.java 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 3a57ee6491..2c0857a657 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -2,12 +2,12 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RequestOperationResolver.ResolvedOperation; import io.floci.aws.services.cloudtrail.CloudTrailService; 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.IamPolicyEvaluator; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; import io.floci.aws.services.iam.IamPolicyEvaluator.ResourceAccountRelationship; @@ -221,6 +221,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private final Clock clock; private final ResourceInfo resourceInfo; private final Instance s3ServiceProvider; + private final RequestOperationResolver operationResolver; @Inject public IamEnforcementFilter(EmulatorConfig config, @@ -261,6 +262,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { this.clock = clock; this.resourceInfo = resourceInfo; this.s3ServiceProvider = s3ServiceProvider; + this.operationResolver = + new RequestOperationResolver(actionRegistry, queryServiceResolver, arnBuilder, catalog); } /** Package-private constructor for callers predating s3ServiceProvider. */ @@ -356,7 +359,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if (!config.services().iam().enforcementEnabled()) { return; } - ProtocolClaim rpcV2Route = rpcV2RouteClaim(ctx); + ProtocolClaim rpcV2Route = operationResolver.rpcV2RouteClaim(ctx, resourceInfo); if (rpcV2Route != null) { // The claim filter runs before routing and can leave a call this endpoint serves // unclaimed, as an unrecognised smithy-protocol value does. Every check below that reads @@ -400,9 +403,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { // action rules, ARN building and condition keys all match the canonical name, so an // alias would resolve to no action and be allowed through without any policy check. String claimedScope = catalog.canonicalCredentialScope(rawScope); - ResolvedAuthorization resolvedAuthorization = resolveAuthorization(auth, claimedScope, ctx); - String credentialScope = resolvedAuthorization.credentialScope(); - String action = resolvedAuthorization.action(); + ResolvedOperation resolvedOperation = operationResolver.resolve(auth, claimedScope, ctx, resourceInfo); + String credentialScope = resolvedOperation.credentialScope(); + String action = resolvedOperation.action(); if (IamActionRegistry.takenByDocumentedRoute(credentialScope, ctx)) { // Another API's request (Glue's Iceberg REST endpoint takes Apache Iceberg's) carries none of the // operation's members, so none is read from it: not its resources, condition keys, tags or roles. @@ -510,7 +513,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } List resources = resolveResourceArns(credentialScope, - targetResources(credentialScope, action, resolvedAuthorization.operation(), ctx, region, accountId)); + targetResources(credentialScope, action, resolvedOperation.operation(), ctx, region, accountId)); Optional presignedScope = iamService.presignedScope(akid); if (presignedScope.isPresent()) { @@ -596,7 +599,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } // A create that carries tags is checked with them where its own action takes them, as the tagging // action it also needs is (see TagOnCreate); keys the service's own resolver gives are kept. - Optional tagOnCreate = TagOnCreate.of(resolvedAuthorization.operation(), ctx); + Optional tagOnCreate = TagOnCreate.of(resolvedOperation.operation(), ctx); List>> requestTags = tagOnCreate.filter(TagOnCreate.Tagging::requestTags) .map(TagOnCreate::requestTagContexts).orElse(List.of()); List>> targetContexts = withRequestTags(conditionContext, requestTags); @@ -631,16 +634,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter { region, accountId, akid)) { return; } - if (abortIfConnectorPassDenied(ctx, caller, callerArns.orElse(null), resolvedAuthorization.operation(), + if (abortIfConnectorPassDenied(ctx, caller, callerArns.orElse(null), resolvedOperation.operation(), region, accountId, akid)) { return; } if (abortIfForwardedDenied(ctx, caller, principal, callerArns.orElse(null), action, - resolvedAuthorization.operation(), credentialScope, resources, region, accountId, akid)) { + resolvedOperation.operation(), credentialScope, resources, region, accountId, akid)) { return; } if (tagOnCreate.isPresent() && abortIfTagOnCreateDenied(ctx, caller, principal, callerArns.orElse(null), - action, resolvedAuthorization.operation(), tagOnCreate.get(), credentialScope, resources, region, + action, resolvedOperation.operation(), tagOnCreate.get(), credentialScope, resources, region, accountId, akid)) { return; } @@ -846,112 +849,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return !value.equals("*") && !value.equals("\"*\""); } - /** - * Resolves both the IAM namespace and action from the service that will actually handle the - * request. Query traffic shares the dispatch resolver with {@link AwsQueryController}; an RPC v2 - * call takes the service and operation its route dispatches; REST traffic uses the JAX-RS - * resource class that won route matching. - */ - private ResolvedAuthorization resolveAuthorization(String auth, String claimedScope, - ContainerRequestContext ctx) { - Object claimValue = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY); - // Form POSTs are also recognized without a claim; GET dispatch requires the Query claim. - if (IamActionRegistry.isQueryRequest(ctx)) { - String queryAction = actionRegistry.queryAction(ctx); - if (queryAction == null || queryAction.isBlank()) { - return new ResolvedAuthorization(claimedScope, null); - } - String service = queryServiceResolver.resolve(auth, queryAction, actionRegistry.queryVersion(ctx)); - String servingScope = catalog.byExternalKey(service) - .map(descriptor -> iamServiceScope(descriptor, claimedScope)) - .orElseGet(() -> catalog.canonicalCredentialScope(service)); - return new ResolvedAuthorization(servingScope, - IamAuthorizedActions.actionFor(servingScope, queryAction), servingScope + ":" + queryAction); - } - - // Read from the route rather than the claim: a path the claim filter takes for RPC v2 can - // reach another route, and an X-Amz-Target header names an operation this endpoint ignores. - ProtocolClaim rpcV2Route = rpcV2RouteClaim(ctx); - if (rpcV2Route != null) { - if (rpcV2Route.service() == null) { - return new ResolvedAuthorization(claimedScope, null); // no service: the endpoint answers 404 - } - String servingScope = iamServiceScope(rpcV2Route.service(), claimedScope); - return new ResolvedAuthorization(servingScope, - actionRegistry.resolveOperation(servingScope, rpcV2Route.operation(), ctx), - servingScope + ":" + rpcV2Route.operation()); - } - - ResolvedAuthorization routeAuthorization = restRouteAuthorization(ctx); - if (routeAuthorization != null) { - return routeAuthorization; - } - - // A REST request is authorized by its route alone, never by an X-Amz-Target it carries. - boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST; - String servingScope = servingCredentialScope(claimedScope, ctx); - if (rest) { - return authorizationForRoute(servingScope, ctx); - } - String targetOperation = IamActionRegistry.targetOperation(ctx); - String action = actionRegistry.resolve(servingScope, ctx); - return targetOperation == null ? new ResolvedAuthorization(servingScope, action) - : new ResolvedAuthorization(servingScope, action, servingScope + ":" + targetOperation); - } - - /** - * The claim of a call JAX-RS routed to the Smithy RPC v2 endpoint, made from the service and - * operation in the route's path parameters, which are what that endpoint dispatches. Null for - * any other request. - */ - private ProtocolClaim rpcV2RouteClaim(ContainerRequestContext ctx) { - if (resourceInfo == null || !AwsJsonCborController.class.equals(resourceInfo.getResourceClass())) { - return null; - } - return ProtocolClaimer.rpcV2RouteClaim(catalog, ctx.getUriInfo().getPathParameters()); - } - - /** - * The action a REST request's matched route maps to, read from the route alone. Null for any - * other request, and for a route no rule maps. - */ - private ResolvedAuthorization restRouteAuthorization(ContainerRequestContext ctx) { - if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim) - || claim.protocol() != WireProtocol.REST - || resourceInfo == null || resourceInfo.getResourceClass() == null) { - return null; - } - Class resourceClass = resourceInfo.getResourceClass(); - if (SharedTagsController.class.equals(resourceClass) || V1TagsController.class.equals(resourceClass)) { - return taggedServiceAuthorization(ctx); - } - return catalog.byResourceClass(resourceClass) - .map(descriptor -> resolveRestAuthorization(descriptor, ctx)) - .orElse(null); - } - - /** - * A shared tagging route hands the request to the service its ARN names, so it is checked as that - * service whatever scope it is signed with. A service with no rule for the route leaves it unchecked, as - * any route no rule maps; an ARN naming no service Floci serves, which the controller refuses, is left - * to the signing scope. - */ - private ResolvedAuthorization taggedServiceAuthorization(ContainerRequestContext ctx) { - String arn = arnBuilder.taggedArn(ctx); - if (!AwsArnUtils.isArn(arn)) { - return null; - } - String service = AwsArnUtils.parse(arn).service(); - return catalog.byCredentialScope(service) - .map(descriptor -> { - ResolvedAuthorization authorization = resolveRestAuthorization(descriptor, ctx); - return authorization != null - ? authorization - : new ResolvedAuthorization(catalog.canonicalCredentialScope(service), null); - }) - .orElse(null); - } - /** * Refuses a request whose {@code Authorization} header this filter cannot read a credential * from: an empty one, one naming no access key (a Bearer token, SigV2, a credential without the @@ -979,7 +876,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { && servesWithoutCredentials(claim, ctx)) { return; } - ResolvedAuthorization routeAuthorization = claimsSigV4(auth) ? restRouteAuthorization(ctx) : null; + ResolvedOperation routeAuthorization = + claimsSigV4(auth) ? operationResolver.restRoute(ctx, resourceInfo) : null; if (routeAuthorization == null && !isRpcCall(ctx)) { return; } @@ -1022,39 +920,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter { && claim.protocol() != WireProtocol.REST; } - private String routeAction(String scope, ContainerRequestContext ctx) { - String matched = actionRegistry.resolveMatchedRoute(scope, resourceInfo); - return matched != null ? matched : actionRegistry.resolveRoute(scope, ctx); - } - - private ResolvedAuthorization resolveRestAuthorization(ServiceDescriptor descriptor, - ContainerRequestContext ctx) { - return descriptor.credentialScopes().stream() - .map(catalog::canonicalCredentialScope) - .distinct() - .sorted() - .map(scope -> authorizationForRoute(scope, ctx)) - .filter(authorization -> authorization.action() != null) - .findFirst() - .orElse(null); - } - - private ResolvedAuthorization authorizationForRoute(String scope, ContainerRequestContext ctx) { - String action = routeAction(scope, ctx); - return new ResolvedAuthorization(scope, action, actionRegistry.operationForRoute(scope, action, ctx)); - } - - /** - * The scope and action a request is authorized as, and the operation it calls as - * {@code :}, which differs from the action for one AWS authorizes under another name. - * A modeled REST route retains its operation when AWS authorizes it under another action name. - */ - private record ResolvedAuthorization(String credentialScope, String action, String operation) { - ResolvedAuthorization(String credentialScope, String action) { - this(credentialScope, action, action); - } - } - /** Floci's account-root principal, which is both the caller and the request's aws:PrincipalArn. */ /** * The caller as this request authenticated it, which for the two operations that take a device @@ -1427,49 +1292,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return false; } - /** - * The scope of the service that will actually serve this request, which is not always the one - * the caller signed for. Everything keyed by scope (the action, its ARNs, its condition keys) - * has to describe the service that runs, or a policy naming that service never matches. - * - *

Only the claim decides this, never {@code X-Amz-Target} read directly: the target routes - * a request solely under the conditions {@link ProtocolClaimer} applies, and reading it here - * would let a header attached to, say, an S3 request move the authorization to another - * service while S3 still served it. - * - *

{@link WireProtocol#AWS_QUERY} is resolved before this method by - * {@link #resolveAuthorization(String, String, ContainerRequestContext)}, which shares - * {@link AwsQueryServiceResolver} with the controller so IAM enforcement follows the service - * that will handle the request. - */ - private String servingCredentialScope(String claimedScope, ContainerRequestContext ctx) { - if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim - && claim.service() != null - && claim.protocol() != WireProtocol.AWS_QUERY) { - return iamServiceScope(claim.service(), claimedScope); - } - return claimedScope; - } - - /** The descriptor's own scope, keeping {@code claimedScope} when the descriptor accepts it. */ - private String iamServiceScope(ServiceDescriptor descriptor, String claimedScope) { - if (descriptor.credentialScopes().contains(claimedScope)) { - return claimedScope; - } - // The service's own key, not just any scope it signs under: pricing accepts both - // "pricing" and "api.pricing", and only the former is the namespace its policies name. - // Sorting the rest keeps the choice stable, since credentialScopes is a Set.of whose - // iteration order changes per JVM run. - if (descriptor.credentialScopes().contains(descriptor.externalKey())) { - return catalog.canonicalCredentialScope(descriptor.externalKey()); - } - return descriptor.credentialScopes().stream() - .filter(scope -> scope.equals(catalog.canonicalCredentialScope(scope))) - .sorted() - .findFirst() - .orElse(catalog.canonicalCredentialScope(descriptor.externalKey())); - } - /** The same contexts with every object-tag key removed, keeping the principal and global keys. */ private static List>> withoutObjectTags( List>> targetContexts) { diff --git a/src/main/java/io/floci/aws/core/common/RequestOperationResolver.java b/src/main/java/io/floci/aws/core/common/RequestOperationResolver.java new file mode 100644 index 0000000000..6ad18485d5 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/RequestOperationResolver.java @@ -0,0 +1,228 @@ +package io.floci.aws.core.common; + +import io.floci.aws.services.iam.IamActionRegistry; +import io.floci.aws.services.iam.IamAuthorizedActions; +import io.floci.aws.services.iam.ResourceArnBuilder; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ResourceInfo; + +/** + * Works out which service a request reaches, the operation it calls there and the IAM action that operation is + * authorized as, from the service that will actually handle it rather than the scope it was signed with. + * + *

Query traffic shares the dispatch resolver with {@link AwsQueryController}; a Smithy RPC v2 call takes the + * service and operation its route dispatches; a JSON call the service its protocol claim names and the operation in + * its {@code X-Amz-Target}; and REST traffic the JAX-RS resource class that won route matching, so a REST request is + * never moved by an {@code X-Amz-Target} it carries. + * + *

The route is only known once JAX-RS has matched one, so it is called from a post-matching filter with that + * request's {@link ResourceInfo}. Stateless, and safe to share between requests. + */ +@ApplicationScoped +public class RequestOperationResolver { + + private final IamActionRegistry actionRegistry; + private final AwsQueryServiceResolver queryServiceResolver; + private final ResourceArnBuilder arnBuilder; + private final ResolvedServiceCatalog catalog; + + @Inject + public RequestOperationResolver(IamActionRegistry actionRegistry, + AwsQueryServiceResolver queryServiceResolver, + ResourceArnBuilder arnBuilder, + ResolvedServiceCatalog catalog) { + this.actionRegistry = actionRegistry; + this.queryServiceResolver = queryServiceResolver; + this.arnBuilder = arnBuilder; + this.catalog = catalog; + } + + /** + * Resolves both the IAM namespace and action from the service that will actually handle the request. + * + * @param auth the request's {@code Authorization} header, or the {@code Credential=} string built from a + * presigned URL, which the Query dispatch reads the signing service from + * @param claimedScope the canonical credential scope the request is signed with, kept when no service is found + * @param ctx the request, after route matching + * @param resourceInfo the matched route, or {@code null} when none matched + */ + public ResolvedOperation resolve(String auth, String claimedScope, ContainerRequestContext ctx, + ResourceInfo resourceInfo) { + Object claimValue = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY); + // Form POSTs are also recognized without a claim; GET dispatch requires the Query claim. + if (IamActionRegistry.isQueryRequest(ctx)) { + String queryAction = actionRegistry.queryAction(ctx); + if (queryAction == null || queryAction.isBlank()) { + return new ResolvedOperation(claimedScope, null); + } + String service = queryServiceResolver.resolve(auth, queryAction, actionRegistry.queryVersion(ctx)); + String servingScope = catalog.byExternalKey(service) + .map(descriptor -> iamServiceScope(descriptor, claimedScope)) + .orElseGet(() -> catalog.canonicalCredentialScope(service)); + return new ResolvedOperation(servingScope, + IamAuthorizedActions.actionFor(servingScope, queryAction), servingScope + ":" + queryAction); + } + + // Read from the route rather than the claim: a path the claim filter takes for RPC v2 can + // reach another route, and an X-Amz-Target header names an operation this endpoint ignores. + ProtocolClaim rpcV2Route = rpcV2RouteClaim(ctx, resourceInfo); + if (rpcV2Route != null) { + if (rpcV2Route.service() == null) { + return new ResolvedOperation(claimedScope, null); // no service: the endpoint answers 404 + } + String servingScope = iamServiceScope(rpcV2Route.service(), claimedScope); + return new ResolvedOperation(servingScope, + actionRegistry.resolveOperation(servingScope, rpcV2Route.operation(), ctx), + servingScope + ":" + rpcV2Route.operation()); + } + + ResolvedOperation routeOperation = restRoute(ctx, resourceInfo); + if (routeOperation != null) { + return routeOperation; + } + + // A REST request is authorized by its route alone, never by an X-Amz-Target it carries. + boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST; + String servingScope = servingCredentialScope(claimedScope, ctx); + if (rest) { + return operationForRoute(servingScope, ctx, resourceInfo); + } + String targetOperation = IamActionRegistry.targetOperation(ctx); + String action = actionRegistry.resolve(servingScope, ctx); + return targetOperation == null ? new ResolvedOperation(servingScope, action) + : new ResolvedOperation(servingScope, action, servingScope + ":" + targetOperation); + } + + /** + * The claim of a call JAX-RS routed to the Smithy RPC v2 endpoint, made from the service and + * operation in the route's path parameters, which are what that endpoint dispatches. Null for + * any other request. + */ + ProtocolClaim rpcV2RouteClaim(ContainerRequestContext ctx, ResourceInfo resourceInfo) { + if (resourceInfo == null || !AwsJsonCborController.class.equals(resourceInfo.getResourceClass())) { + return null; + } + return ProtocolClaimer.rpcV2RouteClaim(catalog, ctx.getUriInfo().getPathParameters()); + } + + /** + * The action a REST request's matched route maps to, read from the route alone. Null for any + * other request, and for a route no rule maps. + */ + ResolvedOperation restRoute(ContainerRequestContext ctx, ResourceInfo resourceInfo) { + if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim) + || claim.protocol() != WireProtocol.REST + || resourceInfo == null || resourceInfo.getResourceClass() == null) { + return null; + } + Class resourceClass = resourceInfo.getResourceClass(); + if (SharedTagsController.class.equals(resourceClass) || V1TagsController.class.equals(resourceClass)) { + return taggedServiceOperation(ctx, resourceInfo); + } + return catalog.byResourceClass(resourceClass) + .map(descriptor -> restOperation(descriptor, ctx, resourceInfo)) + .orElse(null); + } + + /** + * A shared tagging route hands the request to the service its ARN names, so it is checked as that + * service whatever scope it is signed with. A service with no rule for the route leaves it unchecked, as + * any route no rule maps; an ARN naming no service Floci serves, which the controller refuses, is left + * to the signing scope. + */ + private ResolvedOperation taggedServiceOperation(ContainerRequestContext ctx, ResourceInfo resourceInfo) { + String arn = arnBuilder.taggedArn(ctx); + if (!AwsArnUtils.isArn(arn)) { + return null; + } + String service = AwsArnUtils.parse(arn).service(); + return catalog.byCredentialScope(service) + .map(descriptor -> { + ResolvedOperation operation = restOperation(descriptor, ctx, resourceInfo); + return operation != null + ? operation + : new ResolvedOperation(catalog.canonicalCredentialScope(service), null); + }) + .orElse(null); + } + + private String routeAction(String scope, ContainerRequestContext ctx, ResourceInfo resourceInfo) { + String matched = actionRegistry.resolveMatchedRoute(scope, resourceInfo); + return matched != null ? matched : actionRegistry.resolveRoute(scope, ctx); + } + + private ResolvedOperation restOperation(ServiceDescriptor descriptor, ContainerRequestContext ctx, + ResourceInfo resourceInfo) { + return descriptor.credentialScopes().stream() + .map(catalog::canonicalCredentialScope) + .distinct() + .sorted() + .map(scope -> operationForRoute(scope, ctx, resourceInfo)) + .filter(operation -> operation.action() != null) + .findFirst() + .orElse(null); + } + + private ResolvedOperation operationForRoute(String scope, ContainerRequestContext ctx, + ResourceInfo resourceInfo) { + String action = routeAction(scope, ctx, resourceInfo); + return new ResolvedOperation(scope, action, actionRegistry.operationForRoute(scope, action, ctx)); + } + + /** + * The scope of the service that will actually serve this request, which is not always the one + * the caller signed for. Everything keyed by scope (the action, its ARNs, its condition keys) + * has to describe the service that runs, or a policy naming that service never matches. + * + *

Only the claim decides this, never {@code X-Amz-Target} read directly: the target routes + * a request solely under the conditions {@link ProtocolClaimer} applies, and reading it here + * would let a header attached to, say, an S3 request move the authorization to another + * service while S3 still served it. + * + *

{@link WireProtocol#AWS_QUERY} is resolved before this method by + * {@link #resolve(String, String, ContainerRequestContext, ResourceInfo)}, which shares + * {@link AwsQueryServiceResolver} with the controller so IAM enforcement follows the service + * that will handle the request. + */ + private String servingCredentialScope(String claimedScope, ContainerRequestContext ctx) { + if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim + && claim.service() != null + && claim.protocol() != WireProtocol.AWS_QUERY) { + return iamServiceScope(claim.service(), claimedScope); + } + return claimedScope; + } + + /** The descriptor's own scope, keeping {@code claimedScope} when the descriptor accepts it. */ + private String iamServiceScope(ServiceDescriptor descriptor, String claimedScope) { + if (descriptor.credentialScopes().contains(claimedScope)) { + return claimedScope; + } + // The service's own key, not just any scope it signs under: pricing accepts both + // "pricing" and "api.pricing", and only the former is the namespace its policies name. + // Sorting the rest keeps the choice stable, since credentialScopes is a Set.of whose + // iteration order changes per JVM run. + if (descriptor.credentialScopes().contains(descriptor.externalKey())) { + return catalog.canonicalCredentialScope(descriptor.externalKey()); + } + return descriptor.credentialScopes().stream() + .filter(scope -> scope.equals(catalog.canonicalCredentialScope(scope))) + .sorted() + .findFirst() + .orElse(catalog.canonicalCredentialScope(descriptor.externalKey())); + } + + /** + * The scope and action a request is authorized as, and the operation it calls as + * {@code :}, which differs from the action for one AWS authorizes under another name. + * A modeled REST route retains its operation when AWS authorizes it under another action name. The action is + * {@code null} when no rule maps the request, and so is the operation when nothing names one. + */ + public record ResolvedOperation(String credentialScope, String action, String operation) { + ResolvedOperation(String credentialScope, String action) { + this(credentialScope, action, action); + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/RequestOperationResolverTest.java b/src/test/java/io/floci/aws/core/common/RequestOperationResolverTest.java new file mode 100644 index 0000000000..d90bb179e2 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/RequestOperationResolverTest.java @@ -0,0 +1,122 @@ +package io.floci.aws.core.common; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.RequestOperationResolver.ResolvedOperation; +import io.floci.aws.services.iam.IamActionRegistry; +import io.floci.aws.services.iam.ResourceArnBuilder; +import io.floci.aws.services.s3.S3Controller; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ResourceInfo; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriInfo; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * {@link RequestOperationResolver} on its own, outside {@link IamEnforcementFilter}, with the real service catalog + * and action rules: each protocol resolves to the service that serves the request and the operation it calls there. + */ +class RequestOperationResolverTest { + + private static final String SIGNED_FOR = "AWS4-HMAC-SHA256 " + + "Credential=AKIAEXAMPLE/20261117/us-east-1/%s/aws4_request, " + + "SignedHeaders=host;x-amz-date, Signature=deadbeef"; + + private final ResolvedServiceCatalog catalog = + new ResolvedServiceCatalog(mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)); + private final RequestOperationResolver resolver = new RequestOperationResolver(new IamActionRegistry(), + new AwsQueryServiceResolver(catalog), new ResourceArnBuilder(new ObjectMapper()), catalog); + + @Test + void aQueryCallResolvesToTheOperationItsActionNames() { + MultivaluedMap query = new MultivaluedHashMap<>(); + query.add("Action", "DescribeInstances"); + query.add("Version", "2016-11-15"); + ContainerRequestContext ctx = request("GET", "/", query, Map.of(), + new ProtocolClaim(WireProtocol.AWS_QUERY, catalog.byExternalKey("ec2").orElseThrow(), null, null)); + + ResolvedOperation resolved = resolver.resolve(SIGNED_FOR.formatted("ec2"), "ec2", ctx, null); + + assertEquals(new ResolvedOperation("ec2", "ec2:DescribeInstances", "ec2:DescribeInstances"), resolved); + } + + @Test + void aJsonCallResolvesToTheOperationItsTargetNames() { + ContainerRequestContext ctx = request("POST", "/", new MultivaluedHashMap<>(), + Map.of("X-Amz-Target", "Kinesis_20131202.PutRecord"), jsonClaim("kinesis", "PutRecord")); + + ResolvedOperation resolved = resolver.resolve(SIGNED_FOR.formatted("kinesis"), "kinesis", ctx, null); + + assertEquals(new ResolvedOperation("kinesis", "kinesis:PutRecord", "kinesis:PutRecord"), resolved); + } + + @Test + void aCallIsResolvedAsTheServiceThatServesItRatherThanTheScopeItIsSignedFor() { + ContainerRequestContext ctx = request("POST", "/", new MultivaluedHashMap<>(), + Map.of("X-Amz-Target", "DynamoDB_20120810.PutItem"), jsonClaim("dynamodb", "PutItem")); + + ResolvedOperation resolved = resolver.resolve(SIGNED_FOR.formatted("sqs"), "sqs", ctx, null); + + assertEquals("dynamodb", resolved.credentialScope()); + assertEquals("dynamodb:PutItem", resolved.action()); + } + + @Test + void aRestRequestIsResolvedByItsRouteAndNotByAnXAmzTargetItCarries() { + ContainerRequestContext ctx = request("GET", "/bucket/key", new MultivaluedHashMap<>(), + Map.of("X-Amz-Target", "Kinesis_20131202.DeleteStream"), ProtocolClaim.rest()); + ResourceInfo route = mock(ResourceInfo.class); + doReturn(S3Controller.class).when(route).getResourceClass(); + + ResolvedOperation resolved = resolver.resolve(SIGNED_FOR.formatted("s3"), "s3", ctx, route); + + assertEquals(new ResolvedOperation("s3", "s3:GetObject", "s3:GetObject"), resolved); + } + + @Test + void aRequestNoRuleMapsKeepsTheScopeItIsSignedFor() { + MultivaluedMap query = new MultivaluedHashMap<>(); + query.add("Version", "2016-11-15"); + ContainerRequestContext ctx = request("GET", "/", query, Map.of(), + new ProtocolClaim(WireProtocol.AWS_QUERY, catalog.byExternalKey("ec2").orElseThrow(), null, null)); + + ResolvedOperation resolved = resolver.resolve(SIGNED_FOR.formatted("ec2"), "ec2", ctx, null); + + assertEquals(new ResolvedOperation("ec2", null, null), resolved); + } + + private ProtocolClaim jsonClaim(String service, String operation) { + ServiceDescriptor descriptor = catalog.byExternalKey(service).orElseThrow(); + return new ProtocolClaim(WireProtocol.AWS_JSON_1_1, descriptor, operation, null); + } + + private static ContainerRequestContext request(String method, String path, MultivaluedMap query, + Map headers, ProtocolClaim claim) { + ContainerRequestContext ctx = mock(ContainerRequestContext.class); + when(ctx.getMethod()).thenReturn(method); + when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(claim); + when(ctx.getHeaderString(anyString())).thenAnswer(invocation -> headers.get(invocation.getArgument(0))); + when(ctx.getMediaType()).thenReturn("POST".equals(method) + ? MediaType.valueOf("application/x-amz-json-1.1") : null); + UriInfo uri = mock(UriInfo.class); + when(uri.getPath()).thenReturn(path); + when(uri.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + path)); + when(uri.getBaseUri()).thenReturn(URI.create("http://localhost:4566/")); + when(uri.getQueryParameters()).thenReturn(query); + when(uri.getPathParameters()).thenReturn(new MultivaluedHashMap<>()); + when(ctx.getUriInfo()).thenReturn(uri); + return ctx; + } +}