middleware

package
v0.0.0-...-95891f2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0 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 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

View Source
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.

View Source
const BuildHeaderName = "X-Chronicle-Build"

BuildHeaderName carries the running build's token on every response.

View Source
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.

View Source
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

View Source
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.

View Source
var LayoutInjector func(*echo.Context, context.Context) context.Context

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.

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

func BodyLimitFunc(limit func() int64, skip func(*echo.Context) bool) echo.MiddlewareFunc

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:

  1. On every request, if no CSRF cookie exists, generate one and set it.
  2. 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)
  3. 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 ClientIPHeader

func ClientIPHeader() string

ClientIPHeader returns the mode in force.

func GetCSRFToken

func GetCSRFToken(c *echo.Context) string

GetCSRFToken retrieves the CSRF token from the Echo context. Use this in Templ templates to inject the token into forms.

func HTMXRedirect

func HTMXRedirect(c *echo.Context, url string) error

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

func IsAPIRequest(c *echo.Context) bool

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

func IsClientIPMode(mode string) bool

IsClientIPMode reports whether mode is one of the four known values.

func IsHTMX

func IsHTMX(c *echo.Context) bool

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

func IsSameOriginFrame(c *echo.Context) bool

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

func MediaContext(c *echo.Context) context.Context

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

func ParseTrustedProxies(trustedCIDRs []string) ([]*net.IPNet, error)

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

func Render(c *echo.Context, statusCode int, component templ.Component) error

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

func ResponseState(c *echo.Context) *echo.Response

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

func SchemeIsSecure(req *http.Request) bool

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

func ServeAttachment(c *echo.Context, path, name string) error

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

func ServeFile(c *echo.Context, path string) error

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

func TrustedProxies(e *echo.Echo, trustedCIDRs []string) error

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.

Jump to

Keyboard shortcuts

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