mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cognito): answer CORS on the OAuth token, revoke and userInfo endpoints (#8027)
This commit is contained in:
1 parent
332d2c5cc7
commit
013e9b7c2e
5 files changed
+313
-1
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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<String> 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<Object> 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<String, Object> 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(", "));
|
||||
}
|
||||
}
|
||||
@@ -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<S3Service> s3ServiceInstance;
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<String> 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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user