websec

package
v0.0.0-...-f9c80a2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Package cloudeng.io/webapp/websec

import cloudeng.io/webapp/websec

Package websec provides HTTP security middleware for web applications. In particular, it offers NewLocalhostHandler to enforce security controls for HTTP/HTTPS endpoints bound to 127.0.0.1 or ::1, defending against non-loopback connections, DNS rebinding attacks, cross-site browser requests, and framing/MIME-sniffing vulnerabilities.

Constants

DenialNonLoopback, DenialInvalidHost, DenialCrossSite, DenialInvalidJWT
DenialNonLoopback = "non-loopback"
DenialInvalidHost = "invalid-host"
DenialCrossSite = "cross-site"
DenialInvalidJWT = "invalid-jwt"

Denial reason constants used as label values for the denial metric.

Functions

Func DenialMetricValues
func DenialMetricValues() []string

DenialMetricValues is an alias for MetricsDenialValues.

Func MetricsColumns
func MetricsColumns() []string

MetricsColumns returns the list of column/label names used for the denial metric.

Func MetricsDenialValues
func MetricsDenialValues() []string

MetricsDenialValues returns the list of values used for the "reason" label of the denial metric.

Func NewHandler
func NewHandler(next http.Handler, opts ...Option) http.Handler

NewHandler is an alias for NewLocalhostHandler.

Func NewLocalHost
func NewLocalHost(next http.Handler, opts ...Option) http.Handler

NewLocalHost is an alias for NewLocalhostHandler.

Func NewLocalhostHandler
func NewLocalhostHandler(next http.Handler, opts ...Option) http.Handler

NewLocalhostHandler wraps next with security controls designed for services bound to 127.0.0.1 or ::1. By default, it enforces loopback connections, validates Host headers against DNS rebinding, blocks cross-site browser requests, and sets defensive response headers.

Types

Type Option
type Option func(o *options)

Option configures the security handler.

Functions
func WithAllowedHosts(hosts ...string) Option

WithAllowedHosts configures the allowed Host header values for DNS rebinding defense. If not specified, defaults to "127.0.0.1", "localhost", and "::1".

func WithAllowedOrigins(origins ...string) Option

WithAllowedOrigins permits specific external or non-loopback origins to make cross-origin requests (e.g. a dev UI on https://trusted-partner.local or an external web client).

func WithAllowedPorts(ports ...int) Option

WithAllowedPorts restricts the Host header and destination port to specific port numbers (e.g. 8080).

func WithBlockCrossSiteRequests(block bool) Option

WithBlockCrossSiteRequests enables or disables blocking requests initiated cross-site by local web browsers (inspecting Sec-Fetch-Site, Origin, and Referer). Defaults to true.

func WithCounterVec(counter webapp.CounterVecInc) Option

WithCounterVec configures a CounterVecInc metric that is incremented whenever a request is rejected, with the denial reason supplied as a label value (one of MetricsDenialValues).

func WithCounterVecAdd(counter webapp.CounterVecAdd) Option

WithCounterVecAdd configures a CounterVecAdd metric for request denials. At handler initialization, all denial reason labels from MetricsDenialValues are initialized with delta 0, and incremented by 1 on each denial.

func WithCounters(counter webapp.CounterVecInc) Option

WithCounters is an alias for WithCounterVec.

func WithCustomResponseHeaders(headers map[string]string) Option

WithCustomResponseHeaders overrides or extends default response security headers.

func WithEnforceLoopback(enforce bool) Option

WithEnforceLoopback toggles raw socket RemoteAddr loopback verification. Defaults to true.

func WithJWTCookie(cookieName string, validator jwtutil.Validator, validateOptions ...jwt.ValidateOption) Option

WithJWTCookie enables JWT validation for requests presented in a cookie. It verifies that the cookie named cookieName contains a JWT that validator accepts, subject to validateOptions (e.g. jwt.WithClaimValue). If cookieName is empty, it defaults to "auth_token". validateOptions is cloned, so the caller's slice may be reused or modified afterward.

The validated token is stored in the request context under the name of the cookie, for retrieval with jwtutil.TokenFromContext.

func WithLogger(logger *slog.Logger) Option

WithLogger sets the structured logger for security event logging.

func WithMetrics(metrics webapp.CounterVecInc) Option

WithMetrics is an alias for WithCounterVec.

func WithSecurityHeaders(enable bool) Option

WithSecurityHeaders toggles whether defensive HTTP response headers (X-Frame-Options, CSP, nosniff, no-store) are injected. Defaults to true.

Examples

ExampleNewLocalhostHandler

Documentation

Overview

Package websec provides HTTP security middleware for web applications. In particular, it offers NewLocalhostHandler to enforce security controls for HTTP/HTTPS endpoints bound to 127.0.0.1 or ::1, defending against non-loopback connections, DNS rebinding attacks, cross-site browser requests, and framing/MIME-sniffing vulnerabilities.

Index

Examples

Constants

View Source
const (
	DenialNonLoopback = "non-loopback"
	DenialInvalidHost = "invalid-host"
	DenialCrossSite   = "cross-site"
	DenialInvalidJWT  = "invalid-jwt"
)

Denial reason constants used as label values for the denial metric.

Variables

This section is empty.

Functions

func DenialMetricValues

func DenialMetricValues() []string

DenialMetricValues is an alias for MetricsDenialValues.

func MetricsColumns

func MetricsColumns() []string

MetricsColumns returns the list of column/label names used for the denial metric.

func MetricsDenialValues

func MetricsDenialValues() []string

MetricsDenialValues returns the list of values used for the "reason" label of the denial metric.

func NewHandler

func NewHandler(next http.Handler, opts ...Option) http.Handler

NewHandler is an alias for NewLocalhostHandler.

func NewLocalHost

func NewLocalHost(next http.Handler, opts ...Option) http.Handler

NewLocalHost is an alias for NewLocalhostHandler.

func NewLocalhostHandler

func NewLocalhostHandler(next http.Handler, opts ...Option) http.Handler

NewLocalhostHandler wraps next with security controls designed for services bound to 127.0.0.1 or ::1. By default, it enforces loopback connections, validates Host headers against DNS rebinding, blocks cross-site browser requests, and sets defensive response headers.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"cloudeng.io/webapp/cookies"
	"cloudeng.io/webapp/webauth/jwtutil"
	"cloudeng.io/webapp/websec"
	"github.com/lestrrat-go/jwx/v3/jwk"
	"github.com/lestrrat-go/jwx/v3/jwt"
)

