fix(cognito): expose response headers for allowed browser origins (#8109)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-12 11:29:07 -04:00
1 parent 639fbe38d0
commit 021ce5e59b
7 files changed
+486

No files matched your search

@@ -4,6 +4,8 @@ import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.nullValue;
@@ -45,4 +47,34 @@ class GlobalCorsFilterDefaultIntegrationTest {
.statusCode(200)
.header("Access-Control-Allow-Origin", nullValue());
}
@Test
void sharedJsonPreflightIsNotGrantedWithoutAnAllowedOrigin() {
given()
.header("Origin", "http://localhost:3000")
.header("Access-Control-Request-Method", "POST")
.header("Access-Control-Request-Headers", "content-type,x-amz-target,x-amz-user-agent")
.when()
.options("/")
.then()
.statusCode(405)
.header("Access-Control-Allow-Origin", nullValue())
.header("Access-Control-Allow-Headers", nullValue());
}
@ParameterizedTest
@CsvSource(value = {"ListUserPools|200|{\"MaxResults\":1}", "InitiateAuth|400|{}"}, delimiter = '|')
void cognitoResponsesGetNoCorsHeadersWithoutAnAllowedOrigin(String action, int status, String body) {
given()
.header("Origin", "http://localhost:3000")
.header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
.when()
.post("/")
.then()
.statusCode(status)
.header("Access-Control-Allow-Origin", nullValue())
.header("Access-Control-Expose-Headers", nullValue());
}
}
@@ -6,6 +6,8 @@ import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.Map;
@@ -125,6 +127,41 @@ class GlobalCorsFilterIntegrationTest {
.header("Vary", containsString("Origin"));
}
@ParameterizedTest
@CsvSource(value = {"ListUserPools|200|{\"MaxResults\":1}", "InitiateAuth|400|{}"}, delimiter = '|')
void cognitoResponsesKeepDefaultAndConfiguredExposedHeaders(String action, int status, String body) {
given()
.header("Origin", "https://ui.example.test")
.header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action)
.contentType("application/x-amz-json-1.1")
.body(body)
.when()
.post("/")
.then()
.statusCode(status)
.header("Access-Control-Allow-Origin", equalTo("https://ui.example.test"))
.header("Access-Control-Expose-Headers", containsString("x-visible-header"))
.header("Access-Control-Expose-Headers", containsString("x-amzn-RequestId"))
.header("Access-Control-Expose-Headers", containsString("x-amzn-ErrorType"))
.header("Access-Control-Expose-Headers", containsString("x-amzn-ErrorMessage"))
.header("Access-Control-Expose-Headers", containsString("Date"));
}
@Test
void cognitoResponsesFromUnlistedOriginsGetNoCorsHeaders() {
given()
.header("Origin", "https://not-allowed.example.test")
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.ListUserPools")
.contentType("application/x-amz-json-1.1")
.body("{\"MaxResults\":1}")
.when()
.post("/")
.then()
.statusCode(200)
.header("Access-Control-Allow-Origin", nullValue())
.header("Access-Control-Expose-Headers", nullValue());
}
@Test
void requestFromUnlistedOriginGetsNoGlobalCorsHeaders() {
given()
@@ -0,0 +1,98 @@
package io.floci.aws.services.cognito;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsProtocolClaimFilter;
import io.floci.aws.core.common.ProtocolClaim;
import io.floci.aws.core.common.ServiceDescriptor;
import io.floci.aws.core.common.ServiceProtocol;
import io.floci.aws.core.common.WireProtocol;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
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.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class CognitoCorsFilterTest {
@ParameterizedTest
@CsvSource({"false,false", "true,true"})
void disablingCognitoOrCorsSkipsCognitoResponseHeaders(boolean serviceEnabled, boolean corsDisabled) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cognito().enabled()).thenReturn(serviceEnabled);
when(config.security().disableCorsHeaders()).thenReturn(corsDisabled);
when(config.security().extraCorsAllowedOrigins()).thenReturn(Optional.of(List.of("http://localhost:3000")));
CognitoCorsFilter filter = new CognitoCorsFilter(() -> config);
ContainerRequestContext request = cognitoRequest("http://localhost:3000");
ContainerResponseContext response = mock(ContainerResponseContext.class);
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
when(response.getHeaders()).thenReturn(headers);
filter.filter(request, response);
assertTrue(headers.isEmpty());
}
@ParameterizedTest
@CsvSource({"https://ui.example.test,HTTPS://UI.EXAMPLE.TEST,true",
"https://other.example.test,https://ui.example.test,false", "https://other.example.test,*,true"})
void responseExposedHeadersFollowTheOriginAllowList(String origin, String allowedOrigin,
boolean originAllowed) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().cognito().enabled()).thenReturn(true);
when(config.security().extraCorsAllowedOrigins()).thenReturn(Optional.of(List.of(allowedOrigin)));
when(config.security().extraCorsExposeHeaders()).thenReturn(Optional.of(
List.of("x-visible-header", "date", " X-AMZN-REQUESTID ", "x-visible-header")));
CognitoCorsFilter filter = new CognitoCorsFilter(() -> config);
ContainerRequestContext request = cognitoRequest(origin);
ContainerResponseContext response = mock(ContainerResponseContext.class);
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
headers.add("Access-Control-Expose-Headers", "X-Existing, date");
headers.add("Access-Control-Expose-Headers", "x-existing");
when(response.getHeaders()).thenReturn(headers);
filter.filter(request, response);
assertNull(headers.getFirst("Access-Control-Allow-Origin"));
if (!originAllowed) {
assertEquals(List.of("X-Existing, date", "x-existing"), headers.get("Access-Control-Expose-Headers"));
return;
}
Set<String> expected = Set.of("X-Existing", "Date", "x-amzn-RequestId", "x-amzn-ErrorType",
"x-amzn-ErrorMessage", "x-visible-header");
List<String> exposedHeaders = Arrays.asList(headers.getFirst("Access-Control-Expose-Headers")
.toString().split(",\\s*"));
assertEquals(expected.size(), exposedHeaders.size());
assertEquals(expected, new HashSet<>(exposedHeaders));
assertEquals(1, headers.get("Access-Control-Expose-Headers").size());
}
private static ContainerRequestContext cognitoRequest(String origin) {
ContainerRequestContext request = mock(ContainerRequestContext.class);
UriInfo uri = mock(UriInfo.class);
when(request.getUriInfo()).thenReturn(uri);
when(uri.getPath()).thenReturn("");
when(request.getHeaderString("Origin")).thenReturn(origin);
ServiceDescriptor service = new ServiceDescriptor("cognito-idp", "cognito", true, true,
null, null, 0L, null, ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON),
Set.of("AWSCognitoIdentityProviderService."), Set.of("cognito-idp"), Set.of(), Set.of(), Set.of());
when(request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(
new ProtocolClaim(WireProtocol.AWS_JSON_1_1, service, "ListUserPools",
"AWSCognitoIdentityProviderService.ListUserPools"));
return request;
}
}
@@ -0,0 +1,216 @@
package io.floci.aws.services.cognito;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.ExtraCorsOriginProfile;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
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.ValueSource;
import java.util.UUID;
import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction;
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.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
@TestProfile(ExtraCorsOriginProfile.class)
class CognitoCorsIntegrationTest {
private static final String ORIGIN = "http://localhost:3000";
private static final String TARGET_PREFIX = "AWSCognitoIdentityProviderService.";
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(strings = {"content-type,x-amz-target,x-amz-user-agent",
"Content-Type, X-Amz-Target, X-Amz-User-Agent, authorization, x-amz-security-token"})
void browserPreflightAllowsCognitoHeaders(String requestedHeaders) {
given()
.header("Origin", ORIGIN)
.header("Access-Control-Request-Method", "POST")
.header("Access-Control-Request-Headers", requestedHeaders)
.when().options("/")
.then()
.statusCode(204)
.header("Access-Control-Allow-Origin", equalTo(ORIGIN))
.header("Access-Control-Allow-Methods", containsString("POST"))
.header("Access-Control-Allow-Headers", containsString("content-type"))
.header("Access-Control-Allow-Headers", containsString("x-amz-target"))
.header("Access-Control-Allow-Headers", containsString("x-amz-user-agent"))
.header("Access-Control-Allow-Credentials", nullValue());
}
@ParameterizedTest
@CsvSource({ORIGIN + ",true", "https://browser.example.test,false", "null,false"})
void authenticationErrorsOnlyExposeHeadersToAllowedOrigins(String origin, boolean allowed) {
given()
.header("Origin", origin)
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth")
.body("""
{"AuthFlow":"USER_PASSWORD_AUTH","ClientId":"missing-client",
"AuthParameters":{"USERNAME":"alice","PASSWORD":"wrong"}}
""")
.when().post("/")
.then()
.statusCode(400)
.header("Access-Control-Allow-Origin", allowed ? equalTo(origin) : nullValue())
.header("Access-Control-Expose-Headers", allowed ? containsString("x-amzn-RequestId") : nullValue())
.header("Access-Control-Expose-Headers", allowed ? containsString("x-amzn-ErrorType") : nullValue())
.header("Access-Control-Allow-Credentials", nullValue())
.body("__type", equalTo("ResourceNotFoundException"));
}
@ParameterizedTest
@ValueSource(strings = {"{", "[]", "null"})
void browserCanReadSerializationErrors(String body) {
given()
.header("Origin", ORIGIN)
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", TARGET_PREFIX + "InitiateAuth")
.body(body)
.when().post("/")
.then()
.statusCode(400)
.header("Access-Control-Allow-Origin", equalTo(ORIGIN))
.body("__type", equalTo("SerializationException"));
}
@Test
void browserCanCompleteNewPasswordChallenge() throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"browser-cors-%s"}
""".formatted(UUID.randomUUID())).path("UserPool").path("Id").asText();
try {
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"browser",
"ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{"UserPoolId":"%s","Username":"browser-user",
"TemporaryPassword":"Temporary123!","MessageAction":"SUPPRESS"}
""".formatted(poolId)).then().statusCode(200);
Response response = given()
.header("Origin", ORIGIN)
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", TARGET_PREFIX + "InitiateAuth")
.header("X-Amz-User-Agent", "aws-sdk-js/3 browser")
.body("""
{"AuthFlow":"USER_PASSWORD_AUTH","ClientId":"%s",
"AuthParameters":{"USERNAME":"browser-user","PASSWORD":"Temporary123!"}}
""".formatted(clientId))
.when().post("/")
.then()
.statusCode(200)
.header("Access-Control-Allow-Origin", equalTo(ORIGIN))
.body("ChallengeName", equalTo("NEW_PASSWORD_REQUIRED"))
.extract().response();
JsonNode challenge = OBJECT_MAPPER.readTree(response.asByteArray());
given()
.header("Origin", ORIGIN)
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", TARGET_PREFIX + "RespondToAuthChallenge")
.body("""
{"ClientId":"%s","ChallengeName":"NEW_PASSWORD_REQUIRED","Session":"%s",
"ChallengeResponses":{"USERNAME":"browser-user","NEW_PASSWORD":"Permanent123!"}}
""".formatted(clientId, challenge.path("Session").asText()))
.when().post("/")
.then()
.statusCode(200)
.header("Access-Control-Allow-Origin", equalTo(ORIGIN))
.body("AuthenticationResult.AccessToken", notNullValue())
.body("AuthenticationResult.IdToken", notNullValue());
} finally {
cognitoAction("DeleteUserPool", """
{"UserPoolId":"%s"}
""".formatted(poolId)).then().statusCode(200);
}
}
@Test
void requestsWithoutOriginDoNotGetBrowserHeaders() {
cognitoAction("InitiateAuth", "{}")
.then()
.statusCode(400)
.header("Access-Control-Allow-Origin", nullValue());
}
@Test
void unlistedOriginsCannotUseTheSharedJsonPreflight() {
given()
.header("Origin", "https://not-allowed.example.test")
.header("Access-Control-Request-Method", "POST")
.header("Access-Control-Request-Headers", "content-type,x-amz-target")
.when().options("/")
.then()
.statusCode(405)
.header("Access-Control-Allow-Origin", nullValue())
.header("Access-Control-Allow-Headers", nullValue());
given()
.header("Origin", "https://not-allowed.example.test")
.header("X-Amz-Target", "DynamoDB_20120810.ListTables")
.contentType("application/x-amz-json-1.0")
.body("{}")
.when().post("/")
.then()
.statusCode(200)
.header("Access-Control-Allow-Origin", nullValue());
}
@ParameterizedTest
@CsvSource({"/,PUT,content-type;x-amz-target", "/,POST,content-type",
"/bucket/key,POST,content-type;x-amz-target", "/execute-api/missing/prod,POST,content-type;x-amz-target"})
void unrelatedPreflightsDoNotGetCognitoCors(String path, String method, String headers) {
given()
.header("Origin", "https://not-allowed.example.test")
.header("Access-Control-Request-Method", method)
.header("Access-Control-Request-Headers", headers.replace(';', ','))
.when().options(path)
.then()
.header("Access-Control-Allow-Origin", nullValue());
}
@Test
void aCognitoTargetDoesNotExposeAQueryResponseToAnUnlistedOrigin() {
given()
.header("Origin", "https://not-allowed.example.test")
.header("X-Amz-Target", TARGET_PREFIX + "InitiateAuth")
.contentType("application/x-www-form-urlencoded")
.body("Action=GetCallerIdentity&Version=2011-06-15")
.when().post("/")
.then()
.statusCode(200)
.header("Access-Control-Allow-Origin", nullValue());
}
@Test
void preflightDoesNotGrantPrivateNetworkAccessByDefault() {
given()
.header("Origin", ORIGIN)
.header("Access-Control-Request-Method", "POST")
.header("Access-Control-Request-Headers", "content-type,x-amz-target")
.header("Access-Control-Request-Private-Network", "true")
.when().options("/")
.then()
.statusCode(204)
.header("Access-Control-Allow-Private-Network", nullValue());
}
}