auth

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package auth provides secure cookie session authentication for server-rendered ghtmx applications: cookie hygiene, opaque session tokens, CSRF protection, and htmx-aware login redirects, behind one small interface the application implements.

The package owns the request-side mechanics only. Session storage, lookup, expiry policy, user records, password hashing, registration, and authorization all live behind Authenticator, supplied by the application. The library never dictates an identity shape: the Authenticator's ID type parameter is whatever the application returns.

Layering

Middleware and CSRF are net/http middleware (func(http.Handler) http.Handler), directly usable with adapters/nethttp and chi. The adapters for frameworks whose contexts differ (gin, echo, fiber v2/v3) ship thin glue packages that delegate to the same engine functions (Require, AuthenticateToken, VerifyCSRFToken), so behavior is identical by construction.

Install the session middleware before the CSRF middleware: the CSRF token is derived from the session and travels in the request context. Without a session ahead of it, the CSRF middleware rejects every unsafe request — it fails closed, never open.

Threat model

Session tokens are 256-bit random values; only their SHA-256 hash is ever stored server-side (NewSessionToken), so a database disclosure cannot be replayed as a live session. The session cookie is always HttpOnly and host-only (no Domain attribute), Secure unless explicitly configured for local http development, and SameSite Strict or Lax — None is unrepresentable. When the cookie is scoped to the whole site over https, the __Host- prefix is applied automatically.

The always-on CSRF layer uses per-session synchronizer tokens (derived, not stored), and the login form gets its own pre-session double-submit token (SetLoginCSRFCookie) because SameSite does not stop login CSRF: it governs whether an existing cookie is sent, not whether an unauthenticated POST is accepted.

The cookie's TTL is advisory — it tells a well-behaved browser when to drop the cookie. Real expiry and revocation are enforced server-side, inside Authenticator.Authenticate: return an error wrapping ErrUnauthorized and the middleware clears the cookie and redirects to login. There is no anonymous session to fixate: tokens are minted only at successful sign-in, never promoted from a pre-login cookie.

Index

Constants

View Source
const DefaultCSRFFormField = "_csrf"

DefaultCSRFFormField is the form field name VerifyCSRF reads the CSRF token from when it is not in the request header. Templates embed it as a hidden input:

<input type="hidden" name="_csrf" value={ token }>
View Source
const DefaultCookieName = "ghtmx_session"

DefaultCookieName is the session cookie name used when Config.CookieName is empty. The __Host- prefix may still be applied on top; Config.EffectiveCookieName reports the name actually used.

View Source
const MethodQuery = "QUERY"

MethodQuery is the HTTP QUERY method (safe, idempotent, with a body), which net/http does not name yet.

Variables

View Source
var ErrCSRF = errors.New("auth: csrf token missing or invalid")

ErrCSRF is returned by VerifyCSRF and VerifyCSRFToken when the request carries no CSRF token, or one that does not match the session's. The middleware answers it with a 403.

View Source
var ErrUnauthorized = errors.New("auth: unauthorized")

ErrUnauthorized is the sentinel an Authenticator wraps when a session token is unusable — expired, revoked, or unknown. The middleware reacts by clearing the session cookie (so the browser stops resending a value that can never work) and redirecting to the login page. Any other error is treated as an application failure and answered with a plain 500: an auth-store outage must not degrade into "please sign in".

Functions

func AuthenticateToken

func AuthenticateToken[ID any](ctx context.Context, cfg Config[ID], token string) (context.Context, ID, error)

AuthenticateToken is the framework-neutral session step shared by Middleware and the fiber glue: it authenticates the raw cookie token and, on success, returns a context carrying the identity and the derived per-session CSRF token. The error is the Authenticator's, unwrapped — callers branch on ErrUnauthorized.

func CSRF

func CSRF(opts ...CSRFOption) func(http.Handler) http.Handler

CSRF returns the CSRF middleware. The methods DefaultSafeMethods names pass through; every other method must carry the session's CSRF token — in the ghtmx.DefaultCSRFHeaderName header or the DefaultCSRFFormField form field — or the request is rejected with a 403.

Install it after Middleware: the expected token comes from the request context. With no session middleware ahead of it there is no token to match and every unsafe request is rejected — the layer fails closed. It is deliberately not optional: SameSite protects at the registrable-domain level, not the subdomain level, so a hostile or XSS'd sibling subdomain can still forge requests, and the token keeps the protection fail-closed if the cookie policy is ever loosened.

