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
- func BodyLimit(limit int64) func(http.Handler) http.Handler
- func Chain(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler
- func Healthz(w http.ResponseWriter, _ *http.Request)
- func New(o Options) (http.Handler, error)
- func NoStore(next http.Handler) http.Handler
- func NotFound(w http.ResponseWriter, _ *http.Request)
- func PeerGuard(o PeerOptions) func(http.Handler) http.Handler
- func Recover(log *slog.Logger) func(http.Handler) http.Handler
- func RequestLog(log *slog.Logger, mode core.ClientIPMode) func(http.Handler) http.Handler
- func SecurityHeaders(csp string) func(http.Handler) http.Handler
- func SetNoStore(w http.ResponseWriter)
- func SetSecurityHeaders(h http.Header, csp string, coop bool)
- func WriteError(w http.ResponseWriter, status int, code, message string)
- type ErrorBody
- type Options
- type PeerOptions
- type Server
- type ServerOptions
Constants ¶
const ( CodeNoSession = "no_session" CodeStepUp = "step_up_required" CodeForbidden = "forbidden" CodeNotFound = "not_found" CodeConflict = "conflict" CodeInvalid = "invalid" CodeRateLimited = "rate_limited" CodeUpstream = "upstream" 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).
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 )
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.
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).
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.
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 BodyLimit ¶
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).
func Healthz ¶
func Healthz(w http.ResponseWriter, _ *http.Request)
Healthz answers {"status":"ok"} with Cache-Control: no-store (GET and HEAD).
func New ¶
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 ¶
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.
func Recover ¶
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 ¶
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 ¶
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 ¶
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 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 ¶
Addr is the address the server listens on (useful after Listen ":0"); nil before Start.