4 Error Pages: How Templating & Injection Work
vBlackOut edited this page 2026-08-26 07:48:04 +02:00

Error Pages: How Templating & Injection Work

This page explains how ProxyAuth renders error pages (invalid login, expired session, missing 2FA code, etc.) — specifically render_error_page() in network/error.rs — and the HTML template placeholders it looks for. This is separate from a generic backend 5xx: it's what happens when ProxyAuth itself rejects a login attempt and wants to show the user a friendly page instead of a bare JSON error.


Why this exists

/auth normally either succeeds (returns a token/sets a cookie) or fails with a plain error response. But when session_cookie is enabled (browser-based login flow), a bare 401 Unauthorized with no styling is a poor experience for a real login page. Instead, ProxyAuth:

  1. Resolves the page to show — the route matching logout_redirect_url's path and the current request's vhost (so a multi-vhost instance can't accidentally show one vhost's login page while annotating another's — see routes.yml Reference § How a route is matched).
  2. Gets that page's content one of two ways, depending on how the resolved route is configured:
    • Purely static (a static/static_index route with no backend target) — reads the file straight off disk. No network request at all.
    • Proxied (a route with a target/backends) — fetches the page from the backend, the same way a normal visit to it would.
  3. Rewrites a specific <!-- BEGIN_BLOCK_ERROR --> ... <!-- END_BLOCK_ERROR --> comment block inside that HTML to show the error message.
  4. Re-injects a fresh CSRF token into the page if it contains a {{ csrf_token }} placeholder.
  5. If the resolved route has tag_proxyauth: true, also substitutes {{ username }}, {{ proxyauth_version }}, and {{ proxyauth_id }} — see Dynamic Tags in Pages for what these resolve to; this page covers {{ error }}/{{ csrf_token }} specifically, since those two are always available here regardless of tag_proxyauth.
  6. Returns the modified page to the user — with the original response's compression (gzip/deflate/br) re-applied, for the proxied case (the static case has no compression to preserve, since ProxyAuth reads the file raw off disk).

This only triggers when there's something to show the user on the same page they're already on — it requires logout_redirect_url to be configured (used here as "the page to annotate with the error"), and is used for login-flow errors specifically (bad password, expired session, missing/invalid TOTP code, invalid CSRF, vhost login authorization denied). It's not a generic 4xx/5xx handler.


The two placeholders

Your backend's HTML (the page served at logout_redirect_url) can use two independent placeholders, described below. Neither is required — if your page doesn't include them, render_error_page() still returns the page unmodified except for whatever it can apply.

1. <!-- BEGIN_BLOCK_ERROR --> ... <!-- END_BLOCK_ERROR --> — the error message block

Wrap the part of your page that should only be visible when there's an error, as an HTML comment, with {{ error }} where the message itself should appear:

<!-- BEGIN_BLOCK_ERROR -->
<!--
<div class="error-banner">
  {{ error }}
</div>
-->
<!-- END_BLOCK_ERROR -->

When ProxyAuth needs to show an error, it:

  1. Finds the content between the two markers.
  2. Strips the <!--/--> comment delimiters inside that block (uncommenting it).
  3. Replaces {{ error }} with the actual message.
  4. Splices the result back into the page.

So the example above becomes, in the response actually sent to the browser:

<!-- BEGIN_BLOCK_ERROR -->
<div class="error-banner">
  Invalid credentials
</div>
<!-- END_BLOCK_ERROR -->

Why comment it out in the source HTML at all? So that on a normal (non-error) page load — served directly by your backend, without going through this rewriting — the error banner markup exists in the page (for consistent styling/testing) but stays inert as a comment, invisible to users, instead of an empty <div> flashing on every page load.

If your page doesn't have both markers, or the error message is empty, the HTML is returned untouched — this step is a no-op.

2. {{ csrf_token }} (or {{csrf_token}}) — CSRF token injection

Anywhere in your HTML — not just inside the error block — put:

<form method="POST" action="/auth">
  <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
  <!-- ... username/password fields ... -->
</form>

Both {{ csrf_token }} (with spaces) and {{csrf_token}} (without) are recognized. Every occurrence is replaced with a freshly generated, signed CSRF token.

This only happens if both session_cookie and CSRF itself are enabled for the resolved route's vhost — tag_csrf_token if it sets one, otherwise the global csrf_token in config.json (see the config.json Reference and routes.yml Reference § Per-vhost behavior overrides). If either is off, the placeholder is left as-is in the page (so don't rely on it being replaced unless both are on).

This is the same underlying token mechanism used to validate the CSRF nonce on the next /auth submission — see config.json Reference for the global csrf_token/need_csrf, and routes.yml Reference for the per-vhost tag_csrf_token override.


Full flow