WithOnReject watches rejections. WithSafeMethods is the one option that changes whether a request is accepted: it replaces the exempt-method list, and is how an application declines the QUERY exemption.

func CSRFTokenFrom

func CSRFTokenFrom(ctx context.Context) (string, bool)

CSRFTokenFrom returns the per-session CSRF token the session middleware derived for this request — the value templates embed via ghtmx.CSRFHeader or a hidden form field. ok is false when the session middleware is not installed ahead of the caller.

func ClearSessionCookie

func ClearSessionCookie[ID any](w http.ResponseWriter, cfg Config[ID])

ClearSessionCookie deletes the session cookie — on sign-out, or when the middleware learns the session is dead. The middleware calls it itself on ErrUnauthorized; applications call it from their sign-out handler.

func ContextWithCSRFToken

func ContextWithCSRFToken(ctx context.Context, token string) context.Context

ContextWithCSRFToken returns a context carrying the per-session CSRF token, for handler tests that exercise VerifyCSRFToken paths.

func ContextWithIdentity

func ContextWithIdentity(ctx context.Context, identity any) context.Context

ContextWithIdentity returns a context carrying identity, as the session middleware installs it after a successful Authenticate. It is exported so handler tests can build an authenticated context without running the middleware.

func DefaultSafeMethods added in v0.2.1

func DefaultSafeMethods() []string

DefaultSafeMethods returns the methods that need no CSRF token unless WithSafeMethods says otherwise: GET, HEAD, OPTIONS, and QUERY. The result is a fresh slice; mutating it changes nothing.

func EqualTokens

func EqualTokens(a, b string) bool

EqualTokens compares two tokens in constant time. It rejects empty strings explicitly: subtle.ConstantTimeCompare("", "") returns 1, so a naive constant-time compare would accept an empty submission against a session that carries no token.

func HasFormContentType added in v0.1.22

func HasFormContentType(contentType string) bool

HasFormContentType reports whether a Content-Type header value names a form body a CSRF token may legitimately arrive in: urlencoded or multipart, with any parameters (a charset, a multipart boundary). Anything it cannot parse is not a form — the gate fails closed.

It is exported, and takes the header value rather than a request, so the fiber glue — which reads the body natively through fasthttp and has no *http.Request to hand over — gates on this exact rule instead of on an argument that the two paths happen to agree.

func HashSessionToken

func HashSessionToken(token string) string

HashSessionToken returns the SHA-256 hex digest of token — the value NewSessionToken returns as storedHash, recomputed at lookup time so the application's store never sees the token itself.

func IdentityFrom

func IdentityFrom[ID any](ctx context.Context) (ID, bool)

IdentityFrom returns the identity the session middleware stored for this request. ok is false when the middleware is not installed ahead of the caller or ID is not the type the Authenticator returned — both are wiring bugs, and downstream guards must refuse the request (and say why in the log), never treat it as anonymous.

func Middleware

func Middleware[ID any](cfg Config[ID]) func(http.Handler) http.Handler

Middleware returns the session middleware: it authenticates the session cookie on every request and either installs the identity and per-session CSRF token in the request context or answers the request itself (Require describes the exact outcomes). The signature is net/http's middleware shape, so it plugs directly into adapters/nethttp servers and chi routers; the other frameworks have glue packages.

Middleware panics if cfg is invalid — see Config.Validate.

func NewCSRFToken

func NewCSRFToken() (string, error)

NewCSRFToken mints a random token for the pre-session double-submit cookie the login form uses (SetLoginCSRFCookie). Per-session CSRF tokens are not minted with this — they are derived from the session token by the middleware and read with CSRFTokenFrom.

func NewSessionToken

func NewSessionToken() (token, storedHash string, err error)

NewSessionToken mints an opaque session token for a fresh sign-in and the hash to store server-side. Only storedHash — the SHA-256 hex of the token, as HashSessionToken computes it — is ever persisted, so a database disclosure (backup, dump, read-only SQL injection) cannot be replayed as a live session. Plain SHA-256 is correct here: the input is 256 bits of uniform randomness, so a slow KDF would buy nothing but per-request latency.

func RedirectToLogin

