feat(cognito): serve managed login for native users with PKCE (#4238)

GET /oauth2/authorize with identity_provider=COGNITO, or none, now signs
in the pool's own users through managed login instead of requiring a
federated provider. It redirects to a plain sign-in form at
/cognito-idp/login (/login on a custom domain), which checks the
password as USER_PASSWORD_AUTH does, sets a pool-scoped `cognito`
session cookie and redirects to the callback with code and state. A
browser with a live session skips the form.

/oauth2/token enforces PKCE (S256 only, as on AWS) when the
authorization request sent a code_challenge, for managed login and
federated sign-in alike, and refuses a code_verifier for a code issued
without one (RFC 9700). The ID token carries the request's nonce.

/cognito-idp/logout (/logout on a custom domain) ends the session and
redirects to a registered LogoutURL, or back to the sign-in form for
the redirect_uri form of the request. Discovery advertises
code_challenge_methods_supported.

Closes #4218
This commit is contained in:
jwoa95 authored and GitHub committed 2026-09-23 16:35:35 -04:00
1 parent 7e4d4dafae
commit eb039eb71c
18 files changed
+1832 -104

No files matched your search

@@ -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);
throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);
}
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;
return user;
}
private Map<String, Object> handleRefreshToken(UserPool pool, UserPoolClient client,
@@ -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());
@@ -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);
}
@@ -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);
}
}
@@ -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;
}
}
}
@@ -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<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 {
sessionId = managedLoginService.signIn(check.client(), username, password);
} catch (AwsException e) {
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
@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<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 Response.status(Response.Status.FOUND).location(URI.create(location.toString())).build();
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"));
}
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("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&#39;");
}
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);
}
}
}
@@ -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());
@@ -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();
}
@@ -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 {
@@ -11,6 +11,7 @@ public record CognitoAuthorizationTransaction(
String nonce,
String providerName,
String relyingPartyState,
String codeChallenge,
Instant expiresAt) {
public CognitoAuthorizationTransaction {
@@ -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) {
}