safeweb

package
v1.80.3 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2025 License: BSD-3-Clause Imports: 13 Imported by: 0

Documentation

Overview

Package safeweb provides a wrapper around an http.Server that applies basic web application security defenses by default. The wrapper can be used in place of an http.Server. A safeweb.Server adds mitigations for Cross-Site Request Forgery (CSRF) attacks, and annotates requests with appropriate Cross-Origin Resource Sharing (CORS), Content-Security-Policy, X-Content-Type-Options, and Referer-Policy headers.

To use safeweb, the application must separate its "browser" routes from "API" routes, with each on its own http.ServeMux. When serving requests, the server will first check the browser mux, and if no matching route is found it will defer to the API mux.

Browser Routes

All routes in the browser mux enforce CSRF protection using the gorilla/csrf package. The application must template the CSRF token into its forms using the TemplateField and TemplateTag APIs. Applications that are served in a secure context (over HTTPS) should also set the SecureContext field to true to ensure that the the CSRF cookies are marked as Secure.

In addition, browser routes will also have the following applied:

  • Content-Security-Policy header that disallows inline scripts, framing, and third party resources.
  • X-Content-Type-Options header on responses set to "nosniff" to prevent MIME type sniffing attacks.
  • Referer-Policy header set to "same-origin" to prevent leaking referrer information to third parties.

By default the Content-Security-Policy header will disallow inline styles. This can be overridden by setting the CSPAllowInlineStyles field to true in the safeweb.Config struct.

API routes

safeweb inspects the Content-Type header of incoming requests to the API mux and prohibits the use of `application/x-www-form-urlencoded` values. If the application provides a list of allowed origins and methods in its configuration safeweb will set the appropriate CORS headers on pre-flight OPTIONS requests served by the API mux.

HTTP Redirects

The [RedirectHTTP] method returns a handler that redirects all incoming HTTP requests to HTTPS at the same path on the provided fully qualified domain name (FQDN).

Example usage

h := http.NewServeMux()
h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, world!")
})
s, err := safeweb.NewServer(safeweb.Config{
	BrowserMux: h,
})
if err != nil {
	log.Fatalf("failed to create server: %v", err)
}
ln, err := net.Listen("tcp", ":8080")
if err != nil {
	log.Fatalf("failed to listen: %v", err)
}
defer ln.Close()
if err := s.Serve(ln); err != nil && err != http.ErrServerClosed {
	log.Fatalf("failed to serve: %v", err)
}

Index

Constants

This section is empty.

Variables

View Source
var DefaultStrictTransportSecurityOptions = "max-age=31536000"

The default Strict-Transport-Security header. This header tells the browser to exclusively use HTTPS for all requests to the origin for the next year.

Functions

This section is empty.

Types

type CSP added in v1.78.0

type CSP map[string][]string

CSP is the value of a Content-Security-Policy header. Keys are CSP directives (like "default-src") and values are source expressions (like "'self'" or "https://tailscale.com"). A nil slice value is allowed for some directives like "upgrade-insecure-requests" that don't expect a list of source definitions.

func DefaultCSP added in v1.78.0

func DefaultCSP() CSP

DefaultCSP is the recommended CSP to use when not loading resources from other domains and not embedding the current website. If you need to tweak the CSP, it is recommended to extend DefaultCSP instead of writing your own from scratch.

func (CSP) Add added in v1.78.0

func (csp CSP) Add(directive, value string)

Add adds a source expression to an existing directive.

func (CSP) Del added in v1.78.0

func (csp CSP) Del(directive string)

Del deletes a directive and all its values.

func (CSP) Set added in v1.78.0

func (csp CSP) Set(directive string, values ...string)

Set sets the values for a given directive. Empty values are allowed, if the directive doesn't expect any (like "upgrade-insecure-requests").

func (CSP) String added in v1.78.0

func (csp CSP) String() string

type Config

type Config struct {
	// SecureContext specifies whether the Server is running in a secure (HTTPS) context.
	// Setting this to true will cause the Server to set the Secure flag on CSRF cookies.
	SecureContext bool

	// BrowserMux is the HTTP handler for any routes in your application that
	// should only be served to browsers in a primary origin context. These
	// requests will be subject to CSRF protection and will have
	// browser-specific headers in their responses.
	BrowserMux *http.ServeMux

	// APIMux is the HTTP handler for any routes in your application that
	// should only be served to non-browser clients or to browsers in a
	// cross-origin resource sharing context.
	APIMux *http.ServeMux

	// AccessControlAllowOrigin specifies the Access-Control-Allow-Origin header sent in response to pre-flight OPTIONS requests.
	// Provide a list of origins, e.g. ["https://foobar.com", "https://foobar.net"] or the wildcard value ["*"].
	// No headers will be sent if no origins are provided.
	AccessControlAllowOrigin []string
	// AccessControlAllowMethods specifies the Access-Control-Allow-Methods header sent in response to pre-flight OPTIONS requests.
	// Provide a list of methods, e.g. ["GET", "POST", "PUT", "DELETE"].
	// No headers will be sent if no methods are provided.
	AccessControlAllowMethods []string

	// CSRFSecret is the secret used to sign CSRF tokens. It must be 32 bytes long.
	// This should be considered a sensitive value and should be kept secret.
	// If this is not provided, the Server will generate a random CSRF secret on
	// startup.
	CSRFSecret []byte

	// CSP is the Content-Security-Policy header to return with BrowserMux
	// responses.
	CSP CSP
	// CSPAllowInlineStyles specifies whether to include `style-src:
	// unsafe-inline` in the Content-Security-Policy header to permit the use of
	// inline CSS.
	CSPAllowInlineStyles bool

	// CookiesSameSiteLax specifies whether to use SameSite=Lax in cookies. The
	// default is to set SameSite=Strict.
	CookiesSameSiteLax bool

	// StrictTransportSecurityOptions specifies optional directives for the
	// Strict-Transport-Security header sent in response to requests made to the
	// BrowserMux when SecureContext is true.
	// If empty, it defaults to max-age of 1 year.
	StrictTransportSecurityOptions string

	// HTTPServer, if specified, is the underlying http.Server that safeweb will
	// use to serve requests. If nil, a new http.Server will be created.
	// Do not use the Handler field of http.Server, as it will be ignored.
	// Instead, set your handlers using APIMux and BrowserMux.
	HTTPServer *http.Server
}

Config contains the configuration for a safeweb server.

type Server

type Server struct {
	Config
	// contains filtered or unexported fields
}

Server is a safeweb server.

func NewServer

func NewServer(config Config) (*Server, error)

NewServer creates a safeweb server with the provided configuration. It will validate the configuration to ensure that it is complete and return an error if not.

func (*Server) Close added in v1.72.0

func (s *Server) Close() error

Close closes all client connections and stops accepting new ones.

func (*Server) ListenAndServe added in v1.76.0

func (s *Server) ListenAndServe(addr string) error

ListenAndServe listens on the TCP network address addr and then calls Serve to handle requests on incoming connections. If addr == "", ":http" is used.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve starts the server and listens on the provided listener. It will block until the server is closed. The caller is responsible for closing the listener.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Server) ServeRedirectHTTP

func (s *Server) ServeRedirectHTTP(ln net.Listener, fqdn string) error

ServeRedirectHTTP serves a single HTTP handler on the provided listener that redirects all incoming HTTP requests to the HTTPS address of the provided fully qualified domain name (FQDN). Callers are responsible for closing the listener.

func (*Server) Shutdown added in v1.78.0

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. It has the same semantics as[http.Server.Shutdown].

Jump to

Keyboard shortcuts

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