func RedirectToLogin(w http.ResponseWriter, r *http.Request, loginURL string)

RedirectToLogin sends an unauthenticated request to the login page the way its client can follow: browser navigations get a 303 See Other, but a request htmx issued must not — htmx would swap the login page into the target element — so it gets HX-Redirect with a 204 and htmx performs a full page load. The HX-Redirect header is set before the status is written; net/http drops headers set afterwards.

func Require

func Require[ID any](cfg Config[ID], w http.ResponseWriter, r *http.Request) (*http.Request, bool)

Require runs the session check for one request. On success it returns the request with identity and CSRF token installed in its context and ok true. Otherwise it writes the complete response itself and returns ok false:

  • no session cookie: redirect to LoginURL (RedirectToLogin).
  • Authenticate wraps ErrUnauthorized: clear the cookie, then redirect — the browser must stop resending a dead token.
  • any other Authenticate error: plain 500. An auth-store outage is not "please sign in".

Require assumes cfg has been validated; Middleware and the glue packages' constructors do that once at startup. It is exported as the per-request engine those glue packages share.

func SafeMethod

func SafeMethod(method string) bool

SafeMethod reports whether method needs no CSRF token: GET, HEAD, OPTIONS, and QUERY, which must never change state. QUERY is the safe, idempotent method with a body that htmx 4's hx-query issues; like GET it must not mutate, and unlike a form post a browser sends it cross-origin only after a CORS preflight. Exported so the glue packages share one safe-list.

It is the default, not the whole story: a middleware built with WithSafeMethods decides through CSRFOptions.SafeMethod instead. QUERY became exempt here in v0.2.0 for every consumer, whatever htmx version the project pins — see WithSafeMethods to decline it.

func SetLoginCSRFCookie

func SetLoginCSRFCookie[ID any](w http.ResponseWriter, cfg Config[ID]) (formValue string, err error)

SetLoginCSRFCookie mints the login form's pre-session double-submit token, sets it as a cookie, and returns the value the form embeds in a hidden field. SameSite does not protect the login form — it governs whether an existing cookie is sent, not whether an unauthenticated POST is accepted — so without this token an attacker can submit their own credentials from the victim's browser, after which the victim unknowingly works inside the attacker's account. Call it from the GET handler that renders the login page, and check the submission with ValidLoginCSRF before verifying credentials.

func SetSessionCookie

func SetSessionCookie[ID any](w http.ResponseWriter, cfg Config[ID], token string)

SetSessionCookie sets the session cookie after a successful sign-in. token is the raw value from NewSessionToken — the application stores only the hash, the browser only the token.

func ValidLoginCSRF

func ValidLoginCSRF[ID any](r *http.Request, cfg Config[ID], submitted string) bool

ValidLoginCSRF reports whether the login form submission carries the token SetLoginCSRFCookie set, compared in constant time. False — missing cookie, missing submission, or mismatch — means the login POST must be rejected before credentials are even looked at.

func VerifyCSRF

func VerifyCSRF(r *http.Request) error

VerifyCSRF extracts the submitted CSRF token from the request and checks it against the session's (VerifyCSRFToken). The header is consulted first — a browser won't attach a custom header cross-origin without a CORS preflight, making it a strictly stronger channel than the form field — then the DefaultCSRFFormField form field, and only for form Content-Types (HasFormContentType, the same gate the fiber glue applies). The query string is never consulted: tokens must not ride in URLs, where they leak into logs and Referer headers.

The form fallback uses Request.PostFormValue, which parses and caches the request body (multipart bodies at the 32 MB default limit); a handler that later parses the form itself sees the cached result.

func VerifyCSRFToken

func VerifyCSRFToken(ctx context.Context, submitted string) error

VerifyCSRFToken compares a submitted CSRF token against the one the session middleware stored in ctx, in constant time. It returns ErrCSRF when the context carries no token (session middleware not installed ahead of the caller — fail closed), the submission is empty, or the values differ. This is the single comparison site; the fiber glue extracts the submission natively and calls it.

Types

type Authenticator

type Authenticator[ID any] interface {
	// Authenticate returns the identity behind token, or an error
	// wrapping [ErrUnauthorized] when the session is unusable. This is
	// where real session expiry and revocation are enforced; the
	// cookie's TTL only advises the browser.
	Authenticate(ctx context.Context, token string) (ID, error)
}

