Documentation
¶
Overview ¶
Package httpmw is the HTTP layer that turns purser's authenticators into a serving surface: it resolves the Caller onto the request context, stamps how the request was authenticated, guards the browser CSRF vectors, gates a shared transport token, and answers whether an address is safe to bind.
The package is stdlib-only. Everything it needs from a credential it gets through the interfaces in authn, so a surface that serves SPIFFE mTLS and one that serves bearer tokens link the same middleware.
Ordering ¶
The middlewares are not interchangeable and the order is part of the security argument:
Chain(
gate.Middleware(), // outermost: shared transport token
BrowserWriteGuard(), // then the CSRF vectors
caller.Middleware(), // then per-caller identity
)(mux)
The token gate runs outermost because it is the cheapest rejection and because passing it is itself a verified auth source that the caller middleware inherits. The browser guard runs before the caller middleware so a cross-site write is refused whether or not it carries a credential. The caller middleware runs innermost, closest to the handler that reads the Caller off the context.
Both gate and caller are then what CheckBind is given — they are the two things in that chain that can refuse a request for want of a credential, and so the two that can answer whether the address is safe to expose:
if err := CheckBind(addr, gate, caller); err != nil {
return err
}
What this package will not do ¶
It never derives an identity, or the verdict on how a request was authenticated, from a request header. The one header that can change who a request is attributed to — the asserted-caller header — is honored only when the authenticator that verified the connection says the caller may proxy, and the asserted identity is materialized from the authenticator's own table. See NewCaller.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUnauthenticatedBind = errors.New("purser: refusing to bind a non-loopback address with no credential gate")
ErrUnauthenticatedBind is returned by CheckBind for a non-loopback address with nothing gating credentials in front of it.
Functions ¶
func CheckBind ¶
CheckBind reports whether addr is safe to listen on given what gates the surface, and returns an error wrapping ErrUnauthenticatedBind when it is not.
The rule: a non-loopback address requires at least one gate that reports GatesCredentials() == true. Loopback is always permitted — a local-development posture where the operating system's own process isolation is the boundary — and it is the caller's job to say so loudly in a log line, because "any process on this machine may drive this surface" is a real statement, just a much smaller one.
This is a TCP policy. A Unix socket is guarded by its file permissions, so do not route one through here: SplitHostPort would fail on the path and the socket would be refused for the wrong reason.
Ask a gate, do not inspect configuration. The check this replaces keyed off "is a client-CA file configured", which is true for the PKI profile and false for a perfectly good SPIFFE listener that verifies against a trust bundle instead — so a working mutually authenticated surface got refused as unauthenticated. A gate knows what it enforces; a config field only knows how it was spelled.
Ask the right gate, though: the thing that decides whether an unverified request reaches the handler, not the thing that inspects the credential. For an HTTP surface that is the *CallerMiddleware — see Gate, which spells out why an authenticator handed over on its own is the one answer that can be true and useless at the same time.
func IsLoopback ¶
IsLoopback reports whether a TCP listen address binds only a loopback interface.
Conservative on purpose. An empty host (":8443"), the wildcards "0.0.0.0" and "::", and every hostname but "localhost" all count as non-loopback: a name resolves to whatever DNS says today, and the cost of guessing wrong is an open listener, so anything unproven is treated as network-reachable.
Types ¶
type BrowserWriteGuardOptions ¶
type BrowserWriteGuardOptions struct {
// AllowedOrigins are additional origins permitted to drive
// state-changing requests, beyond the loopback and self origins
// the guard always allows. Each must be a scheme://host[:port]
// with no path, and is compared case-insensitively on scheme and
// host.
//
// This is for a single-page app served from a different origin
// than the API. It is an allowlist and nothing else: there is no
// wildcard and no suffix match, because "*.example.com" is one
// subdomain takeover away from being an open door.
AllowedOrigins []string
}
BrowserWriteGuardOptions configures NewBrowserWriteGuard.
type CallerMiddleware ¶
type CallerMiddleware struct {
// contains filtered or unexported fields
}
CallerMiddleware resolves each request's Caller and attaches it, the proxying identity, and the auth-source verdict to the request context for handlers to read with purser.CallerFromContext, purser.ProxyByFromContext and purser.AuthSourceFromContext.
It is a named type rather than a bare Middleware because it is also the answer to CheckBind's question: whether a request can reach the handler without a verified credential is this middleware's decision (CallerOptions.Enforce), not the authenticator's. See GatesCredentials.
It is safe for concurrent use; it is immutable after NewCaller.
func NewCaller ¶
func NewCaller(opts CallerOptions) (*CallerMiddleware, error)
NewCaller builds the caller middleware from opts.
Behavior:
- The authenticator succeeds: its Caller goes on the context and its Source() is the verdict.
- The authenticator returns purser.ErrUnauthenticated and Enforce is false: Fallback goes on the context. The verdict is anonymous unless an outer middleware already stamped a non-anonymous one, in which case that stands — see below.
- The authenticator returns purser.ErrUnauthenticated and Enforce is true: 401 with the configured challenge, and the handler does not run.
- The authenticator returns any other error: 503 with Retry-After and no challenge, whatever Enforce says, and the handler does not run. See "401 or 503" below.
- The request carries the proxy header: 401 unless the request authenticated, the authenticator implements authn.AuthenticatorWithProxy, it permits this caller to proxy, and (where it implements authn.IdentityLookup) it has the asserted identity provisioned. A bad assertion is a security event, not a fall-back-to-the-underlying-identity case: silently ignoring it would let a compromised proxy credential look like a working one while an operator's allowlist change had no effect.
The proxy path requires a *successful* authentication and not merely a Caller, which is the one precondition the underlying interface cannot enforce on its own. authn.AuthenticatorWithProxy asks implementations to return false from CanProxyAs for the zero Caller, but on the fallback path there is no zero Caller to catch: the fallback is a configured identity, or purser.Anonymous(), and an implementation reading only its argument would see a perfectly ordinary Caller. Deciding it here means a request that presented no valid credential can never assert one, whatever any authenticator does.
The auth-source verdict ¶
The verdict comes from the authenticator's Source(), never from inspecting the request or the TLS state. Middleware that infers "mtls" from a populated tls.ConnectionState.VerifiedChains is correct only for the PKI profile: a SPIFFE listener leaves VerifiedChains empty on a perfectly good connection, so the same check silently reports anonymous for a caller whose SVID was verified. Asking the authenticator is the fix, and it is why Source() is on the base interface rather than a type switch here.
One thing is inherited rather than derived. Where this middleware would otherwise report anonymous — the authenticator verifies nothing, or verified nothing on this request — and an outer middleware already stamped a non-anonymous verdict, the outer verdict stands. A TokenGate that validated the shared transport token is the case to picture: the request did not get in anonymously, and reporting that it did would be the lie. The identity is still the fallback's, because a shared token names nobody. This is inheritance from code that did the work, not inference from a header.
A validated proxy assertion outranks both: the asserted path is what an audit record should show, with the proxying credential kept alongside it under purser.WithProxyBy.
401 or 503 ¶
purser.ErrUnauthenticated is the only error that is a verdict on the credential, and the only one that earns a 401. Anything else means the authenticator could not decide — its issuer's keys would not load, the endpoint it asks did not answer — and is a 503. The difference is what the client does next: a 401 tells it to discard its credential and sign in again, which during an outage on this side sends every user back through sign-in at once for a credential that was fine. purser.ErrUnavailable is how an authenticator says so on purpose, and it takes precedence when an error matches both; an error matching neither is treated the same way, since it is not a verdict either.
The 503 carries no WWW-Authenticate, for the same reason, and is logged at Warn.
It applies with Enforce off too (go-steer/purser#29). The fallback is for a request that brought no credential worth honoring, and an undecided one is not that: the authn.Authenticator contract makes a missing credential ErrUnauthenticated, and the conformance suite forbids ErrUnavailable alongside it, so only a client that presented a credential gets here. It asked to be someone. Serving it as Fallback would attribute its request to nobody and show it a view with its own state missing — signed out, its sessions gone — with nothing to say that retrying would fix it. Anonymous traffic is untouched: no credential is still ErrUnauthenticated, and still falls back.
The same split holds on the proxy path. An asserted identity the authenticator's authn.IdentityLookup could not resolve — the directory behind it did not answer — is a 503, not the 401 for an identity nobody provisioned.
func (*CallerMiddleware) GatesCredentials ¶
func (m *CallerMiddleware) GatesCredentials() bool
GatesCredentials reports whether every request that reaches the handler presented a credential the authenticator verified — which is to say, whether CallerOptions.Enforce was set.
It is deliberately the middleware's answer and not the authenticator's. authn.CredentialGate describes what an authenticator does with a request it is handed; whether a request that fails it still reaches the handler is settled here. A bearer table reports GatesCredentials() == true and is telling the truth about itself, yet the surface in front of it admits every anonymous request unless Enforce is set — so it is this method, not that one, that CheckBind has to be given.
func (*CallerMiddleware) Middleware ¶
func (m *CallerMiddleware) Middleware() Middleware
Middleware returns the resolver as a Middleware. It belongs innermost in the chain, closest to the handler that reads the Caller off the context.
type CallerOptions ¶
type CallerOptions struct {
// Authenticator resolves the inbound credential to a Caller.
//
// Nil means authn.Anonymous carrying Fallback: every request
// resolves to the same unverified identity. That is a legitimate
// posture for a surface that has not enabled per-caller identity,
// and it is why the middleware can promise that a Caller is always
// on the context.
Authenticator authn.Authenticator
// Fallback is the Caller a request falls back to when the
// authenticator returns purser.ErrUnauthenticated and Enforce is
// false. A zero Fallback means purser.Anonymous(). A credential the
// authenticator could not check is a 503 instead, Enforce or not; see
// NewCaller, "401 or 503".
//
// It is refused alongside Enforce, which has no fallback path.
Fallback purser.Caller
// Enforce turns a rejected credential into a 401 instead of a
// downgrade to Fallback. This is the posture for a surface that
// requires a credential; leaving it false is the posture for one
// that permits anonymous access. It has no bearing on a credential
// the authenticator could not check, which is a 503 either way.
//
// It is also what CallerMiddleware.GatesCredentials reports, and so
// what CheckBind reads when deciding whether this surface is safe
// to expose on the network.
Enforce bool
// ProxyHeader names the header a proxy-permitted Caller uses to
// assert an effective identity. Empty means
// authn.HeaderAssertedCaller.
//
// The header is consulted on every request regardless of this
// setting's origin, because a request that carries it and is not
// entitled to must be refused rather than ignored.
ProxyHeader string
// Logger receives the rejected-assertion audit line, a Warn for
// every request whose authenticator could not reach a verdict, and
// a Debug for every 401 naming the authenticator's reason. The
// request's own credential is removed from that reason before it is
// logged, as a backstop for an authenticator that quotes it; see
// scrubbed for what that does and does not catch. Nil means
// slog.Default().
Logger *slog.Logger
// Challenge is the WWW-Authenticate value sent with every 401 this
// middleware writes. Empty means `Bearer realm="purser"`.
//
// It exists for protected resources whose clients discover how to
// authenticate from the challenge: an MCP server names its RFC 9728
// metadata document there (`Bearer resource_metadata="https://…"`),
// and an MCP client that cannot find it cannot sign in. The value is
// sent verbatim. NewCaller refuses one that is not a valid header
// field value (RFC 9110 §5.5: no control bytes other than tab),
// because net/http would not refuse it either: HTTP/1 turns CR and
// LF into spaces, and the HTTP/2 server drops the header outright,
// so the client would get a 401 with no challenge at all.
Challenge string
}
CallerOptions configures NewCaller.
type Gate ¶
type Gate interface {
GatesCredentials() bool
}
Gate is the one question the bind policy asks: does this thing guarantee that every request reaching the handler presented a credential it verified?
*CallerMiddleware and *TokenGate implement it, as does an mTLS authenticator whose paired *tls.Config requires a verified client certificate — there the handshake has already refused the connection, so the guarantee holds before any middleware runs.
What does *not* answer this question is a non-transport authenticator on its own. A bearer table reports authn.CredentialGate.GatesCredentials() == true, and it is telling the truth about itself: every request *it* admits presented a token it checked. Whether a request it rejects still reaches the handler is CallerOptions.Enforce, decided a layer up. Pass the *CallerMiddleware.
It is deliberately not authn.CredentialGate itself: CheckBind has no use for Authenticate or Source, and requiring them would exclude a gate that is not an authenticator at all.
type Middleware ¶
Middleware is the decorator every constructor in this package returns. It is the conventional shape, named so that a chain reads as a list rather than as nested calls.
func BrowserWriteGuard ¶
func BrowserWriteGuard() Middleware
BrowserWriteGuard is NewBrowserWriteGuard with no extra allowed origins, for the common case of an API with no cross-origin browser client. It cannot fail, so it returns no error.
func Chain ¶
func Chain(mw ...Middleware) Middleware
Chain composes middlewares into one, outermost first: the first element sees the request before the second, and the handler passed to the result runs last.
Order matters here — see the package documentation — so the composition is spelled out rather than left to whatever order the wrapping happened to be written in.
func NewBrowserWriteGuard ¶
func NewBrowserWriteGuard(opts BrowserWriteGuardOptions) (Middleware, error)
NewBrowserWriteGuard returns the middleware that blocks the browser cross-site request forgery vectors against a JSON API.
A page the operator visits can fire a CORS "simple request" at a listener it cannot otherwise reach — a form POST, or fetch with Content-Type: text/plain — with no preflight. The response stays unreadable to the attacking page, which does not help: the side effect has already landed. For a local daemon on a well-known port with a well-known resource path, that is a one-line attack from any web page.
Two checks run on every state-changing request (any method other than GET, HEAD and OPTIONS), regardless of what credential it carries:
- Origin: when the request has an Origin header it must be a loopback origin, an origin matching the request's own Host, or one of AllowedOrigins. Otherwise 403. Browsers attach Origin to every cross-site write; native clients — curl, a Go SDK, another service — send none and pass untouched.
- Content-Type: application/json is required, otherwise 415. The three media types a cross-site simple request can carry are text/plain, multipart/form-data and application/x-www-form-urlencoded, so requiring JSON forces any browser write through a preflight the server never answers.
Reads are untouched. A cross-origin GET is already unreadable to the attacking page because the server sends no Access-Control-Allow-Origin, and guarding them would break the ordinary case of a browser following a link.
This is defense against the browser, not against a client that can set arbitrary headers. Anything with a socket can send `Content-Type: application/json` and no Origin; what stops *that* is the credential, which is a different middleware.
What it does not stop ¶
DNS rebinding. The self-origin rule compares the Origin's authority against the request's own Host, so a name the attacker controls that resolves to the listener's address — `evil.test` with an A record of 127.0.0.1, served from `http://evil.test:7777` — is same-origin to the browser and passes. The response is readable too, because the browser believes it is talking to its own origin. Closing that needs a Host allowlist, which belongs to the service that knows its own names; the standard mitigation is to reject requests whose Host is not one of them, before this middleware runs. Requiring the credential on every state-changing endpoint is the other half: a rebound page still has to steal one.
func ReadOnly ¶
func ReadOnly() Middleware
ReadOnly returns middleware that refuses every state-changing method with 403, whatever credential it carries.
It is a listener-wide switch, not an authorization rule: which callers may write is authz's question, and this is the blunter "nobody, on this listener" — a read-only mirror, a break-glass posture, a surface exposed for observation only.
type TokenGate ¶
type TokenGate struct {
// contains filtered or unexported fields
}
TokenGate is the transport-level shared-token check: one secret for the whole listener, checked before anything else runs.
It is not identity. Every caller presenting the token is indistinguishable from every other, so a deployment that needs to know *who* called pairs it with an authenticator, or replaces it with one. What it is good for is keeping an unauthenticated surface off the network — which is exactly what the bind policy asks it about, and why it implements Gate.
Prefer mTLS where there is certificate infrastructure. A shared token is a bearer secret: anything that sees it can replay it, it appears in process listings and shell history, and it does not rotate on its own.
func NewTokenGate ¶
func NewTokenGate(opts TokenGateOptions) (*TokenGate, error)
NewTokenGate returns a gate requiring opts.Token on every request.
func (*TokenGate) GatesCredentials ¶
GatesCredentials reports true: every request that gets past this gate presented the token.
func (*TokenGate) Middleware ¶
func (g *TokenGate) Middleware() Middleware
Middleware returns the gate as a Middleware. It belongs outermost in the chain: it is the cheapest rejection available and it runs before anything reads a body.
A request that passes carries purser.AuthSourceBearer on its context, so a caller middleware further in whose authenticator verified nothing itself still reports how the request actually got in. See NewCaller.
type TokenGateOptions ¶
type TokenGateOptions struct {
// Token is the shared secret every request must present.
// Required: a gate with no token would admit everything while
// reporting that it gates credentials, which is the one lie the
// bind policy cannot survive.
Token string
// SideChannelHeader names a header the token may be presented in
// instead of Authorization, for deployments where an identity
// gateway owns Authorization for its own validation. Empty means
// authn.HeaderAttachToken; set it to "-" to accept the token only
// on Authorization.
SideChannelHeader string
// Realm is the WWW-Authenticate realm on a 401. Empty means
// "purser".
Realm string
}
TokenGateOptions configures NewTokenGate.