Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for the Chronicle Echo server. Middleware is applied globally (all routes) or per-route group depending on the middleware type. See internal/app/routes.go for registration.
Package middleware provides HTTP middleware for Chronicle. ratelimit.go implements sliding-window rate limiters stored in memory: RateLimit keys by IP (auth endpoints, uploads), UserRateLimit by a caller-supplied identity (authenticated-only routes).
Index ¶
- Constants
- Variables
- func BodyLimitFunc(limit func() int64, skip func(*echo.Context) bool) echo.MiddlewareFunc
- func BuildHeader(token string) echo.MiddlewareFunc
- func CORS(cfg CORSConfig) echo.MiddlewareFunc
- func CSPReportHandler() echo.HandlerFunc
- func CSRF() echo.MiddlewareFunc
- func ClientIPHeader() string
- func GetCSRFToken(c *echo.Context) string
- func HTMXRedirect(c *echo.Context, url string) error
- func IsAPIRequest(c *echo.Context) bool
- func IsClientIPMode(mode string) bool
- func IsHTMX(c *echo.Context) bool
- func IsSameOriginFrame(c *echo.Context) bool
- func MediaContext(c *echo.Context) context.Context
- func ParseTrustedProxies(trustedCIDRs []string) ([]*net.IPNet, error)
- func RateLimit(maxRequests int, window time.Duration) echo.MiddlewareFunc
- func Recovery() echo.MiddlewareFunc
- func Render(c *echo.Context, statusCode int, component templ.Component) error
- func RequestLogger() echo.MiddlewareFunc
- func RequireInCampaign[T CampaignScoped](ctx context.Context, fetchFn func(ctx context.Context, id string) (T, error), ...) (T, error)
- func ResponseState(c *echo.Context) *echo.Response
- func SchemeIsSecure(req *http.Request) bool
- func SecurityHeaders() echo.MiddlewareFunc
- func ServeAttachment(c *echo.Context, path, name string) error
- func ServeFile(c *echo.Context, path string) error
- func SetClientIPHeader(mode string)
- func StaticCache(urlPrefix string) echo.MiddlewareFunc
- func StaticGzip(urlPrefix string) echo.MiddlewareFunc
- func TrustedProxies(e *echo.Echo, trustedCIDRs []string) error
- func TrustedProxyList() []string
- func UserRateLimit(identity func(*echo.Context) string, maxRequests int, window time.Duration) echo.MiddlewareFunc
- type CORSConfig
- type CampaignScoped
- type ClientIPDiagnosis
Constants ¶
const ( // ClientIPAuto reads X-Real-IP when present, otherwise X-Forwarded-For from // the right. It is what a site that never chose behaves as. ClientIPAuto = "auto" // ClientIPRealIP believes X-Real-IP only. ClientIPRealIP = "x-real-ip" // ClientIPForwardedFor believes X-Forwarded-For only, read from the right. ClientIPForwardedFor = "x-forwarded-for" // ClientIPDirect ignores every header and uses the connection's address. ClientIPDirect = "direct" )
Values of the client-address setting. They match the settings plugin's stored values; middleware cannot import plugins, so app wires them across.
const BuildHeaderName = "X-Chronicle-Build"
BuildHeaderName carries the running build's token on every response.
const CSPReportPath = "/csp-report"
CSPReportPath is where browsers send report-only violations. It takes no session and changes nothing but a log line, so CSRF does not apply to it.
const CSRFFriendlyMessage = "Your session expired or this page was open too long. Please reload and sign in again."
CSRFFriendlyMessage is the human-readable text shown to users when CSRF validation fails. It deliberately avoids the "CSRF" jargon (the precise reason is logged, not surfaced) and points at the real fix: reload. Shared by the middleware (the 403 body) and the login page's recovery banner.
Variables ¶
var DefaultTrustedProxies = []string{
"127.0.0.0/8",
"::1/128",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fd00::/8",
}
DefaultTrustedProxies is the trusted-proxy list used when TRUSTED_PROXY_CIDRS is not set: loopback plus the private ranges a container platform puts its bridges on. It deliberately contains no public or carrier-grade range, so an unconfigured deployment trusts nothing that could arrive from the internet.
A deployment whose reverse proxy reaches Chronicle from outside these ranges -- a mesh VPN peer, for instance, which lands in 100.64.0.0/10 -- MUST name that proxy in TRUSTED_PROXY_CIDRS or every visitor is recorded as the proxy. Name the proxy's own address as a /32 rather than its whole range: every host inside a trusted range can dictate the client IP of every request it relays.
LayoutInjector is a function that copies layout-relevant data from the Echo context (populated by auth/campaign middleware) into Go's context.Context so Templ templates can read it. Registered once at startup in app/routes.go.
This callback pattern avoids the middleware package importing any plugin types.
var MediaSigner func(*echo.Context) (layouts.MediaURLFunc, layouts.MediaThumbFunc)
MediaSigner builds the signed media-URL generators bound to whoever is making the request. Registered once at startup in app/routes.go, where the signing secret lives; nil means signing is off and links fall back to unsigned /media/ paths.
Functions ¶
func BodyLimitFunc ¶
BodyLimitFunc caps the request body at the size limit() returns, read on every request so a changed setting applies without a restart. skip chooses which requests it covers. A limit of 0 or less means no cap.
It exists for upload routes whose cap depends on a live setting but which must be bounded before the CSRF middleware runs: CSRF reads the form field and so parses the whole multipart body before anyone is signed in. A declared length over the limit is refused with 413 straight away; an undeclared (chunked) body is cut off at the limit as it is read.
func BuildHeader ¶
func BuildHeader(token string) echo.MiddlewareFunc
BuildHeader stamps each response with the running build's token. A page keeps its first load's scripts across boosted navigation, live refreshes and Back, which swap only page markup, so after a deploy an open tab would pair new page markup and CSS with old scripts. boot.js compares this header with the token the page loaded with and turns a mismatched swap into a full load.
func CORS ¶
func CORS(cfg CORSConfig) echo.MiddlewareFunc
CORS returns middleware that handles Cross-Origin Resource Sharing headers. Primarily needed for the REST API (/api/v1/*) when external clients like the Foundry VTT module make requests from a different origin; the web UI is same-origin and doesn't need it.
It never allows credentials: outside clients authenticate with a Bearer key, and a page on an allowed origin must not be able to read Chronicle pages, or post to them, with the visitor's session cookie.
func CSPReportHandler ¶
func CSPReportHandler() echo.HandlerFunc
CSPReportHandler accepts both report formats (the older application/csp-report body and the Reporting API's list) and logs each distinct violation once, with how its page and script are found again. Repeats are counted, not logged. It always answers 204, so a browser has nothing to retry and a caller learns nothing.
func CSRF ¶
func CSRF() echo.MiddlewareFunc
CSRF returns middleware that implements the double-submit cookie pattern for CSRF protection on all state-changing requests (POST, PUT, PATCH, DELETE).
How it works:
- On every request, if no CSRF cookie exists, generate one and set it.
- On mutating requests, compare the cookie value with either: - The X-CSRF-Token header (for HTMX/AJAX requests) - The csrf_token form field (for traditional form submissions)
- If they don't match, reject with 403 Forbidden.
The cookie name uses the __Host- prefix over HTTPS for defense against subdomain cookie injection. Over plain HTTP (dev only) the prefix is omitted.
func GetCSRFToken ¶
GetCSRFToken retrieves the CSRF token from the Echo context. Use this in Templ templates to inject the token into forms.
func HTMXRedirect ¶
HTMXRedirect sends a redirect that works for both HTMX and normal requests. For HTMX requests it sets the HX-Redirect header and returns 204 No Content (so HTMX performs a client-side redirect). For normal requests it returns a standard 303 See Other redirect.
func IsAPIRequest ¶
IsAPIRequest reports whether the caller expects JSON rather than HTML: the path is under /api, or the request sent or asked for JSON (Content-Type or Accept: application/json). The header checks catch fetch() widgets under /campaigns/*, and match the app's error handler, so such a caller gets JSON from a refusal the same way it does from an error.
func IsClientIPMode ¶
IsClientIPMode reports whether mode is one of the four known values.
func IsHTMX ¶
IsHTMX returns true if the current request was initiated by HTMX and is NOT a boosted navigation or a history restore. Boosted requests (hx-boost="true") behave like normal page navigations — they expect full page responses so hx-select can extract the target element. A history restore (Back or Forward; boot.js keeps htmx's history cache off, so every one fetches) swaps the whole body with what it gets, so it needs the full page too, or the sidebar and top bar vanish. Handlers use this to decide whether to return a fragment or full page.
func IsSameOriginFrame ¶
IsSameOriginFrame reports whether this request loads a page inside a frame on one of Chronicle's own pages: a page opened beside another (static/js/beside.js). Browsers set both headers themselves, so another site framing Chronicle always says cross-site here.
func MediaContext ¶
MediaContext returns the request context with the signed media-URL generators attached. JSON handlers use it so layouts.AvatarURL and layouts.MediaURL sign links for the caller the way a rendered page does; Render does not run for JSON, so without this they would always fall back to unsigned links.
func ParseTrustedProxies ¶
ParseTrustedProxies turns the configured entries into networks, rejecting anything it cannot parse. A bare address is read as a single host, so an operator naming one proxy does not have to remember the /32 suffix.
func RateLimit ¶
func RateLimit(maxRequests int, window time.Duration) echo.MiddlewareFunc
RateLimit returns middleware that limits requests per IP to maxRequests within the given window duration. Returns 429 when exceeded.
func Recovery ¶
func Recovery() echo.MiddlewareFunc
Recovery returns middleware that recovers from panics, logs the stack trace, and returns a 500 Internal Server Error to the client. This prevents a single panicking handler from crashing the entire server.
func Render ¶
Render writes a Templ component to the response with the given status code. Before rendering, it runs the LayoutInjector (if registered) to copy session/campaign data into the Go context for Templ templates to access.
func RequestLogger ¶
func RequestLogger() echo.MiddlewareFunc
RequestLogger returns middleware that logs every HTTP request with structured fields: method, path, status, latency, and remote IP. Uses Go's built-in slog for structured logging.
Sensitive query parameters (token, key, password, secret) are redacted to prevent credential leakage in log files.
func RequireInCampaign ¶
func RequireInCampaign[T CampaignScoped](ctx context.Context, fetchFn func(ctx context.Context, id string) (T, error), resourceID, campaignID, resourceName string) (T, error)
RequireInCampaign fetches a resource by ID using the provided fetch function, then verifies it belongs to the expected campaign. Returns the resource if ownership matches, or a 404 error if the resource does not exist or belongs to a different campaign. This eliminates duplicated IDOR checks across plugin handlers.
func ResponseState ¶
ResponseState returns Echo's response wrapper for the request, which carries the status, size and committed flag that http.ResponseWriter does not. A middleware may swap in its own writer (gzip, for example), so it unwraps. When nothing unwraps to Echo's type it returns an uncommitted 200, which is what a fresh response reports.
func SchemeIsSecure ¶
SchemeIsSecure reports whether the original client connection was HTTPS, tolerant of a TLS-terminating proxy (X-Forwarded-Proto). Exported so the auth plugin can pick the same __Host--prefixed cookie name for the session cookie as this package uses for the CSRF cookie — one detection, no drift.
func SecurityHeaders ¶
func SecurityHeaders() echo.MiddlewareFunc
SecurityHeaders returns middleware that sets security-related HTTP headers on every response. These headers protect against common web attacks even if application-level vulnerabilities exist.
Since Chronicle runs behind Cosmos Cloud's reverse proxy, TLS is handled externally. These headers provide defense-in-depth at the application layer.
func ServeAttachment ¶
ServeAttachment sends the file at path as a download named name. The name is Go-quoted, so a quote or newline in it cannot end the header value.
func ServeFile ¶
ServeFile sends the file at an operating-system path. Echo's c.File opens names inside its own filesystem, which is rooted at the working directory, so a media or backup directory elsewhere would answer 404. Callers resolve and check the path first; this only opens it.
func SetClientIPHeader ¶
func SetClientIPHeader(mode string)
SetClientIPHeader chooses which header the extractor believes. An unknown value becomes auto, so a damaged setting never turns the headers off or back to reading the leftmost entry.
func StaticCache ¶
func StaticCache(urlPrefix string) echo.MiddlewareFunc
StaticCache sets an explicit Cache-Control policy on static asset responses. Echo's `e.Static` serves via `http.ServeContent`, which emits Last-Modified but no Cache-Control, letting browsers reuse a stale file for hours after a deploy. See layouts.AssetURL for the `?v=` cache-busting token this depends on: with `?v=` the URL is content-addressed, so cache hard and forever (`immutable`); without it (hand-typed URL, legacy link, forgotten conversion), allow caching but force revalidation so a stale copy is at worst one 304 away from correct.
Applied as a default before the handler runs — requests outside urlPrefix pass through, and a handler's own Cache-Control wins afterwards. Registered globally, not on a route group, because static assets are mounted in two places (`/static` and each plugin's `/static/plugins/<slug>`).
func StaticGzip ¶
func StaticGzip(urlPrefix string) echo.MiddlewareFunc
StaticGzip compresses text assets under urlPrefix. A page's scripts and styles come to a few megabytes, and a phone on a slow link spends most of its first visit downloading them. Pages themselves are never compressed here: they carry CSRF tokens, which compression exposes to BREACH-style guessing, while static files hold nothing secret. A reverse proxy that compresses too sees Content-Encoding already set and passes it through.
func TrustedProxies ¶
TrustedProxies configures Echo to trust reverse proxy headers (X-Forwarded-For, X-Real-IP) from specific IP ranges, and returns an error if any entry is unparseable. Without this, c.RealIP() returns the proxy's address for every request, collapsing per-IP rate limiting into one shared bucket and writing the same address into every audit row.
Entries may be CIDR blocks ("10.0.0.0/8") or bare addresses ("100.64.0.10", read as a single host). An unparseable entry is a startup ERROR, never a silent skip, so a typo in the deployment environment can't silently stop client IPs resolving.
SECURITY: once a peer is trusted, the headers it sends decide what gets recorded. X-Forwarded-For is read from the right, so an entry the visitor wrote ahead of the proxy's own is never believed; X-Real-IP is believed as sent, so the proxy must overwrite it. Trust the specific proxy, and pick the header it really sets under Admin > Security > Visitor addresses.
func TrustedProxyList ¶
func TrustedProxyList() []string
TrustedProxyList returns the trusted proxy entries in use, as configured.
func UserRateLimit ¶
func UserRateLimit(identity func(*echo.Context) string, maxRequests int, window time.Duration) echo.MiddlewareFunc
UserRateLimit limits requests to maxRequests per window, keyed by identity(c). The caller supplies identity so this package never imports plugin code; an empty identity skips limiting. Over the limit it answers with the app's normal 429 (apperror.NewTooManyRequests) and Retry-After.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// AllowedOrigins is the list of origins permitted to make cross-origin
// requests. Use ["*"] to allow all (not recommended for production).
// Example: ["https://chronicle.yourdomain.com", "http://localhost:3000"]
AllowedOrigins []string
// DynamicOrigins is an optional function that returns additional allowed
// origins at runtime. Called per-request to support admin-managed origin
// whitelists stored in the database. May return nil.
DynamicOrigins func() []string
}
CORSConfig holds configuration for the CORS middleware.
type CampaignScoped ¶
type CampaignScoped interface {
GetCampaignID() string
}
CampaignScoped is satisfied by any model that belongs to a campaign. Used by RequireInCampaign to validate resource ownership and prevent cross-campaign IDOR attacks.
type ClientIPDiagnosis ¶
type ClientIPDiagnosis struct {
Mode string
// Address is what Chronicle believes the visitor's address is.
Address string
// Direct is the connection's own address.
Direct string
DirectTrusted bool
// RealIP and ForwardedFor are the raw header values received.
RealIP, ForwardedFor string
// HeaderMissing is true when the header the mode relies on is absent or
// unreadable on this request (never true for the direct mode).
HeaderMissing bool
}
ClientIPDiagnosis describes how one request was read, for the admin's Visitor addresses check.
func DiagnoseClientIP ¶
func DiagnoseClientIP(req *http.Request) ClientIPDiagnosis
DiagnoseClientIP reads req the way the extractor does and reports the inputs.