Shipping15 min read

Security

What collage does against request forgery, open redirects, path tricks, cache leaks and oversized bodies — and what is left to you.

A bug in a framework is a bug in every site built on it, so collage does the security work that every site would otherwise have to remember.

This page gathers what it does for you, in one place, with a link to where each part is explained. What it does not do is at the end.

Every request meets collage's checks in the same order, and each one can answer before what comes after it runs:

A request first gets the security headers, then its path is cleaned: a dirty path is redirected, an encoded slash is a 404 and a malformed escape a 400. A path mounted with plain app.Handle is then yours alone, and no middleware runs for it. Everything else meets the middleware, yours and the plugins'. A page, its actions and its fragment paths meet the page's guards before the cache; a guard's own answer is no-store. A page is served from the cache or rendered with a key that holds no cookie, and goes out private, no-cache if it is guarded. A fragment path is an action answering GET, never cached. An action meets the body limit, answering 413, then the origin and the token, answering 403 for an unsafe method, then your handler. In production any error page shows only the status.requestsecurity headersevery responsepath cleanedredirect404 · 400middlewareyours and plugins'app.Handleall yoursguards, before cachepage, actions, fragment pathsguard's answerno-storepageactioncache or renderkey holds no cookieif guardedprivate, no-cachebody limit413 · too largeorigin, then token403 · unsafe methodsyour handlerany error, in productionstatus only: no text, no stackcollageyours
collage's own steps are outlined, and what is yours is filled. Every request gets the security headers and a clean path before any middleware runs. A path mounted with plain app.Handle is then yours alone: no middleware, no guard, no forgery check, no body limit and no cache. Everything else meets the middleware, yours and the plugins'. A page, its actions and its fragment paths meet the page's guards before the cache. An action then meets the body limit (the body is bounded before any middleware runs; an action whose body is too large is refused here), then the origin and the token, before your handler; a fragment path is an action answering GET, and is never cached. In production, an error page shows the status and nothing else.

Forms cannot be forged

Every action with an unsafe method checks a signed token before its handler runs, and a page with {{csrfToken}} is still cached: each reader is sent their own token.

The token is not checked alone. A submission the browser marks as coming from another origin — Sec-Fetch-Site, or Origin against Host — is refused whatever it carries, sibling subdomains included, so a planted cookie is no way in. An origin meant to post here is named in Security.CSRFTrustedOrigins. See Forms and actions.

Set Security.CSRFKey before deploying: a generated key differs in every process, so after a restart, or on another instance behind a load balancer, every form already on a reader's screen is refused.

A token carries the time it was issued, signed, and is refused once it is older than Security.CSRFTokenTTL — twelve hours by default, so a leaked token cannot be replayed forever.

A reader with a long-open form is sent a fresh token rather than refused; set CSRFTokenTTL negative to keep a token valid for as long as its signature.

The token in a form is masked anew in every response: XORed with a fresh random pad and prefixed ~. A compressed response that reflects what a request sent is shorter when the reflection matches part of the token, and an attacker who can make a reader's browser send requests could read the token from those lengths (BREACH). Masked, it is different bytes every time. The check takes the mask off, from the form and the header, and still accepts an unmasked token.

A token that cannot be issued fails the response with a 500 rather than serving the page with the token's placeholder in its form.

GET and HEAD carry no token, by design, so an action answering only those is a change any site can make a reader's browser trigger with a link or an <img>. Registering one logs a warning in development, and HEAD does not fall back to a GET action: it is a 405 unless the action declares it. See Forms and actions.

Redirects stay on the site

No redirect collage writes can send a reader to another site:

  • The redirect that sends /a/./b or /a//b to its clean spelling writes the path escaped, so /./%5Cevil.com goes to /%5Cevil.com, not to /\evil.com, which a browser reads as //evil.com.
  • Locale and trailing-slash redirects never begin with //.
  • A registered redirect to //host or /\host is refused at registration, and a value it captured is escaped for where it lands — in the path, or as one query value, so /login?next={slug} cannot be handed a second next.

