Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(signin): support AWS login credentials provider (#2428)

Alex Banna470ec7771140
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 908ab2ae58..8b280ee24b 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -2,6 +2,23 @@
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
+## AWS Sign-In login credentials
+
+Floci also implements the AWS Sign-In data-plane flow used by the AWS CLI login credentials
+provider. The local `GET /v1/authorize` endpoint performs the emulator's local sign-in and returns
+a one-time PKCE authorization code. `POST /v1/token` exchanges that code (or a refresh token) for
+15-minute temporary SigV4 credentials registered with the local IAM account.
+
+```bash
+aws login --endpoint-url http://localhost:4566 --region us-east-1
+aws sts get-caller-identity --endpoint-url http://localhost:4566
+```
+
+The browser callback is still handled by the AWS CLI; Floci does not contact AWS or require a real
+AWS account. This follows the AWS Sign-In `AuthorizeOAuth2Access` and `CreateOAuth2Token` wire
+shapes, including one-time codes, PKCE verification, refresh-token expiry, and the `aws_sigv4`
+temporary credential type.
+
## Supported Actions
### Users
diff --git a/docs/services/index.md b/docs/services/index.md
index 88772e1f80..ca94de370c 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -24,6 +24,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 76 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
+| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 43 |
| [KMS](kms.md) | `POST /` + `X-Amz-Target: TrentService.*` | JSON 1.1 | 34 |
| [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 25738d4c1f..6006db8887 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -116,6 +116,11 @@ public class ResolvedServiceCatalog {
null, null, 5000L, AwsNamespaces.STS, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
Set.of(), Set.of("sts"), Set.of(), Set.of()),
+ descriptor("signin", "iam", config.services().iam().enabled(), false,
+ null, null, 5000L, null, ServiceProtocol.REST_JSON,
+ protocols(ServiceProtocol.REST_JSON),
+ Set.of(), Set.of("signin"), Set.of(),
+ Set.of(io.github.hectorvent.floci.services.signin.SigninController.class)),
descriptor("elasticache", "elasticache", config.services().elasticache().enabled(), true,
"elasticache", storageMode(config.storage().services().elasticache().mode(), config.storage().mode()),
config.storage().services().elasticache().flushIntervalMs(), AwsNamespaces.EC, ServiceProtocol.QUERY,
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 6e5bd8fcc7..5728d30fbb 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
@@ -1576,6 +1576,22 @@ public class IamService implements SessionAccountLookup {
sessionPolicyDocument, originAccountId));
}
+ /** Stores a temporary session in an explicit account namespace. */
+ public void registerSessionForAccount(String accountId, String sessionAccessKeyId, String secretAccessKey,
+ String roleArn, java.time.Instant expiration,
+ String sessionPolicyDocument) {
+ if (accountId == null || accountId.isBlank()) {
+ throw new IllegalArgumentException("Session account ID must not be blank");
+ }
+ SessionCredential session = new SessionCredential(
+ sessionAccessKeyId, secretAccessKey, roleArn, expiration, sessionPolicyDocument, accountId);
+ if (sessions instanceof AccountAwareStorageBackend<SessionCredential> aware) {
+ aware.putForAccount(accountId, sessionAccessKeyId, session);
+ } else {
+ sessions.put(sessionAccessKeyId, session);
+ }
+ }
+
/**
* Stores a non-expiring session for a Lambda execution role under the function's account.
* Lambda launches can happen outside request scope, so the account namespace must be explicit.
diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java
new file mode 100644
index 0000000000..2c6349d8e8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninController.java
@@ -0,0 +1,127 @@
+package io.github.hectorvent.floci.services.signin;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.iam.model.SessionCreds;
+import io.github.hectorvent.floci.services.signin.model.TokenResult;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.QueryParam;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.Context;
+
+import java.io.IOException;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/** AWS Sign-In data-plane endpoints used by the CLI login credentials provider. */
+@Path("/")
+@Produces(MediaType.APPLICATION_JSON)
+public class SigninController {
+
+ private final SigninService signinService;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public SigninController(SigninService signinService, ObjectMapper objectMapper) {
+ this.signinService = signinService;
+ this.objectMapper = objectMapper;
+ }
+
+ @GET
+ @Path("/v1/authorize")
+ public Response authorize(@QueryParam("client_id") String clientId,
+ @QueryParam("code_challenge") String codeChallenge,
+ @QueryParam("code_challenge_method") String codeChallengeMethod,
+ @QueryParam("redirect_uri") String redirectUri,
+ @QueryParam("response_type") String responseType,
+ @QueryParam("scope") String scope,
+ @QueryParam("state") String state,
+ @QueryParam("resource") String resource) {
+ String location = signinService.authorize(clientId, codeChallenge, codeChallengeMethod,
+ redirectUri, responseType, scope, state, resource);
+ return Response.status(Response.Status.FOUND)
+ .header(HttpHeaders.LOCATION, location)
+ .build();
+ }
+
+ @POST
+ @Path("/v1/token")
+ @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED})
+ public Response token(String body, @Context HttpHeaders headers) {
+ Map<String, String> values = parseBody(body, headers.getHeaderString(HttpHeaders.CONTENT_TYPE));
+ TokenResult result = signinService.exchange(
+ value(values, "clientId", "client_id"),
+ value(values, "grantType", "grant_type"),
+ value(values, "code"),
+ value(values, "redirectUri", "redirect_uri"),
+ value(values, "codeVerifier", "code_verifier"),
+ value(values, "refreshToken", "refresh_token"),
+ value(values, "resource"));
+ Map<String, Object> response = new LinkedHashMap<>();
+ SessionCreds accessToken = result.accessToken();
+ response.put("accessToken", Map.of(
+ "accessKeyId", accessToken.accessKeyId(),
+ "secretAccessKey", accessToken.secretAccessKey(),
+ "sessionToken", accessToken.sessionToken()));
+ response.put("tokenType", "aws_sigv4");
+ response.put("expiresIn", result.expiresIn());
+ response.put("refreshToken", result.refreshToken());
+ if (result.idToken() != null) {
+ response.put("idToken", result.idToken());
+ }
+ return Response.ok(response).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ private Map<String, String> parseBody(String body, String contentType) {
+ try {
+ if (contentType != null && contentType.startsWith(MediaType.APPLICATION_FORM_URLENCODED)) {
+ Map<String, String> values = new LinkedHashMap<>();
+ if (body == null || body.isBlank()) {
+ return values;
+ }
+ for (String pair : body.split("&")) {
+ String[] keyValue = pair.split("=", 2);
+ String key = URLDecoder.decode(keyValue[0], StandardCharsets.UTF_8);
+ String value = keyValue.length == 2
+ ? URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8) : "";
+ values.put(key, value);
+ }
+ return values;
+ }
+ JsonNode root = objectMapper.readTree(body == null ? "" : body);
+ if (root != null && root.has("tokenInput")) {
+ root = root.get("tokenInput");
+ }
+ Map<String, String> values = new LinkedHashMap<>();
+ if (root != null && root.isObject()) {
+ root.fields().forEachRemaining(entry -> {
+ if (entry.getValue().isValueNode()) {
+ values.put(entry.getKey(), entry.getValue().asText());
+ }
+ });
+ }
+ return values;
+ } catch (IOException e) {
+ throw new SigninException("invalid_request", "Request body must be valid JSON");
+ }
+ }
+
+ private static String value(Map<String, String> values, String... names) {
+ for (String name : names) {
+ if (values.containsKey(name)) {
+ return values.get(name);
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninException.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninException.java
new file mode 100644
index 0000000000..855efd5889
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninException.java
@@ -0,0 +1,15 @@
+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 SigninException(String error, String message) {
+ super(error, message, 400);
+ }
+
+ public String error() {
+ return getErrorCode();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninExceptionMapper.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninExceptionMapper.java
new file mode 100644
index 0000000000..bfd5be8202
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninExceptionMapper.java
@@ -0,0 +1,21 @@
+package io.github.hectorvent.floci.services.signin;
+
+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;
+
+/** Preserves the AWS Sign-In REST JSON error shape instead of the generic AWS envelope. */
+@Provider
+public final class SigninExceptionMapper implements ExceptionMapper<SigninException> {
+
+ @Override
+ public Response toResponse(SigninException exception) {
+ return Response.status(exception.getHttpStatus())
+ .type(MediaType.APPLICATION_JSON)
+ .entity(Map.of("error", exception.error(), "message", exception.getMessage()))
+ .build();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java
new file mode 100644
index 0000000000..1916299783
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java
@@ -0,0 +1,414 @@
+package io.github.hectorvent.floci.services.signin;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.SessionCreds;
+import io.github.hectorvent.floci.services.signin.model.TokenResult;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.regex.Pattern;
+
+/**
+ * Local implementation of the AWS Sign-In OAuth flow used by {@code aws login}.
+ *
+ * <p>Floci has no external console to authenticate against, so the authorization endpoint
+ * represents the local emulator account and immediately issues a one-time PKCE authorization
+ * code. The token endpoint still follows the AWS flow: codes are single-use, PKCE is verified,
+ * refresh tokens expire, and returned credentials are registered with IAM for request signing.
+ */
+@ApplicationScoped
+public class SigninService {
+
+ static final String SAME_DEVICE_CLIENT = "arn:aws:signin:::devtools/same-device";
+ static final String CROSS_DEVICE_CLIENT = "arn:aws:signin:::devtools/cross-device";
+ 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 int MAX_AUTHORIZATION_CODE_LENGTH = 512;
+ private static final int MAX_REDIRECT_URI_LENGTH = 2048;
+ private static final int MAX_RESOURCE_LENGTH = 2048;
+ private static final int MAX_REFRESH_TOKEN_LENGTH = 2048;
+ private static final int MAX_STATE_LENGTH = 128;
+ private static final Pattern PKCE_VALUE_PATTERN = Pattern.compile("[A-Za-z0-9._~-]{43,128}");
+ private static final Pattern AWS_SIGNIN_HOST_PATTERN =
+ Pattern.compile("[a-z]{2}-[a-z-]+-\\d+\\.signin\\.aws\\.amazon\\.com");
+
+ private final IamService iamService;
+ private final RegionResolver regionResolver;
+ private final ObjectMapper objectMapper;
+ private final Clock clock;
+ private final SecureRandom random;
+ private final ConcurrentHashMap<String, AuthorizationCode> authorizationCodes = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, RefreshGrant> refreshGrants = new ConcurrentHashMap<>();
+
+ @Inject
+ public SigninService(IamService iamService, RegionResolver regionResolver, ObjectMapper objectMapper,
+ Clock clock) {
+ this.iamService = iamService;
+ this.regionResolver = regionResolver;
+ this.objectMapper = objectMapper;
+ this.clock = clock;
+ this.random = new SecureRandom();
+ }
+
+ public String authorize(String clientId, String codeChallenge, String codeChallengeMethod,
+ String redirectUri, String responseType, String scope, String state,
+ String resource) {
+ validateClient(clientId);
+ if (!"SHA-256".equals(codeChallengeMethod)) {
+ throw new SigninException("invalid_request", "code_challenge_method must be SHA-256");
+ }
+ if (!isValidPkceValue(codeChallenge)) {
+ throw new SigninException("invalid_request",
+ "code_challenge must be 43-128 characters using the AWS PKCE alphabet");
+ }
+ if (!"code".equals(responseType) || !"openid".equals(scope)) {
+ throw new SigninException("invalid_request", "response_type=code and scope=openid are required");
+ }
+ validateRedirectUri(clientId, redirectUri);
+ if (state == null || state.isEmpty() || state.length() > MAX_STATE_LENGTH) {
+ throw new SigninException("invalid_request", "state must be 1-128 characters");
+ }
+ validateOptionalResource(resource);
+ String accountId = regionResolver.getAccountId();
+ Instant now = clock.instant();
+ authorizationCodes.entrySet().removeIf(entry -> !entry.getValue().expiresAt().isAfter(now));
+ String code = randomToken(32);
+ authorizationCodes.put(code, new AuthorizationCode(
+ clientId, codeChallenge, redirectUri, resource, accountId,
+ now.plusSeconds(AUTHORIZATION_CODE_TTL_SECONDS)));
+ return appendQuery(redirectUri, "code", code, "state", state);
+ }
+
+ 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 ("refresh_token".equals(grantType)) {
+ return refresh(clientId, refreshToken);
+ }
+ 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,
+ String resource) {
+ if (code == null || code.isEmpty() || code.length() > MAX_AUTHORIZATION_CODE_LENGTH) {
+ throw new SigninException("invalid_request", "code must be 1-512 characters");
+ }
+ if (redirectUri == null || redirectUri.isEmpty() || redirectUri.length() > MAX_REDIRECT_URI_LENGTH) {
+ throw new SigninException("invalid_request", "redirect_uri must be 1-2048 characters");
+ }
+ if (!isValidPkceValue(codeVerifier)) {
+ throw new SigninException("invalid_request",
+ "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())
+ || !redirectUri.equals(authorization.redirectUri())
+ || !matchesPkce(authorization.codeChallenge(), codeVerifier)) {
+ throw new SigninException("invalid_grant", "The authorization code is invalid or expired");
+ }
+ return issueTokens(clientId, resource != null ? resource : authorization.resource(),
+ authorization.accountId(), true, now);
+ }
+
+ private TokenResult refresh(String clientId, String refreshToken) {
+ if (refreshToken == null || refreshToken.isEmpty() || refreshToken.length() > MAX_REFRESH_TOKEN_LENGTH) {
+ 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())) {
+ throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
+ }
+ synchronized (grant) {
+ if (refreshGrants.get(refreshToken) != grant) {
+ throw new SigninException("invalid_grant", "The refresh token is invalid or expired");
+ }
+ if (grant.replayResult() != null) {
+ if (grant.replayExpiresAt().isAfter(now)) {
+ return grant.replayResultWithRemainingLifetime(now);
+ }
+ 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(
+ clientId, grant.resource(), grant.accountId(), grant.expiresAt());
+ TokenResult result;
+ try {
+ result = issueAccessToken(clientId, grant.resource(), false, successor.token(),
+ grant.accountId(), now);
+ } catch (RuntimeException e) {
+ refreshGrants.remove(successor.token(), successor.grant());
+ throw e;
+ }
+ grant.cacheReplay(result, accessTokenExpiresAt);
+ return result;
+ }
+ }
+
+ private TokenResult issueTokens(String clientId, String resource, String accountId, boolean includeIdToken,
+ Instant now) {
+ cleanupExpiredRefreshGrants(now);
+ StoredRefreshGrant stored = storeRefreshGrant(
+ clientId, resource, accountId, now.plusSeconds(REFRESH_TOKEN_TTL_SECONDS));
+ try {
+ return issueAccessToken(clientId, resource, includeIdToken, stored.token(), accountId, now);
+ } catch (RuntimeException e) {
+ refreshGrants.remove(stored.token(), stored.grant());
+ throw e;
+ }
+ }
+
+ private TokenResult issueAccessToken(String clientId, String resource, boolean includeIdToken,
+ String refreshToken, String accountId, Instant issuedAt) {
+ String accessKeyId = "ASIA" + randomAlphaNumeric(16);
+ String secretAccessKey = randomAlphaNumeric(40);
+ String sessionToken = randomAlphaNumeric(200);
+ Instant expiration = issuedAt.plusSeconds(ACCESS_TOKEN_TTL_SECONDS);
+ String principalArn = "arn:aws:iam::" + accountId + ":root";
+ iamService.registerSessionForAccount(
+ accountId, accessKeyId, secretAccessKey, principalArn, expiration, null);
+
+ SessionCreds accessToken = new SessionCreds(accessKeyId, secretAccessKey, sessionToken);
+ String idToken = includeIdToken ? idToken(principalArn, accountId, clientId, issuedAt) : null;
+ return new TokenResult(accessToken, ACCESS_TOKEN_TTL_SECONDS, refreshToken, idToken);
+ }
+
+ private StoredRefreshGrant storeRefreshGrant(String clientId, String resource, String accountId,
+ Instant expiresAt) {
+ while (true) {
+ String token = randomToken(48);
+ RefreshGrant grant = new RefreshGrant(clientId, resource, accountId, expiresAt);
+ if (refreshGrants.putIfAbsent(token, grant) == null) {
+ return new StoredRefreshGrant(token, grant);
+ }
+ }
+ }
+
+ private String idToken(String principalArn, String accountId, String clientId, Instant issuedAt) {
+ try {
+ long now = issuedAt.getEpochSecond();
+ String header = encodeJson(Map.of("alg", "none", "typ", "JWT"));
+ String payload = encodeJson(Map.of(
+ "iss", "https://signin.amazonaws.com",
+ "sub", principalArn,
+ "aud", clientId,
+ "aws_account_id", accountId,
+ "iat", now,
+ "exp", now + REFRESH_TOKEN_TTL_SECONDS));
+ return header + "." + payload + ".";
+ } catch (JsonProcessingException e) {
+ throw new IllegalStateException("Unable to encode local Sign-In identity token", e);
+ }
+ }
+
+ private String encodeJson(Map<String, ?> value) throws JsonProcessingException {
+ return Base64.getUrlEncoder().withoutPadding()
+ .encodeToString(objectMapper.writeValueAsBytes(value));
+ }
+
+ private static boolean matchesPkce(String challenge, String verifier) {
+ try {
+ byte[] digest = MessageDigest.getInstance("SHA-256")
+ .digest(verifier.getBytes(StandardCharsets.US_ASCII));
+ String calculated = Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+ return MessageDigest.isEqual(calculated.getBytes(StandardCharsets.US_ASCII),
+ challenge.getBytes(StandardCharsets.US_ASCII));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 is required by the AWS Sign-In protocol", e);
+ }
+ }
+
+ private static void validateClient(String clientId) {
+ if (!SAME_DEVICE_CLIENT.equals(clientId) && !CROSS_DEVICE_CLIENT.equals(clientId)) {
+ throw new SigninException("invalid_client", "Unsupported AWS Sign-In client");
+ }
+ }
+
+ private static boolean isValidPkceValue(String value) {
+ return value != null && PKCE_VALUE_PATTERN.matcher(value).matches();
+ }
+
+ private static void validateRedirectUri(String clientId, String redirectUri) {
+ if (redirectUri == null || redirectUri.isEmpty() || redirectUri.length() > MAX_REDIRECT_URI_LENGTH) {
+ throw new SigninException("invalid_request", "redirect_uri must be 1-2048 characters");
+ }
+
+ URI uri;
+ try {
+ uri = URI.create(redirectUri);
+ } catch (IllegalArgumentException e) {
+ throw new SigninException("invalid_request", "redirect_uri is invalid");
+ }
+
+ boolean valid = SAME_DEVICE_CLIENT.equals(clientId)
+ ? isSameDeviceRedirect(uri)
+ : isCrossDeviceRedirect(uri);
+ if (!valid) {
+ throw new SigninException("invalid_request", "redirect_uri is invalid for the AWS Sign-In client");
+ }
+ }
+
+ private static void validateOptionalResource(String resource) {
+ if (resource != null && (resource.isEmpty() || resource.length() > MAX_RESOURCE_LENGTH)) {
+ throw new SigninException("invalid_request", "resource must be 1-2048 characters when provided");
+ }
+ }
+
+ private void cleanupExpiredRefreshGrants(Instant now) {
+ refreshGrants.forEach((token, grant) -> {
+ synchronized (grant) {
+ if (grant.retentionExpiredAt(now)) {
+ refreshGrants.remove(token, grant);
+ }
+ }
+ });
+ }
+
+ private static boolean isSameDeviceRedirect(URI uri) {
+ return "http".equalsIgnoreCase(uri.getScheme())
+ && "127.0.0.1".equals(uri.getHost())
+ && uri.getPort() >= 1 && uri.getPort() <= 65535
+ && "/oauth/callback".equals(uri.getRawPath())
+ && uri.getRawQuery() == null
+ && uri.getRawFragment() == null
+ && uri.getUserInfo() == null;
+ }
+
+ private static boolean isCrossDeviceRedirect(URI uri) {
+ return "https".equalsIgnoreCase(uri.getScheme())
+ && uri.getHost() != null
+ && AWS_SIGNIN_HOST_PATTERN.matcher(uri.getHost()).matches()
+ && uri.getPort() == -1
+ && "/v1/sessions/confirmation".equals(uri.getRawPath())
+ && uri.getRawQuery() == null
+ && uri.getRawFragment() == null
+ && uri.getUserInfo() == null;
+ }
+
+ private static int remainingSeconds(Instant now, Instant expiresAt) {
+ Duration remaining = Duration.between(now, expiresAt);
+ long seconds = remaining.getSeconds() + (remaining.getNano() == 0 ? 0 : 1);
+ return Math.toIntExact(Math.max(1, Math.min(ACCESS_TOKEN_TTL_SECONDS, seconds)));
+ }
+
+ private static String appendQuery(String redirectUri, String... values) {
+ StringBuilder result = new StringBuilder(redirectUri);
+ result.append(redirectUri.contains("?") ? '&' : '?');
+ for (int i = 0; i < values.length; i += 2) {
+ if (i > 0) {
+ result.append('&');
+ }
+ result.append(java.net.URLEncoder.encode(values[i], StandardCharsets.UTF_8))
+ .append('=')
+ .append(java.net.URLEncoder.encode(values[i + 1], StandardCharsets.UTF_8));
+ }
+ return result.toString();
+ }
+
+ private String randomToken(int bytes) {
+ byte[] value = new byte[bytes];
+ random.nextBytes(value);
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
+ }
+
+ private String randomAlphaNumeric(int length) {
+ final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ StringBuilder value = new StringBuilder(length);
+ while (value.length() < length) {
+ value.append(alphabet.charAt(random.nextInt(alphabet.length())));
+ }
+ return value.toString();
+ }
+
+ private record AuthorizationCode(String clientId, String codeChallenge, String redirectUri,
+ String resource, String accountId, Instant expiresAt) {
+ }
+
+ private record StoredRefreshGrant(String token, RefreshGrant grant) {
+ }
+
+ private static final class RefreshGrant {
+ private final String clientId;
+ private final String resource;
+ private final String accountId;
+ private final Instant expiresAt;
+ private TokenResult replayResult;
+ private Instant replayExpiresAt;
+
+ private RefreshGrant(String clientId, String resource, String accountId, Instant expiresAt) {
+ this.clientId = clientId;
+ this.resource = resource;
+ this.accountId = accountId;
+ this.expiresAt = expiresAt;
+ }
+
+ private String clientId() {
+ return clientId;
+ }
+
+ private String resource() {
+ return resource;
+ }
+
+ private String accountId() {
+ return accountId;
+ }
+
+ private Instant expiresAt() {
+ return expiresAt;
+ }
+
+ private TokenResult replayResult() {
+ return replayResult;
+ }
+
+ private Instant replayExpiresAt() {
+ return replayExpiresAt;
+ }
+
+ private boolean retentionExpiredAt(Instant now) {
+ Instant replayExpiry = replayExpiresAt;
+ Instant retentionExpiry = replayExpiry == null ? expiresAt : replayExpiry;
+ return !retentionExpiry.isAfter(now);
+ }
+
+ private TokenResult replayResultWithRemainingLifetime(Instant now) {
+ return new TokenResult(replayResult.accessToken(), remainingSeconds(now, replayExpiresAt),
+ replayResult.refreshToken(), replayResult.idToken());
+ }
+
+ private void cacheReplay(TokenResult result, Instant expiresAt) {
+ this.replayResult = result;
+ this.replayExpiresAt = expiresAt;
+ }
+ }
+
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/signin/model/TokenResult.java b/src/main/java/io/github/hectorvent/floci/services/signin/model/TokenResult.java
new file mode 100644
index 0000000000..f86cdda8e0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/signin/model/TokenResult.java
@@ -0,0 +1,7 @@
+package io.github.hectorvent.floci.services.signin.model;
+
+import io.github.hectorvent.floci.services.iam.model.SessionCreds;
+
+public record TokenResult(SessionCreds accessToken, int expiresIn,
+ String refreshToken, String idToken) {
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index b5ecef9d83..eb7198cb1a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -595,6 +595,25 @@ class IamServiceTest {
assertTrue(sessions.getForAccount(accountId, accessKeyId).isEmpty());
}
+ @Test
+ void temporarySessionUsesExplicitAccountNamespace() {
+ String accountId = "222233334444";
+ String accessKeyId = "ASIASIGNINEXPLICIT";
+ AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
+ new InMemoryStorage<>(), null, "000000000000");
+ IamService service = iamService(false, new InMemoryStorage<>(), sessions);
+
+ service.registerSessionForAccount(
+ accountId, accessKeyId, "signin-secret",
+ "arn:aws:iam::222233334444:root", Instant.now().plusSeconds(900), null);
+
+ SessionCredential stored = sessions.getForAccount(accountId, accessKeyId).orElseThrow();
+ assertEquals(accountId, stored.getOriginAccountId());
+ assertEquals("signin-secret", stored.getSecretAccessKey());
+ assertTrue(sessions.getForAccount("000000000000", accessKeyId).isEmpty());
+ assertEquals(accountId, service.resolveAccountId(accessKeyId).orElseThrow());
+ }
+
@Test
void lambdaExecutionRoleSessionSweepPreservesStsSessions() {
AccountAwareStorageBackend<SessionCredential> sessions = new AccountAwareStorageBackend<>(
diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java
new file mode 100644
index 0000000000..0006a50777
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninIntegrationTest.java
@@ -0,0 +1,254 @@
+package io.github.hectorvent.floci.services.signin;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.Base64;
+import java.util.Map;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+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.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@QuarkusTest
+class SigninIntegrationTest {
+
+ private static final String CLIENT_ID = "arn:aws:signin:::devtools/same-device";
+ private static final String REDIRECT_URI = "http://127.0.0.1:4567/oauth/callback";
+
+ @Test
+ void authorizeRedirectsWithStateAndPkceCode() throws Exception {
+ String verifier = verifier();
+ String state = UUID.randomUUID().toString();
+
+ String location = request()
+ .redirects().follow(false)
+ .queryParam("client_id", CLIENT_ID)
+ .queryParam("code_challenge", challenge(verifier))
+ .queryParam("code_challenge_method", "SHA-256")
+ .queryParam("redirect_uri", REDIRECT_URI)
+ .queryParam("response_type", "code")
+ .queryParam("scope", "openid")
+ .queryParam("state", state)
+ .when()
+ .get("/v1/authorize")
+ .then()
+ .statusCode(302)
+ .extract()
+ .header("Location");
+
+ URI redirect = URI.create(location);
+ assertEquals(REDIRECT_URI, redirect.getScheme() + "://" + redirect.getAuthority() + redirect.getPath());
+ Map<String, String> params = queryParams(redirect.getRawQuery());
+ assertTrue(params.get("code").length() >= 1);
+ assertEquals(state, params.get("state"));
+ }
+
+ @Test
+ void authorizeRejectsOauthS256Alias() throws Exception {
+ request()
+ .queryParam("client_id", CLIENT_ID)
+ .queryParam("code_challenge", challenge(verifier()))
+ .queryParam("code_challenge_method", "S256")
+ .queryParam("redirect_uri", REDIRECT_URI)
+ .queryParam("response_type", "code")
+ .queryParam("scope", "openid")
+ .queryParam("state", UUID.randomUUID().toString())
+ .when()
+ .get("/v1/authorize")
+ .then()
+ .statusCode(400)
+ .body("error", equalTo("invalid_request"))
+ .body("message", equalTo("code_challenge_method must be SHA-256"))
+ .body("$", not(hasKey("__type")));
+ }
+
+ @Test
+ void malformedTokenJsonUsesSigninErrorEnvelope() {
+ request()
+ .contentType("application/json")
+ .body("{")
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(400)
+ .body("error", equalTo("invalid_request"))
+ .body("message", equalTo("Request body must be valid JSON"))
+ .body("$", not(hasKey("__type")));
+ }
+
+ @Test
+ void authorizationCodeExchangeReturnsTemporaryAwsCredentials() throws Exception {
+ String verifier = verifier();
+ String state = UUID.randomUUID().toString();
+ String location = authorize(verifier, state);
+ String code = queryParams(URI.create(location).getRawQuery()).get("code");
+
+ var response = request()
+ .contentType("application/json")
+ .body(Map.of(
+ "clientId", CLIENT_ID,
+ "grantType", "authorization_code",
+ "code", code,
+ "redirectUri", REDIRECT_URI,
+ "codeVerifier", verifier))
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(200)
+ .body("accessToken.accessKeyId", notNullValue())
+ .body("accessToken.secretAccessKey", notNullValue())
+ .body("accessToken.sessionToken", notNullValue())
+ .body("tokenType", equalTo("aws_sigv4"))
+ .body("expiresIn", equalTo(900))
+ .body("refreshToken", notNullValue())
+ .body("idToken", notNullValue())
+ .extract()
+ .response();
+
+ String accessKey = response.path("accessToken.accessKeyId");
+ assertTrue(accessKey.startsWith("ASIA"));
+
+ request()
+ .contentType("application/json")
+ .body(Map.of(
+ "clientId", CLIENT_ID,
+ "grantType", "authorization_code",
+ "code", code,
+ "redirectUri", REDIRECT_URI,
+ "codeVerifier", verifier))
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(400)
+ .body("error", equalTo("invalid_grant"));
+ }
+
+ @Test
+ void refreshTokenReturnsStableCredentialsWithinAccessTokenLifetime() throws Exception {
+ String verifier = verifier();
+ String code = queryParams(URI.create(authorize(verifier, UUID.randomUUID().toString())).getRawQuery())
+ .get("code");
+ String refreshToken = request()
+ .contentType("application/json")
+ .body(Map.of(
+ "clientId", CLIENT_ID,
+ "grantType", "authorization_code",
+ "code", code,
+ "redirectUri", REDIRECT_URI,
+ "codeVerifier", verifier))
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(200)
+ .extract()
+ .path("refreshToken");
+
+ var firstRefresh = request()
+ .contentType("application/json")
+ .body(Map.of(
+ "clientId", CLIENT_ID,
+ "grantType", "refresh_token",
+ "refreshToken", refreshToken))
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(200)
+ .body("accessToken.accessKeyId", notNullValue())
+ .body("tokenType", equalTo("aws_sigv4"))
+ .body("expiresIn", equalTo(900))
+ .body("refreshToken", not(equalTo(refreshToken)))
+ .body("idToken", equalTo(null))
+ .extract()
+ .response();
+
+ String rotatedRefreshToken = firstRefresh.path("refreshToken");
+
+ request()
+ .contentType("application/json")
+ .body(Map.of(
+ "clientId", CLIENT_ID,
+ "grantType", "refresh_token",
+ "refreshToken", refreshToken))
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(200)
+ .body("accessToken.accessKeyId", equalTo(firstRefresh.path("accessToken.accessKeyId")))
+ .body("accessToken.secretAccessKey", equalTo(firstRefresh.path("accessToken.secretAccessKey")))
+ .body("accessToken.sessionToken", equalTo(firstRefresh.path("accessToken.sessionToken")))
+ .body("refreshToken", equalTo(rotatedRefreshToken))
+ .body("idToken", equalTo(null));
+ }
+
+ @Test
+ void rejectsInvalidPkceProof() throws Exception {
+ String verifier = verifier();
+ String code = queryParams(URI.create(authorize(verifier, UUID.randomUUID().toString())).getRawQuery())
+ .get("code");
+
+ request()
+ .contentType("application/json")
+ .body(Map.of(
+ "clientId", CLIENT_ID,
+ "grantType", "authorization_code",
+ "code", code,
+ "redirectUri", REDIRECT_URI,
+ "codeVerifier", verifier + "wrong"))
+ .when()
+ .post("/v1/token")
+ .then()
+ .statusCode(400)
+ .body("error", equalTo("invalid_grant"));
+ }
+
+ private String authorize(String verifier, String state) throws Exception {
+ return request()
+ .redirects().follow(false)
+ .queryParam("client_id", CLIENT_ID)
+ .queryParam("code_challenge", challenge(verifier))
+ .queryParam("code_challenge_method", "SHA-256")
+ .queryParam("redirect_uri", REDIRECT_URI)
+ .queryParam("response_type", "code")
+ .queryParam("scope", "openid")
+ .queryParam("state", state)
+ .when()
+ .get("/v1/authorize")
+ .then()
+ .statusCode(302)
+ .extract()
+ .header("Location");
+ }
+
+ private RequestSpecification request() {
+ return given();
+ }
+
+ private static String verifier() {
+ return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
+ }
+
+ private static String challenge(String verifier) throws Exception {
+ byte[] digest = MessageDigest.getInstance("SHA-256")
+ .digest(verifier.getBytes(StandardCharsets.US_ASCII));
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+ }
+
+ private static Map<String, String> queryParams(String query) {
+ return java.util.Arrays.stream(query.split("&"))
+ .map(pair -> pair.split("=", 2))
+ .collect(java.util.stream.Collectors.toMap(
+ parts -> URLDecoder.decode(parts[0], StandardCharsets.UTF_8),
+ parts -> URLDecoder.decode(parts[1], StandardCharsets.UTF_8)));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java
new file mode 100644
index 0000000000..d42ddaf12e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/signin/SigninServiceTest.java
@@ -0,0 +1,348 @@
+package io.github.hectorvent.floci.services.signin;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.signin.model.TokenResult;
+import io.github.hectorvent.floci.testing.MutableClock;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.net.URI;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.Duration;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doAnswer;
+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.when;
+
+class SigninServiceTest {
+
+ private static final String CLIENT_ID = SigninService.SAME_DEVICE_CLIENT;
+ private static final String REDIRECT_URI = "http://127.0.0.1:4567/oauth/callback";
+ private static final String ACCOUNT_A = "000000000000";
+ private static final String ACCOUNT_B = "111111111111";
+ private static final String VERIFIER = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
+
+ private IamService iam;
+ private AtomicReference<String> accountId;
+ private MutableClock clock;
+ private SigninService service;
+
+ @BeforeEach
+ void setUp() {
+ iam = mock(IamService.class);
+ RegionResolver region = mock(RegionResolver.class);
+ accountId = new AtomicReference<>(ACCOUNT_A);
+ when(region.getAccountId()).thenAnswer(ignored -> accountId.get());
+ clock = new MutableClock();
+ service = new SigninService(iam, region, new ObjectMapper(), clock);
+ }
+
+ @Test
+ void issuesSingleUsePkceCodeAndRegistersAwsSessionCredentials() throws Exception {
+ String code = authorizeCode(VERIFIER);
+
+ TokenResult tokens = exchangeCode(code, VERIFIER);
+
+ assertTrue(tokens.accessToken().accessKeyId().startsWith("ASIA"));
+ assertEquals(900, tokens.expiresIn());
+ 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));
+ }
+
+ @Test
+ void requiresAwsSha256ChallengeMethod() throws Exception {
+ SigninException error = assertThrows(SigninException.class,
+ () -> service.authorize(CLIENT_ID, challenge(VERIFIER), "S256", REDIRECT_URI,
+ "code", "openid", "state", null));
+
+ assertEquals("invalid_request", error.error());
+ service.authorize(CLIENT_ID, challenge(VERIFIER), "SHA-256", REDIRECT_URI,
+ "code", "openid", "state", null);
+ }
+
+ @Test
+ void validatesAuthorizationRequestBoundariesAndClientRedirects() throws Exception {
+ authorize("A".repeat(43), CLIENT_ID, REDIRECT_URI, "s".repeat(128));
+ authorize("A".repeat(128), CLIENT_ID, REDIRECT_URI, "state");
+ authorize(challenge(VERIFIER), SigninService.CROSS_DEVICE_CLIENT,
+ "https://us-east-1.signin.aws.amazon.com/v1/sessions/confirmation", "state");
+
+ assertInvalidAuthorization("A".repeat(42), CLIENT_ID, REDIRECT_URI, "state");
+ assertInvalidAuthorization("A".repeat(129), CLIENT_ID, REDIRECT_URI, "state");
+ assertInvalidAuthorization("A".repeat(42) + "!", CLIENT_ID, REDIRECT_URI, "state");
+ assertInvalidAuthorization(challenge(VERIFIER), CLIENT_ID, REDIRECT_URI, "s".repeat(129));
+ assertInvalidAuthorization(challenge(VERIFIER), CLIENT_ID,
+ "http://localhost:4567/oauth/callback", "state");
+ assertInvalidAuthorization(challenge(VERIFIER), CLIENT_ID,
+ "https://127.0.0.1:4567/oauth/callback", "state");
+ assertInvalidAuthorization(challenge(VERIFIER), CLIENT_ID,
+ "http://127.0.0.1:4567/wrong", "state");
+ assertInvalidAuthorization(challenge(VERIFIER), SigninService.CROSS_DEVICE_CLIENT,
+ "https://example.com/v1/sessions/confirmation", "state");
+ assertInvalidAuthorization(challenge(VERIFIER), SigninService.CROSS_DEVICE_CLIENT,
+ REDIRECT_URI, "state");
+ assertInvalidAuthorization(challenge(VERIFIER), CLIENT_ID, "x".repeat(2049), "state");
+ }
+
+ @Test
+ void validatesPkceVerifierBoundaries() throws Exception {
+ String minimumVerifier = "A".repeat(43);
+ String maximumVerifier = "A".repeat(128);
+ exchangeCode(authorizeCode(minimumVerifier), minimumVerifier);
+ exchangeCode(authorizeCode(maximumVerifier), maximumVerifier);
+
+ assertInvalidVerifier("A".repeat(42));
+ assertInvalidVerifier("A".repeat(129));
+ assertInvalidVerifier("A".repeat(42) + "!");
+ }
+
+ @Test
+ void validatesModeledTokenAndResourceBoundsBeforeConsumingState() throws Exception {
+ String code = authorizeCode(VERIFIER);
+
+ assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", "x".repeat(513),
+ REDIRECT_URI, VERIFIER, null, null));
+ assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", code,
+ "x".repeat(2049), VERIFIER, null, null));
+ assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", code,
+ REDIRECT_URI, VERIFIER, null, ""));
+ assertInvalidRequest(() -> service.exchange(CLIENT_ID, "authorization_code", code,
+ REDIRECT_URI, VERIFIER, null, "r".repeat(2049)));
+ assertInvalidRequest(() -> 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", ""));
+ assertInvalidRequest(() -> service.authorize(CLIENT_ID, challengeUnchecked(VERIFIER), "SHA-256",
+ REDIRECT_URI, "code", "openid", "state", "r".repeat(2049)));
+
+ TokenResult result = service.exchange(CLIENT_ID, "authorization_code", code,
+ REDIRECT_URI, VERIFIER, null, "r".repeat(2048));
+ assertEquals(900, result.expiresIn());
+ }
+
+ @Test
+ void authorizationCodeExpiresAtFiveMinuteBoundary() throws Exception {
+ String code = authorizeCode(VERIFIER);
+ clock.advance(Duration.ofMinutes(5));
+
+ SigninException error = assertThrows(SigninException.class,
+ () -> exchangeCode(code, VERIFIER));
+
+ assertEquals("invalid_grant", error.error());
+ }
+
+ @Test
+ void rejectsPkceMismatchWithoutRegisteringCredentials() throws Exception {
+ String code = authorizeCode(VERIFIER);
+
+ SigninException error = assertThrows(SigninException.class,
+ () -> exchangeCode(code, VERIFIER + "wrong"));
+
+ assertEquals("invalid_grant", error.error());
+ }
+
+ @Test
+ void refreshRotationIsIdempotentUnderConcurrency() throws Exception {
+ TokenResult initial = issueInitialTokens();
+ int callers = 8;
+ ExecutorService executor = Executors.newFixedThreadPool(callers);
+ CountDownLatch ready = new CountDownLatch(callers);
+ CountDownLatch start = new CountDownLatch(1);
+ try {
+ List<Future<TokenResult>> futures = java.util.stream.IntStream.range(0, callers)
+ .mapToObj(ignored -> executor.submit(() -> {
+ ready.countDown();
+ start.await();
+ return refresh(initial.refreshToken());
+ }))
+ .toList();
+ assertTrue(ready.await(5, TimeUnit.SECONDS));
+ start.countDown();
+
+ TokenResult first = futures.getFirst().get(5, TimeUnit.SECONDS);
+ assertNotEquals(initial.refreshToken(), first.refreshToken());
+ for (Future<TokenResult> future : futures) {
+ TokenResult result = future.get(5, TimeUnit.SECONDS);
+ assertEquals(first.accessToken(), result.accessToken());
+ assertEquals(first.refreshToken(), result.refreshToken());
+ assertEquals(900, result.expiresIn());
+ }
+ verify(iam, times(2)).registerSessionForAccount(eq(ACCOUNT_A), anyString(), anyString(),
+ anyString(), any(), isNull());
+ } finally {
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ void predecessorReplayReportsRemainingLifetimeAndExpires() throws Exception {
+ TokenResult initial = issueInitialTokens();
+ TokenResult first = refresh(initial.refreshToken());
+
+ clock.advance(Duration.ofMinutes(10));
+ TokenResult replay = refresh(initial.refreshToken());
+ assertEquals(first.accessToken(), replay.accessToken());
+ assertEquals(first.refreshToken(), replay.refreshToken());
+ assertEquals(300, replay.expiresIn());
+
+ clock.advance(Duration.ofMinutes(5).plusSeconds(1));
+ assertInvalidRefresh(initial.refreshToken());
+ TokenResult successor = refresh(first.refreshToken());
+ assertNotEquals(first.refreshToken(), successor.refreshToken());
+ }
+
+ @Test
+ void rotatedRefreshTokenKeepsOriginalAbsoluteExpiry() throws Exception {
+ TokenResult initial = issueInitialTokens();
+ clock.advance(Duration.ofHours(11).plusMinutes(59));
+
+ TokenResult rotated = refresh(initial.refreshToken());
+ clock.advance(Duration.ofMinutes(2));
+
+ assertInvalidRefresh(rotated.refreshToken());
+ }
+
+ @Test
+ void expiryCleanupWaitsForInFlightRotation() throws Exception {
+ TokenResult initial = issueInitialTokens();
+ clock.advance(Duration.ofHours(12).minusMillis(2));
+ CountDownLatch issuanceStarted = new CountDownLatch(1);
+ CountDownLatch allowIssuance = new CountDownLatch(1);
+ doAnswer(ignored -> {
+ issuanceStarted.countDown();
+ assertTrue(allowIssuance.await(5, TimeUnit.SECONDS));
+ return null;
+ }).when(iam).registerSessionForAccount(anyString(), anyString(), anyString(),
+ anyString(), any(), isNull());
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ try {
+ Future<TokenResult> rotation =
+ executor.submit(() -> refresh(initial.refreshToken()));
+ assertTrue(issuanceStarted.await(5, TimeUnit.SECONDS));
+ Future<?> cleanup = executor.submit(() -> assertInvalidRefresh("unknown-refresh-token"));
+
+ allowIssuance.countDown();
+ TokenResult rotated = rotation.get(5, TimeUnit.SECONDS);
+ cleanup.get(5, TimeUnit.SECONDS);
+
+ TokenResult replay = refresh(initial.refreshToken());
+ assertEquals(rotated.accessToken(), replay.accessToken());
+ assertEquals(rotated.refreshToken(), replay.refreshToken());
+ } finally {
+ allowIssuance.countDown();
+ executor.shutdownNow();
+ }
+ }
+
+ @Test
+ void authorizationCodesAndRefreshGrantsIssueOnlyForCapturedAccount() throws Exception {
+ String code = authorizeCode(VERIFIER);
+ accountId.set(ACCOUNT_B);
+ TokenResult initial = exchangeCode(code, VERIFIER);
+
+ TokenResult rotated = refresh(initial.refreshToken());
+ assertNotEquals(initial.refreshToken(), rotated.refreshToken());
+ verify(iam, times(2)).registerSessionForAccount(eq(ACCOUNT_A), anyString(), anyString(),
+ eq("arn:aws:iam::" + ACCOUNT_A + ":root"), any(), isNull());
+ verify(iam, never()).registerSessionForAccount(eq(ACCOUNT_B), anyString(), anyString(),
+ anyString(), any(), isNull());
+ }
+
+ private TokenResult issueInitialTokens() throws Exception {
+ return exchangeCode(authorizeCode(VERIFIER), VERIFIER);
+ }
+
+ private String authorizeCode(String verifier) throws Exception {
+ String redirect = service.authorize(CLIENT_ID, challenge(verifier), "SHA-256", REDIRECT_URI,
+ "code", "openid", "state", null);
+ return query(URI.create(redirect).getRawQuery()).get("code");
+ }
+
+ private String authorize(String codeChallenge, String clientId, String redirectUri, String state) {
+ return service.authorize(clientId, codeChallenge, "SHA-256", redirectUri,
+ "code", "openid", state, null);
+ }
+
+ private TokenResult exchangeCode(String code, String verifier) {
+ return service.exchange(CLIENT_ID, "authorization_code", code,
+ REDIRECT_URI, verifier, null, null);
+ }
+
+ private TokenResult refresh(String refreshToken) {
+ return service.exchange(CLIENT_ID, "refresh_token", null,
+ null, null, refreshToken, null);
+ }
+
+ private void assertInvalidAuthorization(String challenge, String clientId, String redirectUri, String state) {
+ SigninException error = assertThrows(SigninException.class,
+ () -> authorize(challenge, clientId, redirectUri, state));
+ assertEquals("invalid_request", error.error());
+ }
+
+ private void assertInvalidVerifier(String verifier) throws Exception {
+ String code = authorizeCode(verifier);
+ SigninException error = assertThrows(SigninException.class,
+ () -> exchangeCode(code, verifier));
+ assertEquals("invalid_request", error.error());
+ }
+
+ private void assertInvalidRefresh(String refreshToken) {
+ SigninException error = assertThrows(SigninException.class,
+ () -> refresh(refreshToken));
+ assertEquals("invalid_grant", error.error());
+ }
+
+ private void assertInvalidRequest(org.junit.jupiter.api.function.Executable request) {
+ SigninException error = assertThrows(SigninException.class, request);
+ assertEquals("invalid_request", error.error());
+ }
+
+ private static String challengeUnchecked(String verifier) {
+ try {
+ return challenge(verifier);
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static String challenge(String verifier) throws Exception {
+ byte[] digest = MessageDigest.getInstance("SHA-256")
+ .digest(verifier.getBytes(StandardCharsets.US_ASCII));
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
+ }
+
+ private static Map<String, String> query(String query) {
+ return java.util.Arrays.stream(query.split("&"))
+ .map(pair -> pair.split("=", 2))
+ .collect(java.util.stream.Collectors.toMap(
+ parts -> URLDecoder.decode(parts[0], StandardCharsets.UTF_8),
+ parts -> URLDecoder.decode(parts[1], StandardCharsets.UTF_8)));
+ }
+}