summaryrefslogtreecommitdiffstats
path: root/jdisc-security-filters
diff options
context:
space:
mode:
authorBjørn Christian Seime <bjorncs@oath.com>2018-04-05 13:06:20 +0200
committerBjørn Christian Seime <bjorncs@oath.com>2018-04-09 12:49:33 +0200
commit467ec6be1c0f7fd20eb0a4fea065671f51809740 (patch)
treea25cc0b96974df04bca30d7fc0c3badda42f56cd /jdisc-security-filters
parentfb46c366e01128f48d478b28ee39ba8f1d71acc4 (diff)
Add new module jdisc-security-filters
* Add new base class for security filters supporting CORS headers * Add CORS response filter and preflight request filter
Diffstat (limited to 'jdisc-security-filters')
-rw-r--r--jdisc-security-filters/OWNERS1
-rw-r--r--jdisc-security-filters/pom.xml60
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsLogic.java56
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilter.java61
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBase.java81
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilter.java38
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/package-info.java8
-rw-r--r--jdisc-security-filters/src/main/resources/configdefinitions/cors-security-filter.def4
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilterTest.java78
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBaseTest.java60
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilterTest.java112
11 files changed, 559 insertions, 0 deletions
diff --git a/jdisc-security-filters/OWNERS b/jdisc-security-filters/OWNERS
new file mode 100644
index 00000000000..fb71c67318d
--- /dev/null
+++ b/jdisc-security-filters/OWNERS
@@ -0,0 +1 @@
+bjorncs \ No newline at end of file
diff --git a/jdisc-security-filters/pom.xml b/jdisc-security-filters/pom.xml
new file mode 100644
index 00000000000..bcee244ef69
--- /dev/null
+++ b/jdisc-security-filters/pom.xml
@@ -0,0 +1,60 @@
+<?xml version="1.0"?>
+<!-- Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
+ http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <artifactId>jdisc-security-filters</artifactId>
+ <packaging>container-plugin</packaging>
+ <version>6-SNAPSHOT</version>
+
+ <parent>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>parent</artifactId>
+ <version>6-SNAPSHOT</version>
+ <relativePath>../parent/pom.xml</relativePath>
+ </parent>
+ <dependencies>
+ <!-- provided -->
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>container-dev</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- test -->
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>container-test</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsLogic.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsLogic.java
new file mode 100644
index 00000000000..3f1aeff9e95
--- /dev/null
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsLogic.java
@@ -0,0 +1,56 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.google.common.collect.ImmutableMap;
+import com.yahoo.jdisc.HeaderFields;
+import com.yahoo.jdisc.Response;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * @author bjorncs
+ */
+class CorsLogic {
+ private CorsLogic() {}
+
+ static final String CORS_PREFLIGHT_REQUEST_CACHE_TTL = Long.toString(Duration.ofDays(7).getSeconds());
+
+ static final String ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin";
+
+ static final Map<String, String> ACCESS_CONTROL_HEADERS = ImmutableMap.of(
+ "Access-Control-Max-Age", CORS_PREFLIGHT_REQUEST_CACHE_TTL,
+ "Access-Control-Allow-Headers", "Origin,Content-Type,Accept,Yahoo-Principal-Auth",
+ "Access-Control-Allow-Methods", "OPTIONS,GET,PUT,DELETE,POST",
+ "Access-Control-Allow-Credentials", "true"
+ );
+
+ static Map<String, String> createCorsResponseHeaders(String requestOriginHeader,
+ Set<String> allowedOrigins) {
+ if (requestOriginHeader == null) return Collections.emptyMap();
+ TreeMap<String, String> headers = new TreeMap<>();
+ allowedOrigins.stream()
+ .filter(allowedUrl -> matchesRequestOrigin(requestOriginHeader, allowedUrl))
+ .findAny()
+ .ifPresent(allowedOrigin -> headers.put(ALLOW_ORIGIN_HEADER, allowedOrigin));
+ ACCESS_CONTROL_HEADERS.forEach(headers::put);
+ return headers;
+ }
+
+ static Map<String, String> createCorsPreflightResponseHeaders(String requestOriginHeader,
+ Set<String> allowedOrigins) {
+ TreeMap<String, String> headers = new TreeMap<>();
+ if (allowedOrigins.contains(requestOriginHeader))
+ headers.put(ALLOW_ORIGIN_HEADER, requestOriginHeader);
+ ACCESS_CONTROL_HEADERS.forEach(headers::put);
+ return headers;
+ }
+
+ private static boolean matchesRequestOrigin(String requestOrigin, String allowedUrl) {
+ return allowedUrl.equals("*") || requestOrigin.startsWith(allowedUrl);
+ }
+}
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilter.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilter.java
new file mode 100644
index 00000000000..d162fff53b1
--- /dev/null
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilter.java
@@ -0,0 +1,61 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.google.inject.Inject;
+import com.yahoo.jdisc.Response;
+import com.yahoo.jdisc.handler.ContentChannel;
+import com.yahoo.jdisc.handler.ResponseHandler;
+import com.yahoo.jdisc.http.HttpResponse;
+import com.yahoo.jdisc.http.filter.DiscFilterRequest;
+import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
+import com.yahoo.yolean.chain.Provides;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import static com.yahoo.jdisc.http.HttpRequest.Method.OPTIONS;
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.createCorsPreflightResponseHeaders;
+
+/**
+ * <p>
+ * This filter makes sure we respond as quickly as possible to CORS pre-flight requests
+ * which browsers transmit before the Hosted Vespa dashboard code is allowed to send a "real" request.
+ * </p>
+ * <p>
+ * An "Access-Control-Max-Age" header is added so that the browser will cache the result of this pre-flight request,
+ * further improving the responsiveness of the Hosted Vespa dashboard application.
+ * </p>
+ * <p>
+ * Runs after all standard security request filters, but before BouncerFilter, as the browser does not send
+ * credentials with pre-flight requests.
+ * </p>
+ *
+ * @author andreer
+ * @author gv
+ * @author bjorncs
+ */
+@Provides("CorsPreflightSecurityRequestFilter")
+public class CorsPreflightSecurityRequestFilter implements SecurityRequestFilter {
+ private final Set<String> allowedUrls;
+
+ @Inject
+ public CorsPreflightSecurityRequestFilter(CorsSecurityFilterConfig config) {
+ this.allowedUrls = new HashSet<>(config.allowedUrls());
+ }
+
+ @Override
+ public void filter(DiscFilterRequest discFilterRequest, ResponseHandler responseHandler) {
+ String origin = discFilterRequest.getHeader("Origin");
+
+ if (!discFilterRequest.getMethod().equals(OPTIONS.name()))
+ return;
+
+ HttpResponse response = HttpResponse.newInstance(Response.Status.OK);
+
+ createCorsPreflightResponseHeaders(origin, allowedUrls)
+ .forEach(response.headers()::put);
+
+ ContentChannel cc = responseHandler.handleResponse(response);
+ cc.close(null);
+ }
+}
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBase.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBase.java
new file mode 100644
index 00000000000..fd64aa37875
--- /dev/null
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBase.java
@@ -0,0 +1,81 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.yahoo.jdisc.Response;
+import com.yahoo.jdisc.handler.FastContentWriter;
+import com.yahoo.jdisc.handler.ResponseDispatch;
+import com.yahoo.jdisc.handler.ResponseHandler;
+import com.yahoo.jdisc.http.filter.DiscFilterRequest;
+import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
+
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.createCorsResponseHeaders;
+
+/**
+ * Security request filters should extend this base class to ensure that CORS header are included in the response of a rejected request.
+ * This is required as response filter chains are not executed when a request is rejected in a request filter.
+ *
+ * @author bjorncs
+ */
+public abstract class CorsSecurityRequestFilterBase implements SecurityRequestFilter {
+
+ private static final ObjectMapper mapper = new ObjectMapper();
+
+ private final Set<String> allowedUrls;
+
+ protected CorsSecurityRequestFilterBase(CorsSecurityFilterConfig config) {
+ this(new HashSet<>(config.allowedUrls()));
+ }
+
+ protected CorsSecurityRequestFilterBase(Set<String> allowedUrls) {
+ this.allowedUrls = allowedUrls;
+ }
+
+ @Override
+ public final void filter(DiscFilterRequest request, ResponseHandler handler) {
+ filter(request)
+ .ifPresent(errorResponse -> sendErrorResponse(request, errorResponse, handler));
+ }
+
+ protected abstract Optional<ErrorResponse> filter(DiscFilterRequest request);
+
+ private void sendErrorResponse(DiscFilterRequest request,
+ ErrorResponse errorResponse,
+ ResponseHandler responseHandler) {
+ Response response = new Response(errorResponse.statusCode);
+ addHeaders(request, response);
+ writeResponse(errorResponse, responseHandler, response);
+ }
+
+ private void addHeaders(DiscFilterRequest request, Response response) {
+ createCorsResponseHeaders(request.getHeader("Origin"), allowedUrls)
+ .forEach(response.headers()::add);
+ response.headers().add("Content-Type", "application/json");
+ }
+
+ private void writeResponse(ErrorResponse errorResponse, ResponseHandler responseHandler, Response response) {
+ ObjectNode errorMessage = mapper.createObjectNode();
+ errorMessage.put("message", errorResponse.message);
+ try (FastContentWriter writer = ResponseDispatch.newInstance(response).connectFastWriter(responseHandler)) {
+ writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(errorMessage));
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ protected static class ErrorResponse {
+ final int statusCode;
+ final String message;
+
+ public ErrorResponse(int statusCode, String message) {
+ this.statusCode = statusCode;
+ this.message = message;
+ }
+ }
+}
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilter.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilter.java
new file mode 100644
index 00000000000..bf288661bc4
--- /dev/null
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilter.java
@@ -0,0 +1,38 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.google.inject.Inject;
+import com.yahoo.jdisc.AbstractResource;
+import com.yahoo.jdisc.http.filter.DiscFilterResponse;
+import com.yahoo.jdisc.http.filter.RequestView;
+import com.yahoo.jdisc.http.filter.SecurityResponseFilter;
+import com.yahoo.yolean.chain.Provides;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.createCorsResponseHeaders;
+
+
+/**
+ * @author gv
+ * @author Tony Vaagenes
+ * @author bjorncs
+ */
+@Provides("CorsSecurityResponseFilter")
+public class CorsSecurityResponseFilter extends AbstractResource implements SecurityResponseFilter {
+
+ private final Set<String> allowedUrls;
+
+ @Inject
+ public CorsSecurityResponseFilter(CorsSecurityFilterConfig config) {
+ this.allowedUrls = new HashSet<>(config.allowedUrls());
+ }
+
+ @Override
+ public void filter(DiscFilterResponse response, RequestView request) {
+ createCorsResponseHeaders(request.getFirstHeader("Origin").orElse(null), allowedUrls)
+ .forEach(response::setHeader);
+ }
+
+}
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/package-info.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/package-info.java
new file mode 100644
index 00000000000..6357acc4e99
--- /dev/null
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filters/cors/package-info.java
@@ -0,0 +1,8 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+/**
+ * @author bjorncs
+ */
+@ExportPackage
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.yahoo.osgi.annotation.ExportPackage; \ No newline at end of file
diff --git a/jdisc-security-filters/src/main/resources/configdefinitions/cors-security-filter.def b/jdisc-security-filters/src/main/resources/configdefinitions/cors-security-filter.def
new file mode 100644
index 00000000000..71d4b998b99
--- /dev/null
+++ b/jdisc-security-filters/src/main/resources/configdefinitions/cors-security-filter.def
@@ -0,0 +1,4 @@
+# Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+namespace=jdisc.http.filters.cors
+
+allowedUrls[] string
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilterTest.java
new file mode 100644
index 00000000000..cb934c32bee
--- /dev/null
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsPreflightSecurityRequestFilterTest.java
@@ -0,0 +1,78 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.yahoo.jdisc.HeaderFields;
+import com.yahoo.jdisc.Response;
+import com.yahoo.jdisc.handler.ContentChannel;
+import com.yahoo.jdisc.handler.ResponseHandler;
+import com.yahoo.jdisc.http.filter.DiscFilterRequest;
+import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
+import com.yahoo.jdisc.http.filters.cors.CorsSecurityFilterConfig.Builder;
+import org.junit.Test;
+
+import java.util.Arrays;
+
+import static com.yahoo.jdisc.http.HttpRequest.Method.OPTIONS;
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.ACCESS_CONTROL_HEADERS;
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+
+/**
+ * @author gjoranv
+ * @author bjorncs
+ */
+public class CorsPreflightSecurityRequestFilterTest {
+
+ @Test
+ public void any_options_request_yields_access_control_headers_in_response() {
+ HeaderFields headers = doFilterRequest(newRequestFilter(), "http://any.origin");
+ ACCESS_CONTROL_HEADERS.keySet().forEach(
+ header -> assertFalse("Empty header: " + header, headers.getFirst(header).isEmpty()));
+ }
+
+ @Test
+ public void allowed_request_origin_yields_allow_origin_header_in_response() {
+ final String ALLOWED_ORIGIN = "http://allowed.origin";
+ HeaderFields headers = doFilterRequest(newRequestFilter(ALLOWED_ORIGIN), ALLOWED_ORIGIN);
+ assertEquals(ALLOWED_ORIGIN, headers.getFirst(ALLOW_ORIGIN_HEADER));
+ }
+
+ @Test
+ public void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
+ HeaderFields headers = doFilterRequest(newRequestFilter("http://allowed.origin"), "http://disallowed.origin");
+ assertNull(headers.getFirst(ALLOW_ORIGIN_HEADER));
+ }
+
+ private static HeaderFields doFilterRequest(SecurityRequestFilter filter, String originUrl) {
+ AccessControlResponseHandler responseHandler = new AccessControlResponseHandler();
+ filter.filter(newOptionsRequest(originUrl), responseHandler);
+ return responseHandler.response.headers();
+ }
+
+ private static DiscFilterRequest newOptionsRequest(String origin) {
+ DiscFilterRequest request = mock(DiscFilterRequest.class);
+ when(request.getHeader("Origin")).thenReturn(origin);
+ when(request.getMethod()).thenReturn(OPTIONS.name());
+ return request;
+ }
+
+ private static CorsPreflightSecurityRequestFilter newRequestFilter(String... allowedOriginUrls) {
+ Builder builder = new Builder();
+ Arrays.asList(allowedOriginUrls).forEach(builder::allowedUrls);
+ return new CorsPreflightSecurityRequestFilter(new CorsSecurityFilterConfig(builder));
+ }
+
+ private static class AccessControlResponseHandler implements ResponseHandler {
+ Response response;
+
+ @Override
+ public ContentChannel handleResponse(Response response) {
+ this.response = response;
+ return mock(ContentChannel.class);
+ }
+ }
+
+}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBaseTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBaseTest.java
new file mode 100644
index 00000000000..65fb78cdbd6
--- /dev/null
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityRequestFilterBaseTest.java
@@ -0,0 +1,60 @@
+// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.yahoo.container.jdisc.RequestHandlerTestDriver.MockResponseHandler;
+import com.yahoo.jdisc.Response;
+import com.yahoo.jdisc.http.filter.DiscFilterRequest;
+import org.junit.Test;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * @author bjorncs
+ */
+public class CorsSecurityRequestFilterBaseTest {
+
+ @Test
+ public void adds_cors_headers_when_filter_reject_request() {
+ String origin = "http://allowed.origin";
+ Set<String> allowedOrigins = Collections.singleton(origin);
+ int statusCode = 403;
+ SimpleCorsSecurityRequestFilter filter =
+ new SimpleCorsSecurityRequestFilter(allowedOrigins, statusCode, "Forbidden");
+ DiscFilterRequest request = mock(DiscFilterRequest.class);
+ when(request.getHeader("Origin")).thenReturn(origin);
+ MockResponseHandler responseHandler = new MockResponseHandler();
+ filter.filter(request, responseHandler);
+
+ Response response = responseHandler.getResponse();
+ assertThat(response, notNullValue());
+ assertThat(response.getStatus(), equalTo(statusCode));
+ List<String> allowOriginHeader = response.headers().get(ALLOW_ORIGIN_HEADER);
+ assertThat(allowOriginHeader.size(), equalTo(1));
+ assertThat(allowOriginHeader.get(0), equalTo(origin));
+ }
+
+ private static class SimpleCorsSecurityRequestFilter extends CorsSecurityRequestFilterBase {
+ private final ErrorResponse errorResponse;
+
+ SimpleCorsSecurityRequestFilter(Set<String> allowedUrls, int statusCode, String message) {
+ super(allowedUrls);
+ this.errorResponse = new ErrorResponse(statusCode, message);
+ }
+
+ @Override
+ protected Optional<ErrorResponse> filter(DiscFilterRequest request) {
+ return Optional.ofNullable(this.errorResponse);
+ }
+ }
+
+} \ No newline at end of file
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilterTest.java
new file mode 100644
index 00000000000..cadc4b217b3
--- /dev/null
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filters/cors/CorsSecurityResponseFilterTest.java
@@ -0,0 +1,112 @@
+// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.jdisc.http.filters.cors;
+
+import com.yahoo.jdisc.http.Cookie;
+import com.yahoo.jdisc.http.filter.DiscFilterResponse;
+import com.yahoo.jdisc.http.filter.RequestView;
+import com.yahoo.jdisc.http.filter.SecurityResponseFilter;
+import com.yahoo.jdisc.http.filters.cors.CorsSecurityFilterConfig.Builder;
+import com.yahoo.jdisc.http.servlet.ServletOrJdiscHttpResponse;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.ACCESS_CONTROL_HEADERS;
+import static com.yahoo.jdisc.http.filters.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * @author gjoranv
+ * @author bjorncs
+ */
+public class CorsSecurityResponseFilterTest {
+
+ @Test
+ public void any_request_yields_access_control_headers_in_response() {
+ Map<String, String> headers = doFilterRequest(newResponseFilter(), "http://any.origin");
+ ACCESS_CONTROL_HEADERS.keySet().forEach(
+ header -> assertFalse("Empty header: " + header, headers.get(header).isEmpty()));
+ }
+
+ @Test
+ public void allowed_request_origin_yields_allow_origin_header_in_response() {
+ final String ALLOWED_ORIGIN = "http://allowed.origin";
+ Map<String, String> headers = doFilterRequest(newResponseFilter(ALLOWED_ORIGIN), ALLOWED_ORIGIN);
+ assertEquals(ALLOWED_ORIGIN, headers.get(ALLOW_ORIGIN_HEADER));
+ }
+
+ @Test
+ public void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
+ Map<String, String> headers = doFilterRequest(newResponseFilter("http://allowed.origin"), "http://disallowed.origin");
+ assertNull(headers.get(ALLOW_ORIGIN_HEADER));
+ }
+
+ @Test
+ public void any_request_origin_yields_allow_origin_header_in_response_when_wildcard_is_allowed() {
+ Map<String, String> headers = doFilterRequest(newResponseFilter("*"), "http://any.origin");
+ assertEquals("*", headers.get(ALLOW_ORIGIN_HEADER));
+ }
+
+ private static Map<String, String> doFilterRequest(SecurityResponseFilter filter, String originUrl) {
+ TestResponse response = new TestResponse();
+ filter.filter(response, newRequestView(originUrl));
+ return Collections.unmodifiableMap(response.headers);
+ }
+
+ private static CorsSecurityResponseFilter newResponseFilter(String... allowedOriginUrls) {
+ Builder builder = new Builder();
+ Arrays.asList(allowedOriginUrls).forEach(builder::allowedUrls);
+ return new CorsSecurityResponseFilter(new CorsSecurityFilterConfig(builder));
+ }
+
+ private static RequestView newRequestView(String originUrl) {
+ RequestView request = mock(RequestView.class);
+ when(request.getFirstHeader("Origin")).thenReturn(Optional.of(originUrl));
+ return request;
+ }
+
+ private static class TestResponse extends DiscFilterResponse {
+ Map<String, String> headers = new HashMap<>();
+
+ TestResponse() {
+ super(mock(ServletOrJdiscHttpResponse.class));
+ }
+
+ @Override
+ public void setHeader(String name, String value) {
+ headers.put(name, value);
+ }
+
+ @Override
+ public String getHeader(String name) {
+ return headers.get(name);
+ }
+
+ @Override
+ public void removeHeaders(String s) { throw new UnsupportedOperationException(); }
+
+ @Override
+ public void setHeaders(String s, String s1) { throw new UnsupportedOperationException(); }
+
+ @Override
+ public void setHeaders(String s, List<String> list) { throw new UnsupportedOperationException(); }
+
+ @Override
+ public void addHeader(String s, String s1) { throw new UnsupportedOperationException(); }
+
+ @Override
+ public void setCookies(List<Cookie> list) { throw new UnsupportedOperationException(); }
+
+ @Override
+ public void setStatus(int i) { throw new UnsupportedOperationException(); }
+ }
+}