mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(signin): preserve AWS token error modes (#2554)
This commit is contained in:
1 parent
4083d0667d
commit
399bf20387
11 files changed
+560
-52
No files matched your search
@@ -140,6 +140,10 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>iam</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>signin</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>kafka</artifactId>
|
||||
|
||||
@@ -39,6 +39,7 @@ import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
|
||||
import software.amazon.awssdk.services.ses.SesClient;
|
||||
import software.amazon.awssdk.services.sesv2.SesV2Client;
|
||||
import software.amazon.awssdk.services.sfn.SfnClient;
|
||||
import software.amazon.awssdk.services.signin.SigninClient;
|
||||
import software.amazon.awssdk.services.swf.SwfClient;
|
||||
import software.amazon.awssdk.services.sns.SnsClient;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
@@ -294,6 +295,14 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static SigninClient signinClient() {
|
||||
return SigninClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
.region(REGION)
|
||||
.credentialsProvider(CREDENTIALS)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static S3Client s3Client() {
|
||||
return S3Client.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.signin.SigninClient;
|
||||
import software.amazon.awssdk.services.signin.model.OAuth2ErrorCode;
|
||||
import software.amazon.awssdk.services.signin.model.ValidationException;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("AWS Sign-In")
|
||||
class SigninTest {
|
||||
|
||||
@Test
|
||||
void tokenValidationErrorsUseTheModeledAwsResponse() {
|
||||
try (SigninClient signin = TestFixtures.signinClient()) {
|
||||
assertThatThrownBy(() -> signin.createOAuth2Token(request -> request
|
||||
.tokenInput(input -> input
|
||||
.clientId("arn:aws:signin:::devtools/same-device")
|
||||
.grantType("authorization_code")
|
||||
.code("invalid-authorization-code")
|
||||
.redirectUri("http://127.0.0.1:4567/oauth/callback")
|
||||
.codeVerifier("a".repeat(43)))))
|
||||
.isInstanceOfSatisfying(ValidationException.class, exception -> {
|
||||
assertThat(exception.statusCode()).isEqualTo(400);
|
||||
assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("ValidationException");
|
||||
assertThat(exception.error()).isEqualTo(OAuth2ErrorCode.INVALID_REQUEST);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+36
@@ -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();
|
||||
}
|
||||
}
|
||||
+100
-5
@@ -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);
|
||||
|
||||
+55
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user