func main() {
	// 1. Setup signing & verification keys
	ki, _ := jwtutil.NewED25519KeyInfo("user", "key")
	signer, _ := jwtutil.ED25519{}.Signer(ki)
	pubKey, _ := signer.PublicKey()
	keys := jwk.NewSet()
	_ = keys.AddKey(pubKey)
	validator := jwtutil.NewValidator(keys)

	// 2. Wrap app with websec middleware
	appHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tok, _ := jwtutil.TokenFromContext(r.Context(), "session_token")
		sub, _ := tok.Subject()
		_, _ = w.Write([]byte("Hello, " + sub))
	})

	secured := websec.NewLocalhostHandler(appHandler,
		websec.WithAllowedPorts(8080),
		websec.WithJWTCookie("session_token", validator, jwt.WithClaimValue("role", "admin")),
	)

	// 3. Deliver a token to the browser as the cookie the middleware reads.
	// The middleware only reads that cookie; setting it is the application's
	// responsibility.
	tokenBytes, _ := jwtutil.CreateVerificationToken(context.Background(),
		signer, "local-user", "role", "admin", time.Hour, "", "")

	mux := http.NewServeMux()
	mux.Handle("/", secured)
	mux.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		// cookies.Secure supplies the name, and the Secure, HttpOnly and
		// SameSite attributes.
		cookies.Secure("session_token").Set(w, &http.Cookie{ //nolint:gosec // G124: set by cookies.Secure, not here.
			Value: string(tokenBytes),
			Path:  "/",
		})
		http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
	})

	fmt.Println("Open in browser: http://127.0.0.1:8080/login")

	_ = http.ListenAndServe("127.0.0.1:8080", mux) //nolint:gosec // G114: an example, not a server to be run.
}

Types

type Option

type Option func(o *options)

Option configures the security handler.

func WithAllowedHosts

func WithAllowedHosts(hosts ...string) Option

WithAllowedHosts configures the allowed Host header values for DNS rebinding defense. If not specified, defaults to "127.0.0.1", "localhost", and "::1".

func WithAllowedOrigins

func WithAllowedOrigins(origins ...string) Option

WithAllowedOrigins permits specific external or non-loopback origins to make cross-origin requests (e.g. a dev UI on https://trusted-partner.local or an external web client).

func WithAllowedPorts

func WithAllowedPorts(ports ...int) Option

WithAllowedPorts restricts the Host header and destination port to specific port numbers (e.g. 8080).

func WithBlockCrossSiteRequests

func WithBlockCrossSiteRequests(block bool) Option

WithBlockCrossSiteRequests enables or disables blocking requests initiated cross-site by local web browsers (inspecting Sec-Fetch-Site, Origin, and Referer). Defaults to true.

func WithCounterVec

func WithCounterVec(counter webapp.CounterVecInc) Option

WithCounterVec configures a CounterVecInc metric that is incremented whenever a request is rejected, with the denial reason supplied as a label value (one of MetricsDenialValues).

func WithCounterVecAdd

func WithCounterVecAdd(counter webapp.CounterVecAdd) Option

WithCounterVecAdd configures a CounterVecAdd metric for request denials. At handler initialization, all denial reason labels from MetricsDenialValues are initialized with delta 0, and incremented by 1 on each denial.

func WithCounters

func WithCounters(counter webapp.CounterVecInc) Option

WithCounters is an alias for WithCounterVec.

func WithCustomResponseHeaders

func WithCustomResponseHeaders(headers map[string]string) Option

WithCustomResponseHeaders overrides or extends default response security headers.

func WithEnforceLoopback

func WithEnforceLoopback(enforce bool) Option

WithEnforceLoopback toggles raw socket RemoteAddr loopback verification. Defaults to true.

func WithJWTCookie

func WithJWTCookie(cookieName string, validator jwtutil.Validator, validateOptions ...jwt.ValidateOption) Option

WithJWTCookie enables JWT validation for requests presented in a cookie. It verifies that the cookie named cookieName contains a JWT that validator accepts, subject to validateOptions (e.g. jwt.WithClaimValue). If cookieName is empty, it defaults to "auth_token". validateOptions is cloned, so the caller's slice may be reused or modified afterward.

The validated token is stored in the request context under the name of the cookie, for retrieval with jwtutil.TokenFromContext.

func WithLogger

func WithLogger(logger *slog.Logger) Option

WithLogger sets the structured logger for security event logging.

func WithMetrics

func WithMetrics(metrics webapp.CounterVecInc) Option

WithMetrics is an alias for WithCounterVec.

func WithSecurityHeaders

func WithSecurityHeaders(enable bool) Option

WithSecurityHeaders toggles whether defensive HTTP response headers (X-Frame-Options, CSP, nosniff, no-store) are injected. Defaults to true.

Jump to

Keyboard shortcuts

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