fix(apigateway): refuse a long-term access key sent with a session token (#5875)

* fix(apigateway): refuse a long-term access key sent with a session token

AWS answers 403 "The security token included in the request is invalid"
when a long-term key comes with X-Amz-Security-Token, signed or not. The
same message without the period answers a temporary key with a wrong token.

The session token check moves to core.common.auth, and Lambda Web IamAuth
uses it too.

Closes #5858

* fix(apigateway): read the session token where the signature is and refuse an empty one

AWS ignores a token in the query of a header-signed request and a token
header on a presigned one. It refuses an empty token with any key.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-17 09:30:35 -04:00
1 parent 9705b2584d
commit 4f4db89d8f
9 files changed
+196 -58

No files matched your search

+7 -4
View File
@@ -226,10 +226,12 @@ placements AWS accepts are honoured: an `Authorization` header and a presigned q
(`X-Amz-Algorithm=AWS4-HMAC-SHA256`). The credential must be scoped to the `execute-api` service.
Temporary credentials must also present the session token they were issued with, as
`X-Amz-Security-Token` (a header, or a query parameter on a presigned request). The token is
`X-Amz-Security-Token` (a header, or a query parameter on a presigned request). As on AWS, the
token is read only from where the signature is, and an empty one counts as sent. The token is
compared against the value recorded when STS minted the credential, so a missing or fabricated one
is rejected: the secret alone is not the whole credential. Whether the token is covered by
`SignedHeaders` is not required either way, since SigV4 leaves that service-specific.
is rejected: the secret alone is not the whole credential. A long-term key must come with no
token, as on AWS. Whether the token is covered by `SignedHeaders` is not required either way, since
SigV4 leaves that service-specific.
Rejections are `403`, and never reach the integration:
@@ -238,7 +240,8 @@ Rejections are `403`, and never reach the integration:
| No SigV4 credentials at all | `Missing Authentication Token` / `MissingAuthenticationTokenException` | `Forbidden` |
| Credentials present but incomplete, or scoped to another service | `Incomplete Signature` / `IncompleteSignatureException` | `Forbidden` |
| Access key the emulator never issued | `The security token included in the request is invalid.` / `UnrecognizedClientException` | `Forbidden` |
| Temporary credential presenting no `X-Amz-Security-Token`, or one that is not the token it was issued | `The security token included in the request is invalid.` / `UnrecognizedClientException` | `Forbidden` |
| Temporary credential presenting no `X-Amz-Security-Token`, or an empty one with any key | `The security token included in the request is invalid.` / `UnrecognizedClientException` | `Forbidden` |
| `X-Amz-Security-Token` that is not the token the key was issued with, or any token with a long-term key | `The security token included in the request is invalid` / `UnrecognizedClientException` | `Forbidden` |
| `X-Amz-Date` outside the 5-minute window, or a presigned URL past `X-Amz-Expires` | `Signature expired` / `InvalidSignatureException` | `Forbidden` |
| Signature mismatch | `The request signature we calculated does not match…` / `InvalidSignatureException` | `Forbidden` |
@@ -0,0 +1,40 @@
package io.github.hectorvent.floci.core.common.auth;
import io.github.hectorvent.floci.services.iam.IamService;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
/**
* Whether the session token on a SigV4 request fits the access key that signed it. A temporary key
* needs the token it was issued with, and a long-term key must come without one, as on AWS. The
* token counts whether it is inside the signature or not, and an empty one counts too.
*/
public enum SessionTokenCheck {
VALID,
/** A temporary key with no token, or an empty token with any key. */
MISSING,
/** A token that was not issued with the key, or any token with a long-term key. */
INVALID;
/** {@code sessionToken} is null when the request carries none. */
public static SessionTokenCheck of(IamService iamService, String accessKeyId, String sessionToken) {
boolean temporary = IamService.isTemporaryAccessKey(accessKeyId);
if (sessionToken == null) {
return temporary ? MISSING : VALID;
}
if (sessionToken.isBlank()) {
return MISSING;
}
if (!temporary) {
return INVALID;
}
String issued = iamService.findSessionToken(accessKeyId).orElse(null);
// A session stored before Floci recorded tokens has none to compare.
if (issued == null || MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8),
sessionToken.getBytes(StandardCharsets.UTF_8))) {
return VALID;
}
return INVALID;
}
}
@@ -2996,6 +2996,9 @@ public class ApiGatewayExecuteController {
"Incomplete Signature", GatewayResponseType.INVALID_SIGNATURE);
case UNKNOWN_KEY -> new RestIamError("UnrecognizedClientException",
"The security token included in the request is invalid.", GatewayResponseType.ACCESS_DENIED);
// AWS drops the period when a session token came and does not fit the key.
case INVALID_TOKEN -> new RestIamError("UnrecognizedClientException",
"The security token included in the request is invalid", GatewayResponseType.ACCESS_DENIED);
case EXPIRED -> new RestIamError("InvalidSignatureException",
"Signature expired", GatewayResponseType.EXPIRED_TOKEN);
case MISMATCH -> new RestIamError("InvalidSignatureException",
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
import io.github.hectorvent.floci.core.common.auth.SessionTokenCheck;
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest;
@@ -16,8 +17,6 @@ import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
/**
@@ -31,8 +30,8 @@ import java.time.Instant;
* string, the headers named in {@code SignedHeaders}, and the SHA-256 of the body), and the derived
* signature is compared in constant time.
*
* <p>A temporary credential must additionally present the session token it was issued with, which
* is checked by {@link #checkSessionToken}.
* <p>A temporary credential must also present the session token it was issued with, and a long-term
* one must present none. {@link #checkSessionToken} checks this.
*
* <h2>Deliberate deviations from real AWS</h2>
* <ul>
@@ -77,6 +76,8 @@ public class ExecuteApiSigV4Authorizer {
MALFORMED,
/** The credential names an access key this emulator has never issued. */
UNKNOWN_KEY,
/** A session token came that was not issued with the access key. */
INVALID_TOKEN,
/** The signing timestamp is outside the accepted window, or a presigned URL has expired. */
EXPIRED,
/** The signature does not match the one derived from the caller's secret key. */
@@ -164,7 +165,9 @@ public class ExecuteApiSigV4Authorizer {
return Result.rejected(Failure.UNKNOWN_KEY, "access key is not registered");
}
Result sessionToken = checkSessionToken(scope.accessKeyId(), headers, queryParameters);
Result sessionToken = checkSessionToken(scope.accessKeyId(), presigned
? queryParameters.getFirst(SECURITY_TOKEN)
: headers == null ? null : headers.getHeaderString(SECURITY_TOKEN));
if (sessionToken != null) {
return sessionToken;
}
@@ -242,50 +245,19 @@ public class ExecuteApiSigV4Authorizer {
}
/**
* Rejects a temporary credential that does not present the session token Floci issued with it,
* returning {@code null} when there is nothing to object to.
*
* <p>The secret alone is not the whole credential. AWS requires the session token on every
* request made with temporary credentials precisely because it is what confirms the credential
* is live and genuinely STS-issued, so accepting an {@code ASIA...} key on its secret alone
* lets an incomplete credential through a route that is supposed to demand a complete one.
*
* <p>The token is compared against the value recorded at mint time rather than merely required
* to be present, so a fabricated token fails as well as a missing one. Presence is all that can
* be demanded of a session stored before Floci recorded tokens: {@code findSessionToken} is
* empty there, and rejecting it would lock out a credential that is otherwise perfectly valid.
* {@code findSecretKey(accessKeyId, sessionToken)} is the stricter one-step alternative, which
* this deliberately does not use because it cannot tell that case apart from a real mismatch.
*
* <p>Folding the token into the canonical request is deliberately not required. Whether a
* service covers it by {@code SignedHeaders} or appends it after signing is service-specific in
* SigV4, and comparing against the issued value binds the token regardless of where it rode.
* Rejects a session token that does not fit the access key, returning {@code null} when there
* is nothing to object to. AWS reads the token from where the signature is, the header or the
* presigned query, and ignores it in the other place.
*/
private Result checkSessionToken(String accessKeyId, HttpHeaders headers,
MultivaluedMap<String, String> queryParameters) {
if (!IamService.isTemporaryAccessKey(accessKeyId)) {
private Result checkSessionToken(String accessKeyId, String presented) {
if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {
return null;
}
String presented = queryParameters.getFirst(SECURITY_TOKEN);
if (isBlank(presented) && headers != null) {
presented = headers.getHeaderString(SECURITY_TOKEN);
}
if (isBlank(presented)) {
LOG.debugv("execute-api request uses temporary credential accessKey={0} with no {1}",
SigV4RequestValidator.sanitizeForLog(accessKeyId), SECURITY_TOKEN);
return Result.rejected(Failure.UNKNOWN_KEY, "temporary credential presents no session token");
}
String issued = iamService.findSessionToken(accessKeyId).orElse(null);
if (issued == null) {
return null;
}
if (!MessageDigest.isEqual(issued.getBytes(StandardCharsets.UTF_8),
presented.getBytes(StandardCharsets.UTF_8))) {
LOG.debugv("execute-api request presents a session token that does not match the one"
+ " issued for accessKey={0}", SigV4RequestValidator.sanitizeForLog(accessKeyId));
return Result.rejected(Failure.UNKNOWN_KEY, "session token does not match the issued credential");
}
return null;
return switch (SessionTokenCheck.of(iamService, accessKeyId, presented)) {
case VALID -> null;
case MISSING -> Result.rejected(Failure.UNKNOWN_KEY, "session token is missing or empty");
case INVALID -> Result.rejected(Failure.INVALID_TOKEN, "session token was not issued with the access key");
};
}
/**
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.auth.CredentialScope;
import io.github.hectorvent.floci.core.common.auth.SessionTokenCheck;
import io.github.hectorvent.floci.core.common.auth.SigV4Canonicalization;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest;
@@ -171,16 +172,14 @@ public class LambdaWebIamAuth {
}
/**
* The secret of a key Floci issued. A temporary key needs its session token, and a long-term
* key with a session token is refused, as on AWS. The local {@code test} key signs with
* {@code test}.
* The secret of a key Floci issued, when the session token fits it. The local {@code test} key
* signs with {@code test}.
*/
private String secretKey(String accessKeyId, String sessionToken) {
if (TEST_ACCESS_KEY.equals(accessKeyId)) {
return TEST_ACCESS_KEY;
}
boolean temporary = IamService.isTemporaryAccessKey(accessKeyId);
if (temporary && isBlank(sessionToken) || !temporary && !isBlank(sessionToken)) {
if (SessionTokenCheck.of(iamService, accessKeyId, sessionToken) != SessionTokenCheck.VALID) {
return null;
}
return iamService.findSecretKeyInAnyAccount(accessKeyId, sessionToken)
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.core.common.auth;
import io.github.hectorvent.floci.services.iam.IamService;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SessionTokenCheckTest {
@Test
void aLongTermKeyComesWithoutAToken() {
IamService iam = mock(IamService.class);
assertEquals(SessionTokenCheck.VALID, SessionTokenCheck.of(iam, "AKIAEXAMPLE", null));
assertEquals(SessionTokenCheck.MISSING, SessionTokenCheck.of(iam, "AKIAEXAMPLE", ""));
assertEquals(SessionTokenCheck.INVALID, SessionTokenCheck.of(iam, "AKIAEXAMPLE", "bogus"));
}
@Test
void aTemporaryKeyNeedsTheTokenIssuedWithIt() {
IamService iam = mock(IamService.class);
when(iam.findSessionToken("ASIAEXAMPLE")).thenReturn(Optional.of("issued"));
assertEquals(SessionTokenCheck.MISSING, SessionTokenCheck.of(iam, "ASIAEXAMPLE", null));
assertEquals(SessionTokenCheck.MISSING, SessionTokenCheck.of(iam, "ASIAEXAMPLE", ""));
assertEquals(SessionTokenCheck.VALID, SessionTokenCheck.of(iam, "ASIAEXAMPLE", "issued"));
assertEquals(SessionTokenCheck.INVALID, SessionTokenCheck.of(iam, "ASIAEXAMPLE", "bogus"));
}
@Test
void aSessionWithNoRecordedTokenTakesAnyToken() {
IamService iam = mock(IamService.class);
when(iam.findSessionToken("ASIAOLD")).thenReturn(Optional.empty());
assertEquals(SessionTokenCheck.VALID, SessionTokenCheck.of(iam, "ASIAOLD", "anything"));
assertEquals(SessionTokenCheck.MISSING, SessionTokenCheck.of(iam, "ASIAOLD", null));
}
}
@@ -1,6 +1,10 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
@@ -8,9 +12,12 @@ import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
@@ -39,6 +46,12 @@ class ApiGatewayIamAuthorizationTest {
private static String apiId;
private static String iamResourceId;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@TestHTTPResource("/")
URI baseUri;
@Test
@Order(0)
void setup() {
@@ -159,11 +172,32 @@ class ApiGatewayIamAuthorizationTest {
given().headers(headers)
.when().get(userRequestPath("iam"))
.then().statusCode(403)
.header("x-amzn-ErrorType", "UnrecognizedClientException");
.header("x-amzn-ErrorType", "UnrecognizedClientException")
.body("message", equalTo("The security token included in the request is invalid."));
}
@Test
@Order(16)
void longTermKeyWithASessionTokenIsRejected() throws Exception {
UserCredentials user = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
EnforcementFixtures.auth(ACCESS_KEY, "iam"), "rest-iam-token-user");
Map<String, String> headers = new LinkedHashMap<>(ExecuteApiRequestSigner.signedHeaders(
"GET", userRequestPath("iam"), Map.of(), host(), null,
user.accessKeyId(), user.secretAccessKey(), REGION, Instant.now()));
given().headers(headers)
.when().get(userRequestPath("iam"))
.then().statusCode(200);
headers.put("X-Amz-Security-Token", "bogus");
given().headers(headers)
.when().get(userRequestPath("iam"))
.then().statusCode(403)
.header("x-amzn-ErrorType", "UnrecognizedClientException")
.body("message", equalTo("The security token included in the request is invalid"));
}
@Test
@Order(17)
void methodWithoutIamAuthorizationStillAcceptsUnsignedRequests() {
given().when().get(userRequestPath("open"))
.then().statusCode(200)
@@ -16,6 +16,7 @@ import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
@@ -194,7 +195,7 @@ class ExecuteApiSigV4AuthorizerTest {
ExecuteApiSigV4Authorizer.Result result = authorizer.authorize(
"GET", headers(signed), uriInfo(PATH, null), null, null);
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY, result.failure());
assertEquals(ExecuteApiSigV4Authorizer.Failure.INVALID_TOKEN, result.failure());
}
@Test
@@ -211,11 +212,50 @@ class ExecuteApiSigV4AuthorizerTest {
String forged = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "ASIAPRESIGNED", "session-secret", REGION,
Instant.now(), 900, "forged-session-token");
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY,
assertEquals(ExecuteApiSigV4Authorizer.Failure.INVALID_TOKEN,
authorizer.authorize("GET", headers(Map.of()), uriInfo(PATH, forged), null, null)
.failure());
}
@Test
void longTermKeyWithASessionTokenIsRejectedWhereverTheTokenRides() throws Exception {
when(iamService.findSecretKey("AKIALONGTERM")).thenReturn(Optional.of("s3cr3t"));
when(iamService.resolveAccountId("AKIALONGTERM")).thenReturn(Optional.of("111122223333"));
Map<String, String> signed = new LinkedHashMap<>(ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, Map.of(), HOST, null, "AKIALONGTERM", "s3cr3t", REGION, Instant.now()));
assertTrue(authorizer.authorize("GET", headers(signed), uriInfo(PATH, null), null, null).authorized());
signed.put("X-Amz-Security-Token", "bogus");
assertEquals(ExecuteApiSigV4Authorizer.Failure.INVALID_TOKEN,
authorizer.authorize("GET", headers(signed), uriInfo(PATH, null), null, null).failure());
signed.put("X-Amz-Security-Token", "");
assertEquals(ExecuteApiSigV4Authorizer.Failure.UNKNOWN_KEY,
authorizer.authorize("GET", headers(signed), uriInfo(PATH, null), null, null).failure());
String presigned = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "AKIALONGTERM", "s3cr3t", REGION, Instant.now(), 900, "bogus");
assertEquals(ExecuteApiSigV4Authorizer.Failure.INVALID_TOKEN,
authorizer.authorize("GET", headers(Map.of()), uriInfo(PATH, presigned), null, null).failure());
}
@Test
void theTokenIsReadOnlyFromWhereTheSignatureIs() throws Exception {
when(iamService.findSecretKey("AKIALONGTERM")).thenReturn(Optional.of("s3cr3t"));
when(iamService.resolveAccountId("AKIALONGTERM")).thenReturn(Optional.of("111122223333"));
Map<String, String> query = Map.of("X-Amz-Security-Token", "bogus");
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders(
"GET", PATH, query, HOST, null, "AKIALONGTERM", "s3cr3t", REGION, Instant.now());
assertTrue(authorizer.authorize("GET", headers(signed),
uriInfo(PATH, "X-Amz-Security-Token=bogus"), null, null).authorized());
String presigned = ExecuteApiRequestSigner.presignedQueryString(
"GET", PATH, HOST, "AKIALONGTERM", "s3cr3t", REGION, Instant.now(), 900);
assertTrue(authorizer.authorize("GET", headers(Map.of("X-Amz-Security-Token", "bogus")),
uriInfo(PATH, presigned), null, null).authorized());
}
private void liveSession(String accessKeyId, String issuedToken) {
when(iamService.findSecretKey(accessKeyId)).thenReturn(Optional.of("session-secret"));
when(iamService.resolveAccountId(accessKeyId)).thenReturn(Optional.of("111122223333"));
@@ -151,6 +151,14 @@ class LambdaWebIamAuthTest {
.withHeader("X-Amz-Security-Token", null)));
}
@Test
void theSessionTokenIsReadFromWhereTheSignatureIsAndMayNotBeEmpty() {
LambdaWebRequestSigner longTerm = signer().credentials(USER_KEY, USER_SECRET, null);
assertFalse(allows(longTerm.sign("GET", HOST, "/").withHeader("X-Amz-Security-Token", "")));
assertTrue(allows(longTerm.sign("GET", HOST, "/x?X-Amz-Security-Token=bogus")));
assertTrue(allows(longTerm.presigned().sign("GET", HOST, "/").withHeader("X-Amz-Security-Token", "bogus")));
}
@Test
void aMalformedDateOrQueryIsRefused() {
assertFalse(allows(signer().sign("GET", HOST, "/").withHeader("X-Amz-Date", "20261017T99")));