mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class AwsQueryServiceResolverTest {
|
||||
|
||||
private ResolvedServiceCatalog catalog;
|
||||
private AwsQueryServiceResolver resolver;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = mock(ResolvedServiceCatalog.class);
|
||||
resolver = new AwsQueryServiceResolver(catalog);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedSignedScopeFallsBackToActionDispatch() {
|
||||
when(catalog.byCredentialScope("lambda")).thenReturn(Optional.of(
|
||||
descriptor("lambda", ServiceProtocol.REST_JSON)));
|
||||
|
||||
assertEquals("iam", resolver.resolve(authorization("lambda"), "CreateUser"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryCapableSignedScopeKeepsControllerDispatch() {
|
||||
when(catalog.byCredentialScope("sqs")).thenReturn(Optional.of(
|
||||
descriptor("sqs", ServiceProtocol.QUERY)));
|
||||
|
||||
assertEquals("sqs", resolver.resolve(authorization("sqs"), "CreateUser"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchingQueryScopeResolvesNormally() {
|
||||
when(catalog.byCredentialScope("iam")).thenReturn(Optional.of(
|
||||
descriptor("iam", ServiceProtocol.QUERY)));
|
||||
|
||||
assertEquals("iam", resolver.resolve(authorization("iam"), "CreateUser"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAuthorizationKeepsActionFallback() {
|
||||
assertEquals("sqs", resolver.resolve(null, "UnknownQueryAction"));
|
||||
}
|
||||
|
||||
private static String authorization(String scope) {
|
||||
return "AWS4-HMAC-SHA256 Credential=AKIA/20260925/us-east-1/" + scope
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
|
||||
private static ServiceDescriptor descriptor(String service, ServiceProtocol protocol) {
|
||||
return new ServiceDescriptor(service, service, true, true, service, "memory", 0L,
|
||||
null, protocol, Set.of(protocol), Set.of(), Set.of(service), Set.of(), Set.of());
|
||||
}
|
||||
}
|
||||
+163
-41
@@ -2,22 +2,26 @@ package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayController;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.iam.IamActionRegistry;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService;
|
||||
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.s3.S3Controller;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
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.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -35,6 +39,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -102,10 +107,22 @@ class IamEnforcementFilterTest {
|
||||
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
|
||||
requestContext, conditionContextResolver,
|
||||
mock(CloudTrailService.class),
|
||||
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup);
|
||||
}
|
||||
|
||||
private IamEnforcementFilter newFilter(ResourceInfo resourceInfo) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ScpProvider> scpProvider = mock(Instance.class);
|
||||
when(scpProvider.isResolvable()).thenReturn(false);
|
||||
return new IamEnforcementFilter(
|
||||
config, accountResolver, iamService, evaluator, actionRegistry,
|
||||
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
|
||||
conditionContextResolver, mock(CloudTrailService.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup, null, resourceInfo);
|
||||
}
|
||||
|
||||
@Test
|
||||
void filterBuildsResourceArnWithRequestContextAccount() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
@@ -148,7 +165,6 @@ class IamEnforcementFilterTest {
|
||||
@Test
|
||||
void jsonProtocolActionComesFromTheTargetNotTheSignedScope() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
// Signed for lambda, but X-Amz-Target sends it to DynamoDB, which is where it will run.
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/lambda/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
@@ -217,6 +233,138 @@ class IamEnforcementFilterTest {
|
||||
verify(actionRegistry).resolve(eq("dynamodb"), eq(containerRequest));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetHeaderOnARequestThatIsNotDispatchedOnItDoesNotMoveTheAuthorization() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20120810.DescribeTable");
|
||||
lenient().when(catalog.matchTarget("DynamoDB_20120810.DescribeTable")).thenReturn(Optional.of(
|
||||
new ServiceCatalog.TargetMatch(dynamoDbDescriptor(), "DynamoDB_20120810.", "DescribeTable")));
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(ProtocolClaim.rest());
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve(eq("s3"), eq(containerRequest));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restRouteAuthorizesTheServiceThatMatchedTheRequest() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260924/us-east-1/iam/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
requestContext.setRegion("us-east-1");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(ProtocolClaim.rest());
|
||||
when(catalog.byResourceClass(ApiGatewayController.class))
|
||||
.thenReturn(Optional.of(descriptor("apigateway", ServiceProtocol.REST_JSON,
|
||||
Set.of("apigateway", "execute-api"), ApiGatewayController.class)));
|
||||
when(actionRegistry.resolve("apigateway", containerRequest)).thenReturn("apigateway:POST");
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
IamEnforcementFilter filter = newFilter(resourceInfo(ApiGatewayController.class));
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve("apigateway", containerRequest);
|
||||
verify(actionRegistry, never()).resolve("iam", containerRequest);
|
||||
verify(arnBuilder).buildResources("apigateway", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(conditionContextResolver).resolve("apigateway", "apigateway:POST", containerRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3RouteDoesNotUseApiGatewayRules() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260924/us-east-1/iam/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(ProtocolClaim.rest());
|
||||
when(catalog.byResourceClass(S3Controller.class))
|
||||
.thenReturn(Optional.of(descriptor("s3", ServiceProtocol.REST_XML,
|
||||
Set.of("s3", "s3express"), S3Controller.class)));
|
||||
when(catalog.canonicalCredentialScope("s3express")).thenReturn("s3");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:CreateBucket");
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
IamEnforcementFilter filter = newFilter(resourceInfo(S3Controller.class));
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve("s3", containerRequest);
|
||||
verify(actionRegistry, never()).resolve("apigateway", containerRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryActionAuthorizesTheServiceSelectedByDispatch() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260924/us-east-1/lambda/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
requestContext.setRegion("us-east-1");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubQueryRequest(containerRequest);
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(new ProtocolClaim(WireProtocol.AWS_QUERY, null, null, null));
|
||||
when(actionRegistry.queryAction(containerRequest)).thenReturn("CreateUser");
|
||||
when(catalog.byCredentialScope("lambda")).thenReturn(Optional.of(
|
||||
descriptor("lambda", ServiceProtocol.REST_JSON, Set.of("lambda"), null)));
|
||||
when(catalog.byExternalKey("iam")).thenReturn(Optional.of(
|
||||
descriptor("iam", ServiceProtocol.QUERY, Set.of("iam"), null)));
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).queryAction(containerRequest);
|
||||
verify(actionRegistry, never()).resolve("lambda", containerRequest);
|
||||
verify(arnBuilder).buildResources("iam", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(conditionContextResolver).resolve("iam", "iam:CreateUser", containerRequest);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryActionUsesTheDispatchServiceWithoutAProtocolClaim() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260924/us-east-1/lambda/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
requestContext.setRegion("us-east-1");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubQueryRequest(containerRequest);
|
||||
when(actionRegistry.queryAction(containerRequest)).thenReturn("CreateUser");
|
||||
when(catalog.byCredentialScope("lambda")).thenReturn(Optional.of(
|
||||
descriptor("lambda", ServiceProtocol.REST_JSON, Set.of("lambda"), null)));
|
||||
when(catalog.byExternalKey("iam")).thenReturn(Optional.of(
|
||||
descriptor("iam", ServiceProtocol.QUERY, Set.of("iam"), null)));
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).queryAction(containerRequest);
|
||||
verify(actionRegistry, never()).resolve("lambda", containerRequest);
|
||||
verify(arnBuilder).buildResources("iam", containerRequest,
|
||||
"us-east-1", "000000000000");
|
||||
verify(conditionContextResolver).resolve("iam", "iam:CreateUser", containerRequest);
|
||||
}
|
||||
|
||||
private static void stubQueryRequest(ContainerRequestContext ctx) {
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
when(ctx.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("");
|
||||
when(ctx.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
}
|
||||
|
||||
private static void stubClaim(ContainerRequestContext ctx, WireProtocol protocol,
|
||||
ServiceDescriptor descriptor) {
|
||||
when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
@@ -229,43 +377,17 @@ class IamEnforcementFilterTest {
|
||||
Set.of("dynamodb"), Set.of(), Set.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetHeaderOnARequestThatIsNotDispatchedOnItDoesNotMoveTheAuthorization() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
// An S3 REST delete carrying a DynamoDB target. JAX-RS routes it to S3 whatever the header
|
||||
// says, so the header must not decide which service gets authorized.
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20120810.DescribeTable");
|
||||
// The target does resolve to DynamoDB; what must stop it is that this request was never
|
||||
// claimed for target dispatch, so the header is not what routes it.
|
||||
lenient().when(catalog.matchTarget("DynamoDB_20120810.DescribeTable")).thenReturn(Optional.of(
|
||||
new ServiceCatalog.TargetMatch(dynamoDbDescriptor(), "DynamoDB_20120810.", "DescribeTable")));
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(ProtocolClaim.rest());
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve(eq("s3"), eq(containerRequest));
|
||||
private static ResourceInfo resourceInfo(Class<?> resourceClass) {
|
||||
ResourceInfo resourceInfo = mock(ResourceInfo.class);
|
||||
doReturn(resourceClass).when(resourceInfo).getResourceClass();
|
||||
return resourceInfo;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueryClaimNeverOverridesTheScopeItWasBuiltFrom() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/lambda/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubClaim(containerRequest, WireProtocol.AWS_QUERY, dynamoDbDescriptor());
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(actionRegistry).resolve(eq("lambda"), eq(containerRequest));
|
||||
private static ServiceDescriptor descriptor(String service, ServiceProtocol protocol,
|
||||
Set<String> scopes, Class<?> resourceClass) {
|
||||
Set<Class<?>> resourceClasses = resourceClass == null ? Set.of() : Set.of(resourceClass);
|
||||
return new ServiceDescriptor(service, service, true, true, service, "memory", 0L,
|
||||
null, protocol, Set.of(protocol), Set.of(), scopes, Set.of(), resourceClasses);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -766,7 +888,7 @@ class IamEnforcementFilterTest {
|
||||
config, accountResolver, iamService, new IamPolicyEvaluator(new ObjectMapper()),
|
||||
actionRegistry, arnBuilder, requestContext, conditionContextResolver,
|
||||
mock(CloudTrailService.class),
|
||||
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup);
|
||||
}
|
||||
|
||||
@@ -1317,7 +1439,7 @@ class IamEnforcementFilterTest {
|
||||
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
|
||||
requestContext, conditionContextResolver,
|
||||
mock(CloudTrailService.class),
|
||||
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
|
||||
mock(CurrentVertxRequest.class),
|
||||
catalog, scpProvider, sessionAccountLookup, providers);
|
||||
}
|
||||
}
|
||||
+9
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayController;
|
||||
import io.github.hectorvent.floci.services.s3.S3Controller;
|
||||
import io.github.hectorvent.floci.services.securityadmin.SecurityAdminController;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -82,6 +84,13 @@ class ServiceCatalogRoutingIntegrationTest {
|
||||
assertEquals("guardduty", catalog.byCredentialScope("guardduty").orElseThrow().externalKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamEnforcementCanResolveRestServicesFromMatchedRoutes() {
|
||||
assertEquals("s3", catalog.byResourceClass(S3Controller.class).orElseThrow().externalKey());
|
||||
assertEquals("apigateway",
|
||||
catalog.byResourceClass(ApiGatewayController.class).orElseThrow().externalKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownTargetsRemainUnresolved() {
|
||||
assertTrue(catalog.matchTarget("UnknownService.DoThing").isEmpty());
|
||||
|
||||
@@ -40,6 +40,53 @@ class IamActionRegistryTest {
|
||||
assertEquals("iam:ListUsers", registry.resolve("iam", ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesOperationFromFormEncodedBody() {
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
"POST", "/",
|
||||
new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE,
|
||||
"Operation=CreateUser&Version=2010-05-08&UserName=alice");
|
||||
assertEquals("CreateUser", registry.queryAction(ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void actionTakesPrecedenceOverOperation() {
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
"POST", "/",
|
||||
new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE,
|
||||
"Action=ListUsers&Operation=CreateUser");
|
||||
assertEquals("ListUsers", registry.queryAction(ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restActionIgnoresOperationFromFormBody() {
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
"PUT", "/bucket/key",
|
||||
new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE,
|
||||
"Operation=ListBucket");
|
||||
assertEquals("s3:PutObject", registry.resolve("s3", ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restActionIgnoresActionFromUrl() {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", "ListBucket");
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
"PUT", "/bucket/key", query, null, "");
|
||||
assertEquals("s3:PutObject", registry.resolve("s3", ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restActionIgnoresActionFromFormBody() {
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
"PUT", "/bucket/key", new MultivaluedHashMap<>(),
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE, "Action=ListBucket");
|
||||
assertEquals("s3:PutObject", registry.resolve("s3", ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesUrlEncodedActionValueFromFormBody() {
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
@@ -51,9 +98,8 @@ class IamActionRegistryTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void prefersUrlQueryActionOverFormBody() {
|
||||
// Some clients (older AWS CLI, curl) send Query-protocol requests with
|
||||
// Action in the URL query string; that path must keep working.
|
||||
void formBodyActionTakesPrecedenceOverUrlQueryAction() {
|
||||
// The controller dispatches the form body, even when the URL names another action.
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", "ListUsers");
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
@@ -61,7 +107,17 @@ class IamActionRegistryTest {
|
||||
query,
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE,
|
||||
"Action=DeleteUser");
|
||||
assertEquals("iam:ListUsers", registry.resolve("iam", ctx));
|
||||
assertEquals("iam:DeleteUser", registry.resolve("iam", ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
void urlQueryActionDoesNotAuthorizeAnAbsentFormAction() {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add("Action", "ListUsers");
|
||||
ContainerRequestContext ctx = mockCtx(
|
||||
"POST", "/", query, MediaType.APPLICATION_FORM_URLENCODED_TYPE,
|
||||
"Version=2010-05-08");
|
||||
assertNull(registry.queryAction(ctx));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class IamServingServiceEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void queryRequestCannotBorrowPermissionsFromItsSigningScope() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String caller = "query-scope-" + suffix;
|
||||
String attempted = "created-through-query-" + suffix;
|
||||
String accessKeyId = createUserWithPolicy(caller, "LambdaOnly", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:*","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
iamCall(accessKeyId, "lambda", "CreateUser", Map.of("UserName", attempted))
|
||||
.statusCode(403)
|
||||
.body(containsString("iam:CreateUser"));
|
||||
|
||||
adminIam("GetUser", Map.of("UserName", attempted)).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationOnlyQueryRequestCannotBypassIamEnforcement() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String caller = "operation-scope-" + suffix;
|
||||
String attempted = "created-through-operation-" + suffix;
|
||||
String accessKeyId = createUserWithPolicy(caller, "LambdaOnly", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:*","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
iamOperationCall(accessKeyId, "lambda", "CreateUser", Map.of("UserName", attempted))
|
||||
.statusCode(403)
|
||||
.body(containsString("iam:CreateUser"));
|
||||
|
||||
adminIam("GetUser", Map.of("UserName", attempted)).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryRequestCannotBorrowGetUserPermissionFromUrlAction() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String caller = "query-url-action-" + suffix;
|
||||
String attempted = "created-through-url-action-" + suffix;
|
||||
String accessKeyId = createUserWithPolicy(caller, "GetUserOnly", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:GetUser","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
given()
|
||||
.header("Authorization", authorization(accessKeyId, "iam"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.queryParam("Action", "GetUser")
|
||||
.formParam("Action", "CreateUser")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("UserName", attempted)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("iam:CreateUser"));
|
||||
|
||||
adminIam("GetUser", Map.of("UserName", attempted)).statusCode(404);
|
||||
}
|
||||
|
||||
@Test
|
||||
void restRequestCannotBypassApiGatewayPolicyWithIamScope() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String caller = "rest-scope-" + suffix;
|
||||
String apiName = "blocked-api-" + suffix;
|
||||
String accessKeyId = createUserWithPolicy(caller, "IamOnly", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:*","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
given()
|
||||
.header("Authorization", authorization(accessKeyId, "iam"))
|
||||
.contentType("application/json")
|
||||
.body(Map.of("name", apiName))
|
||||
.when()
|
||||
.post("/restapis")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("apigateway:POST"));
|
||||
|
||||
given()
|
||||
.header("Authorization", authorization(ACCOUNT_ID, "apigateway"))
|
||||
.when()
|
||||
.get("/restapis")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString(apiName)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void restPutCannotBorrowListBucketPermissionThroughAction() {
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = "action-bypass-" + suffix;
|
||||
String accessKeyId = createUserWithPolicy("action-bypass-user-" + suffix,
|
||||
"ListBucketOnly", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
|
||||
]}""");
|
||||
|
||||
given().header("Authorization", authorization(ACCOUNT_ID, "s3"))
|
||||
.when().put("/" + bucket).then().statusCode(200);
|
||||
|
||||
given().header("Authorization", authorization(accessKeyId, "s3"))
|
||||
.queryParam("Action", "ListBucket")
|
||||
.body("query-spoof")
|
||||
.when().put("/" + bucket + "/from-query")
|
||||
.then().statusCode(403).body(containsString("s3:PutObject"));
|
||||
|
||||
given().header("Authorization", authorization(accessKeyId, "s3"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.body("Action=ListBucket")
|
||||
.when().put("/" + bucket + "/from-form")
|
||||
.then().statusCode(403).body(containsString("s3:PutObject"));
|
||||
|
||||
given().header("Authorization", authorization(ACCOUNT_ID, "s3"))
|
||||
.when().get("/" + bucket + "/from-query")
|
||||
.then().statusCode(404);
|
||||
given().header("Authorization", authorization(ACCOUNT_ID, "s3"))
|
||||
.when().get("/" + bucket + "/from-form")
|
||||
.then().statusCode(404);
|
||||
}
|
||||
|
||||
private static String createUserWithPolicy(String userName, String policyName, String policyDocument) {
|
||||
adminIam("CreateUser", Map.of("UserName", userName)).statusCode(200);
|
||||
adminIam("PutUserPolicy", Map.of(
|
||||
"UserName", userName,
|
||||
"PolicyName", policyName,
|
||||
"PolicyDocument", policyDocument)).statusCode(200);
|
||||
return adminIam("CreateAccessKey", Map.of("UserName", userName))
|
||||
.statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private static ValidatableResponse adminIam(String action, Map<String, String> params) {
|
||||
return iamCall(ACCOUNT_ID, "iam", action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse iamCall(String accessKeyId, String scope, String action,
|
||||
Map<String, String> params) {
|
||||
return iamCall(accessKeyId, scope, "Action", action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse iamOperationCall(String accessKeyId, String scope, String operation,
|
||||
Map<String, String> params) {
|
||||
return iamCall(accessKeyId, scope, "Operation", operation, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse iamCall(String accessKeyId, String scope, String operationName,
|
||||
String operation, Map<String, String> params) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", authorization(accessKeyId, scope))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam(operationName, operation)
|
||||
.formParam("Version", "2010-05-08");
|
||||
params.forEach(spec::formParam);
|
||||
return spec.when().post("/").then();
|
||||
}
|
||||
|
||||
private static String authorization(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260924/" + REGION + "/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user