mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
20bc835b6f
commit
1a0afce7ec
10 files changed
+859
-31
No files matched your search
+108
-9
@@ -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);
|
||||
|
||||
+56
-5
@@ -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) {
|
||||
}
|
||||
}
|
||||
+92
-9
@@ -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 {
|
||||
|
||||
+187
-1
@@ -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());
|
||||
|
||||
+195
@@ -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", """
|
||||
{
|
||||
|
||||
+27
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user