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 ¶
- Constants
- func DenialMetricValues() []string
- func MetricsColumns() []string
- func MetricsDenialValues() []string
- func NewHandler(next http.Handler, opts ...Option) http.Handler
- func NewLocalHost(next http.Handler, opts ...Option) http.Handler
- func NewLocalhostHandler(next http.Handler, opts ...Option) http.Handler
- type Option
- func WithAllowedHosts(hosts ...string) Option
- func WithAllowedOrigins(origins ...string) Option
- func WithAllowedPorts(ports ...int) Option
- func WithBlockCrossSiteRequests(block bool) Option
- func WithCounterVec(counter webapp.CounterVecInc) Option
- func WithCounterVecAdd(counter webapp.CounterVecAdd) Option
- func WithCounters(counter webapp.CounterVecInc) Option
- func WithCustomResponseHeaders(headers map[string]string) Option
- func WithEnforceLoopback(enforce bool) Option
- func WithJWTCookie(cookieName string, validator jwtutil.Validator, ...) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMetrics(metrics webapp.CounterVecInc) Option
- func WithSecurityHeaders(enable bool) Option
Examples ¶
Constants ¶
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 ¶
NewHandler is an alias for NewLocalhostHandler.
func NewLocalHost ¶
NewLocalHost is an alias for NewLocalhostHandler.
func NewLocalhostHandler ¶
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.
}
Output:
Types ¶
type Option ¶
type Option func(o *options)
Option configures the security handler.
func WithAllowedHosts ¶
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 ¶
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 ¶
WithAllowedPorts restricts the Host header and destination port to specific port numbers (e.g. 8080).
func WithBlockCrossSiteRequests ¶
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 ¶
WithCustomResponseHeaders overrides or extends default response security headers.
func WithEnforceLoopback ¶
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 ¶
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 ¶
WithSecurityHeaders toggles whether defensive HTTP response headers (X-Frame-Options, CSP, nosniff, no-store) are injected. Defaults to true.