From f9910386f1510f81dbea69db30972a609b77e065 Mon Sep 17 00:00:00 2001
From: Nathan Wallach <taniwallach@gmail.com>
Date: Mon, 24 Jan 2022 21:52:14 +0200
Subject: [PATCH] Add support for including a Strict-Transport-Security header.

This header is meant to force browsers to only contact site via TLS/SSL
("https"). Using this header is a commonly recommended security
practice, but is dangerous should the site have any need to work over
plain (port 80) HTTP.

The value for the header is provided in render.conf as a string value
called HSTS_HEADER, and when that value is not provided (or is "false"
for Perl purposes) no Strict-Transport-Security header will be set.

No default value is being provided in render.conf.dist so the header will
not be enabled by accident.

The header should only be used on a server which is available via a proxy
or load balancer which has a valid SSL certificate and handles the TLS/SSL
level (and which will continue to do so for the long-term).
---
 lib/RenderApp.pm | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/lib/RenderApp.pm b/lib/RenderApp.pm
index f129404a0..2c78c8c8f 100644
--- a/lib/RenderApp.pm
+++ b/lib/RenderApp.pm
@@ -58,6 +58,16 @@ sub startup {
 	$ENV{baseURL} = $ENV{SITE_HOST} . $ENV{baseURL} unless ( $ENV{baseURL} =~ m|^https?://| );
 	$ENV{formURL} = $ENV{baseURL} . $ENV{formURL} unless ( $ENV{formURL} =~ m|^https?://| );
 
+	# Handle optional Strict-Transport-Security header
+	if (my $HSTS_HEADER = $self->config('HSTS_HEADER')) {
+		$self->hook(before_dispatch => sub {
+			my $c = shift;
+			$c->res->headers->header(
+				'Strict-Transport-Security' => $HSTS_HEADER
+			       );
+		});
+	}
+
 	# Handle optional CORS settings
 	if (my $CORS_ORIGIN = $self->config('CORS_ORIGIN')) {
 		die "CORS_ORIGIN ($CORS_ORIGIN) must be an absolute URL or '*'"