security

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 19, 2026 License: Apache-2.0 Imports: 2 Imported by: 0

README

Security

Go Reference Go Version License

Add security-related HTTP headers to protect your app from common issues like clickjacking, MIME sniffing, and XSS. One middleware sets several headers that follow common best practices.

Full docs: Middleware Guide and Middleware Reference.

Features

  • X-Content-Type-Options: nosniff (stops MIME sniffing)
  • X-Frame-Options (reduces clickjacking risk)
  • X-XSS-Protection (legacy browsers)
  • Referrer-Policy and Permissions-Policy
  • Optional HSTS (force HTTPS)
  • Optional Content-Security-Policy (CSP)
  • Configurable per header

Installation

go get rivaas.dev/middleware/security

Requires Go 1.25 or later.

Quick Start

package main

import (
    "net/http"
    "rivaas.dev/router"
    "rivaas.dev/middleware/security"
)

func main() {
    r := router.New()
    r.Use(security.New())

    r.GET("/", func(c *router.Context) {
        c.String(http.StatusOK, "Hello")
    })

    http.ListenAndServe(":8080", r)
}

Configuration

Option What it does
WithFrameOptions X-Frame-Options (e.g. DENY, SAMEORIGIN)
WithContentTypeNosniff X-Content-Type-Options: nosniff (default: true)
WithXSSProtection X-XSS-Protection value
WithReferrerPolicy Referrer-Policy value
WithPermissionsPolicy Permissions-Policy value
WithHSTS HTTP Strict Transport Security (maxAge, includeSubdomains, preload)
WithContentSecurityPolicy Content-Security-Policy value

Example with HSTS and CSP:

r.Use(security.New(
    security.WithHSTS(31536000, true, true), // 1 year, subdomains, preload
    security.WithContentSecurityPolicy("default-src 'self'; script-src 'self'"),
))

Security note

Use HTTPS in production and set HSTS when you are sure all traffic should be HTTPS.

Examples

A runnable example is in the example/ directory:

cd example
go run main.go

Learn More

License

Apache License 2.0 – see LICENSE for details.

Documentation

Overview

Package security provides middleware for setting security-related HTTP headers to protect against common web vulnerabilities.

This middleware sets various security headers recommended by security best practices and standards (OWASP, Mozilla, etc.) to protect web applications from common attacks like XSS, clickjacking, MIME type sniffing, and more.

Basic Usage

import "rivaas.dev/middleware/security"

r := router.MustNew()
r.Use(security.New())

Security Headers

The middleware sets the following security headers by default:

  • X-Content-Type-Options: Prevents MIME type sniffing (nosniff)
  • X-Frame-Options: Prevents clickjacking (DENY)
  • X-XSS-Protection: Legacy XSS protection (0; mode=block)
  • Referrer-Policy: Controls referrer information (no-referrer-when-downgrade)
  • Permissions-Policy: Controls browser features and APIs

Configuration Options

  • WithFrameOptions: X-Frame-Options value (DENY, SAMEORIGIN, ALLOW-FROM)
  • WithContentTypeOptions: X-Content-Type-Options value (nosniff)
  • WithXSSProtection: X-XSS-Protection value
  • WithReferrerPolicy: Referrer-Policy value
  • WithPermissionsPolicy: Permissions-Policy value
  • WithHSTS: HTTP Strict Transport Security configuration
  • WithCSP: Content Security Policy configuration

HSTS Configuration

HTTP Strict Transport Security (HSTS) forces HTTPS connections:

r.Use(security.New(
    security.WithHSTS(
        security.HSTSMaxAge(31536000), // 1 year
        security.HSTSIncludeSubdomains(true),
        security.HSTSPreload(true),
    ),
))

CSP Configuration

Content Security Policy (CSP) controls resource loading:

r.Use(security.New(
    security.WithCSP("default-src 'self'; script-src 'self' 'unsafe-inline'"),
))

Security Best Practices

This middleware implements security headers recommended by:

  • OWASP Secure Headers Project
  • Mozilla Observatory
  • Security Headers (securityheaders.com)

Always use HTTPS in production and configure HSTS appropriately.

Package security provides middleware for setting security-related HTTP headers such as Content-Security-Policy, X-Frame-Options, and other security headers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(opts ...Option) router.HandlerFunc

New returns a middleware that sets security headers on HTTP responses. These headers help protect against common web vulnerabilities.

Security headers included (with secure defaults):

  • X-Frame-Options: DENY
  • X-Content-Type-Options: nosniff
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security: max-age=31536000; includeSubDomains
  • Content-Security-Policy: default-src 'self'
  • Referrer-Policy: strict-origin-when-cross-origin

Basic usage with secure defaults:

r := router.MustNew()
r.Use(security.New())

Custom configuration:

r.Use(security.New(
    security.WithFrameOptions("SAMEORIGIN"),
    security.WithContentSecurityPolicy("default-src 'self'; script-src 'self' https://cdn.example.com"),
))

For development (more permissive):

r.Use(security.New(
    security.WithFrameOptions("SAMEORIGIN"),
    security.WithContentSecurityPolicy("default-src 'self' 'unsafe-inline' 'unsafe-eval'"),
))

Disable HSTS (useful in development):

r.Use(security.New(
    security.WithHSTS(0, false, false), // Disables HSTS
))

Types

type Option

type Option func(*config)

Option defines functional options for security middleware configuration.

func DevelopmentPreset

func DevelopmentPreset() Option

DevelopmentPreset returns an option with relaxed security headers suitable for development. This preset includes basic security headers but allows inline scripts and styles for easier development.

Headers set:

  • X-Frame-Options: SAMEORIGIN
  • X-Content-Type-Options: nosniff
  • X-XSS-Protection: 1; mode=block
  • Content-Security-Policy: Relaxed policy with unsafe-inline and unsafe-eval
  • Referrer-Policy: no-referrer-when-downgrade
  • No HSTS (to allow switching between HTTP/HTTPS in development)

Example:

security.New(security.DevelopmentPreset())

func NoSecurityHeaders

func NoSecurityHeaders() Option

NoSecurityHeaders is an option that disables all security headers. This is useful for testing or when security headers are handled by an upstream proxy/gateway.

Example:

security.New(security.NoSecurityHeaders())

func ProductionPreset

func ProductionPreset() Option

ProductionPreset returns an option with strict security headers for production environments. This preset enables all recommended security headers with strict policies.

Headers set:

  • X-Frame-Options: DENY
  • X-Content-Type-Options: nosniff
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
  • Content-Security-Policy: default-src 'self'
  • Referrer-Policy: strict-origin-when-cross-origin
  • Permissions-Policy: Restrict geolocation, microphone, and camera

Example:

security.New(security.ProductionPreset())

You can override specific headers:

security.New(
    security.ProductionPreset(),
    security.WithFrameOptions("SAMEORIGIN"),
)

func WithContentSecurityPolicy

func WithContentSecurityPolicy(policy string) Option

WithContentSecurityPolicy sets the Content-Security-Policy header. CSP helps prevent XSS, clickjacking, and other code injection attacks. Default: "default-src 'self'"

Example:

security.New(security.WithContentSecurityPolicy(
    "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'",
))

func WithContentTypeNosniff

func WithContentTypeNosniff(enabled bool) Option

WithContentTypeNosniff enables or disables X-Content-Type-Options: nosniff. This prevents browsers from MIME-sniffing responses. Default: true

Example:

security.New(security.WithContentTypeNosniff(true))

func WithCustomHeader

func WithCustomHeader(name, value string) Option

WithCustomHeader adds a custom security header.

Example:

security.New(security.WithCustomHeader("X-Custom-Security", "value"))

func WithFrameOptions

func WithFrameOptions(value string) Option

WithFrameOptions sets the X-Frame-Options header. Common values: "DENY", "SAMEORIGIN", "ALLOW-FROM uri" Default: "DENY"

Example:

security.New(security.WithFrameOptions("SAMEORIGIN"))

func WithHSTS

func WithHSTS(maxAge int, includeSubdomains, preload bool) Option

WithHSTS configures HTTP Strict Transport Security. maxAge is in seconds (default: 31536000 = 1 year).

Example:

security.New(security.WithHSTS(63072000, true, true)) // 2 years, includeSubdomains, preload

func WithPermissionsPolicy

func WithPermissionsPolicy(policy string) Option

WithPermissionsPolicy sets the Permissions-Policy header. Controls which browser features and APIs can be used.

Example:

security.New(security.WithPermissionsPolicy(
    "geolocation=(), microphone=(), camera=()",
))

func WithReferrerPolicy

func WithReferrerPolicy(policy string) Option

WithReferrerPolicy sets the Referrer-Policy header. Controls how much referrer information is sent with requests. Default: "strict-origin-when-cross-origin"

Common values:

  • "no-referrer" - Never send referrer
  • "same-origin" - Send referrer only to same origin
  • "strict-origin" - Send origin only
  • "strict-origin-when-cross-origin" - Full URL to same origin, origin only to others

Example:

security.New(security.WithReferrerPolicy("same-origin"))

func WithXSSProtection

func WithXSSProtection(value string) Option

WithXSSProtection sets the X-XSS-Protection header. Common values: "1; mode=block", "0" (to disable) Default: "1; mode=block"

Note: This header is deprecated in modern browsers but still useful for older ones.

Example:

security.New(security.WithXSSProtection("1; mode=block"))

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL