fix(signin): preserve AWS token error modes (#2554)

This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-25 23:38:18 -05:00
1 parent 4083d0667d
commit 399bf20387
11 files changed
+560 -52

No files matched your search

@@ -17,6 +17,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -74,7 +75,7 @@ class SigninIntegrationTest {
}
@Test
void malformedTokenJsonUsesSigninErrorEnvelope() {
void malformedTokenJsonUsesOauthErrorEnvelope() {
request()
.contentType("application/json")
.body("{")
@@ -82,9 +83,99 @@ class SigninIntegrationTest {
.post("/v1/token")
.then()
.statusCode(400)
.body("error", equalTo("invalid_request"))
.body("message", equalTo("Request body must be valid JSON"))
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", nullValue())
.body("error", equalTo("unsupported_grant_type"))
.body("error_description", equalTo(
"The authorization grant type is not supported by the authorization server."))
.body("$", not(hasKey("message")))
.body("$", not(hasKey("__type")));
String supportedGrantWithTrailingJson = """
{"clientId":"%s","grantType":"authorization_code","code":"bogus",
"redirectUri":"%s","codeVerifier":"%s"}{}
""".formatted(CLIENT_ID, REDIRECT_URI, verifier());
request()
.contentType("application/json")
.body(supportedGrantWithTrailingJson)
.when()
.post("/v1/token")
.then()
.statusCode(400)
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", nullValue())
.body("error", equalTo("unsupported_grant_type"))
.body("error_description", equalTo(
"The authorization grant type is not supported by the authorization server."));
}
@Test
void invalidAuthorizationCodeUsesModeledValidationErrorForJsonAndForm() {
Map<String, String> invalidGrant = Map.of(
"clientId", CLIENT_ID,
"grantType", "authorization_code",
"code", "bogus",
"redirectUri", REDIRECT_URI,
"codeVerifier", verifier());
request()
.contentType("application/json")
.body(invalidGrant)
.when()
.post("/v1/token")
.then()
.statusCode(400)
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", equalTo("ValidationException"))
.body("error", equalTo("INVALID_REQUEST"))
.body("message", equalTo(
"The request is missing a required parameter, includes an invalid parameter value, "
+ "or is otherwise malformed."))
.body("$", not(hasKey("error_description")));
request()
.contentType("application/x-www-form-urlencoded")
.body("client_id=" + CLIENT_ID
+ "&grant_type=authorization_code"
+ "&code=bogus"
+ "&redirect_uri=" + java.net.URLEncoder.encode(REDIRECT_URI, StandardCharsets.UTF_8)
+ "&code_verifier=" + verifier())
.when()
.post("/v1/token")
.then()
.statusCode(400)
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", equalTo("ValidationException"))
.body("error", equalTo("INVALID_REQUEST"));
}
@Test
void unsupportedGrantAndMalformedFormUseOauthErrorEnvelope() {
request()
.contentType("application/json")
.body(Map.of("clientId", CLIENT_ID, "grantType", "unsupported"))
.when()
.post("/v1/token")
.then()
.statusCode(400)
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", nullValue())
.body("error", equalTo("unsupported_grant_type"))
.body("error_description", equalTo(
"The authorization grant type is not supported by the authorization server."));
request()
.contentType("application/x-www-form-urlencoded")
.body("grant_type=%ZZ")
.when()
.post("/v1/token")
.then()
.statusCode(400)
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", nullValue())
.body("error", equalTo("unsupported_grant_type"))
.body("error_description", equalTo(
"The authorization grant type is not supported by the authorization server."));
}
@Test
@@ -131,7 +222,9 @@ class SigninIntegrationTest {
.post("/v1/token")
.then()
.statusCode(400)
.body("error", equalTo("invalid_grant"));
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", equalTo("ValidationException"))
.body("error", equalTo("INVALID_REQUEST"));
}
@Test
@@ -209,7 +302,9 @@ class SigninIntegrationTest {
.post("/v1/token")
.then()
.statusCode(400)
.body("error", equalTo("invalid_grant"));
.header("Cache-Control", equalTo("no-store"))
.header("X-Amzn-ErrorType", equalTo("ValidationException"))
.body("error", equalTo("INVALID_REQUEST"));
}
private String authorize(String verifier, String state) throws Exception {
@@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -72,7 +73,7 @@ class SigninServiceTest {
verify(iam).registerSessionForAccount(eq(ACCOUNT_A), eq(tokens.accessToken().accessKeyId()),
eq(tokens.accessToken().secretAccessKey()),
eq("arn:aws:iam::" + ACCOUNT_A + ":root"), any(), isNull());
assertThrows(SigninException.class, () -> exchangeCode(code, VERIFIER));
assertTokenValidation(() -> exchangeCode(code, VERIFIER));
}
@Test
@@ -126,15 +127,15 @@ class SigninServiceTest {
void validatesModeledTokenAndResourceBoundsBeforeConsumingState() throws Exception {
String code = authorizeCode(VERIFIER);
assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", "x".repeat(513),
assertTokenValidation(() -> service.exchange(CLIENT_ID, "authorization_code", "x".repeat(513),
REDIRECT_URI, VERIFIER, null, null));
assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", code,
assertTokenValidation(() -> service.exchange(CLIENT_ID, "authorization_code", code,
"x".repeat(2049), VERIFIER, null, null));
assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", code,
assertTokenValidation(() -> service.exchange(CLIENT_ID, "authorization_code", code,
REDIRECT_URI, VERIFIER, null, ""));
assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", code,
assertTokenValidation(() -> service.exchange(CLIENT_ID, "authorization_code", code,
REDIRECT_URI, VERIFIER, null, "r".repeat(2049)));
assertInvalidRequest(() -> service.exchange(CLIENT_ID, "refresh_token", null,
assertTokenValidation(() -> service.exchange(CLIENT_ID, "refresh_token", null,
null, null, "r".repeat(2049), null));
assertInvalidRequest(() -> service.authorize(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256",
REDIRECT_URI, "code", "openid", "state", ""));
@@ -151,20 +152,42 @@ class SigninServiceTest {
String code = authorizeCode(VERIFIER);
clock.advance(Duration.ofMinutes(5));
SigninException error = assertThrows(SigninException.class,
() -> exchangeCode(code, VERIFIER));
assertAuthorizationCodeExpired(code);
}
assertEquals("invalid_grant", error.error());
@Test
void authorizationCodeExpiryRemainsModeledAfterUnrelatedCleanup() throws Exception {
String code = authorizeCode(VERIFIER);
clock.advance(Duration.ofMinutes(5));
authorizeCode(VERIFIER);
assertAuthorizationCodeExpired(code);
}
@Test
void authorizationCodeTombstoneCutoffIsCleanupIndependent() throws Exception {
String directAtCutoff = authorizeCode(VERIFIER);
String cleanedAtCutoff = authorizeCode(VERIFIER);
clock.advance(Duration.ofMinutes(20));
assertTokenValidation(() -> exchangeCode(directAtCutoff, VERIFIER));
authorizeCode(VERIFIER);
assertTokenValidation(() -> exchangeCode(cleanedAtCutoff, VERIFIER));
String directAfterCutoff = authorizeCode(VERIFIER);
String cleanedAfterCutoff = authorizeCode(VERIFIER);
clock.advance(Duration.ofMinutes(20).plusSeconds(1));
assertTokenValidation(() -> exchangeCode(directAfterCutoff, VERIFIER));
authorizeCode(VERIFIER);
assertTokenValidation(() -> exchangeCode(cleanedAfterCutoff, VERIFIER));
}
@Test
void rejectsPkceMismatchWithoutRegisteringCredentials() throws Exception {
String code = authorizeCode(VERIFIER);
SigninException error = assertThrows(SigninException.class,
() -> exchangeCode(code, VERIFIER + "wrong"));
assertEquals("invalid_grant", error.error());
assertTokenValidation(() -> exchangeCode(code, VERIFIER + "wrong"));
}
@Test
@@ -223,15 +246,53 @@ class SigninServiceTest {
clock.advance(Duration.ofHours(11).plusMinutes(59));
TokenResult rotated = refresh(initial.refreshToken());
clock.advance(Duration.ofMinutes(2));
clock.advance(Duration.ofMinutes(1));
assertInvalidRefresh(rotated.refreshToken());
assertRefreshExpired(rotated.refreshToken());
}
@Test
void refreshExpiryRemainsModeledAfterUnrelatedCleanup() throws Exception {
TokenResult initial = issueInitialTokens();
clock.advance(Duration.ofHours(12));
exchangeCode(authorizeCode(VERIFIER), VERIFIER);
assertRefreshExpired(initial.refreshToken());
}
@Test
void refreshTombstoneCutoffIsCleanupIndependent() throws Exception {
TokenResult directAtCutoff = issueInitialTokens();
TokenResult cleanedAtCutoff = issueInitialTokens();
clock.advance(Duration.ofHours(12).plusMinutes(15));
assertTokenValidation(() -> refresh(directAtCutoff.refreshToken()));
assertTokenValidation(() -> refresh(cleanedAtCutoff.refreshToken()));
TokenResult directAfterCutoff = issueInitialTokens();
TokenResult cleanedAfterCutoff = issueInitialTokens();
clock.advance(Duration.ofHours(12).plusMinutes(15).plusSeconds(1));
assertTokenValidation(() -> refresh(directAfterCutoff.refreshToken()));
assertTokenValidation(() -> refresh(cleanedAfterCutoff.refreshToken()));
}
@Test
void unsupportedGrantUsesOauthErrorMode() {
SigninTokenException error = assertThrows(SigninTokenException.class,
() -> service.exchange(CLIENT_ID, "unsupported", null,
null, null, null, null));
assertEquals("unsupported_grant_type", error.responseError());
assertEquals(SigninTokenException.UNSUPPORTED_GRANT_MESSAGE, error.getMessage());
assertEquals(400, error.getHttpStatus());
assertFalse(error.modeled());
}
@Test
void expiryCleanupWaitsForInFlightRotation() throws Exception {
TokenResult initial = issueInitialTokens();
clock.advance(Duration.ofHours(12).minusMillis(2));
clock.advance(Duration.ofHours(12).minusSeconds(1));
CountDownLatch issuanceStarted = new CountDownLatch(1);
CountDownLatch allowIssuance = new CountDownLatch(1);
doAnswer(ignored -> {
@@ -308,15 +369,27 @@ class SigninServiceTest {
private void assertInvalidVerifier(String verifier) throws Exception {
String code = authorizeCode(verifier);
SigninException error = assertThrows(SigninException.class,
() -> exchangeCode(code, verifier));
assertEquals("invalid_request", error.error());
assertTokenValidation(() -> exchangeCode(code, verifier));
}
private void assertInvalidRefresh(String refreshToken) {
SigninException error = assertThrows(SigninException.class,
assertTokenValidation(() -> refresh(refreshToken));
}
private void assertRefreshExpired(String refreshToken) {
SigninTokenException error = assertThrows(SigninTokenException.class,
() -> refresh(refreshToken));
assertEquals("invalid_grant", error.error());
assertEquals("AccessDeniedException", error.getErrorCode());
assertEquals("TOKEN_EXPIRED", error.responseError());
assertEquals(401, error.getHttpStatus());
}
private void assertAuthorizationCodeExpired(String code) {
SigninTokenException error = assertThrows(SigninTokenException.class,
() -> exchangeCode(code, VERIFIER));
assertEquals("AccessDeniedException", error.getErrorCode());
assertEquals("AUTHCODE_EXPIRED", error.responseError());
assertEquals(401, error.getHttpStatus());
}
private void assertInvalidRequest(org.junit.jupiter.api.function.Executable request) {
@@ -324,6 +397,13 @@ class SigninServiceTest {
assertEquals("invalid_request", error.error());
}
private void assertTokenValidation(org.junit.jupiter.api.function.Executable request) {
SigninTokenException error = assertThrows(SigninTokenException.class, request);
assertEquals("ValidationException", error.getErrorCode());
assertEquals("INVALID_REQUEST", error.responseError());
assertEquals(400, error.getHttpStatus());
}
private static String challengeUnchecked(String verifier) {
try {
return challenge(verifier);
@@ -0,0 +1,55 @@
package io.github.hectorvent.floci.services.signin;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
class SigninTokenExceptionMapperTest {
private final SigninTokenExceptionMapper mapper = new SigninTokenExceptionMapper();
@Test
void modeledValidationUsesAwsErrorHeaderAndBody() {
Response response = mapper.toResponse(SigninTokenException.validation());
assertEquals(400, response.getStatus());
assertEquals("no-store", response.getHeaderString("Cache-Control"));
assertEquals("ValidationException", response.getHeaderString("X-Amzn-ErrorType"));
assertEquals(Map.of(
"error", "INVALID_REQUEST",
"message", SigninTokenException.INVALID_REQUEST_MESSAGE), response.getEntity());
}
@Test
void modeledExpiryUsesAccessDeniedStatusAndErrorCode() {
Response response = mapper.toResponse(SigninTokenException.refreshTokenExpired());
assertEquals(401, response.getStatus());
assertEquals("no-store", response.getHeaderString("Cache-Control"));
assertEquals("AccessDeniedException", response.getHeaderString("X-Amzn-ErrorType"));
@SuppressWarnings("unchecked")
Map<String, String> body = (Map<String, String>) response.getEntity();
assertEquals("TOKEN_EXPIRED", body.get("error"));
assertEquals("The refresh token is invalid or expired", body.get("message"));
assertFalse(body.containsKey("error_description"));
}
@Test
void oauthErrorUsesDescriptionWithoutAwsErrorHeader() {
Response response = mapper.toResponse(SigninTokenException.unsupportedGrant());
assertEquals(400, response.getStatus());
assertEquals("no-store", response.getHeaderString("Cache-Control"));
assertNull(response.getHeaderString("X-Amzn-ErrorType"));
@SuppressWarnings("unchecked")
Map<String, String> body = (Map<String, String>) response.getEntity();
assertEquals("unsupported_grant_type", body.get("error"));
assertEquals(SigninTokenException.UNSUPPORTED_GRANT_MESSAGE, body.get("error_description"));
assertFalse(body.containsKey("message"));
}
}