httpsec

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 16 Imported by: ? 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.

Documentation

Overview

Package httpsec holds the HTTP plumbing every gatekeeper package shares: the JSON error form, security headers, the request log and the client-address rules.

errors.go is frozen (docs/PLAN.md §4.1); the rest of the package belongs to card G5.

Index

Constants

View Source
const (
	CodeNoSession    = "no_session"
	CodeStepUp       = "step_up_required"
	CodeForbidden    = "forbidden"
	CodeNotFound     = "not_found"
	CodeConflict     = "conflict"
	CodeInvalid      = "invalid"
	CodeRateLimited  = "rate_limited"
	CodeUpstream     = "upstream"
	CodeUnauthorized = "unauthorized" // no token
	CodeInvalidToken = "invalid_token"
	CodeInternal     = "internal"
	CodeOtherBrowser = "other_browser" // a consent transaction opened in another browser
)

Error codes of the JSON error form {"error":"<code>","message":"…"} (docs/PLAN.md §4.4).

View Source
const (
	// ReadHeaderTimeout bounds reading a request's headers.
	ReadHeaderTimeout = 10 * time.Second
	// IdleTimeout closes keep-alive connections that sit idle.
	IdleTimeout = 2 * time.Minute
	// MaxHeaderBytes caps the request headers.
	MaxHeaderBytes = 64 << 10
	// ShutdownGrace is how long a stop waits for the requests in flight.
	ShutdownGrace = 10 * time.Second
)
View Source
const BodyReadTimeout = 30 * time.Second

BodyReadTimeout is how long a client may take to send a request body (review GK-17). The server has no ReadTimeout, which would cut long answers, so without it a body sent a byte at a time holds the connection, and on an MCP door the caller's in-flight place, for as long as the client likes.

View Source
const DefaultCSP = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; " +
	"connect-src 'self'; manifest-src 'self'; worker-src 'self'; base-uri 'none'; form-action 'self'; " +
	"frame-ancestors 'none'"

DefaultCSP is the strict Content-Security-Policy Family Hub ships for its SPA: no inline script or style, no eval, everything from the page's own origin, no framing. An application passes its own policy where it needs more; it should stay at least this tight.

View Source
const HSTSValue = "max-age=31536000"

HSTSValue is the Strict-Transport-Security header: a year, without includeSubDomains or preload (the domain belongs to the application's owner, who may serve other things on its subdomains).

View Source
const HealthPath = "/healthz"

HealthPath is the route whose request lines are logged at debug level, so a container health probe does not flood the log.

View Source
const MaxBody = 2 << 20

MaxBody is the default cap on a request body. An application's own, smaller limit (Family Hub's MCP gateway) stays below it, so that limit's own 413 still answers.

Variables

This section is empty.

Functions

func BodyDeadline added in v0.2.0

func BodyDeadline(w http.ResponseWriter, d time.Duration) (lift func())

BodyDeadline gives the client of w until d from now to send the rest of its request body: a read after that fails with an error that wraps os.ErrDeadlineExceeded. The handler calls lift once it has read the whole body, and only then: on HTTP/1.1 the deadline is the connection's, and one still set when it passes would end the request's context in the middle of a long answer (an event stream); left in place after a failed read, it lets the server give up on the rest of the body at once instead of waiting for it. A writer that cannot set deadlines (a test recorder) gets none, and lift does nothing.

func BodyLimit

func BodyLimit(limit int64) func(http.Handler) http.Handler

BodyLimit refuses a declared body above limit at once with 413 {"error":"invalid"} and caps the rest while it is read (the reader then fails with *http.MaxBytesError). The client has BodyReadTimeout from the start of the request to send the body (BodyDeadline): a read after that fails with an error that wraps os.ErrDeadlineExceeded, which the handler answers as it answers any body it cannot read (mcpguard.ReadBody: 408).

func Chain

