Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors domain filter #715

Merged
merged 8 commits into from
Apr 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ public void buildOptions() {
"useWhiteList",
"disablePeerDiscovery",
"serverConfigs.serverAddress",
"serverConfigs.cors.allowedOrigins",
"serverConfigs.cors.allowCredentials",
"serverConfigs.cors.allowedHeaders",
"serverConfigs.cors.allowedMethods",
"serverConfigs.sslConfig.serverTrustStore",
"serverConfigs.influxConfig.dbName",
"serverConfigs.sslConfig.knownClientsFile",
Expand Down Expand Up @@ -120,8 +124,8 @@ public void buildOptions() {
final Map<String, Class> results = OverrideUtil.buildConfigOptions();

assertThat(results.keySet())
.filteredOn(s -> !s.contains("$jacocoData"))
.containsExactlyInAnyOrderElementsOf(expected);
.filteredOn(s -> !s.contains("$jacocoData"))
.containsExactlyInAnyOrderElementsOf(expected);

assertThat(results.get("serverConfigs.sslConfig.knownClientsFile")).isEqualTo(Path.class);
assertThat(results.get("keys.passwords")).isEqualTo(String[].class);
Expand Down Expand Up @@ -209,9 +213,9 @@ public void isSimple() {
@Test
public void toArrayType() {
assertThat(OverrideUtil.toArrayType(String.class))
.isEqualTo(String[].class);
.isEqualTo(String[].class);
assertThat(OverrideUtil.toArrayType(Path.class))
.isEqualTo(Path[].class);
.isEqualTo(Path[].class);
}

@Test
Expand Down Expand Up @@ -241,7 +245,7 @@ public void convertTo() {
assertThat(OverrideUtil.convertTo(Boolean.class, "true")).isTrue();

assertThat(OverrideUtil.convertTo(SslAuthenticationMode.class, "STRICT"))
.isEqualTo(SslAuthenticationMode.STRICT);
.isEqualTo(SslAuthenticationMode.STRICT);

assertThat(OverrideUtil.convertTo(String.class, null)).isNull();

Expand Down Expand Up @@ -320,7 +324,7 @@ public void setValueOnNullDoesNothing() {
@Test
public void setValuePreservePreDefined() throws Exception {
final Config config;
try(InputStream data = getClass().getResourceAsStream("/sample-config.json")) {
try (InputStream data = getClass().getResourceAsStream("/sample-config.json")) {
config = JaxbUtil.unmarshal(data, Config.class);
}

Expand All @@ -339,11 +343,10 @@ public void definePrivateAndPublicKeyWithOverridesOnly() throws Exception {

Config config = OverrideUtil.createInstance(Config.class);


OverrideUtil.setValue(config, "keys.keyData.publicKey", "PUBLICKEY");
OverrideUtil.setValue(config, "keys.keyData.privateKey", "PRIVATEKEY");
//UNmarshlling to COnfig to
try(ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
JaxbUtil.marshalWithNoValidation(config, bout);
Config result = JaxbUtil.unmarshal(new ByteArrayInputStream(bout.toByteArray()), Config.class);
assertThat(result.getKeys()).isNotNull();
Expand All @@ -365,7 +368,7 @@ public void defineAlwaysSendToWithOverridesOnly() throws Exception {

OverrideUtil.setValue(config, "alwaysSendTo", "ONE", "TWO");

try(ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
JaxbUtil.marshalWithNoValidation(config, bout);

Config result = JaxbUtil.unmarshal(new ByteArrayInputStream(bout.toByteArray()), Config.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.quorum.tessera.config;

import java.util.Arrays;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class CrossDomainConfig extends ConfigItem {

@XmlElement
private List<String> allowedMethods = Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD");

@XmlElement
private List<String> allowedOrigins;

@XmlElement
private List<String> allowedHeaders;

@XmlElement
private Boolean allowCredentials = Boolean.TRUE;

public List<String> getAllowedOrigins() {
return allowedOrigins;
}

public void setAllowedOrigins(List<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}

public List<String> getAllowedMethods() {
return allowedMethods;
}

public void setAllowedMethods(List<String> allowedMethods) {
this.allowedMethods = allowedMethods;
}

public List<String> getAllowedHeaders() {
return allowedHeaders;
}

public void setAllowedHeaders(List<String> allowedHeaders) {
this.allowedHeaders = allowedHeaders;
}

public Boolean getAllowCredentials() {
return allowCredentials;
}

public void setAllowCredentials(Boolean allowCredentials) {
this.allowCredentials = allowCredentials;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ public class ServerConfig extends ConfigItem {
@XmlElement
private String serverAddress;

@XmlElement(name = "cors")
private CrossDomainConfig crossDomainConfig;

public ServerConfig(final AppType app,
final boolean enabled,
final String serverAddress,
Expand Down Expand Up @@ -148,4 +151,14 @@ public boolean isUnixSocket() {
return Objects.equals(getServerUri().getScheme(), "unix");
}

public CrossDomainConfig getCrossDomainConfig() {
return crossDomainConfig;
}

public void setCrossDomainConfig(CrossDomainConfig crossDomainConfig) {
this.crossDomainConfig = crossDomainConfig;
}



}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.quorum.tessera.thridparty;

import com.quorum.tessera.api.filter.DomainFilter;
import com.quorum.tessera.api.model.*;
import com.quorum.tessera.config.apps.ThirdPartyApp;
import com.quorum.tessera.transaction.TransactionManager;
Expand All @@ -23,7 +22,6 @@
/**
* Provides endpoints for dealing with raw transactions
*/
@DomainFilter
@Path("/")
public class RawTransactionResource implements ThirdPartyApp {

Expand Down
3 changes: 0 additions & 3 deletions jaxrs-service/src/main/resources/tessera-jaxrs-spring.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,11 @@
</constructor-arg>
</bean>

<bean class="com.quorum.tessera.api.filter.LoggingFilter"/>

<bean class="com.quorum.tessera.api.filter.IPWhitelistFilter">
<constructor-arg ref="configService"/>
</bean>

<bean class="com.quorum.tessera.api.filter.DomainResponseFilter"/>

<bean class="com.quorum.tessera.api.exception.DefaultExceptionMapper"/>
<bean class="com.quorum.tessera.api.exception.DecodingExceptionMapper"/>
<bean class="com.quorum.tessera.api.exception.KeyNotFoundExceptionMapper"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,26 @@
import com.jpmorgan.quorum.server.utils.ServerUtils;
import com.quorum.tessera.config.InfluxConfig;
import com.quorum.tessera.config.ServerConfig;
import com.quorum.tessera.server.jaxrs.CorsDomainResponseFilter;
import com.quorum.tessera.server.jaxrs.LoggingFilter;
import com.quorum.tessera.server.monitoring.InfluxDbClient;
import com.quorum.tessera.server.monitoring.InfluxDbPublisher;
import com.quorum.tessera.server.monitoring.MetricsResource;
import org.glassfish.jersey.server.ResourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import javax.ws.rs.core.Application;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import javax.ws.rs.core.Application;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;

/**
* Implementation of a RestServer using Jersey and Jetty.
Expand Down Expand Up @@ -76,7 +77,12 @@ public void start() throws Exception {
final ResourceConfig config = ResourceConfig.forApplication(application);

config.addProperties(initParams)
.register(MetricsResource.class);
.register(MetricsResource.class)
.register(LoggingFilter.class);

if (serverConfig.getCrossDomainConfig() != null) {
prd-fox marked this conversation as resolved.
Show resolved Hide resolved
config.register(new CorsDomainResponseFilter(serverConfig.getCrossDomainConfig()));
}

this.server = ServerUtils.buildWebServer(serverConfig);

Expand Down Expand Up @@ -104,7 +110,7 @@ private void startInfluxMonitoring() {
Runnable publisher = new InfluxDbPublisher(influxDbClient);

final Runnable exceptionSafePublisher = () -> {
try{
try {
publisher.run();
} catch (final Throwable ex) {
LOGGER.error("Error when executing action {}", publisher.getClass().getSimpleName());
Expand All @@ -125,7 +131,7 @@ public void stop() {
}

if (Objects.nonNull(this.server)) {
try{
try {
this.server.stop();
} catch (Exception ex) {
LOGGER.warn(null, ex);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.quorum.tessera.server.jaxrs;

import com.quorum.tessera.config.CrossDomainConfig;
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CorsDomainResponseFilter implements ContainerResponseFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(CorsDomainResponseFilter.class);

private final OriginMatchUtil originMatchUtil;

private CrossDomainConfig corsConfig;

public CorsDomainResponseFilter(CrossDomainConfig corsConfig) {
this.corsConfig = corsConfig;
this.originMatchUtil = new OriginMatchUtil(corsConfig.getAllowedOrigins());
}

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

if ("unixsocket".equals(requestContext.getUriInfo().getBaseUri().toString())) {
return;
}

final String origin = requestContext.getHeaderString("Origin");

if (originMatchUtil.matches(origin)) {

MultivaluedMap<String, Object> headers = responseContext.getHeaders();

headers.add("Access-Control-Allow-Origin", origin);
headers.add("Access-Control-Allow-Credentials", corsConfig.getAllowCredentials().toString());
headers.add("Access-Control-Allow-Methods", String.join(",", corsConfig.getAllowedMethods()));

final String allowedHeaders;
if(corsConfig.getAllowedHeaders() != null) {
allowedHeaders = String.join(",",corsConfig.getAllowedHeaders());
} else {
allowedHeaders = requestContext.getHeaderString("Access-Control-Request-Headers");
}

headers.add("Access-Control-Allow-Headers", allowedHeaders);

}
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.quorum.tessera.api.filter;
package com.quorum.tessera.server.jaxrs;

import java.util.Optional;
import org.slf4j.Logger;
Expand All @@ -9,9 +9,7 @@
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.container.PreMatching;

@PreMatching
public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter {

private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class);
Expand Down
Loading