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; *
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 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 {
* 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.
*
* 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 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 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> 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.
+ *
+ *
> 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 {
*
ExpiredTokenException"),
+ 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);
+
+ ArgumentCaptorExpiredToken"),
+ 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);
+
+ ArgumentCaptorIncompleteSignature"),
+ 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);
+
+ ArgumentCaptorAuthorizationHeaderMalformed"),
+ 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);
+
+ ArgumentCaptorAuthorizationQueryParametersError"),
+ 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);
+
+ ArgumentCaptorAuthorizationHeaderMalformed"),
+ 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);
MultivaluedHashMapExpiredTokenException"));
+ // Asked again, it is still expired rather than gone.
+ getCallerIdentity(accessKeyId)
+ .then().statusCode(403).body(containsString("ExpiredTokenException"));
+ 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("ExpiredToken"));
+ }
+
+ @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("ExpiredToken"));
+ // Refusing it did not delete the session, which would leave the key unknown.
+ getCallerIdentity(accessKeyId)
+ .then().statusCode(403).body(containsString("ExpiredTokenException"));
+ }
+
+ 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() {
+ AccountAwareStorageBackendInvalidAccessKeyId"));
+ 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("InvalidClientTokenId"));
+ }
+
+ @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("IncompleteSignature"));
+
+ 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("AuthorizationHeaderMalformed"));
+ }
+
+ @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("AuthorizationQueryParametersError"));
+ }
+
+ @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);
+ }
+}