mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): refuse inactive keys and unreadable credentials in enforcement (#5346)
With enforcement on, three kinds of request got past the filter's
credential checks, and an expired session was answered as a key that
exists nowhere.
A deactivated access key could still be used. Account routing skips an
inactive key, so its requests landed in the default account. A key of a
user there kept that user's permissions, since resolveCallerContext
reads the user's policies whatever the key's status. A key of another
account matched no user in the default account, and isKnownAccessKey,
which counts every key in every account, let the request through as a
credential the filter could not map, with no policy check at all.
Deactivating a key of a user allowed nothing let it create IAM users
and mint session tokens. The IAM User Guide ("Manage access keys for
IAM users") says that once deactivated a key "can no longer be used by
API calls" until it is activated again.
An Authorization header the filter could not read a credential from made
it return before any check. That covered a header naming no access key
at all (a Bearer token, SigV2, a Credential without the SigV4 scheme or
with the key left out) and a SigV4 scope missing a part, such as its
aws4_request terminator. Any caller could make any call that way,
including the management calls an unsigned request is refused. Such a
request is now refused as AWS refuses a header it cannot read:
IncompleteSignature for Query services and IncompleteSignatureException
for JSON and CBOR ones (the common errors, and the IAM User Guide's
SigV4 troubleshooting section), and S3's AuthorizationHeaderMalformed
with the wording S3HeaderSignatureFilter already uses, all 400. A
presigned S3 URL sends no header, and S3 answers a mal-formed
X-Amz-Credential with AuthorizationQueryParametersError, so that is
what it gets. Otherwise the request is treated as an unsigned one is: an
operation AWS serves without credentials is left alone, and a REST
request is refused only when the header claims SigV4 and its route maps
to an action, since AppSync, CodeArtifact's package endpoints, Identity
Store's SCIM endpoint and API Gateway's authorizers take Bearer and
Basic tokens of their own. An empty header with nothing else to read is
refused the same way, not as a missing one; next to a presigned URL's
X-Amz-Credential it still defers to that credential. Where the guide
gives the message, the refusal uses it: "Authorization header cannot be
empty." and, for a SigV4 header with no Credential, "Authorization
header requires 'Credential' parameter.". The other shapes get the
common errors' "The request signature does not conform to AWS
standards.".
sts:GetCallerIdentity answered a key that exists nowhere, as the
default account's root, because its exemption ran before the
unknown-key check. The exemption is about permissions only, so the key
checks now run first.
An expired session was refused with InvalidClientTokenId or
UnrecognizedClientException, because resolveCallerContext deletes it and
the known-key check then finds nothing. The common errors of the IAM,
STS, EC2, SNS, CloudFormation, Lambda and Step Functions API references
give ExpiredTokenException, 403, "The security token included in the
request has expired", and S3's error list gives ExpiredToken, 400. The
filter now asks isExpiredSession before resolving the caller, so it no
longer deletes the session, and later uses get the same answer. Both
lookups are asked about one moment: read apart, a session expiring
between them would be deleted and answered as unknown, or on the
presigned POST path below allowed with no policy check. Once Floci's own
sweep has removed the session (the first presigned URL it generates in a
process runs one), the key reads as unknown again, as
docs/services/iam.md says.
The inactive-key, expired-session and unknown-key checks run before the
action is used, on every Query, JSON and CBOR call and on every REST
request whose route maps to an action. A REST request no rule maps is
left alone, as an unsigned one already is: the filter cannot tell it
from the API Gateway execute path, Lambda function URLs and the other
paths it sees that are unsigned by design, and the execute path answers
a bad AWS_IAM signature in its own shape. Every refusal to a CBOR call,
AccessDenied included, now arrives CBOR-encoded, where only the
unsigned-call refusal did before; the others were JSON bodies the client
could not read. AccessDenied keeps its 403, the status the Kinesis and
CloudWatch common errors give it. The filter's JSON errors are now
written from AwsErrorResponse, as AwsExceptionMapper writes every other
JSON error, rather than built as strings. That gives a REST JSON
refusal, such as Lambda's, the X-Amzn-Errortype header the rest of
Floci's REST JSON errors carry.
A presigned POST carries its credential in the form body, which the
filter never sees, so authorizeAdditionalResource is the only IAM check
it gets. That evaluated an inactive key with its user's policies, and
resolved an expired session, which deleted it. Both are now refused
there as the filter refuses them, before the caller is resolved:
InvalidAccessKeyId, 403, and ExpiredToken, 400. A key that exists
nowhere, or a credential that cannot be read, is still left to S3's own
presigned-POST check, and uploads as an unsigned request would when that
check is off. docs/services/iam.md now says so.
isKnownAccessKey keeps counting inactive keys: GetSessionToken relies
on it, so a session minted with an inactive key has no issuer rather
than acting as the account root. resolveCallerContext keeps returning
an inactive key's user policies rather than null, which AppSync and RDS
read as allowed; both verify the signature first, which an inactive key
fails. isInactiveAccessKey looks in the request's account before
scanning the others, since routing sends an active key to its own
account.
Integration tests cover a same-account and another account's inactive
key (including GetCallerIdentity, GetSessionToken, S3, a JSON service,
a presigned POST, and reactivation); an expired session on Query (asked
twice), JSON (with its X-Amzn-Errortype header), S3 and presigned POST
calls; an unreadable credential on Query (eight header shapes, none of
which creates the user), JSON, CBOR and S3 calls, on a presigned S3 URL,
and with the guide's two messages; the cases left alone (a Cognito flow
AWS serves without credentials, a Bearer token on S3, a REST route no
rule maps); an unknown key on GetCallerIdentity and on a CBOR call; and
AccessDenied on a CBOR call. Every refusal fails without this change.
IamServiceTest and IamEnforcementFilterTest check that the expiry check
and the caller lookup are asked about one moment. The SDK compatibility
suite's IamEnforcementTest adds a deactivated key, refused by STS and S3
with the codes the SDK reads and accepted again once activated.
docs/services/iam.md lists the cases in both enforcement tables and
under unsigned requests.
This commit is contained in:
1 parent
4793f1aa77
commit
46f9c23c8b
11 files changed
+1482
-122
No files matched your search
+394
-41
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.apigateway.ApiGatewayController;
|
||||
@@ -33,6 +34,7 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -40,6 +42,7 @@ import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
@@ -147,7 +150,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.resolve(auth)).thenReturn("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("lambda", containerRequest)).thenReturn("lambda:InvokeFunction");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"lambda:InvokeFunction",
|
||||
@@ -183,7 +186,7 @@ class IamEnforcementFilterTest {
|
||||
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"))
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"dynamodb:*","Resource":"*"}]}""")));
|
||||
@@ -220,7 +223,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getMediaType()).thenReturn(MediaType.valueOf(contentType));
|
||||
stubClaim(containerRequest, protocol, dynamoDbDescriptor());
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
// A REST-claimed request resolves from its route, the others from the registry's full rules.
|
||||
lenient().when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
lenient().when(actionRegistry.resolveRoute("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
@@ -247,7 +250,7 @@ class IamEnforcementFilterTest {
|
||||
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()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
@@ -270,7 +273,7 @@ class IamEnforcementFilterTest {
|
||||
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()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
@@ -289,7 +292,7 @@ class IamEnforcementFilterTest {
|
||||
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()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
@@ -313,7 +316,7 @@ class IamEnforcementFilterTest {
|
||||
.thenReturn(Optional.of(descriptor("apigateway", ServiceProtocol.REST_JSON,
|
||||
Set.of("apigateway", "execute-api"), ApiGatewayController.class)));
|
||||
when(actionRegistry.resolveRoute("apigateway", containerRequest)).thenReturn("apigateway:POST");
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
IamEnforcementFilter filter = newFilter(resourceInfo(ApiGatewayController.class));
|
||||
filter.filter(containerRequest);
|
||||
@@ -340,7 +343,7 @@ class IamEnforcementFilterTest {
|
||||
Set.of("s3", "s3express"), S3Controller.class)));
|
||||
when(catalog.canonicalCredentialScope("s3express")).thenReturn("s3");
|
||||
when(actionRegistry.resolveRoute("s3", containerRequest)).thenReturn("s3:CreateBucket");
|
||||
when(iamService.resolveCallerContext("AKIAUSER")).thenReturn(CallerContext.of(List.of()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
IamEnforcementFilter filter = newFilter(resourceInfo(S3Controller.class));
|
||||
filter.filter(containerRequest);
|
||||
@@ -366,7 +369,7 @@ class IamEnforcementFilterTest {
|
||||
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()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
@@ -392,7 +395,7 @@ class IamEnforcementFilterTest {
|
||||
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()));
|
||||
when(iamService.resolveCallerContext(eq("AKIAUSER"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
@@ -445,7 +448,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIADOESNOTEXIST0000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("lambda", containerRequest)).thenReturn("lambda:InvokeFunction");
|
||||
when(iamService.resolveCallerContext("AKIADOESNOTEXIST0000")).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq("AKIADOESNOTEXIST0000"), any())).thenReturn(null);
|
||||
when(iamService.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
@@ -467,7 +470,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIADOESNOTEXIST0000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext("AKIADOESNOTEXIST0000")).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq("AKIADOESNOTEXIST0000"), any())).thenReturn(null);
|
||||
when(iamService.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
@@ -489,7 +492,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(actionRegistry.resolve("sts", containerRequest)).thenReturn("sts:AssumeRole");
|
||||
when(iamService.resolveCallerContext("AKIADOESNOTEXIST0000")).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq("AKIADOESNOTEXIST0000"), any())).thenReturn(null);
|
||||
when(iamService.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
@@ -503,6 +506,341 @@ class IamEnforcementFilterTest {
|
||||
response.getValue().getEntity().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownAccessKeyIsRejectedOnGetCallerIdentity() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260629/us-east-1/sts/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIADOESNOTEXIST0000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(actionRegistry.resolve("sts", containerRequest)).thenReturn("sts:GetCallerIdentity");
|
||||
when(iamService.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(403, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("InvalidClientTokenId"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredSessionIsRejectedAsExpiredRatherThanUnknown() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIAEXPIRED/20260629/us-east-1/lambda/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIAEXPIRED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("lambda", containerRequest)).thenReturn("lambda:ListFunctions");
|
||||
when(iamService.isExpiredSession(eq("ASIAEXPIRED"), any())).thenReturn(true);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(403, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("\"__type\":\"ExpiredTokenException\""),
|
||||
entityString(response.getValue()));
|
||||
// Resolving the caller would delete the session and leave it indistinguishable from unknown.
|
||||
verify(iamService, never()).resolveCallerContext(any(), any());
|
||||
verifyNoInteractions(evaluator);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredSessionIsRejectedOnGetCallerIdentity() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIAEXPIRED/20260629/us-east-1/sts/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIAEXPIRED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(actionRegistry.resolve("sts", containerRequest)).thenReturn("sts:GetCallerIdentity");
|
||||
when(iamService.isExpiredSession(eq("ASIAEXPIRED"), any())).thenReturn(true);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(403, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("<Code>ExpiredTokenException</Code>"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredSessionOnAnS3RequestIsRejectedWithTheS3ErrorCode() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIAEXPIRED/20260629/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIAEXPIRED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.isExpiredSession(eq("ASIAEXPIRED"), any())).thenReturn(true);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("<Code>ExpiredToken</Code>"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExpiryCheckAndTheCallerLookupAreAskedAboutTheSameMoment() {
|
||||
// Asked about two moments, a session expiring between them would be deleted by the lookup
|
||||
// and then answered as a key that exists nowhere.
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260629/us-east-1/dynamodb/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any())).thenReturn(CallerContext.of(List.of()));
|
||||
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("dynamodb:PutItem"), any(), any()))
|
||||
.thenReturn(IamPolicyEvaluator.Decision.DENY);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Instant> checked = ArgumentCaptor.captor();
|
||||
ArgumentCaptor<Instant> resolved = ArgumentCaptor.captor();
|
||||
verify(iamService).isExpiredSession(eq("ASIASESSION"), checked.capture());
|
||||
verify(iamService).resolveCallerContext(eq("ASIASESSION"), resolved.capture());
|
||||
assertSame(checked.getValue(), resolved.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownAccessKeyIsRejectedOnAnRpcCallNoRuleMaps() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260629/us-east-1/dynamodb/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
requestContext.setAccountId("000000000000");
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIADOESNOTEXIST0000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_0, dynamoDbDescriptor());
|
||||
when(iamService.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(403, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("UnrecognizedClientException"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestRouteNoRuleMapsIsLeftToItsHandlerWhateverTheKey() {
|
||||
// As for an unsigned REST request: the filter cannot tell it from the API Gateway execute
|
||||
// path, function URLs and the other paths it sees that are unsigned by design.
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260629/us-east-1/execute-api/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIADOESNOTEXIST0000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(ProtocolClaim.rest());
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
verify(iamService, never()).isInactiveAccessKey(any());
|
||||
verify(iamService, never()).isKnownAccessKey(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableCredentialScopeOnAJsonCallIsRejected() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260629/us-east-1/dynamodb, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIADOESNOTEXIST0000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_0, dynamoDbDescriptor());
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("\"__type\":\"IncompleteSignatureException\""),
|
||||
entityString(response.getValue()));
|
||||
verifyNoInteractions(iamService, evaluator);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableCredentialScopeOnAQueryCallIsRejectedWithTheQueryErrorCode() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/iam, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAUSER");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
stubQueryRequest(containerRequest);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("<Code>IncompleteSignature</Code>"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableCredentialScopeOnAMappedS3RouteIsRejectedWithTheS3ErrorCode() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/s3, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
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"), S3Controller.class)));
|
||||
when(actionRegistry.resolveRoute("s3", containerRequest)).thenReturn("s3:ListAllMyBuckets");
|
||||
|
||||
newFilter(resourceInfo(S3Controller.class)).filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("<Code>AuthorizationHeaderMalformed</Code>"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadablePresignedCredentialOnAMappedS3RouteIsRejectedWithTheQueryErrorCode() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubPresignedCredential(containerRequest, "AKIAUSER/20260629/us-east-1/s3");
|
||||
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/s3"))
|
||||
.thenReturn("AKIAUSER");
|
||||
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"), S3Controller.class)));
|
||||
when(actionRegistry.resolveRoute("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
|
||||
newFilter(resourceInfo(S3Controller.class)).filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("<Code>AuthorizationQueryParametersError</Code>"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableCredentialScopeOnARestRouteNoRuleMapsIsLeftToItsHandler() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
String auth = "AWS4-HMAC-SHA256 Credential=AKIAUSER/20260629/us-east-1/execute-api, "
|
||||
+ "SignedHeaders=host, Signature=garbage";
|
||||
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)));
|
||||
|
||||
newFilter(resourceInfo(ApiGatewayController.class)).filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyHeaderOnAJsonCallIsRejectedAsUnreadableNotAsMissing() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubNoQueryParameters(containerRequest);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(" ");
|
||||
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_0, dynamoDbDescriptor());
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("\"__type\":\"IncompleteSignatureException\""),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyHeaderOnARestRequestIsTreatedAsUnsigned() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
stubNoQueryParameters(containerRequest);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn("");
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(ProtocolClaim.rest());
|
||||
|
||||
newFilter(resourceInfo(S3Controller.class)).filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeaderNamingNoAccessKeyOnAJsonCallIsRejected() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn("Bearer not-an-aws-credential");
|
||||
stubClaim(containerRequest, WireProtocol.AWS_JSON_1_0, dynamoDbDescriptor());
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("\"__type\":\"IncompleteSignatureException\""),
|
||||
entityString(response.getValue()));
|
||||
verifyNoInteractions(iamService, evaluator);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeaderNamingNoAccessKeyOnAnOperationAwsServesWithoutCredentialsIsLeftAlone() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn("Bearer not-an-aws-credential");
|
||||
when(containerRequest.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(new ProtocolClaim(WireProtocol.AWS_JSON_1_1,
|
||||
descriptor("cognito-idp", ServiceProtocol.JSON, Set.of("cognito-idp"), null),
|
||||
"InitiateAuth", "AWSCognitoIdentityProviderService.InitiateAuth"));
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSigV4HeaderNamingNoAccessKeyOnAMappedS3RouteIsRejectedWithTheS3ErrorCode() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
when(containerRequest.getHeaderString("Authorization"))
|
||||
.thenReturn("AWS4-HMAC-SHA256 Credential=/20260629/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=garbage");
|
||||
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"), S3Controller.class)));
|
||||
when(actionRegistry.resolveRoute("s3", containerRequest)).thenReturn("s3:ListAllMyBuckets");
|
||||
|
||||
newFilter(resourceInfo(S3Controller.class)).filter(containerRequest);
|
||||
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.captor();
|
||||
verify(containerRequest).abortWith(response.capture());
|
||||
assertEquals(400, response.getValue().getStatus());
|
||||
assertTrue(entityString(response.getValue()).contains("<Code>AuthorizationHeaderMalformed</Code>"),
|
||||
entityString(response.getValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBearerTokenOnAMappedRestRouteIsTreatedAsUnsigned() {
|
||||
// AppSync, CodeArtifact's package endpoints and API Gateway's authorizers take their own tokens.
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn("Bearer not-an-aws-credential");
|
||||
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"), S3Controller.class)));
|
||||
when(actionRegistry.resolveRoute("s3", containerRequest)).thenReturn("s3:ListAllMyBuckets");
|
||||
|
||||
newFilter(resourceInfo(S3Controller.class)).filter(containerRequest);
|
||||
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKnownCredentialWithoutAMappableCallerContextStillPassesThrough() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
@@ -512,7 +850,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIAIDENTITYSESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("lambda", containerRequest)).thenReturn("lambda:InvokeFunction");
|
||||
when(iamService.resolveCallerContext("ASIAIDENTITYSESSION")).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq("ASIAIDENTITYSESSION"), any())).thenReturn(null);
|
||||
when(iamService.isKnownAccessKey("ASIAIDENTITYSESSION")).thenReturn(true);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
@@ -561,7 +899,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext("ASIASCOPE"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASCOPE"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}")));
|
||||
when(iamService.presignedScope("ASIASCOPE"))
|
||||
.thenReturn(Optional.of(new IamService.PresignedScope(
|
||||
@@ -590,7 +928,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext("ASIASCOPE"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASCOPE"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}")));
|
||||
when(iamService.presignedScope("ASIASCOPE"))
|
||||
.thenReturn(Optional.of(new IamService.PresignedScope(
|
||||
@@ -615,7 +953,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("lambda", containerRequest)).thenReturn("lambda:InvokeFunction");
|
||||
when(iamService.resolveCallerContext("000000000000")).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq("000000000000"), any())).thenReturn(null);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
@@ -635,7 +973,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.resolve(auth)).thenReturn("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:GetItem");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"dynamodb:GetItem",
|
||||
@@ -674,7 +1012,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.resolve(auth)).thenReturn("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:BatchGetItem");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("{}")));
|
||||
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
|
||||
.thenReturn(List.of(
|
||||
@@ -732,7 +1070,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.resolve(auth)).thenReturn("000000000000");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:BatchGetItem");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("{}")));
|
||||
when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
|
||||
.thenReturn(List.of(
|
||||
@@ -773,13 +1111,16 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("sts", containerRequest)).thenReturn("sts:GetCallerIdentity");
|
||||
// A caller whose policies deny everything: the key is checked, the policies are not.
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any())).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"*","Resource":"*"}]}""")));
|
||||
|
||||
IamEnforcementFilter filter = newFilter();
|
||||
|
||||
filter.filter(containerRequest);
|
||||
|
||||
verify(iamService, never()).resolveCallerContext(any());
|
||||
verify(evaluator, never()).evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any());
|
||||
verify(iamService).resolveCallerContext(eq("ASIASESSION"), any());
|
||||
verifyNoInteractions(evaluator);
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@@ -796,7 +1137,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIATAGGED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("ec2", containerRequest)).thenReturn("ec2:TerminateInstances");
|
||||
when(iamService.resolveCallerContext("AKIATAGGED"))
|
||||
when(iamService.resolveCallerContext(eq("AKIATAGGED"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
@@ -907,7 +1248,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIATAGGED");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("ec2", containerRequest)).thenReturn("ec2:TerminateInstances");
|
||||
when(iamService.resolveCallerContext("AKIATAGGED"))
|
||||
when(iamService.resolveCallerContext(eq("AKIATAGGED"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ec2:TerminateInstances","Resource":"*",
|
||||
@@ -932,7 +1273,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:ListBucket");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
|
||||
@@ -979,7 +1320,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext("ASIASESSION"))
|
||||
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
|
||||
@@ -1042,7 +1383,7 @@ class IamEnforcementFilterTest {
|
||||
.thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
|
||||
when(actionRegistry.resolve("organizations", containerRequest))
|
||||
.thenReturn("organizations:LeaveOrganization");
|
||||
when(iamService.resolveCallerContext(account)).thenReturn(null); // account root: not an IAM identity
|
||||
when(iamService.resolveCallerContext(eq(account), any())).thenReturn(null); // account root: not an IAM identity
|
||||
when(arnBuilder.build(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
|
||||
.thenReturn("*");
|
||||
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
|
||||
@@ -1079,7 +1420,7 @@ class IamEnforcementFilterTest {
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("organizations", containerRequest))
|
||||
.thenReturn("organizations:DescribeOrganization");
|
||||
when(iamService.resolveCallerContext(account)).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq(account), any())).thenReturn(null);
|
||||
when(arnBuilder.buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
|
||||
.thenReturn(List.of("*"));
|
||||
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
|
||||
@@ -1135,7 +1476,7 @@ class IamEnforcementFilterTest {
|
||||
when(otherAction.getMediaType()).thenReturn(MediaType.valueOf("application/x-amz-json-1.1"));
|
||||
when(actionRegistry.resolve("organizations", otherAction))
|
||||
.thenReturn("organizations:DescribeOrganization");
|
||||
when(iamService.resolveCallerContext(account)).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq(account), any())).thenReturn(null);
|
||||
when(arnBuilder.build(eq("organizations"), eq(otherAction), eq("us-east-1"), eq(account)))
|
||||
.thenReturn("*");
|
||||
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(otherAction)))
|
||||
@@ -1189,7 +1530,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn(account);
|
||||
when(accountResolver.resolve(auth)).thenReturn(account);
|
||||
when(actionRegistry.resolve("s3", ctx)).thenReturn("s3:ListBucket");
|
||||
when(iamService.resolveCallerContext(account)).thenReturn(null);
|
||||
when(iamService.resolveCallerContext(eq(account), any())).thenReturn(null);
|
||||
when(arnBuilder.build(eq("s3"), eq(ctx), eq("us-east-1"), eq(account))).thenReturn("*");
|
||||
when(conditionContextResolver.resolve(eq("s3"), anyString(), eq(ctx))).thenReturn(null);
|
||||
|
||||
@@ -1229,7 +1570,7 @@ class IamEnforcementFilterTest {
|
||||
when(actionRegistry.resolve("organizations", containerRequest))
|
||||
.thenReturn("organizations:DescribeOrganization");
|
||||
// A real IAM user: full-access identity policy plus a known principal ARN.
|
||||
when(iamService.resolveCallerContext(akid))
|
||||
when(iamService.resolveCallerContext(eq(akid), any()))
|
||||
.thenReturn(CallerContext.of(List.of(FULL_AWS_ACCESS)));
|
||||
String userArn = "arn:aws:iam::" + account + ":user/alice";
|
||||
when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(userArn, userArn)));
|
||||
@@ -1277,7 +1618,7 @@ class IamEnforcementFilterTest {
|
||||
when(actionRegistry.resolve("organizations", containerRequest))
|
||||
.thenReturn("organizations:DescribeOrganization");
|
||||
// A real IAM user whose ONLY grant is conditional on being an IAM-user principal.
|
||||
when(iamService.resolveCallerContext(akid))
|
||||
when(iamService.resolveCallerContext(eq(akid), any()))
|
||||
.thenReturn(CallerContext.of(List.of(ALLOW_IF_IAM_USER_PRINCIPAL)));
|
||||
String userArn = "arn:aws:iam::" + account + ":user/bob";
|
||||
when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(userArn, userArn)));
|
||||
@@ -1312,7 +1653,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.resolve(auth)).thenReturn(account);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:GetObject");
|
||||
when(iamService.resolveCallerContext(akid)).thenReturn(CallerContext.of(List.of()));
|
||||
when(iamService.resolveCallerContext(eq(akid), any())).thenReturn(CallerContext.of(List.of()));
|
||||
String sessionArn = "arn:aws:sts::" + account + ":assumed-role/App/s";
|
||||
String roleArn = "arn:aws:iam::" + account + ":role/team/App";
|
||||
when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(sessionArn, roleArn)));
|
||||
@@ -1340,7 +1681,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request"))
|
||||
.thenReturn("AKIADENIEDUSER");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
|
||||
when(iamService.resolveCallerContext("AKIADENIEDUSER"))
|
||||
when(iamService.resolveCallerContext(eq("AKIADENIEDUSER"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
|
||||
@@ -1376,7 +1717,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request"))
|
||||
.thenReturn("AKIADENIEDUSER");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
|
||||
when(iamService.resolveCallerContext("AKIADENIEDUSER"))
|
||||
when(iamService.resolveCallerContext(eq("AKIADENIEDUSER"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
|
||||
@@ -1411,7 +1752,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId("AWS4-HMAC-SHA256 Credential=AKIAALLOWEDUSER/20260907/us-east-1/s3/aws4_request"))
|
||||
.thenReturn("AKIAALLOWEDUSER");
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
|
||||
when(iamService.resolveCallerContext("AKIAALLOWEDUSER"))
|
||||
when(iamService.resolveCallerContext(eq("AKIAALLOWEDUSER"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
|
||||
@@ -1444,17 +1785,21 @@ class IamEnforcementFilterTest {
|
||||
@Test
|
||||
void filterBypassesWhenNeitherAuthorizationHeaderNorPresignedCredentialIsPresent() {
|
||||
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
|
||||
stubNoQueryParameters(containerRequest);
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(null);
|
||||
|
||||
newFilter().filter(containerRequest);
|
||||
|
||||
verify(iamService, never()).resolveCallerContext(any());
|
||||
verify(iamService, never()).resolveCallerContext(any(), any());
|
||||
verify(containerRequest, never()).abortWith(any());
|
||||
}
|
||||
|
||||
private static void stubNoQueryParameters(ContainerRequestContext containerRequest) {
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
|
||||
}
|
||||
|
||||
private void stubPresignedCredential(ContainerRequestContext containerRequest, String credential) {
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
MultivaluedHashMap<String, String> queryParams = new MultivaluedHashMap<>();
|
||||
@@ -1561,6 +1906,14 @@ class IamEnforcementFilterTest {
|
||||
if (entity instanceof byte[] b) {
|
||||
return new String(b, StandardCharsets.UTF_8);
|
||||
}
|
||||
if (entity instanceof AwsErrorResponse error) {
|
||||
// Serialized as the response writer serializes it.
|
||||
try {
|
||||
return new ObjectMapper().writeValueAsString(error);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
return entity.toString();
|
||||
}
|
||||
|
||||
@@ -1580,7 +1933,7 @@ class IamEnforcementFilterTest {
|
||||
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIACROSS");
|
||||
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
|
||||
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:ListBucket");
|
||||
when(iamService.resolveCallerContext("ASIACROSS"))
|
||||
when(iamService.resolveCallerContext(eq("ASIACROSS"), any()))
|
||||
.thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* With enforcement on, a CBOR call the caller is not allowed to make is refused in CBOR. It used
|
||||
* to be refused with a JSON body, which the CBOR client that sent the call cannot read.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class CborAccessDeniedEnforcementIntegrationTest {
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCborCallTheCallerIsNotAllowedIsRefusedInCbor() {
|
||||
String userName = "cbor-denied-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
iam("CreateUser", userName);
|
||||
String accessKeyId = iam("CreateAccessKey", userName)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
|
||||
byte[] body = given()
|
||||
.contentType("application/x-amz-cbor-1.1")
|
||||
.header("Authorization", authorization(accessKeyId, "kinesis"))
|
||||
.header("X-Amz-Target", "Kinesis_20131202.ListStreams")
|
||||
.body(new byte[] {(byte) 0xa0})
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType("application/x-amz-cbor-1.1")
|
||||
.extract().asByteArray();
|
||||
|
||||
assertTrue(new String(body, StandardCharsets.ISO_8859_1).contains("AccessDeniedException"),
|
||||
"the refusal must arrive CBOR-encoded, not as JSON");
|
||||
}
|
||||
|
||||
private static ValidatableResponse iam(String action, String userName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization("test", "iam"))
|
||||
.formParam("Action", action)
|
||||
.formParam("UserName", userName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static String authorization(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260101/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=not-verified";
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* With enforcement on, a session past its expiration is answered with AWS's
|
||||
* {@code ExpiredTokenException}, not as a key that exists nowhere, on every call and every time.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class ExpiredSessionEnforcementIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT_ID = "000000000000";
|
||||
private static final Instant LONG_AGO = Instant.parse("2020-01-01T00:00:00Z");
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredSessionIsRefusedAsExpired() {
|
||||
String accessKeyId = expiredSession();
|
||||
|
||||
getCallerIdentity(accessKeyId)
|
||||
.then().statusCode(403).body(containsString("<Code>ExpiredTokenException</Code>"));
|
||||
// Asked again, it is still expired rather than gone.
|
||||
getCallerIdentity(accessKeyId)
|
||||
.then().statusCode(403).body(containsString("<Code>ExpiredTokenException</Code>"));
|
||||
given()
|
||||
.header("Authorization", authorization(accessKeyId, "lambda"))
|
||||
.contentType("application/json")
|
||||
.when()
|
||||
.get("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.header("X-Amzn-Errortype", "ExpiredTokenException")
|
||||
.body("__type", containsString("ExpiredTokenException"));
|
||||
given()
|
||||
.header("Authorization", authorization(accessKeyId, "s3"))
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>ExpiredToken</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPresignedPostWithAnExpiredSessionIsRefusedAndTheSessionStaysExpired() {
|
||||
// A presigned POST carries its credential in the form body, which only S3 reads.
|
||||
String accessKeyId = expiredSession();
|
||||
String bucket = "expired-session-post-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
given()
|
||||
.header("Authorization", authorization("test", "s3"))
|
||||
.when()
|
||||
.put("/" + bucket)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.multiPart("key", "expired.txt")
|
||||
.multiPart("x-amz-credential", accessKeyId + "/20260101/us-east-1/s3/aws4_request")
|
||||
.multiPart("file", "expired.txt", "x".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + bucket)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>ExpiredToken</Code>"));
|
||||
// Refusing it did not delete the session, which would leave the key unknown.
|
||||
getCallerIdentity(accessKeyId)
|
||||
.then().statusCode(403).body(containsString("<Code>ExpiredTokenException</Code>"));
|
||||
}
|
||||
|
||||
private String expiredSession() {
|
||||
String accessKeyId = "ASIAEXPIRED"
|
||||
+ UUID.randomUUID().toString().replace("-", "").substring(0, 9).toUpperCase(Locale.ROOT);
|
||||
iamService.registerSessionForAccount(ACCOUNT_ID, accessKeyId, "secret",
|
||||
"arn:aws:iam::" + ACCOUNT_ID + ":role/expired-session-role", LONG_AGO, null);
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
private static Response getCallerIdentity(String accessKeyId) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization(accessKeyId, "sts"))
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.when()
|
||||
.post("/");
|
||||
}
|
||||
|
||||
private static String authorization(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260101/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=not-verified";
|
||||
}
|
||||
}
|
||||
@@ -1588,6 +1588,80 @@ class IamServiceTest {
|
||||
assertTrue(service.resolveAccountId(accessKey.getAccessKeyId()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInactiveAccessKeyIsReportedWhicheverAccountHoldsIt() {
|
||||
AccountAwareStorageBackend<AccessKey> accessKeys = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000");
|
||||
AccessKey inactive = new AccessKey("AKIAINACTIVEEXAMPLE", "secret", "worker");
|
||||
inactive.setStatus("Inactive");
|
||||
accessKeys.putForAccount("111122223333", inactive.getAccessKeyId(), inactive);
|
||||
AccessKey active = new AccessKey("AKIAACTIVEEXAMPLE", "secret", "worker");
|
||||
accessKeys.putForAccount("111122223333", active.getAccessKeyId(), active);
|
||||
|
||||
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
|
||||
|
||||
// Routing skips the inactive key, so a request lands in another account than the one holding it.
|
||||
assertTrue(service.isInactiveAccessKey(inactive.getAccessKeyId()));
|
||||
assertFalse(service.isInactiveAccessKey(active.getAccessKeyId()));
|
||||
assertFalse(service.isInactiveAccessKey("AKIADOESNOTEXIST0000"));
|
||||
assertFalse(service.isInactiveAccessKey("ASIATEMPORARYEXAMPLE"));
|
||||
assertFalse(service.isInactiveAccessKey(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredSessionIsReportedWhicheverAccountStoresItAndIsNotDeletedByAsking() {
|
||||
AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000");
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), sessions);
|
||||
service.registerSessionForAccount("111122223333", "ASIAEXPIREDEXAMPLE", "secret",
|
||||
"arn:aws:iam::111122223333:role/worker", Instant.parse("2020-01-01T00:00:00Z"), null);
|
||||
service.registerSessionForAccount("111122223333", "ASIALIVEEXAMPLE", "secret",
|
||||
"arn:aws:iam::111122223333:role/worker", Instant.parse("2999-01-01T00:00:00Z"), null);
|
||||
|
||||
Instant now = Instant.parse("2026-01-01T00:00:00Z");
|
||||
|
||||
assertTrue(service.isExpiredSession("ASIAEXPIREDEXAMPLE", now));
|
||||
// Still stored, so a second request is answered the same way.
|
||||
assertTrue(service.isExpiredSession("ASIAEXPIREDEXAMPLE", now));
|
||||
assertFalse(service.isExpiredSession("ASIALIVEEXAMPLE", now));
|
||||
assertFalse(service.isExpiredSession("ASIADOESNOTEXIST0000", now));
|
||||
assertFalse(service.isExpiredSession("AKIAEXPIREDEXAMPLE", now));
|
||||
assertFalse(service.isExpiredSession(null, now));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSessionLiveAtTheMomentEnforcementAsksAboutIsResolvedAndKept() {
|
||||
// Enforcement asks both questions about one moment. A lookup reading its own, later clock
|
||||
// could find the session expired, delete it and leave it to be answered as unknown.
|
||||
IamService service = iamService(false, new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
Instant expiration = Instant.parse("2026-01-01T00:00:00Z");
|
||||
service.registerSessionForAccount("000000000000", "ASIAEXPIRINGEXAMPLE", "secret",
|
||||
"arn:aws:iam::000000000000:role/worker", expiration, null);
|
||||
Instant asked = expiration.minusNanos(1);
|
||||
|
||||
assertFalse(service.isExpiredSession("ASIAEXPIRINGEXAMPLE", asked));
|
||||
assertNotNull(service.resolveCallerContext("ASIAEXPIRINGEXAMPLE", asked));
|
||||
// Not deleted, so the next request finds it expired rather than unknown.
|
||||
assertTrue(service.isExpiredSession("ASIAEXPIRINGEXAMPLE", expiration.plusNanos(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccessKeyOfTheRequestAccountIsCheckedWithoutScanningOtherAccounts() {
|
||||
AccountAwareStorageBackend<AccessKey> accessKeys = Mockito.spy(new AccountAwareStorageBackend<>(
|
||||
new InMemoryStorage<>(), null, "000000000000"));
|
||||
AccessKey active = new AccessKey("AKIAOWNACTIVEKEY", "secret", "dev");
|
||||
accessKeys.putForAccount("000000000000", active.getAccessKeyId(), active);
|
||||
AccessKey inactive = new AccessKey("AKIAOWNINACTIVEKEY", "secret", "dev");
|
||||
inactive.setStatus("Inactive");
|
||||
accessKeys.putForAccount("000000000000", inactive.getAccessKeyId(), inactive);
|
||||
|
||||
IamService service = iamService(false, accessKeys, new InMemoryStorage<>());
|
||||
|
||||
assertFalse(service.isInactiveAccessKey(active.getAccessKeyId()));
|
||||
assertTrue(service.isInactiveAccessKey(inactive.getAccessKeyId()));
|
||||
Mockito.verify(accessKeys, Mockito.never()).scanAllAccountEntries(Mockito.any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findSecretKeyDoesNotResolveAnotherAccountsKey() {
|
||||
// The ElastiCache, MemoryDB and RDS IAM-auth proxies verify through findSecretKey and do
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* With enforcement on, a deactivated access key "can no longer be used by API calls" until it is
|
||||
* activated again (IAM User Guide, "Manage access keys for IAM users"). It is refused as a key that
|
||||
* exists nowhere is, in each protocol's own vocabulary.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class InactiveAccessKeyEnforcementIntegrationTest {
|
||||
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private static final String OTHER_ACCOUNT = "222233334444";
|
||||
private static final String LIST_USERS = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*"}]}""";
|
||||
private static final String PUT_OBJECT = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}]}""";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeactivatedKeyIsRefusedUntilItIsActivatedAgain() {
|
||||
String userName = "inactive-key-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String accessKeyId = userWithKey(DEFAULT_ACCOUNT, userName, LIST_USERS);
|
||||
query(accessKeyId, "iam", "ListUsers").then().statusCode(200);
|
||||
|
||||
setStatus(DEFAULT_ACCOUNT, userName, accessKeyId, "Inactive");
|
||||
query(accessKeyId, "iam", "ListUsers")
|
||||
.then().statusCode(403).body(containsString("InvalidClientTokenId"));
|
||||
// Not even a call that needs no permission.
|
||||
query(accessKeyId, "sts", "GetCallerIdentity")
|
||||
.then().statusCode(403).body(containsString("InvalidClientTokenId"));
|
||||
|
||||
setStatus(DEFAULT_ACCOUNT, userName, accessKeyId, "Active");
|
||||
query(accessKeyId, "iam", "ListUsers").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeactivatedKeyOfAnotherAccountIsRefusedRatherThanAllowedInTheDefaultOne() {
|
||||
// Routing skips an inactive key, so its requests land in the default account, where no user
|
||||
// holds it. The key's own user may do nothing at all.
|
||||
String userName = "inactive-elsewhere-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String accessKeyId = userWithKey(OTHER_ACCOUNT, userName, null);
|
||||
query(accessKeyId, "iam", "CreateUser", "UserName", userName + "-made")
|
||||
.then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
setStatus(OTHER_ACCOUNT, userName, accessKeyId, "Inactive");
|
||||
query(accessKeyId, "iam", "CreateUser", "UserName", userName + "-made")
|
||||
.then().statusCode(403).body(containsString("InvalidClientTokenId"));
|
||||
query(accessKeyId, "sts", "GetSessionToken")
|
||||
.then().statusCode(403).body(containsString("InvalidClientTokenId"));
|
||||
given()
|
||||
.header("Authorization", authorization(accessKeyId, "s3"))
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("InvalidAccessKeyId"));
|
||||
given()
|
||||
.header("Authorization", authorization(accessKeyId, "lambda"))
|
||||
.contentType("application/json")
|
||||
.when()
|
||||
.get("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("UnrecognizedClientException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeactivatedKeyCannotUploadThroughAPresignedPost() {
|
||||
// A presigned POST carries its credential in the form body, which only S3 reads.
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String bucket = "inactive-key-post-" + suffix;
|
||||
String userName = "inactive-key-post-" + suffix;
|
||||
given()
|
||||
.header("Authorization", authorization("test", "s3"))
|
||||
.when()
|
||||
.put("/" + bucket)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
String accessKeyId = userWithKey(DEFAULT_ACCOUNT, userName, PUT_OBJECT);
|
||||
presignedPost(accessKeyId, bucket, "before.txt").then().statusCode(204);
|
||||
|
||||
setStatus(DEFAULT_ACCOUNT, userName, accessKeyId, "Inactive");
|
||||
presignedPost(accessKeyId, bucket, "after.txt")
|
||||
.then().statusCode(403).body(containsString("<Code>InvalidAccessKeyId</Code>"));
|
||||
given()
|
||||
.header("Authorization", authorization("test", "s3"))
|
||||
.when()
|
||||
.head("/" + bucket + "/after.txt")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
}
|
||||
|
||||
/** Creates a user in {@code account}, with an inline policy when one is given, and returns its access key ID. */
|
||||
private static String userWithKey(String account, String userName, String policy) {
|
||||
query(account, "iam", "CreateUser", "UserName", userName).then().statusCode(200);
|
||||
if (policy != null) {
|
||||
query(account, "iam", "PutUserPolicy", "UserName", userName, "PolicyName", "inline",
|
||||
"PolicyDocument", policy).then().statusCode(200);
|
||||
}
|
||||
return query(account, "iam", "CreateAccessKey", "UserName", userName)
|
||||
.then().statusCode(200)
|
||||
.extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
|
||||
}
|
||||
|
||||
private static void setStatus(String account, String userName, String accessKeyId, String status) {
|
||||
query(account, "iam", "UpdateAccessKey", "UserName", userName, "AccessKeyId", accessKeyId,
|
||||
"Status", status).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static Response presignedPost(String accessKeyId, String bucket, String key) {
|
||||
return given()
|
||||
.multiPart("key", key)
|
||||
.multiPart("x-amz-credential", accessKeyId + "/20260101/us-east-1/s3/aws4_request")
|
||||
.multiPart("file", key, "x".getBytes(StandardCharsets.UTF_8), "text/plain")
|
||||
.when()
|
||||
.post("/" + bucket);
|
||||
}
|
||||
|
||||
private static Response query(String accessKeyId, String service, String action, String... params) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization(accessKeyId, service))
|
||||
.formParam("Action", action);
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request = request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
return request.when().post("/");
|
||||
}
|
||||
|
||||
private static String authorization(String accessKeyId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260101/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=not-verified";
|
||||
}
|
||||
}
|
||||
+33
@@ -57,6 +57,39 @@ class UnknownAccessKeyEnforcementIntegrationTest {
|
||||
.body(containsString("InvalidAccessKeyId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCallerIdentityRefusesAnUnknownAccessKey() {
|
||||
// It needs no permission, but it still needs a credential AWS recognises.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", UNKNOWN_KEY_AUTH.formatted("sts"))
|
||||
.formParam("Action", "GetCallerIdentity")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.body(containsString("<Code>InvalidClientTokenId</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCborServiceRejectsAnUnknownAccessKeyInCbor() {
|
||||
byte[] body = given()
|
||||
.contentType("application/x-amz-cbor-1.1")
|
||||
.header("Authorization", UNKNOWN_KEY_AUTH.formatted("kinesis"))
|
||||
.header("X-Amz-Target", "Kinesis_20131202.ListStreams")
|
||||
.body(new byte[] {(byte) 0xa0})
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(403)
|
||||
.contentType("application/x-amz-cbor-1.1")
|
||||
.extract().asByteArray();
|
||||
|
||||
assertTrue(new String(body, StandardCharsets.ISO_8859_1).contains("UnrecognizedClientException"),
|
||||
"the rejection must arrive CBOR-encoded, not as JSON");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsignedJsonServiceCallIsRefused() {
|
||||
given()
|
||||
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* With enforcement on, a request whose {@code Authorization} header carries no readable credential
|
||||
* has nothing to check. It used to skip enforcement altogether: leaving off the
|
||||
* {@code aws4_request} terminator, or sending a header that names no access key at all, let any
|
||||
* caller make the management calls an unsigned request is refused.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class UnreadableCredentialEnforcementIntegrationTest {
|
||||
|
||||
private static final String UNREADABLE_SCOPE_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260101/us-east-1/%s, "
|
||||
+ "SignedHeaders=host, Signature=not-a-real-signature";
|
||||
|
||||
private static final String NO_KEY_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=/20260101/us-east-1/%s/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=not-a-real-signature";
|
||||
|
||||
private static final String NO_CREDENTIAL_AUTH =
|
||||
"AWS4-HMAC-SHA256 SignedHeaders=host, Signature=not-a-real-signature";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
UNREADABLE_SCOPE_AUTH,
|
||||
NO_KEY_AUTH,
|
||||
NO_CREDENTIAL_AUTH,
|
||||
"Bearer not-an-aws-credential",
|
||||
"AWS AKIADOESNOTEXIST0000:c2lnbmF0dXJl",
|
||||
"Credential=AKIADOESNOTEXIST0000/20260101/us-east-1/iam/aws4_request",
|
||||
"garbage",
|
||||
""})
|
||||
void aQueryCallIsRefusedAndDoesNothing(String authorization) {
|
||||
String userName = "unreadable-credential-" + Integer.toHexString(authorization.hashCode());
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization.formatted("iam"))
|
||||
.formParam("Action", "CreateUser")
|
||||
.formParam("UserName", userName)
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>IncompleteSignature</Code>"));
|
||||
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/iam/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=setup")
|
||||
.formParam("Action", "GetUser")
|
||||
.formParam("UserName", userName)
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("NoSuchEntity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyHeaderIsRefusedWithTheGuidesWordingForIt() {
|
||||
// The IAM User Guide's "Troubleshoot SigV4" gives the message for this case.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", "")
|
||||
.formParam("Action", "ListUsers")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Message>Authorization header cannot be empty.</Message>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSigV4HeaderWithoutACredentialIsRefusedWithTheGuidesWordingForIt() {
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.header("Authorization", NO_CREDENTIAL_AUTH)
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.ListTables")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("IncompleteSignatureException"))
|
||||
.body("message", equalTo("Authorization header requires 'Credential' parameter."));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {UNREADABLE_SCOPE_AUTH, "Bearer not-an-aws-credential"})
|
||||
void aJsonCallIsRefused(String authorization) {
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.header("Authorization", authorization.formatted("dynamodb"))
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.ListTables")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("IncompleteSignatureException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCborCallIsRefusedInCbor() {
|
||||
byte[] body = given()
|
||||
.contentType("application/x-amz-cbor-1.1")
|
||||
.header("Authorization", UNREADABLE_SCOPE_AUTH.formatted("kinesis"))
|
||||
.header("X-Amz-Target", "Kinesis_20131202.ListStreams")
|
||||
.body(new byte[] {(byte) 0xa0})
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.contentType("application/x-amz-cbor-1.1")
|
||||
.extract().asByteArray();
|
||||
|
||||
assertTrue(new String(body, StandardCharsets.ISO_8859_1).contains("IncompleteSignatureException"),
|
||||
"the rejection must arrive CBOR-encoded, not as JSON");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCognitoFlowAwsServesWithoutCredentialsIsNotRefused() {
|
||||
// As for an unsigned request: the operation needs no credential, so an unreadable one
|
||||
// does not stop it, and Cognito answers the missing client itself.
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", "Bearer not-an-aws-credential")
|
||||
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth")
|
||||
.body("{}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {UNREADABLE_SCOPE_AUTH, NO_KEY_AUTH})
|
||||
void anS3CallClaimingSigV4IsRefusedWithTheS3ErrorCode(String authorization) {
|
||||
given()
|
||||
.header("Authorization", authorization.formatted("s3"))
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>AuthorizationHeaderMalformed</Code>"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
// Slashes encoded twice, as in an AWS-recorded presigned URL: one segment, no scope.
|
||||
"AKIADOESNOTEXIST0000%252F20260101%252Fus-east-1%252Fs3%252Faws4_request",
|
||||
"AKIADOESNOTEXIST0000%2F20260101%2Fus-east-1%2Fs3"})
|
||||
void aPresignedS3UrlWithAMalformedCredentialIsRefusedWithTheQueryErrorCode(String credential) {
|
||||
given()
|
||||
.urlEncodingEnabled(false)
|
||||
.when()
|
||||
.get("/unreadable-credential-bucket/key?X-Amz-Algorithm=AWS4-HMAC-SHA256"
|
||||
+ "&X-Amz-Credential=" + credential
|
||||
// A signing time the URL's expiry check never passes, so the test reads no clock.
|
||||
+ "&X-Amz-Date=29990101T000000Z"
|
||||
+ "&X-Amz-Expires=300&X-Amz-SignedHeaders=host&X-Amz-Signature=not-a-real-signature")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>AuthorizationQueryParametersError</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestCallWithAnotherSchemeIsTreatedAsUnsigned() {
|
||||
// AppSync, CodeArtifact's package endpoints and API Gateway's authorizers take Bearer and
|
||||
// Basic tokens of their own, so a REST request carrying one is not refused here.
|
||||
given()
|
||||
.header("Authorization", "Bearer not-an-aws-credential")
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestRouteNoActionMapsIsLeftToItsHandler() {
|
||||
// As for an unsigned REST request: the filter cannot tell it from the API Gateway execute
|
||||
// path, function URLs and the other paths it sees that are unsigned by design.
|
||||
given()
|
||||
.header("Authorization", UNREADABLE_SCOPE_AUTH.formatted("iam"))
|
||||
.when()
|
||||
.get("/_floci/health")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user