class Amber::Pipe::SecurityHeaders

Overview

Adds browser security headers to every response that passes through the pipeline: X-Content-Type-Options, X-Frame-Options, a frame-ancestors Content-Security-Policy, Referrer-Policy, Permissions-Policy, Cross-Origin-Opener-Policy, and, on HTTPS requests, Strict-Transport-Security.

The values come from the security_headers settings section (Amber::Configuration::SecurityHeadersConfig), which has secure defaults and is overridden per environment in config/environments/<env>.yml or with AMBER_SECURITY_HEADERS_* variables.

The pipe writes its headers before the rest of the pipeline runs and never replaces a header that is already on the response, so a pipe plugged earlier keeps its value and a controller that assigns one of these headers has the final word.

Whether a request is HTTPS is decided by HTTP::Request#https?, the same method the cookie jar uses for the Secure flag, so Strict-Transport-Security and secure cookies always agree.

pipeline :web do
  plug Amber::Pipe::Error.new
  plug Amber::Pipe::Logger.new
  plug Amber::Pipe::SecurityHeaders.new
  plug Amber::Pipe::Session.new
end

Defined in:

amber/pipes/security_headers.cr

Constant Summary

STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"

Constructors

Instance Method Summary

Instance methods inherited from class Amber::Pipe::Base

call(context : HTTP::Server::Context) call

Constructor Detail

def self.new(config : Amber::Configuration::SecurityHeadersConfig | Nil = nil) #

Creates the pipe. Without config it reads Amber.settings.security_headers on each request, so it follows the loaded environment settings.


[View source]

Instance Method Detail

def call(context : HTTP::Server::Context) : Nil #

Writes the configured headers to the response, then runs the rest of the pipeline, so error pages that Amber::Pipe::Error renders for a failing controller carry them too.


[View source]
def write_headers(context : HTTP::Server::Context) : Nil #

Writes the configured headers to the response of context, leaving a header that is already present as it is. Amber::Pipe::Pipeline also calls it for responses no pipeline's pipes produce: a request that matched no route, a failed route constraint and a WebSocket handshake.


[View source]