Skip to content

Add cloudfront CDN and CORS filter #84

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

Merged
merged 1 commit into from
Sep 29, 2018
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 @@ -4,6 +4,8 @@
import java.time.format.DateTimeFormatter;

import com.github.jknack.handlebars.Options;
import com.google.common.base.Strings;
import com.typesafe.config.Config;

public class TemplateHelpers {
static final DateTimeFormatter MMMddyyyyFmt = DateTimeFormatter.ofPattern("MMM dd, yyyy");
Expand All @@ -12,4 +14,16 @@ public static CharSequence dateFormat(String dateString, Options options) {
LocalDateTime date = LocalDateTime.parse(dateString);
return MMMddyyyyFmt.format(date);
}

private static final String cdnHost = Configs.<String>getOrDefault(Configs.properties(),
"cdn.host",
Config::getString,
() -> null);
// This expects the url to be relative (eg. /static/img.jpg)
public static CharSequence cdn(String url) {
if (Strings.isNullOrEmpty(cdnHost)) {
return url;
}
return cdnHost + url;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class Templating {
static {
Templating.Builder builder =
new Templating.Builder()
.withHelper("dateFormat", TemplateHelpers::dateFormat)
.withHelpers(new TemplateHelpers())
.withHelper("md", new MarkdownHelper())
.withHelper(AssignHelper.NAME, AssignHelper.INSTANCE)
.register(HumanizeHelper::register);
Expand Down Expand Up @@ -148,6 +148,12 @@ public <T> Builder withHelper(String helperName, Helper<T> helper) {
return this;
}

public <T> Builder withHelpers(Object helpers) {
log.debug("using template helpers {}" , helpers.getClass());
handlebars.registerHelpers(helpers);
return this;
}

public <T> Builder register(Consumer<Handlebars> consumer) {
log.debug("registering helpers");
consumer.accept(handlebars);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,12 @@ default Optional<String> getHeader(HttpServerExchange exchange, String header) {
RequestHeaderAttribute reqHeader = new RequestHeaderAttribute(new HttpString(header));
return Optional.ofNullable(reqHeader.readAttribute(exchange));
}

default void setHeader(HttpServerExchange exchange, HttpString header, String value) {
exchange.getResponseHeaders().add(header, value);
}

default void setHeader(HttpServerExchange exchange, String header, String value) {
exchange.getResponseHeaders().add(new HttpString(header), value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import java.io.File;
import java.nio.file.Paths;
import java.util.Set;
import java.util.SortedMap;

import org.slf4j.Logger;
Expand Down Expand Up @@ -168,4 +169,18 @@ public static HttpHandler securityHeaders(HttpHandler next, ReferrerPolicy polic
return security.complete(next);
}
// {{end:securityHeaders}}

public static HttpHandler corsOriginWhitelist(HttpHandler next, Set<String> originWhitelist) {
return exchange -> {
String origin = Exchange.headers()
.getHeader(exchange, Headers.ORIGIN)
.orElse("");
log.debug("Origin: {} Whitelist: {}", origin, originWhitelist);
if (originWhitelist.contains(origin)) {
log.debug("Origin whitelist matched adding CORS header");
Exchange.headers().setHeader(exchange, "Access-Control-Allow-Origin", origin);
}
next.handleRequest(exchange);
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Sets;
import com.stubbornjava.common.seo.SitemapRoutes;
import com.stubbornjava.common.undertow.SimpleServer;
import com.stubbornjava.common.undertow.handlers.CustomHandlers;
Expand Down Expand Up @@ -37,27 +38,28 @@ private static HttpHandler exceptionHandler(HttpHandler next) {
// {{start:csp}}
private static HttpHandler contentSecurityPolicy(HttpHandler delegate) {
return new ContentSecurityPolicyHandler.Builder()
.defaultSrc(ContentSecurityPolicy.SELF)
.scriptSrc(ContentSecurityPolicy.SELF.getValue(), "https://www.google-analytics.com")
.defaultSrc(ContentSecurityPolicy.SELF.getValue(), "https://*.stubbornjava.com")
.scriptSrc(ContentSecurityPolicy.SELF.getValue(), "https://*.stubbornjava.com", "https://www.google-analytics.com", "data:")
// Drop the wildcard when we host our own images.
.imgSrc(ContentSecurityPolicy.SELF.getValue(), "https://www.google-analytics.com", "*")
.connectSrc(ContentSecurityPolicy.SELF.getValue(), "https://www.google-analytics.com")
.fontSrc(ContentSecurityPolicy.SELF.getValue(), "data:")
.styleSrc(ContentSecurityPolicy.SELF.getValue(), ContentSecurityPolicy.UNSAFE_INLINE.getValue())
.imgSrc(ContentSecurityPolicy.SELF.getValue(), "https://*.stubbornjava.com", "https://www.google-analytics.com", "data:")
.connectSrc(ContentSecurityPolicy.SELF.getValue(), "https://*.stubbornjava.com", "https://www.google-analytics.com")
.fontSrc(ContentSecurityPolicy.SELF.getValue(), "https://*.stubbornjava.com", "data:")
.styleSrc(ContentSecurityPolicy.SELF.getValue(), ContentSecurityPolicy.UNSAFE_INLINE.getValue(), "https://*.stubbornjava.com")
.build(delegate);
}
// {{end:csp}}

// {{start:middleware}}
private static HttpHandler wrapWithMiddleware(HttpHandler next) {
return MiddlewareBuilder.begin(PageRoutes::redirector)
return MiddlewareBuilder.begin(ex -> CustomHandlers.accessLog(ex, logger))
.next(StubbornJavaWebApp::exceptionHandler)
.next(CustomHandlers::statusCodeMetrics)
.next(handler -> CustomHandlers.securityHeaders(handler, ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN))
.next(StubbornJavaWebApp::contentSecurityPolicy)
.next(CustomHandlers::gzip)
.next(h -> CustomHandlers.corsOriginWhitelist(next, Sets.newHashSet("https://www.stubbornjava.com")))
.next(PageRoutes::redirector)
.next(BlockingHandler::new)
.next(ex -> CustomHandlers.accessLog(ex, logger))
.next(CustomHandlers::statusCodeMetrics)
.next(StubbornJavaWebApp::exceptionHandler)
.complete(next);
}
// {{end:middleware}}
Expand Down
3 changes: 3 additions & 0 deletions stubbornjava-webapp/src/main/resources/sjweb.production.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
cdn {
host="https://cdn.stubbornjava.com"
}
2 changes: 1 addition & 1 deletion stubbornjava-webapp/ui/src/common/head.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
<meta http-equiv="x-ua-compatible" content="ie=edge"/>
<meta name="description" content="{{#if metaDesc }}{{metaDesc}}{{/if}}"/>
{{!-- <link rel="stylesheet" href="/css/3rdparty.css"/>--}}
<link rel="stylesheet" href="/assets/css/common.css"/>
<link rel="stylesheet" href="{{cdn "/assets/css/common.css"}}"/>
2 changes: 1 addition & 1 deletion stubbornjava-webapp/ui/src/common/scripts.hbs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{{!-- <script async type="text/javascript" src="/js/3rdparty.js"></script> --}}
{{!-- Making this script async breaks the jump to id functionality :( --}}
<script type="text/javascript" src="/assets/js/common.js"></script>
<script type="text/javascript" src="{{cdn "/assets/js/common.js"}}"></script>
2 changes: 1 addition & 1 deletion stubbornjava-webapp/ui/src/widgets/nav/header.hbs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<nav class="navbar navbar-inverse navbar-expand fixed-top" role="navigation">
<a class="navbar-brand logo" href="/">
<span class="align-middle"><img src="/assets/images/PenguinHQ_compressed.png" height="40px"> Stubborn<span class="java">Java</span></span>
<span class="align-middle"><img src="{{cdn "/assets/images/PenguinHQ_compressed.png"}}" height="40px"> Stubborn<span class="java">Java</span></span>
{{!-- Add this SVG instead later. I can't get CSS to work --}}
{{!-- <span>{{> templates/src/widgets/nav/logo }} Stubborn<span class="java">Java</span></span> --}}
</a>
Expand Down