Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cognito): serve managed login for native users with PKCE (#4238)
jwoa95eb039eb71c4f
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 162c78e78c..ceaf1caeb7 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -75,9 +75,9 @@ AWS-shaped `/oauth2/authorize` and `/oauth2/idpresponse` endpoints to the configOIDC 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.+Only `ProviderType=OIDC` is supported by this flow. Floci does not implement social providers+such as Google, Facebook, Login with Amazon or SignInWithApple. The pool's own users sign in+through managed login instead (see [Managed login](#managed-login)).Two deliberate divergences from AWS, both consequences of not calling out to a thirdparty:@@ -110,8 +110,11 @@ always returns it.A domain created with `CustomDomainConfig` answers the OAuth endpoints on that host, as on AWS:```+GET https://auth.example.localhost.floci.io/oauth2/authorizePOST https://auth.example.localhost.floci.io/oauth2/tokenGET https://auth.example.localhost.floci.io/oauth2/userInfo+GET https://auth.example.localhost.floci.io/login+GET https://auth.example.localhost.floci.io/logout```Requests are matched on the `Host` header, so the name must resolve to Floci (any@@ -120,7 +123,8 @@ the account that created it, since these requests carry no AWS credential: a `clanother 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-domainURLs when one exists. Prefix domains (`<prefix>.auth.<region>.amazoncognito.com`) are stored but not-routed, since that hostname never reaches Floci. `/login` and `/logout` are not served on any host.+routed, since that hostname never reaches Floci. `/login` and `/logout` are served at the root only+on a custom-domain host; on Floci's own host they are `/cognito-idp/login` and `/cognito-idp/logout`.With TLS enabled, a custom domain (`CustomDomainConfig` set) is added to Floci's servercertificate as soon as it is created, so `https://<domain>` verifies without a restart; see@@ -280,8 +284,8 @@ up, so an oversized request naming something that does not exist reports the reqproblem rather than `ResourceNotFoundException`, and an update violating both reports themin one message with the asset list first.-Branding is presentation for the hosted UI, which Floci does not serve, so it is stored-and returned rather than rendered. Two divergences follow from that:+Branding is presentation for the managed login pages. Floci's sign-in page is deliberately+plain, so branding is stored and returned rather than rendered. Two divergences follow from that:- **`Settings` is stored opaquely.** AWS validates it against a deep schema, rejectingunknown properties with `Invalid settings provided. Validation errors: [{property:@@ -302,20 +306,106 @@ 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 |-| `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/authorize` | Authorization-code start endpoint, for managed login and OIDC |+| `GET /cognito-idp/oauth2/idpresponse` | OIDC provider callback endpoint |+| `GET`, `POST /cognito-idp/login` | Managed login sign-in form |+| `GET /cognito-idp/logout` | Managed login sign-out |+| `POST /cognito-idp/oauth2/token` | OAuth authorization-code and client-credentials token endpoint |++The OAuth endpoints support browser-style authorization-code sign-in, for the pool's own+users and through a federated OIDC provider, as well as the emulator-friendly+client-credentials flow:++- `GET /cognito-idp/oauth2/authorize` validates the app client and callback. With no+ `identity_provider`, or `identity_provider=COGNITO`, it starts managed login (below);+ with any other provider name it redirects to that OIDC provider with an opaque state and nonce.- `GET /cognito-idp/oauth2/idpresponse` consumes the provider state, exchanges the providercode 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+- `POST /cognito-idp/oauth2/token` redeems that authorization code once, checking its PKCE+ `code_verifier` when the authorization request sent a `code_challenge`, or issues a machinetoken for `grant_type=client_credentials`.+### Managed login++Managed login signs in the pool's own users with authorization code and, optionally, PKCE.+The client needs `COGNITO` in `SupportedIdentityProviders`, `AllowedOAuthFlows=["code"]` and+the callback in `CallbackURLs`. No domain is needed; on a custom domain the same flow runs at+`/oauth2/authorize`, `/login` and `/logout`.++1. `GET /cognito-idp/oauth2/authorize` redirects to `/cognito-idp/login` with the request's+ parameters. If the browser already has a managed login session in the pool, it skips the+ form and redirects straight to the callback with a code, as AWS does.+2. `GET /cognito-idp/login` renders a plain username and password form. The form carries the+ request in hidden fields and a CSRF token that must match the `XSRF-TOKEN` cookie set with it.+3. `POST /cognito-idp/login` checks the password as `USER_PASSWORD_AUTH` does, including+ sign-in aliases and the pre and post authentication and user migration triggers, but+ without the client's `ExplicitAuthFlows`. On success it sets a `cognito` session cookie+ (one hour) and redirects to the callback with `code` and `state`. A wrong password shows+ the form again with `Incorrect username or password.`; an unknown user reads the same.+4. `POST /cognito-idp/oauth2/token` redeems the code. The ID token carries the request's+ `nonce`.+5. `GET /cognito-idp/logout?client_id=...&logout_uri=...` ends the session and redirects to+ `logout_uri`, which must be one of the client's `LogoutURLs`. With `redirect_uri` and+ `response_type=code` instead of `logout_uri`, it ends the session and redirects to the+ sign-in form for that request.++PKCE follows AWS: `code_challenge_method` must be `S256`, and discovery advertises+`code_challenge_methods_supported: ["S256"]`. A code issued with a `code_challenge` is+redeemed only with the matching `code_verifier`, so a public client (no secret) can use it+alone. A code issued without one is refused if a `code_verifier` is sent, as RFC 9700+recommends. A failed PKCE check spends the code; a request naming the wrong client or+`redirect_uri` does not. PKCE applies to federated OIDC sign-in too.++Differences from AWS:++- **No challenge pages.** A user who must change or reset their password, or who is not+ confirmed, sees an error on the form instead. Sign-up, forgot-password, MFA and passkey+ pages are not served, and `prompt`, `login_hint`, `lang` and `idp_identifier` are ignored.+- **Errors are JSON.** An authorization request error returns `400` with an OAuth error body,+ even after `redirect_uri` is validated, where AWS redirects the error to the callback.+- **Relative redirect.** The redirect from `/oauth2/authorize` to the sign-in form has a+ relative `Location`, where AWS's is absolute.+- **One session cookie per host.** Floci's own host serves every pool, so signing in to a+ second pool there replaces the first pool's session. Custom domains keep separate sessions,+ as on AWS. Sessions are held in memory and are lost on restart.+- **No PreTokenGeneration on code redemption.** As with federated sign-in, the token endpoint+ does not invoke the pre token generation trigger.++```bash+EP=http://localhost:4566+POOL_ID=$(aws --endpoint-url $EP cognito-idp create-user-pool --pool-name web \+ --query UserPool.Id --output text)+CLIENT_ID=$(aws --endpoint-url $EP cognito-idp create-user-pool-client --user-pool-id $POOL_ID \+ --client-name spa --supported-identity-providers COGNITO \+ --allowed-o-auth-flows-user-pool-client --allowed-o-auth-flows code \+ --allowed-o-auth-scopes openid email --callback-urls https://app.example.com/cb \+ --logout-urls https://app.example.com/ --query UserPoolClient.ClientId --output text)+aws --endpoint-url $EP cognito-idp admin-create-user --user-pool-id $POOL_ID --username alice+aws --endpoint-url $EP cognito-idp admin-set-user-password --user-pool-id $POOL_ID \+ --username alice --password 'Perm1234!' --permanent++# PKCE pair: verifier, and its unpadded base64url SHA-256 challenge+VERIFIER=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=\n')+CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')++# Open the sign-in form, then post the credentials with its CSRF token+Q="response_type=code&client_id=$CLIENT_ID&redirect_uri=https%3A%2F%2Fapp.example.com%2Fcb&scope=openid&state=s1&code_challenge=$CHALLENGE&code_challenge_method=S256"+CSRF=$(curl -s -c jar "$EP/cognito-idp/login?$Q" | sed -n 's/.*name="_csrf" value="\([^"]*\)".*/\1/p')+CODE=$(curl -s -b jar -c jar -o /dev/null -w '%{redirect_url}' "$EP/cognito-idp/login?$Q" \+ --data-urlencode "_csrf=$CSRF" --data-urlencode username=alice --data-urlencode 'password=Perm1234!' \+ | sed -n 's/.*[?&]code=\([^&]*\).*/\1/p')++# Redeem the code with the verifier+curl -s -X POST "$EP/cognito-idp/oauth2/token" \+ --data-urlencode grant_type=authorization_code --data-urlencode client_id=$CLIENT_ID \+ --data-urlencode code=$CODE --data-urlencode redirect_uri=https://app.example.com/cb \+ --data-urlencode code_verifier=$VERIFIER++# Sign out+curl -s -b jar -o /dev/null -w '%{http_code} %{redirect_url}\n' \+ "$EP/cognito-idp/logout?client_id=$CLIENT_ID&logout_uri=https%3A%2F%2Fapp.example.com%2F"+```+`POST /cognito-idp/oauth2/token` is intentionally emulator-friendly rather than full Cognito parity:- It requires an existing `client_id`.diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.javaindex 3f93c5fd97..15e9d54917 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java@@ -44,6 +44,8 @@ final class CognitoAuthFlowHandler {private static final Logger LOG = Logger.getLogger(CognitoAuthFlowHandler.class);private static final ObjectMapper MAPPER = new ObjectMapper();private static final String CUSTOM_MESSAGE_CODE_PARAMETER = "{####}";+ /** The message of a wrong password, which managed login also shows for an unknown user. */+ static final String INCORRECT_CREDENTIALS = "Incorrect username or password";private final CognitoService service;private final LambdaService lambdaService;@@ -285,6 +287,41 @@ final class CognitoAuthFlowHandler {if (password == null) throw new AwsException("InvalidParameterException", "PASSWORD is required", 400);validateSecretHash(client, params, username);+ CognitoUser user = verifyPassword(pool, client, username, password, clientMetadata);++ if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {+ return buildNewPasswordRequiredChallenge(pool, client, user);+ }++ Map<String, Object> result = new HashMap<>();+ result.put("AuthenticationResult",+ issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata));+ return result;+ }++ /**+ * Managed login's username and password sign-in: the checks of USER_PASSWORD_AUTH, without the+ * client's {@code ExplicitAuthFlows} or a {@code SECRET_HASH}, neither of which managed login+ * uses. It issues no tokens, since the token endpoint redeems the authorization code for them,+ * and it refuses a user who would get a challenge, because the sign-in page answers none.+ */+ CognitoUser authenticateManagedLogin(UserPool pool, UserPoolClient client, String username, String password) {+ CognitoUser user = verifyPassword(pool, client, username, password, Map.of());+ if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {+ throw new AwsException("NotAuthorizedException", "This user must set a new password, which this "+ + "sign-in page does not support. Set a permanent password with AdminSetUserPassword.", 400);+ }+ firePostAuthentication(pool, client, user, Map.of(), false);+ return user;+ }++ /**+ * The credential check USER_PASSWORD_AUTH and managed login share: finds the user by username or+ * alias, or through the UserMigration trigger, fires PreAuthentication, refuses a user who cannot+ * sign in, and compares the password.+ */+ private CognitoUser verifyPassword(UserPool pool, UserPoolClient client, String username, String password,+ Map<String, String> clientMetadata) {CognitoUser user;try {user = service.adminGetUser(pool.getId(), username);@@ -305,17 +342,9 @@ final class CognitoAuthFlowHandler {throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400);}if (user.getPasswordHash() == null || !user.getPasswordHash().equals(service.hashPassword(password))) {- throw new AwsException("NotAuthorizedException", "Incorrect username or password", 400);- }-- if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) {- return buildNewPasswordRequiredChallenge(pool, client, user);+ throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);}-- Map<String, Object> result = new HashMap<>();- result.put("AuthenticationResult",- issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata));- return result;+ return user;}private Map<String, Object> handleRefreshToken(UserPool pool, UserPoolClient client,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.javaindex a81f560557..7993ad8a84 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@@ -14,13 +14,15 @@ import org.jboss.logging.Logger;import java.net.URI;import java.util.Optional;+import java.util.Set;/*** Routes Cognito custom-domain requests by Host. On AWS a custom domain serves- * {@code https://<domain>/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.+ * {@code https://<domain>/oauth2/token}, {@code /oauth2/userInfo}, {@code /oauth2/authorize},+ * {@code /oauth2/idpresponse}, and managed login's {@code /login} and {@code /logout}; Floci maps+ * those onto the {@code /cognito-idp/...} handlers and pins the pool and the account that own the+ * domain, since the request itself carries no AWS credential. On any other host these paths are+ * left alone, so {@code /login} stays an S3 bucket path and {@code /logout} the SSO portal's.*/@Provider@PreMatching@@ -36,7 +38,8 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {private static final Logger LOG = Logger.getLogger(CognitoCustomDomainFilter.class);private static final String OAUTH_PREFIX = "/oauth2/";- private static final String TARGET_PREFIX = "/cognito-idp/oauth2/";+ private static final Set<String> MANAGED_LOGIN_PATHS = Set.of("/login", "/logout");+ private static final String TARGET_PREFIX = "/cognito-idp";private final CognitoService cognitoService;@@ -49,7 +52,7 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {public void filter(ContainerRequestContext requestContext) {URI originalUri = requestContext.getUriInfo().getRequestUri();String path = originalUri.getRawPath();- if (path == null || !path.startsWith(OAUTH_PREFIX)) {+ if (path == null || !(path.startsWith(OAUTH_PREFIX) || MANAGED_LOGIN_PATHS.contains(path))) {return;}String host = RequestHost.of(requestContext);@@ -62,7 +65,7 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {}URI newUri = UriBuilder.fromUri(originalUri)- .replacePath(TARGET_PREFIX + path.substring(OAUTH_PREFIX.length()))+ .replacePath(TARGET_PREFIX + path).build();LOG.debugv("Cognito custom domain routing: {0}{1} -> {2}", host, path, newUri.getPath());requestContext.setProperty(POOL_PROPERTY, domain.get().getUserPoolId());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.javaindex 06470cc5fc..f4b52b78f8 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationService.java@@ -42,19 +42,24 @@ public class CognitoFederationService {public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List<String> scopes,String nonce, String providerName) {- return beginAuthorization(userPoolId, clientId, redirectUri, scopes, nonce, providerName, null);+ return beginAuthorization(userPoolId, clientId, redirectUri, scopes, nonce, providerName, null, null);}+ /**+ * @param codeChallenge the relying party's S256 PKCE challenge, or null. It stays with Cognito:+ * the relying party proves it at Cognito's token endpoint, not the provider's.+ */public String beginAuthorization(String userPoolId, String clientId, String redirectUri, List<String> scopes,- String nonce, String providerName, String relyingPartyState) {+ String nonce, String providerName, String relyingPartyState,+ String codeChallenge) {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);+ CognitoAuthorizationTransaction transaction = new CognitoAuthorizationTransaction(userPoolId, clientId,+ redirectUri, scopes, nonce, providerName, relyingPartyState, codeChallenge, expiresAt);String state = stateStore.putTransaction(transaction);Map<String, String> parameters = new LinkedHashMap<>();@@ -89,7 +94,8 @@ public class CognitoFederationService {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));+ transaction.scopes(), transaction.nonce(), transaction.codeChallenge(),+ clock.instant().plus(AUTHORIZATION_CODE_LIFETIME));return stateStore.putAuthorizationCode(authorizationCode);}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.javaindex ee35192bb1..654466e557 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStore.java@@ -2,6 +2,7 @@ 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 io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;import jakarta.enterprise.context.ApplicationScoped;import java.security.SecureRandom;@@ -20,6 +21,7 @@ public class CognitoFederationStateStore {private final ConcurrentHashMap<String, CognitoAuthorizationTransaction> transactions = new ConcurrentHashMap<>();private final ConcurrentHashMap<String, CognitoAuthorizationCode> authorizationCodes = new ConcurrentHashMap<>();+ private final ConcurrentHashMap<String, CognitoManagedLoginSession> sessions = new ConcurrentHashMap<>();private final Clock clock;private final SecureRandom secureRandom = new SecureRandom();@@ -44,15 +46,33 @@ public class CognitoFederationStateStore {}public Optional<CognitoAuthorizationCode> findAuthorizationCode(String code) {- CognitoAuthorizationCode authorizationCode = authorizationCodes.get(code);- if (authorizationCode == null) {+ return find(authorizationCodes, code, CognitoAuthorizationCode::expiresAt);+ }++ /** Stores a managed login session and returns its id, the value of the browser's session cookie. */+ public String putSession(CognitoManagedLoginSession session) {+ return put(sessions, session);+ }++ /** A session id comes from a cookie, so a missing one is simply no session. */+ public Optional<CognitoManagedLoginSession> findSession(String sessionId) {+ if (sessionId == null) {return Optional.empty();}- if (isExpired(authorizationCode.expiresAt())) {- authorizationCodes.remove(code, authorizationCode);- return Optional.empty();+ return find(sessions, sessionId, CognitoManagedLoginSession::expiresAt);+ }++ public void deleteSession(String sessionId) {+ if (sessionId != null) {+ sessions.remove(sessionId);}- return Optional.of(authorizationCode);+ }++ /** A random value in the form of this store's keys, for tokens that are not stored, such as the CSRF token. */+ String generateOpaqueKey() {+ byte[] bytes = new byte[OPAQUE_KEY_BYTES];+ secureRandom.nextBytes(bytes);+ return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);}private <T> String put(ConcurrentHashMap<String, T> store, T value) {@@ -63,6 +83,18 @@ public class CognitoFederationStateStore {return key;}+ private <T> Optional<T> find(ConcurrentHashMap<String, T> store, String key, Function<T, Instant> expiresAt) {+ T value = store.get(key);+ if (value == null) {+ return Optional.empty();+ }+ if (isExpired(expiresAt.apply(value))) {+ store.remove(key, value);+ return Optional.empty();+ }+ return Optional.of(value);+ }+private <T> Optional<T> consume(ConcurrentHashMap<String, T> store, String key,Function<T, Instant> expiresAt) {AtomicReference<T> consumed = new AtomicReference<>();@@ -78,10 +110,4 @@ public class CognitoFederationStateStore {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/CognitoManagedLoginService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.javanew file mode 100644index 0000000000..a8731e4871--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginService.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.services.cognito;++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.CognitoManagedLoginSession;+import io.github.hectorvent.floci.services.cognito.model.CognitoUser;+import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Clock;+import java.time.Duration;+import java.util.List;+import java.util.Optional;++/**+ * Managed login for a pool's own users: signs a user in with their password, keeps the browser's+ * session, and issues the authorization codes that {@code /oauth2/token} redeems.+ * {@link CognitoFederationService} does the same for users of an external identity provider.+ */+@ApplicationScoped+public class CognitoManagedLoginService {++ /** AWS: "The authorization code is valid for five minutes." */+ private static final Duration AUTHORIZATION_CODE_LIFETIME = Duration.ofMinutes(5);+ /** How long AWS keeps a managed login session. */+ static final Duration SESSION_LIFETIME = Duration.ofHours(1);++ private static final Logger LOG = Logger.getLogger(CognitoManagedLoginService.class);++ private final CognitoService cognitoService;+ private final CognitoFederationStateStore stateStore;+ private final Clock clock;++ @Inject+ public CognitoManagedLoginService(CognitoService cognitoService, CognitoFederationStateStore stateStore,+ Clock clock) {+ this.cognitoService = cognitoService;+ this.stateStore = stateStore;+ this.clock = clock;+ }++ /**+ * Signs a user in to the client's pool with their password and opens a session for them.+ *+ * @return the session's id, the value of the browser's session cookie+ * @throws AwsException when the user cannot sign in, with the reason in its message+ */+ public String signIn(UserPoolClient client, String username, String password) {+ CognitoUser user = cognitoService.authenticateManagedLogin(client, username, password);+ return stateStore.putSession(new CognitoManagedLoginSession(+ client.getUserPoolId(), user.getUsername(), clock.instant().plus(SESSION_LIFETIME)));+ }++ /**+ * Issues an authorization code to the user of the browser's session, or nothing when there is+ * no session for the client's pool. Every pool's session travels in the same cookie on Floci's+ * own host, so a session of one pool must never sign its user in to another.+ */+ public Optional<String> issueAuthorizationCode(String sessionId, UserPoolClient client, String redirectUri,+ List<String> scopes, String nonce, String codeChallenge) {+ Optional<CognitoManagedLoginSession> session = stateStore.findSession(sessionId)+ .filter(candidate -> candidate.userPoolId().equals(client.getUserPoolId()));+ if (session.isEmpty()) {+ return Optional.empty();+ }+ if (!canStillSignIn(session.get())) {+ stateStore.deleteSession(sessionId);+ return Optional.empty();+ }+ CognitoAuthorizationCode code = new CognitoAuthorizationCode(client.getUserPoolId(), client.getClientId(),+ session.get().username(), redirectUri, scopes, nonce, codeChallenge,+ clock.instant().plus(AUTHORIZATION_CODE_LIFETIME));+ return Optional.of(stateStore.putAuthorizationCode(code));+ }++ /**+ * Ends the browser's session in the pool, and says whether its cookie can go too: not while it+ * holds a live session of another pool, which is not this pool's to end.+ */+ public boolean signOut(String sessionId, String userPoolId) {+ Optional<CognitoManagedLoginSession> session = stateStore.findSession(sessionId);+ if (session.isPresent() && !session.get().userPoolId().equals(userPoolId)) {+ return false;+ }+ stateStore.deleteSession(sessionId);+ return true;+ }++ /** A session outlives neither its user nor AdminDisableUser, after which the user cannot sign in. */+ private boolean canStillSignIn(CognitoManagedLoginSession session) {+ try {+ return cognitoService.adminGetUser(session.userPoolId(), session.username()).isEnabled();+ } catch (AwsException e) {+ LOG.debugv("Ending the managed login session of {0} in pool {1}: {2}",+ session.username(), session.userPoolId(), e.getMessage());+ return false;+ }+ }+}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.javaindex f38f1cf835..a6b088e70e 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@@ -11,6 +11,7 @@ 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.CookieParam;import jakarta.ws.rs.GET;import jakarta.ws.rs.HeaderParam;import jakarta.ws.rs.POST;@@ -19,6 +20,7 @@ import jakarta.ws.rs.QueryParam;import jakarta.ws.rs.Produces;import jakarta.ws.rs.container.ContainerRequestContext;import jakarta.ws.rs.core.Context;+import jakarta.ws.rs.core.HttpHeaders;import jakarta.ws.rs.core.MediaType;import jakarta.ws.rs.core.MultivaluedMap;import jakarta.ws.rs.core.Response;@@ -28,12 +30,14 @@ import java.net.URI;import java.net.URLEncoder;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;+import java.security.NoSuchAlgorithmException;import java.util.ArrayList;import java.util.Base64;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Optional;+import java.util.regex.Pattern;@ApplicationScoped@Path("/")@@ -42,21 +46,42 @@ public class CognitoOAuthController {private static final Logger LOG = Logger.getLogger(CognitoOAuthController.class);+ /** The {@code identity_provider} value, and the SupportedIdentityProviders entry, of the pool's own users. */+ private static final String COGNITO_PROVIDER = "COGNITO";+ /** AWS's managed login cookie names: the session, and the CSRF token that the sign-in form echoes. */+ private static final String SESSION_COOKIE = "cognito";+ private static final String CSRF_COOKIE = "XSRF-TOKEN";+ private static final String CSRF_FIELD = "_csrf";+ /** The only PKCE method Cognito accepts; its challenge is an unpadded base64url SHA-256 hash. */+ private static final String PKCE_METHOD = "S256";+ private static final Pattern CODE_CHALLENGE_PATTERN = Pattern.compile("[A-Za-z0-9_-]{43}");+ /** RFC 7636 section 4.1: 43 to 128 characters of the unreserved set. */+ private static final Pattern CODE_VERIFIER_PATTERN = Pattern.compile("[A-Za-z0-9._~-]{43,128}");+private final CognitoService cognitoService;private final ObjectMapper objectMapper;private final CognitoFederationService federationService;private final CognitoFederationStateStore stateStore;+ private final CognitoManagedLoginService managedLoginService;@Injectpublic CognitoOAuthController(CognitoService cognitoService, ObjectMapper objectMapper,CognitoFederationService federationService,- CognitoFederationStateStore stateStore) {+ CognitoFederationStateStore stateStore,+ CognitoManagedLoginService managedLoginService) {this.cognitoService = cognitoService;this.objectMapper = objectMapper;this.federationService = federationService;this.stateStore = stateStore;+ this.managedLoginService = managedLoginService;}+ /**+ * Without an {@code identity_provider}, or with {@code COGNITO}, signs in one of the pool's own+ * users through managed login; any other value names an external provider to federate with.+ * A client that does not list COGNITO cannot use managed login, even when it supports exactly+ * one other provider: the caller names that provider instead.+ */@GET@Path("/cognito-idp/oauth2/authorize")public Response authorize(@Context ContainerRequestContext requestContext,@@ -66,38 +91,172 @@ public class CognitoOAuthController {@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");+ @QueryParam("state") String relyingPartyState,+ @QueryParam("code_challenge") String codeChallenge,+ @QueryParam("code_challenge_method") String codeChallengeMethod,+ @CookieParam(SESSION_COOKIE) String sessionId) {+ AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope,+ relyingPartyState, nonce, codeChallenge, codeChallengeMethod);+ String provider = trimToNull(providerName);+ if (provider == null || COGNITO_PROVIDER.equals(provider)) {+ return authorizeWithManagedLogin(requestContext, request, sessionId);}- UserPoolClient client;+ AuthorizationCheck check = checkAuthorizationRequest(requestContext, request);+ if (check.error() != null) {+ return check.error();+ }try {- client = cognitoService.findClientById(clientId);+ String location = federationService.beginAuthorization(check.client().getUserPoolId(), clientId,+ redirectUri, splitScopes(scope), trimToNull(nonce), providerName, relyingPartyState,+ trimToNull(codeChallenge));+ return Response.status(Response.Status.FOUND).location(URI.create(location)).build();} 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");+ return oauthError("invalid_request", e.getMessage());}- if (!client.getCallbackURLs().contains(redirectUri)) {- return oauthError("invalid_request", "redirect_uri is not registered for this client");+ }++ /**+ * AWS skips the sign-in form for a browser that already has a session in the pool, and otherwise+ * redirects to the login endpoint with the request's parameters.+ */+ private Response authorizeWithManagedLogin(ContainerRequestContext requestContext, AuthorizationRequest request,+ String sessionId) {+ AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);+ if (check.error() != null) {+ return check.error();+ }+ Optional<String> code = issueAuthorizationCode(sessionId, check.client(), request);+ if (code.isPresent()) {+ return redirectWithCode(request, code.get());+ }+ return Response.status(Response.Status.FOUND)+ .header(HttpHeaders.LOCATION, loginPath(requestContext) + "?" + formEncode(request.parameters()))+ .build();+ }++ @GET+ @Path("/cognito-idp/login")+ @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})+ public Response loginPage(@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("state") String state,+ @QueryParam("code_challenge") String codeChallenge,+ @QueryParam("code_challenge_method") String codeChallengeMethod) {+ AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope, state,+ nonce, codeChallenge, codeChallengeMethod);+ AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);+ if (check.error() != null) {+ return check.error();+ }+ return signInPage(requestContext, request, Response.Status.OK, null);+ }++ /**+ * Signs the user in and redirects to the callback with a code. A failed sign-in shows the form+ * again with the reason; a missing or wrong CSRF token shows it with a fresh token instead.+ */+ @POST+ @Path("/cognito-idp/login")+ @Consumes(MediaType.APPLICATION_FORM_URLENCODED)+ @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})+ public Response login(@Context ContainerRequestContext requestContext,+ @CookieParam(CSRF_COOKIE) String csrfCookie,+ MultivaluedMap<String, String> formParams) {+ // The form carries the request in hidden fields. AWS's own form posts it in the query string+ // instead, so a script that replays AWS's form by posting only the credentials works too.+ AuthorizationRequest request = AuthorizationRequest.from(formParams.containsKey("client_id")+ ? formParams : requestContext.getUriInfo().getQueryParameters());+ AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);+ if (check.error() != null) {+ return check.error();+ }+ if (!csrfTokenMatches(csrfCookie, formParams.getFirst(CSRF_FIELD))) {+ return signInPage(requestContext, request, Response.Status.FORBIDDEN,+ "Your sign-in page expired. Sign in again.");+ }+ String username = formParams.getFirst("username");+ String password = formParams.getFirst("password");+ if (trimToNull(username) == null || password == null || password.isEmpty()) {+ return signInPage(requestContext, request, Response.Status.BAD_REQUEST,+ "Enter your username and password.");}+ String sessionId;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();+ sessionId = managedLoginService.signIn(check.client(), username, password);} catch (AwsException e) {- return oauthError("invalid_request", e.getMessage());+ return signInPage(requestContext, request, Response.Status.BAD_REQUEST, signInError(e));}+ Optional<String> code = issueAuthorizationCode(sessionId, check.client(), request);+ if (code.isEmpty()) {+ return signInPage(requestContext, request, Response.Status.BAD_REQUEST,+ CognitoAuthFlowHandler.INCORRECT_CREDENTIALS);+ }+ return Response.fromResponse(redirectWithCode(request, code.get()))+ .header(HttpHeaders.SET_COOKIE, cookie(SESSION_COOKIE, sessionId,+ CognitoManagedLoginService.SESSION_LIFETIME.toSeconds(), isHttps(requestContext)))+ .build();+ }++ /**+ * Signs the browser out of managed login. With {@code logout_uri}, which wins when both are+ * given, redirects there and nowhere else, as AWS does; with {@code redirect_uri}, redirects to+ * the login endpoint with the request's authorization parameters so the user signs in again.+ * A session cookie of another pool is left as it is: on AWS that pool has its own domain.+ */+ @GET+ @Path("/cognito-idp/logout")+ public Response logout(@Context ContainerRequestContext requestContext,+ @QueryParam("client_id") String clientId,+ @QueryParam("logout_uri") String logoutUri,+ @QueryParam("redirect_uri") String redirectUri,+ @QueryParam("response_type") String responseType,+ @QueryParam("scope") String scope,+ @QueryParam("nonce") String nonce,+ @QueryParam("state") String state,+ @QueryParam("code_challenge") String codeChallenge,+ @QueryParam("code_challenge_method") String codeChallengeMethod,+ @CookieParam(SESSION_COOKIE) String sessionId) {+ UserPoolClient client;+ Response redirect;+ if (trimToNull(logoutUri) != null) {+ if (trimToNull(clientId) == null) {+ return oauthError("invalid_request", "client_id is required");+ }+ AuthorizationCheck check = lookUpClient(requestContext, clientId);+ if (check.error() != null) {+ return check.error();+ }+ if (!check.client().getLogoutURLs().contains(logoutUri)) {+ return oauthError("invalid_request", "logout_uri is not registered for this client");+ }+ client = check.client();+ redirect = Response.status(Response.Status.FOUND).location(URI.create(logoutUri)).build();+ } else if (trimToNull(redirectUri) != null) {+ AuthorizationRequest request = new AuthorizationRequest(responseType, clientId, redirectUri, scope,+ state, nonce, codeChallenge, codeChallengeMethod);+ AuthorizationCheck check = checkManagedLoginRequest(requestContext, request);+ if (check.error() != null) {+ return check.error();+ }+ client = check.client();+ redirect = Response.status(Response.Status.FOUND)+ .header(HttpHeaders.LOCATION, loginPath(requestContext) + "?" + formEncode(request.parameters()))+ .build();+ } else {+ return oauthError("invalid_request", "logout_uri or redirect_uri is required");+ }+ if (!managedLoginService.signOut(sessionId, client.getUserPoolId())) {+ return redirect;+ }+ return Response.fromResponse(redirect)+ .header(HttpHeaders.SET_COOKIE, cookie(SESSION_COOKIE, "", 0L, isHttps(requestContext)))+ .build();}@GET@@ -249,10 +408,17 @@ public class CognitoOAuthController {return oauthError("invalid_grant", "Authorization code is invalid or has expired");}CognitoAuthorizationCode consumedCode = consumed.get();+ // Checked after the code is spent: a code that fails its PKCE check may have been intercepted,+ // so it gets no second attempt, unlike a request that names the wrong client or redirect_uri.+ String pkceError = pkceError(consumedCode.codeChallenge(), trimToNull(formParams.getFirst("code_verifier")));+ if (pkceError != null) {+ return oauthError("invalid_grant", pkceError);+ }try {UserPool pool = cognitoService.describeUserPool(consumedCode.userPoolId());CognitoUser user = cognitoService.adminGetUser(consumedCode.userPoolId(), consumedCode.userId());- Map<String, Object> authentication = cognitoService.generateAuthResult(user, pool, client, null);+ Map<String, Object> authentication = cognitoService.generateAuthResult(user, pool, client,+ nonceClaim(consumedCode.nonce()));ObjectNode body = objectMapper.createObjectNode();body.put("access_token", (String) authentication.get("AccessToken"));body.put("id_token", (String) authentication.get("IdToken"));@@ -268,18 +434,254 @@ public class CognitoOAuthController {}private Response redirect(String redirectUri, Map<String, String> parameters) {- StringBuilder location = new StringBuilder(redirectUri);- location.append(redirectUri.contains("?") ? '&' : '?');- boolean first = true;+ String location = redirectUri + (redirectUri.contains("?") ? '&' : '?') + formEncode(parameters);+ return Response.status(Response.Status.FOUND).location(URI.create(location)).build();+ }++ private static String formEncode(Map<String, String> parameters) {+ StringBuilder query = new StringBuilder();for (Map.Entry<String, String> parameter : parameters.entrySet()) {- if (!first) {- location.append('&');+ if (!query.isEmpty()) {+ query.append('&');}- location.append(URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8));- location.append('=').append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8));- first = false;+ query.append(URLEncoder.encode(parameter.getKey(), StandardCharsets.UTF_8));+ query.append('=').append(URLEncoder.encode(parameter.getValue(), StandardCharsets.UTF_8));+ }+ return query.toString();+ }++ private Response redirectWithCode(AuthorizationRequest request, String code) {+ Map<String, String> parameters = new LinkedHashMap<>();+ parameters.put("code", code);+ if (request.state() != null) {+ parameters.put("state", request.state());+ }+ return redirect(request.redirectUri(), parameters);+ }++ private Optional<String> issueAuthorizationCode(String sessionId, UserPoolClient client,+ AuthorizationRequest request) {+ return managedLoginService.issueAuthorizationCode(sessionId, client, request.redirectUri(),+ splitScopes(request.scope()), trimToNull(request.nonce()), trimToNull(request.codeChallenge()));+ }++ /**+ * The checks every authorization request passes, for managed login and federation alike. Errors+ * are 400 JSON, including those found after redirect_uri is known to be registered, where AWS+ * redirects the error to it instead.+ */+ private AuthorizationCheck checkAuthorizationRequest(ContainerRequestContext requestContext,+ AuthorizationRequest request) {+ if (!"code".equals(trimToNull(request.responseType()))) {+ return AuthorizationCheck.rejected(+ oauthError("unsupported_response_type", "Only response_type=code is supported"));+ }+ if (trimToNull(request.clientId()) == null || trimToNull(request.redirectUri()) == null) {+ return AuthorizationCheck.rejected(oauthError("invalid_request", "client_id and redirect_uri are required"));+ }+ AuthorizationCheck check = lookUpClient(requestContext, request.clientId());+ if (check.error() != null) {+ return check;+ }+ UserPoolClient client = check.client();+ if (!client.isAllowedOAuthFlowsUserPoolClient() || !client.getAllowedOAuthFlows().contains("code")) {+ return AuthorizationCheck.rejected(+ oauthError("unauthorized_client", "Client is not allowed to use the authorization code flow"));+ }+ if (!client.getCallbackURLs().contains(request.redirectUri())) {+ return AuthorizationCheck.rejected(+ oauthError("invalid_request", "redirect_uri is not registered for this client"));}- return Response.status(Response.Status.FOUND).location(URI.create(location.toString())).build();+ String pkceError = pkceRequestError(request);+ if (pkceError != null) {+ return AuthorizationCheck.rejected(oauthError("invalid_request", pkceError));+ }+ return check;+ }++ /** An authorization request that managed login answers, at the authorize, login, and logout endpoints. */+ private AuthorizationCheck checkManagedLoginRequest(ContainerRequestContext requestContext,+ AuthorizationRequest request) {+ AuthorizationCheck check = checkAuthorizationRequest(requestContext, request);+ if (check.error() == null && !check.client().getSupportedIdentityProviders().contains(COGNITO_PROVIDER)) {+ return AuthorizationCheck.rejected(+ oauthError("invalid_request", "COGNITO is not a supported identity provider for this client"));+ }+ return check;+ }++ /** As on AWS, a client of another pool does not exist on a pool's custom domain. */+ private AuthorizationCheck lookUpClient(ContainerRequestContext requestContext, String clientId) {+ UserPoolClient client;+ try {+ client = cognitoService.findClientById(clientId);+ } catch (AwsException e) {+ return AuthorizationCheck.rejected(oauthError("invalid_client", "Client not found"));+ }+ String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY);+ if (domainPoolId != null && !domainPoolId.equals(client.getUserPoolId())) {+ return AuthorizationCheck.rejected(oauthError("invalid_client", "Client not found"));+ }+ return new AuthorizationCheck(client, null);+ }++ /** Why the request's PKCE parameters are unusable, or null when it has none or valid ones. */+ private String pkceRequestError(AuthorizationRequest request) {+ String challenge = trimToNull(request.codeChallenge());+ String method = trimToNull(request.codeChallengeMethod());+ if (challenge == null) {+ return method == null ? null : "code_challenge is required with code_challenge_method";+ }+ if (!PKCE_METHOD.equals(method)) {+ return "code_challenge_method must be S256";+ }+ if (!CODE_CHALLENGE_PATTERN.matcher(challenge).matches()) {+ return "code_challenge must be the unpadded base64url encoding of a SHA-256 hash";+ }+ return null;+ }++ /**+ * RFC 7636 section 4.6 with S256, or null when the verifier proves the challenge. A verifier sent+ * for a code issued without a challenge is refused, as RFC 9700 section 2.1.1 requires, so a code+ * obtained without PKCE cannot be injected into a client's PKCE flow.+ */+ static String pkceError(String codeChallenge, String codeVerifier) {+ if (codeChallenge == null) {+ return codeVerifier == null ? null+ : "code_verifier was sent for an authorization code issued without a code_challenge";+ }+ if (codeVerifier == null) {+ return "code_verifier is required for this authorization code";+ }+ if (!CODE_VERIFIER_PATTERN.matcher(codeVerifier).matches()) {+ return "code_verifier must be 43 to 128 unreserved characters";+ }+ byte[] computed = Base64.getUrlEncoder().withoutPadding()+ .encode(sha256(codeVerifier.getBytes(StandardCharsets.US_ASCII)));+ if (!MessageDigest.isEqual(computed, codeChallenge.getBytes(StandardCharsets.US_ASCII))) {+ return "code_verifier does not match the code_challenge";+ }+ return null;+ }++ private static byte[] sha256(byte[] value) {+ try {+ return MessageDigest.getInstance("SHA-256").digest(value);+ } catch (NoSuchAlgorithmException e) {+ throw new IllegalStateException("SHA-256 is required for PKCE", e);+ }+ }++ /** AWS puts the authorization request's nonce in the ID token. */+ private static CognitoService.ClaimsOverride nonceClaim(String nonce) {+ if (nonce == null) {+ return null;+ }+ return new CognitoService.ClaimsOverride(Map.of("nonce", nonce), null, null, null, null, null, null, null,+ null);+ }++ /** Managed login's endpoints are served at the root of a custom domain, and under /cognito-idp elsewhere. */+ private static String loginPath(ContainerRequestContext requestContext) {+ return requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY) != null+ ? "/login" : "/cognito-idp/login";+ }++ /**+ * The sign-in form, deliberately plain: a username, a password, and the authorization request in+ * hidden fields. Each rendering sets a fresh CSRF token cookie that the form echoes back.+ */+ private Response signInPage(ContainerRequestContext requestContext, AuthorizationRequest request,+ Response.Status status, String error) {+ String csrfToken = stateStore.generateOpaqueKey();+ List<String> hiddenFields = new ArrayList<>();+ for (Map.Entry<String, String> parameter : request.parameters().entrySet()) {+ hiddenFields.add(" <input type=\"hidden\" name=\"" + escapeHtml(parameter.getKey())+ + "\" value=\"" + escapeHtml(parameter.getValue()) + "\">");+ }+ String page = """+ <!doctype html>+ <html lang="en">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>Sign in</title>+ </head>+ <body>+ <main>+ <h1>Sign in</h1>+ %s+ <form method="post" action="%s">+ <input type="hidden" name="%s" value="%s">+ %s+ <label for="username">Username</label>+ <input id="username" name="username" type="text" autocomplete="username" autocapitalize="none" required>+ <label for="password">Password</label>+ <input id="password" name="password" type="password" autocomplete="current-password" required>+ <button type="submit">Sign in</button>+ </form>+ </main>+ </body>+ </html>+ """.formatted(error == null ? "" : " <p role=\"alert\">" + escapeHtml(error) + "</p>",+ escapeHtml(loginPath(requestContext)), CSRF_FIELD, escapeHtml(csrfToken),+ String.join("\n", hiddenFields));+ // No form-action directive: browsers apply it to the redirect after the form is submitted,+ // which goes to the client's callback on another origin.+ return Response.status(status)+ .type(MediaType.TEXT_HTML)+ .entity(page)+ .header(HttpHeaders.CACHE_CONTROL, "no-store")+ .header("Referrer-Policy", "no-referrer")+ .header("X-Content-Type-Options", "nosniff")+ .header("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'none'")+ .header(HttpHeaders.SET_COOKIE, cookie(CSRF_COOKIE, csrfToken, null, isHttps(requestContext)))+ .build();+ }++ /** The reason a sign-in failed, as the form shows it. An unknown user reads the same as a wrong password. */+ private static String signInError(AwsException e) {+ if ("UserNotFoundException".equals(e.getErrorCode())) {+ return CognitoAuthFlowHandler.INCORRECT_CREDENTIALS;+ }+ return e.getMessage();+ }++ private static boolean csrfTokenMatches(String cookieToken, String formToken) {+ if (cookieToken == null || cookieToken.isEmpty() || formToken == null) {+ return false;+ }+ return MessageDigest.isEqual(cookieToken.getBytes(StandardCharsets.UTF_8),+ formToken.getBytes(StandardCharsets.UTF_8));+ }++ /**+ * A managed login cookie: host-only, sent on every path, hidden from scripts, left off cross-site+ * subrequests, and Secure on HTTPS. A null {@code maxAgeSeconds} lasts until the browser closes.+ */+ private static String cookie(String name, String value, Long maxAgeSeconds, boolean secure) {+ StringBuilder cookie = new StringBuilder(name).append('=').append(value).append("; Path=/");+ if (maxAgeSeconds != null) {+ cookie.append("; Max-Age=").append(maxAgeSeconds);+ }+ cookie.append("; HttpOnly; SameSite=Lax");+ if (secure) {+ cookie.append("; Secure");+ }+ return cookie.toString();+ }++ private static boolean isHttps(ContainerRequestContext requestContext) {+ return "https".equalsIgnoreCase(requestContext.getUriInfo().getRequestUri().getScheme());+ }++ private static String escapeHtml(String value) {+ return value.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace("\"", """)+ .replace("'", "'");}private boolean secretsEqual(String expected, String actual) {@@ -359,4 +761,45 @@ public class CognitoOAuthController {private record BasicCredentials(String clientId, String clientSecret) {}++ /** The authorization request that managed login carries from the authorize endpoint to the sign-in form and back. */+ private record AuthorizationRequest(String responseType, String clientId, String redirectUri, String scope,+ String state, String nonce, String codeChallenge,+ String codeChallengeMethod) {++ static AuthorizationRequest from(MultivaluedMap<String, String> parameters) {+ return new AuthorizationRequest(parameters.getFirst("response_type"), parameters.getFirst("client_id"),+ parameters.getFirst("redirect_uri"), parameters.getFirst("scope"), parameters.getFirst("state"),+ parameters.getFirst("nonce"), parameters.getFirst("code_challenge"),+ parameters.getFirst("code_challenge_method"));+ }++ /** The parameters the request carried, in the order of AWS's redirect to the login endpoint. */+ Map<String, String> parameters() {+ Map<String, String> parameters = new LinkedHashMap<>();+ putIfPresent(parameters, "response_type", responseType);+ putIfPresent(parameters, "client_id", clientId);+ putIfPresent(parameters, "redirect_uri", redirectUri);+ putIfPresent(parameters, "scope", scope);+ putIfPresent(parameters, "state", state);+ putIfPresent(parameters, "nonce", nonce);+ putIfPresent(parameters, "code_challenge", codeChallenge);+ putIfPresent(parameters, "code_challenge_method", codeChallengeMethod);+ return parameters;+ }++ private static void putIfPresent(Map<String, String> parameters, String name, String value) {+ if (value != null) {+ parameters.put(name, value);+ }+ }+ }++ /** The client an authorization request names, or the error response that rejects the request. */+ private record AuthorizationCheck(UserPoolClient client, Response error) {++ static AuthorizationCheck rejected(Response error) {+ return new AuthorizationCheck(null, error);+ }+ }}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.javaindex e1721b1381..d76171832c 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@@ -2722,6 +2722,12 @@ public class CognitoService implements ResourceProvider {return authFlowHandler.adminInitiateAuth(userPoolId, clientId, authFlow, authParameters, clientMetadata);}+ /** Managed login's username and password check; see {@link CognitoAuthFlowHandler#authenticateManagedLogin}. */+ CognitoUser authenticateManagedLogin(UserPoolClient client, String username, String password) {+ return authFlowHandler.authenticateManagedLogin(describeUserPool(client.getUserPoolId()), client,+ username, password);+ }+public Map<String, Object> respondToAuthChallenge(String clientId, String challengeName,String session, Map<String, String> responses) {return authFlowHandler.respondToAuthChallenge(clientId, challengeName, session, responses, Map.of());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.javaindex d3bae7b8e5..1d91b8936a 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@@ -66,7 +66,7 @@ public class CognitoWellKnownController {String authorizationEndpoint = tokenEndpoint.replace("/token", "/authorize");String body = """- {"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"]}+ {"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"],"code_challenge_methods_supported":["S256"]}""".formatted(issuer, jwksUri, authorizationEndpoint, tokenEndpoint, userInfoEndpoint).strip();return Response.ok(body).build();}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.javaindex f71fc8a1ad..d13c47311a 100644--- 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@@ -3,12 +3,19 @@ package io.github.hectorvent.floci.services.cognito.model;import java.time.Instant;import java.util.List;+/**+ * A one-time authorization code. {@code nonce} and {@code codeChallenge} are the authorization+ * request's values, or null when it sent none; the token endpoint puts the nonce in the ID token+ * and requires a matching {@code code_verifier} when there is a challenge.+ */public record CognitoAuthorizationCode(String userPoolId,String clientId,String userId,String redirectUri,List<String> scopes,+ String nonce,+ String codeChallenge,Instant expiresAt) {public CognitoAuthorizationCode {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.javaindex 1c2482a0bf..5f8e11f505 100644--- 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@@ -11,6 +11,7 @@ public record CognitoAuthorizationTransaction(String nonce,String providerName,String relyingPartyState,+ String codeChallenge,Instant expiresAt) {public CognitoAuthorizationTransaction {diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.javanew file mode 100644index 0000000000..9c70d3b03f--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoManagedLoginSession.java@@ -0,0 +1,10 @@+package io.github.hectorvent.floci.services.cognito.model;++import java.time.Instant;++/**+ * A browser's managed login session, which lets {@code /oauth2/authorize} skip the sign-in form.+ * {@code username} is the user's canonical username, not the alias they typed.+ */+public record CognitoManagedLoginSession(String userPoolId, String username, Instant expiresAt) {+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.javaindex d5a59d7902..57e0d413a4 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomDomainFilterTest.java@@ -47,15 +47,45 @@ class CognitoCustomDomainFilterTest {verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp/oauth2/userInfo"));}+ @Test+ void rewritesManagedLoginPathsOnACustomDomainAndPinsThePool() {+ when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));+ for (String path : new String[] {"/login", "/logout"}) {+ ContainerRequestContext request = request("https://" + DOMAIN + path + "?client_id=c&state=a%26b", DOMAIN);++ filter.filter(request);++ verify(request).setProperty(CognitoCustomDomainFilter.POOL_PROPERTY, "us-east-1_abc");+ verify(request).setProperty(AccountContextFilter.PINNED_ACCOUNT_PROPERTY, ACCOUNT);+ verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp" + path + "?client_id=c&state=a%26b"));+ }+ }+@Testvoid leavesOtherPathsAlone() {- ContainerRequestContext request = request("http://" + DOMAIN + "/cognito-idp/oauth2/token", DOMAIN);+ for (String path : new String[] {"/cognito-idp/oauth2/token", "/login/", "/loginx", "/logout/x", "/signup"}) {+ ContainerRequestContext request = request("http://" + DOMAIN + path, DOMAIN);- filter.filter(request);+ filter.filter(request);+ verify(request, never()).setRequestUri(any());+ verify(request, never()).setProperty(any(), any());+ }verifyNoInteractions(cognitoService);- verify(request, never()).setRequestUri(any());- verify(request, never()).setProperty(any(), any());+ }++ /** Without a custom domain, /login is an S3 bucket path and /logout the SSO portal's. */+ @Test+ void leavesManagedLoginPathsOfOtherHostsAlone() {+ when(cognitoService.findCustomDomain("localhost")).thenReturn(Optional.empty());+ for (String path : new String[] {"/login", "/logout"}) {+ ContainerRequestContext request = request("http://localhost:4566" + path, "localhost:4566");++ filter.filter(request);++ verify(request, never()).setRequestUri(any());+ verify(request, never()).setProperty(any(), any());+ }}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.javaindex c45e033465..3bfa5eedd8 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java@@ -137,12 +137,28 @@ class CognitoFederationServiceTest {String redirect = federationService.beginAuthorization(pool.getId(), "cognito-client", "https://application.example.test/callback",- List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state");+ List.of("openid"), "nonce-value", "ExampleOidc", "relying-party-state", null);CognitoAuthorizationTransaction transaction = stateStore.consumeTransaction(queryValue(redirect, "state")).orElseThrow();assertEquals("relying-party-state", transaction.relyingPartyState());}+ @Test+ void completeAuthorizationCarriesTheNonceAndCodeChallengeIntoTheCode() {+ createDefaultProvider();+ String challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";+ String redirect = federationService.beginAuthorization(+ pool.getId(), "cognito-client", "https://application.example.test/callback",+ List.of("openid"), "nonce-value", "ExampleOidc", null, challenge);++ String authorizationCode = federationService.completeAuthorization(queryValue(redirect, "state"), "provider-code");++ CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(authorizationCode).orElseThrow();+ assertEquals("nonce-value", storedCode.nonce());+ assertEquals(challenge, storedCode.codeChallenge());+ assertFalse(redirect.contains(challenge), "the challenge stays with Cognito: " + redirect);+ }+@Testvoid completeAuthorizationRejectsNonOidcProvider() {createProvider("ExampleGoogle", "Google", Map.of(@@ -389,7 +405,7 @@ class CognitoFederationServiceTest {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)));+ List.of("openid"), "nonce-value", providerName, null, null, CLOCK.instant().plusSeconds(60)));}private String endpoint(String path) {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.javaindex 356afdcecc..064efb000b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationStateStoreTest.java@@ -2,6 +2,7 @@ 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 io.github.hectorvent.floci.services.cognito.model.CognitoManagedLoginSession;import org.junit.jupiter.api.Test;import java.lang.reflect.Field;@@ -121,6 +122,53 @@ class CognitoFederationStateStoreTest {assertTrue(store.consumeAuthorizationCode(code).isEmpty());}+ @Test+ void findSession_returnsStoredUnexpiredSessionUntilDeleted() {+ CognitoFederationStateStore store = storeAt(NOW);+ CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60));++ String sessionId = store.putSession(session);++ assertEquals(Optional.of(session), store.findSession(sessionId));+ assertEquals(Optional.of(session), store.findSession(sessionId));+ store.deleteSession(sessionId);+ assertTrue(store.findSession(sessionId).isEmpty());+ }++ @Test+ void findSession_expiredSessionReturnsEmptyAndIsRemoved() throws ReflectiveOperationException {+ MutableClock clock = new MutableClock(NOW);+ CognitoFederationStateStore store = new CognitoFederationStateStore(clock);+ String sessionId = store.putSession(new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60)));++ clock.set(NOW.plusSeconds(60));++ assertTrue(store.findSession(sessionId).isEmpty());+ assertTrue(storeMap(store, "sessions").isEmpty());+ }++ @Test+ void findSession_missingOrUnknownIdReturnsEmpty() {+ CognitoFederationStateStore store = storeAt(NOW);++ assertTrue(store.findSession(null).isEmpty());+ assertTrue(store.findSession("unknown").isEmpty());+ store.deleteSession(null);+ }++ @Test+ void putSession_idsAreOpaqueAndDistinct() {+ CognitoFederationStateStore store = storeAt(NOW);+ CognitoManagedLoginSession session = new CognitoManagedLoginSession("pool-id", "user", NOW.plusSeconds(60));++ String first = store.putSession(session);+ String second = store.putSession(session);++ assertFalse(first.equals(second));+ assertTrue(first.matches("[A-Za-z0-9_-]{43}"), first);+ assertFalse(first.contains("user") || first.contains("pool-id"));+ }+private CognitoFederationStateStore storeAt(Instant now) {return new CognitoFederationStateStore(Clock.fixed(now, ZoneOffset.UTC));}@@ -128,14 +176,14 @@ class CognitoFederationStateStoreTest {private CognitoAuthorizationTransaction transaction(Instant expiresAt) {return new CognitoAuthorizationTransaction("pool-id", "client-id", "https://example.com/callback", List.of("openid", "email"),- "nonce", "ExampleOidc", null, expiresAt+ "nonce", "ExampleOidc", null, 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+ null, null, expiresAt);}@@ -146,6 +194,13 @@ class CognitoFederationStateStoreTest {field.set(store, replacement);}+ private ConcurrentHashMap<?, ?> storeMap(CognitoFederationStateStore store, String fieldName)+ throws ReflectiveOperationException {+ Field field = CognitoFederationStateStore.class.getDeclaredField(fieldName);+ field.setAccessible(true);+ return (ConcurrentHashMap<?, ?>) field.get(store);+ }+private static final class MutableClock extends Clock {private Instant now;diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.javaindex 8675830da3..87c55ae72b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java@@ -675,6 +675,87 @@ class CognitoLambdaTriggersTest {// UserMigration// =========================================================================+ // =========================================================================+ // Managed login shares USER_PASSWORD_AUTH's password check and its triggers+ // =========================================================================++ @Test+ void managedLoginFiresPreAndPostAuthenticationButIssuesNoTokens() {+ UserPool pool = createPoolWithLambdaConfig(Map.of(+ "PreAuthentication", "arn:aws:lambda:::pre",+ "PostAuthentication", "arn:aws:lambda:::post",+ "PreTokenGeneration", "arn:aws:lambda:::pretoken"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);+ when(lambdaService.invoke(anyString(), anyString(), any(byte[].class), any())).thenReturn(ok(Map.of()));++ CognitoUser user = service.authenticateManagedLogin(client, "alice", "Perm1234!");++ assertEquals("alice", user.getUsername());+ verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any());+ verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());+ verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::pretoken"), any(byte[].class), any());+ }++ @Test+ void managedLoginPreAuthenticationErrorBlocksSignIn() {+ UserPool pool = createPoolWithLambdaConfig(Map.of(+ "PreAuthentication", "arn:aws:lambda:::pre",+ "PostAuthentication", "arn:aws:lambda:::post"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))+ .thenReturn(lambdaError("Unhandled", "Email not verified"));++ AwsException ex = assertThrows(AwsException.class,+ () -> service.authenticateManagedLogin(client, "alice", "Perm1234!"));++ assertEquals("PreAuthentication failed with error Email not verified.", ex.getMessage());+ verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());+ }++ @Test+ void managedLoginMigratesAMissingUser() {+ UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate"));+ UserPoolClient client = createClient(pool);+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::migrate"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("userAttributes", Map.of("email", "[email protected]"),+ "finalUserStatus", "CONFIRMED")));++ CognitoUser user = service.authenticateManagedLogin(client, "newcomer", "MyPassword1!");++ assertEquals("newcomer", user.getUsername());+ assertEquals("[email protected]", service.adminGetUser(pool.getId(), "newcomer").getAttributes().get("email"));+ }++ /** Managed login needs neither ALLOW_USER_PASSWORD_AUTH nor a SECRET_HASH for a client with a secret. */+ @Test+ void managedLoginIgnoresExplicitAuthFlowsAndSecretHash() {+ UserPool pool = createPoolWithLambdaConfig(Map.of());+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", true, false, List.of(), List.of(),+ null, List.of(), null, List.of("ALLOW_REFRESH_TOKEN_AUTH"), null, null, List.of(), null, List.of(),+ null, null, null, List.of(), null, null);++ assertThrows(AwsException.class, () -> service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));+ assertEquals("alice", service.authenticateManagedLogin(client, "alice", "Perm1234!").getUsername());+ }++ @Test+ void managedLoginRefusesAUserWhoMustSetANewPassword() {+ UserPool pool = createPoolWithLambdaConfig(Map.of("PostAuthentication", "arn:aws:lambda:::post"));+ service.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), "Temp1234!");+ UserPoolClient client = createClient(pool);++ AwsException ex = assertThrows(AwsException.class,+ () -> service.authenticateManagedLogin(client, "alice", "Temp1234!"));++ assertEquals("NotAuthorizedException", ex.getErrorCode());+ assertTrue(ex.getMessage().contains("must set a new password"), ex.getMessage());+ verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());+ }+@Test@SuppressWarnings("unchecked")void userMigrationCreatesAndAuthenticatesMissingUser() {diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.javanew file mode 100644index 0000000000..525e13d0c0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java@@ -0,0 +1,621 @@+package io.github.hectorvent.floci.services.cognito;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.response.Response;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.net.URI;+import java.net.URLDecoder;+import java.nio.charset.StandardCharsets;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain;+import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload;+import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;+import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;+import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.startsWith;+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.assertTrue;++/**+ * Managed login for a pool's own users, driven over HTTP the way a browser drives it:+ * {@code /oauth2/authorize} redirects to the sign-in form, the form posts the credentials, the+ * callback receives a code, and {@code /oauth2/token} redeems it, with PKCE, the session cookie+ * that skips the form, and {@code /logout}.+ */+@QuarkusTest+class CognitoManagedLoginIntegrationTest {++ private static final String CALLBACK = "https://app.example.test/callback";+ private static final String SIGNED_OUT = "https://app.example.test/signed-out";+ private static final String PASSWORD = "Perm1234!";+ /** RFC 7636 appendix B. */+ private static final String VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";+ private static final String CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";+ private static final String INCORRECT_CREDENTIALS = "Incorrect username or password";+ private static final Pattern HIDDEN_FIELD = Pattern.compile("<input type=\"hidden\" name=\"([^\"]*)\" value=\"([^\"]*)\">");+ private static final Pattern FORM_ACTION = Pattern.compile("<form method=\"post\" action=\"([^\"]*)\">");++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @Test+ void authorizeWithoutIdentityProviderRedirectsToTheLoginPageWithTheRequest() throws Exception {+ Pool pool = newPool();++ for (String provider : new String[] {null, "COGNITO"}) {+ Map<String, String> query = authorizeRequest(pool.clientId());+ if (provider != null) {+ query.put("identity_provider", provider);+ }+ String location = browserGet(null, "/cognito-idp/oauth2/authorize", query, null)+ .then().statusCode(302).extract().header("Location");++ assertEquals("/cognito-idp/login", URI.create(location).getPath());+ query.remove("identity_provider");+ assertEquals(query, queryOf(location));+ }+ }++ @Test+ void loginPageRendersAPlainFormAndEscapesTheState() throws Exception {+ Pool pool = newPool();+ Map<String, String> query = authorizeRequest(pool.clientId());+ query.put("state", "\"><script>alert(1)</script>");++ Response page = browserGet(null, "/cognito-idp/login", query, null);++ page.then().statusCode(200)+ .contentType(startsWith("text/html"))+ .header("Cache-Control", equalTo("no-store"))+ .header("X-Content-Type-Options", equalTo("nosniff"))+ .header("Content-Security-Policy", equalTo("default-src 'none'; base-uri 'none'; frame-ancestors 'none'"));+ String html = page.asString();+ assertTrue(html.contains("name=\"username\""), html);+ assertTrue(html.contains("name=\"password\" type=\"password\""), html);+ assertFalse(html.contains("<script>"), html);+ assertTrue(html.contains("value=\""><script>alert(1)</script>\""), html);+ assertEquals("/cognito-idp/login", formAction(html));+ Map<String, String> fields = hiddenFields(html);+ assertEquals(query.get("state"), fields.get("state"));+ assertEquals(CHALLENGE, fields.get("code_challenge"));+ String csrfCookie = setCookie(page, "XSRF-TOKEN");+ assertTrue(csrfCookie.contains("; Path=/; HttpOnly; SameSite=Lax"), csrfCookie);+ assertEquals(page.getCookie("XSRF-TOKEN"), fields.get("_csrf"));+ }++ @Test+ void wrongPasswordOrUnknownUserShowsTheSameErrorWithoutACodeOrSession() throws Exception {+ Pool pool = newPool();++ for (String username : new String[] {pool.username(), "nobody-" + System.nanoTime()}) {+ Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));+ Response failed = submit(null, page, username, "Wrong1234!");++ failed.then().statusCode(400).contentType(startsWith("text/html"));+ assertNull(failed.getHeader("Location"));+ assertNull(setCookie(failed, "cognito"));+ assertTrue(failed.asString().contains("<p role=\"alert\">" + INCORRECT_CREDENTIALS + "</p>"), failed.asString());+ assertNotNull(hiddenFields(failed.asString()).get("_csrf"), "the form is shown again");+ }+ }++ @Test+ void signInWithoutTheCsrfTokenOrWithAnotherIsRejected() throws Exception {+ Pool pool = newPool();+ Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()));+ Map<String, String> fields = hiddenFields(page.asString());++ Response withoutCookie = given().redirects().follow(false)+ .formParams(fields).formParam("username", pool.username()).formParam("password", PASSWORD)+ .when().post("/cognito-idp/login");+ Response otherToken = given().redirects().follow(false)+ .cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))+ .formParams(withField(fields, "_csrf", "forged-token"))+ .formParam("username", pool.username()).formParam("password", PASSWORD)+ .when().post("/cognito-idp/login");+ Response withoutField = given().redirects().follow(false)+ .cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))+ .formParams(withField(fields, "_csrf", null))+ .formParam("username", pool.username()).formParam("password", PASSWORD)+ .when().post("/cognito-idp/login");++ for (Response rejected : List.of(withoutCookie, otherToken, withoutField)) {+ rejected.then().statusCode(403).body(containsString("<p role=\"alert\">"));+ assertNull(rejected.getHeader("Location"));+ assertNull(setCookie(rejected, "cognito"));+ }+ }++ @Test+ void signInRedirectsToTheCallbackWithACodeTheStateAndASessionCookie() throws Exception {+ Pool pool = newPool();++ Response signedIn = signIn(null, pool, authorizeRequest(pool.clientId()));++ signedIn.then().statusCode(302);+ String location = signedIn.getHeader("Location");+ assertTrue(location.startsWith(CALLBACK + "?code="), location);+ assertEquals("client-state", queryOf(location).get("state"));+ String sessionCookie = setCookie(signedIn, "cognito");+ assertTrue(sessionCookie.matches("cognito=[A-Za-z0-9_-]{43}; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax"),+ sessionCookie);+ }++ /** The client allows only refresh: USER_PASSWORD_AUTH is refused, yet managed login signs in. */+ @Test+ void managedLoginDoesNotDependOnTheClientsExplicitAuthFlows() throws Exception {+ Pool pool = newPool();++ cognitoAction("InitiateAuth", """+ {"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH","AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}+ """.formatted(pool.clientId(), pool.username(), PASSWORD)).then().statusCode(400);+ signIn(null, pool, authorizeRequest(pool.clientId())).then().statusCode(302);+ }++ @Test+ void codeRedeemsWithTheVerifierForTokensOfTheSignedInUser() throws Exception {+ Pool pool = newPool();+ String code = code(signIn(null, pool, authorizeRequest(pool.clientId())));++ Response tokens = redeem(null, pool.clientId(), code, VERIFIER);++ tokens.then().statusCode(200).body("token_type", equalTo("Bearer"));+ JsonNode idToken = jwtPayload(tokens.path("id_token"));+ assertEquals(pool.sub(), idToken.path("sub").asText());+ assertEquals(pool.username(), idToken.path("cognito:username").asText());+ assertEquals("client-nonce", idToken.path("nonce").asText());+ assertEquals(pool.clientId(), idToken.path("aud").asText());+ JsonNode accessToken = jwtPayload(tokens.path("access_token"));+ assertEquals(pool.username(), accessToken.path("username").asText());+ assertFalse(accessToken.has("nonce"));+ }++ @Test+ void codeIsRefusedWithAWrongOrMissingVerifierAndAWrongOneSpendsIt() throws Exception {+ Pool pool = newPool();+ Response signedIn = signIn(null, pool, authorizeRequest(pool.clientId()));+ String session = signedIn.getCookie("cognito");+ String wrongVerifierCode = code(signedIn);+ String missingVerifierCode = code(browserGet(null, "/cognito-idp/oauth2/authorize",+ authorizeRequest(pool.clientId()), session));++ redeem(null, pool.clientId(), wrongVerifierCode, VERIFIER.replace('d', 'e'))+ .then().statusCode(400).body("error", equalTo("invalid_grant"));+ redeem(null, pool.clientId(), wrongVerifierCode, VERIFIER)+ .then().statusCode(400).body("error", equalTo("invalid_grant"));+ redeem(null, pool.clientId(), missingVerifierCode, null)+ .then().statusCode(400).body("error", equalTo("invalid_grant"));+ }++ @Test+ void codeCannotBeRedeemedTwice() throws Exception {+ Pool pool = newPool();+ String code = code(signIn(null, pool, authorizeRequest(pool.clientId())));++ redeem(null, pool.clientId(), code, VERIFIER).then().statusCode(200);+ redeem(null, pool.clientId(), code, VERIFIER).then().statusCode(400).body("error", equalTo("invalid_grant"));+ }++ @Test+ void codeWithoutPkceRedeemsWithoutAVerifierButNotWithOne() throws Exception {+ Pool pool = newPool();+ Map<String, String> query = authorizeRequest(pool.clientId());+ query.remove("code_challenge");+ query.remove("code_challenge_method");+ Response signedIn = signIn(null, pool, query);+ String withVerifier = code(browserGet(null, "/cognito-idp/oauth2/authorize", query, signedIn.getCookie("cognito")));++ redeem(null, pool.clientId(), code(signedIn), null).then().statusCode(200);+ redeem(null, pool.clientId(), withVerifier, VERIFIER).then().statusCode(400).body("error", equalTo("invalid_grant"));+ }++ @Test+ void plainOrMissingCodeChallengeMethodIsRejected() throws Exception {+ Pool pool = newPool();++ for (String method : new String[] {"plain", null}) {+ Map<String, String> query = authorizeRequest(pool.clientId());+ query.remove("code_challenge_method");+ if (method != null) {+ query.put("code_challenge_method", method);+ }+ browserGet(null, "/cognito-idp/oauth2/authorize", query, null)+ .then().statusCode(400).body("error", equalTo("invalid_request"));+ }+ }++ @Test+ void authorizeWithTheSessionCookieSkipsTheForm() throws Exception {+ Pool pool = newPool();+ String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");+ Map<String, String> query = authorizeRequest(pool.clientId());+ query.put("state", "second-state");++ Response again = browserGet(null, "/cognito-idp/oauth2/authorize", query, session);++ again.then().statusCode(302);+ assertEquals("second-state", queryOf(again.getHeader("Location")).get("state"));+ assertTrue(again.getHeader("Location").startsWith(CALLBACK + "?code="));+ JsonNode idToken = jwtPayload(redeem(null, pool.clientId(), code(again), VERIFIER)+ .then().statusCode(200).extract().path("id_token"));+ assertEquals(pool.username(), idToken.path("cognito:username").asText());+ }++ @Test+ void sessionCookieOfAnotherPoolNeitherSignsInNorSignsOutThere() throws Exception {+ Pool poolA = newPool();+ Pool poolB = newPool();+ String sessionOfA = signIn(null, poolA, authorizeRequest(poolA.clientId())).getCookie("cognito");++ String location = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(poolB.clientId()), sessionOfA)+ .then().statusCode(302).extract().header("Location");+ assertTrue(location.startsWith("/cognito-idp/login?"), location);++ Response logoutOfB = browserGet(null, "/cognito-idp/logout",+ Map.of("client_id", poolB.clientId(), "logout_uri", SIGNED_OUT), sessionOfA);+ logoutOfB.then().statusCode(302).header("Location", equalTo(SIGNED_OUT));+ assertNull(setCookie(logoutOfB, "cognito"), "the browser keeps pool A's cookie");+ String stillSignedIn = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(poolA.clientId()),+ sessionOfA).then().statusCode(302).extract().header("Location");+ assertTrue(stillSignedIn.startsWith(CALLBACK + "?code="), stillSignedIn);+ }++ @Test+ void logoutWithAnUnregisteredLogoutUriIsRejected() throws Exception {+ Pool pool = newPool();++ browserGet(null, "/cognito-idp/logout",+ Map.of("client_id", pool.clientId(), "logout_uri", "https://evil.example.test/"), null)+ .then().statusCode(400).body("error", equalTo("invalid_request"));+ browserGet(null, "/cognito-idp/logout", Map.of("client_id", pool.clientId()), null)+ .then().statusCode(400).body("error", equalTo("invalid_request"));+ }++ @Test+ void logoutEndsTheSessionClearsTheCookieAndRedirectsToTheLogoutUri() throws Exception {+ Pool pool = newPool();+ String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");++ Response logout = browserGet(null, "/cognito-idp/logout",+ Map.of("client_id", pool.clientId(), "logout_uri", SIGNED_OUT), session);++ logout.then().statusCode(302).header("Location", equalTo(SIGNED_OUT));+ assertEquals("cognito=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", setCookie(logout, "cognito"));+ String location = browserGet(null, "/cognito-idp/oauth2/authorize", authorizeRequest(pool.clientId()), session)+ .then().statusCode(302).extract().header("Location");+ assertTrue(location.startsWith("/cognito-idp/login?"), "the old cookie no longer signs in: " + location);+ }++ @Test+ void logoutWithRedirectUriSendsTheUserBackToSignIn() throws Exception {+ Pool pool = newPool();+ String session = signIn(null, pool, authorizeRequest(pool.clientId())).getCookie("cognito");+ Map<String, String> query = new LinkedHashMap<>();+ query.put("response_type", "code");+ query.put("client_id", pool.clientId());+ query.put("redirect_uri", CALLBACK);+ query.put("state", "after-logout");++ Response logout = browserGet(null, "/cognito-idp/logout", query, session);++ logout.then().statusCode(302);+ assertEquals("/cognito-idp/login", URI.create(logout.getHeader("Location")).getPath());+ assertEquals(query, queryOf(logout.getHeader("Location")));+ assertEquals("cognito=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", setCookie(logout, "cognito"));+ browserGet(null, "/cognito-idp/logout", withField(query, "redirect_uri", "https://evil.example.test/"), null)+ .then().statusCode(400).body("error", equalTo("invalid_request"));+ }++ @Test+ void clientWithoutCognitoAmongItsProvidersCannotUseManagedLogin() throws Exception {+ String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"FederatedOnlyPool\"}").path("UserPool").path("Id").asText();+ cognitoJson("CreateIdentityProvider", """+ {"UserPoolId":"%s","ProviderName":"ExampleOidc","ProviderType":"OIDC",+ "ProviderDetails":{"authorize_url":"https://idp.example.test/authorize","client_id":"idp-client","attributes_request_method":"GET","oidc_issuer":"https://idp.example.test"}}+ """.formatted(poolId));+ String clientId = cognitoJson("CreateUserPoolClient", """+ {"UserPoolId":"%s","ClientName":"federated-only","AllowedOAuthFlowsUserPoolClient":true,+ "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid"],"CallbackURLs":["%s"],+ "SupportedIdentityProviders":["ExampleOidc"]}+ """.formatted(poolId, CALLBACK)).path("UserPoolClient").path("ClientId").asText();+ Map<String, String> query = authorizeRequest(clientId);++ browserGet(null, "/cognito-idp/oauth2/authorize", query, null)+ .then().statusCode(400).body("error", equalTo("invalid_request"));+ browserGet(null, "/cognito-idp/login", query, null)+ .then().statusCode(400).body("error", equalTo("invalid_request"));+ }++ @Test+ void emailUsernamePoolSignsInByEmail() throws Exception {+ String poolId = cognitoJson("CreateUserPool", """+ {"PoolName":"EmailUsernamePool","UsernameAttributes":["email"]}+ """).path("UserPool").path("Id").asText();+ String clientId = codeClient(poolId);+ String email = "alias-" + System.nanoTime() + "@example.com";+ Pool pool = withUser(poolId, clientId, email);+ assertFalse(pool.username().equals(email), "the canonical username of an email pool is generated");++ Response signedIn = signIn(null, new Pool(poolId, clientId, email, pool.sub()), authorizeRequest(clientId));++ JsonNode idToken = jwtPayload(redeem(null, clientId, code(signedIn), VERIFIER)+ .then().statusCode(200).extract().path("id_token"));+ assertEquals(pool.username(), idToken.path("cognito:username").asText());+ assertEquals(pool.sub(), idToken.path("sub").asText());+ assertEquals(email, idToken.path("email").asText());+ }++ @Test+ void userWhoMustSetANewPasswordIsToldWhy() throws Exception {+ String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"TemporaryPasswordPool\"}").path("UserPool").path("Id").asText();+ String clientId = codeClient(poolId);+ String username = "temporary-" + System.nanoTime();+ cognitoAction("AdminCreateUser", """+ {"UserPoolId":"%s","Username":"%s","TemporaryPassword":"Temp1234!"}+ """.formatted(poolId, username)).then().statusCode(200);++ Response page = loginPage(null, "/cognito-idp/oauth2/authorize", authorizeRequest(clientId));+ Response refused = submit(null, page, username, "Temp1234!");++ refused.then().statusCode(400).body(containsString("must set a new password"));+ assertNull(setCookie(refused, "cognito"));+ }++ /** AWS's own form posts the authorization request in the query string and only the credentials in the body. */+ @Test+ void signInAcceptsTheRequestInTheQueryStringAsAwsFormPostsIt() throws Exception {+ Pool pool = newPool();+ Map<String, String> query = authorizeRequest(pool.clientId());+ Response page = browserGet(null, "/cognito-idp/login", query, null);++ Response signedIn = given().redirects().follow(false)+ .cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))+ .queryParams(query)+ .formParam("_csrf", page.getCookie("XSRF-TOKEN"))+ .formParam("username", pool.username())+ .formParam("password", PASSWORD)+ .when().post("/cognito-idp/login");++ signedIn.then().statusCode(302);+ redeem(null, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200);+ }++ @Test+ void customDomainServesLoginAndLogoutAtItsRoot() throws Exception {+ Pool pool = newPool();+ String domain = "managed-login-" + System.nanoTime() + ".teos.localhost.floci.io";+ cognitoJson("CreateUserPoolDomain", customDomain(domain, pool.poolId(), requestCertificate(domain)));++ Response authorize = browserGet(domain, "/oauth2/authorize", authorizeRequest(pool.clientId()), null);+ String location = authorize.then().statusCode(302).extract().header("Location");+ assertEquals("/login", URI.create(location).getPath());+ Response page = follow(domain, location);+ page.then().statusCode(200);+ assertEquals("/login", formAction(page.asString()));+ Response signedIn = submit(domain, page, pool.username(), PASSWORD);+ signedIn.then().statusCode(302);+ redeem(domain, pool.clientId(), code(signedIn), VERIFIER).then().statusCode(200);++ Response logout = browserGet(domain, "/logout",+ Map.of("client_id", pool.clientId(), "logout_uri", SIGNED_OUT), signedIn.getCookie("cognito"));+ logout.then().statusCode(302).header("Location", equalTo(SIGNED_OUT));+ assertEquals("cognito=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", setCookie(logout, "cognito"));++ String anotherPoolsClient = newPool().clientId();+ browserGet(domain, "/login", authorizeRequest(anotherPoolsClient), null)+ .then().statusCode(400).body("error", equalTo("invalid_client"));+ }++ /** Without a custom domain Host, /login stays S3's path-style bucket route. */+ @Test+ void loginOnFlocisOwnHostIsNotManagedLogin() {+ given().redirects().follow(false)+ .when().get("/login")+ .then().statusCode(404).body(containsString("NoSuchBucket"));+ }++ @Test+ void discoveryAdvertisesS256() throws Exception {+ Pool pool = newPool();++ given().when().get("/" + pool.poolId() + "/.well-known/openid-configuration")+ .then().statusCode(200).body("code_challenge_methods_supported", equalTo(List.of("S256")));+ }++ // ──────────────────────────── Fixtures ────────────────────────────++ /** A pool with a confirmed user, and a public client that uses the code grant and allows only refresh. */+ private record Pool(String poolId, String clientId, String username, String sub) {+ }++ private static Pool newPool() throws Exception {+ String poolId = cognitoJson("CreateUserPool", "{\"PoolName\":\"ManagedLoginPool\"}").path("UserPool").path("Id").asText();+ return withUser(poolId, codeClient(poolId), "user-" + System.nanoTime());+ }++ private static String codeClient(String poolId) throws Exception {+ return cognitoJson("CreateUserPoolClient", """+ {"UserPoolId":"%s","ClientName":"managed-login","AllowedOAuthFlowsUserPoolClient":true,+ "AllowedOAuthFlows":["code"],"AllowedOAuthScopes":["openid","email"],"CallbackURLs":["%s"],+ "LogoutURLs":["%s"],"SupportedIdentityProviders":["COGNITO"],"ExplicitAuthFlows":["ALLOW_REFRESH_TOKEN_AUTH"]}+ """.formatted(poolId, CALLBACK, SIGNED_OUT)).path("UserPoolClient").path("ClientId").asText();+ }++ private static Pool withUser(String poolId, String clientId, String username) throws Exception {+ String email = username.contains("@") ? username : username + "@example.com";+ cognitoAction("AdminCreateUser", """+ {"UserPoolId":"%s","Username":"%s","UserAttributes":[{"Name":"email","Value":"%s"}]}+ """.formatted(poolId, username, email)).then().statusCode(200);+ cognitoAction("AdminSetUserPassword", """+ {"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}+ """.formatted(poolId, username, PASSWORD)).then().statusCode(200);+ JsonNode user = cognitoJson("AdminGetUser", """+ {"UserPoolId":"%s","Username":"%s"}+ """.formatted(poolId, username));+ String sub = null;+ for (JsonNode attribute : user.path("UserAttributes")) {+ if ("sub".equals(attribute.path("Name").asText())) {+ sub = attribute.path("Value").asText();+ }+ }+ return new Pool(poolId, clientId, user.path("Username").asText(), sub);+ }++ /** A PKCE authorization request, as a single-page app sends one. */+ private static Map<String, String> authorizeRequest(String clientId) {+ Map<String, String> query = new LinkedHashMap<>();+ query.put("response_type", "code");+ query.put("client_id", clientId);+ query.put("redirect_uri", CALLBACK);+ query.put("scope", "openid email");+ query.put("state", "client-state");+ query.put("nonce", "client-nonce");+ query.put("code_challenge", CHALLENGE);+ query.put("code_challenge_method", "S256");+ return query;+ }++ // ──────────────────────────── Browser ────────────────────────────++ private static Response browserGet(String host, String path, Map<String, String> query, String sessionCookie) {+ RequestSpecification request = given().redirects().follow(false).queryParams(query);+ if (host != null) {+ request.header("Host", host);+ }+ if (sessionCookie != null) {+ request.cookie("cognito", sessionCookie);+ }+ return request.when().get(path);+ }++ /** Follows a relative redirect, as a browser resolves it against the page's own origin. */+ private static Response follow(String host, String location) {+ URI uri = URI.create(location);+ assertFalse(uri.isAbsolute(), location);+ return browserGet(host, uri.getPath(), queryOf(location), null);+ }++ private static Response loginPage(String host, String authorizePath, Map<String, String> query) {+ String location = browserGet(host, authorizePath, query, null).then().statusCode(302).extract().header("Location");+ Response page = follow(host, location);+ page.then().statusCode(200);+ return page;+ }++ /** Submits the sign-in form the way a browser does: its hidden fields, its CSRF cookie, and the credentials. */+ private static Response submit(String host, Response page, String username, String password) {+ String html = page.asString();+ RequestSpecification request = given().redirects().follow(false)+ .cookie("XSRF-TOKEN", page.getCookie("XSRF-TOKEN"))+ .formParams(hiddenFields(html))+ .formParam("username", username)+ .formParam("password", password);+ if (host != null) {+ request.header("Host", host);+ }+ return request.when().post(formAction(html));+ }++ /** Signs a fresh browser in through the authorize endpoint and returns the redirect to the callback. */+ private static Response signIn(String host, Pool pool, Map<String, String> query) {+ Response page = loginPage(host, host == null ? "/cognito-idp/oauth2/authorize" : "/oauth2/authorize", query);+ return submit(host, page, pool.username(), PASSWORD);+ }++ private static Response redeem(String host, String clientId, String code, String verifier) {+ RequestSpecification request = given()+ .formParam("grant_type", "authorization_code")+ .formParam("client_id", clientId)+ .formParam("code", code)+ .formParam("redirect_uri", CALLBACK);+ if (verifier != null) {+ request.formParam("code_verifier", verifier);+ }+ if (host != null) {+ request.header("Host", host);+ }+ return request.when().post(host == null ? "/cognito-idp/oauth2/token" : "/oauth2/token");+ }++ private static String code(Response callbackRedirect) {+ callbackRedirect.then().statusCode(302);+ String code = queryOf(callbackRedirect.getHeader("Location")).get("code");+ assertNotNull(code, callbackRedirect.getHeader("Location"));+ return code;+ }++ // ──────────────────────────── Parsing ────────────────────────────++ /** The Set-Cookie header that sets {@code name}, or null. */+ private static String setCookie(Response response, String name) {+ for (String header : response.getHeaders().getValues("Set-Cookie")) {+ if (header.startsWith(name + "=")) {+ return header;+ }+ }+ return null;+ }++ private static Map<String, String> hiddenFields(String html) {+ Map<String, String> fields = new LinkedHashMap<>();+ Matcher matcher = HIDDEN_FIELD.matcher(html);+ while (matcher.find()) {+ fields.put(unescapeHtml(matcher.group(1)), unescapeHtml(matcher.group(2)));+ }+ return fields;+ }++ private static String formAction(String html) {+ Matcher matcher = FORM_ACTION.matcher(html);+ assertTrue(matcher.find(), html);+ return unescapeHtml(matcher.group(1));+ }++ private static String unescapeHtml(String value) {+ return value.replace("<", "<").replace(">", ">").replace(""", "\"").replace("'", "'")+ .replace("&", "&");+ }++ private static Map<String, String> queryOf(String location) {+ Map<String, String> parameters = new LinkedHashMap<>();+ String query = URI.create(location).getRawQuery();+ if (query == null) {+ return parameters;+ }+ for (String pair : query.split("&")) {+ String[] parts = pair.split("=", 2);+ parameters.put(URLDecoder.decode(parts[0], StandardCharsets.UTF_8),+ parts.length == 2 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : "");+ }+ return parameters;+ }++ /** A copy of {@code parameters} with {@code name} set to {@code value}, or removed when it is null. */+ private static Map<String, String> withField(Map<String, String> parameters, String name, String value) {+ Map<String, String> copy = new LinkedHashMap<>(parameters);+ if (value == null) {+ copy.remove(name);+ } else {+ copy.put(name, value);+ }+ return copy;+ }+}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.javaindex 31dcbd5899..60aeba183b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoOAuthControllerTest.java@@ -5,6 +5,7 @@ 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.CognitoManagedLoginSession;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;@@ -13,6 +14,9 @@ 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 org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;+import org.mockito.ArgumentCaptor;import java.nio.charset.StandardCharsets;import java.time.Clock;@@ -24,6 +28,7 @@ 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.assertNull;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;@@ -36,6 +41,8 @@ class CognitoOAuthControllerTest {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 static final String RFC_7636_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";+ private static final String RFC_7636_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";private final ObjectMapper objectMapper = new ObjectMapper();private final CognitoService cognitoService = mock(CognitoService.class);@@ -47,7 +54,9 @@ class CognitoOAuthControllerTest {@BeforeEachvoid setUp() {stateStore = new CognitoFederationStateStore(CLOCK);- controller = new CognitoOAuthController(cognitoService, objectMapper, federationService, stateStore);+ CognitoManagedLoginService managedLoginService = new CognitoManagedLoginService(cognitoService, stateStore, CLOCK);+ controller = new CognitoOAuthController(cognitoService, objectMapper, federationService, stateStore,+ managedLoginService);client = client();when(cognitoService.findClientById(CLIENT_ID)).thenReturn(client);}@@ -55,11 +64,11 @@ class CognitoOAuthControllerTest {@Testvoid authorizeRedirectsToConfiguredIdentityProvider() {when(federationService.beginAuthorization(POOL_ID, CLIENT_ID, CALLBACK_URI, List.of("openid"), "nonce", "ExampleOidc",- " relying-party-state "))+ " relying-party-state ", RFC_7636_CHALLENGE)).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 ");+ "ExampleOidc", " relying-party-state ", RFC_7636_CHALLENGE, "S256", null);assertEquals(302, response.getStatus());assertEquals("https://provider.example.test/authorize?state=provider-state", response.getHeaderString("Location"));@@ -71,7 +80,7 @@ class CognitoOAuthControllerTest {.thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400));Response response = controller.authorize(requestContext(null), "missing-client", CALLBACK_URI, "code", "openid", null,- "ExampleOidc", null);+ "ExampleOidc", null, null, null, null);assertOAuthError(response, "invalid_client");}@@ -79,18 +88,120 @@ class CognitoOAuthControllerTest {@Testvoid authorizeReturnsInvalidRequestForUnregisteredRedirectUri() {Response response = controller.authorize(requestContext(null), CLIENT_ID, "https://other.example.test/callback", "code", "openid",- null, "ExampleOidc", null);+ null, "ExampleOidc", null, null, null, null);assertOAuthError(response, "invalid_request");}@Testvoid authorizeReturnsUnsupportedResponseTypeForTokenResponse() {- Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc", null);+ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "token", "openid", null, "ExampleOidc",+ null, null, null, null);assertOAuthError(response, "unsupported_response_type");}+ @Test+ void authorizeWithoutIdentityProviderRedirectsToTheLoginEndpointWithTheRequest() {+ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid email",+ "nonce", null, "state & more", RFC_7636_CHALLENGE, "S256", null);++ assertEquals(302, response.getStatus());+ assertEquals("/cognito-idp/login?response_type=code&client_id=" + CLIENT_ID+ + "&redirect_uri=https%3A%2F%2Fapplication.example.test%2Fcallback&scope=openid+email"+ + "&state=state+%26+more&nonce=nonce&code_challenge=" + RFC_7636_CHALLENGE+ + "&code_challenge_method=S256",+ response.getHeaderString("Location"));+ }++ @Test+ void authorizeWithCognitoProviderOnACustomDomainRedirectsToItsLoginPath() {+ Response response = controller.authorize(requestContext(POOL_ID), CLIENT_ID, CALLBACK_URI, "code", null, null,+ "COGNITO", null, null, null, null);++ assertEquals(302, response.getStatus());+ assertEquals("/login?response_type=code&client_id=" + CLIENT_ID+ + "&redirect_uri=https%3A%2F%2Fapplication.example.test%2Fcallback", response.getHeaderString("Location"));+ }++ @Test+ void authorizeRejectsManagedLoginForAClientWithoutCognito() {+ client.setSupportedIdentityProviders(List.of("ExampleOidc"));++ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,+ null, null, null, null, null);++ assertOAuthError(response, "invalid_request");+ }++ @ParameterizedTest+ @CsvSource(nullValues = "null", value = {+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, plain",+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, null",+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM, s256",+ "null, S256",+ "too-short, S256",+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-c=, S256",+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cMx, S256"})+ void authorizeRejectsUnusablePkceParametersForEitherProvider(String challenge, String method) {+ for (String provider : new String[] {null, "ExampleOidc"}) {+ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", null,+ provider, null, challenge, method, null);++ assertOAuthError(response, "invalid_request");+ String description = ((JsonNode) response.getEntity()).path("error_description").asText();+ assertTrue(description.startsWith("code_challenge"), description);+ }+ }++ @Test+ void authorizeWithASessionOfThePoolRedirectsWithACodeCarryingTheNonceAndChallenge() {+ when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(user("session-user"));+ String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",+ CLOCK.instant().plusSeconds(60)));++ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", "openid", "nonce",+ null, "relying-party-state", RFC_7636_CHALLENGE, "S256", sessionId);++ assertEquals(302, response.getStatus());+ String location = response.getHeaderString("Location");+ assertTrue(location.startsWith(CALLBACK_URI + "?code="), location);+ assertTrue(location.endsWith("&state=relying-party-state"), location);+ String code = location.substring((CALLBACK_URI + "?code=").length(), location.indexOf("&state="));+ CognitoAuthorizationCode storedCode = stateStore.consumeAuthorizationCode(code).orElseThrow();+ assertEquals("session-user", storedCode.userId());+ assertEquals("nonce", storedCode.nonce());+ assertEquals(RFC_7636_CHALLENGE, storedCode.codeChallenge());+ }++ @Test+ void authorizeIgnoresASessionOfAnotherPool() {+ String sessionId = stateStore.putSession(new CognitoManagedLoginSession("us-east-1_other", "session-user",+ CLOCK.instant().plusSeconds(60)));++ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,+ null, null, null, null, sessionId);++ assertEquals(302, response.getStatus());+ assertTrue(response.getHeaderString("Location").startsWith("/cognito-idp/login?"));+ assertTrue(stateStore.findSession(sessionId).isPresent(), "another pool's session is left alone");+ }++ @Test+ void authorizeEndsTheSessionOfADisabledUser() {+ CognitoUser disabled = user("session-user");+ disabled.setEnabled(false);+ when(cognitoService.adminGetUser(POOL_ID, "session-user")).thenReturn(disabled);+ String sessionId = stateStore.putSession(new CognitoManagedLoginSession(POOL_ID, "session-user",+ CLOCK.instant().plusSeconds(60)));++ Response response = controller.authorize(requestContext(null), CLIENT_ID, CALLBACK_URI, "code", null, null,+ null, null, null, null, sessionId);++ assertTrue(response.getHeaderString("Location").startsWith("/cognito-idp/login?"));+ assertTrue(stateStore.findSession(sessionId).isEmpty());+ }+@Testvoid idpResponseReturnsInvalidRequestForUnknownState() {Response response = controller.idpResponse(requestContext(null), "unknown-state", "provider-code", null, null);@@ -124,7 +235,8 @@ class CognitoOAuthControllerTest {@Testvoid tokenRedeemsAuthorizationCodeOnce() throws Exception {String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(- POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60)));+ POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), null, null,+ 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)))@@ -148,7 +260,8 @@ class CognitoOAuthControllerTest {@Testvoid tokenRejectsAuthorizationCodeForAnotherClient() {String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(- POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60)));+ POOL_ID, "other-client", "federated-user", CALLBACK_URI, List.of("openid"), null, null,+ 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));@@ -216,14 +329,93 @@ class CognitoOAuthControllerTest {assertOAuthError(response, "invalid_request");}+ /** RFC 7636 appendix B: the S256 challenge of a known verifier. */+ @Test+ void pkceAcceptsTheRfc7636ExampleVerifierAndNothingElse() {+ assertNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_VERIFIER));+ assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_VERIFIER.replace('d', 'e')));+ assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, null));+ assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_CHALLENGE));+ assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, "short"));+ assertNotNull(CognitoOAuthController.pkceError(RFC_7636_CHALLENGE, RFC_7636_VERIFIER + "!"));+ assertNotNull(CognitoOAuthController.pkceError(null, RFC_7636_VERIFIER));+ assertNull(CognitoOAuthController.pkceError(null, null));+ }++ /** The client has no secret: a public client proves itself with the verifier alone. */+ @Test+ void tokenRedeemsAPkceCodeForAPublicClientWithTheMatchingVerifier() {+ String code = putAuthorizationCode(null, RFC_7636_CHALLENGE);++ Response response = controller.token(null, requestContext(null),+ withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER));++ assertEquals(200, response.getStatus());+ assertEquals("access-token", ((JsonNode) response.getEntity()).path("access_token").asText());+ }++ @Test+ void tokenRejectsAWrongVerifierAndSpendsTheCode() {+ String code = putAuthorizationCode(null, RFC_7636_CHALLENGE);++ Response wrong = controller.token(null, requestContext(null),+ withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER.replace('d', 'e')));+ Response retry = controller.token(null, requestContext(null),+ withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER));++ assertOAuthError(wrong, "invalid_grant");+ assertOAuthError(retry, "invalid_grant");+ }++ @Test+ void tokenRejectsAPkceCodeWithoutAVerifier() {+ String code = putAuthorizationCode(null, RFC_7636_CHALLENGE);++ Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));++ assertOAuthError(response, "invalid_grant");+ assertTrue(stateStore.findAuthorizationCode(code).isEmpty());+ }++ @Test+ void tokenRejectsAVerifierForACodeIssuedWithoutAChallenge() {+ String code = putAuthorizationCode(null, null);++ Response response = controller.token(null, requestContext(null),+ withVerifier(validAuthorizationCodeForm(code), RFC_7636_VERIFIER));++ assertOAuthError(response, "invalid_grant");+ }++ @Test+ void tokenPutsTheNonceInTheIdTokenOnly() {+ String code = putAuthorizationCode("request-nonce", null);+ ArgumentCaptor<CognitoService.ClaimsOverride> override = ArgumentCaptor.forClass(CognitoService.ClaimsOverride.class);+ when(cognitoService.generateAuthResult(any(CognitoUser.class), any(UserPool.class), eq(client), override.capture()))+ .thenReturn(Map.of("AccessToken", "access-token", "IdToken", "id-token", "RefreshToken", "refresh-token",+ "ExpiresIn", 3600, "TokenType", "Bearer"));++ Response response = controller.token(null, requestContext(null), validAuthorizationCodeForm(code));++ assertEquals(200, response.getStatus());+ assertEquals(Map.of("nonce", "request-nonce"), override.getValue().idClaimsToAddOrOverride());+ assertNull(override.getValue().accessClaimsToAddOrOverride());+ assertNull(override.getValue().groupsToOverride());+ }+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)));+ List.of("openid"), "nonce", "ExampleOidc", relyingPartyState, null, CLOCK.instant().plusSeconds(60)));}private String putAuthorizationCode() {+ return putAuthorizationCode(null, null);+ }++ private String putAuthorizationCode(String nonce, String codeChallenge) {String code = stateStore.putAuthorizationCode(new CognitoAuthorizationCode(- POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), CLOCK.instant().plusSeconds(60)));+ POOL_ID, CLIENT_ID, "federated-user", CALLBACK_URI, List.of("openid"), nonce, codeChallenge,+ 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)))@@ -232,6 +424,12 @@ class CognitoOAuthControllerTest {return code;}+ private static MultivaluedHashMap<String, String> withVerifier(MultivaluedHashMap<String, String> form,+ String codeVerifier) {+ form.add("code_verifier", codeVerifier);+ return form;+ }+private static MultivaluedHashMap<String, String> validAuthorizationCodeForm(String code) {return form("grant_type", "authorization_code", "client_id", CLIENT_ID, "code", code, "redirect_uri", CALLBACK_URI);}@@ -247,6 +445,7 @@ class CognitoOAuthControllerTest {result.setAllowedOAuthFlowsUserPoolClient(true);result.setAllowedOAuthFlows(List.of("code"));result.setCallbackURLs(List.of(CALLBACK_URI));+ result.setSupportedIdentityProviders(List.of("COGNITO"));return result;}@@ -257,8 +456,12 @@ class CognitoOAuthControllerTest {}private static CognitoUser user() {+ return user("federated-user");+ }++ private static CognitoUser user(String username) {CognitoUser result = new CognitoUser();- result.setUsername("federated-user");+ result.setUsername(username);result.setUserPoolId(POOL_ID);return result;}