Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(iam): reject an access key that exists nowhere under enforcement (#4182)

Priamo Germosend30a744b66f0
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 19d22d30d4..75b7ecc48d 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -455,8 +455,7 @@ floci:
SCP semantics match AWS: SCPs never grant permissions — they cap what identity policies
may allow; the organization's **management account is exempt**; and an account outside
-any organization is unaffected. The `test` credential and unknown access keys are never
-SCP-denied.
+any organization is unaffected. The `test` credential is never SCP-denied.
**The account-root principal is subject to SCPs.** floci's account root is a bare
12-digit account-id access key (the LocalStack multi-account convention). It carries no
@@ -468,8 +467,8 @@ allow-everything root identity and evaluates the request against the SCP chain.
case **SCPs apply and nothing else does** — no identity policies, permission boundary, or
session policy attaches to the bare account key. If the account has no effective SCP
ceiling (the management account, an account outside any organization, or the SCP type
-disabled), the bare key still bypasses enforcement entirely, and unknown `AKIA…` keys
-always bypass unconditionally.
+disabled), the bare key still bypasses enforcement entirely. An `AKIA…` key that exists
+nowhere is rejected rather than bypassed.
### Bypass rules
@@ -478,7 +477,8 @@ These identities always bypass enforcement (backward-compatible defaults):
| Identity | Behaviour |
|---|---|
| Access key `test` (the default dev credential) | Always allowed — no policy lookup |
-| Unknown access key (not in IAM store) | Always allowed — backward-compatible with pre-existing keys |
+| Access key that exists nowhere | **Rejected** with `403`: `InvalidAccessKeyId` for S3, `InvalidClientTokenId` for Query services, `UnrecognizedClientException` for JSON services |
+| 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) |
| Unresolvable IAM action for the request | Allowed — unknown mappings are permissive |
@@ -659,7 +659,8 @@ the emulator cannot reason about:
| --- | --- |
| Unresolvable action | Allowed. An action the registry cannot resolve is not evaluated. |
| `sts:GetCallerIdentity` | Always allowed — AWS returns caller identity even when a policy denies it. |
-| Unknown access key | Allowed. A key that resolves to no IAM identity bypasses enforcement. |
+| 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. |
+| 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 df254dcfc2..ea64e7d327 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
@@ -41,7 +41,8 @@ import java.util.regex.Pattern;
* <ul>
* <li>Enforcement is disabled (default)</li>
* <li>Access key is {@code "test"} (root/admin stand-in)</li>
- * <li>Access key is not found in the IAM store (backward-compatible with pre-existing credentials)</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>
* <li>The action cannot be resolved (unknown mapping → permissive)</li>
* <li>The action is {@code sts:GetCallerIdentity}, which AWS allows without permissions</li>
* </ul>
@@ -65,6 +66,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private static final Pattern SERVICE_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
+ /** 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.";
+
/**
* Implicit identity policy for the account-root principal: full access, bounded only by SCPs.
* The account root is not a registered IAM identity, so it has no stored identity policy.
@@ -195,13 +199,24 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
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; otherwise
- // preserve the historical unknown-key bypass.
- if (scpLevels == null || !akid.equals(accountId)) {
- return; // unknown access key or no SCP ceiling → bypass (backward-compat)
+ // 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)) {
+ // A real credential this filter cannot map to policies, such as a session with no
+ // role ARN. Denying it would reject an authenticated caller, so it stays allowed.
+ 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;
}
- caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
- accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
@@ -392,6 +407,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid);
if (caller == null) {
+ // No unknown-key rejection here, unlike filter(): this path runs only for a
+ // presigned POST, whose form signature S3PostPolicySigner has already verified
+ // against the key's secret, so an unknown key never reaches it.
if (scpLevels == null || !akid.equals(accountId)) {
return;
}
@@ -633,11 +651,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
private static Response queryXmlAccessDenied(String message) {
+ return queryXmlError("AccessDenied", message);
+ }
+
+ private static Response queryXmlError(String code, String message) {
String xml = new XmlBuilder()
.start("ErrorResponse")
.start("Error")
.elem("Type", "Sender")
- .elem("Code", "AccessDenied")
+ .elem("Code", code)
.elem("Message", message)
.end("Error")
.elem("RequestId", UUID.randomUUID().toString())
@@ -650,11 +672,19 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return s3XmlAccessDenied(message, null);
}
+ private static Response s3XmlError(String code, String message) {
+ return s3Xml(code, message, null);
+ }
+
private static Response s3XmlAccessDenied(String message, String resourcePath) {
+ return s3Xml("AccessDenied", message, resourcePath);
+ }
+
+ private static Response s3Xml(String code, String message, String resourcePath) {
XmlBuilder xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("Error")
- .elem("Code", "AccessDenied")
+ .elem("Code", code)
.elem("Message", message);
if (resourcePath != null && !resourcePath.isBlank()) {
xml.elem("Resource", resourcePath);
@@ -664,6 +694,28 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml.build()).build();
}
+ /**
+ * The response for an access key that exists nowhere, in each protocol's own vocabulary for
+ * the same failure. S3 answers with {@code InvalidAccessKeyId}, as
+ * {@code S3HeaderSignatureFilter} already does. Query services answer with
+ * {@code InvalidClientTokenId}: neither code is modelled by sts, iam or sqs, but botocore's
+ * own integration tests retry on {@code InvalidClientTokenId} from {@code sts:AssumeRole} and
+ * {@code iam:ListGroups} while credentials propagate. JSON services answer with
+ * {@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) {
+ if ("s3".equals(credentialScope)) {
+ return s3XmlError("InvalidAccessKeyId",
+ "The AWS Access Key Id you provided does not exist in our records.");
+ }
+ if (isFormEncoded(requestMediaType)) {
+ return queryXmlError("InvalidClientTokenId", INVALID_SECURITY_TOKEN);
+ }
+ String body = "{\"__type\":\"UnrecognizedClientException\",\"message\":\"" + INVALID_SECURITY_TOKEN + "\"}";
+ return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).build();
+ }
+
private static Response jsonAccessDenied(String message) {
String body = "{\"__type\":\"AccessDeniedException\",\"message\":\"" + message + "\"}";
return Response.status(403).type(MediaType.APPLICATION_JSON).entity(body).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 0ec9c4552b..bf76e145c9 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
@@ -2439,6 +2439,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return null;
}
+ /**
+ * True when this access key exists anywhere in the emulator: an IAM user's long-term key in
+ * any account, or a session credential.
+ *
+ * <p>{@link #resolveCallerContext} returns null both for a key that does not exist and for a
+ * key it cannot map to policies (a session carrying no role ARN). Only the first of those is
+ * 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.
+ */
+ public boolean isKnownAccessKey(String accessKeyId) {
+ if (accessKeyId == null || accessKeyId.isBlank()) {
+ return false;
+ }
+ if (findSessionForCallerContext(accessKeyId).isPresent()) {
+ return true;
+ }
+ if (accessKeys.get(accessKeyId).isPresent()) {
+ return true;
+ }
+ return accessKeys instanceof AccountAwareStorageBackend<AccessKey> aware
+ && !aware.scanAllAccountEntries(accessKeyId::equals).isEmpty();
+ }
+
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 4e7f953f23..cbc7a391b3 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
@@ -38,6 +38,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
@@ -141,6 +142,108 @@ class IamEnforcementFilterTest {
verify(arnBuilder).buildResources("lambda", containerRequest, "us-east-1", "222233334444");
}
+ @Test
+ void unknownAccessKeyIsRejectedInsteadOfBypassingEnforcement() {
+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
+ String auth = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260629/us-east-1/lambda/aws4_request, "
+ + "SignedHeaders=host, Signature=garbage";
+ requestContext.setAccountId("000000000000");
+ 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.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
+
+ newFilter().filter(containerRequest);
+
+ ArgumentCaptor<Response> response = ArgumentCaptor.captor();
+ verify(containerRequest).abortWith(response.capture());
+ assertEquals(403, response.getValue().getStatus());
+ assertTrue(response.getValue().getEntity().toString().contains("UnrecognizedClientException"),
+ response.getValue().getEntity().toString());
+ verifyNoInteractions(evaluator);
+ }
+
+ @Test
+ void unknownAccessKeyOnAnS3RequestIsRejectedWithTheS3ErrorCode() {
+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
+ String auth = "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260629/us-east-1/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=garbage";
+ requestContext.setAccountId("000000000000");
+ 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.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
+
+ newFilter().filter(containerRequest);
+
+ ArgumentCaptor<Response> response = ArgumentCaptor.captor();
+ verify(containerRequest).abortWith(response.capture());
+ assertEquals(403, response.getValue().getStatus());
+ assertTrue(response.getValue().getEntity().toString().contains("InvalidAccessKeyId"),
+ response.getValue().getEntity().toString());
+ }
+
+ @Test
+ void unknownAccessKeyOnAQueryRequestIsRejectedWithTheQueryErrorCode() {
+ 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:AssumeRole");
+ when(iamService.resolveCallerContext("AKIADOESNOTEXIST0000")).thenReturn(null);
+ when(iamService.isKnownAccessKey("AKIADOESNOTEXIST0000")).thenReturn(false);
+
+ newFilter().filter(containerRequest);
+
+ ArgumentCaptor<Response> response = ArgumentCaptor.captor();
+ verify(containerRequest).abortWith(response.capture());
+ assertEquals(403, response.getValue().getStatus());
+ // Query services answer an unrecognised credential with InvalidClientTokenId, not the
+ // JSON services' UnrecognizedClientException.
+ assertTrue(response.getValue().getEntity().toString().contains("InvalidClientTokenId"),
+ response.getValue().getEntity().toString());
+ }
+
+ @Test
+ void aKnownCredentialWithoutAMappableCallerContextStillPassesThrough() {
+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
+ String auth = "AWS4-HMAC-SHA256 Credential=ASIAIDENTITYSESSION/20260629/us-east-1/lambda/aws4_request, "
+ + "SignedHeaders=host, Signature=abc";
+ requestContext.setAccountId("000000000000");
+ 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.isKnownAccessKey("ASIAIDENTITYSESSION")).thenReturn(true);
+
+ newFilter().filter(containerRequest);
+
+ verify(containerRequest, never()).abortWith(any());
+ verifyNoInteractions(evaluator);
+ }
+
+ @Test
+ void bareAccountIdKeyWithNoScpCeilingStillPassesThrough() {
+ ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
+ String auth = "AWS4-HMAC-SHA256 Credential=000000000000/20260629/us-east-1/lambda/aws4_request, "
+ + "SignedHeaders=host, Signature=abc";
+ requestContext.setAccountId("000000000000");
+ 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);
+
+ newFilter().filter(containerRequest);
+
+ verify(containerRequest, never()).abortWith(any());
+ verify(iamService, never()).isKnownAccessKey(any());
+ }
+
@Test
void filterBuildsResourceArnForDynamoDbTable() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
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
new file mode 100644
index 0000000000..8b12923592
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/UnknownAccessKeyEnforcementIntegrationTest.java
@@ -0,0 +1,56 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+
+/**
+ * With enforcement on, an access key that exists nowhere must be rejected rather than waved
+ * through. Before this was closed, any string in the credential scope authorized the request.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class UnknownAccessKeyEnforcementIntegrationTest {
+
+ private static final String UNKNOWN_KEY_AUTH =
+ "AWS4-HMAC-SHA256 Credential=AKIADOESNOTEXIST0000/20260101/us-east-1/%s/aws4_request, "
+ + "SignedHeaders=host, Signature=not-a-real-signature";
+
+ @Test
+ void jsonServiceRejectsAnUnknownAccessKey() {
+ given()
+ .header("Authorization", UNKNOWN_KEY_AUTH.formatted("lambda"))
+ .contentType("application/json")
+ .when()
+ .get("/2015-03-31/functions")
+ .then()
+ .statusCode(403)
+ .body(containsString("UnrecognizedClientException"));
+ }
+
+ @Test
+ void s3RejectsAnUnknownAccessKeyWithTheS3ErrorCode() {
+ given()
+ .header("Authorization", UNKNOWN_KEY_AUTH.formatted("s3"))
+ .when()
+ .get("/")
+ .then()
+ .statusCode(403)
+ .body(containsString("InvalidAccessKeyId"));
+ }
+
+ @Test
+ void theRootStandInKeyStillWorks() {
+ given()
+ .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/s3/aws4_request, "
+ + "SignedHeaders=host, Signature=whatever")
+ .when()
+ .get("/")
+ .then()
+ .statusCode(200);
+ }
+}