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

@@ -1,7 +1,9 @@
package io.github.hectorvent.floci.services.signin;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
import io.github.hectorvent.floci.services.signin.model.TokenResult;
import jakarta.inject.Inject;
@@ -28,12 +30,13 @@ import java.util.Map;
public class SigninController {
private final SigninService signinService;
private final ObjectMapper objectMapper;
private final ObjectReader tokenRequestReader;
@Inject
public SigninController(SigninService signinService, ObjectMapper objectMapper) {
this.signinService = signinService;
this.objectMapper = objectMapper;
this.tokenRequestReader = objectMapper.reader()
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
}
@GET
@@ -97,7 +100,7 @@ public class SigninController {
}
return values;
}
JsonNode root = objectMapper.readTree(body == null ? "" : body);
JsonNode root = tokenRequestReader.readTree(body == null ? "" : body);
if (root != null && root.has("tokenInput")) {
root = root.get("tokenInput");
}
@@ -110,8 +113,8 @@ public class SigninController {
});
}
return values;
} catch (IOException e) {
throw new SigninException("invalid_request", "Request body must be valid JSON");
} catch (IOException | IllegalArgumentException e) {
throw SigninTokenException.unsupportedGrant();
}
}
@@ -3,12 +3,16 @@ package io.github.hectorvent.floci.services.signin;
import io.github.hectorvent.floci.core.common.AwsException;
/** AWS Sign-In error with the service's OAuth wire error code. */
public final class SigninException extends AwsException {
public class SigninException extends AwsException {
public SigninException(String error, String message) {
super(error, message, 400);
}
protected SigninException(String error, String message, int httpStatus) {
super(error, message, httpStatus);
}
public String error() {
return getErrorCode();
}
@@ -38,6 +38,7 @@ public class SigninService {
static final int ACCESS_TOKEN_TTL_SECONDS = 900;
private static final long AUTHORIZATION_CODE_TTL_SECONDS = 300;
private static final long REFRESH_TOKEN_TTL_SECONDS = 12 * 60 * 60;
private static final long EXPIRED_TOKEN_TOMBSTONE_TTL_SECONDS = ACCESS_TOKEN_TTL_SECONDS;
private static final int MAX_AUTHORIZATION_CODE_LENGTH = 512;
private static final int MAX_REDIRECT_URI_LENGTH = 2048;
private static final int MAX_RESOURCE_LENGTH = 2048;
@@ -86,9 +87,9 @@ public class SigninService {
validateOptionalResource(resource);
String accountId = regionResolver.getAccountId();
Instant now = clock.instant();
authorizationCodes.entrySet().removeIf(entry -> !entry.getValue().expiresAt().isAfter(now));
cleanupExpiredAuthorizationCodes(now);
String code = randomToken(32);
authorizationCodes.put(code, new AuthorizationCode(
authorizationCodes.put(code, AuthorizationCode.active(
clientId, codeChallenge, redirectUri, resource, accountId,
now.plusSeconds(AUTHORIZATION_CODE_TTL_SECONDS)));
return appendQuery(redirectUri, "code", code, "state", state);
@@ -96,15 +97,21 @@ public class SigninService {
public TokenResult exchange(String clientId, String grantType, String code, String redirectUri,
String codeVerifier, String refreshToken, String resource) {
validateClient(clientId);
validateOptionalResource(resource);
if ("authorization_code".equals(grantType)) {
return exchangeCode(clientId, code, redirectUri, codeVerifier, resource);
if (!"authorization_code".equals(grantType) && !"refresh_token".equals(grantType)) {
throw SigninTokenException.unsupportedGrant();
}
if ("refresh_token".equals(grantType)) {
try {
validateClient(clientId);
validateOptionalResource(resource);
if ("authorization_code".equals(grantType)) {
return exchangeCode(clientId, code, redirectUri, codeVerifier, resource);
}
return refresh(clientId, refreshToken);
} catch (SigninTokenException e) {
throw e;
} catch (SigninException e) {
throw SigninTokenException.validation();
}
throw new SigninException("invalid_request", "grant_type must be authorization_code or refresh_token");
}
private TokenResult exchangeCode(String clientId, String code, String redirectUri, String codeVerifier,
@@ -120,9 +127,8 @@ public class SigninService {
"code_verifier must be 43-128 characters using the AWS PKCE alphabet");
}
Instant now = clock.instant();
AuthorizationCode authorization = authorizationCodes.remove(code);
if (authorization == null || !authorization.expiresAt().isAfter(now)
|| !clientId.equals(authorization.clientId())
AuthorizationCode authorization = claimAuthorizationCode(code, now);
if (!clientId.equals(authorization.clientId())
|| !redirectUri.equals(authorization.redirectUri())
|| !matchesPkce(authorization.codeChallenge(), codeVerifier)) {
throw new SigninException("invalid_grant", "The authorization code is invalid or expired");
@@ -136,15 +142,26 @@ public class SigninService {
throw new SigninException("invalid_request", "refresh_token must be 1-2048 characters");
}
Instant now = clock.instant();
cleanupExpiredRefreshGrants(now);
RefreshGrant grant = refreshGrants.get(refreshToken);
if (grant == null || !clientId.equals(grant.clientId())) {
cleanupExpiredRefreshGrants(now, refreshToken);
if (grant == null) {
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
rejectExpiredRefreshTombstone(refreshToken, grant, now);
if (!clientId.equals(grant.clientId())) {
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
synchronized (grant) {
if (refreshGrants.get(refreshToken) != grant) {
rejectExpiredRefreshTombstone(refreshToken, refreshGrants.get(refreshToken), now);
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
if (!grant.expiresAt().isAfter(now)) {
if (replaceWithExpiredRefreshTombstone(refreshToken, grant, now)) {
throw SigninTokenException.refreshTokenExpired();
}
throw SigninTokenException.validation();
}
if (grant.replayResult() != null) {
if (grant.replayExpiresAt().isAfter(now)) {
return grant.replayResultWithRemainingLifetime(now);
@@ -152,10 +169,6 @@ public class SigninService {
refreshGrants.remove(refreshToken, grant);
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
if (!grant.expiresAt().isAfter(now)) {
refreshGrants.remove(refreshToken, grant);
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
Instant accessTokenExpiresAt = now.plusSeconds(ACCESS_TOKEN_TTL_SECONDS);
StoredRefreshGrant successor = storeRefreshGrant(
@@ -282,16 +295,99 @@ public class SigninService {
}
}
private AuthorizationCode claimAuthorizationCode(String code, Instant now) {
while (true) {
AuthorizationCode authorization = authorizationCodes.get(code);
if (authorization == null) {
throw new SigninException("invalid_grant", "The authorization code is invalid or expired");
}
if (authorization.expiredTombstone()) {
if (authorization.expiredTombstoneUntil().isAfter(now)) {
throw SigninTokenException.authorizationCodeExpired();
}
if (authorizationCodes.remove(code, authorization)) {
throw new SigninException("invalid_grant", "The authorization code is invalid or expired");
}
continue;
}
if (!authorization.expiresAt().isAfter(now)) {
AuthorizationCode tombstone = authorization.toExpiredTombstone();
if (tombstone.expiredTombstoneUntil().isAfter(now)) {
if (authorizationCodes.replace(code, authorization, tombstone)) {
throw SigninTokenException.authorizationCodeExpired();
}
} else if (authorizationCodes.remove(code, authorization)) {
throw SigninTokenException.validation();
}
continue;
}
if (authorizationCodes.remove(code, authorization)) {
return authorization;
}
}
}
private void cleanupExpiredAuthorizationCodes(Instant now) {
authorizationCodes.forEach((code, authorization) -> {
if (authorization.expiredTombstone()) {
if (!authorization.expiredTombstoneUntil().isAfter(now)) {
authorizationCodes.remove(code, authorization);
}
return;
}
if (!authorization.expiresAt().isAfter(now)) {
AuthorizationCode tombstone = authorization.toExpiredTombstone();
if (tombstone.expiredTombstoneUntil().isAfter(now)) {
authorizationCodes.replace(code, authorization, tombstone);
} else {
authorizationCodes.remove(code, authorization);
}
}
});
}
private void cleanupExpiredRefreshGrants(Instant now) {
cleanupExpiredRefreshGrants(now, null);
}
private void cleanupExpiredRefreshGrants(Instant now, String refreshTokenInUse) {
refreshGrants.forEach((token, grant) -> {
if (token.equals(refreshTokenInUse)) {
return;
}
synchronized (grant) {
if (grant.retentionExpiredAt(now)) {
if (refreshGrants.get(token) != grant || !grant.retentionExpiredAt(now)) {
return;
}
if (!grant.expiredTombstone() && !grant.expiresAt().isAfter(now)) {
replaceWithExpiredRefreshTombstone(token, grant, now);
} else {
refreshGrants.remove(token, grant);
}
}
});
}
private void rejectExpiredRefreshTombstone(String token, RefreshGrant grant, Instant now) {
if (grant == null || !grant.expiredTombstone()) {
return;
}
if (grant.expiredTombstoneUntil().isAfter(now)) {
throw SigninTokenException.refreshTokenExpired();
}
refreshGrants.remove(token, grant);
throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
}
private boolean replaceWithExpiredRefreshTombstone(String token, RefreshGrant grant, Instant now) {
Instant retainedUntil = grant.expiresAt().plusSeconds(EXPIRED_TOKEN_TOMBSTONE_TTL_SECONDS);
if (retainedUntil.isAfter(now)) {
return refreshGrants.replace(token, grant, RefreshGrant.expired(retainedUntil));
}
refreshGrants.remove(token, grant);
return false;
}
private static boolean isSameDeviceRedirect(URI uri) {
return "http".equalsIgnoreCase(uri.getScheme())
&& "127.0.0.1".equals(uri.getHost())
@@ -349,7 +445,23 @@ public class SigninService {
}
private record AuthorizationCode(String clientId, String codeChallenge, String redirectUri,
String resource, String accountId, Instant expiresAt) {
String resource, String accountId, Instant expiresAt,
Instant expiredTombstoneUntil) {
private static AuthorizationCode active(String clientId, String codeChallenge, String redirectUri,
String resource, String accountId, Instant expiresAt) {
return new AuthorizationCode(clientId, codeChallenge, redirectUri, resource, accountId,
expiresAt, null);
}
private boolean expiredTombstone() {
return expiredTombstoneUntil != null;
}
private AuthorizationCode toExpiredTombstone() {
return new AuthorizationCode(null, null, null, null, null, null,
expiresAt.plusSeconds(EXPIRED_TOKEN_TOMBSTONE_TTL_SECONDS));
}
}
private record StoredRefreshGrant(String token, RefreshGrant grant) {
@@ -360,6 +472,7 @@ public class SigninService {
private final String resource;
private final String accountId;
private final Instant expiresAt;
private final Instant expiredTombstoneUntil;
private TokenResult replayResult;
private Instant replayExpiresAt;
@@ -368,6 +481,19 @@ public class SigninService {
this.resource = resource;
this.accountId = accountId;
this.expiresAt = expiresAt;
this.expiredTombstoneUntil = null;
}
private RefreshGrant(Instant expiredTombstoneUntil) {
this.clientId = null;
this.resource = null;
this.accountId = null;
this.expiresAt = null;
this.expiredTombstoneUntil = expiredTombstoneUntil;
}
private static RefreshGrant expired(Instant retainedUntil) {
return new RefreshGrant(retainedUntil);
}
private String clientId() {
@@ -386,6 +512,14 @@ public class SigninService {
return expiresAt;
}
private boolean expiredTombstone() {
return expiredTombstoneUntil != null;
}
private Instant expiredTombstoneUntil() {
return expiredTombstoneUntil;
}
private TokenResult replayResult() {
return replayResult;
}
@@ -395,8 +529,12 @@ public class SigninService {
}
private boolean retentionExpiredAt(Instant now) {
if (expiredTombstone()) {
return !expiredTombstoneUntil.isAfter(now);
}
Instant replayExpiry = replayExpiresAt;
Instant retentionExpiry = replayExpiry == null ? expiresAt : replayExpiry;
Instant retentionExpiry = replayExpiry == null || expiresAt.isBefore(replayExpiry)
? expiresAt : replayExpiry;
return !retentionExpiry.isAfter(now);
}
@@ -0,0 +1,52 @@
package io.github.hectorvent.floci.services.signin;
/** AWS Sign-In token error with explicit modeled or OAuth response semantics. */
public final class SigninTokenException extends SigninException {
static final String INVALID_REQUEST_MESSAGE =
"The request is missing a required parameter, includes an invalid parameter value, "
+ "or is otherwise malformed.";
static final String UNSUPPORTED_GRANT_MESSAGE =
"The authorization grant type is not supported by the authorization server.";
private final String responseError;
private final boolean modeled;
private SigninTokenException(String awsErrorCode, String responseError, String message,
int httpStatus, boolean modeled) {
super(awsErrorCode, message, httpStatus);
this.responseError = responseError;
this.modeled = modeled;
}
public static SigninTokenException validation() {
return new SigninTokenException(
"ValidationException", "INVALID_REQUEST", INVALID_REQUEST_MESSAGE, 400, true);
}
public static SigninTokenException authorizationCodeExpired() {
return new SigninTokenException(
"AccessDeniedException", "AUTHCODE_EXPIRED",
"The authorization code is invalid or expired", 401, true);
}
public static SigninTokenException refreshTokenExpired() {
return new SigninTokenException(
"AccessDeniedException", "TOKEN_EXPIRED",
"The refresh token is invalid or expired", 401, true);
}
public static SigninTokenException unsupportedGrant() {
return new SigninTokenException(
"unsupported_grant_type", "unsupported_grant_type",
UNSUPPORTED_GRANT_MESSAGE, 400, false);
}
public String responseError() {
return responseError;
}
public boolean modeled() {
return modeled;
}
}
@@ -0,0 +1,36 @@
package io.github.hectorvent.floci.services.signin;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;
import java.util.Map;
/** Maps AWS Sign-In token failures to their modeled or OAuth wire envelopes. */
@Provider
public final class SigninTokenExceptionMapper implements ExceptionMapper<SigninTokenException> {
private static final String ERROR_TYPE_HEADER = "X-Amzn-ErrorType";
@Override
public Response toResponse(SigninTokenException exception) {
Response.ResponseBuilder response = Response.status(exception.getHttpStatus())
.type(MediaType.APPLICATION_JSON)
.header(HttpHeaders.CACHE_CONTROL, "no-store");
if (exception.modeled()) {
return response
.header(ERROR_TYPE_HEADER, exception.getErrorCode())
.entity(Map.of(
"error", exception.responseError(),
"message", exception.getMessage()))
.build();
}
return response
.entity(Map.of(
"error", exception.responseError(),
"error_description", exception.getMessage()))
.build();
}
}