fix(iam): authorize REST and Query serving services (#4419)

* fix(iam): authorize REST and Query serving services

* fix(iam): enforce Operation query actions

* fix(iam): scope Operation fallback to Query requests

* style(iam): import CurrentVertxRequest in tests

* fix(iam): ignore Action fields on REST routes

* fix(iam): authorize Query actions from dispatched form body

* fix(iam): make Query authorization independent of claim order
This commit is contained in:
XuJian authored and GitHub committed 2026-09-27 08:54:31 -04:00
1 parent 9c93e6ab7b
commit 228086ddb3
10 files changed
+668 -112

No files matched your search

@@ -212,7 +212,7 @@ public class AwsQueryController {
private final AutoScalingQueryHandler autoScalingQueryHandler;
private final ElasticBeanstalkQueryHandler elasticBeanstalkQueryHandler;
private final RedshiftQueryHandler redshiftQueryHandler;
private final ResolvedServiceCatalog catalog;
private final AwsQueryServiceResolver serviceResolver;
private final RegionResolver regionResolver;
@Inject
@@ -235,7 +235,7 @@ public class AwsQueryController {
AutoScalingQueryHandler autoScalingQueryHandler,
ElasticBeanstalkQueryHandler elasticBeanstalkQueryHandler,
RedshiftQueryHandler redshiftQueryHandler,
ResolvedServiceCatalog catalog,
AwsQueryServiceResolver serviceResolver,
RegionResolver regionResolver) {
this.cloudFormationQueryHandler = cloudFormationQueryHandler;
this.elastiCacheQueryHandler = elastiCacheQueryHandler;
@@ -258,7 +258,7 @@ public class AwsQueryController {
this.autoScalingQueryHandler = autoScalingQueryHandler;
this.elasticBeanstalkQueryHandler = elasticBeanstalkQueryHandler;
this.redshiftQueryHandler = redshiftQueryHandler;
this.catalog = catalog;
this.serviceResolver = serviceResolver;
this.regionResolver = regionResolver;
}
@@ -270,16 +270,13 @@ public class AwsQueryController {
@Context HttpHeaders httpHeaders,
MultivaluedMap<String, String> formParams) {
String action = formParams.getFirst("Action");
if (action == null) {
action = formParams.getFirst("Operation");
}
String action = AwsQueryServiceResolver.action(formParams);
if (action == null) {
return xmlErrorResponse("MissingAction",
"The request must contain the parameter Action", 400);
}
String service = resolveService(authorization, action);
String service = serviceResolver.resolve(authorization, action);
LOG.debugv("Query protocol service={0} action={1}", service, action);
String region = regionResolver.resolveRegion(httpHeaders);
@@ -620,17 +617,7 @@ public class AwsQueryController {
"GetClusterCredentials", "GetClusterCredentialsWithIAM"
);
private String resolveService(String authorization, String action) {
ServiceDescriptor descriptor = SigV4CredentialScope.serviceName(authorization)
.flatMap(catalog::byCredentialScope)
.orElse(null);
if (descriptor != null && descriptor.supportsProtocol(ServiceProtocol.QUERY)) {
return descriptor.externalKey();
}
return inferServiceFromAction(action);
}
private String inferServiceFromAction(String action) {
static String inferServiceFromAction(String action) {
if (STS_ACTIONS.contains(action)) {
return "sts";
}
@@ -0,0 +1,41 @@
package io.github.hectorvent.floci.core.common;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
/**
* Resolves the service that {@link AwsQueryController} will dispatch a Query-protocol action to.
* IAM enforcement uses the same result so a caller-chosen signing scope cannot select a different
* policy namespace from the handler that actually runs.
*/
@ApplicationScoped
public class AwsQueryServiceResolver {
private final ResolvedServiceCatalog catalog;
@Inject
public AwsQueryServiceResolver(ResolvedServiceCatalog catalog) {
this.catalog = catalog;
}
public String resolve(String authorization, String action) {
ServiceDescriptor descriptor = SigV4CredentialScope.serviceName(authorization)
.flatMap(catalog::byCredentialScope)
.orElse(null);
if (descriptor != null && descriptor.supportsProtocol(ServiceProtocol.QUERY)) {
return descriptor.externalKey();
}
return AwsQueryController.inferServiceFromAction(action);
}
/** Returns the operation the Query controller will dispatch from a form request. */
public static String action(MultivaluedMap<String, String> formParams) {
return action(formParams.getFirst("Action"), formParams.getFirst("Operation"));
}
/** Applies the Query controller's legacy {@code Operation} fallback. */
public static String action(String action, String operation) {
return action != null ? action : operation;
}
}
@@ -18,6 +18,8 @@ import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.Provider;
@@ -81,6 +83,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private final IamService iamService;
private final IamPolicyEvaluator evaluator;
private final IamActionRegistry actionRegistry;
private final AwsQueryServiceResolver queryServiceResolver;
private final ResourceArnBuilder arnBuilder;
private final RequestContext requestContext;
private final IamConditionContextResolver conditionContextResolver;
@@ -90,6 +93,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private final Instance<ScpProvider> scpProvider;
private final SessionAccountLookup sessionAccountLookup;
private final Instance<ResourcePolicyProvider> resourcePolicyProviders;
private final ResourceInfo resourceInfo;
@Inject
public IamEnforcementFilter(EmulatorConfig config,
@@ -97,6 +101,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
IamService iamService,
IamPolicyEvaluator evaluator,
IamActionRegistry actionRegistry,
AwsQueryServiceResolver queryServiceResolver,
ResourceArnBuilder arnBuilder,
RequestContext requestContext,
IamConditionContextResolver conditionContextResolver,
@@ -105,12 +110,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
ResolvedServiceCatalog catalog,
Instance<ScpProvider> scpProvider,
SessionAccountLookup sessionAccountLookup,
Instance<ResourcePolicyProvider> resourcePolicyProviders) {
Instance<ResourcePolicyProvider> resourcePolicyProviders,
@Context ResourceInfo resourceInfo) {
this.config = config;
this.accountResolver = accountResolver;
this.iamService = iamService;
this.evaluator = evaluator;
this.actionRegistry = actionRegistry;
this.queryServiceResolver = queryServiceResolver;
this.arnBuilder = arnBuilder;
this.requestContext = requestContext;
this.conditionContextResolver = conditionContextResolver;
@@ -120,6 +127,28 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this.scpProvider = scpProvider;
this.sessionAccountLookup = sessionAccountLookup;
this.resourcePolicyProviders = resourcePolicyProviders;
this.resourceInfo = resourceInfo;
}
/** Package-private constructor for callers predating Query dispatch-aware enforcement. */
IamEnforcementFilter(EmulatorConfig config,
AccountResolver accountResolver,
IamService iamService,
IamPolicyEvaluator evaluator,
IamActionRegistry actionRegistry,
ResourceArnBuilder arnBuilder,
RequestContext requestContext,
IamConditionContextResolver conditionContextResolver,
CloudTrailService cloudTrailService,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog catalog,
Instance<ScpProvider> scpProvider,
SessionAccountLookup sessionAccountLookup,
Instance<ResourcePolicyProvider> resourcePolicyProviders) {
this(config, accountResolver, iamService, evaluator, actionRegistry,
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
scpProvider, sessionAccountLookup, resourcePolicyProviders, null);
}
/** Package-private constructor for callers predating resourcePolicyProviders. */
@@ -136,9 +165,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
ResolvedServiceCatalog catalog,
Instance<ScpProvider> scpProvider,
SessionAccountLookup sessionAccountLookup) {
this(config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
requestContext, conditionContextResolver, cloudTrailService, currentVertxRequest,
catalog, scpProvider, sessionAccountLookup, null);
this(config, accountResolver, iamService, evaluator, actionRegistry,
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
scpProvider, sessionAccountLookup, null, null);
}
@Override
@@ -167,9 +197,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
// Normalise signing aliases (s3express → s3) before anything keyed by scope runs:
// 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 credentialScope = servingCredentialScope(catalog.canonicalCredentialScope(rawScope), ctx);
String action = actionRegistry.resolve(credentialScope, ctx);
String claimedScope = catalog.canonicalCredentialScope(rawScope);
ResolvedAuthorization resolvedAuthorization = resolveAuthorization(auth, claimedScope, ctx);
String credentialScope = resolvedAuthorization.credentialScope();
String action = resolvedAuthorization.action();
if (action == null) {
return; // unknown action → ALLOW (permissive)
}
@@ -270,6 +301,57 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
}
/**
* 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}; 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);
// Authorization must not depend on the pre-matching claim filter running first.
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);
String servingScope = catalog.byExternalKey(service)
.map(descriptor -> iamServiceScope(descriptor, claimedScope))
.orElseGet(() -> catalog.canonicalCredentialScope(service));
return new ResolvedAuthorization(servingScope, servingScope + ":" + queryAction);
}
if (claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST
&& resourceInfo != null && resourceInfo.getResourceClass() != null) {
ServiceDescriptor descriptor = catalog.byResourceClass(resourceInfo.getResourceClass()).orElse(null);
if (descriptor != null) {
ResolvedAuthorization routeAuthorization = resolveRestAuthorization(descriptor, ctx);
if (routeAuthorization != null) {
return routeAuthorization;
}
}
}
String servingScope = servingCredentialScope(claimedScope, ctx);
return new ResolvedAuthorization(servingScope, actionRegistry.resolve(servingScope, ctx));
}
private ResolvedAuthorization resolveRestAuthorization(ServiceDescriptor descriptor,
ContainerRequestContext ctx) {
return descriptor.credentialScopes().stream()
.map(catalog::canonicalCredentialScope)
.distinct()
.sorted()
.map(scope -> new ResolvedAuthorization(scope, actionRegistry.resolve(scope, ctx)))
.filter(authorization -> authorization.action() != null)
.findFirst()
.orElse(null);
}
private record ResolvedAuthorization(String credentialScope, String action) {
}
/**
* Evaluates one action against every resource and target context, aborting the request with
* AccessDenied on the first DENY. Returns true when the request was aborted.
@@ -325,12 +407,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* would let a header attached to, say, an S3 request move the authorization to another
* service while S3 still served it.
*
* <p>{@link WireProtocol#AWS_QUERY} is out of scope for this method, not solved by it. A Query
* claim carries the credential-scope service, which restates the caller whenever that service
* serves Query at all; when it does not, {@code AwsQueryController} falls through to inferring
* the service from the action name and can dispatch somewhere else entirely. Closing that needs
* the controller's inference shared rather than duplicated here, and is tracked in
* <a href="https://github.com/floci-io/floci/issues/4296">#4296</a>.
* <p>{@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
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayController;
import io.github.hectorvent.floci.services.appconfig.AppConfigController;
import io.github.hectorvent.floci.services.backup.BackupController;
import io.github.hectorvent.floci.services.resourceexplorer2.ResourceExplorer2Controller;
@@ -73,6 +74,7 @@ import io.github.hectorvent.floci.services.marketplace.MarketplaceDeploymentCont
import io.github.hectorvent.floci.services.marketplace.MarketplaceDiscoveryController;
import io.github.hectorvent.floci.services.marketplace.MarketplaceReportingController;
import io.github.hectorvent.floci.services.sagemaker.SageMakerRuntimeController;
import io.github.hectorvent.floci.services.s3.S3Controller;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -118,7 +120,7 @@ public class ResolvedServiceCatalog {
5000L, AwsNamespaces.S3, ServiceProtocol.REST_XML,
protocols(ServiceProtocol.REST_XML),
// s3express: directory-bucket (S3 Express One Zone) clients sign with it
Set.of(), Set.of("s3", "s3express"), Set.of(), Set.of()),
Set.of(), Set.of("s3", "s3express"), Set.of(), Set.of(S3Controller.class)),
descriptor("dynamodb", "dynamodb", config.services().dynamodb().enabled(), true,
"dynamodb", storageMode(config.storage().services().dynamodb().mode(), config.storage().mode()),
config.storage().services().dynamodb().flushIntervalMs(), null, ServiceProtocol.JSON,
@@ -141,7 +143,8 @@ public class ResolvedServiceCatalog {
descriptor("apigateway", "apigateway", config.services().apigateway().enabled(), true,
"apigateway", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("apigateway", "execute-api"), Set.of(), Set.of()),
Set.of(), Set.of("apigateway", "execute-api"), Set.of(),
Set.of(ApiGatewayController.class)),
descriptor("iam", "iam", config.services().iam().enabled(), true,
"iam", config.storage().mode(), 5000L, AwsNamespaces.IAM, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
@@ -1,19 +1,21 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import org.jboss.logging.Logger;
import java.util.List;
import java.util.regex.Pattern;
import org.jboss.logging.Logger;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MultivaluedMap;
/**
* Maps (credentialScope, httpMethod, requestPath) → IAM action string.
*
* For Query-protocol services (SQS, SNS, IAM, STS, ...) the Action form
* parameter is mapped directly to {@code <service>:<Action>}.
* parameter, or the controller's Operation fallback, is mapped directly to
* {@code <service>:<Action>}.
*
* For REST-JSON services the first matching rule wins (specific before wildcard).
*/
@@ -93,8 +95,9 @@ public class IamActionRegistry {
/**
* Resolves the IAM action for an incoming request.
*
* For Query-protocol services the action comes directly from the {@code Action}
* form param (e.g. {@code sqs:SendMessage}).
* For Query-protocol requests the action comes from {@code Action} or
* {@code Operation} (e.g. {@code sqs:SendMessage}). REST requests never
* read these caller-controlled fields as an IAM action.
*
* For JSON 1.1 protocol the action comes from {@code X-Amz-Target}
* (e.g. {@code DynamoDB_20120810.PutItem} → {@code dynamodb:PutItem}).
@@ -104,16 +107,12 @@ public class IamActionRegistry {
* Returns {@code null} when the action is unknown (caller treats this as ALLOW).
*/
public String resolve(String credentialScope, ContainerRequestContext ctx) {
// Query-protocol: Action param → service:Action.
// AWS SDKs send Query-protocol calls (IAM, STS, EC2, SQS, SNS, ...) as
// POST with Action=... in the application/x-www-form-urlencoded body,
// not the URL query string — so we look in both places.
String queryAction = ctx.getUriInfo().getQueryParameters().getFirst("Action");
if (queryAction == null || queryAction.isBlank()) {
queryAction = readFormAction(ctx);
}
if (queryAction != null && !queryAction.isBlank()) {
return credentialScope + ":" + queryAction;
// REST requests with Action or Operation fields still use their method and path rules.
if (isQueryRequest(ctx)) {
String queryAction = queryAction(ctx);
if (queryAction != null && !queryAction.isBlank()) {
return credentialScope + ":" + queryAction;
}
}
// JSON 1.1: X-Amz-Target → service:OperationName
@@ -125,7 +124,7 @@ public class IamActionRegistry {
// REST-JSON: match against rule table
String method = ctx.getMethod().toUpperCase();
String path = ctx.getUriInfo().getPath();
String path = ctx.getUriInfo().getPath();
if (!path.startsWith("/")) path = "/" + path;
// S3 sub-resource override: the URL path alone doesn't distinguish
@@ -152,6 +151,30 @@ public class IamActionRegistry {
return null;
}
/**
* Returns the Query-protocol action from the form body while preserving the entity stream for
* the controller. The controller dispatches only the form body, using the same Action-first,
* Operation-second rule. A URL Action must not override the operation that will execute.
*/
public String queryAction(ContainerRequestContext ctx) {
return AwsQueryServiceResolver.action(
RequestBodyReader.formField(ctx, "Action"),
RequestBodyReader.formField(ctx, "Operation"));
}
/** The same form POST at the root that the Query controller dispatches. */
public static boolean isQueryRequest(ContainerRequestContext ctx) {
if (!"POST".equalsIgnoreCase(ctx.getMethod()) || ctx.getUriInfo() == null) {
return false;
}
String path = ctx.getUriInfo().getPath();
MediaType mediaType = ctx.getMediaType();
return (path == null || path.isEmpty() || "/".equals(path))
&& mediaType != null
&& "application".equalsIgnoreCase(mediaType.getType())
&& "x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype());
}
/** One bucket sub-resource operation: the query parameter that selects it, and the IAM action. */
private record SubResourceAction(String queryParameter, String action) {}
@@ -260,17 +283,4 @@ public class IamActionRegistry {
return null;
}
/**
* Reads {@code Action} from a {@code application/x-www-form-urlencoded}
* request body and restores the entity stream so downstream consumers
* (e.g. {@code AwsQueryController}'s {@code MultivaluedMap} injection)
* can still parse the form themselves. Returns {@code null} if the
* request is not form-encoded or the body has no {@code Action} field.
*/
private static String readFormAction(ContainerRequestContext ctx) {
// Delegates to RequestBodyReader so this and ResourceArnBuilder's per-service resource
// lookups share one buffered copy of the body per request instead of each independently
// reading (and needing to reset) the live entity stream.
return RequestBodyReader.formField(ctx, "Action");
}
}