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

@@ -51,6 +51,11 @@ Running Floci directly on a Linux host (not in a container) with services that s
| `FLOCI_SECURITY_DISABLE_CORS_HEADERS` | `false` | Disable Floci's global CORS response headers. Alias: `DISABLE_CORS_HEADERS` |
| `FLOCI_SECURITY_CORS_ALLOW_PRIVATE_NETWORK` | `false` | Answer Private Network Access preflights with `Access-Control-Allow-Private-Network: true`, letting a page on a public/secure origin reach this loopback backend. Only applies after the origin passes the allow-list above. |
The [Cognito JSON API](../services/cognito.md) follows this same origin allow-list,
including its empty default, for both preflights and actual responses. For allowed
origins, Cognito's request ID and error headers are exposed alongside configured extra
exposed headers. The disable-CORS switch above also disables this behavior.
---
## TLS / HTTPS
+15
View File
@@ -3,6 +3,21 @@
**Protocol:** JSON 1.1 (`X-Amz-Target: AWSCognitoIdentityProviderService.*`)
**Endpoint:** `POST http://localhost:4566/`
Browser clients can call the Cognito JSON API after their origin is admitted by
`EXTRA_CORS_ALLOWED_ORIGINS` or `FLOCI_SECURITY_EXTRA_CORS_ALLOWED_ORIGINS`.
For example, set `EXTRA_CORS_ALLOWED_ORIGINS=http://localhost:3000` for a local frontend.
The default allow-list is empty. Unlisted origins receive no CORS headers, including on
preflights and on successful or failed Cognito responses.
The global CORS filter answers allowed preflights with 204 and supplies the allowed
origin and request headers, including `content-type`, `x-amz-target`, and `x-amz-user-agent`.
For allowed origins, Cognito responses also expose the AWS request ID and error headers.
Those names are merged with configured extra exposed headers and any existing exposed
headers, without duplicates that differ only in case. The global filter also controls
Private Network Access and explicit wildcard-origin configuration.
`FLOCI_SECURITY_DISABLE_CORS_HEADERS=true` disables CORS headers. Disabling the Cognito
service disables its extra exposed headers. S3 and API Gateway retain their existing CORS policies.
Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys.
When configured, `PreAuthentication`, `PostAuthentication` and `PreTokenGeneration` Lambda triggers
@@ -0,0 +1,83 @@
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.MemoizedSupplier;
import io.floci.aws.core.common.ProtocolClaim;
import io.floci.aws.core.common.WireProtocol;
import jakarta.annotation.Priority;
import jakarta.inject.Inject;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.Provider;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/** Cognito exposed headers for browser origins admitted by the global CORS policy. */
@Provider
@Priority(Priorities.HEADER_DECORATOR + 1)
public class CognitoCorsFilter implements ContainerResponseFilter {
private static final String EXPOSE_HEADERS = "x-amzn-RequestId,x-amzn-ErrorType,x-amzn-ErrorMessage,Date";
private final MemoizedSupplier<EmulatorConfig> config;
@Inject
public CognitoCorsFilter(jakarta.inject.Provider<EmulatorConfig> configProvider) {
// Qualify the CDI Provider to distinguish it from the JAX-RS annotation.
config = new MemoizedSupplier<>(configProvider::get);
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
if (!isBrowserRootRequest(requestContext)
|| !(requestContext.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim)
|| claim.protocol() != WireProtocol.AWS_JSON_1_1 || claim.service() == null
|| !"cognito-idp".equals(claim.service().externalKey())
|| !enabledForOrigin(requestContext.getHeaderString("Origin"))) {
return;
}
mergeExposedHeaders(responseContext.getHeaders());
}
private boolean enabledForOrigin(String origin) {
EmulatorConfig config = this.config.get();
EmulatorConfig.SecurityConfig security = config.security();
return config.services().cognito().enabled() && !security.disableCorsHeaders()
&& security.extraCorsAllowedOrigins().orElse(List.of()).stream()
.anyMatch(allowed -> "*".equals(allowed) || allowed.equalsIgnoreCase(origin));
}
private void mergeExposedHeaders(MultivaluedMap<String, Object> headers) {
Set<String> exposedHeaders = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
addHeaderNames(exposedHeaders, EXPOSE_HEADERS);
for (Object value : headers.getOrDefault("Access-Control-Expose-Headers", List.of())) {
addHeaderNames(exposedHeaders, String.valueOf(value));
}
EmulatorConfig.SecurityConfig security = config.get().security();
security.extraCorsExposeHeaders().ifPresent(values ->
values.forEach(value -> addHeaderNames(exposedHeaders, value)));
headers.putSingle("Access-Control-Expose-Headers", String.join(", ", exposedHeaders));
}
private static void addHeaderNames(Set<String> names, String value) {
Arrays.stream(value.split(","))
.map(String::trim)
.filter(name -> !name.isEmpty())
.forEach(names::add);
}
private static boolean isBrowserRootRequest(ContainerRequestContext requestContext) {
String origin = requestContext.getHeaderString("Origin");
String path = requestContext.getUriInfo().getPath();
return origin != null && !origin.isBlank() && (path.isEmpty() || "/".equals(path));
}
}
@@ -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());
}
}