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

+21
View File
@@ -159,9 +159,13 @@ A domain created with `CustomDomainConfig` answers the OAuth endpoints on that h
```
GET https://auth.example.localhost.floci.io/oauth2/authorize
GET https://auth.example.localhost.floci.io/oauth2/idpresponse
POST https://auth.example.localhost.floci.io/oauth2/token
POST https://auth.example.localhost.floci.io/oauth2/revoke
GET https://auth.example.localhost.floci.io/oauth2/userInfo
POST https://auth.example.localhost.floci.io/oauth2/userInfo
GET https://auth.example.localhost.floci.io/login
POST https://auth.example.localhost.floci.io/login
GET https://auth.example.localhost.floci.io/logout
```
@@ -173,6 +177,11 @@ another pool is refused with `invalid_client`, and an access token issued by ano
URLs when one exists. Prefix domains (`<prefix>.auth.<region>.amazoncognito.com`) are stored but not
routed, since that hostname never reaches Floci. `/login` and `/logout` are served at the root only
on a custom-domain host; on Floci's own host they are `/cognito-idp/login` and `/cognito-idp/logout`.
On a custom-domain host, any other path under `/oauth2/` is answered with AWS's JSON 404, and a
served path called with a method it does not serve with an empty 405 whose `Allow` header lists
the methods it does serve. HEAD is answered as GET, as on AWS, except on `/logout`, which AWS
refuses rather than sign the browser out. AWS answers `GET /oauth2/token` with its managed login
error page instead; Floci answers 405.
With TLS enabled, a custom domain (`CustomDomainConfig` set) is added to Floci's server
certificate as soon as it is created, so `https://<domain>` verifies without a restart; see
@@ -445,6 +454,8 @@ plain, so branding is stored and returned rather than rendered. Two divergences
| `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 |
| `POST /cognito-idp/oauth2/revoke` | OAuth refresh token revocation endpoint |
| `GET`, `POST /cognito-idp/oauth2/userInfo` | OIDC userInfo endpoint, for a user's access token |
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
@@ -458,6 +469,16 @@ client-credentials flow:
- `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`.
- `POST /cognito-idp/oauth2/revoke` revokes a refresh token (`token`), and with it every access
and ID token minted from it, as `RevokeToken` does. A public client sends `client_id`; a client
with a secret sends it in a Basic `Authorization` header. Unlike the token endpoint, it ignores a
`client_secret` in the form body, as AWS does. Success, and a token that is not valid or already
revoked, are 200 with an empty body. A missing token, or a client with
`EnableTokenRevocation=false`, is 400 `invalid_request`; a JWT, such as an access or ID token, is
400 `unsupported_token_type`, judged as AWS does by its shape without checking the signature;
missing or bad client credentials, a client of another pool on a
custom domain, and a token issued to another client are 401 `invalid_client` with
`WWW-Authenticate: Basic`.
### Managed login
@@ -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",
@@ -3,12 +3,19 @@ package io.github.hectorvent.floci.services.cognito;
import io.github.hectorvent.floci.core.common.AccountContextFilter;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.net.URI;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -26,7 +33,7 @@ class CognitoCustomDomainFilterTest {
@Test
void rewritesAnOauthPathOnACustomDomainAndPinsThePool() {
ContainerRequestContext request = request("http://" + DOMAIN + ":4566/oauth2/token?x=1", DOMAIN + ":4566");
ContainerRequestContext request = request("POST", "http://" + DOMAIN + ":4566/oauth2/token?x=1", DOMAIN + ":4566");
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
filter.filter(request);
@@ -39,7 +46,7 @@ class CognitoCustomDomainFilterTest {
/** HTTP/2 carries no Host header; the authority is on the request URI. */
@Test
void fallsBackToTheRequestAuthorityWithoutAHostHeader() {
ContainerRequestContext request = request("https://" + DOMAIN + "/oauth2/userInfo", null);
ContainerRequestContext request = request("GET", "https://" + DOMAIN + "/oauth2/userInfo", null);
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
filter.filter(request);
@@ -51,7 +58,7 @@ class CognitoCustomDomainFilterTest {
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);
ContainerRequestContext request = request("GET", "https://" + DOMAIN + path + "?client_id=c&state=a%26b", DOMAIN);
filter.filter(request);
@@ -64,7 +71,7 @@ class CognitoCustomDomainFilterTest {
@Test
void leavesOtherPathsAlone() {
for (String path : new String[] {"/cognito-idp/oauth2/token", "/login/", "/loginx", "/logout/x", "/signup"}) {
ContainerRequestContext request = request("http://" + DOMAIN + path, DOMAIN);
ContainerRequestContext request = request("GET", "http://" + DOMAIN + path, DOMAIN);
filter.filter(request);
@@ -79,7 +86,7 @@ class CognitoCustomDomainFilterTest {
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");
ContainerRequestContext request = request("GET", "http://localhost:4566" + path, "localhost:4566");
filter.filter(request);
@@ -90,17 +97,109 @@ class CognitoCustomDomainFilterTest {
@Test
void leavesUnknownHostsAlone() {
ContainerRequestContext request = request("http://nobody.localhost.floci.io/oauth2/token", "nobody.localhost.floci.io");
when(cognitoService.findCustomDomain("nobody.localhost.floci.io")).thenReturn(Optional.empty());
for (String path : new String[] {"/oauth2/token", "/oauth2/no-such-path"}) {
ContainerRequestContext request = request("GET", "http://nobody.localhost.floci.io" + path,
"nobody.localhost.floci.io");
filter.filter(request);
verify(request, never()).setRequestUri(any());
verify(request, never()).setProperty(any(), any());
verify(request, never()).abortWith(any());
}
}
@Test
void rewritesEveryPathCognitoServesWithItsMethods() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String route : new String[] {"POST /oauth2/token", "POST /oauth2/revoke", "GET /oauth2/authorize",
"GET /oauth2/idpresponse", "GET /oauth2/userInfo", "POST /oauth2/userInfo", "GET /login",
"POST /login", "GET /logout"}) {
String[] parts = route.split(" ");
ContainerRequestContext request = request(parts[0], "https://" + DOMAIN + parts[1], DOMAIN);
filter.filter(request);
verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp" + parts[1]));
verify(request, never()).abortWith(any());
}
}
/** OPTIONS is left to the CORS filter and the existing routing, unchanged by the method check. */
@Test
void passesAPreflightToAServedPathThrough() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
ContainerRequestContext request = request("OPTIONS", "https://" + DOMAIN + "/oauth2/token", DOMAIN);
filter.filter(request);
verify(request, never()).setRequestUri(any());
verify(request, never()).setProperty(any(), any());
verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp/oauth2/token"));
verify(request, never()).abortWith(any());
}
private static ContainerRequestContext request(String uri, String hostHeader) {
/** AWS's answer, which otherwise S3 would give, as a key of a bucket named cognito-idp. */
@Test
void answersAnOauthPathCognitoDoesNotServeWithAJsonNotFound() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String path : new String[] {"/oauth2/no-such-path", "/oauth2/revoke/x", "/oauth2/", "/oauth2/Token"}) {
ContainerRequestContext request = request("POST", "https://" + DOMAIN + path, DOMAIN);
filter.filter(request);
Response response = abortedWith(request);
assertEquals(404, response.getStatus(), path);
assertTrue(MediaType.APPLICATION_JSON_TYPE.isCompatible(response.getMediaType()), path);
assertEquals("{\"error\":\"This URL doesn't exist on the authorization server.\"}", response.getEntity());
verify(request, never()).setRequestUri(any());
}
}
@Test
void answersAServedPathCalledWithAnotherMethodWithAnEmptyMethodNotAllowed() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String route : new String[] {"GET /oauth2/token POST", "GET /oauth2/revoke POST",
"HEAD /oauth2/revoke POST", "DELETE /oauth2/token POST", "POST /oauth2/authorize GET, HEAD",
"POST /oauth2/idpresponse GET, HEAD", "DELETE /oauth2/userInfo GET, HEAD, POST",
"PUT /login GET, HEAD, POST", "POST /logout GET", "HEAD /logout GET"}) {
String[] parts = route.split(" ", 3);
ContainerRequestContext request = request(parts[0], "https://" + DOMAIN + parts[1], DOMAIN);
filter.filter(request);
Response response = abortedWith(request);
assertEquals(405, response.getStatus(), route);
assertEquals(parts[2], response.getHeaderString(HttpHeaders.ALLOW), route);
assertNull(response.getEntity(), route);
assertNull(response.getMediaType(), route);
verify(request, never()).setRequestUri(any());
}
}
/** AWS answers HEAD as GET on these paths, so the filter serves it with the GET handler. */
@Test
void servesAHeadWithTheGetHandler() {
when(cognitoService.findCustomDomain(DOMAIN)).thenReturn(Optional.of(domain("us-east-1_abc")));
for (String path : new String[] {"/oauth2/authorize", "/oauth2/idpresponse", "/oauth2/userInfo", "/login"}) {
ContainerRequestContext request = request("HEAD", "https://" + DOMAIN + path, DOMAIN);
filter.filter(request);
verify(request).setMethod("GET");
verify(request).setRequestUri(URI.create("https://" + DOMAIN + "/cognito-idp" + path));
verify(request, never()).abortWith(any());
}
}
private static Response abortedWith(ContainerRequestContext request) {
ArgumentCaptor<Response> response = ArgumentCaptor.forClass(Response.class);
verify(request).abortWith(response.capture());
return response.getValue();
}
private static ContainerRequestContext request(String method, String uri, String hostHeader) {
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getMethod()).thenReturn(method);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getRequestUri()).thenReturn(URI.create(uri));
when(request.getUriInfo()).thenReturn(uriInfo);
@@ -12,8 +12,15 @@ import java.util.Base64;
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.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
/** Shared setup for the custom-domain integration tests: pools, clients, certificates and token calls. */
/**
* Shared setup for the custom-domain integration tests: pools, clients, certificates and token calls,
* and AWS's answers of the revocation endpoint.
*/
final class CognitoCustomDomainFixtures {
static final String FLOCI_URL = "http://localhost:4566";
@@ -84,8 +91,17 @@ final class CognitoCustomDomainFixtures {
/** A public client, a confirmed user and the access token USER_PASSWORD_AUTH issues for it. */
static String signInNewUser(String poolId) throws Exception {
return signIn(poolId).accessToken();
}
/** A confirmed user signed in through a new public client with USER_PASSWORD_AUTH. */
static SignedInUser signIn(String poolId) throws Exception {
String publicClient = cognitoJson("CreateUserPoolClient", """
{"UserPoolId": "%s", "ClientName": "routing-user-client", "ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH"]}
{
"UserPoolId": "%s",
"ClientName": "routing-user-client",
"ExplicitAuthFlows": ["ALLOW_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH"]
}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
String username = "user-" + System.nanoTime() + "@example.com";
cognitoAction("AdminCreateUser", """
@@ -101,14 +117,26 @@ final class CognitoCustomDomainFixtures {
cognitoAction("AdminSetUserPassword", """
{"UserPoolId": "%s", "Username": "%s", "Password": "%s", "Permanent": true}
""".formatted(poolId, username, PASSWORD)).then().statusCode(200);
return cognitoJson("InitiateAuth", """
JsonNode tokens = cognitoJson("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "USER_PASSWORD_AUTH",
"AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}
}
""".formatted(publicClient, username, PASSWORD))
.path("AuthenticationResult").path("AccessToken").asText();
""".formatted(publicClient, username, PASSWORD)).path("AuthenticationResult");
return new SignedInUser(publicClient, tokens.path("AccessToken").asText(),
tokens.path("RefreshToken").asText());
}
/** The REFRESH_TOKEN_AUTH call that renews a signed-in user's tokens. */
static Response refresh(SignedInUser user) {
return cognitoAction("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "REFRESH_TOKEN_AUTH",
"AuthParameters": {"REFRESH_TOKEN": "%s"}
}
""".formatted(user.clientId(), user.refreshToken()));
}
/** A client-credentials request with Basic authentication, on {@code host} when one is given. */
@@ -132,6 +160,25 @@ final class CognitoCustomDomainFixtures {
return null;
}
/** AWS's answer to a revocation it accepts: 200, with no body and no Content-Type. */
static void assertRevoked(Response response) {
response.then()
.statusCode(200)
.header("Content-Length", "0")
.header("Content-Type", nullValue())
.body(emptyString());
}
/** AWS's answer to every client the revocation endpoint cannot authenticate. */
static void assertInvalidClient(Response response) {
response.then()
.statusCode(401)
.contentType(containsString("application/json"))
.header("WWW-Authenticate", "Basic")
.body("error", equalTo("invalid_client"))
.body("error_description", equalTo("Invalid client credentials in request"));
}
static String basic(String clientId, String secret) {
return "Basic " + Base64.getEncoder().encodeToString((clientId + ":" + secret).getBytes(StandardCharsets.UTF_8));
}
@@ -139,4 +186,8 @@ final class CognitoCustomDomainFixtures {
static JsonNode jwtPayload(String token) throws Exception {
return OBJECT_MAPPER.readTree(Base64.getUrlDecoder().decode(token.split("\\.")[1]));
}
/** A user signed in through the public client {@code clientId}, with the tokens it was issued. */
record SignedInUser(String clientId, String accessToken, String refreshToken) {
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.SignedInUser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
@@ -18,24 +19,30 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.FLOCI_URL;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.assertInvalidClient;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.assertRevoked;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.basic;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.confidentialClient;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.createPool;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.customDomain;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.expect;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.jwtPayload;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refresh;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.requestCertificate;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.signIn;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.tokenRequest;
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.emptyString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The OAuth contract of the token and userInfo endpoints when reached on a custom domain: the
* The OAuth contract of the token, revoke and userInfo endpoints when reached on a custom domain: the
* same answers AWS gives on {@code https://<domain>/oauth2/...}.
*/
@QuarkusTest
@@ -45,6 +52,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
private static final String DOMAIN = "auth-c-" + System.nanoTime() + ".teos.localhost.floci.io";
private static String poolA;
private static String poolB;
private static String clientA;
private static String secretA;
private static String clientB;
@@ -59,7 +67,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
@Order(1)
void setUpTwoPoolsAndOneCustomDomain() throws Exception {
poolA = createPool("ContractPoolA");
String poolB = createPool("ContractPoolB");
poolB = createPool("ContractPoolB");
JsonNode a = cognitoJson("CreateUserPoolClient", confidentialClient(poolA)).path("UserPoolClient");
clientA = a.path("ClientId").asText();
@@ -175,7 +183,6 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
.header("WWW-Authenticate", startsWith("Bearer error=\"invalid_token\""));
}
/** Floci has no hosted UI revoke endpoint. */
@Test
@Order(9)
void authorizeRouteIsServedOnCustomDomain() {
@@ -186,6 +193,14 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
.then()
.statusCode(400)
.body("error", equalTo("unsupported_response_type"));
given()
.header("Host", DOMAIN)
.when()
.head("/oauth2/authorize")
.then()
.statusCode(400)
.body(emptyString());
}
@Test
@@ -202,20 +217,88 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
@Test
@Order(11)
void revokeEndpointIsNotServed() {
for (String path : List.of("/oauth2/revoke")) {
void revokeIsServedOnTheCustomDomain() throws Exception {
SignedInUser user = signIn(poolA);
assertRevoked(given()
.header("Host", DOMAIN)
.formParam("token", user.refreshToken())
.formParam("client_id", user.clientId())
.when()
.post("/oauth2/revoke"));
refresh(user)
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"));
}
/** As on AWS, a client of another pool does not exist on a pool's custom domain. */
@Test
@Order(12)
void revokeRefusesAClientOfAnotherPool() throws Exception {
SignedInUser user = signIn(poolB);
assertInvalidClient(given()
.header("Host", DOMAIN)
.formParam("token", user.refreshToken())
.formParam("client_id", user.clientId())
.when()
.post("/oauth2/revoke"));
refresh(user).then().statusCode(200);
}
/**
* Cognito answers every path under /oauth2/ on its custom domain, so none reaches S3 as a key of
* a bucket named cognito-idp: a served path with an error, a served path called with another
* method, and a path Cognito does not serve.
*/
@Test
@Order(13)
void cognitoAnswersItsPathsWhateverTheAcceptHeader() {
for (String accept : List.of("application/json", "application/xml", "text/html", "*/*")) {
given()
.header("Host", DOMAIN)
.header("Accept", accept)
.header("Authorization", basic(clientA, secretA))
.formParam("client_id", clientA)
.when()
.get(path)
.post("/oauth2/revoke")
.then()
.statusCode(404);
.statusCode(400)
.contentType(containsString("application/json"))
.body("error", equalTo("invalid_request"))
.body("error_description", equalTo("Invalid parameter in request"));
given()
.header("Host", DOMAIN)
.header("Accept", accept)
.when()
.get("/oauth2/token")
.then()
.statusCode(405)
.header("Allow", equalTo("POST"))
.header("Content-Type", nullValue())
.body(emptyString());
for (String method : List.of("GET", "POST")) {
given()
.header("Host", DOMAIN)
.header("Accept", accept)
.when()
.request(method, "/oauth2/no-such-path")
.then()
.statusCode(404)
.contentType(containsString("application/json"))
.body(equalTo("{\"error\":\"This URL doesn't exist on the authorization server.\"}"));
}
}
}
/** A prefix domain's hostname resolves to AWS, so Floci never routes by it. */
@Test
@Order(12)
@Order(14)
void prefixDomainHostIsNotRouted() throws Exception {
String prefix = "routing-prefix-" + System.nanoTime();
cognitoJson("CreateUserPoolDomain", """
@@ -235,7 +318,7 @@ class CognitoCustomDomainOAuthContractIntegrationTest {
* requests on many threads must never let one request's pin decide another's answer.
*/
@Test
@Order(13)
@Order(15)
void concurrentRequestsKeepTheirOwnPinnedPool() throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(8);
try {
@@ -11,12 +11,15 @@ import io.github.hectorvent.floci.services.cognito.model.IdentityProvider;
import io.github.hectorvent.floci.services.cognito.model.UserPool;
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.net.URI;
@@ -29,6 +32,7 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -36,6 +40,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -49,6 +54,8 @@ class CognitoOAuthControllerTest {
private static final String CALLBACK_URI = "https://application.example.test/callback";
private static final String RFC_7636_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
private static final String RFC_7636_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
/** Three dot-separated parts, as an access or ID token has. */
private static final String ACCESS_TOKEN_SHAPE = jwtShape("{\"alg\":\"RS256\"}", "signature");
private final ObjectMapper objectMapper = new ObjectMapper();
private final CognitoService cognitoService = mock(CognitoService.class);
@@ -528,6 +535,155 @@ class CognitoOAuthControllerTest {
verify(cognitoService, never()).generateAuthResult(any(CognitoUser.class), any(UserPool.class), any(), any());
}
@Test
void revokeAnswersOkWithAnEmptyBodyForAPublicClient() {
Response response = controller.revoke(null, requestContext(null),
form("token", "refresh-token", "client_id", CLIENT_ID));
assertEquals(200, response.getStatus());
assertNull(response.getEntity());
verify(cognitoService).revokeToken(CLIENT_ID, "refresh-token", null);
}
@Test
void revokeAuthenticatesAConfidentialClientWithBasicCredentials() {
Response response = controller.revoke(basicAuthorization(CLIENT_ID, "client-secret"), requestContext(null),
form("token", "refresh-token"));
assertEquals(200, response.getStatus());
verify(cognitoService).revokeToken(CLIENT_ID, "refresh-token", "client-secret");
}
/** AWS takes a secret only from the Basic header: client_secret_post does not authenticate a revocation. */
@Test
void revokeIgnoresAClientSecretInTheForm() {
Response response = controller.revoke(null, requestContext(null),
form("token", "refresh-token", "client_id", CLIENT_ID, "client_secret", "client-secret"));
assertEquals(200, response.getStatus());
verify(cognitoService).revokeToken(CLIENT_ID, "refresh-token", null);
}
@ParameterizedTest
@CsvSource({
"InvalidParameterException, Invalid parameter in request",
"UnsupportedOperationException, Unsupported operation"
})
void revokeAnswersARequestTheServiceRefusesWithInvalidRequest(String errorCode, String description) {
doThrow(new AwsException(errorCode, "reason", 400)).when(cognitoService)
.revokeToken(CLIENT_ID, "refresh-token", null);
Response response = controller.revoke(null, requestContext(null),
form("token", "refresh-token", "client_id", CLIENT_ID));
assertOAuthError(response, "invalid_request", description);
assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
}
@ParameterizedTest
@ValueSource(strings = {"ResourceNotFoundException", "UnauthorizedException"})
void revokeAnswersAClientTheServiceRefusesWithInvalidClient(String errorCode) {
doThrow(new AwsException(errorCode, "reason", 400)).when(cognitoService)
.revokeToken(CLIENT_ID, "refresh-token", null);
Response response = controller.revoke(null, requestContext(null),
form("token", "refresh-token", "client_id", CLIENT_ID));
assertInvalidClient(response);
}
@Test
void revokeAnswersAJwtTheServiceRefusesWithUnsupportedTokenType() {
doThrow(new AwsException("UnsupportedTokenTypeException", "Only refresh tokens can be revoked", 400))
.when(cognitoService).revokeToken(CLIENT_ID, ACCESS_TOKEN_SHAPE, null);
Response response = controller.revoke(null, requestContext(null),
form("token", ACCESS_TOKEN_SHAPE, "client_id", CLIENT_ID));
assertEquals(400, response.getStatus());
assertEquals("{\"error\":\"unsupported_token_type\"}", response.getEntity().toString());
}
/**
* AWS answers 200 for a token that is not valid. Only a JWT is an unsupported token type, which AWS
* decides by its shape: three parts, a signature, and a header naming an {@code alg}.
*/
@ParameterizedTest
@MethodSource("tokensThatAreNotJwts")
void revokeAnswersOkForATokenThatIsNotAJwt(String token) {
doThrow(new AwsException("UnsupportedTokenTypeException", "Only refresh tokens can be revoked", 400))
.when(cognitoService).revokeToken(CLIENT_ID, token, null);
Response response = controller.revoke(null, requestContext(null),
form("token", token, "client_id", CLIENT_ID));
assertEquals(200, response.getStatus());
assertNull(response.getEntity());
}
/** The token is checked first: a request without one is invalid_request even when it names no client. */
@Test
void revokeWithoutATokenIsInvalidRequest() {
for (MultivaluedHashMap<String, String> form : List.of(form(), form("token", " ", "client_id", CLIENT_ID))) {
Response response = controller.revoke(null, requestContext(null), form);
assertOAuthError(response, "invalid_request", "Invalid parameter in request");
}
verify(cognitoService, never()).revokeToken(any(), any(), any());
}
@Test
void revokeOnACustomDomainRefusesAClientOfAnotherPool() {
Response response = controller.revoke(null, requestContext("other-pool"),
form("token", "refresh-token", "client_id", CLIENT_ID));
assertInvalidClient(response);
verify(cognitoService, never()).revokeToken(any(), any(), any());
}
@Test
void revokeOnACustomDomainRefusesAnUnknownClient() {
when(cognitoService.findClientById("missing-client"))
.thenThrow(new AwsException("ResourceNotFoundException", "Client not found", 400));
Response response = controller.revoke(null, requestContext(POOL_ID),
form("token", "refresh-token", "client_id", "missing-client"));
assertInvalidClient(response);
verify(cognitoService, never()).revokeToken(any(), any(), any());
}
@Test
void revokeOnTheCustomDomainOfTheClientsPoolRevokes() {
Response response = controller.revoke(null, requestContext(POOL_ID),
form("token", "refresh-token", "client_id", CLIENT_ID));
assertEquals(200, response.getStatus());
verify(cognitoService).revokeToken(CLIENT_ID, "refresh-token", null);
}
/**
* Credentials that name no client, or that cannot be trusted: no client_id, a Basic header with an
* empty secret (as a public client might send), a malformed one, or one that disagrees with client_id.
*/
@Test
void revokeRefusesCredentialsThatDoNotAuthenticateAClient() {
List<String[]> requests = List.of(
new String[] {null, null},
new String[] {basicAuthorization(CLIENT_ID, ""), null},
new String[] {"Basic !!!", null},
new String[] {basicAuthorization(CLIENT_ID, "client-secret"), "other-client"});
for (String[] request : requests) {
MultivaluedHashMap<String, String> form = request[1] == null
? form("token", "refresh-token") : form("token", "refresh-token", "client_id", request[1]);
Response response = controller.revoke(request[0], requestContext(null), form);
assertInvalidClient(response);
}
verify(cognitoService, never()).revokeToken(any(), any(), any());
}
private String putTransaction(String relyingPartyState) {
return stateStore.putTransaction(new CognitoAuthorizationTransaction(POOL_ID, CLIENT_ID, CALLBACK_URI,
List.of("openid"), "nonce", "ExampleOidc", relyingPartyState, null, CLOCK.instant().plusSeconds(60)));
@@ -598,6 +754,19 @@ class CognitoOAuthControllerTest {
return result;
}
static Stream<String> tokensThatAreNotJwts() {
return Stream.of("not-a-token", "a.b.c",
jwtShape("{\"kid\":\"x\"}", "signature"),
jwtShape("{\"alg\":5}", "signature"),
jwtShape("{\"alg\":\"RS256\"}", ""),
jwtShape("{\"alg\":\"RS256\"}", "signature.extra"));
}
private static String jwtShape(String header, String signature) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(header.getBytes(StandardCharsets.UTF_8))
+ ".payload." + signature;
}
private static MultivaluedHashMap<String, String> form(String... values) {
MultivaluedHashMap<String, String> result = new MultivaluedHashMap<>();
for (int index = 0; index < values.length; index += 2) {
@@ -635,7 +804,24 @@ class CognitoOAuthControllerTest {
}
private void assertOAuthError(Response response, String error) {
assertEquals(400, response.getStatus());
assertOAuthError(response, 400, error);
}
private void assertOAuthError(Response response, String error, String description) {
assertOAuthError(response, 400, error);
assertEquals(description, ((JsonNode) response.getEntity()).path("error_description").asText());
}
/** AWS's answer to every client the revocation endpoint cannot authenticate. */
private void assertInvalidClient(Response response) {
assertOAuthError(response, 401, "invalid_client");
assertEquals("Invalid client credentials in request",
((JsonNode) response.getEntity()).path("error_description").asText());
assertEquals("Basic", response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
}
private void assertOAuthError(Response response, int status, String error) {
assertEquals(status, response.getStatus());
assertNotNull(response.getEntity());
JsonNode body = (JsonNode) response.getEntity();
assertEquals(error, body.path("error").asText());
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.SignedInUser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
@@ -19,10 +20,18 @@ import java.security.Signature;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.PASSWORD;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.assertInvalidClient;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.assertRevoked;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.basic;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.refresh;
import static io.github.hectorvent.floci.services.cognito.CognitoCustomDomainFixtures.signIn;
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.nullValue;
import static org.junit.jupiter.api.Assertions.*;
@QuarkusTest
@@ -30,6 +39,7 @@ import static org.junit.jupiter.api.Assertions.*;
class CognitoOAuthTokenIntegrationTest {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private static final String REVOKE = "/cognito-idp/oauth2/revoke";
private static String poolId;
private static String clientId;
@@ -481,6 +491,191 @@ class CognitoOAuthTokenIntegrationTest {
assertEquals("client_secret_basic", document.path("token_endpoint_auth_methods_supported").get(0).asText());
}
/**
* The sign-out of an app: the refresh token, and every access token minted from it, before or after
* a refresh, stop working. Another sign-in of the same user is another family, and keeps working.
*/
@Test
@Order(22)
void revokeEndsTheSessionOfAPublicClient() throws Exception {
SignedInUser user = signIn(poolId);
String refreshedAccessToken = refresh(user)
.then()
.statusCode(200)
.extract()
.path("AuthenticationResult.AccessToken");
getUser(user.accessToken()).then().statusCode(200);
getUser(refreshedAccessToken).then().statusCode(200);
SignedInUser otherSession = signInAgain(user);
assertRevoked(revoke(user.refreshToken(), user.clientId()));
refresh(user)
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"))
.body("message", equalTo("Refresh Token has been revoked"));
cognitoAction("GetTokensFromRefreshToken", """
{"ClientId": "%s", "RefreshToken": "%s"}
""".formatted(user.clientId(), user.refreshToken()))
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"))
.body("message", equalTo("Refresh Token has been revoked"));
for (String revokedAccessToken : new String[] {user.accessToken(), refreshedAccessToken}) {
getUser(revokedAccessToken)
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"))
.body("message", equalTo("Access Token has been revoked"));
}
getUser(otherSession.accessToken()).then().statusCode(200);
refresh(otherSession).then().statusCode(200);
}
@Test
@Order(23)
void revokeAnswersOkForATokenAlreadyRevokedOrNotValid() throws Exception {
SignedInUser user = signIn(poolId);
revoke(user.refreshToken(), user.clientId()).then().statusCode(200);
assertRevoked(revoke(user.refreshToken(), user.clientId()));
assertRevoked(revoke("not-a-token", user.clientId()));
}
@Test
@Order(24)
void revokeRefusesAnAccessTokenAndLeavesItsFamilyAlone() throws Exception {
SignedInUser user = signIn(poolId);
revoke(user.accessToken(), user.clientId())
.then()
.statusCode(400)
.contentType(containsString("application/json"))
.body(equalTo("{\"error\":\"unsupported_token_type\"}"));
refresh(user).then().statusCode(200);
}
@Test
@Order(25)
void revokeRefusesATokenIssuedToAnotherClient() throws Exception {
SignedInUser user = signIn(poolId);
String otherClientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId": "%s", "ClientName": "other-public-client"}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
assertInvalidClient(revoke(user.refreshToken(), otherClientId));
refresh(user).then().statusCode(200);
}
/** No client_id, an unknown one, or a Basic header with an empty secret. */
@Test
@Order(26)
void revokeRefusesAPublicClientThatDoesNotAuthenticate() throws Exception {
SignedInUser user = signIn(poolId);
assertInvalidClient(given().formParam("token", user.refreshToken()).when().post(REVOKE));
assertInvalidClient(revoke(user.refreshToken(), "no-such-client"));
assertInvalidClient(given()
.header("Authorization", basic(user.clientId(), ""))
.formParam("token", user.refreshToken())
.when()
.post(REVOKE));
refresh(user).then().statusCode(200);
}
/** Unlike the token endpoint, revocation takes a secret only from the Basic header. */
@Test
@Order(27)
void revokeAuthenticatesAConfidentialClientOnlyWithBasicCredentials() {
assertInvalidClient(revoke("not-a-token", confidentialClientId));
assertInvalidClient(given()
.formParam("token", "not-a-token")
.formParam("client_id", confidentialClientId)
.formParam("client_secret", confidentialClientSecret)
.when()
.post(REVOKE));
assertInvalidClient(given()
.header("Authorization", basic(confidentialClientId, "wrong-secret"))
.formParam("token", "not-a-token")
.when()
.post(REVOKE));
assertRevoked(given()
.header("Authorization", basic(confidentialClientId, confidentialClientSecret))
.formParam("token", "not-a-token")
.when()
.post(REVOKE));
assertRevoked(given()
.header("Authorization", basic(confidentialClientId, confidentialClientSecret))
.formParam("token", "not-a-token")
.formParam("client_id", confidentialClientId)
.when()
.post(REVOKE));
}
/** The token is checked first, so a request with no parameters at all is invalid_request too. */
@Test
@Order(28)
void revokeWithoutATokenIsInvalidRequest() {
assertInvalidRequest(given().formParam("client_id", clientId).when().post(REVOKE),
"Invalid parameter in request");
assertInvalidRequest(revoke("", clientId), "Invalid parameter in request");
assertInvalidRequest(given().contentType("application/x-www-form-urlencoded").when().post(REVOKE),
"Invalid parameter in request");
assertInvalidRequest(given().when().post(REVOKE), "Invalid parameter in request");
}
@Test
@Order(29)
void revokeIsInvalidRequestWhenTheClientDisablesRevocation() throws Exception {
String disabledClientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId": "%s", "ClientName": "revocation-disabled-client", "EnableTokenRevocation": false}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
assertInvalidRequest(revoke("any-token", disabledClientId), "Unsupported operation");
}
/** The same user signed in again through the same client, which starts a new token family. */
private static SignedInUser signInAgain(SignedInUser user) throws Exception {
String username = cognitoJson("GetUser", """
{"AccessToken": "%s"}
""".formatted(user.accessToken())).path("Username").asText();
JsonNode tokens = cognitoJson("InitiateAuth", """
{
"ClientId": "%s",
"AuthFlow": "USER_PASSWORD_AUTH",
"AuthParameters": {"USERNAME": "%s", "PASSWORD": "%s"}
}
""".formatted(user.clientId(), username, PASSWORD)).path("AuthenticationResult");
return new SignedInUser(user.clientId(), tokens.path("AccessToken").asText(),
tokens.path("RefreshToken").asText());
}
private static Response revoke(String token, String clientId) {
return given()
.formParam("token", token)
.formParam("client_id", clientId)
.when()
.post(REVOKE);
}
private static void assertInvalidRequest(Response response, String description) {
response.then()
.statusCode(400)
.contentType(containsString("application/json"))
.header("WWW-Authenticate", nullValue())
.body("error", equalTo("invalid_request"))
.body("error_description", equalTo(description));
}
private static Response getUser(String accessToken) {
return cognitoAction("GetUser", """
{"AccessToken": "%s"}
""".formatted(accessToken));
}
private static String cognitoDescribeClientSecret(String clientId) {
return cognitoAction("DescribeUserPoolClient", """
{
@@ -337,6 +337,33 @@ class CognitoUserInfoIntegrationTest {
.header("WWW-Authenticate", containsString("invalid_token"));
}
/** AWS serves userInfo on POST as well as GET, with the same answer. */
@Test
@Order(14)
void userInfoAnswersAPostAsItAnswersAGet() throws Exception {
String get = given()
.header("Authorization", "Bearer " + accessToken)
.when()
.get("/cognito-idp/oauth2/userInfo")
.then()
.statusCode(200)
.extract()
.asString();
String post = given()
.header("Authorization", "Bearer " + accessToken)
.when()
.post("/cognito-idp/oauth2/userInfo")
.then()
.statusCode(200)
.contentType(containsString("application/json"))
.extract()
.asString();
assertEquals(OBJECT_MAPPER.readTree(get), OBJECT_MAPPER.readTree(post));
assertEquals(USERNAME, OBJECT_MAPPER.readTree(post).path("username").asText());
}
private static String base64Url(String raw) {
return java.util.Base64.getUrlEncoder().withoutPadding()
.encodeToString(raw.getBytes(java.nio.charset.StandardCharsets.UTF_8));