feat(cognito): serve the OAuth token revocation endpoint (#4936)

POST /cognito-idp/oauth2/revoke, and /oauth2/revoke on a custom domain,
revoke a refresh token through RevokeToken and answer as AWS's revocation
endpoint does, as measured: 200 with no body for a revoked, already
revoked or invalid token; 400 invalid_request for a missing token or a
client with revocation disabled; 400 unsupported_token_type for an access
or ID token; and 401 invalid_client with WWW-Authenticate: Basic for
missing or bad client credentials, a client of another pool, or a token
issued to another client. Unlike the token endpoint, a client secret is
taken only from the Basic header.

On a custom domain, the Cognito filter now answers a path under /oauth2/
that Cognito does not serve with AWS's JSON 404, and a served path called
with another method with an empty 405, so neither reaches S3 as a key of a
bucket named cognito-idp.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-11 19:38:32 -04:00
1 parent 20bc835b6f
commit 1a0afce7ec
10 files changed
+859 -31

No files matched your search

@@ -5,24 +5,33 @@ import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import java.net.URI;
import java.util.List;
import java.util.Map;
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},
* {@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.
* {@code https://<domain>/oauth2/token}, {@code /oauth2/revoke}, {@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. Any other
* path under {@code /oauth2/} is answered here with AWS's JSON 404, and a served path called with a
* method it does not serve with an empty 405, so neither reaches S3 as a key of a bucket named
* {@code cognito-idp}. 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
@@ -40,6 +49,18 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
private static final String OAUTH_PREFIX = "/oauth2/";
private static final Set<String> MANAGED_LOGIN_PATHS = Set.of("/login", "/logout");
private static final String TARGET_PREFIX = "/cognito-idp";
/** The paths the Cognito handlers serve on a custom domain, and their methods. */
private static final Map<String, List<String>> SERVED_ROUTES = Map.of(
"/oauth2/token", List.of(HttpMethod.POST),
"/oauth2/revoke", List.of(HttpMethod.POST),
"/oauth2/authorize", List.of(HttpMethod.GET, HttpMethod.HEAD),
"/oauth2/idpresponse", List.of(HttpMethod.GET, HttpMethod.HEAD),
"/oauth2/userInfo", List.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST),
"/login", List.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST),
// AWS refuses a HEAD here rather than sign the browser out.
"/logout", List.of(HttpMethod.GET));
/** AWS's answer to a path under /oauth2/ that its authorization server does not serve. */
private static final String NOT_FOUND_BODY = "{\"error\":\"This URL doesn't exist on the authorization server.\"}";
private final CognitoService cognitoService;
@@ -63,6 +84,27 @@ public class CognitoCustomDomainFilter implements ContainerRequestFilter {
if (domain.isEmpty()) {
return;
}
List<String> methods = SERVED_ROUTES.get(path);
if (methods == null) {
requestContext.abortWith(Response.status(Response.Status.NOT_FOUND)
.type(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8"))
.entity(NOT_FOUND_BODY)
.build());
return;
}
// OPTIONS is left to the CORS filter and the existing routing, unchanged by this method check.
String method = requestContext.getMethod();
if (!methods.contains(method) && !HttpMethod.OPTIONS.equals(method)) {
requestContext.abortWith(Response.status(Response.Status.METHOD_NOT_ALLOWED)
.header(HttpHeaders.ALLOW, String.join(", ", methods))
.build());
return;
}
if (HttpMethod.HEAD.equals(method)) {
// Served by the GET handler, as S3's HeadObject route would otherwise take the rewritten path;
// the server still sends a HEAD no body.
requestContext.setMethod(HttpMethod.GET);
}
URI newUri = UriBuilder.fromUri(originalUri)
.replacePath(TARGET_PREFIX + path)
@@ -26,6 +26,7 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@@ -57,6 +58,8 @@ public class CognitoOAuthController {
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}");
/** AWS's description of a revocation without a token. */
private static final String INVALID_PARAMETER = "Invalid parameter in request";
private final CognitoService cognitoService;
private final ObjectMapper objectMapper;
@@ -397,6 +400,112 @@ public class CognitoOAuthController {
return issueToken(authorization, formParams, domainPoolId);
}
/**
* Revokes a refresh token and every access and ID token minted from it. A public client names
* itself with {@code client_id}; a client with a secret presents it in a Basic header, the only
* place AWS takes it from here. Success, and a token that is not valid or already revoked, are 200
* with an empty body, as on AWS. Errors are JSON whatever the {@code Accept} header asks for.
*/
@POST
@Path("/cognito-idp/oauth2/revoke")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.WILDCARD)
public Response revoke(@HeaderParam("Authorization") String authorization,
@Context ContainerRequestContext requestContext,
MultivaluedMap<String, String> formParams) {
String token = trimToNull(formParams.getFirst("token"));
if (token == null) {
return oauthError("invalid_request", INVALID_PARAMETER);
}
Optional<BasicCredentials> client = revokingClient(authorization,
trimToNull(formParams.getFirst("client_id")));
String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY);
if (client.isEmpty() || (domainPoolId != null && !isClientOfPool(client.get().clientId(), domainPoolId))) {
return invalidClient();
}
try {
cognitoService.revokeToken(client.get().clientId(), token, client.get().clientSecret());
} catch (AwsException e) {
return revocationError(e, token);
}
return Response.ok().build();
}
/**
* The client a revocation authenticates as, or empty when its credentials are refused. Unlike the
* token endpoint, AWS takes a secret only from a Basic header, and refuses one that is empty.
*/
private Optional<BasicCredentials> revokingClient(String authorization, String bodyClientId) {
BasicCredentials basicCredentials;
try {
basicCredentials = parseBasicCredentials(authorization);
} catch (IllegalArgumentException expected) {
// A malformed Basic header authenticates no client, like a wrong secret.
return Optional.empty();
}
if (basicCredentials == null) {
return Optional.ofNullable(bodyClientId).map(clientId -> new BasicCredentials(clientId, null));
}
if (basicCredentials.clientId() == null || basicCredentials.clientSecret() == null
|| (bodyClientId != null && !bodyClientId.equals(basicCredentials.clientId()))) {
return Optional.empty();
}
return Optional.of(basicCredentials);
}
/**
* AWS's answer to a revocation that {@code RevokeToken} refuses. A token that is not a refresh
* token is refused only when it is a JWT, an access or ID token; any other token is not valid,
* which AWS answers with 200.
*/
private Response revocationError(AwsException e, String token) {
return switch (e.getErrorCode()) {
case "InvalidParameterException" -> oauthError("invalid_request", INVALID_PARAMETER);
case "UnsupportedOperationException" -> oauthError("invalid_request", "Unsupported operation");
case "ResourceNotFoundException", "UnauthorizedException" -> invalidClient();
case "UnsupportedTokenTypeException" -> isJwt(token)
? oauthError("unsupported_token_type", null)
: Response.ok().build();
default -> {
LOG.errorv(e, "Failed to revoke a Cognito token");
yield oauthError("invalid_request", INVALID_PARAMETER);
}
};
}
/**
* Whether AWS takes the token for a JWT, which it decides by shape without checking the signature:
* three parts, the last not empty, and a header naming its {@code alg}.
*/
private boolean isJwt(String token) {
String[] parts = token.split("\\.", -1);
if (parts.length != 3 || parts[2].isEmpty()) {
return false;
}
try {
return objectMapper.readTree(Base64.getUrlDecoder().decode(parts[0])).path("alg").isTextual();
} catch (IllegalArgumentException | IOException expected) {
// A header that is not Base64url JSON is not a JWT's, so AWS takes the token as not valid.
return false;
}
}
/** AWS's answer to every client the revocation endpoint cannot authenticate. */
private Response invalidClient() {
return Response.fromResponse(oauthError(Response.Status.UNAUTHORIZED, "invalid_client",
"Invalid client credentials in request"))
.header(HttpHeaders.WWW_AUTHENTICATE, "Basic")
.build();
}
private boolean isClientOfPool(String clientId, String poolId) {
try {
return poolId.equals(cognitoService.findClientById(clientId).getUserPoolId());
} catch (AwsException e) {
return false;
}
}
private Response issueToken(String authorization, MultivaluedMap<String, String> formParams,
String domainPoolId) {
String grantType = trimToNull(formParams.getFirst("grant_type"));
@@ -889,10 +998,16 @@ public class CognitoOAuthController {
}
private Response oauthError(String error, String description) {
return oauthError(Response.Status.BAD_REQUEST, error, description);
}
private Response oauthError(Response.Status status, String error, String description) {
ObjectNode body = objectMapper.createObjectNode();
body.put("error", error);
body.put("error_description", description);
return Response.status(400)
if (description != null) {
body.put("error_description", description);
}
return Response.status(status)
.type(MediaType.APPLICATION_JSON)
.header("Cache-Control", "no-store")
.header("Pragma", "no-cache")
@@ -8,6 +8,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.container.ContainerRequestContext;
@@ -111,6 +112,14 @@ public class CognitoUserInfoController {
.build();
}
/** AWS serves the endpoint on POST too, with the same answer. */
@POST
@Path("/cognito-idp/oauth2/userInfo")
public Response userInfoByPost(@HeaderParam("Authorization") String authorization,
@Context ContainerRequestContext requestContext) {
return userInfo(authorization, requestContext);
}
private static final List<String> OIDC_PROFILE_CLAIMS = List.of(
"name", "family_name", "given_name", "middle_name", "nickname",
"preferred_username", "profile", "picture", "website", "gender",