flowchart TD
    A(["Login fails<br/>bad password · expired session · bad TOTP · bad CSRF · vhost login denied"]) --> B["render_error_page(request, app_state, message)"]
    B --> C["1. Resolve the route<br/>logout_redirect_url's path, matched to the current request's vhost"]
    C --> D{"Static, or proxied?"}
    D -->|"static/static_index, no target"| E1["2a. Read the file off disk<br/>no network request at all"]
    D -->|"target/backends configured"| E2["2b. GET the page from the backend<br/>forwarding Cookie · Origin · Accept-Language · User-Agent"]
    E2 --> E3["Decompress the response<br/>if gzip / deflate / br encoded"]
    E1 --> F["3. Toggle BEGIN_BLOCK_ERROR<br/>filling in the error placeholder"]
    E3 --> F
    F --> G["4. Inject a fresh CSRF token<br/>if session_cookie + csrf_token are both on"]
    G --> G2{"tag_proxyauth: true<br/>on this route?"}
    G2 -->|yes| G3["5. Also substitute username /<br/>proxyauth_version / proxyauth_id"]
    G2 -->|no| H
    G3 --> H(["6. Re-compress if proxied, set no-cache headers<br/>return as 401 Unauthorized"])

    classDef step fill:#f8fafc,stroke:#64748b,stroke-width:1px,color:#0f172a
    classDef edge fill:#eef2ff,stroke:#4f46e5,stroke-width:1px,color:#1e1b4b
    classDef branch fill:#fefce8,stroke:#ca8a04,stroke-width:1px,color:#422006
    class A,H edge
    class B,C,E1,E2,E3,F,G,G3 step
    class D,G2 branch

The response is always sent with Cache-Control: no-store, no-cache, must-revalidate, max-age=0 — an error page must never be cached and silently re-shown on a later, unrelated request.


Where this is triggered from

Every one of these login-flow failures in token/auth.rs renders the error page this way, so all of them can appear inside your {{ error }} block:

Situation Message shown
CSRF token missing/invalid on submission invalid csrf request
Session cookie present but expired Session expired, please re-authenticate
Session cookie present but invalid/revoked Invalid credential, please re-authenticate
User's IP not in their allow list Access denied
Username doesn't satisfy this vhost's allow_users/allow_groups/allow_roles, or is in exclude_users — see routes.yml Reference § Vhost login authorization Access denied
login_via_otp is on, but no TOTP code submitted Missing TOTP code
login_via_otp is on, but the user has no enrolled otpkey Missing TOTP secret
The user's stored TOTP secret is malformed (corrupted config) Internal TOTP error
TOTP code submitted but incorrect Invalid TOTP code
Username/password combination incorrect Invalid credentials

These are fixed, English-language strings baked into the binary — there's currently no per-language/i18n mechanism, so if you need localized messages you'd need to translate {{ error }}'s content client-side (e.g. with JS mapping known message strings to translations) rather than expecting ProxyAuth to localize them itself.


Practical example

A minimal login page compatible with both placeholders:

<!DOCTYPE html>
<html>
<head><title>Sign in</title></head>
<body>
  <!-- BEGIN_BLOCK_ERROR -->
  <!--
  <p style="color:red">{{ error }}</p>
  -->
  <!-- END_BLOCK_ERROR -->

  <form method="POST" action="/auth">
    <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Sign in</button>
  </form>
</body>
</html>
  • On a normal page load (served directly by your backend, not through ProxyAuth's error path), the <p> stays a harmless HTML comment, and {{ csrf_token }} is whatever your own backend put there (or left as literal text, if your backend doesn't handle it itself — in which case the first real value the user sees only appears after ProxyAuth injects it on the way through, if session_cookie/CSRF (tag_csrf_token or the global csrf_token) are on for that route).
  • On a failed login, ProxyAuth serves the same page with the comment uncommented and filled in, and a fresh CSRF token spliced into the hidden field.

Things to know

  • logout_redirect_url must be set and must match a route in routes.yml, for the current vhost, for this to work at all — if no route matches both the path and the vhost, render_error_page returns a plain 400 Bad Request instead of a rendered page.
  • Route matching is vhost-aware, using the same longest-prefix-first ordering every proxied request goes through (see routes.yml Reference § How a route is matched) — on a multi-vhost instance where more than one vhost has a route at the same path (most commonly /), this correctly picks the current request's own vhost rather than whichever route happens to be listed first in routes.yml.
  • For a static route (static/static_index, no target): the file is read directly off disk — no timeout, no backend status code to worry about, and no compression to preserve (ProxyAuth reads and serves it raw). A file that can't be read (permissions, doesn't exist) results in a plain 500 Internal Server Error.
  • For a proxied route: the fetch has a 500ms timeout (for routes without backends; routes with backends use the normal load-balancer failover/timeout behavior instead — see Load Balancing & Failover). If your backend is slow to respond, users could briefly see a generic Upstream timeout response instead of the styled error page. A 4xx/5xx from the backend while fetching the page results in a plain Backend status: <code> response — this whole mechanism assumes your login page itself is reliably reachable and returns 2xx.
  • Compression is preserved for the proxied case, not stripped — if your backend served the page gzip-compressed, the modified page is re-gzipped before being sent back, so intermediate caches/proxies relying on Content-Encoding keep working correctly. This is a mechanism of its own, separate from the compression middleware: it re-encodes with whatever the backend used, at the library default level, not with the compression block's algorithm/level. Because the result already carries a Content-Encoding, the middleware skips it — the two never collide.

See also

  • config.json Reference — session_cookie, csrf_token, logout_redirect_url.
  • routes.yml Reference — how logout_redirect_url's path is matched to a backend.
  • Load Balancing & Failover — applies when the matched route has backends configured.
  • Dynamic Tags in Pages — {{ username }}/{{ proxyauth_version }}/{{ proxyauth_id }}, the broader tag_proxyauth-gated substitution that also applies here, and to static files and proxied responses generally.