fix(iam): authorize the service that serves the request, not the one it was signed for (#4295)

A target-dispatched request is routed on X-Amz-Target, but the enforced action took its service prefix from the caller's SigV4 credential scope. Signing a DynamoDB PutItem under the lambda scope authorized lambda:PutItem while the call still ran against DynamoDB, so a policy denying dynamodb:* never matched.

Take the service from the protocol claim instead, which only carries one when the request really is dispatched on the wire's own naming, and never for AWS_QUERY, whose claim is built from the credential scope. Reading the target header directly here would instead let a header attached to an S3 request move the authorization to another service while S3 still served it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-25 07:40:42 -05:00
1 parent 1a009300dd
commit d2c0705ea9
2 files changed
+170 -1

No files matched your search

@@ -167,7 +167,7 @@ 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 = catalog.canonicalCredentialScope(rawScope);
String credentialScope = servingCredentialScope(catalog.canonicalCredentialScope(rawScope), ctx);
String action = actionRegistry.resolve(credentialScope, ctx);
if (action == null) {
@@ -314,6 +314,50 @@ 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.
*
* <p>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.
*
* <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 separately.
*/
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 descriptor.externalKey();
}
return descriptor.credentialScopes().stream()
.filter(scope -> scope.equals(catalog.canonicalCredentialScope(scope)))
.sorted()
.findFirst()
.orElse(descriptor.externalKey());
}
/** The same contexts with every object-tag key removed, keeping the principal and global keys. */
private static List<Map<String, List<String>>> withoutObjectTags(
List<Map<String, List<String>>> targetContexts) {
@@ -26,6 +26,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -34,6 +35,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.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -142,6 +144,129 @@ class IamEnforcementFilterTest {
verify(arnBuilder).buildResources("lambda", containerRequest, "us-east-1", "222233334444");
}
@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");
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(containerRequest.getHeaderString("X-Amz-Target")).thenReturn("DynamoDB_20120810.PutItem");
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_0, dynamoDbDescriptor());
when(iamService.resolveCallerContext("AKIAUSER"))
.thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"dynamodb:*","Resource":"*"}]}""")));
// Resolve for the serving service only. Left unstubbed the filter would leave through its
// permissive unknown-action branch and the deny below would never be reached.
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
.thenReturn(List.of("*"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("dynamodb:PutItem"), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
// Resolved as the serving service, and the deny on that service actually lands.
verify(actionRegistry).resolve(eq("dynamodb"), eq(containerRequest));
ArgumentCaptor<Response> denied = ArgumentCaptor.captor();
verify(containerRequest).abortWith(denied.capture());
assertEquals(403, denied.getValue().getStatus());
}
@Test
void theServingScopeIsTheServicesOwnNamespaceNotJustAnySigningAlias() {
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);
// Pricing signs under both "pricing" and "api.pricing"; only the former names its actions.
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_1, pricingDescriptor());
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
newFilter().filter(containerRequest);
verify(actionRegistry).resolve(eq("pricing"), eq(containerRequest));
}
private static ServiceDescriptor pricingDescriptor() {
return new ServiceDescriptor("pricing", "pricing", true, true, null, null, 5000L, null,
ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON), Set.of("AWSPriceListService."),
Set.of("pricing", "api.pricing"), Set.of(), Set.of());
}
@Test
void aScopeTheTargetsServiceAcceptsIsLeftAlone() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/dynamodb/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.PutItem");
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_0, dynamoDbDescriptor());
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
newFilter().filter(containerRequest);
verify(actionRegistry).resolve(eq("dynamodb"), eq(containerRequest));
}
private static void stubClaim(ContainerRequestContext ctx, WireProtocol protocol,
ServiceDescriptor descriptor) {
when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
.thenReturn(new ProtocolClaim(protocol, descriptor, null, null));
}
private static ServiceDescriptor dynamoDbDescriptor() {
return new ServiceDescriptor("dynamodb", "dynamodb", true, true, "dynamodb", "memory", 0L, null,
ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON), Set.of("DynamoDB_20120810."),
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));
}
@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));
}
@Test
void unknownAccessKeyIsRejectedInsteadOfBypassingEnforcement() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);