Server Proxy — Unified Caddy Reverse Proxy
Purpose
The Proxy submodule provides a unified interface for exposing internal services through Caddy. It handles virtual host configuration, automatic SSL via ACME, OAuth2 authentication with Kanidm, static API key authentication, and public exposure through Cloudflared tunnels. It abstracts the complexity of reverse proxying by allowing services to define their proxy requirements within their own module configuration, automatically coordinating between backend hosts and the primary IO host to ensure ports are open and traffic is correctly routed.
Entry Point
- Main file:
modules/nixos/server/proxy/default.nix - Supporting file:
modules/nixos/server/proxy/options.nix - Supporting file:
modules/nixos/server/proxy/config.nix - Supporting file:
modules/nixos/server/proxy/kanidm.nix - Supporting file:
modules/nixos/server/proxy/extensions.nix - Supporting file:
modules/nixos/server/proxy/extensions/l4.nix
Options
server.proxy.extensions
| Type | attribute set of (submodule) |
| Default | { } |
Registry of proxy extensions. Each extension provides config functions that are injected into vhost Caddy blocks, sorted by priority.
server.proxy.extensions.<name>.config
| Type | function that evaluates to a(n) function that evaluates to a(n) function that evaluates to a(n) string |
Function: vhostName -> vhostAttrSet -> hostConfig -> string. Returns Caddy directives to inject, or ‘’ for no-op. The vhostAttrSet includes the resolved extraConfig (already localhost-replaced) as _resolvedExtraConfig.
server.proxy.extensions.<name>.consumesExtraConfig
| Type | boolean |
| Default | false |
Whether this extension embeds extraConfig inside its output. When true, config.nix skips the post-extension extraConfig append for this vhost.
server.proxy.extensions.<name>.enable
| Type | boolean |
| Default | false |
Whether this extension is globally enabled.
Each extension SHOULD auto-detect whether it has work to do and set this to true via mkDefault in its module config.
User can explicitly override to force-disable (higher merge priority than mkDefault).
server.proxy.extensions.<name>.globalConfig
| Type | function that evaluates to a(n) string |
| Default | <function> |
Function: hostConfig -> string. Returns Caddy directives to inject into the top-level globalConfig block. Only called on the IO primary host. Sorted by priority across extensions.
server.proxy.extensions.<name>.priority
| Type | signed integer |
| Default | 100 |
Lower values = earlier in Caddy config. Priority ranges: 0-49 reserved, 50-99 auth, 100-199 general, 200+ post-processing.
server.proxy.extensions.<name>.vhostModule
| Type | null or module |
| Default | null |
Optional module to inject into each vhost submodule. Use options.<extensionName> (relative to vhost scope) to declare per-vhost options.
server.proxy.kanidmContexts
| Type | attribute set of (submodule) |
| Default | { } |
Shared Kanidm OAuth2 context configurations.
server.proxy.kanidmContexts.<name>.allowGroups
| Type | list of string |
| Default | [ ] |
| Example | [ "idm_all_persons@auth.racci.dev" "admins@auth.racci.dev" ] |
Default list of Kanidm groups allowed to access virtualHosts using this context.
server.proxy.kanidmContexts.<name>.authDomain
| Type | null or string |
| Default | null |
| Example | "auth.example.com" |
The domain where Kanidm is hosted. Defaults to auth.<data.site.domain> if not specified.
server.proxy.kanidmContexts.<name>.cookieDomain
| Type | null or string |
| Default | null |
| Example | "example.com" |
Cookie domain for the portal session cookies. When set, the cookie is shared by every host under this domain, which is what makes authentication carry across those hosts. A leading dot is accepted and stripped by the plugin.
server.proxy.kanidmContexts.<name>.scopes
| Type | list of string |
| Default | [ "openid" "email" "profile" "groups" ] |
OAuth scopes to request from Kanidm.
server.proxy.kanidmContexts.<name>.sharedPortal
| Type | boolean |
| Default | false |
Serve one authentication portal for every virtual host using this context.
A single portal means a single session, so a login on one host is valid on the others once they share cookieDomain.
server.proxy.kanidmContexts.<name>.tokenLifetime
| Type | signed integer |
| Default | 3600 |
Token lifetime in seconds for the authentication portal.
server.proxy.kanidmPortalCss
| Type | null or absolute path |
| Default | /nix/store/z8pavkbghx2fcr1ksmy8pzv8d39r1gxm-source/modules/nixos/server/proxy/portal.css |
Stylesheet applied to every Kanidm authentication portal. Defaults to the dark theme shipped with this module. Set to null to use the plugin’s own styling.
server.proxy.virtualHosts
| Type | attribute set of (submodule) |
| Default | { } |
Virtual hosts to be handled by the IO server and forwarded to the respective backend.
server.proxy.virtualHosts.<name>.aliases
| Type | list of string |
| Default | [ ] |
A list of virtual host names that should be routed using this configuration.
Options added here will inherit the base domain from data.site.domain.
server.proxy.virtualHosts.<name>.baseUrl
| Type | string |
| Default | ${subdomain}.${self.data.site.domain} |
The base url including the configured base domain name.
server.proxy.virtualHosts.<name>.extensions
| Type | null or (list of string) |
| Default | null |
List of extension names to enable for this virtual host. When null (default), all globally enabled extensions apply. When set to a list, only those named extensions apply. Set to [] to disable all extensions for this vhost.
server.proxy.virtualHosts.<name>.extraConfig
| Type | string |
| Default | "" |
Configuration to be placed in the caddy virtualHost extraConfig.
server.proxy.virtualHosts.<name>.kanidm
| Type | null or (submodule) |
| Default | null |
Enable Kanidm OAuth2 authentication for this virtual host.
server.proxy.virtualHosts.<name>.kanidm.allowGroups
| Type | list of string |
| Default | [ ] |
| Example | [ "idm_all_persons@auth.racci.dev" "admins@auth.racci.dev" ] |
Default list of Kanidm groups allowed to access virtualHosts using this context.
server.proxy.virtualHosts.<name>.kanidm.authDomain
| Type | null or string |
| Default | null |
| Example | "auth.example.com" |
The domain where Kanidm is hosted. Defaults to auth.<data.site.domain> if not specified.
server.proxy.virtualHosts.<name>.kanidm.bypassPaths
| Type | list of string |
| Default | [ ] |
| Example | [ "/health" "/api/webhooks/*" ] |
List of path patterns that never require authentication.
server.proxy.virtualHosts.<name>.kanidm.context
| Type | string |
| Default | "‹name›" |
The OAuth context name for this virtual host.
server.proxy.virtualHosts.<name>.kanidm.logoutPath
| Type | null or string |
| Default | null |
| Example | "/logout" |
Path that signs the user out instead of being proxied. It clears the proxy cookies and ends the Kanidm session, so the next request cannot be silently re-authenticated.
server.proxy.virtualHosts.<name>.kanidm.protectedPaths
| Type | list of string |
| Default | [ ] |
| Example | [ "/ui/*" ] |
Path patterns that require authentication.
When empty, the whole host requires authentication.
When set, only matching paths do and every other path is served
without authentication, which keeps machine endpoints reachable.
bypassPaths still takes precedence for the paths it lists.
server.proxy.virtualHosts.<name>.kanidm.scopes
| Type | list of string |
| Default | [ "openid" "email" "profile" "groups" ] |
OAuth scopes to request from Kanidm.
server.proxy.virtualHosts.<name>.kanidm.tokenLifetime
| Type | signed integer |
| Default | 3600 |
Token lifetime in seconds for the authentication portal.
server.proxy.virtualHosts.<name>.l4
| Type | null or (submodule) |
| Default | null |
This option has no description.
server.proxy.virtualHosts.<name>.l4.config
| Type | string |
| Default | "" |
Configuration for the L4 plugin.
server.proxy.virtualHosts.<name>.l4.listenPort
| Type | 16 bit unsigned integer; between 0 and 65535 (both inclusive) |
Port to listen on for L4 traffic.
server.proxy.virtualHosts.<name>.l4.protocol
| Type | one of "tcp", "udp" |
| Default | "tcp" |
Protocol for L4 listener.
server.proxy.virtualHosts.<name>.listenPorts
| Type | non-empty (list of 16 bit unsigned integer; between 0 and 65535 (both inclusive)) |
| Default | [ 443 ] |
Port(s) to listen on for incoming traffic for this virtual host. If multiple ports are specified, the virtual host will be accessible on all of them.
server.proxy.virtualHosts.<name>.ports
| Type | list of 16 bit unsigned integer; between 0 and 65535 (both inclusive) |
| Default | [ ] |
Ports to be opened from the host for IO Hosts to forward traffic to.
server.proxy.virtualHosts.<name>.public
| Type | boolean |
| Default | false |
When enabled this service will be accessible to the public via Cloudflared Tunnels.
server.proxy.virtualHosts.<name>.requireApiKey
| Type | null or (submodule) |
| Default | null |
This option has no description.
server.proxy.virtualHosts.<name>.requireApiKey.bypassPaths
| Type | list of string |
| Default | [ ] |
| Example | [ "/health" "/api/webhooks/*" ] |
List of path patterns that bypass API key authentication.
server.proxy.virtualHosts.<name>.requireApiKey.enable
| Type | boolean |
| Default | false |
Enable API key authentication for this virtual host.
server.proxy.virtualHosts.<name>.useAcmeCerts
| Type | boolean |
| Default | true |
Whether to generate and use ACME certificates for this virtual host. If false, you must provide your own TLS configuration in extraConfig via the caddy tls directive.
Architecture / Services / Scope
File Layout
default.nix— Logic and helpers: resolving OAuth contexts and mapping local addresses to backend hostnames.options.nix— Option definitions for virtual hosts and shared contexts.config.nix— Caddy integration: generation ofservices.caddy.virtualHostsand ACME certificate requests. L4 (TCP/UDP) forwarding is handled by thel4extension, not byconfig.nix.kanidm.nix— Authentication security: generates the Caddysecurityblock, including identity providers, portals, and authorisation policies.extensions.nix— System integration: connects the proxy to the dashboard, Cloudflared tunnels, and automates Kanidm client provisioning.
Extension System
The proxy module supports a registry-based extension system. Extensions are self-contained modules that inject Caddy directives into virtual host configurations — without modifying proxy internals.
Extension Registry
Extensions register themselves via server.proxy.extensions.<name>, an attribute set of submodules.
Each extension has:
| Field | Type | Default | Description |
|---|---|---|---|
priority | int | 100 | Lower values = earlier Caddy config placement. Ranges: 0-49 reserved, 50-99 auth, 100-199 general, 200+ post-processing |
enable | bool | false | Globally enabled. Set via mkDefault based on detected config |
consumesExtraConfig | bool | false | When true, the extension embeds vh._resolvedExtraConfig in its output. config.nix skips appending raw extraConfig |
config | vhostName -> vhostAttrSet -> hostConfig -> str | required | Per-vhost Caddy directive generator |
globalConfig | hostConfig -> str | _ → "" | Top-level Caddy globalConfig directives |
vhostModule | nullOr deferredModule | null | Per-vhost option declarations |
Per-Vhost Extension Selection
Each vhost has server.proxy.virtualHosts.<name>.extensions (default null = all enabled extensions).
Set to a list of extension names for selective enablement, or [] to disable all extensions.
Config Function Signature
config :: vhostName -> vhostAttrSet -> hostConfig -> string
Arguments:
vhostName(str): The vhost’s attribute name (e.g.,"grafana").vhostAttrSet: The full vhost attribute set, including_resolvedExtraConfig(user’sextraConfigwithreplaceLocalHostapplied) and_name.hostConfig: Full host-level NixOS config.
GlobalConfig Function Signature
globalConfig :: hostConfig -> string
Called once per enabled extension on the IO primary host.
Output concatenated into services.caddy.globalConfig, sorted by extension priority.
Auto-Enable Pattern
Extensions auto-detect whether they have work to do using mkDefault; users can force-disable with explicit enable = false.
Priority Ordering
Extensions sort by priority ascending. Equal priorities break alphabetically by extension name. Extensions with lower priority numbers generate config earlier.
Authoring a New Extension
- Create file:
modules/nixos/server/proxy/extensions/<name>.nix - Import in
proxy/default.nix. - Set
server.proxy.extensions.<name>with priority, config function, etc. - Declare per-vhost options via
options.server.proxy.virtualHostswithattrsOf (submodule ...). - Use
proxyLibfor helpers:replaceLocalHost,resolveKanidmContext,hasAnyKanidm,portalName,sanitiseName.
API Key Auth Extension
The api-key-auth extension provides static API key authentication for virtual hosts.
When enabled, requests must include a valid Req-API-Key header matching a securely generated secret.
Bypass paths are supported per vhost.
Mutual exclusivity with Kanidm on the same vhost is enforced by the existing consumesExtraConfig assertion.
Migrated Extensions
| Extension | Priority | Purpose |
|---|---|---|
l4 | 10 | L4 TCP/UDP forwarding (layer4 Caddy block + firewall ports) |
kanidm | 50 | Kanidm OAuth2 authentication per vhost |
api-key-auth | 50 | Static API key authentication per vhost (with bypass paths) |
dashboard | 200 | Auto-generate dashboard items |
cloudflared | 200 | Cloudflared tunnel ingress |
Secrets
Kanidm OAuth2 Context
Authentication requires specific secrets per context, managed via sops-nix:
KANIDM/OAUTH2/<UPPER_CONTEXT>_SECRET: OAuth2 client secret. The Identity Coordinator uses it for Kanidm provisioning; the IO Coordinator uses the same value for Caddy.PROXY_AUTH/KANIDM/<UPPER_CONTEXT>_SHARED_KEY: Shared key used by Caddy to sign and verify authentication tokens.
On the IO Coordinator, the module renders PROXY_AUTH/KANIDM/<UPPER_CONTEXT>_ENV and loads it as a Caddy environment file with OAUTH_<UPPER_CONTEXT>_CLIENT_SECRET and <UPPER_CONTEXT>_SHARED_KEY.
The OAuth2 secret value must match between the Identity Coordinator and IO Coordinator hosts when they are separate.
Kanidm Session Sharing and Path Gating
By default each virtual host gets its own authentication portal and a host-only cookie,
so two hosts sharing one OAuth context still prompt twice.
Sharing a session is opt-in per context via server.proxy.kanidmContexts.<context>:
| Option | Default | Effect |
|---|---|---|
sharedPortal | false | One portal named <context>_portal for every vhost using the context, instead of one per vhost |
cookieDomain | null | Emits cookie domain <value>; required when sharedPortal is set. A leading dot is stripped. |
With both set, the session cookie is scoped to the parent domain and validated by one portal instance,
so a login on one host is accepted on the others. The cookie prefix is derived from the context name
(<UPPER_CONTEXT>_SESSION_ID, <UPPER_CONTEXT>_ACCESS_TOKEN), and the matching policy cookie names are emitted for every vhost in that context.
Enabling this renames cookies, so existing sessions are dropped once.
The policy points at the absolute OAuth2 endpoint of its own host, https://<host>/auth/oauth2/<context>,
which the plugin uses to build the provider callback and the post-login redirect.
Both /auth and /auth/* are matched with a handle so the portal resolves before the authorize handle,
and the authenticate handler declares that mount with at /auth,
which requires caddy-security v1.6 or newer.
allowGroups feeds two places: the allow groups lines of the Caddy policy, and the scope map of the
Kanidm OAuth2 client that the extension provisions for the context.
Each group in the resolved set gets a scope map entry carrying the context scopes,
with the domain stripped (sysadmin, not sysadmin@auth.racci.dev).
Groups may be declared on the context or on the virtual host; the union is used.
A context whose hosts resolve no groups fails an assertion, because Kanidm then issues no token at all
and every login ends on an Access Denied page.
Each portal also carries a transform user block that adds the authp/user role to the issued token.
The portal’s own access list only admits its reserved roles (authp/admin, authp/user, authp/guest),
while Kanidm sends group SPNs only. Without the transform the login succeeds, the access token is issued,
and the portal then rejects that token on the next request and deletes its cookie, which restarts the login.
This role is not an authorization decision: allowGroups on the policy is.
The portal only honours a post-login redirect_url that matches a declared trusted target.
Every host and alias of a virtual host using the portal gets one:
trust login redirect uri domain exact <host> path prefix /
Without it the login completes and the browser is sent to the plugin’s own page, /auth/portal,
instead of the page the user asked for. The plugin’s /auth/profile/ page is its own account UI and is
not backed by an OAuth2 provider; it answers oauth is not supported with profile API and is unused here.
Path gating uses server.proxy.virtualHosts.<name>.kanidm:
| Option | Default | Effect |
|---|---|---|
bypassPaths | [ ] | Paths that never require authentication |
protectedPaths | [ ] | Paths that require authentication; everything else is served unauthenticated |
An empty protectedPaths means the whole host requires authentication.
Both lists can be combined, and bypassPaths wins for the paths it lists.
Use protectedPaths for hosts that mix browser and machine traffic, such as a storage component
whose UI should be gated while its data plane stays reachable.
Signing Out
Applications behind the proxy have no session of their own, so a logout button in their UI does nothing.
logoutPath intercepts such a path instead of proxying it:
| Option | Default | Effect |
|---|---|---|
logoutPath | null | Path that clears the proxy cookies and ends the Kanidm session |
On that path the extension emits Set-Cookie deletions for <PREFIX>_ACCESS_TOKEN,
<PREFIX>_SESSION_ID and <PREFIX>_REDIRECT_URL, then redirects to
https://<authDomain>/ui/logout. Clearing only the proxy cookies is not enough: Kanidm would
authenticate the next request silently.
Kanidm ignores post-logout redirect parameters, so the browser ends on the Kanidm login page.
Portal Theme
Every portal emits a ui block that selects the basic theme and a stylesheet from
server.proxy.kanidmPortalCss:
| Option | Default | Effect |
|---|---|---|
kanidmPortalCss | the module’s portal.css | Stylesheet served with the portal; the default overrides the theme variables with a dark palette |
portal.css only overrides CSS variables (--brand-*) and color-scheme, so it keeps working
when the plugin changes its markup. Set the option to null to fall back to the plugin’s own colours.
The file is read from its store path at request time, so it needs no caddy adapt cycle.
API Key Auth
Secrets are auto-generated via sops at PROXY_AUTH/<VHOST_NAME>_API_KEY, injected via systemd LoadCredential.
Operational Notes / Assumptions
- Caddy Integration: The module assumes the existence of a
defaultCaddy snippet for common headers and security settings. Whenpublicis enabled, it also expects apublicsnippet. - Dashboard Integration: Services defined in
server.proxy.virtualHostsare automatically added to the server dashboard with default titles and icons derived from the host name. - Layer 4 Forwarding: L4 forwarding uses the
caddy.layer4plugin for non-HTTP traffic like database connections or SSH. Managed by thel4extension (modules/nixos/server/proxy/extensions/l4.nix), which auto-enables when any vhost hasl4 != null. - Kanidm Bootstrap Ordering: OAuth identity providers use delayed metadata discovery (
delay_startwith retries). This avoids startup deadlocks when the metadata endpoint is served through the same Caddy instance.