Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iam): refuse inactive keys and unreadable credentials in enforcement (#5346)

Priamo Germosen46f9c23c8be8
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java
index e14a8cd5e0..68d22dccba 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamEnforcementTest.java
@@ -563,6 +563,43 @@ class IamEnforcementTest {
}
}
+ @Test
+ @Order(14)
+ @DisplayName("a deactivated access key is refused until it is activated again")
+ void deactivatedAccessKeyIsRefusedUntilActivatedAgain() {
+ assumeEnforcementEnabled();
+ AccessKey key = iam.createAccessKey(CreateAccessKeyRequest.builder().userName(USER).build()).accessKey();
+ try (StsClient caller = StsClient.builder()
+ .endpointOverride(TestFixtures.endpoint())
+ .region(Region.US_EAST_1)
+ .credentialsProvider(StaticCredentialsProvider.create(
+ AwsBasicCredentials.create(key.accessKeyId(), key.secretAccessKey())))
+ .build();
+ S3Client s3 = s3WithCredentials(key.accessKeyId(), key.secretAccessKey())) {
+ iam.updateAccessKey(UpdateAccessKeyRequest.builder()
+ .userName(USER).accessKeyId(key.accessKeyId()).status(StatusType.INACTIVE).build());
+ // Not even a call that needs no permission.
+ assertThatThrownBy(caller::getCallerIdentity)
+ .isInstanceOfSatisfying(StsException.class, error -> {
+ assertThat(error.statusCode()).isEqualTo(403);
+ assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidClientTokenId");
+ });
+ assertThatThrownBy(s3::listBuckets)
+ .isInstanceOfSatisfying(S3Exception.class, error -> {
+ assertThat(error.statusCode()).isEqualTo(403);
+ assertThat(error.awsErrorDetails().errorCode()).isEqualTo("InvalidAccessKeyId");
+ });
+
+ iam.updateAccessKey(UpdateAccessKeyRequest.builder()
+ .userName(USER).accessKeyId(key.accessKeyId()).status(StatusType.ACTIVE).build());
+ assertThatCode(caller::getCallerIdentity).doesNotThrowAnyException();
+ } finally {
+ cleanupResource("delete access key " + key.accessKeyId(),
+ () -> iam.deleteAccessKey(DeleteAccessKeyRequest.builder()
+ .userName(USER).accessKeyId(key.accessKeyId()).build()));
+ }
+ }
+
private static StaticCredentialsProvider userCredentials() {
return StaticCredentialsProvider.create(AwsBasicCredentials.create(userAccessKeyId, userSecretKey));
}
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 6c7bbac247..a6403490ba 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1004,9 +1004,12 @@ These identities always bypass enforcement (backward-compatible defaults):
| Identity | Behaviour |
|---|---|
| Access key `test` (the default dev credential) | Always allowed — no policy lookup |
-| Access key that exists nowhere | **Rejected** with `403`: `InvalidAccessKeyId` for S3, `InvalidClientTokenId` for Query services, `UnrecognizedClientException` for JSON services |
+| Access key that exists nowhere | **Rejected** with `403`, `sts:GetCallerIdentity` included: `InvalidAccessKeyId` for S3, `InvalidClientTokenId` for Query services, `UnrecognizedClientException` for JSON services. A presigned POST, whose credential is in the form body, is left to S3's own presigned-POST check |
+| Inactive access key | **Rejected** the same way, until the key is activated again |
+| Expired session credentials | **Rejected** with `403 ExpiredTokenException`, or `400 ExpiredToken` for S3, rather than as a key that exists nowhere, for as long as Floci still holds the session |
+| `Authorization` header with no readable credential: no access key (a Bearer token, SigV2, a credential without the SigV4 scheme or without its key), or a scope missing a part such as its `aws4_request` terminator, or an empty header. An empty header next to a presigned URL's `X-Amz-Credential` defers to that credential | **Rejected** with `400`: `AuthorizationHeaderMalformed` for S3 (`AuthorizationQueryParametersError` when the credential is a presigned URL's `X-Amz-Credential`), `IncompleteSignature` for Query services, `IncompleteSignatureException` for JSON services. A REST request is rejected only when the header claims SigV4; otherwise it is treated as unsigned (see [Unsigned requests](#unsigned-requests)) |
| Credential the filter cannot map to policies, such as a session carrying no role ARN | Allowed: it is a real credential, so rejecting it would refuse an authenticated caller |
-| No `Authorization` header | Allowed — unauthenticated path (e.g. health checks) |
+| No `Authorization` header | **Rejected** for a JSON, CBOR or Query management call, unless AWS serves the operation without credentials. Allowed for a REST request such as a health check (see [Unsigned requests](#unsigned-requests)) |
| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
**IAM's own resources are mostly not named.** When enforcement evaluates a request, the target
@@ -1229,6 +1232,15 @@ function URLs, CloudFront serving, the Cognito OIDC endpoints and Floci's own he
of which are unsigned by design, and a REST request does not say which service will serve it. An
unsigned REST call therefore still reaches the service, including an unsigned S3 call.
+**A header with no readable credential does not get around this.** An `Authorization` header that
+names no access key (a Bearer token, SigV2, a credential without the SigV4 scheme or without its
+key), or whose SigV4 scope is missing a part, is refused on the same management calls with
+`400 IncompleteSignature`, the error AWS gives a header it cannot read. A REST request carrying one
+is refused only when the header claims SigV4 and the route maps to an IAM action. Otherwise it is
+treated as unsigned, because 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
+is refused the same way, unless a presigned URL's `X-Amz-Credential` is there to read instead.
+
## Bypass rules
Enforcement is deliberately permissive in a few cases, so that enabling it does not break workloads
@@ -1236,11 +1248,14 @@ the emulator cannot reason about:
| Case | Behaviour |
| --- | --- |
-| Unresolvable action | Allowed. An action the registry cannot resolve is not evaluated. |
+| Unresolvable action | Allowed. An action the registry cannot resolve is not evaluated. The credential is still checked on an RPC call, as in the rows below. A REST request is left alone, as an unsigned one 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. |
| No `Authorization` header, RPC protocol | **Rejected** with `403 MissingAuthenticationToken`, unless the operation is one AWS itself serves without credentials. |
| No `Authorization` header, REST protocol | Allowed. This filter also sees the API Gateway execute path, Lambda function URLs, CloudFront serving and the Cognito OIDC endpoints, which are unsigned by design. |
-| `sts:GetCallerIdentity` | Always allowed — AWS returns caller identity even when a policy denies it. |
-| Access key that exists nowhere | **Rejected** with `403`, in each protocol's own vocabulary: `InvalidAccessKeyId` for S3, `InvalidClientTokenId` for Query services, `UnrecognizedClientException` for JSON services. Allowing it would let any string authorize the request. |
+| `sts:GetCallerIdentity` | No policy is evaluated: AWS returns caller identity even when a policy denies it. The credential is still checked: a key that exists nowhere or is inactive, an expired session, or a header with no readable credential is refused as below. |
+| Access key that exists nowhere | **Rejected** with `403`, in each protocol's own vocabulary: `InvalidAccessKeyId` for S3, `InvalidClientTokenId` for Query services, `UnrecognizedClientException` for JSON services. Allowing it would let any string authorize the request. A presigned POST is the exception: its credential is in the form body, so a key that exists nowhere, or a credential that cannot be read, is left to S3's own presigned-POST check, and uploads as an unsigned request would when that check is off. An inactive key or an expired session is refused there as everywhere else. |
+| Inactive access key | **Rejected** the same way: a deactivated key can no longer be used by API calls until it is activated again. |
+| Expired session credentials | **Rejected** with `403 ExpiredTokenException`, or `400 ExpiredToken` for S3. Once Floci has removed an expired session it no longer knows the key, and answers as for one that exists nowhere. |
+| `Authorization` header with no readable credential | **Rejected** with `400`, in each protocol's own vocabulary: `AuthorizationHeaderMalformed` for S3 (`AuthorizationQueryParametersError` when the credential is a presigned URL's `X-Amz-Credential`), `IncompleteSignature` for Query services, `IncompleteSignatureException` for JSON services. Without a key or a scope there is nothing to check, so allowing it would skip enforcement altogether. As with no header, an operation AWS serves without credentials is left alone, and a REST request is rejected only when the header claims SigV4. |
| Known credential with no mappable caller context | Allowed. A stored session carrying no role ARN is a real credential, so it is not treated as unauthenticated. |
| Bare account-id key with no SCP ceiling | Allowed. With no organization or SCP enforcement off, the account root keeps the historical bypass. |
| Bare account-id key **with** an SCP ceiling | Enforced as the account root, bounded by the SCP chain. |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index 8f2dba2034..6ea6e16ade 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -33,6 +33,7 @@ import org.jboss.logging.Logger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -53,9 +54,12 @@ import java.util.regex.Pattern;
* <li>Enforcement is disabled (default)</li>
* <li>Access key is {@code "test"} (root/admin stand-in)</li>
* <li>Access key is a real credential this filter cannot map to policies, such as a session
- * carrying no role ARN. An access key that exists nowhere is rejected, not bypassed.</li>
+ * carrying no role ARN. An access key that exists nowhere or is inactive, an expired
+ * session, and an {@code Authorization} header with no readable credential are rejected,
+ * not bypassed.</li>
* <li>The action cannot be resolved (unknown mapping → permissive)</li>
- * <li>The action is {@code sts:GetCallerIdentity}, which AWS allows without permissions</li>
+ * <li>The action is {@code sts:GetCallerIdentity}, which AWS allows without permissions. The
+ * key itself is still checked.</li>
* </ul>
*
* <p>Evaluates the caller's identity policies, optional session policy, and optional
@@ -80,6 +84,25 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
/** AWS's wording for a credential it does not recognise. */
private static final String INVALID_SECURITY_TOKEN = "The security token included in the request is invalid.";
+ /** S3's wording for an access key it does not recognise. */
+ private static final String S3_INVALID_ACCESS_KEY_ID =
+ "The AWS Access Key Id you provided does not exist in our records.";
+
+ /** AWS's wording for temporary credentials past their expiration. */
+ private static final String EXPIRED_TOKEN = "The security token included in the request has expired.";
+
+ /** S3's wording for the same. */
+ private static final String S3_EXPIRED_TOKEN = "The provided token has expired.";
+
+ /** AWS's wording for a signature that does not follow its format. */
+ private static final String INCOMPLETE_SIGNATURE = "The request signature does not conform to AWS standards.";
+
+ /** The IAM User Guide's "Troubleshoot SigV4" wording for an empty header. */
+ private static final String EMPTY_AUTHORIZATION = "Authorization header cannot be empty.";
+
+ /** The same guide's wording for a SigV4 header without its credential. */
+ private static final String MISSING_CREDENTIAL = "Authorization header requires 'Credential' parameter.";
+
/** AWS's wording for a request that carries no credentials at all. */
private static final String MISSING_AUTHENTICATION_TOKEN =
"The request must contain a valid AWS access key ID or X.509 certificate.";
@@ -257,21 +280,29 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
String auth = ctx.getHeaderString("Authorization");
- if (auth == null || auth.isBlank()) {
+ boolean emptyHeader = auth != null && auth.isBlank();
+ if (auth == null || emptyHeader) {
auth = requestAuthorization(null, ctx.getUriInfo().getQueryParameters());
}
if (auth == null) {
- refuseUnsignedManagementCall(ctx);
+ if (emptyHeader) {
+ // An empty header is not a missing one: "Authorization header cannot be empty" is
+ // among the failures the IAM User Guide's "Troubleshoot SigV4" lists.
+ refuseUnreadableCredential(ctx, "");
+ } else {
+ refuseUnsignedManagementCall(ctx);
+ }
return;
}
String akid = accountResolver.extractAccessKeyId(auth);
- if (akid == null || "test".equals(akid)) {
+ if ("test".equals(akid)) {
return; // root bypass
}
- String rawScope = extractCredentialScope(auth);
+ String rawScope = akid == null ? null : extractCredentialScope(auth);
if (rawScope == null) {
+ refuseUnreadableCredential(ctx, auth);
return;
}
// Normalise signing aliases (s3express → s3) before anything keyed by scope runs:
@@ -285,11 +316,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if (!"OPTIONS".equalsIgnoreCase(ctx.getMethod())
&& iamService.presignedScope(akid).isPresent()) {
ctx.abortWith(accessDeniedForRequest("Unknown", credentialScope, ctx));
+ return;
+ }
+ if (!isRpcCall(ctx)) {
+ return; // REST route no rule maps → ALLOW, as an unsigned REST request is
}
- return; // unknown action → ALLOW for ordinary credentials (permissive)
- }
- if ("sts:GetCallerIdentity".equals(action)) {
- return; // AWS returns caller identity even when an identity policy explicitly denies it
}
String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion();
@@ -297,42 +328,66 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
? accountResolver.resolve(auth)
: requestContext.getAccountId();
+ // The key is checked before the action is used: an API call needs a usable key whatever it
+ // asks for, even one that needs no permission, such as GetCallerIdentity. A bare 12-digit
+ // account-id key is floci's account-root principal, never an IAM user's key.
+ boolean accountRootKey = akid.equals(accountId);
+ if (!accountRootKey && iamService.isInactiveAccessKey(akid)) {
+ LOG.debugv("Rejecting request signed with an inactive access key id {0}", akid);
+ ctx.abortWith(unrecognizedClientResponse(credentialScope, ctx));
+ return;
+ }
+ // Both lookups are asked about one moment, so a session that expires between them is not
+ // deleted and then answered as a key that exists nowhere.
+ Instant now = Instant.now();
+ if (iamService.isExpiredSession(akid, now)) {
+ LOG.debugv("Rejecting request signed with an expired session {0}", akid);
+ ctx.abortWith(expiredTokenResponse(credentialScope, ctx));
+ return;
+ }
+ CallerContext caller = iamService.resolveCallerContext(akid, now);
+ if (caller == null && !accountRootKey && !iamService.isKnownAccessKey(akid)) {
+ // No such credential anywhere. Enforcement is on and the caller is unauthenticated,
+ // so allowing it would hand an arbitrary access key id every permission there is.
+ LOG.debugv("Rejecting request signed with an unknown access key id {0}", akid);
+ ctx.abortWith(unrecognizedClientResponse(credentialScope, ctx));
+ return;
+ }
+ if (action == null) {
+ return; // unknown action → ALLOW for ordinary credentials (permissive)
+ }
+ if ("sts:GetCallerIdentity".equals(action)) {
+ return; // AWS returns caller identity even when an identity policy explicitly denies it
+ }
+
// Service control policies from the caller's organization, when the Organizations
// service is present and SCP enforcement is enabled. Resolved lazily via Instance
// to avoid a hard IAM → Organizations dependency.
//
- // Resolved before resolveCallerContext because the account-root branch below needs to
- // know whether a ceiling exists in order to decide between enforcing and bypassing. That
- // costs an organization lookup on requests that then bypass; both flags are opt-in, and
- // effectiveScpLevels returns null immediately when SCP enforcement is off.
+ // Resolved before the account-root branch below, which needs to know whether a ceiling
+ // exists in order to decide between enforcing and bypassing. That costs an organization
+ // lookup on requests that then bypass; both flags are opt-in, and effectiveScpLevels
+ // returns null immediately when SCP enforcement is off.
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId)
: null;
boolean accountRootPrincipal = false;
- CallerContext caller = iamService.resolveCallerContext(akid);
if (caller == null) {
- // A bare 12-digit account-id key is floci's account-root principal: not a registered
- // IAM identity (resolveCallerContext → null), but in AWS the account root is still
- // bounded by SCPs. Enforce them when the account actually has an SCP ceiling.
- if (akid.equals(accountId)) {
- if (scpLevels == null) {
- return; // account root with no ceiling → nothing to enforce
- }
- caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
- accountRootPrincipal = true;
- } else if (iamService.isKnownAccessKey(akid)) {
+ if (!accountRootKey) {
// A real credential this filter cannot map to policies, such as a session Floci mints
// for its own presigned URLs with no policy to scope it. Denying it would reject an
// authenticated caller.
return;
- } else {
- // No such credential anywhere. Enforcement is on and the caller is unauthenticated,
- // so allowing it would hand an arbitrary access key id every permission there is.
- LOG.debugv("Rejecting request signed with an unknown access key id {0}", akid);
- ctx.abortWith(unrecognizedClientResponse(credentialScope, ctx.getMediaType()));
- return;
}
+ // A bare 12-digit account-id key is floci's account-root principal: not a registered
+ // IAM identity (resolveCallerContext → null), but in AWS the account root is still
+ // bounded by SCPs. Enforce them when the account actually has an SCP ceiling.
+ if (scpLevels == null) {
+ return; // account root with no ceiling → nothing to enforce
+ }
+ caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
+ accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
@@ -480,24 +535,104 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return new ResolvedAuthorization(servingScope, servingScope + ":" + queryAction);
}
- boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST;
- if (rest && resourceInfo != null && resourceInfo.getResourceClass() != null) {
- ServiceDescriptor descriptor = catalog.byResourceClass(resourceInfo.getResourceClass()).orElse(null);
- if (descriptor != null) {
- ResolvedAuthorization routeAuthorization = resolveRestAuthorization(descriptor, ctx);
- if (routeAuthorization != null) {
- return routeAuthorization;
- }
- }
+ ResolvedAuthorization routeAuthorization = restRouteAuthorization(ctx);
+ if (routeAuthorization != null) {
+ return routeAuthorization;
}
// A REST request is authorized by its route alone, never by an X-Amz-Target it carries.
+ boolean rest = claimValue instanceof ProtocolClaim claim && claim.protocol() == WireProtocol.REST;
String servingScope = servingCredentialScope(claimedScope, ctx);
return new ResolvedAuthorization(servingScope, rest
? actionRegistry.resolveRoute(servingScope, ctx)
: actionRegistry.resolve(servingScope, ctx));
}
+ /**
+ * The action a REST request's matched route maps to, read from the route alone. Null for any
+ * other request, and for a route no rule maps.
+ */
+ private ResolvedAuthorization restRouteAuthorization(ContainerRequestContext ctx) {
+ if (!(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim)
+ || claim.protocol() != WireProtocol.REST
+ || resourceInfo == null || resourceInfo.getResourceClass() == null) {
+ return null;
+ }
+ return catalog.byResourceClass(resourceInfo.getResourceClass())
+ .map(descriptor -> resolveRestAuthorization(descriptor, ctx))
+ .orElse(null);
+ }
+
+ /**
+ * Refuses a request whose {@code Authorization} header this filter cannot read a credential
+ * from: an empty one, one naming no access key (a Bearer token, SigV2, a credential without the
+ * SigV4 scheme or without its key, see {@link AccountResolver#extractAccessKeyId}), or a SigV4
+ * credential scope missing a part, such as its {@code aws4_request} terminator. With no key or
+ * no scope there is nothing to check, so letting it through would skip enforcement, the key
+ * checks included, for any action. The IAM User Guide's "Troubleshoot SigV4" lists these
+ * failures (an empty header, a missing credential, a header that does not start with an
+ * algorithm name) under {@code IncompleteSignatureException}. The other services' common errors
+ * call it {@code IncompleteSignature}, and S3's error list {@code AuthorizationHeaderMalformed},
+ * or {@code AuthorizationQueryParametersError} for a presigned URL, all 400.
+ *
+ * <p>Otherwise it is treated as an unsigned request is. An operation AWS serves without
+ * credentials is left alone. A REST request is refused only when it claims SigV4 and its route
+ * maps to an action: AppSync, CodeArtifact's package endpoints, Identity Store's SCIM endpoint
+ * and API Gateway's authorizers take Bearer and Basic tokens of their own, and this filter
+ * cannot tell the API Gateway execute path, Lambda function URLs and the other paths it sees
+ * that are unsigned by design from the rest. A SigV4a scope, which has no region segment, does
+ * not get here: {@link AccountContextFilter} reads its service name as the region and refuses
+ * it, unless unknown regions are allowed.
+ */
+ private void refuseUnreadableCredential(ContainerRequestContext ctx, String auth) {
+ if (ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
+ && claim.protocol() != WireProtocol.REST
+ && servesWithoutCredentials(claim, ctx)) {
+ return;
+ }
+ ResolvedAuthorization routeAuthorization = claimsSigV4(auth) ? restRouteAuthorization(ctx) : null;
+ if (routeAuthorization == null && !isRpcCall(ctx)) {
+ return;
+ }
+ LOG.debugv("Rejecting a {0} request whose Authorization header carries no readable credential",
+ ctx.getMethod());
+ ctx.abortWith(incompleteSignatureResponse(
+ routeAuthorization == null ? null : routeAuthorization.credentialScope(), ctx,
+ incompleteSignatureMessage(auth)));
+ }
+
+ /**
+ * The guide's own wording where it gives one: for an empty header, and for a SigV4 header
+ * without its credential. It gives none for the other shapes, which get the common errors' text.
+ */
+ private static String incompleteSignatureMessage(String auth) {
+ if (auth.isEmpty()) {
+ return EMPTY_AUTHORIZATION;
+ }
+ if (auth.startsWith("AWS4-") && !auth.contains("Credential=")) {
+ return MISSING_CREDENTIAL;
+ }
+ return INCOMPLETE_SIGNATURE;
+ }
+
+ /**
+ * A SigV4 {@code Authorization} header, or the {@code Credential=} string
+ * {@link #requestAuthorization} builds from a presigned URL.
+ */
+ private static boolean claimsSigV4(String auth) {
+ return auth.startsWith("AWS4-") || auth.contains("Credential=");
+ }
+
+ /**
+ * Whether this is a Query, JSON or CBOR call. Only an AWS API client sends one, whereas a REST
+ * request may be one of the unsigned-by-design paths this filter also sees.
+ */
+ private static boolean isRpcCall(ContainerRequestContext ctx) {
+ return IamActionRegistry.isQueryRequest(ctx)
+ || ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
+ && claim.protocol() != WireProtocol.REST;
+ }
+
private ResolvedAuthorization resolveRestAuthorization(ServiceDescriptor descriptor,
ContainerRequestContext ctx) {
return descriptor.credentialScopes().stream()
@@ -636,7 +771,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* <p>Returns normally when the action is allowed, or when enforcement does not
* apply to this request (enforcement disabled, no Authorization header, root or
* unknown access key). Throws {@link AwsException} with the same AccessDenied
- * shape as {@link #filter} when the caller's policies deny the action.
+ * shape as {@link #filter} when the caller's policies deny the action, and with the
+ * codes {@link #filter} answers when the access key is inactive or the session has expired.
*
* <p>The account used for policy evaluation is always re-resolved from {@code akid} here
* (see {@link #resolveCredentialAccountId}) rather than trusted from {@link RequestContext},
@@ -713,11 +849,28 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
String previousAccountId = requestContext.getAccountId();
requestContext.setAccountId(accountId);
try {
+ // A presigned POST carries its credential only in the form body, which filter() never
+ // sees, so a key IAM holds but that can no longer be used is refused here as filter()
+ // refuses it. Otherwise an inactive key would act with its user's policies, and
+ // resolveCallerContext would delete an expired session, which would then read as a key
+ // that exists nowhere. For a second resource of a request filter() has seen, the key
+ // has already passed these checks.
+ boolean accountRootKey = akid.equals(accountId);
+ if (!accountRootKey && iamService.isInactiveAccessKey(akid)) {
+ throw unrecognizedClientException(credentialScope);
+ }
+ // One moment for both lookups, as in filter(): a session expiring between them would
+ // otherwise be deleted and then allowed below as a credential with no context.
+ Instant now = Instant.now();
+ if (iamService.isExpiredSession(akid, now)) {
+ throw expiredTokenException(credentialScope);
+ }
+
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
boolean accountRootPrincipal = false;
- CallerContext caller = iamService.resolveCallerContext(akid);
+ CallerContext caller = iamService.resolveCallerContext(akid, now);
if (caller == null) {
// No unknown-key rejection here, unlike filter(), and none is needed. For a second
// resource of a request filter() has seen (CopyObject's source, RotateSecret's
@@ -726,7 +879,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
// presigned POST carries its credential only in the form body, which filter() never
// sees: an unknown key there is refused by S3's presigned-POST signature check when
// S3 auth enforcement is on, and otherwise uploads as an unsigned request would.
- if (scpLevels == null || !akid.equals(accountId)) {
+ if (scpLevels == null || !accountRootKey) {
return;
}
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
@@ -995,6 +1148,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* <li>{@code application/x-www-form-urlencoded} body → AWS Query
* {@code <ErrorResponse>...</ErrorResponse>} (IAM/STS/EC2/SQS/SNS/...)</li>
* <li>JSON 1.x: JSON with HTTP 400; REST-JSON: JSON with HTTP 403</li>
+ * <li>CBOR: the request's own encoding with HTTP 403, from {@link #accessDeniedForRequest},
+ * which has the request to read it from</li>
* </ul>
*/
// Package-private for unit testing.
@@ -1012,14 +1167,21 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static Response accessDeniedForRequest(String action, String credentialScope,
ContainerRequestContext ctx, String resourceArn) {
- WireProtocol protocol = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
- ? claim.protocol() : WireProtocol.REST;
+ WireProtocol protocol = claimedProtocol(ctx);
+ if (isCbor(protocol)) {
+ // 403, the status the Kinesis and CloudWatch common errors give AccessDeniedException.
+ return cborError(ctx, "AccessDeniedException", accessDeniedMessage(action), 403);
+ }
return accessDeniedResponse(action, credentialScope, ctx.getMediaType(), resourceArn, protocol);
}
+ private static String accessDeniedMessage(String action) {
+ return "User is not authorized to perform: " + action;
+ }
+
static Response accessDeniedResponse(String action, String credentialScope, MediaType requestMediaType,
String resourceArn, WireProtocol protocol) {
- String message = "User is not authorized to perform: " + action;
+ String message = accessDeniedMessage(action);
if ("s3".equals(credentialScope)) {
String resourcePath = formatS3ResourcePath(resourceArn);
return s3XmlAccessDenied(message, resourcePath);
@@ -1050,6 +1212,10 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
private static Response queryXmlError(String code, String message) {
+ return queryXmlError(code, message, 403);
+ }
+
+ private static Response queryXmlError(String code, String message, int status) {
String xml = new XmlBuilder()
.start("ErrorResponse")
.start("Error")
@@ -1060,22 +1226,22 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
.elem("RequestId", UUID.randomUUID().toString())
.end("ErrorResponse")
.build();
- return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build();
+ return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml).build();
}
private static Response s3XmlAccessDenied(String message) {
return s3XmlAccessDenied(message, null);
}
- private static Response s3XmlError(String code, String message) {
- return s3Xml(code, message, null);
+ private static Response s3XmlError(String code, String message, int status) {
+ return s3Xml(code, message, null, status);
}
private static Response s3XmlAccessDenied(String message, String resourcePath) {
- return s3Xml("AccessDenied", message, resourcePath);
+ return s3Xml("AccessDenied", message, resourcePath, 403);
}
- private static Response s3Xml(String code, String message, String resourcePath) {
+ private static Response s3Xml(String code, String message, String resourcePath, int status) {
XmlBuilder xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("Error")
@@ -1086,7 +1252,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
xml.elem("RequestId", UUID.randomUUID().toString())
.end("Error");
- return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml.build()).build();
+ return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml.build()).build();
}
/**
@@ -1099,16 +1265,66 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* {@code UnrecognizedClientException}, the only place botocore models it (CloudWatch Logs)
* and what the API Gateway execute path already returns.
*/
- static Response unrecognizedClientResponse(String credentialScope, MediaType requestMediaType) {
+ static Response unrecognizedClientResponse(String credentialScope, ContainerRequestContext ctx) {
if ("s3".equals(credentialScope)) {
- return s3XmlError("InvalidAccessKeyId",
- "The AWS Access Key Id you provided does not exist in our records.");
+ return s3XmlError("InvalidAccessKeyId", S3_INVALID_ACCESS_KEY_ID, 403);
}
- if (isFormEncoded(requestMediaType)) {
- return queryXmlError("InvalidClientTokenId", INVALID_SECURITY_TOKEN);
+ return protocolError(claimedProtocol(ctx), ctx, "InvalidClientTokenId", "UnrecognizedClientException",
+ INVALID_SECURITY_TOKEN, 403);
+ }
+
+ /** {@link #unrecognizedClientResponse} for a caller that renders the error itself. */
+ private static AwsException unrecognizedClientException(String credentialScope) {
+ return "s3".equals(credentialScope)
+ ? new AwsException("InvalidAccessKeyId", S3_INVALID_ACCESS_KEY_ID, 403)
+ : new AwsException("UnrecognizedClientException", INVALID_SECURITY_TOKEN, 403);
+ }
+
+ /**
+ * The response for a session whose temporary credentials have expired. S3's error list names it
+ * {@code ExpiredToken}, 400. The other services' common errors name it
+ * {@code ExpiredTokenException}, 403, under the same name for Query services as for JSON ones.
+ */
+ static Response expiredTokenResponse(String credentialScope, ContainerRequestContext ctx) {
+ if ("s3".equals(credentialScope)) {
+ return s3XmlError("ExpiredToken", S3_EXPIRED_TOKEN, 400);
}
- String body = "{\"__type\":\"UnrecognizedClientException\",\"message\":\"" + INVALID_SECURITY_TOKEN + "\"}";
- return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build();
+ return protocolError(claimedProtocol(ctx), ctx, "ExpiredTokenException", "ExpiredTokenException",
+ EXPIRED_TOKEN, 403);
+ }
+
+ /** {@link #expiredTokenResponse} for a caller that renders the error itself. */
+ private static AwsException expiredTokenException(String credentialScope) {
+ return "s3".equals(credentialScope)
+ ? new AwsException("ExpiredToken", S3_EXPIRED_TOKEN, 400)
+ : new AwsException("ExpiredTokenException", EXPIRED_TOKEN, 403);
+ }
+
+ /**
+ * The response for a signature that does not follow AWS's format, from
+ * {@link #refuseUnreadableCredential}. S3 answers with {@code AuthorizationHeaderMalformed}
+ * and the wording {@code S3HeaderSignatureFilter} uses for a mal-formed credential, so S3 answers
+ * the same whichever check catches it. A presigned URL sends no header: its credential is the
+ * {@code X-Amz-Credential} parameter, and S3 answers a mal-formed one with
+ * {@code AuthorizationQueryParametersError}. Other services answer with
+ * {@code IncompleteSignature}, spelled with the {@code Exception} suffix outside Query as the
+ * other codes here are, and the {@code message} the caller picked. All 400.
+ */
+ static Response incompleteSignatureResponse(String credentialScope, ContainerRequestContext ctx,
+ String message) {
+ if ("s3".equals(credentialScope)) {
+ String header = ctx.getHeaderString("Authorization");
+ if (header == null || header.isBlank()) {
+ return s3XmlError("AuthorizationQueryParametersError", "Error parsing the X-Amz-Credential "
+ + "parameter; the Credential is mal-formed; expecting "
+ + "\"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".", 400);
+ }
+ return s3XmlError("AuthorizationHeaderMalformed", "The authorization header is malformed; "
+ + "the Credential is mal-formed; expecting "
+ + "\"<YOUR-AKID>/YYYYMMDD/REGION/SERVICE/aws4_request\".", 400);
+ }
+ return protocolError(claimedProtocol(ctx), ctx, "IncompleteSignature", "IncompleteSignatureException",
+ message, 400);
}
/**
@@ -1166,27 +1382,56 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* returns for the same failure on its own path.
*/
static Response missingAuthenticationTokenResponse(WireProtocol protocol, ContainerRequestContext ctx) {
- if (protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET) {
- // A CBOR client cannot read a JSON body, so the rejection has to arrive in the encoding
- // the request used, the same shape the rpcv2 controller returns for its own errors.
- String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER);
- if (requestContentType == null) {
- requestContentType = ctx.getHeaderString("Content-Type");
- }
- return CborErrorResponses.of(
- new AwsException("MissingAuthenticationTokenException", MISSING_AUTHENTICATION_TOKEN, 403),
- CborErrorResponses.mediaTypeFor(requestContentType));
+ return protocolError(protocol, ctx, "MissingAuthenticationToken", "MissingAuthenticationTokenException",
+ MISSING_AUTHENTICATION_TOKEN, 403);
+ }
+
+ private static WireProtocol claimedProtocol(ContainerRequestContext ctx) {
+ return ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim
+ ? claim.protocol() : WireProtocol.REST;
+ }
+
+ /**
+ * An authentication failure outside S3, in the shape the caller's protocol reads: a Query
+ * {@code ErrorResponse} for a form-encoded request, the request's own encoding for a CBOR
+ * call, and JSON otherwise. Query names some failures without the {@code Exception} suffix, and
+ * some differently altogether, so it takes its own code.
+ */
+ private static Response protocolError(WireProtocol protocol, ContainerRequestContext ctx, String queryCode,
+ String code, String message, int status) {
+ if (isCbor(protocol)) {
+ return cborError(ctx, code, message, status);
}
if (isFormEncoded(ctx.getMediaType())) {
- return queryXmlError("MissingAuthenticationToken", MISSING_AUTHENTICATION_TOKEN);
+ return queryXmlError(queryCode, message, status);
+ }
+ return jsonError(code, message, status);
+ }
+
+ private static boolean isCbor(WireProtocol protocol) {
+ return protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET;
+ }
+
+ /**
+ * A CBOR client cannot read a JSON body, so a rejection has to arrive in the encoding the
+ * request used, the same shape the rpcv2 controller returns for its own errors.
+ */
+ private static Response cborError(ContainerRequestContext ctx, String code, String message, int status) {
+ String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER);
+ if (requestContentType == null) {
+ requestContentType = ctx.getHeaderString("Content-Type");
}
- String body = "{\"__type\":\"MissingAuthenticationTokenException\",\"message\":\""
- + MISSING_AUTHENTICATION_TOKEN + "\"}";
- return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build();
+ return CborErrorResponses.of(new AwsException(code, message, status),
+ CborErrorResponses.mediaTypeFor(requestContentType));
}
private static Response jsonAccessDenied(String message, int status) {
- String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}";
- return Response.status(status).type(MediaType.APPLICATION_JSON).entity(body).build();
+ return jsonError("AccessDeniedException", message, status);
+ }
+
+ /** A JSON error in the shape {@link AwsExceptionMapper} gives every other JSON failure. */
+ private static Response jsonError(String code, String message, int status) {
+ return Response.status(status).type(MediaType.APPLICATION_JSON)
+ .entity(new AwsErrorResponse(code, message)).build();
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 84eef44d6b..62d36dbd68 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -4416,6 +4416,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* <p>Returns {@code null} if the access key is unknown (bypass — backward-compatible).
*/
public CallerContext resolveCallerContext(String accessKeyId) {
+ return resolveCallerContext(accessKeyId, Instant.now());
+ }
+
+ /**
+ * {@link #resolveCallerContext(String)} as of {@code now}. Enforcement passes the moment it
+ * asked {@link #isExpiredSession} about, so a session that expires between the two calls is
+ * neither deleted here nor then answered as a key that exists nowhere.
+ */
+ public CallerContext resolveCallerContext(String accessKeyId, Instant now) {
// Check user access keys
Optional<AccessKey> akOpt = accessKeys.get(accessKeyId);
if (akOpt.isPresent()) {
@@ -4430,7 +4439,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isPresent()) {
SessionCredential session = sessionOpt.get();
- if (session.getExpiration() != null && session.getExpiration().isBefore(Instant.now())) {
+ if (session.getExpiration() != null && session.getExpiration().isBefore(now)) {
deleteSession(accessKeyId, session);
return null; // expired — unknown key → bypass
}
@@ -4465,6 +4474,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* an unauthenticated caller, so enforcement needs to tell them apart. The lookup spans every
* account deliberately: a key belonging to another account is a real credential, and denying
* it here would be a false rejection rather than a closed hole.
+ *
+ * <p>An inactive key counts too. {@link #registerIssuedSession} relies on that, so a session
+ * minted with an inactive key has no issuer rather than acting as the account root, and
+ * enforcement refuses the key itself through {@link #isInactiveAccessKey}.
*/
public boolean isKnownAccessKey(String accessKeyId) {
if (accessKeyId == null || accessKeyId.isBlank()) {
@@ -4480,6 +4493,43 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
&& !aware.scanAllAccountEntries(accessKeyId::equals).isEmpty();
}
+ /**
+ * True when this is an IAM user's long-term access key, in any account, that is not Active. An
+ * inactive key can't be used for API calls (IAM User Guide, "Manage access keys for IAM
+ * users"), so enforcement refuses it as it refuses a key that exists nowhere, rather than
+ * letting {@link #isKnownAccessKey}, which counts it as a credential, wave it through.
+ */
+ public boolean isInactiveAccessKey(String accessKeyId) {
+ if (accessKeyId == null || accessKeyId.isBlank() || isTemporaryAccessKey(accessKeyId)) {
+ return false;
+ }
+ // Routing sends an active key to its own account, so the usual case is answered here
+ // without scanning the others. An inactive key lands in the default account instead.
+ Optional<AccessKey> routed = accessKeys.get(accessKeyId);
+ if (routed.isPresent()) {
+ return !"Active".equals(routed.get().getStatus());
+ }
+ return accessKeys instanceof AccountAwareStorageBackend<AccessKey> aware
+ && aware.scanAllAccountEntries(accessKeyId::equals).stream()
+ .anyMatch(entry -> !"Active".equals(entry.value().getStatus()));
+ }
+
+ /**
+ * True when this temporary access key belongs to a session that had expired by {@code now} but
+ * is still stored. AWS answers its use with {@code ExpiredTokenException} rather than as a key
+ * it does not know, so enforcement asks before {@link #resolveCallerContext(String, Instant)},
+ * which deletes such a session and leaves nothing to tell the two apart.
+ */
+ public boolean isExpiredSession(String accessKeyId, Instant now) {
+ if (!isTemporaryAccessKey(accessKeyId)) {
+ return false;
+ }
+ return findSessionForCallerContext(accessKeyId)
+ .map(SessionCredential::getExpiration)
+ .filter(expiration -> expiration.isBefore(now))
+ .isPresent();
+ }
+
private Optional<SessionCredential> findSessionForCallerContext(String accessKeyId) {
if (accessKeyId == null || accessKeyId.isBlank()) {
return Optional.empty();
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
index 70a19c260d..c3b67e5285 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
@@ -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":"*"}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/CborAccessDeniedEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/CborAccessDeniedEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..bda0b94c01
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/CborAccessDeniedEnforcementIntegrationTest.java
@@ -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";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ExpiredSessionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ExpiredSessionEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..9613f1c36b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ExpiredSessionEnforcementIntegrationTest.java
@@ -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";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index 129e71e27b..89041f313d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -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
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/InactiveAccessKeyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/InactiveAccessKeyEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..8db9f9debc
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/InactiveAccessKeyEnforcementIntegrationTest.java
@@ -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";
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java
index 6a5f7798ee..a32a633423 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java
@@ -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()
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/UnreadableCredentialEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/UnreadableCredentialEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..bd32bcd88b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/UnreadableCredentialEnforcementIntegrationTest.java
@@ -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);
+ }
+}