func Chain(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler

Chain wraps h in mws, the first one outermost: Chain(h, a, b) runs a, then b, then h.

func Healthz

func Healthz(w http.ResponseWriter, _ *http.Request)

Healthz answers {"status":"ok"} with Cache-Control: no-store (GET and HEAD).

func LoopbackPeers added in v0.2.0

func LoopbackPeers() []netip.Prefix

LoopbackPeers is the network of a connector on the same machine (cloudflared run by the application itself): 127.0.0.0/8 and ::1/128, for PeerOptions.Trusted or Options.Trusted. An IPv4-mapped peer (::ffff:127.0.0.1) counts as its IPv4 address. Each call returns a new slice.

Trust it only on a listener bound to loopback: any process on the machine can then name the client, and is trusted as much as the user it runs as anyway.

func MountClean added in v0.2.0

func MountClean(next http.Handler) http.Handler

MountClean is a middleware for a gatekeeper package's handler (its http.ServeMux) mounted route by route under another router (review GK-19). It answers NotFound to a request whose path is not clean and passes the rest to next:

  • a path that is empty or does not start with "/";
  • a "." or ".." segment, or an empty one ("//"), which the mux would answer with a 307 to the cleaned path, outside the application's own answers;
  • an escaped "/" (%2F), which the outer router may take for part of a parameter while the mux does not.

A ServeMux at the top of the application does not need it: its redirect sends the client through the whole chain again. The check is about consistency, not access: every guard of a package runs inside its handlers.

func New

func New(o Options) (http.Handler, error)

New returns the application's HTTP front: a mux with GET and HEAD /healthz and every registrar's routes, answering the JSON 404 for any other route, behind these middlewares, outermost first: RequestLog, Recover, PeerGuard, BodyLimit. Nothing compresses or buffers answers, so server-sent events reach the client as they are flushed.

func NoStore

func NoStore(next http.Handler) http.Handler

NoStore is a middleware that sends Cache-Control: no-store on every answer of next (a handler may still replace it).

func NotFound

func NotFound(w http.ResponseWriter, _ *http.Request)

NotFound answers 404 {"error":"not_found","message":"no such route"}.

func PeerGuard

func PeerGuard(o PeerOptions) func(http.Handler) http.Handler

PeerGuard keeps a request from claiming more than its TCP peer is. A peer outside Trusted does not get to name the client: its CF-Connecting-IP and X-Forwarded-For headers are deleted, so core.ClientIP, which runs later in the handlers and in the request log, falls back to the peer. A peer in Refused is answered with 403. An address that does not parse (no TCP peer) is neither trusted nor refused. With no Trusted prefixes nothing is believed.

A Site whose ClientIP mode reads a header (core.ClientIPCloudflare, core.ClientIPForwarded) needs this guard with Trusted holding only the connector's or proxy's address, or any client names its own address to the per-address limits and the audit (review GK-2). A connector on the same machine: LoopbackPeers, and listen on loopback only, so that every request comes through it; a request that arrives without the header is counted by its TCP peer, which would then be the same for every client.

func Recover

func Recover(log *slog.Logger) func(http.Handler) http.Handler

Recover turns a panic into a 500 {"error":"internal"} and a log line with the stack. http.ErrAbortHandler passes on: it is how a handler drops a connection on purpose. When the answer has started already, only the log line is written and the answer is left as it is.

func RequestLog

func RequestLog(log *slog.Logger, mode core.ClientIPMode) func(http.Handler) http.Handler

RequestLog writes one line per request: the method, the route pattern, the status, the size, the duration and the client address (core.ClientIP under mode). It never has the raw path or the query string, a header (Authorization, cookies) or a body. Health checks go to debug, server errors to warn, the rest to info.

Put it outermost, before Recover and PeerGuard, so it sees the final status and the address PeerGuard leaves.

func SecurityHeaders

func SecurityHeaders(csp string) func(http.Handler) http.Handler

SecurityHeaders is a middleware that sets SetSecurityHeaders (with COOP) on every answer of next.

func SetNoStore

func SetNoStore(w http.ResponseWriter)

SetNoStore marks the answer as uncacheable: Cache-Control: no-store.

func SetSecurityHeaders

func SetSecurityHeaders(h http.Header, csp string, coop bool)

SetSecurityHeaders sets the headers every page carries: the CSP csp, nosniff, Referrer-Policy: no-referrer, X-Frame-Options: DENY and HSTS. coop adds Cross-Origin-Opener-Policy: same-origin; leave it off for a page that runs inside an assistant's connector window (the consent page), where COOP would cut the window's tie to the assistant's page.

func WriteError

func WriteError(w http.ResponseWriter, status int, code, message string)

WriteError answers with the JSON error form and Cache-Control: no-store. The body is json.Marshal's, without a trailing newline, byte for byte what Family Hub's Gin wrote.

Types

type ErrorBody

type ErrorBody struct {
	Error   string `json:"error"`
	Message string `json:"message"`
}

ErrorBody is the JSON error form. Message is English and never holds a secret.

type Options

type Options struct {
	// Site gives the client-address mode of the request log.
	Site core.Site
	// Routes register their routes on the mux, in order. None may register "/" or "GET /healthz": New does.
	Routes []core.RouteRegistrar
	// Trusted, Refused and RefusedMessage are the PeerGuard rules.
	Trusted        []netip.Prefix
	Refused        []netip.Prefix
	RefusedMessage string
	// MaxBody caps request bodies; 0 is the package's MaxBody.
	MaxBody int64
	// Logger is the request log and the panic log; nil discards.
	Logger *slog.Logger
}

Options build the application's HTTP front with New.

type PeerOptions

type PeerOptions struct {
	// Trusted are the peers allowed to say who the client is (CF-Connecting-IP, X-Forwarded-For): the network
	// where cloudflared or the host's reverse proxy reaches the application. Nothing else is believed.
	Trusted []netip.Prefix
	// Refused are peers that get 403 {"error":"forbidden"} and nothing else (Family Hub: its module networks;
	// modules never call the hub). Optional.
	Refused []netip.Prefix
	// RefusedMessage is the message of that 403; "" is "peer not allowed".
	RefusedMessage string
}

PeerOptions are the rules PeerGuard applies by the TCP peer of a request.

type Server

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

Server is an http.Server with the timeouts the gatekeeper wants. It has a ReadHeaderTimeout but no ReadTimeout or WriteTimeout, which would cut server-sent event streams that run as long as a tool does.

func NewServer

func NewServer(o ServerOptions) (*Server, error)

NewServer returns a server for o.Handler on o.Listen; Start runs it.

func (*Server) Addr

func (s *Server) Addr() net.Addr

Addr is the address the server listens on (useful after Listen ":0"); nil before Start.

func (*Server) Start

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

Start listens (so a port in use fails the start) and serves in the background.

func (*Server) Stop

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

Stop lets the requests in flight finish for ShutdownGrace at most (or until ctx ends), then closes what is left: long event streams, so the rest of the application still has time to stop.

type ServerOptions

type ServerOptions struct {
	Listen  string       // e.g. ":8080"
	Handler http.Handler // usually New's
	Logger  *slog.Logger // nil discards
}

ServerOptions are the listener of Server.

Jump to

Keyboard shortcuts

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