Authenticator is the one interface the application implements. It resolves a session token to the identity behind it. Everything else — session storage, lookup, server-side expiry, revocation, user records — is the application's business, behind this method.

type CSRFOption added in v0.1.22

type CSRFOption func(*CSRFOptions)

CSRFOption configures a CSRF middleware. The same options work for CSRF and for every adapter's glue CSRF middleware, so an application wires its observability once and keeps it across a framework switch.

func WithOnReject added in v0.1.22

func WithOnReject(fn func(ctx context.Context, rej CSRFRejection)) CSRFOption

WithOnReject installs an observer called just before the middleware answers 403, so an application can count probes, alert, or debug a migration without wrapping the middleware. It cannot change the outcome: the 403 is already decided, and the hook's return value — there is none — is not consulted.

The hook runs on the request's goroutine, so a slow one is a slow rejection; hand anything expensive to a queue. Read the identity, when there is one, with IdentityFrom on the same ctx.

func WithSafeMethods added in v0.2.1

func WithSafeMethods(methods ...string) CSRFOption

WithSafeMethods replaces the set of methods that need no CSRF token, for this middleware only. The default is DefaultSafeMethods — GET, HEAD, OPTIONS, and QUERY.

It exists because the QUERY exemption arrived with htmx 4 support and applies to every consumer, whatever htmx version the project pins: this package is runtime code and cannot see the compile-time pin. An application that serves a state-changing handler on QUERY — Fiber v3 carries QUERY in its DefaultMethods, so an app.All route answers it — declines the exemption with the htmx 2 safe-list:

auth.CSRF(auth.WithSafeMethods(
	http.MethodGet, http.MethodHead, http.MethodOptions))

Methods are matched exactly, so pass them in the upper case the standard library's http.Method* constants use. Calling it with no arguments makes every method unsafe, GET included — the safe-list is replaced wholesale, never merged with the default.

type CSRFOptions added in v0.1.22

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

CSRFOptions is the applied form of the CSRFOption list a CSRF middleware was constructed with. It is exported, with unexported fields, because every glue package builds one and reports through it — the same reason SafeMethod and VerifyCSRFToken are exported.

func NewCSRFOptions added in v0.1.22

func NewCSRFOptions(opts ...CSRFOption) CSRFOptions

NewCSRFOptions applies opts. The glue packages call it once at construction, not per request, and keep the result.

func (CSRFOptions) Report added in v0.1.22

func (o CSRFOptions) Report(ctx context.Context, rej CSRFRejection)

Report invokes the WithOnReject hook if one is set, and does nothing otherwise. It is the single reporting site every middleware shares, so the nil check can never diverge between adapters.

func (CSRFOptions) SafeMethod added in v0.2.1

func (o CSRFOptions) SafeMethod(method string) bool

SafeMethod reports whether method needs no CSRF token under these options: the WithSafeMethods list if one was given, and the package-level SafeMethod default otherwise. It is the single decision site every middleware shares, so the safe-list can never diverge between adapters — the same reason CSRFOptions.Report is the single reporting site.

type CSRFRejection added in v0.1.22

type CSRFRejection struct {
	// Method is the rejected request's HTTP method.
	Method string
	// Path is the request path — never the route pattern, and never the
	// query string, which must not carry tokens in the first place.
	Path string
	// Err is why the request was rejected; it always satisfies
	// errors.Is(err, ErrCSRF).
	Err error
}

CSRFRejection describes one rejected unsafe request, as handed to a WithOnReject hook. It is a struct rather than loose parameters so later releases can report more without breaking every hook.

The identity is deliberately absent: it is generic in the Authenticator's ID type, which this struct cannot be, and the hook can read it from the same context with IdentityFrom.

type Config

