diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 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 config OIDC provider, exchanges the returned code, provisions or reconciles the federated user, and issues a Cognito authorization code for the registered callback. -Only `ProviderType=OIDC` is supported by this flow. Floci does not provide a built-in hosted -UI and does not implement social providers such as Google, Facebook, Login with Amazon or -SignInWithApple. +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 third party: @@ -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/authorize POST https://auth.example.localhost.floci.io/oauth2/token GET 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 `cl another pool is refused with `invalid_client`, and an access token issued by another pool with `invalid_token`. Domain names are unique across all accounts, as on AWS. The pool's `openid-configuration` advertises the custom-domain URLs when one exists. Prefix domains (`.auth..amazoncognito.com`) are stored but not -routed, since that hostname never reaches Floci. `/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 server certificate as soon as it is created, so `https://` verifies without a restart; see @@ -280,8 +284,8 @@ up, so an oversized request naming something that does not exist reports the req problem rather than `ResourceNotFoundException`, and an update violating both reports them in 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, rejecting unknown 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 | +| `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 OIDC authorization-code sign-in as well as the -emulator-friendly client-credentials flow: +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, then redirects - to the configured provider with an opaque state and nonce. +- `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 provider code and redirects to the registered callback with a one-time Cognito authorization code. -- `POST /cognito-idp/oauth2/token` redeems that authorization code once, or issues a machine +- `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 machine token 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.java index 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 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 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); + throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400); } - - if (user.isTemporaryPassword() || "FORCE_CHANGE_PASSWORD".equals(user.getUserStatus())) { - return buildNewPasswordRequiredChallenge(pool, client, user); - } - - Map result = new HashMap<>(); - result.put("AuthenticationResult", - issueTokens(pool, client, user, "TokenGeneration_Authentication", clientMetadata)); - return result; + return user; } private Map 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.java index 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:///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:///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 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.java index 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 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 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 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.java index 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 transactions = new ConcurrentHashMap<>(); private final ConcurrentHashMap authorizationCodes = new ConcurrentHashMap<>(); + private final ConcurrentHashMap sessions = new ConcurrentHashMap<>(); private final Clock clock; private final SecureRandom secureRandom = new SecureRandom(); @@ -44,15 +46,33 @@ public class CognitoFederationStateStore { } public Optional 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 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 String put(ConcurrentHashMap store, T value) { @@ -63,6 +83,18 @@ public class CognitoFederationStateStore { return key; } + private Optional find(ConcurrentHashMap store, String key, Function 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 Optional consume(ConcurrentHashMap store, String key, Function expiresAt) { AtomicReference 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.java new file mode 100644 index 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 issueAuthorizationCode(String sessionId, UserPoolClient client, String redirectUri, + List scopes, String nonce, String codeChallenge) { + Optional 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 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.java index 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; @Inject public 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,40 +91,174 @@ 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); - } catch (AwsException e) { - return oauthError("invalid_client", "Client not found"); - } - String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY); - if (domainPoolId != null && !domainPoolId.equals(client.getUserPoolId())) { - return oauthError("invalid_client", "Client not found"); - } - if (!client.isAllowedOAuthFlowsUserPoolClient() || !client.getAllowedOAuthFlows().contains("code")) { - return oauthError("unauthorized_client", "Client is not allowed to use the authorization code flow"); - } - if (!client.getCallbackURLs().contains(redirectUri)) { - return oauthError("invalid_request", "redirect_uri is not registered for this client"); - } - - try { - String location = federationService.beginAuthorization(client.getUserPoolId(), clientId, redirectUri, - splitScopes(scope), trimToNull(nonce), providerName, relyingPartyState); + 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_request", e.getMessage()); } } + /** + * 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 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 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 { + sessionId = managedLoginService.signIn(check.client(), username, password); + } catch (AwsException e) { + return signInPage(requestContext, request, Response.Status.BAD_REQUEST, signInError(e)); + } + Optional 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 @Path("/cognito-idp/oauth2/idpresponse") public Response idpResponse(@Context ContainerRequestContext requestContext, @@ -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 authentication = cognitoService.generateAuthResult(user, pool, client, null); + Map 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 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 parameters) { + StringBuilder query = new StringBuilder(); for (Map.Entry 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 Response.status(Response.Status.FOUND).location(URI.create(location.toString())).build(); + return query.toString(); + } + + private Response redirectWithCode(AuthorizationRequest request, String code) { + Map parameters = new LinkedHashMap<>(); + parameters.put("code", code); + if (request.state() != null) { + parameters.put("state", request.state()); + } + return redirect(request.redirectUri(), parameters); + } + + private Optional 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")); + } + 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 hiddenFields = new ArrayList<>(); + for (Map.Entry parameter : request.parameters().entrySet()) { + hiddenFields.add(" "); + } + String page = """ + + + + + + Sign in + + +
+

Sign in

+ %s +
+ + %s + + + + + +
+
+ + + """.formatted(error == null ? "" : "

" + escapeHtml(error) + "

", + 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 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 parameters() { + Map 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 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.java index 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 respondToAuthChallenge(String clientId, String challengeName, String session, Map 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.java index 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.java index 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 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.java index 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.java new file mode 100644 index 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.java index 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")); + } + } + @Test void 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()); + } } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoFederationServiceTest.java index 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); + } + @Test void 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.java index 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.java index 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", "newcomer@example.com"), + "finalUserStatus", "CONFIRMED"))); + + CognitoUser user = service.authenticateManagedLogin(client, "newcomer", "MyPassword1!"); + + assertEquals("newcomer", user.getUsername()); + assertEquals("newcomer@example.com", 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", "alice@example.com"), "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.java new file mode 100644 index 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(""); + private static final Pattern FORM_ACTION = Pattern.compile("
"); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void authorizeWithoutIdentityProviderRedirectsToTheLoginPageWithTheRequest() throws Exception { + Pool pool = newPool(); + + for (String provider : new String[] {null, "COGNITO"}) { + Map 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 query = authorizeRequest(pool.clientId()); + query.put("state", "\">"); + + 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("