diff --git a/docs/services/cognito.md b/docs/services/cognito.md index c67d30f48e..c296c063dc 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -691,6 +691,13 @@ plain, so branding is stored and returned rather than rendered. Two divergences | `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 | +`token`, `revoke` and `userInfo` answer CORS as AWS does, so a browser app can call them with +`fetch` from any origin, on Floci's host and on a custom domain alike: a response to a request +with an `Origin` echoes it in `Access-Control-Allow-Origin`, with +`Access-Control-Allow-Credentials: true`, on success and on error. A preflight is answered with +200, the requested method and headers, and `Access-Control-Max-Age: 1800`. As on AWS, +`authorize` and `logout`, which the browser navigates to, carry no CORS headers. + The OAuth endpoints support browser-style authorization-code sign-in, for the pool's own users and through a federated OIDC provider, as well as the emulator-friendly client-credentials flow: diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoOAuthCorsFilter.java b/src/main/java/io/floci/aws/services/cognito/CognitoOAuthCorsFilter.java new file mode 100644 index 0000000000..105e48ccd8 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cognito/CognitoOAuthCorsFilter.java @@ -0,0 +1,97 @@ +package io.floci.aws.services.cognito; + +import io.floci.aws.services.s3.S3VirtualHostFilter; +import jakarta.annotation.Priority; +import jakarta.ws.rs.HttpMethod; +import jakarta.ws.rs.Priorities; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.ContainerResponseContext; +import jakarta.ws.rs.container.ContainerResponseFilter; +import jakarta.ws.rs.container.PreMatching; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.Provider; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * CORS on the endpoints a browser app calls with {@code fetch}: token, revoke and userInfo. AWS + * allows any Origin there, with credentials, on success and error alike, and answers the preflight + * itself; authorize and logout, which a browser navigates to, carry no CORS headers. Runs after + * {@link CognitoCustomDomainFilter} has rewritten a custom-domain request onto these paths, after + * {@link S3VirtualHostFilter} has marked a bucket host's requests, which keep S3's CORS like any + * method Cognito does not serve there; after an opted-in {@code GlobalCorsFilter}, whose preflight + * answer keeps its Private Network Access grant; and before matching, so S3's + * {@code OPTIONS /{bucket}/{key}} route never refuses the preflight. + */ +@Provider +@PreMatching +@Priority(Priorities.USER + 1) // after S3VirtualHostFilter (USER), whose marker leaves a bucket host's requests to S3 +public class CognitoOAuthCorsFilter implements ContainerRequestFilter, ContainerResponseFilter { + + /** The method and path of each request Cognito serves; any other there falls through to S3's object routes. */ + private static final Set CORS_ROUTES = Set.of( + "POST /cognito-idp/oauth2/token", + "POST /cognito-idp/oauth2/revoke", + "GET /cognito-idp/oauth2/userInfo", + "POST /cognito-idp/oauth2/userInfo"); + private static final String REQUEST_METHOD = "Access-Control-Request-Method"; + private static final String REQUEST_HEADERS = "Access-Control-Request-Headers"; + private static final List VARY = List.of("Origin", REQUEST_METHOD, REQUEST_HEADERS); + + @Override + public void filter(ContainerRequestContext request) { + if (!HttpMethod.OPTIONS.equals(request.getMethod()) || corsOrigin(request) == null) { + return; + } + request.abortWith(Response.ok() + .header("Access-Control-Allow-Methods", request.getHeaderString(REQUEST_METHOD)) + .header("Access-Control-Allow-Headers", requestedHeaders(request)) + .header("Access-Control-Max-Age", "1800") + .build()); + } + + @Override + public void filter(ContainerRequestContext request, ContainerResponseContext response) { + String origin = corsOrigin(request); + if (origin == null) { + return; + } + MultivaluedMap headers = response.getHeaders(); + headers.putSingle("Access-Control-Allow-Origin", origin); + headers.putSingle("Access-Control-Allow-Credentials", "true"); + headers.put("Vary", new ArrayList<>(VARY)); + } + + /** The Origin of a request Cognito serves, or of a preflight for one; null for S3's, which keep S3's CORS. */ + private static String corsOrigin(ContainerRequestContext request) { + if (request.getProperty(S3VirtualHostFilter.ORIGINAL_REQUEST_URI_PROPERTY) != null) { + return null; + } + String method = HttpMethod.OPTIONS.equals(request.getMethod()) + ? request.getHeaderString(REQUEST_METHOD) + : request.getMethod(); + if (HttpMethod.HEAD.equals(method) && request.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY) != null) { + // The custom-domain filter serves HEAD with the GET handler. + method = HttpMethod.GET; + } + return CORS_ROUTES.contains(method + " " + request.getUriInfo().getPath()) ? request.getHeaderString("Origin") : null; + } + + /** The requested headers as AWS echoes them, trimmed and comma-separated, or null, which leaves the header out. */ + private static String requestedHeaders(ContainerRequestContext request) { + String requested = request.getHeaderString(REQUEST_HEADERS); + if (requested == null || requested.isBlank()) { + return null; + } + return Arrays.stream(requested.split(",")) + .map(String::trim) + .filter(header -> !header.isEmpty()) + .collect(Collectors.joining(", ")); + } +} diff --git a/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java b/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java index 4b2c6c7acb..164b32f328 100644 --- a/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java +++ b/src/main/java/io/floci/aws/services/s3/S3VirtualHostFilter.java @@ -33,7 +33,7 @@ import java.util.Set; @ApplicationScoped public class S3VirtualHostFilter implements ContainerRequestFilter { - static final String ORIGINAL_REQUEST_URI_PROPERTY = S3VirtualHostFilter.class.getName() + ".originalRequestUri"; + public static final String ORIGINAL_REQUEST_URI_PROPERTY = S3VirtualHostFilter.class.getName() + ".originalRequestUri"; private final String baseHostname; private final Instance s3ServiceInstance; diff --git a/src/test/java/io/floci/aws/core/common/GlobalCorsFilterIntegrationTest.java b/src/test/java/io/floci/aws/core/common/GlobalCorsFilterIntegrationTest.java index 1f2318b56f..840b3ca41f 100644 --- a/src/test/java/io/floci/aws/core/common/GlobalCorsFilterIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/GlobalCorsFilterIntegrationTest.java @@ -94,6 +94,21 @@ class GlobalCorsFilterIntegrationTest { .header("Access-Control-Allow-Private-Network", nullValue()); } + @Test + void cognitoTokenPreflightKeepsThePrivateNetworkGrant() { + given() + .header("Origin", "http://localhost:3000") + .header("Access-Control-Request-Method", "POST") + .header("Access-Control-Request-Private-Network", "true") + .when() + .options("/cognito-idp/oauth2/token") + .then() + .statusCode(204) + .header("Access-Control-Allow-Private-Network", equalTo("true")) + .header("Access-Control-Allow-Origin", equalTo("http://localhost:3000")) + .header("Access-Control-Allow-Credentials", equalTo("true")); + } + @Test void actualRequestFromExtraAllowedOriginGetsCorsHeaders() { given() diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoOAuthCorsIntegrationTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoOAuthCorsIntegrationTest.java new file mode 100644 index 0000000000..71902de181 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cognito/CognitoOAuthCorsIntegrationTest.java @@ -0,0 +1,193 @@ +package io.floci.aws.services.cognito; + +import io.floci.aws.services.cognito.CognitoCustomDomainFixtures.SignedInUser; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; + +import static io.floci.aws.services.cognito.CognitoCustomDomainFixtures.createPool; +import static io.floci.aws.services.cognito.CognitoCustomDomainFixtures.customDomain; +import static io.floci.aws.services.cognito.CognitoCustomDomainFixtures.requestCertificate; +import static io.floci.aws.services.cognito.CognitoCustomDomainFixtures.signIn; +import static io.floci.aws.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.assertEquals; + +/** + * AWS answers CORS on the token, revoke and userInfo endpoints for any Origin, with credentials, + * on success and error alike, so a browser app can call them with fetch. A preflight there must + * not reach S3's OPTIONS route, which refuses it, while S3's own requests, on a bucket host or for a method Cognito does not serve, keep S3's CORS. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class CognitoOAuthCorsIntegrationTest { + + private static final String ORIGIN = "https://tklocal.example.test"; + private static final String DOMAIN = "auth-cors-" + System.nanoTime() + ".teos.localhost.floci.io"; + private static final List VARY = List.of( + "Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"); + + private static SignedInUser user; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + @Order(1) + void setUpPoolUserAndCustomDomain() throws Exception { + String poolId = createPool("CorsPool"); + user = signIn(poolId); + cognitoJson("CreateUserPoolDomain", customDomain(DOMAIN, poolId, requestCertificate(DOMAIN))); + } + + @ParameterizedTest + @ValueSource(strings = {"token", "revoke", "userInfo"}) + @Order(2) + void preflightEchoesTheOriginMethodAndHeaders(String endpoint) { + assertVary(given() + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", "POST") + .header("Access-Control-Request-Headers", "Content-Type , Authorization") + .when() + .options("/cognito-idp/oauth2/" + endpoint) + .then() + .statusCode(200) + .header("Access-Control-Allow-Origin", ORIGIN) + .header("Access-Control-Allow-Methods", "POST") + .header("Access-Control-Allow-Headers", "Content-Type, Authorization") + .header("Access-Control-Allow-Credentials", "true") + .header("Access-Control-Max-Age", "1800")); + } + + @Test + @Order(3) + void refreshGrantEchoesTheOrigin() { + assertVary(given() + .header("Origin", ORIGIN) + .formParam("grant_type", "refresh_token") + .formParam("client_id", user.clientId()) + .formParam("refresh_token", user.refreshToken()) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(200) + .header("Access-Control-Allow-Origin", ORIGIN) + .header("Access-Control-Allow-Credentials", "true")); + } + + @Test + @Order(4) + void tokenErrorEchoesTheOrigin() { + given() + .header("Origin", ORIGIN) + .formParam("client_id", user.clientId()) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .body("error", equalTo("invalid_request")) + .header("Access-Control-Allow-Origin", ORIGIN) + .header("Access-Control-Allow-Credentials", "true"); + } + + @Test + @Order(5) + void requestWithoutOriginGetsNoCorsHeaders() { + given() + .formParam("client_id", user.clientId()) + .when() + .post("/cognito-idp/oauth2/token") + .then() + .statusCode(400) + .header("Access-Control-Allow-Origin", nullValue()) + .header("Access-Control-Allow-Credentials", nullValue()); + } + + @ParameterizedTest + @CsvSource({ + "POST, /oauth2/token", + "HEAD, /oauth2/userInfo"}) + @Order(6) + void customDomainPreflightIsAnsweredByCognito(String method, String path) { + given() + .header("Host", DOMAIN) + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", method) + .when() + .options(path) + .then() + .statusCode(200) + .header("Access-Control-Allow-Origin", ORIGIN) + .header("Access-Control-Allow-Methods", method) + .header("Access-Control-Allow-Headers", nullValue()) + .header("Access-Control-Max-Age", "1800"); + } + + @Test + @Order(7) + void customDomainRefreshGrantEchoesTheOrigin() { + given() + .header("Host", DOMAIN) + .header("Origin", ORIGIN) + .formParam("grant_type", "refresh_token") + .formParam("client_id", user.clientId()) + .formParam("refresh_token", user.refreshToken()) + .when() + .post("/oauth2/token") + .then() + .statusCode(200) + .header("Access-Control-Allow-Origin", ORIGIN) + .header("Access-Control-Allow-Credentials", "true"); + } + + @ParameterizedTest + @CsvSource({ + "cors-bucket.s3.localhost.floci.io, /cognito-idp/oauth2/token, POST", + "cognito-idp.s3.localhost.floci.io, /oauth2/token, POST", + "localhost, /cognito-idp/oauth2/token, PUT", + "localhost, /cognito-idp/oauth2/userInfo, HEAD"}) + @Order(8) + void s3PreflightIsLeftToS3(String host, String path, String method) { + given() + .header("Host", host) + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", method) + .when() + .options(path) + .then() + .statusCode(403) + .header("Access-Control-Allow-Origin", nullValue()); + } + + @Test + @Order(9) + void methodCognitoDoesNotServeIsLeftToS3() { + given() + .header("Origin", ORIGIN) + .when() + .get("/cognito-idp/oauth2/token") + .then() + .statusCode(404) + .body(containsString("NoSuchBucket")) + .header("Access-Control-Allow-Origin", nullValue()); + } + + private static void assertVary(ValidatableResponse response) { + assertEquals(VARY, response.extract().headers().getValues("Vary")); + } +}