An action's Location and a guard's are yours: collage writes them as you set them, so do not build one from the request without checking it. Some must leave the site (a sign-in provider's page), which is why collage does not check them.

For a next taken from the URL, collage offers its own check:

loc := collage.SafeRedirect(rc.Request.URL.Query().Get("next"), "/")

SafeRedirect returns next when it is a path on this site — it starts with /, not with //, holds no backslash and no control character, and still starts with a single / once cleaned — and the fallback otherwise (/ when the fallback is not one either).

The cleaning matters because http.Redirect cleans a rooted path: /./\evil.example would leave as /\evil.example, which a browser reads as //evil.example. An absolute URL is never accepted, even one on this site's own origin.

A path means one thing

Middleware reads the decoded r.URL.Path; the router reads the escaped one. Where the two could disagree, the request reaches nothing:

  • A path with dot segments or doubled slashes is redirected to its clean spelling before middleware runs, so a check on /admin/ never meets /x/../admin.
  • A path holding an encoded slash, %2F, is a 404. %2F is not a separator, but a middleware reads the decoded path, where /public%2Fsecret is /public/secret: two segments to the middleware, one to the router.
  • A malformed escape is a 400, not a 500.
  • An action's or a document's other trailing-slash spelling is redirected to its one spelling — 308 for an action, 301 for a document, as for a page — and never served. The redirect comes after your middleware, which sees the path as it arrived, so compare the canonical path (or trim the slash) in a check on an exact path, or POST /admin/delete/ is judged as a path you did not write. A prefix such as /admin/ has no such gap. See Middleware and your own API.

These refusals are not invisible. They are timed, traced and counted like any other request, under a bounded label rather than the scanner's path: collage.RouteInfo reports the kind "rejected" and the name "normalise", and Metrics.HTTPResponse and the request span get no path. A dashboard or a ban plugin sees the probing without one time series per probe.

See Paths are cleaned first.

Private pages stay private

A guard runs before the cache is read, for the page's renders, the actions on its URL and its fragment paths.

A guarded page goes out private, no-cache, and a guard's own answer no-store, so a CDN never hands one reader's page or refusal to the next. A static export does not write guarded pages at all.

A fragment a plugin pushes over a stream is held to the same: it is rendered as a request to the fragment's own URL, which passes your middleware and the plugins' for that path, then the guards, which read that URL's parameters, never the stream's. A basicauth on /admin/ keeps /admin/stats out of a live stream, and a reader the middleware or a guard now refuses is sent nothing.

Plugins reach what HTTP reaches

A plugin is trusted code, but its Host keeps the promises its documentation makes:

  • A pushed fragment is a request.RenderFragment runs the middleware, the guards and every PersonaliseHook — a CSP nonce, a honeypot marker — and carries none of the caller's context values. A Shared render is made once per change and handed only to readers their middleware and guards admitted.
  • Configuration ends with Configure. A kept ConfigHost adds no template function and wraps no mount afterwards (ErrConfigureClosed), where a late render function would crash the process.
  • A plugin cannot take a name of the template language.html, js, urlquery, eq and the rest are refused, so no plugin's html stands in for html/template's escaping; and the application's Config.Template.Funcs win over every plugin's function.
  • A host carries only its own plugin's configuration, and Host.Pages hands out copies of every container a page holds, so a plugin cannot read another's section or change the cache key through its copy.
  • A plugin's Host.Handle body is bounded at Server.MaxBodyBytes before the middleware, as a page's is.
  • Every OnCacheInvalidate runs, so one failing plugin cannot keep a CDN purge from happening, and PersonaliseEvent.Personal is sticky: once a hook set it, a nonce'd body is never answered as public or with a 304.
  • Command names are one shell word, and none is the dispatcher's or, for a plugin, the collage binary's own.

See Writing a plugin.

A cached page is nobody's in particular

A render stored in the cache is served to every reader whose request has its key, so it is handed only what the key holds:

  • the path and the host;
  • the query parameters in the key;
  • the headers declared with collage.Vary.

It is never handed a reader's cookies, credentials or address. The host is in the key, so a request naming another host cannot poison the copy everyone else gets. It is normalised — lower-case, no port, no trailing dot — so EXAMPLE.com:8080 and example.com share one entry, and a client varying the spelling of Host cannot push the pages everyone reads out of a bounded cache. A cacheable page builds absolute URLs from collage.BaseURL(rc), not from the port in r.Host, which it no longer sees.

A degraded render, an error page and a page in development are never publicly cacheable. Nor is a response that carries a Set-Cookie when its cache headers are written — a session refresh a middleware set, say: it is sent Cache-Control: private, no-store, so a CDN cannot replay one reader's cookie to the next. The page is still cached on the server. A request over TLS and a plain one for the same URL are separate entries. See What a shared render sees.

Bodies are bounded

A request body is limited — 4 MiB unless you say otherwise — before your middleware runs, at the limit of the action it routes to, also when there is no middleware, so a page's or an action's guard reads it bounded. A body that says it is larger is refused before the handler runs. A urlencoded form past net/http's own 10 MB is a 413 however high the limit is, not a 403.

Multipart files spilled to disk are removed when the request has been answered, whoever parsed the form, and a cookie the forgery check never signed is refused before the body is read at all. See Request bodies are bounded.

Files are what they say they are

An asset mount types a file by its extension. One whose name says nothing is typed from its content, so an extensionless image upload is still an image.

It is never typed into a type that runs: one that looks like HTML or XML is text/plain, and with nosniff the browser keeps to that, so an extensionless upload holding markup is not served as a page.

A file with an extension is served as its extension says, by design: a static site's .html and .svg are pages and images. So never mount a folder of files your visitors uploaded with a plain Mount: an .html or .svg there runs its script as your site. Mount it with collage.WithAttachments() — .html, .xhtml, .svg and .xml are then sent with Content-Disposition: attachment, so a browser saves them instead of running them — or control the extensions you store. elagoht/uploads checks each file by its content and serves it so that it cannot.

A mount never lists a directory, and never serves or exports a dotfile — .env, .git/ — except .well-known. collage serve does the same.

Errors say nothing in production

In production, collage's own error page shows the status and nothing else: no error text, no stack, no path.

The development overlay and the reload channel exist only in development, and collage dev answers only a Host naming this machine, so a page on another site cannot read them through DNS rebinding.

A request path in a log line is quoted when it holds a control character, so it cannot forge a line or rewrite your terminal.

Security headers

Every response carries X-Content-Type-Options: nosniff and X-Frame-Options: SAMEORIGIN by default, so a site has MIME-sniff and clickjacking protection on its forms without adding anything.

Security.FrameOptions sets the value — "-" sends none, anything else is sent verbatim — and Security.DisableNoSniff turns nosniff off.

A full Content-Security-Policy, HSTS and the rest are what the elagoht/secure plugin adds, and its headers override these; a production page carries no framework script, so a strict policy needs no nonce.

What is left to you

  • A Go toolchain with the security fixes. A program carries the standard library it was built with. collage requires Go 1.26.11, so with the default GOTOOLCHAIN=auto the go command fetches it for a build that would have used an older Go. Check a binary with go version -m. Go 1.26.11 fixes GO-2026-6859, a race in http.MaxBytesReader that can crash an HTTP/1 server and that collage's body limit is built on; Go 1.26.10 rejected the compromised eMudhra intermediate certificates (CVE-2026-111943).

  • TLS, at a proxy that passes X-Forwarded-Proto and the browser's Host on. See Deployment. Set Server.TrustedProxies: without it X-Forwarded-Proto is believed from anyone, so a client reaching the server directly can claim the TLS connection it does not have.

  • Where your own redirects go. An action's or a guard's Location is written as you set it; check a next from the URL with collage.SafeRedirect.

  • What you mount. A plain Mount serves .html and .svg as they are; keep untrusted uploads out of one (see above).

  • Rate limits — elagoht/ratelimit. It, and elagoht/fail2ban, count an IPv6 client as its /64 by default; one holder of a /48 has 65536 of those, so set ipv6Prefix to 48 when such clients are what you face.

  • Sign-in state before sign-in.elagoht/oauth keeps a pending sign-in in a short collage_oauth cookie of its own, and starts a session only at a successful callback, so an anonymous visit to the login route hands out no session that turns the page cache off.

  • A handler mounted with app.Handle is your own: no forgery check, no body limit, no cache, and no middleware — no plugin's authentication, rate limit, ban or access log covers it unless it is mounted collage.WithMiddleware(). See No middleware, unless you ask.

  • What a data handler reads. On a cacheable page, a value middleware put in the request context is hidden from the shared render, so one reader's cannot reach another's page; declare it with collage.Vary and read it with collage.Varied.

  • A layout's {{hoist}} area names.{{hoist "head"}} takes a name made of letters, digits, _ and - and refuses anything else, so {{hoist .Area}} cannot be turned into markup. Still, write the area as a literal.

Fixes and reporting

pkg/collage and pkg/collagetest follow semantic versioning from v1.0.0. A security fix ships as a patch release on the latest v1 minor, and its CHANGELOG entry, under Security, says what was affected. There are no backports to an older minor, so the way to receive a fix is to upgrade to the latest v1 release, which never breaks an application.

To report a vulnerability, use GitHub's private reporting — the Report a vulnerability button on the Security tab of the collage repository — and not a public issue, pull request or discussion. Say which version you tested, what an attacker can do, and the smallest request or program that shows it. A handler mounted with app.Handle is your own, so what it does is not a collage vulnerability; a way for a request to reach it that should not is.

Example: a team's task list, before it goes live

The team task list from Middleware and your own API and Forms and actions is about to go live:

  • every member signs in, and has a role: an admin may change any task of the team, a member only the tasks assigned to them;
  • the team's list is a page at /teams/{team}/tasks, with an "add a task" form;
  • a JSON API for the team's command-line tool is mounted with app.Handle, WithMiddleware().

Each risk below is covered by collage, by a plugin the application adds, or by the application itself:

Riskcollage, built inPluginStill the app's job
Another site posts the "add a task" formOrigin, then token, on every action with an unsafe method—{{csrfToken}} in the form; Security.CSRFKey set
Who is signed in—elagoht/session: a signed cookie, HttpOnly, SameSite=Lax, encrypted with EncryptThe login action; Regenerate when a reader signs in
A signed-out reader on the listGuards run before the cache, for the page, its actions and its fragment pathssession.RequireUser("/login") as the guardPutting the guarded layout on every private page
A member changing another member's task, or another team's——The role and team check, where the data is: a guard such as requireRole, and the action and the API
next after sign-in sends the reader off the sitecollage.SafeRedirectRequireUser puts next in the URLPassing next through SafeRedirect
/x/../admin slipping past a path checkPath cleaned before middleware——
One member's page served to anotherA guarded page is private, no-cache; the cache key holds no cookieelagoht/session: a request with a session is rendered fresh, private, no-store—
A huge upload4 MiB per action by default; WithMaxBodyBytes—The API's own bound: http.MaxBytesReader
Password guessing on /login—elagoht/ratelimit: a /login ruleServer.TrustedProxies behind a proxy; buckets are per process
Bots filling a form—elagoht/honeypot: {{honeypot}}, checked after the forgery check, before the handlerPairing it with elagoht/ratelimit
Injected scripts, framing, plain HTTPnosniff; X-Frame-Options: SAMEORIGINelagoht/secure: a CSP with a nonce, HSTSThe policy itself; TLS at the proxy
An error showing a database addressThe production error page shows the status alone—The error text the API writes itself
A stolen session cookie—elagoht/session: a session cannot be revoked, it lives in the cookieA short maxAge or idleTimeout

The plugins go in Config.Plugins: elagoht/secure and elagoht/honeypot add template functions ({{cspNonce}}, {{honeypot}}). A plugin's key is read from an environment variable — SESSION_KEY, SECURE_KEY, HONEYPOT_KEY, or another its KeyEnv names — never from plugins-config.json:

app, err := collage.New(&collage.Config{
	Server: collage.ServerConfig{
		// The proxy that ends TLS, so ClientIP and IsHTTPS believe it.
		TrustedProxies: []string{"10.0.1.10"},
	},
	Security: collage.SecurityConfig{
		CSRFKey: []byte(os.Getenv("COLLAGE_CSRF_KEY")),
	},
	Plugins: []collage.Plugin{
		session.New(session.Options{Encrypt: true}),
		secure.New(secure.Options{
			CSP: "default-src 'self'; script-src 'self' 'nonce-{nonce}'",
		}),
		ratelimit.New(ratelimit.Options{Rules: []ratelimit.Rule{
			{PathPrefix: "/login", Rate: 0.1, Burst: 5},
			{Rate: 0.5, Burst: 10},
		}}),
		honeypot.New(honeypot.Options{}),
	},
})

The second rule has no path and no methods, so it counts every method but GET, HEAD and OPTIONS everywhere outside its skip list — the API's PATCH too, since the API is mounted WithMiddleware(). A plain app.Handle mount runs no middleware, so neither this rate limit nor any other plugin's middleware would cover it.

The roles stay the application's. The guard that lets only admins through is the requireRole of Example: a blog with a private area, and the API checks the team and the assignee itself, as The API, mounted as it is shows: collage says nothing about who may change what.