From f004aeaad517b8e412827cabbd35abd2f1f7bbdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Thu, 17 Sep 2026 20:00:11 +0700 Subject: [PATCH] feat(cognito): implement federated sign-in (#3748) * feat(cognito): add federation transaction stores * fix(cognito): atomically consume federation state * feat(cognito): support OIDC provider exchange * fix(cognito): validate OIDC federation providers * fix(cognito): validate OIDC endpoint schemes * feat(cognito): add federated oauth routes * fix(cognito): preserve oauth state and codes * feat(cognito): implement federated sign-in coverage * chore: remove internal task report * fix(cognito): use Cognito IdP callback for federation * fix(cognito): use provider callback for token exchange --- docs/services/cognito.md | 35 +- .../cognito/CognitoCustomDomainFilter.java | 3 +- .../cognito/CognitoFederationService.java | 172 +++++++ .../cognito/CognitoFederationStateStore.java | 87 ++++ .../cognito/CognitoOAuthController.java | 210 ++++++++- .../services/cognito/CognitoOidcClient.java | 140 ++++++ .../services/cognito/CognitoService.java | 63 +++ .../cognito/CognitoWellKnownController.java | 11 +- .../model/CognitoAuthorizationCode.java | 17 + .../CognitoAuthorizationTransaction.java | 19 + .../services/cognito/model/CognitoUser.java | 18 + ...tomDomainOAuthContractIntegrationTest.java | 38 +- ...CognitoFederatedSignInIntegrationTest.java | 156 +++++++ .../cognito/CognitoFederationServiceTest.java | 438 ++++++++++++++++++ .../CognitoFederationStateStoreTest.java | 198 ++++++++ .../cognito/CognitoOAuthControllerTest.java | 292 ++++++++++++ .../services/cognito/MockOidcProvider.java | 82 ++++ 17 files changed, 1952 insertions(+), 27 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOidcClient.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationTransaction.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederatedSignInIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cognito/MockOidcProvider.java diff --git a/docs/services/cognito.md b/docs/services/cognito.md index d53b7a774e..b64ad94a8b 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -70,10 +70,14 @@ An action given a user pool ID that does not resolve returns `ResourceNotFoundEx | UpdateIdentityProvider | Updates a provider's details, attribute mapping or identifiers. | | DeleteIdentityProvider | Deletes an identity provider from a user pool. | -Providers are stored configuration only. Floci does not perform the federated sign-in -flow: there is no `/oauth2/authorize` or `/oauth2/idpresponse` endpoint, so a registered -provider cannot be used to authenticate. This covers infrastructure tooling that creates -and reads provider configuration, not federated login. +Providers can be used for generic OIDC authorization-code sign-in. Floci routes the +AWS-shaped `/oauth2/authorize` and `/oauth2/idpresponse` endpoints to the configured local +OIDC provider, exchanges the returned code, provisions or reconciles the federated user, +and issues a Cognito authorization code for the registered callback. + +Only `ProviderType=OIDC` is supported by this flow. Floci does not provide a built-in hosted +UI and does not implement social providers such as Google, Facebook, Login with Amazon or +SignInWithApple. Two deliberate divergences from AWS, both consequences of not calling out to a third party: @@ -116,8 +120,7 @@ the account that created it, since these requests carry no AWS credential: a `cl another pool is refused with `invalid_client`, and an access token issued by another pool with `invalid_token`. Domain names are unique across all accounts, as on AWS. The pool's `openid-configuration` advertises the custom-domain URLs when one exists. Prefix domains (`.auth..amazoncognito.com`) are stored but not -routed, since that hostname never reaches Floci. `/oauth2/authorize`, `/login` and `/logout` are not -served on any host. +routed, since that hostname never reaches Floci. `/login` and `/logout` are not served on any host. With TLS enabled, a custom domain (`CustomDomainConfig` set) is added to Floci's server certificate as soon as it is created, so `https://` verifies without a restart; see @@ -273,16 +276,30 @@ and returned rather than rendered. Two divergences follow from that: |------------------------------------------------------|------------------------------------------------------------------| | `GET /{userPoolId}/.well-known/openid-configuration` | OpenID discovery document | | `GET /{userPoolId}/.well-known/jwks.json` | JSON Web Key Set for JWT validation | -| `POST /cognito-idp/oauth2/token` | Relaxed OAuth token endpoint for `grant_type=client_credentials` | +| `GET /cognito-idp/oauth2/authorize` | OIDC authorization-code start endpoint | +| `GET /cognito-idp/oauth2/idpresponse` | OIDC provider callback endpoint | +| `POST /cognito-idp/oauth2/token` | OAuth authorization-code and client-credentials token endpoint | + +The OAuth endpoints support browser-style OIDC authorization-code sign-in as well as the +emulator-friendly client-credentials flow: + +- `GET /cognito-idp/oauth2/authorize` validates the app client and callback, then redirects + to the configured provider with an opaque state and nonce. +- `GET /cognito-idp/oauth2/idpresponse` consumes the provider state, exchanges the provider + code and redirects to the registered callback with a one-time Cognito authorization code. +- `POST /cognito-idp/oauth2/token` redeems that authorization code once, or issues a machine + token for `grant_type=client_credentials`. `POST /cognito-idp/oauth2/token` is intentionally emulator-friendly rather than full Cognito parity: - It requires an existing `client_id`. - It accepts `client_id` and `client_secret` from the form body or Basic auth. -- It requires a confidential app client created with `GenerateSecret=true`. +- Client-credentials requires a confidential app client created with `GenerateSecret=true`. +- Authorization-code redemption validates the client, callback URI and one-time code binding. - It requires `AllowedOAuthFlowsUserPoolClient=true` and `AllowedOAuthFlows=["client_credentials"]`. - It doesn't require a Cognito domain. -- It returns only `access_token`, `token_type`, and `expires_in`. +- Client-credentials returns only `access_token`, `token_type`, and `expires_in`; authorization-code + redemption returns the Cognito access, ID and refresh token set. - It validates requested OAuth scopes against the app client's `AllowedOAuthScopes` and the pool's registered resource-server scopes. - It advertises the prefixed token endpoint in `/{userPoolId}/.well-known/openid-configuration`, or `https:///oauth2/token` when the pool has a custom domain (see Custom domains above). diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java index ad38831d9b..9be7bccefe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilter.java @@ -16,7 +16,8 @@ import java.util.Optional; /** * Routes Cognito custom-domain requests by Host. On AWS a custom domain serves - * {@code https:///oauth2/token} and {@code /oauth2/userInfo}; Floci maps those onto + * {@code https:///oauth2/token}, {@code /oauth2/userInfo}, {@code /oauth2/authorize}, and + * {@code /oauth2/idpresponse}; Floci maps those onto * the {@code /cognito-idp/oauth2/...} handlers and pins the pool and the account that own the * domain, since the request itself carries no AWS credential. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java new file mode 100644 index 0000000000..06470cc5fc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java @@ -0,0 +1,172 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; +import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.IdentityProvider; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +@ApplicationScoped +public class CognitoFederationService { + + private static final Duration TRANSACTION_LIFETIME = Duration.ofMinutes(5); + private static final Duration AUTHORIZATION_CODE_LIFETIME = Duration.ofMinutes(5); + private static final String OIDC_PROVIDER_TYPE = "OIDC"; + + private final CognitoService cognitoService; + private final CognitoFederationStateStore stateStore; + private final CognitoOidcClient oidcClient; + private final Clock clock; + + @Inject + public CognitoFederationService(CognitoService cognitoService, CognitoFederationStateStore stateStore, + CognitoOidcClient oidcClient, Clock clock) { + this.cognitoService = cognitoService; + this.stateStore = stateStore; + this.oidcClient = oidcClient; + this.clock = clock; + } + + public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List scopes, + String nonce, String providerName) { + return beginAuthorization(userPoolId, clientId, redirectUri, scopes, nonce, providerName, null); + } + + public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List scopes, + String nonce, String providerName, String relyingPartyState) { + IdentityProvider provider = cognitoService.describeIdentityProvider(userPoolId, providerName); + requireOidcProvider(provider); + String authorizeEndpoint = requiredProviderDetail(provider, "authorize_url", "authorize endpoint"); + String providerClientId = requiredProviderDetail(provider, "client_id", "client_id"); + validateAuthorizeEndpoint(authorizeEndpoint, provider.getProviderName()); + Instant expiresAt = clock.instant().plus(TRANSACTION_LIFETIME); + CognitoAuthorizationTransaction transaction = new CognitoAuthorizationTransaction( + userPoolId, clientId, redirectUri, scopes, nonce, providerName, relyingPartyState, expiresAt); + String state = stateStore.putTransaction(transaction); + + Map parameters = new LinkedHashMap<>(); + parameters.put("response_type", "code"); + parameters.put("client_id", providerClientId); + parameters.put("redirect_uri", cognitoService.getIdentityProviderCallbackEndpoint(userPoolId)); + parameters.put("scope", providerScopes(provider, scopes)); + parameters.put("state", state); + if (nonce != null && !nonce.isBlank()) { + parameters.put("nonce", nonce); + } + return appendQuery(authorizeEndpoint, parameters); + } + + public String completeAuthorization(String state, String providerCode) { + CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(state) + .orElseThrow(() -> new AwsException("InvalidParameterException", "Invalid federation state", 400)); + return completeAuthorization(transaction, providerCode); + } + + String completeAuthorization(CognitoAuthorizationTransaction transaction, String providerCode) { + IdentityProvider provider = cognitoService.describeIdentityProvider( + transaction.userPoolId(), transaction.providerName()); + requireOidcProvider(provider); + String providerCallback = cognitoService.getIdentityProviderCallbackEndpoint(transaction.userPoolId()); + JsonNode tokenResponse = oidcClient.exchangeCode(provider, providerCode, providerCallback); + String accessToken = requiredText(tokenResponse, "access_token", "access token"); + JsonNode claims = oidcClient.fetchClaims(provider, accessToken); + String subject = requiredText(claims, "sub", "subject"); + String issuer = optionalText(claims, "iss"); + CognitoUser user = cognitoService.provisionFederatedUser(transaction.userPoolId(), provider, + subject, issuer, mapAttributes(provider, claims)); + CognitoAuthorizationCode authorizationCode = new CognitoAuthorizationCode( + transaction.userPoolId(), transaction.clientId(), user.getUsername(), transaction.redirectUri(), + transaction.scopes(), clock.instant().plus(AUTHORIZATION_CODE_LIFETIME)); + return stateStore.putAuthorizationCode(authorizationCode); + } + + private Map mapAttributes(IdentityProvider provider, JsonNode claims) { + Map attributes = new LinkedHashMap<>(); + for (Map.Entry mapping : provider.getAttributeMapping().entrySet()) { + JsonNode claim = claims.get(mapping.getValue()); + if (claim != null && !claim.isNull() && claim.isValueNode()) { + attributes.put(mapping.getKey(), claim.asText()); + } + } + return attributes; + } + + private String providerScopes(IdentityProvider provider, List scopes) { + String configuredScopes = provider.getProviderDetails().get("authorize_scopes"); + return configuredScopes != null && !configuredScopes.isBlank() + ? configuredScopes : String.join(" ", scopes); + } + + private String requiredText(JsonNode json, String fieldName, String description) { + String value = optionalText(json, fieldName); + if (value == null) { + throw new AwsException("InvalidParameterException", "Identity provider response is missing " + description, 400); + } + return value; + } + + private String optionalText(JsonNode json, String fieldName) { + JsonNode value = json.get(fieldName); + if (value == null || value.isNull() || !value.isValueNode() || value.asText().isBlank()) { + return null; + } + return value.asText(); + } + + private String requiredProviderDetail(IdentityProvider provider, String detailName, String description) { + String value = provider.getProviderDetails().get(detailName); + if (value == null || value.isBlank()) { + throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName() + + " does not have a " + description + " configured", 400); + } + return value; + } + + private void requireOidcProvider(IdentityProvider provider) { + if (!OIDC_PROVIDER_TYPE.equals(provider.getProviderType())) { + throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName() + + " must have ProviderType OIDC", 400); + } + } + + private void validateAuthorizeEndpoint(String endpoint, String providerName) { + try { + URI uri = URI.create(endpoint); + if (!uri.isAbsolute()) { + throw new IllegalArgumentException("URI must be absolute"); + } + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidParameterException", "Identity provider " + providerName + + " has an invalid authorize endpoint", 400); + } + } + + private String appendQuery(String endpoint, Map parameters) { + StringBuilder result = new StringBuilder(endpoint); + result.append(endpoint.contains("?") ? '&' : '?'); + boolean first = true; + for (Map.Entry parameter : parameters.entrySet()) { + if (!first) { + result.append('&'); + } + result.append(URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)); + result.append('='); + result.append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8)); + first = false; + } + return result.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java new file mode 100644 index 0000000000..ee35192bb1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java @@ -0,0 +1,87 @@ +package io.github.hectorvent.floci.services.cognito; + +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; +import jakarta.enterprise.context.ApplicationScoped; + +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Base64; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; + +@ApplicationScoped +public class CognitoFederationStateStore { + + private static final int OPAQUE_KEY_BYTES = 32; + + private final ConcurrentHashMap transactions = new ConcurrentHashMap<>(); + private final ConcurrentHashMap authorizationCodes = new ConcurrentHashMap<>(); + private final Clock clock; + private final SecureRandom secureRandom = new SecureRandom(); + + public CognitoFederationStateStore(Clock clock) { + this.clock = clock; + } + + public String putTransaction(CognitoAuthorizationTransaction transaction) { + return put(transactions, transaction); + } + + public Optional consumeTransaction(String state) { + return consume(transactions, state, CognitoAuthorizationTransaction::expiresAt); + } + + public String putAuthorizationCode(CognitoAuthorizationCode authorizationCode) { + return put(authorizationCodes, authorizationCode); + } + + public Optional consumeAuthorizationCode(String code) { + return consume(authorizationCodes, code, CognitoAuthorizationCode::expiresAt); + } + + public Optional findAuthorizationCode(String code) { + CognitoAuthorizationCode authorizationCode = authorizationCodes.get(code); + if (authorizationCode == null) { + return Optional.empty(); + } + if (isExpired(authorizationCode.expiresAt())) { + authorizationCodes.remove(code, authorizationCode); + return Optional.empty(); + } + return Optional.of(authorizationCode); + } + + private String put(ConcurrentHashMap store, T value) { + String key; + do { + key = generateOpaqueKey(); + } while (store.putIfAbsent(key, value) != null); + return key; + } + + private Optional consume(ConcurrentHashMap store, String key, + Function expiresAt) { + AtomicReference consumed = new AtomicReference<>(); + store.computeIfPresent(key, (ignored, value) -> { + if (!isExpired(expiresAt.apply(value))) { + consumed.set(value); + } + return null; + }); + return Optional.ofNullable(consumed.get()); + } + + private boolean isExpired(Instant expiresAt) { + return !expiresAt.isAfter(clock.instant()); + } + + private String generateOpaqueKey() { + byte[] bytes = new byte[OPAQUE_KEY_BYTES]; + secureRandom.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java index 20c0aface3..f38f1cf835 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthController.java @@ -3,12 +3,19 @@ package io.github.hectorvent.floci.services.cognito; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; +import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.UserPool; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.GET; import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; +import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.core.Context; @@ -17,9 +24,16 @@ import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; +import java.net.URI; +import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.ArrayList; import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.Optional; @ApplicationScoped @Path("/") @@ -30,11 +44,100 @@ public class CognitoOAuthController { private final CognitoService cognitoService; private final ObjectMapper objectMapper; + private final CognitoFederationService federationService; + private final CognitoFederationStateStore stateStore; @Inject - public CognitoOAuthController(CognitoService cognitoService, ObjectMapper objectMapper) { + public CognitoOAuthController(CognitoService cognitoService, ObjectMapper objectMapper, + CognitoFederationService federationService, + CognitoFederationStateStore stateStore) { this.cognitoService = cognitoService; this.objectMapper = objectMapper; + this.federationService = federationService; + this.stateStore = stateStore; + } + + @GET + @Path("/cognito-idp/oauth2/authorize") + public Response authorize(@Context ContainerRequestContext requestContext, + @QueryParam("client_id") String clientId, + @QueryParam("redirect_uri") String redirectUri, + @QueryParam("response_type") String responseType, + @QueryParam("scope") String scope, + @QueryParam("nonce") String nonce, + @QueryParam("identity_provider") String providerName, + @QueryParam("state") String relyingPartyState) { + if (!"code".equals(trimToNull(responseType))) { + return oauthError("unsupported_response_type", "Only response_type=code is supported"); + } + if (trimToNull(clientId) == null || trimToNull(redirectUri) == null || trimToNull(providerName) == null) { + return oauthError("invalid_request", "client_id, redirect_uri, and identity_provider are required"); + } + + UserPoolClient client; + try { + client = cognitoService.findClientById(clientId); + } catch (AwsException e) { + return oauthError("invalid_client", "Client not found"); + } + String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY); + if (domainPoolId != null && !domainPoolId.equals(client.getUserPoolId())) { + return oauthError("invalid_client", "Client not found"); + } + if (!client.isAllowedOAuthFlowsUserPoolClient() || !client.getAllowedOAuthFlows().contains("code")) { + return oauthError("unauthorized_client", "Client is not allowed to use the authorization code flow"); + } + if (!client.getCallbackURLs().contains(redirectUri)) { + return oauthError("invalid_request", "redirect_uri is not registered for this client"); + } + + try { + String location = federationService.beginAuthorization(client.getUserPoolId(), clientId, redirectUri, + splitScopes(scope), trimToNull(nonce), providerName, relyingPartyState); + return Response.status(Response.Status.FOUND).location(URI.create(location)).build(); + } catch (AwsException e) { + return oauthError("invalid_request", e.getMessage()); + } + } + + @GET + @Path("/cognito-idp/oauth2/idpresponse") + public Response idpResponse(@Context ContainerRequestContext requestContext, + @QueryParam("state") String state, + @QueryParam("code") String providerCode, + @QueryParam("error") String error, + @QueryParam("error_description") String errorDescription) { + String normalizedState = trimToNull(state); + if (normalizedState == null) { + return oauthError("invalid_request", "state is required"); + } + Optional transaction = stateStore.consumeTransaction(normalizedState); + if (transaction.isEmpty()) { + return oauthError("invalid_request", "Invalid federation state"); + } + String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY); + if (domainPoolId != null && !domainPoolId.equals(transaction.get().userPoolId())) { + return oauthError("invalid_request", "Invalid federation state"); + } + if (trimToNull(error) != null) { + Map errorParameters = new LinkedHashMap<>(); + errorParameters.put("error", error); + errorParameters.put("error_description", errorDescription == null ? "" : errorDescription); + putRelyingPartyState(errorParameters, transaction.get()); + return redirect(transaction.get().redirectUri(), errorParameters); + } + if (trimToNull(providerCode) == null) { + return oauthError("invalid_request", "code is required"); + } + try { + String authorizationCode = federationService.completeAuthorization(transaction.get(), providerCode); + Map parameters = new LinkedHashMap<>(); + parameters.put("code", authorizationCode); + putRelyingPartyState(parameters, transaction.get()); + return redirect(transaction.get().redirectUri(), parameters); + } catch (AwsException e) { + return oauthError("invalid_request", e.getMessage()); + } } @POST @@ -53,10 +156,6 @@ public class CognitoOAuthController { if (grantType == null) { return oauthError("invalid_request", "grant_type is required"); } - if (!"client_credentials".equals(grantType)) { - return oauthError("unsupported_grant_type", "Only client_credentials is supported"); - } - BasicCredentials basicCredentials; try { basicCredentials = parseBasicCredentials(authorization); @@ -69,7 +168,7 @@ public class CognitoOAuthController { String basicClientId = basicCredentials != null ? basicCredentials.clientId() : null; String basicClientSecret = basicCredentials != null ? basicCredentials.clientSecret() : null; - if (bodyClientSecret != null && basicClientSecret != null && !bodyClientSecret.equals(basicClientSecret)) { + if (bodyClientSecret != null && basicClientSecret != null && !secretsEqual(bodyClientSecret, basicClientSecret)) { return oauthError("invalid_request", "client_secret does not match Authorization header"); } @@ -83,6 +182,12 @@ public class CognitoOAuthController { } String clientSecret = bodyClientSecret != null ? bodyClientSecret : basicClientSecret; + if ("authorization_code".equals(grantType)) { + return redeemAuthorizationCode(clientId, clientSecret, formParams, domainPoolId); + } + if (!"client_credentials".equals(grantType)) { + return oauthError("unsupported_grant_type", "Only client_credentials and authorization_code are supported"); + } String scope = trimToNull(formParams.getFirst("scope")); try { @@ -111,6 +216,99 @@ public class CognitoOAuthController { } } + private Response redeemAuthorizationCode(String clientId, String clientSecret, + MultivaluedMap formParams, String domainPoolId) { + String code = trimToNull(formParams.getFirst("code")); + String redirectUri = trimToNull(formParams.getFirst("redirect_uri")); + if (code == null || redirectUri == null) { + return oauthError("invalid_request", "code and redirect_uri are required"); + } + UserPoolClient client; + try { + client = cognitoService.findClientById(clientId); + } catch (AwsException e) { + return oauthError("invalid_client", "Client not found"); + } + if (client.getClientSecret() != null && !client.getClientSecret().isBlank() + && !secretsEqual(client.getClientSecret(), clientSecret)) { + return oauthError("invalid_client", "Client secret is invalid"); + } + + Optional authorizationCode = stateStore.findAuthorizationCode(code); + if (authorizationCode.isEmpty()) { + return oauthError("invalid_grant", "Authorization code is invalid or has expired"); + } + CognitoAuthorizationCode storedCode = authorizationCode.get(); + if (!clientId.equals(storedCode.clientId()) || !redirectUri.equals(storedCode.redirectUri()) + || (domainPoolId != null && !domainPoolId.equals(storedCode.userPoolId())) + || !storedCode.userPoolId().equals(client.getUserPoolId())) { + return oauthError("invalid_grant", "Authorization code was not issued to this client"); + } + Optional consumed = stateStore.consumeAuthorizationCode(code); + if (consumed.isEmpty()) { + return oauthError("invalid_grant", "Authorization code is invalid or has expired"); + } + CognitoAuthorizationCode consumedCode = consumed.get(); + try { + UserPool pool = cognitoService.describeUserPool(consumedCode.userPoolId()); + CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId()); + Map authentication = cognitoService.generateAuthResult(user, pool, client, null); + ObjectNode body = objectMapper.createObjectNode(); + body.put("access_token", (String) authentication.get("AccessToken")); + body.put("id_token", (String) authentication.get("IdToken")); + body.put("refresh_token", (String) authentication.get("RefreshToken")); + body.put("expires_in", ((Number) authentication.get("ExpiresIn")).longValue()); + body.put("token_type", (String) authentication.get("TokenType")); + return Response.ok(body).type(MediaType.APPLICATION_JSON) + .header("Cache-Control", "no-store").header("Pragma", "no-cache").build(); + } catch (AwsException e) { + LOG.error("Failed to redeem Cognito authorization code", e); + return oauthError("invalid_grant", e.getMessage()); + } + } + + private Response redirect(String redirectUri, Map parameters) { + StringBuilder location = new StringBuilder(redirectUri); + location.append(redirectUri.contains("?") ? '&' : '?'); + boolean first = true; + for (Map.Entry parameter : parameters.entrySet()) { + if (!first) { + location.append('&'); + } + location.append(URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8)); + location.append('=').append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8)); + first = false; + } + return Response.status(Response.Status.FOUND).location(URI.create(location.toString())).build(); + } + + private boolean secretsEqual(String expected, String actual) { + if (expected == null || actual == null) { + return expected == actual; + } + return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), actual.getBytes(StandardCharsets.UTF_8)); + } + + private void putRelyingPartyState(Map parameters, CognitoAuthorizationTransaction transaction) { + if (transaction.relyingPartyState() != null) { + parameters.put("state", transaction.relyingPartyState()); + } + } + + private List splitScopes(String scope) { + String normalizedScope = trimToNull(scope); + if (normalizedScope == null) { + return List.of(); + } + List scopes = new ArrayList<>(); + for (String value : normalizedScope.split("\\s+")) { + if (!value.isBlank()) { + scopes.add(value); + } + } + return scopes; + } + private Response oauthError(String error, String description) { ObjectNode body = objectMapper.createObjectNode(); body.put("error", error); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOidcClient.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOidcClient.java new file mode 100644 index 0000000000..ecb7683aa8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoOidcClient.java @@ -0,0 +1,140 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cognito.model.IdentityProvider; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.io.IOException; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.Function; + +@ApplicationScoped +public class CognitoOidcClient { + + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10); + private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(15); + + private final HttpClient httpClient; + private final ObjectMapper objectMapper; + + @Inject + public CognitoOidcClient(ObjectMapper objectMapper) { + this(HttpClient.newBuilder().connectTimeout(CONNECT_TIMEOUT).build(), objectMapper); + } + + CognitoOidcClient(HttpClient httpClient, ObjectMapper objectMapper) { + this.httpClient = httpClient; + this.objectMapper = objectMapper; + } + + public JsonNode exchangeCode(IdentityProvider provider, String code, String redirectUri) { + String tokenEndpoint = requiredEndpoint(provider, "token_url", "token"); + Map form = new LinkedHashMap<>(); + form.put("grant_type", "authorization_code"); + form.put("client_id", requiredProviderDetail(provider, "client_id")); + String clientSecret = provider.getProviderDetails().get("client_secret"); + if (clientSecret != null && !clientSecret.isBlank()) { + form.put("client_secret", clientSecret); + } + form.put("code", code); + form.put("redirect_uri", redirectUri); + + HttpRequest request = buildRequest(tokenEndpoint, provider.getProviderName(), "token", builder -> builder + .header("Accept", "application/json") + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(formEncode(form))) + .build()); + return send(request, "token exchange"); + } + + public JsonNode fetchClaims(IdentityProvider provider, String accessToken) { + String claimsEndpoint = requiredEndpoint(provider, "attributes_url", "claims"); + if (accessToken == null || accessToken.isBlank()) { + throw new AwsException("NotAuthorizedException", "Identity provider did not return an access token", 400); + } + + HttpRequest request = buildRequest(claimsEndpoint, provider.getProviderName(), "claims", builder -> builder + .header("Accept", "application/json") + .header("Authorization", "Bearer " + accessToken) + .GET() + .build()); + return send(request, "claims request"); + } + + private JsonNode send(HttpRequest request, String operation) { + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() < 200 || response.statusCode() >= 300) { + throw new AwsException("NotAuthorizedException", "Identity provider " + operation + " failed", 400); + } + JsonNode responseJson = objectMapper.readTree(response.body()); + if (responseJson == null || !responseJson.isObject()) { + throw new AwsException("NotAuthorizedException", "Identity provider " + operation + + " returned an invalid response", 400); + } + return responseJson; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AwsException("NotAuthorizedException", "Identity provider " + operation + " was interrupted", 400); + } catch (IOException | IllegalArgumentException e) { + throw new AwsException("NotAuthorizedException", "Identity provider " + operation + " failed", 400); + } + } + + private String requiredEndpoint(IdentityProvider provider, String detailName, String endpointName) { + String endpoint = provider.getProviderDetails().get(detailName); + if (endpoint == null || endpoint.isBlank()) { + throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName() + + " does not have a " + endpointName + " endpoint configured", 400); + } + return endpoint; + } + + private HttpRequest buildRequest(String endpoint, String providerName, String endpointName, + Function requestFactory) { + try { + URI uri = URI.create(endpoint); + if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) { + throw new IllegalArgumentException("Unsupported URI scheme"); + } + HttpRequest.Builder builder = HttpRequest.newBuilder(uri).timeout(REQUEST_TIMEOUT); + return requestFactory.apply(builder); + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidParameterException", "Identity provider " + providerName + + " has an invalid " + endpointName + " endpoint", 400); + } + } + + private String requiredProviderDetail(IdentityProvider provider, String detailName) { + String value = provider.getProviderDetails().get(detailName); + if (value == null || value.isBlank()) { + throw new AwsException("InvalidParameterException", "Identity provider " + provider.getProviderName() + + " does not have " + detailName + " configured", 400); + } + return value; + } + + private String formEncode(Map form) { + StringBuilder encoded = new StringBuilder(); + for (Map.Entry entry : form.entrySet()) { + if (!encoded.isEmpty()) { + encoded.append('&'); + } + encoded.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)); + encoded.append('='); + encoded.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)); + } + return encoded.toString(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index b8c7f0d868..cff7653b5b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -2034,6 +2034,59 @@ public class CognitoService implements ResourceProvider { return MAPPER.createArrayNode(); } + public Optional findFederatedUser(String userPoolId, String providerName, String subject) { + describeUserPool(userPoolId); + String prefix = userPoolId + "::"; + return userStore.scan(key -> key.startsWith(prefix)).stream() + .filter(user -> providerName.equals(user.getFederatedProviderName()) + && subject.equals(user.getFederatedSubject())) + .findFirst(); + } + + public CognitoUser provisionFederatedUser(String userPoolId, IdentityProvider provider, String subject, + String issuer, Map mappedAttributes) { + describeUserPool(userPoolId); + synchronized (identityLinkLock) { + CognitoUser user = findFederatedUser(userPoolId, provider.getProviderName(), subject).orElse(null); + if (user == null) { + user = new CognitoUser(); + user.setUsername(provider.getProviderName() + "_" + UUID.randomUUID()); + user.setUserPoolId(userPoolId); + user.getAttributes().put("sub", UUID.randomUUID().toString()); + } + user.getAttributes().putAll(mappedAttributes); + user.setFederatedProviderName(provider.getProviderName()); + user.setFederatedSubject(subject); + updateFederatedIdentity(user, provider, subject, issuer); + user.setEnabled(true); + user.setUserStatus("CONFIRMED"); + user.setLastModifiedDate(System.currentTimeMillis() / 1000L); + userStore.put(userKey(userPoolId, user.getUsername()), user); + LOG.infov("Reconciled federated user {0} from provider {1} in pool {2}", + user.getUsername(), provider.getProviderName(), userPoolId); + return user; + } + } + + private void updateFederatedIdentity(CognitoUser user, IdentityProvider provider, String subject, String issuer) { + ArrayNode identities = readIdentities(user); + ArrayNode reconciled = MAPPER.createArrayNode(); + for (JsonNode identity : identities) { + if (!provider.getProviderName().equals(identity.path("providerName").asText()) + || !subject.equals(identity.path("userId").asText())) { + reconciled.add(identity); + } + } + reconciled.addObject() + .put("userId", subject) + .put("providerName", provider.getProviderName()) + .put("providerType", provider.getProviderType()) + .put("issuer", issuer) + .put("primary", false) + .put("dateCreated", System.currentTimeMillis()); + user.getAttributes().put(IDENTITIES_ATTRIBUTE, reconciled.toString()); + } + public List listUsers(String userPoolId, String filter) { describeUserPool(userPoolId); String prefix = userPoolId + "::"; @@ -2998,6 +3051,16 @@ public class CognitoService implements ResourceProvider { return oauthEndpoint(poolId, "userInfo"); } + /** + * Returns the callback endpoint that an external identity provider uses to return its + * authorization response to Cognito. + */ + public String getIdentityProviderCallbackEndpoint(String poolId) { + return findCustomDomainForPool(poolId) + .map(d -> "https://" + d.getDomain() + "/oauth2/idpresponse") + .orElse(baseUrl + "/cognito-idp/oauth2/idpresponse"); + } + private String oauthEndpoint(String poolId, String operation) { return findCustomDomainForPool(poolId) .map(d -> "https://" + d.getDomain() + "/oauth2/" + operation) diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java index d184b6f4b0..d3bae7b8e5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoWellKnownController.java @@ -10,6 +10,8 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import java.math.BigInteger; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; import java.util.Base64; /** @@ -43,7 +45,7 @@ public class CognitoWellKnownController { public Response getJwks(@PathParam("poolId") String poolId) { UserPool pool = cognitoService.describeUserPool(poolId); String kid = cognitoService.getSigningKeyId(pool); - var publicKey = cognitoService.getSigningPublicKey(pool); + RSAPublicKey publicKey = cognitoService.getSigningPublicKey(pool); String modulus = base64UrlEncodeUnsigned(publicKey.getModulus()); String exponent = base64UrlEncodeUnsigned(publicKey.getPublicExponent()); @@ -61,17 +63,18 @@ public class CognitoWellKnownController { String jwksUri = cognitoService.getJwksUri(pool.getId()); String tokenEndpoint = cognitoService.getTokenEndpoint(pool.getId()); String userInfoEndpoint = cognitoService.getUserInfoEndpoint(pool.getId()); + String authorizationEndpoint = tokenEndpoint.replace("/token", "/authorize"); String body = """ - {"issuer":"%s","jwks_uri":"%s","token_endpoint":"%s","userinfo_endpoint":"%s","subject_types_supported":["public"],"response_types_supported":[],"grant_types_supported":["client_credentials"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"]} - """.formatted(issuer, jwksUri, tokenEndpoint, userInfoEndpoint).strip(); + {"issuer":"%s","jwks_uri":"%s","authorization_endpoint":"%s","token_endpoint":"%s","userinfo_endpoint":"%s","subject_types_supported":["public"],"response_types_supported":["code"],"grant_types_supported":["client_credentials","authorization_code"],"token_endpoint_auth_methods_supported":["client_secret_basic","client_secret_post"],"id_token_signing_alg_values_supported":["RS256"]} + """.formatted(issuer, jwksUri, authorizationEndpoint, tokenEndpoint, userInfoEndpoint).strip(); return Response.ok(body).build(); } private String base64UrlEncodeUnsigned(BigInteger value) { byte[] bytes = value.toByteArray(); if (bytes.length > 1 && bytes[0] == 0) { - bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + bytes = Arrays.copyOfRange(bytes, 1, bytes.length); } return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java new file mode 100644 index 0000000000..f71fc8a1ad --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationCode.java @@ -0,0 +1,17 @@ +package io.github.hectorvent.floci.services.cognito.model; + +import java.time.Instant; +import java.util.List; + +public record CognitoAuthorizationCode( + String userPoolId, + String clientId, + String userId, + String redirectUri, + List scopes, + Instant expiresAt) { + + public CognitoAuthorizationCode { + scopes = List.copyOf(scopes); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationTransaction.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationTransaction.java new file mode 100644 index 0000000000..1c2482a0bf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoAuthorizationTransaction.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.cognito.model; + +import java.time.Instant; +import java.util.List; + +public record CognitoAuthorizationTransaction( + String userPoolId, + String clientId, + String redirectUri, + List scopes, + String nonce, + String providerName, + String relyingPartyState, + Instant expiresAt) { + + public CognitoAuthorizationTransaction { + scopes = List.copyOf(scopes); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java index ee89911f94..e765d42785 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java @@ -26,6 +26,8 @@ public class CognitoUser { private String srpSalt; private String srpVerifier; private EmailMfaSettings emailMfaSettings; + private String federatedProviderName; + private String federatedSubject; public CognitoUser() { long now = System.currentTimeMillis() / 1000L; @@ -89,4 +91,20 @@ public class CognitoUser { public void setEmailMfaSettings(EmailMfaSettings emailMfaSettings) { this.emailMfaSettings = emailMfaSettings; } + + public String getFederatedProviderName() { + return federatedProviderName; + } + + public void setFederatedProviderName(String federatedProviderName) { + this.federatedProviderName = federatedProviderName; + } + + public String getFederatedSubject() { + return federatedSubject; + } + + public void setFederatedSubject(String federatedSubject) { + this.federatedSubject = federatedSubject; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java index 84a11b3708..b10c7101f4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainOAuthContractIntegrationTest.java @@ -98,7 +98,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest { @Test @Order(4) - void unsupportedGrantTypeIsRefused() { + void authorizationCodeGrantRequiresItsMandatoryParameters() { given() .header("Host", DOMAIN) .header("Authorization", basic(clientA, secretA)) @@ -108,7 +108,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest { .post("/oauth2/token") .then() .statusCode(400) - .body("error", equalTo("unsupported_grant_type")); + .body("error", equalTo("invalid_request")); } @Test @@ -175,11 +175,35 @@ class CognitoCustomDomainOAuthContractIntegrationTest { .header("WWW-Authenticate", startsWith("Bearer error=\"invalid_token\"")); } - /** Floci has no hosted UI: the other endpoints AWS serves on a domain are absent, not stubbed. */ + /** Floci has no hosted UI revoke endpoint. */ @Test @Order(9) - void otherHostedUiPathsAreNotServed() { - for (String path : List.of("/oauth2/authorize", "/oauth2/revoke", "/oauth2/idpresponse")) { + void authorizeRouteIsServedOnCustomDomain() { + given() + .header("Host", DOMAIN) + .when() + .get("/oauth2/authorize") + .then() + .statusCode(400) + .body("error", equalTo("unsupported_response_type")); + } + + @Test + @Order(10) + void idpResponseRouteIsServedOnCustomDomain() { + given() + .header("Host", DOMAIN) + .when() + .get("/oauth2/idpresponse") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")); + } + + @Test + @Order(11) + void revokeEndpointIsNotServed() { + for (String path : List.of("/oauth2/revoke")) { given() .header("Host", DOMAIN) .when() @@ -191,7 +215,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest { /** A prefix domain's hostname resolves to AWS, so Floci never routes by it. */ @Test - @Order(10) + @Order(12) void prefixDomainHostIsNotRouted() throws Exception { String prefix = "routing-prefix-" + System.nanoTime(); cognitoJson("CreateUserPoolDomain", """ @@ -211,7 +235,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest { * requests on many threads must never let one request's pin decide another's answer. */ @Test - @Order(11) + @Order(13) void concurrentRequestsKeepTheirOwnPinnedPool() throws Exception { ExecutorService pool = Executors.newFixedThreadPool(8); try { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederatedSignInIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederatedSignInIntegrationTest.java new file mode 100644 index 0000000000..b8ce2cd3d4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederatedSignInIntegrationTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.net.URI; +import java.net.URLDecoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain; +import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate; +import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@QuarkusTest +class CognitoFederatedSignInIntegrationTest { + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final String DOMAIN = "federated-" + System.nanoTime() + ".teos.localhost.floci.io"; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void oidcProviderReceivesAuthorizationRequestAndDiscoveryAdvertisesCodeFlow() throws Exception { + try (MockOidcProvider provider = new MockOidcProvider()) { + String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"FederatedPool\"}") + .path("UserPool").path("Id").asText(); + JsonNode client = cognitoJson("CreateUserPoolClient", """ + {"UserPoolId":"%s","ClientName":"federated-client","AllowedOAuthFlowsUserPoolClient":true, + "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid"],"CallbackURLs":["https://client.example/callback"]} + """.formatted(poolId)).path("UserPoolClient"); + String clientId = client.path("ClientId").asText(); + cognitoJson("CreateIdentityProvider", """ + {"UserPoolId":"%s","ProviderName":"LocalOidc","ProviderType":"OIDC", + "ProviderDetails":{"authorize_url":"%s/authorize","token_url":"%s/token","attributes_url":"%s/userinfo","client_id":"provider-client","client_secret":"provider-secret"}, + "AttributeMapping":{"email":"email","username":"sub"}} + """.formatted(poolId, provider.baseUrl(), provider.baseUrl(), provider.baseUrl())); + cognitoJson("CreateUserPoolDomain", customDomain(DOMAIN, poolId, requestCertificate(DOMAIN))); + + Response authorizeResponse = given() + .redirects().follow(false) + .header("Host", DOMAIN) + .queryParam("client_id", clientId) + .queryParam("redirect_uri", "https://client.example/callback") + .queryParam("response_type", "code") + .queryParam("scope", "openid") + .queryParam("identity_provider", "LocalOidc") + .queryParam("state", "client-state") + .when() + .get("/oauth2/authorize") + .then().statusCode(302).extract().response(); + String location = authorizeResponse.getHeader("Location"); + assertNotNull(location, authorizeResponse.getHeaders().toString()); + + assertEquals(provider.baseUrl() + "/authorize", URI.create(location).resolve("/authorize").toString()); + String providerState = queryParameter(location, "state"); + assertNotNull(providerState); + assertFalse(providerState.equals("client-state")); + assertEquals("code", queryParameter(location, "response_type")); + + HttpClient httpClient = HttpClient.newHttpClient(); + HttpResponse providerAuthorizeResponse = httpClient.send( + HttpRequest.newBuilder(URI.create(location)).GET().build(), + HttpResponse.BodyHandlers.discarding()); + assertEquals(302, providerAuthorizeResponse.statusCode()); + Map providerParameters = provider.authorizationParameters(); + assertEquals("provider-client", providerParameters.get("client_id")); + assertEquals("code", providerParameters.get("response_type")); + assertEquals("https://" + DOMAIN + "/oauth2/idpresponse", providerParameters.get("redirect_uri")); + assertEquals("openid", providerParameters.get("scope")); + + Response callbackResponse = given() + .redirects().follow(false) + .header("Host", DOMAIN) + .queryParam("state", providerState) + .queryParam("code", "provider-code") + .when() + .get("/oauth2/idpresponse") + .then().statusCode(302).extract().response(); + String callbackLocation = callbackResponse.getHeader("Location"); + assertEquals("client-state", queryParameter(callbackLocation, "state")); + String authorizationCode = queryParameter(callbackLocation, "code"); + + Response tokenResponse = given() + .header("Host", DOMAIN) + .formParam("grant_type", "authorization_code") + .formParam("client_id", clientId) + .formParam("code", authorizationCode) + .formParam("redirect_uri", "https://client.example/callback") + .when() + .post("/oauth2/token") + .then().statusCode(200) + .body("token_type", equalTo("Bearer")) + .extract().response(); + assertEquals("authorization_code", formValue(provider.tokenRequestBody(), "grant_type")); + assertEquals("Bearer provider-access-token", provider.userInfoAuthorization()); + + JsonNode users = cognitoJson("ListUsers", "{\"UserPoolId\":\"%s\",\"Filter\":\"email = \\\"federated@example.com\\\"\"}".formatted(poolId)); + JsonNode attributes = users.path("Users").get(0).path("Attributes"); + assertEquals("federated@example.com", attributeValue(attributes, "email")); + JsonNode identities = OBJECT_MAPPER.readTree(attributeValue(attributes, "identities")).get(0); + assertEquals("LocalOidc", identities.path("providerName").asText()); + assertEquals("provider-subject", identities.path("userId").asText()); + assertFalse(identities.path("primary").asBoolean()); + String accessToken = tokenResponse.path("access_token").toString(); + assertFalse(accessToken.isBlank()); + + given() + .get("/" + poolId + "/.well-known/openid-configuration") + .then() + .statusCode(200) + .body("response_types_supported[0]", equalTo("code")) + .body("authorization_endpoint", equalTo("https://" + DOMAIN + "/oauth2/authorize")) + .body("grant_types_supported[1]", equalTo("authorization_code")); + } + } + + private String queryParameter(String location, String name) { + for (String parameter : URI.create(location).getRawQuery().split("&")) { + String[] pair = parameter.split("=", 2); + if (pair[0].equals(name)) { + return URLDecoder.decode(pair[1], StandardCharsets.UTF_8); + } + } + return null; + } + + private String formValue(String form, String name) { + return queryParameter("http://localhost/?" + form, name); + } + + private String attributeValue(JsonNode attributes, String name) { + for (JsonNode attribute : attributes) { + if (name.equals(attribute.path("Name").asText())) { + return attribute.path("Value").asText(); + } + } + return null; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java new file mode 100644 index 0000000000..c45e033465 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java @@ -0,0 +1,438 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.acm.AcmService; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; +import io.github.hectorvent.floci.services.cognito.model.CognitoGroup; +import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.IdentityProvider; +import io.github.hectorvent.floci.services.cognito.model.ResourceServer; +import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo; +import io.github.hectorvent.floci.services.cognito.model.UserPool; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; +import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.URI; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class CognitoFederationServiceTest { + + private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-09-16T00:00:00Z"), ZoneOffset.UTC); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private HttpServer oidcServer; + private CognitoService cognitoService; + private CognitoFederationStateStore stateStore; + private CognitoFederationService federationService; + private UserPool pool; + private final AtomicReference tokenRequest = new AtomicReference<>(); + private final AtomicReference claimsRequest = new AtomicReference<>(); + private volatile int tokenStatus; + private volatile String tokenResponse; + private volatile int claimsStatus; + private volatile String claimsResponse; + + @BeforeEach + void setUp() throws IOException { + oidcServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + oidcServer.createContext("/token", this::handleToken); + oidcServer.createContext("/userinfo", this::handleClaims); + oidcServer.start(); + + cognitoService = new CognitoService( + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + "http://localhost:4566", + new RegionResolver("us-east-1", "000000000000"), + null, + mock(AcmService.class), + null, + null, + null); + stateStore = new CognitoFederationStateStore(CLOCK); + federationService = new CognitoFederationService( + cognitoService, stateStore, new CognitoOidcClient(MAPPER), CLOCK); + pool = cognitoService.createUserPool(Map.of("PoolName", "FederationPool"), "us-east-1"); + tokenStatus = 200; + tokenResponse = "{\"access_token\":\"provider-access-token\"}"; + claimsStatus = 200; + claimsResponse = "{\"sub\":\"provider-subject\",\"iss\":\"https://issuer.example.test\"," + + "\"email\":\"alice@example.test\",\"name\":\"Alice Provider\"}"; + } + + @AfterEach + void tearDown() { + oidcServer.stop(0); + } + + @Test + void beginAuthorizationRejectsProviderWithoutAuthorizeEndpoint() { + createProvider(Map.of( + "client_id", "provider-client", + "token_url", endpoint("/token"), + "attributes_url", endpoint("/userinfo")), Map.of()); + + AwsException exception = assertThrows(AwsException.class, () -> federationService.beginAuthorization( + pool.getId(), "cognito-client", "https://application.example.test/callback", + List.of("openid"), "nonce-value", "ExampleOidc")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void beginAuthorizationRejectsNonOidcProviderBeforeStoringState() { + createProvider("ExampleGoogle", "Google", Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "token_url", endpoint("/token"), + "attributes_url", endpoint("/userinfo")), Map.of()); + + AwsException exception = assertThrows(AwsException.class, () -> federationService.beginAuthorization( + pool.getId(), "cognito-client", "https://application.example.test/callback", + List.of("openid"), "nonce-value", "ExampleGoogle")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + assertNull(tokenRequest.get()); + assertNull(claimsRequest.get()); + } + + @Test + void beginAuthorizationStoresRelyingPartyStateInTransaction() { + createDefaultProvider(); + + String redirect = federationService.beginAuthorization( + pool.getId(), "cognito-client", "https://application.example.test/callback", + List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state"); + + CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(queryValue(redirect, "state")).orElseThrow(); + assertEquals("relying-party-state", transaction.relyingPartyState()); + } + + @Test + void completeAuthorizationRejectsNonOidcProvider() { + createProvider("ExampleGoogle", "Google", Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "token_url", endpoint("/token"), + "attributes_url", endpoint("/userinfo")), Map.of()); + String state = putTransaction("ExampleGoogle"); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + assertNull(tokenRequest.get()); + assertNull(claimsRequest.get()); + } + + @Test + void completeAuthorizationRejectsProviderWithoutTokenEndpoint() { + createProvider(Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "attributes_url", endpoint("/userinfo")), Map.of()); + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationRejectsProviderWithoutClaimsEndpoint() { + createProvider(Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "token_url", endpoint("/token")), Map.of()); + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationConvertsInvalidTokenEndpointUriToAwsException() { + createProvider(Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "token_url", "http://[invalid", + "attributes_url", endpoint("/userinfo")), Map.of()); + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationRejectsUnsupportedTokenEndpointScheme() { + createProvider(Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "token_url", "ftp://provider.example.test/token", + "attributes_url", endpoint("/userinfo")), Map.of()); + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationRejectsUnsupportedClaimsEndpointScheme() { + createProvider(Map.of( + "client_id", "provider-client", + "authorize_url", "https://provider.example.test/authorize", + "token_url", endpoint("/token"), + "attributes_url", "ftp://provider.example.test/userinfo"), Map.of()); + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationRejectsFailedTokenExchange() { + createDefaultProvider(); + tokenStatus = 400; + tokenResponse = "{\"error\":\"invalid_grant\"}"; + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("NotAuthorizedException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationRejectsFailedClaimsRequest() { + createDefaultProvider(); + claimsStatus = 503; + claimsResponse = "{\"error\":\"temporarily_unavailable\"}"; + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("NotAuthorizedException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationRejectsClaimsWithoutSubject() { + createDefaultProvider(); + claimsResponse = "{\"email\":\"alice@example.test\"}"; + String state = beginAuthorization(); + + AwsException exception = assertThrows(AwsException.class, + () -> federationService.completeAuthorization(state, "provider-code")); + + assertEquals("InvalidParameterException", exception.getErrorCode()); + } + + @Test + void completeAuthorizationMapsClaimsAndUsesOidcRequests() { + createDefaultProvider(); + String state = beginAuthorization(); + + String authorizationCode = federationService.completeAuthorization(state, "provider code"); + + CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow(); + CognitoUser user = cognitoService.adminGetUser(pool.getId(), storedCode.userId()); + assertEquals("alice@example.test", user.getAttributes().get("email")); + assertEquals("Alice Provider", user.getAttributes().get("name")); + assertEquals("ExampleOidc", user.getFederatedProviderName()); + assertEquals("provider-subject", user.getFederatedSubject()); + + Request observedTokenRequest = tokenRequest.get(); + assertNotNull(observedTokenRequest); + assertEquals("POST", observedTokenRequest.method()); + assertEquals("authorization_code", formValue(observedTokenRequest.body(), "grant_type")); + assertEquals("provider-client", formValue(observedTokenRequest.body(), "client_id")); + assertEquals("provider-secret", formValue(observedTokenRequest.body(), "client_secret")); + assertEquals("provider code", formValue(observedTokenRequest.body(), "code")); + assertEquals(cognitoService.getIdentityProviderCallbackEndpoint(pool.getId()), + formValue(observedTokenRequest.body(), "redirect_uri")); + + Request observedClaimsRequest = claimsRequest.get(); + assertNotNull(observedClaimsRequest); + assertEquals("GET", observedClaimsRequest.method()); + assertEquals("Bearer provider-access-token", observedClaimsRequest.authorization()); + } + + @Test + void completeAuthorizationProvisionsNewFederatedUser() { + createDefaultProvider(); + + CognitoAuthorizationCode storedCode = completeAndConsumeAuthorizationCode(); + CognitoUser user = cognitoService.adminGetUser(pool.getId(), storedCode.userId()); + + assertEquals(pool.getId(), user.getUserPoolId()); + assertEquals("CONFIRMED", user.getUserStatus()); + assertTrue(user.isEnabled()); + assertFalse(user.getUsername().isBlank()); + assertNotNull(user.getAttributes().get("sub")); + } + + @Test + void completeAuthorizationReconcilesExistingFederatedUserWithoutLosingOtherAttributes() { + createDefaultProvider(); + CognitoAuthorizationCode firstCode = completeAndConsumeAuthorizationCode(); + CognitoUser firstUser = cognitoService.adminGetUser(pool.getId(), firstCode.userId()); + cognitoService.adminUpdateUserAttributes(pool.getId(), firstUser.getUsername(), + Map.of("custom:note", "preserve-me", "email", "old@example.test")); + claimsResponse = "{\"sub\":\"provider-subject\",\"iss\":\"https://issuer.example.test\"," + + "\"email\":\"new@example.test\",\"name\":\"Updated Provider\"}"; + + CognitoAuthorizationCode secondCode = completeAndConsumeAuthorizationCode(); + CognitoUser reconciledUser = cognitoService.adminGetUser(pool.getId(), secondCode.userId()); + + assertEquals(firstUser.getUsername(), reconciledUser.getUsername()); + assertEquals("new@example.test", reconciledUser.getAttributes().get("email")); + assertEquals("Updated Provider", reconciledUser.getAttributes().get("name")); + assertEquals("preserve-me", reconciledUser.getAttributes().get("custom:note")); + } + + @Test + void completeAuthorizationStoresAwsCompatibleIdentityFields() throws Exception { + createDefaultProvider(); + + CognitoAuthorizationCode storedCode = completeAndConsumeAuthorizationCode(); + CognitoUser user = cognitoService.adminGetUser(pool.getId(), storedCode.userId()); + JsonNode identity = MAPPER.readTree(user.getAttributes().get("identities")).get(0); + List fieldNames = new ArrayList<>(); + identity.fieldNames().forEachRemaining(fieldNames::add); + + assertEquals(List.of("userId", "providerName", "providerType", "issuer", "primary", "dateCreated"), + fieldNames); + assertEquals("provider-subject", identity.path("userId").asText()); + assertEquals("ExampleOidc", identity.path("providerName").asText()); + assertEquals("OIDC", identity.path("providerType").asText()); + assertEquals("https://issuer.example.test", identity.path("issuer").asText()); + assertFalse(identity.path("primary").asBoolean()); + assertTrue(identity.path("dateCreated").asLong() > 0L); + } + + private IdentityProvider createDefaultProvider() { + return createProvider(Map.of( + "client_id", "provider-client", + "client_secret", "provider-secret", + "authorize_url", "https://provider.example.test/authorize", + "token_url", endpoint("/token"), + "attributes_url", endpoint("/userinfo")), + Map.of("email", "email", "name", "name")); + } + + private IdentityProvider createProvider(Map details, Map attributeMapping) { + return createProvider("ExampleOidc", "OIDC", details, attributeMapping); + } + + private IdentityProvider createProvider(String providerName, String providerType, Map details, + Map attributeMapping) { + return cognitoService.createIdentityProvider(pool.getId(), providerName, providerType, details, + attributeMapping, List.of()); + } + + private CognitoAuthorizationCode completeAndConsumeAuthorizationCode() { + String authorizationCode = federationService.completeAuthorization(beginAuthorization(), "provider-code"); + return stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow(); + } + + private String beginAuthorization() { + String redirect = federationService.beginAuthorization( + pool.getId(), "cognito-client", "https://application.example.test/callback", + List.of("openid"), "nonce-value", "ExampleOidc"); + return queryValue(redirect, "state"); + } + + private String putTransaction(String providerName) { + return stateStore.putTransaction(new CognitoAuthorizationTransaction( + pool.getId(), "cognito-client", "https://application.example.test/callback", + List.of("openid"), "nonce-value", providerName, null, CLOCK.instant().plusSeconds(60))); + } + + private String endpoint(String path) { + return "http://127.0.0.1:" + oidcServer.getAddress().getPort() + path; + } + + private void handleToken(HttpExchange exchange) throws IOException { + tokenRequest.set(new Request(exchange.getRequestMethod(), + new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8), + exchange.getRequestHeaders().getFirst("Authorization"))); + writeResponse(exchange, tokenStatus, tokenResponse); + } + + private void handleClaims(HttpExchange exchange) throws IOException { + claimsRequest.set(new Request(exchange.getRequestMethod(), + new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8), + exchange.getRequestHeaders().getFirst("Authorization"))); + writeResponse(exchange, claimsStatus, claimsResponse); + } + + private void writeResponse(HttpExchange exchange, int status, String response) throws IOException { + byte[] body = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, body.length); + exchange.getResponseBody().write(body); + exchange.close(); + } + + private String queryValue(String uri, String name) { + String query = URI.create(uri).getRawQuery(); + for (String pair : query.split("&")) { + String[] parts = pair.split("=", 2); + if (parts.length == 2 && name.equals(URLDecoder.decode(parts[0], StandardCharsets.UTF_8))) { + return URLDecoder.decode(parts[1], StandardCharsets.UTF_8); + } + } + throw new AssertionError("Query parameter " + name + " was absent from " + uri); + } + + private String formValue(String form, String name) { + return queryValue("https://form.example.test/?" + form, name); + } + + private record Request(String method, String body, String authorization) { + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java new file mode 100644 index 0000000000..356afdcecc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java @@ -0,0 +1,198 @@ +package io.github.hectorvent.floci.services.cognito; + +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +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.function.BiFunction; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class CognitoFederationStateStoreTest { + + private static final Instant NOW = Instant.parse("2026-09-16T12:00:00Z"); + + @Test + void consumeTransaction_returnsStoredUnexpiredTransaction() { + CognitoFederationStateStore store = storeAt(NOW); + CognitoAuthorizationTransaction transaction = transaction(NOW.plusSeconds(60)); + + String state = store.putTransaction(transaction); + + assertEquals(Optional.of(transaction), store.consumeTransaction(state)); + } + + @Test + void consumeTransaction_expiredTransactionReturnsEmpty() { + CognitoFederationStateStore store = storeAt(NOW); + String state = store.putTransaction(transaction(NOW)); + + assertTrue(store.consumeTransaction(state).isEmpty()); + } + + @Test + void consumeTransaction_expiringAtMapMutationReturnsEmpty() throws ReflectiveOperationException { + Instant expiresAt = NOW.plusSeconds(1); + MutableClock clock = new MutableClock(NOW); + CognitoFederationStateStore store = new CognitoFederationStateStore(clock); + replaceStoreMap(store, "transactions", new ExpiringAtMutationMap<>(clock, expiresAt)); + String state = store.putTransaction(transaction(expiresAt)); + + assertTrue(store.consumeTransaction(state).isEmpty()); + } + + @Test + void consumeTransaction_concurrentRequestsReturnTransactionOnlyOnce() throws Exception { + CognitoFederationStateStore store = storeAt(NOW); + String state = store.putTransaction(transaction(NOW.plusSeconds(60))); + int consumers = 16; + CountDownLatch ready = new CountDownLatch(consumers); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(consumers); + + try { + List>> results = IntStream.range(0, consumers) + .mapToObj(ignored -> executor.submit(() -> { + ready.countDown(); + start.await(); + return store.consumeTransaction(state); + })) + .toList(); + assertTrue(ready.await(5, TimeUnit.SECONDS)); + + start.countDown(); + + long successfulConsumptions = 0; + for (Future> result : results) { + if (result.get(5, TimeUnit.SECONDS).isPresent()) { + successfulConsumptions++; + } + } + assertEquals(1, successfulConsumptions); + } finally { + executor.shutdownNow(); + } + } + + @Test + void consumeAuthorizationCode_returnsStoredUnexpiredCode() { + CognitoFederationStateStore store = storeAt(NOW); + CognitoAuthorizationCode authorizationCode = authorizationCode(NOW.plusSeconds(60)); + + String code = store.putAuthorizationCode(authorizationCode); + + assertEquals(Optional.of(authorizationCode), store.consumeAuthorizationCode(code)); + } + + @Test + void consumeAuthorizationCode_replayedCodeReturnsEmpty() { + CognitoFederationStateStore store = storeAt(NOW); + CognitoAuthorizationCode authorizationCode = authorizationCode(NOW.plusSeconds(60)); + String code = store.putAuthorizationCode(authorizationCode); + + assertEquals(Optional.of(authorizationCode), store.consumeAuthorizationCode(code)); + assertFalse(store.consumeAuthorizationCode(code).isPresent()); + } + + @Test + void consumeAuthorizationCode_expiringAtMapMutationReturnsEmpty() throws ReflectiveOperationException { + Instant expiresAt = NOW.plusSeconds(1); + MutableClock clock = new MutableClock(NOW); + CognitoFederationStateStore store = new CognitoFederationStateStore(clock); + replaceStoreMap(store, "authorizationCodes", new ExpiringAtMutationMap<>(clock, expiresAt)); + String code = store.putAuthorizationCode(authorizationCode(expiresAt)); + + assertTrue(store.consumeAuthorizationCode(code).isEmpty()); + } + + private CognitoFederationStateStore storeAt(Instant now) { + return new CognitoFederationStateStore(Clock.fixed(now, ZoneOffset.UTC)); + } + + private CognitoAuthorizationTransaction transaction(Instant expiresAt) { + return new CognitoAuthorizationTransaction( + "pool-id", "client-id", "https://example.com/callback", List.of("openid", "email"), + "nonce", "ExampleOidc", null, expiresAt + ); + } + + private CognitoAuthorizationCode authorizationCode(Instant expiresAt) { + return new CognitoAuthorizationCode( + "pool-id", "client-id", "user-id", "https://example.com/callback", List.of("openid", "email"), + expiresAt + ); + } + + private void replaceStoreMap(CognitoFederationStateStore store, String fieldName, + ConcurrentHashMap replacement) throws ReflectiveOperationException { + Field field = CognitoFederationStateStore.class.getDeclaredField(fieldName); + field.setAccessible(true); + field.set(store, replacement); + } + + private static final class MutableClock extends Clock { + private Instant now; + + private MutableClock(Instant now) { + this.now = now; + } + + void set(Instant now) { + this.now = now; + } + + @Override + public ZoneOffset getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return this; + } + + @Override + public Instant instant() { + return now; + } + } + + private static final class ExpiringAtMutationMap extends ConcurrentHashMap { + private final MutableClock clock; + private final Instant expiresAt; + + private ExpiringAtMutationMap(MutableClock clock, Instant expiresAt) { + this.clock = clock; + this.expiresAt = expiresAt; + } + + @Override + public boolean remove(Object key, Object value) { + clock.set(expiresAt); + return super.remove(key, value); + } + + @Override + public V computeIfPresent(String key, + BiFunction remappingFunction) { + clock.set(expiresAt); + return super.computeIfPresent(key, remappingFunction); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java new file mode 100644 index 0000000000..31dcbd5899 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java @@ -0,0 +1,292 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationCode; +import io.github.hectorvent.floci.services.cognito.model.CognitoAuthorizationTransaction; +import io.github.hectorvent.floci.services.cognito.model.CognitoUser; +import io.github.hectorvent.floci.services.cognito.model.UserPool; +import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class CognitoOAuthControllerTest { + + private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-09-16T00:00:00Z"), ZoneOffset.UTC); + private static final String POOL_ID = "us-east-1_pool"; + private static final String CLIENT_ID = "cognito-client"; + private static final String CALLBACK_URI = "https://application.example.test/callback"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private final CognitoService cognitoService = mock(CognitoService.class); + private final CognitoFederationService federationService = mock(CognitoFederationService.class); + private CognitoFederationStateStore stateStore; + private CognitoOAuthController controller; + private UserPoolClient client; + + @BeforeEach + void setUp() { + stateStore = new CognitoFederationStateStore(CLOCK); + controller = new CognitoOAuthController(cognitoService, objectMapper, federationService, stateStore); + client = client(); + when(cognitoService.findClientById(CLIENT_ID)).thenReturn(client); + } + + @Test + void authorizeRedirectsToConfiguredIdentityProvider() { + when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), "nonce", "ExampleOidc", + " relying-party-state ")) + .thenReturn("https://provider.example.test/authorize?state=provider-state"); + + Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce", + "ExampleOidc", " relying-party-state "); + + assertEquals(302, response.getStatus()); + assertEquals("https://provider.example.test/authorize?state=provider-state", response.getHeaderString("Location")); + } + + @Test + void authorizeReturnsInvalidClientForUnknownClient() { + when(cognitoService.findClientById("missing-client")) + .thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400)); + + Response response = controller.authorize(requestContext(null), "missing-client", CALLBACK_URI, "code", "openid", null, + "ExampleOidc", null); + + assertOAuthError(response, "invalid_client"); + } + + @Test + void authorizeReturnsInvalidRequestForUnregisteredRedirectUri() { + Response response = controller.authorize(requestContext(null), CLIENT_ID, "https://other.example.test/callback", "code", "openid", + null, "ExampleOidc", null); + + assertOAuthError(response, "invalid_request"); + } + + @Test + void authorizeReturnsUnsupportedResponseTypeForTokenResponse() { + Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc", null); + + assertOAuthError(response, "unsupported_response_type"); + } + + @Test + void idpResponseReturnsInvalidRequestForUnknownState() { + Response response = controller.idpResponse(requestContext(null), "unknown-state", "provider-code", null, null); + + assertOAuthError(response, "invalid_request"); + } + + @Test + void idpResponseRedirectsProviderErrorToApplication() { + String state = putTransaction("relying-party-state"); + + Response response = controller.idpResponse(requestContext(null), state, null, "access_denied", "The provider refused access"); + + assertEquals(302, response.getStatus()); + assertEquals(CALLBACK_URI + "?error=access_denied&error_description=The+provider+refused+access&state=relying-party-state", + response.getHeaderString("Location")); + } + + @Test + void idpResponseRedirectsAuthorizationCodeToApplication() { + String state = putTransaction("relying-party-state"); + when(federationService.completeAuthorization(any(CognitoAuthorizationTransaction.class), eq("provider-code"))) + .thenReturn("authorization-code"); + + Response response = controller.idpResponse(requestContext(null), state, "provider-code", null, null); + + assertEquals(302, response.getStatus()); + assertEquals(CALLBACK_URI + "?code=authorization-code&state=relying-party-state", response.getHeaderString("Location")); + } + + @Test + void tokenRedeemsAuthorizationCodeOnce() throws Exception { + String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode( + POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60))); + when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool()); + when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user()); + when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null))) + .thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token", + "ExpiresIn", 3600, "TokenType", "Bearer")); + + MultivaluedHashMap form = form("grant_type", "authorization_code", "client_id", CLIENT_ID, + "code", code, "redirect_uri", CALLBACK_URI); + Response first = controller.token(null, requestContext(null), form); + Response replay = controller.token(null, requestContext(null), form); + + assertEquals(200, first.getStatus()); + JsonNode body = (JsonNode) first.getEntity(); + assertEquals("access-token", body.path("access_token").asText()); + assertEquals("id-token", body.path("id_token").asText()); + assertEquals("refresh-token", body.path("refresh_token").asText()); + assertEquals(3600, body.path("expires_in").asInt()); + assertOAuthError(replay, "invalid_grant"); + } + + @Test + void tokenRejectsAuthorizationCodeForAnotherClient() { + String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode( + POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60))); + + Response response = controller.token(null, requestContext(null), form("grant_type", "authorization_code", + "client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI)); + + assertOAuthError(response, "invalid_grant"); + } + + @Test + void tokenDoesNotConsumeAuthorizationCodeWhenRedirectUriIsInvalid() { + String code = putAuthorizationCode(); + + Response invalid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", CLIENT_ID, + "code", code, "redirect_uri", "https://application.example.test/other")); + Response valid = controller.token(null, requestContext(null), validAuthorizationCodeForm(code)); + + assertOAuthError(invalid, "invalid_grant"); + assertEquals(200, valid.getStatus()); + } + + @Test + void tokenDoesNotConsumeAuthorizationCodeWhenClientDoesNotMatch() { + UserPoolClient otherClient = client("other-client"); + when(cognitoService.findClientById("other-client")).thenReturn(otherClient); + String code = putAuthorizationCode(); + + Response invalid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", "other-client", + "code", code, "redirect_uri", CALLBACK_URI)); + Response valid = controller.token(null, requestContext(null), validAuthorizationCodeForm(code)); + + assertOAuthError(invalid, "invalid_grant"); + assertEquals(200, valid.getStatus()); + } + + @Test + void tokenDoesNotConsumeAuthorizationCodeWhenClientSecretIsInvalid() { + client.setClientSecret("correct-secret"); + String code = putAuthorizationCode(); + + Response invalid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", CLIENT_ID, + "client_secret", "wrong-secret", "code", code, "redirect_uri", CALLBACK_URI)); + Response valid = controller.token(null, requestContext(null), form("grant_type", "authorization_code", "client_id", CLIENT_ID, + "client_secret", "correct-secret", "code", code, "redirect_uri", CALLBACK_URI)); + + assertOAuthError(invalid, "invalid_client"); + assertEquals(200, valid.getStatus()); + } + + @Test + void tokenDoesNotConsumeAuthorizationCodeWhenDomainDoesNotMatch() { + String code = putAuthorizationCode(); + + Response invalid = controller.token(null, requestContext("other-pool"), validAuthorizationCodeForm(code)); + Response valid = controller.token(null, requestContext(null), validAuthorizationCodeForm(code)); + + assertOAuthError(invalid, "invalid_grant"); + assertEquals(200, valid.getStatus()); + } + + @Test + void tokenRejectsMismatchedBasicAndFormClientAuthentication() { + Response response = controller.token(basicAuthorization(CLIENT_ID, "header-secret"), requestContext(null), + form("grant_type", "authorization_code", "client_id", CLIENT_ID, "client_secret", "form-secret", + "code", "authorization-code", "redirect_uri", CALLBACK_URI)); + + assertOAuthError(response, "invalid_request"); + } + + private String putTransaction(String relyingPartyState) { + return stateStore.putTransaction(new CognitoAuthorizationTransaction(POOL_ID, CLIENT_ID, CALLBACK_URI, + List.of("openid"), "nonce", "ExampleOidc", relyingPartyState, CLOCK.instant().plusSeconds(60))); + } + + private String putAuthorizationCode() { + String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode( + POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60))); + when(cognitoService.describeUserPool(POOL_ID)).thenReturn(pool()); + when(cognitoService.adminGetUser(POOL_ID, "federated-user")).thenReturn(user()); + when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), eq(null))) + .thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token", + "ExpiresIn", 3600, "TokenType", "Bearer")); + return code; + } + + private static MultivaluedHashMap validAuthorizationCodeForm(String code) { + return form("grant_type", "authorization_code", "client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI); + } + + private static UserPoolClient client() { + return client(CLIENT_ID); + } + + private static UserPoolClient client(String clientId) { + UserPoolClient result = new UserPoolClient(); + result.setClientId(clientId); + result.setUserPoolId(POOL_ID); + result.setAllowedOAuthFlowsUserPoolClient(true); + result.setAllowedOAuthFlows(List.of("code")); + result.setCallbackURLs(List.of(CALLBACK_URI)); + return result; + } + + private static UserPool pool() { + UserPool result = new UserPool(); + result.setId(POOL_ID); + return result; + } + + private static CognitoUser user() { + CognitoUser result = new CognitoUser(); + result.setUsername("federated-user"); + result.setUserPoolId(POOL_ID); + return result; + } + + private static ContainerRequestContext requestContext(String poolId) { + ContainerRequestContext result = mock(ContainerRequestContext.class); + when(result.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY)).thenReturn(poolId); + return result; + } + + private static MultivaluedHashMap form(String... values) { + MultivaluedHashMap result = new MultivaluedHashMap<>(); + for (int index = 0; index < values.length; index += 2) { + result.add(values[index], values[index + 1]); + } + return result; + } + + private static String basicAuthorization(String clientId, String clientSecret) { + String credentials = clientId + ":" + clientSecret; + return "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + } + + private void assertOAuthError(Response response, String error) { + assertEquals(400, response.getStatus()); + assertNotNull(response.getEntity()); + JsonNode body = (JsonNode) response.getEntity(); + assertEquals(error, body.path("error").asText()); + assertTrue(body.hasNonNull("error_description")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/MockOidcProvider.java b/src/test/java/io/github/hectorvent/floci/services/cognito/MockOidcProvider.java new file mode 100644 index 0000000000..19b9d97320 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/MockOidcProvider.java @@ -0,0 +1,82 @@ +package io.github.hectorvent.floci.services.cognito; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +final class MockOidcProvider implements AutoCloseable { + + private final HttpServer server; + private final Map authorizationParameters = new ConcurrentHashMap<>(); + private volatile String tokenRequestBody; + private volatile String userInfoAuthorization; + + MockOidcProvider() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/authorize", exchange -> { + authorizationParameters.putAll(queryParameters(exchange.getRequestURI().getRawQuery())); + respond(exchange, 302, ""); + }); + server.createContext("/token", exchange -> { + tokenRequestBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); + respond(exchange, 200, "{\"access_token\":\"provider-access-token\",\"token_type\":\"Bearer\"}"); + }); + server.createContext("/userinfo", exchange -> { + userInfoAuthorization = exchange.getRequestHeaders().getFirst("Authorization"); + respond(exchange, 200, "{\"sub\":\"provider-subject\",\"email\":\"federated@example.com\"}"); + }); + server.start(); + } + + String baseUrl() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + Map authorizationParameters() { + return new LinkedHashMap<>(authorizationParameters); + } + + String tokenRequestBody() { + return tokenRequestBody; + } + + String userInfoAuthorization() { + return userInfoAuthorization; + } + + private Map queryParameters(String query) { + Map parameters = new LinkedHashMap<>(); + if (query == null || query.isBlank()) { + return parameters; + } + for (String parameter : query.split("&")) { + String[] pair = parameter.split("=", 2); + if (pair.length == 2) { + parameters.put(URLDecoder.decode(pair[0], StandardCharsets.UTF_8), + URLDecoder.decode(pair[1], StandardCharsets.UTF_8)); + } + } + return parameters; + } + + private void respond(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(bytes); + } + } + + @Override + public void close() { + server.stop(0); + } +}