diff --git a/README.md b/README.md index e7dcde3..54dd3c0 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,44 @@ python3 tests/test_native_image_script.py These tests stub Maven and Docker to check packaging and failure handling. They are not run by Maven. The source-build CI workflow runs them separately from the real native smoke. +### Scoped CORS policies + +The request middleware uses `CorsConfig.policyForPath(path)` and its compiled +origin matcher for both preflight and actual requests. This requires the +`cors-config` implementation introduced by +[light-4j PR #2847](https://github.com/networknt/light-4j/pull/2847); upgrade the +middleware and framework artifact together. Older middleware that compares raw +origin strings does not support wildcard patterns. + +With `cors.enabled: true`, global and per-path origins support HTTP/HTTPS +patterns such as `https://*.example.com`, including nested subdomains and excluding +the apex. Explicit origins retain custom schemes, ASCII/Punycode hosts, and +normalized default ports. Public/private PSL suffixes and malformed patterns fail +validation. Per-path policies replace global origins and methods using the shared +first-prefix matching contract. Lambda retains explicit-allowlist matching and +does not add Undertow's implicit server-origin fallback. + +The request phase validates a single Origin across API Gateway's single-value +and multi-value header representations. Conflicting or duplicate values are +rejected. The response phase uses that validated request snapshot, returns the +actual Origin, and merges `Vary: Origin` with backend cache keys. No-Origin +requests pass through without CORS allow headers. Invalid configuration refreshes +retain the last valid policy; a missing configuration or absent `enabled` key +stays disabled. + +To qualify a coordinated source change locally without publishing artifacts, +check out the matching light-4j source in a sibling directory and run: + +```sh +mvn -f ../light-4j/pom.xml -pl cors-config -am install -DskipTests +mvn test -Dtest=CorsMiddlewareTest,CorsPolicyIntegrationTest +``` + +`CorsPolicyIntegrationTest` covers actual/preflight matching, path isolation, +custom schemes/default ports, API Gateway header ambiguity, reload, and response +snapshot/cache behavior without contacting AWS. Native-image and deployed AWS +qualification are separate from these JVM tests. + ### Test with Main We have provided a Main class in the src folder for testing all the middleware handlers with a sample request. You can run the Main class within your IDE with debug mode to see how each middleware handler works. diff --git a/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/RequestCorsMiddleware.java b/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/RequestCorsMiddleware.java index 79e8146..0c66fb2 100644 --- a/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/RequestCorsMiddleware.java +++ b/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/RequestCorsMiddleware.java @@ -4,7 +4,6 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.networknt.aws.lambda.LightLambdaExchange; import com.networknt.aws.lambda.handler.MiddlewareHandler; -import com.networknt.config.Config; import com.networknt.cors.CorsConfig; import com.networknt.status.Status; import com.networknt.utility.MapUtil; @@ -14,73 +13,43 @@ import java.util.*; import static com.networknt.cors.CorsHeaders.*; -import static com.networknt.cors.CorsUtil.sanitizeDefaultPort; -/** - * This middleware is responsible for adding CORS headers to the response and return it if the request - * is a CORS preflight request. If the preflight request has the correct origin and method, it will return - * 200 with the correct headers. Otherwise, 403 will be returned. - * - * If the request is a normal request with origin header and the origin is not matched, it will return 403. - * - * @author Steve Hu - * - */ +/** Validate CORS requests with the shared compiled cors-config policy. */ public class RequestCorsMiddleware implements MiddlewareHandler { private static final Logger LOG = LoggerFactory.getLogger(RequestCorsMiddleware.class); private static final String SUC10200 = "SUC10200"; private static final String CORS_PREFLIGHT_REQUEST_FAILED = "ERR10092"; - private static final String ONE_HOUR_IN_SECONDS = "3600"; - private final CorsConfig config; + static final LightLambdaExchange.Attachable ACCEPTED_ORIGIN = + LightLambdaExchange.Attachable.createAttachable(AcceptedOrigin.class); + record AcceptedOrigin(String origin, List methods) { } + private record OriginHeader(boolean present, String value) { } + public RequestCorsMiddleware() { - this.config = CorsConfig.load(); + CorsConfig.load(); LOG.info("RequestCorsMiddleware is constructed"); } @Override public Status execute(LightLambdaExchange exchange) { - LOG.trace("RequestCorsMiddleware.executeMiddleware starts."); - - APIGatewayProxyRequestEvent requestEvent = exchange.getRequest(); - if(requestEvent != null) { - LOG.trace("Request event is not null."); - - List allowedOrigins = config.getAllowedOrigins(); - List allowedMethods = config.getAllowedMethods(); - - Map requestHeaders = requestEvent.getHeaders(); - if(isCorsRequest(requestHeaders)) { - // set the allowed origins and methods based on the path prefix. - if (config.getPathPrefixAllowed() != null) { - String requestPath = requestEvent.getPath(); - for(Map.Entry entry: config.getPathPrefixAllowed().entrySet()) { - if (requestPath.startsWith(entry.getKey())) { - Map endpointCorsMap = (Map) entry.getValue(); - allowedOrigins = (List) endpointCorsMap.get(CorsConfig.ALLOWED_ORIGINS); - allowedMethods = (List) endpointCorsMap.get(CorsConfig.ALLOWED_METHODS); - break; - } - } - } - // if it is a preflight request, then handle it and return. - if (isPreflightedRequest(requestEvent.getHttpMethod())) { - // it is a preflight request. Handle it and return the response. - return handlePreflightRequest(exchange, allowedOrigins, allowedMethods); - } else { - // normal request with origin header. check the origin and reject if it is not matched. - String origin = matchOrigin(requestEvent, allowedOrigins); - if(origin == null) { - return new Status(CORS_PREFLIGHT_REQUEST_FAILED); - } - } + CorsConfig config = CorsConfig.load(); + if (!config.isEnabled()) return disabledMiddlewareStatus(); + APIGatewayProxyRequestEvent request = exchange.getRequest(); + if (request == null) return successMiddlewareStatus(); + OriginHeader header = originHeader(request); + if (!header.present) return successMiddlewareStatus(); + CorsConfig.Policy policy = config.policyForPath(request.getPath() == null ? "/" : request.getPath()); + if (header.value == null || !policy.origins().matches(header.value)) { + if (isPreflightedRequest(request.getHttpMethod())) { + exchange.setInitialResponse(new APIGatewayProxyResponseEvent().withIsBase64Encoded(false) + .withStatusCode(403).withHeaders(Map.of("Vary", "Origin"))); } + return new Status(CORS_PREFLIGHT_REQUEST_FAILED); } - // need to set the response header for the normal cors request that passed the origin check. It needs - // to be set in the response chain instead of request chain. - - LOG.trace("RequestCorsMiddleware.executeMiddleware ends."); + AcceptedOrigin accepted = new AcceptedOrigin(header.value, policy.methods()); + exchange.addAttachment(ACCEPTED_ORIGIN, accepted); + if (isPreflightedRequest(request.getHttpMethod())) return handlePreflightRequest(exchange, accepted); return successMiddlewareStatus(); } @@ -89,70 +58,45 @@ public boolean isEnabled() { return CorsConfig.load().isEnabled(); } - private Status handlePreflightRequest(LightLambdaExchange exchange, List allowedOrigins, List allowedMethods) { - APIGatewayProxyResponseEvent responseEvent = new APIGatewayProxyResponseEvent(); - responseEvent.setIsBase64Encoded(false); + private Status handlePreflightRequest(LightLambdaExchange exchange, AcceptedOrigin accepted) { + Map headers = new LinkedHashMap<>(); + headers.put(ACCESS_CONTROL_ALLOW_ORIGIN, accepted.origin); + headers.put("Vary", "Origin"); + headers.put(ACCESS_CONTROL_ALLOW_METHODS, convertToString(accepted.methods)); Map requestHeaders = exchange.getRequest().getHeaders(); - Map responseHeaders = new HashMap<>(); - if (MapUtil.getValueIgnoreCase(requestHeaders, ORIGIN).isPresent()) { - if(matchOrigin(exchange.getRequest(), allowedOrigins) != null) { - responseHeaders.put(ACCESS_CONTROL_ALLOW_ORIGIN, MapUtil.getValueIgnoreCase(requestHeaders, ORIGIN).get()); - responseHeaders.put("Vary", "Origin"); - } else { - responseEvent.setHeaders(responseHeaders); - responseEvent.setStatusCode(403); - exchange.setInitialResponse(responseEvent); - return new Status(CORS_PREFLIGHT_REQUEST_FAILED); - } - } - responseHeaders.put(ACCESS_CONTROL_ALLOW_METHODS, convertToString(allowedMethods)); - Optional acRequestHeaders = MapUtil.getValueIgnoreCase(requestHeaders, ACCESS_CONTROL_REQUEST_HEADERS); - if (acRequestHeaders.isPresent()) { - responseHeaders.put(ACCESS_CONTROL_ALLOW_HEADERS, acRequestHeaders.get()); - } else { - responseHeaders.put(ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type, WWW-Authenticate, Authorization"); - } - responseHeaders.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); - responseHeaders.put(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS); - responseEvent.setHeaders(responseHeaders); - responseEvent.setStatusCode(200); - exchange.setInitialResponse(responseEvent); + String requestedHeaders = requestHeaders == null ? null + : MapUtil.getValueIgnoreCase(requestHeaders, ACCESS_CONTROL_REQUEST_HEADERS).orElse(null); + headers.put(ACCESS_CONTROL_ALLOW_HEADERS, requestedHeaders == null + ? "Content-Type, WWW-Authenticate, Authorization" : requestedHeaders); + headers.put(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); + headers.put(ACCESS_CONTROL_MAX_AGE, ONE_HOUR_IN_SECONDS); + exchange.setInitialResponse(new APIGatewayProxyResponseEvent().withIsBase64Encoded(false) + .withStatusCode(200).withHeaders(headers)); return new Status(SUC10200); } - /** - * Match the Origin header with the allowed origins. - * If it doesn't match then a 403 response code is set on the response and it returns null. - * @param requestEvent the current request event. - * @param allowedOrigins list of sanitized allowed origins. - * @return the first matching origin, null otherwise. - */ - static String matchOrigin(APIGatewayProxyRequestEvent requestEvent, Collection allowedOrigins) { - Map requestHeaders = requestEvent.getHeaders(); - Optional optionalOrigin = MapUtil.getValueIgnoreCase(requestHeaders, ORIGIN); - String origin = optionalOrigin.orElse(null); - LOG.trace("origin from the request header = {} allowedOrigins = {}", origin, allowedOrigins); - if (origin != null && allowedOrigins != null && !allowedOrigins.isEmpty()) { - for (String allowedOrigin : allowedOrigins) { - if (allowedOrigin.equalsIgnoreCase(sanitizeDefaultPort(origin))) { - return allowedOrigin; - } - } + private static OriginHeader originHeader(APIGatewayProxyRequestEvent request) { + List singles = originValues(request.getHeaders()); + List> multiples = originValues(request.getMultiValueHeaders()); + boolean present = !singles.isEmpty() || !multiples.isEmpty(); + if (!present || singles.size() > 1 || multiples.size() > 1) return new OriginHeader(present, null); + if (!multiples.isEmpty()) { + List values = multiples.getFirst(); + if (values == null || values.size() != 1) return new OriginHeader(true, null); + String value = values.getFirst(); + return new OriginHeader(true, singles.isEmpty() || Objects.equals(singles.getFirst(), value) ? value : null); } - LOG.debug("Request rejected due to HOST/ORIGIN mis-match."); - return null; + return new OriginHeader(true, singles.getFirst()); } - static boolean isCorsRequest(Map requestHeaders) { - // all cors request will have origin header regardless it is a preflight request - // or normal request with method other than OPTIONS. - return MapUtil.getValueIgnoreCase(requestHeaders, ORIGIN).isPresent(); + private static List originValues(Map headers) { + if (headers == null) return List.of(); + return headers.entrySet().stream().filter(entry -> ORIGIN.equalsIgnoreCase(entry.getKey())) + .map(Map.Entry::getValue).toList(); } - static boolean isPreflightedRequest(String requestMethod) { - // only the preflight request will have OPTIONS method, and it should be checked - // after it is confirmed a cors request with origin header. - return "OPTIONS".equalsIgnoreCase(requestMethod); + static boolean isPreflightedRequest(String method) { + return "OPTIONS".equalsIgnoreCase(method); } static String convertToString(List list) { diff --git a/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/ResponseCorsMiddleware.java b/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/ResponseCorsMiddleware.java index 627cbe1..eda23c2 100644 --- a/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/ResponseCorsMiddleware.java +++ b/src/main/java/com/networknt/aws/lambda/handler/middleware/cors/ResponseCorsMiddleware.java @@ -3,57 +3,52 @@ import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.networknt.aws.lambda.LightLambdaExchange; import com.networknt.aws.lambda.handler.MiddlewareHandler; -import com.networknt.config.Config; import com.networknt.cors.CorsConfig; import com.networknt.status.Status; -import com.networknt.utility.MapUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * This middleware is responsible for adding CORS headers to the response if the request is a CORS request. - * It means the request has a header Origin. The middleware will add the following headers to the response: - * Access-Control-Allow-Origin: The value of the Origin header - * Access-Control-Allow-Methods: The value of the Access-Control-Request-Method header - * - * @author Steve Hu - */ -public class ResponseCorsMiddleware implements MiddlewareHandler { - - private static final Logger LOG = LoggerFactory.getLogger(ResponseCorsMiddleware.class); - - public ResponseCorsMiddleware() { - LOG.info("ResponseCorsMiddleware is constructed"); - } +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; +import static com.networknt.cors.CorsHeaders.*; +/** Apply the request's validated origin/policy snapshot after downstream response headers exist. */ +public class ResponseCorsMiddleware implements MiddlewareHandler { @Override public Status execute(LightLambdaExchange exchange) { - if(LOG.isTraceEnabled()) LOG.trace("RequestCorsMiddleware.executeMiddleware starts."); - CorsConfig config = CorsConfig.load(); - if (!config.isEnabled()) { - if(LOG.isTraceEnabled()) LOG.trace("RequestCorsMiddleware is not enabled."); - return disabledMiddlewareStatus(); - } - APIGatewayProxyResponseEvent responseEvent = exchange.getResponse(); - if(responseEvent != null) { - if (LOG.isTraceEnabled()) LOG.trace("Response event is not null."); - var responseHeaders = responseEvent.getHeaders(); - if (responseHeaders != null) { - if (LOG.isTraceEnabled()) LOG.trace("Response headers is not null."); - if (MapUtil.getValueIgnoreCase(exchange.getReadOnlyRequest().getHeaders(), "Origin").isPresent()) { - // this is a CORS request, and it is passed the CORS check in the RequestCorsMiddleware. - responseHeaders.put("Access-Control-Allow-Origin", exchange.getReadOnlyRequest().getHeaders().get("Origin")); - } - } + RequestCorsMiddleware.AcceptedOrigin accepted = exchange.getAttachment(RequestCorsMiddleware.ACCEPTED_ORIGIN); + if (accepted == null && !CorsConfig.load().isEnabled()) return disabledMiddlewareStatus(); + APIGatewayProxyResponseEvent response = exchange.getResponse(); + if (response == null) return successMiddlewareStatus(); + Map headers = new LinkedHashMap<>(); + if (response.getHeaders() != null) headers.putAll(response.getHeaders()); + addVaryOrigin(headers); + if (accepted != null) { + putHeader(headers, ACCESS_CONTROL_ALLOW_ORIGIN, accepted.origin()); + putHeader(headers, ACCESS_CONTROL_ALLOW_METHODS, RequestCorsMiddleware.convertToString(accepted.methods())); + putHeader(headers, ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } - if(LOG.isTraceEnabled()) LOG.trace("RequestCorsMiddleware.executeMiddleware ends."); + response.setHeaders(headers); return successMiddlewareStatus(); } + private static void addVaryOrigin(Map headers) { + String vary = headers.entrySet().stream().filter(entry -> "Vary".equalsIgnoreCase(entry.getKey())) + .map(Map.Entry::getValue).filter(Objects::nonNull).collect(Collectors.joining(", ")); + boolean covered = Arrays.stream(vary.split(",")).map(String::trim) + .anyMatch(token -> token.equals("*") || token.equalsIgnoreCase("Origin")); + putHeader(headers, "Vary", covered ? vary : vary.isBlank() ? "Origin" : vary + ", Origin"); + } + + private static void putHeader(Map headers, String name, String value) { + headers.keySet().removeIf(key -> name.equalsIgnoreCase(key)); + headers.put(name, value); + } + @Override public boolean isEnabled() { return CorsConfig.load().isEnabled(); } - } diff --git a/src/test/java/com/networknt/aws/lambda/middleware/cors/CorsPolicyIntegrationTest.java b/src/test/java/com/networknt/aws/lambda/middleware/cors/CorsPolicyIntegrationTest.java new file mode 100644 index 0000000..4ed6036 --- /dev/null +++ b/src/test/java/com/networknt/aws/lambda/middleware/cors/CorsPolicyIntegrationTest.java @@ -0,0 +1,140 @@ +package com.networknt.aws.lambda.middleware.cors; + +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; +import com.networknt.aws.lambda.LightLambdaExchange; +import com.networknt.aws.lambda.handler.chain.Chain; +import com.networknt.aws.lambda.handler.middleware.cors.RequestCorsMiddleware; +import com.networknt.aws.lambda.handler.middleware.cors.ResponseCorsMiddleware; +import com.networknt.config.Config; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class CorsPolicyIntegrationTest { + private Map original; + + @BeforeEach + void saveConfig() { + original = Config.getInstance().getJsonMapConfig("cors"); + } + + @AfterEach + void restoreConfig() { + if (original == null) Config.getInstance().clearConfigCache("cors"); + else Config.getInstance().putInConfigCache("cors", original); + } + + private static void configure() { + Config.getInstance().putInConfigCache("cors", Map.of("enabled", true, + "allowedOrigins", List.of("https://*.example.com", "capacitor://localhost", "https://example.org:443"), + "allowedMethods", List.of("GET", "PUT"), "pathPrefixAllowed", + Map.of("/private", Map.of("allowedOrigins", List.of("https://trusted.example.com"), "allowedMethods", List.of("GET"))))); + } + + @Test + void sharedCompiledPolicyAcceptsWildcardsCustomSchemesAndNormalizedPorts() { + configure(); + RequestCorsMiddleware middleware = new RequestCorsMiddleware(); + for (String method : List.of("GET", "OPTIONS")) { + for (String origin : List.of("https://app.example.com", "https://team.app.example.com:443", "capacitor://localhost", "https://example.org")) { + LightLambdaExchange exchange = exchange("/public", method, origin); + assertEquals(200, middleware.execute(exchange).getStatusCode(), origin); + if (method.equals("OPTIONS")) assertEquals(origin, exchange.getResponse().getHeaders().get("Access-Control-Allow-Origin")); + } + } + } + + @Test + void perPathPolicyReplacesGlobalAndRejectsInvalidOrUntrustedOrigins() { + configure(); + RequestCorsMiddleware middleware = new RequestCorsMiddleware(); + for (String method : List.of("GET", "OPTIONS")) { + for (String origin : List.of("https://example.com", "https://badexample.com", "https://example.com.attacker.net", + "http://app.example.com", "https://app.example.com:8443", "https://app.example.com/", "null")) { + assertEquals(403, middleware.execute(exchange("/public", method, origin)).getStatusCode(), origin); + } + assertEquals(403, middleware.execute(exchange("/private", method, "https://app.example.com")).getStatusCode()); + assertEquals(200, middleware.execute(exchange("/private", method, "https://trusted.example.com")).getStatusCode()); + } + } + + @Test + void responseUsesValidatedRequestSnapshotAndPreservesBackendVary() { + configure(); + LightLambdaExchange exchange = exchange("/public", "GET", "https://app.example.com"); + assertEquals(200, new RequestCorsMiddleware().execute(exchange).getStatusCode()); + Config.getInstance().putInConfigCache("cors", Map.of("enabled", true, + "allowedOrigins", List.of("https://other.example.org"), "allowedMethods", List.of("POST"))); + exchange.setInitialResponse(new APIGatewayProxyResponseEvent().withStatusCode(200) + .withHeaders(new LinkedHashMap<>(Map.of("Vary", "Accept-Encoding")))); + assertEquals(200, new ResponseCorsMiddleware().execute(exchange).getStatusCode()); + Map headers = exchange.getResponse().getHeaders(); + assertEquals("https://app.example.com", headers.get("Access-Control-Allow-Origin")); + assertEquals("true", headers.get("Access-Control-Allow-Credentials")); + assertEquals("GET,PUT", headers.get("Access-Control-Allow-Methods")); + assertTrue(headers.get("Vary").contains("Accept-Encoding")); + assertTrue(headers.get("Vary").contains("Origin")); + } + + @Test + void duplicateOrConflictingOriginRepresentationsAreRejected() { + configure(); + RequestCorsMiddleware middleware = new RequestCorsMiddleware(); + for (String method : List.of("GET", "OPTIONS")) { + LightLambdaExchange duplicate = exchange("/public", method, "https://app.example.com"); + duplicate.getRequest().getHeaders().put("origin", "https://app.example.com"); + assertEquals(403, middleware.execute(duplicate).getStatusCode()); + LightLambdaExchange multiple = exchange("/public", method, "https://app.example.com"); + multiple.getRequest().setMultiValueHeaders(Map.of("Origin", List.of("https://app.example.com", "https://evil.net"))); + assertEquals(403, middleware.execute(multiple).getStatusCode()); + LightLambdaExchange conflicting = exchange("/public", method, "https://app.example.com"); + conflicting.getRequest().setMultiValueHeaders(Map.of("Origin", List.of("https://other.example.com"))); + assertEquals(403, middleware.execute(conflicting).getStatusCode()); + LightLambdaExchange consistent = exchange("/public", method, "https://app.example.com"); + consistent.getRequest().setMultiValueHeaders(Map.of("oRiGiN", List.of("https://app.example.com"))); + assertEquals(200, middleware.execute(consistent).getStatusCode()); + LightLambdaExchange multiOnly = exchange("/public", method, "https://app.example.com"); + multiOnly.getRequest().setHeaders(null); + multiOnly.getRequest().setMultiValueHeaders(Map.of("origin", List.of("https://app.example.com"))); + assertEquals(200, middleware.execute(multiOnly).getStatusCode()); + } + } + + @Test + void middlewareReloadsPoliciesAndNoOriginResponsesKeepCacheVariation() { + configure(); + RequestCorsMiddleware middleware = new RequestCorsMiddleware(); + assertEquals(200, middleware.execute(exchange("/public", "GET", "https://app.example.com")).getStatusCode()); + Config.getInstance().putInConfigCache("cors", Map.of("enabled", true, + "allowedOrigins", List.of("https://other.example.org"), "allowedMethods", List.of("GET"))); + assertEquals(403, middleware.execute(exchange("/public", "GET", "https://app.example.com")).getStatusCode()); + assertEquals(200, middleware.execute(exchange("/public", "GET", "https://other.example.org")).getStatusCode()); + for (String vary : List.of("Accept-Encoding", "*", "origin")) { + LightLambdaExchange noOrigin = exchange("/public", "GET", "https://app.example.com"); + noOrigin.getRequest().setHeaders(Map.of("Access-Control-Request-Method", "PUT")); + assertEquals(200, middleware.execute(noOrigin).getStatusCode()); + noOrigin.setInitialResponse(new APIGatewayProxyResponseEvent().withStatusCode(200) + .withHeaders(Map.of("vary", vary))); + assertEquals(200, new ResponseCorsMiddleware().execute(noOrigin).getStatusCode()); + Map headers = noOrigin.getResponse().getHeaders(); + assertNull(headers.get("Access-Control-Allow-Origin")); + assertTrue(headers.get("Vary").contains(vary)); + if (vary.equals("Accept-Encoding")) assertTrue(headers.get("Vary").contains("Origin")); + else assertEquals(vary, headers.get("Vary")); + } + } + + private static LightLambdaExchange exchange(String path, String method, String origin) { + LightLambdaExchange exchange = new LightLambdaExchange(null, new Chain()); + exchange.setInitialRequest(new APIGatewayProxyRequestEvent().withPath(path).withHttpMethod(method) + .withHeaders(new LinkedHashMap<>(Map.of("Origin", origin)))); + return exchange; + } +}