type Config[ID any] struct {
	// Authenticator resolves session tokens to identities. Required.
	Authenticator Authenticator[ID]

	// CookieName is the session cookie's base name,
	// [DefaultCookieName] when empty. The __Host- prefix is applied
	// automatically when the cookie is site-wide and Secure; use
	// [Config.EffectiveCookieName] for the name on the wire.
	CookieName string

	// CookiePath scopes the cookie, "/" when empty. Setting it to a
	// sub-app path (e.g. "/admin") keeps the token off the rest of the
	// host's requests, but is mutually exclusive with the __Host-
	// prefix, which requires Path=/. The cookie is host-only either
	// way: no Domain attribute is ever set, so the session is never
	// shared with subdomains.
	CookiePath string

	// Insecure drops the cookie's Secure attribute — for local http
	// development only. The zero value keeps Secure on, which is why
	// this field is inverted: forgetting it must mean secure.
	Insecure bool

	// SameSite is Strict (zero value) or Lax; see [SameSite].
	SameSite SameSite

	// TTL is the cookie's Max-Age. Zero means a session cookie
	// (dropped when the browser closes). This only advises the
	// browser — real expiry is enforced server-side, inside
	// [Authenticator.Authenticate].
	TTL time.Duration

	// LoginURL is where unauthenticated requests are sent: browser
	// navigations with a 303, htmx requests with HX-Redirect and a
	// 204 (so htmx performs a full page load instead of swapping the
	// login page into the target element). Required.
	LoginURL string
}

Config configures the session middleware. The zero value of every optional field is the safe choice: cookies are Secure, SameSite Strict, named DefaultCookieName, and scoped to "/" (which also activates the __Host- prefix). Authenticator and LoginURL are required; Config.Validate reports anything unusable, and the middleware constructors panic on an invalid Config rather than serve a single request with it.

func (Config[ID]) EffectiveCookieName

func (c Config[ID]) EffectiveCookieName() string

EffectiveCookieName is the session cookie name actually used on the wire: CookieName (or DefaultCookieName) with the __Host- prefix applied when the cookie is site-wide and Secure.

func (Config[ID]) LoginCSRFCookie

func (c Config[ID]) LoginCSRFCookie(token string) *http.Cookie

LoginCSRFCookie is the Set-Cookie payload for the login form's pre-session double-submit token: session-lifetime (no Max-Age), otherwise sharing the session cookie's attributes.

func (Config[ID]) LoginCSRFCookieName

func (c Config[ID]) LoginCSRFCookieName() string

LoginCSRFCookieName is the name of the login form's pre-session double-submit cookie, derived from the session cookie name under the same prefix rule.

func (Config[ID]) SessionClearingCookie

func (c Config[ID]) SessionClearingCookie() *http.Cookie

SessionClearingCookie is the Set-Cookie payload that deletes the session cookie: same name and attributes, empty value, MaxAge -1 — net/http's convention for "expire immediately", which it serializes as Max-Age=0 (RFC 6265).

MaxAge -1 is a value, not a wire format, and the fiber glue does not hand this cookie to net/http: each fiber major translates it into fasthttp's cookie type and must get the deletion attributes right for its own serializer. See fiberauth.ClearSessionCookie and fiberv3auth.ClearSessionCookie, which differ for that reason.

func (Config[ID]) SessionCookie

func (c Config[ID]) SessionCookie(token string) *http.Cookie

SessionCookie is the Set-Cookie payload for a fresh sign-in: the session cookie carrying token, with Max-Age from TTL (rounded up to a whole second; absent for a zero TTL, making it a browser-session cookie). Most net/http applications use SetSessionCookie instead; this constructor exists so the fiber glue can translate the exact same attributes into fasthttp's cookie type.

func (Config[ID]) Validate

func (c Config[ID]) Validate() error

Validate reports whether the Config is usable. The middleware constructors call it and panic on error — a bad Config is a wiring bug, detectable at process start, and gin/echo/fiber middleware constructors have no error return. Applications preferring an error can call Validate themselves first.

type SameSite

type SameSite int

SameSite is the SameSite attribute of the session cookie. Only Strict and Lax exist: None would let the cookie ride on cross-site requests and is unrepresentable here by design. The zero value is Strict.

The choice is UX, not security — the always-on CSRF token layer keeps both settings safe. Strict is right for portals and dashboards nothing links into; Lax is right for an app users arrive at via external links, where Strict would drop the cookie on that first navigation and land a signed-in user on the login page.

const (
	// SameSiteStrict sends the cookie on same-site requests only. The
	// default.
	SameSiteStrict SameSite = iota
	// SameSiteLax additionally sends the cookie on top-level cross-site
	// navigations (following an external link), per the htmx security
	// essay's baseline.
	SameSiteLax
)

Jump to

Keyboard shortcuts

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