# TinySesam forward-auth with Caddy.
#
# IMPORTANT (gotcha): Caddy's `forward_auth` shortcut only passes a 401 through and does NOT
# redirect to the login automatically. The redirect needs the expanded reverse_proxy form with
# handle_response, which evaluates the header X-TinySesam-Location set by the auth service.
#
# Upstreams come from the environment, so the same file is right on bare metal and in compose:
# without the variables set, 127.0.0.1 applies (services on the same host), `docker-compose.yml`
# sets the service names. In the Caddy CONTAINER 127.0.0.1 is the container itself — nothing
# listens on 8000 there, and a `docker compose up -d` would yield a stack that does not work.
#
# Prerequisite in TinySesamConfig:
#   forward_auth_enabled=True
#   base_url="https://auth.example.com"          # central login domain
#   cookie_domain=".example.com"                 # cookie applies to all subdomains (SSO)
#   trusted_redirect_hosts=["app.example.com"]   # allows next= back to the app
#   trusted_proxies=["<Caddy-IP>/32"]            # real client IP behind the proxy

# Central auth service (TinySesam) — its own subdomain
auth.example.com {
	# HSTS (ASVS 3.4.1): one year, also for subdomains OF THIS HOST — never for its siblings or the parent
	# domain. No `preload`: the browsers' preload list is hard to leave again. Caddy does not set it itself.
	header Strict-Transport-Security "max-age=31536000; includeSubDomains"
	reverse_proxy {$TS_AUTH_UPSTREAM:127.0.0.1:8000}
}

# Require roles (optional): add `header_up X-TinySesam-Roles editors,admin` to the
# sub-request — one of the named roles suffices. TinySesam then answers 403 instead of 200 when
# someone is signed in but lacks the role; without it /auth/forward stays binary.
# The header belongs in THIS file: `header_up` overwrites a same-named header of the
# client. (Even if it did not, a client would get nowhere with it — several values are
# AND-combined, so it could only tighten the check.)

# Protected app (can be any third-party app / static site)
app.example.com {
	header Strict-Transport-Security "max-age=31536000; includeSubDomains"   # HSTS, see above

	# ONLY this proxy sets the identity: every Remote-* the browser sends goes first, on every path. Below, each
	# header is set again only when TinySesam's answer carries it (T-58).
	request_header -Remote-User
	request_header -Remote-Name
	request_header -Remote-Email
	request_header -Remote-Groups
	request_header -Remote-Id
	request_header -Remote-Auth
	request_header -Remote-Kind
	# Nor a target the browser made up (F1): an X-Original-URL/-URI of its own reached the application, which
	# builds addresses or decides from it (measured in tests/test_gate_caddy.py).
	request_header -X-Original-URL
	request_header -X-Original-URI

	# Sign-out at the application (T-22): /.tinysesam/logout and /.tinysesam/after-logout belong to
	# TinySesam, not to the application — and bypass the gate: signing out must also work with an
	# expired sign-in. On this host, because only here can the gate cookie be deleted.
	# The application's sign-out link points to https://app.example.com/.tinysesam/logout
	# (?scope=app|all, otherwise forward_logout applies); register
	# https://app.example.com/.tinysesam/after-logout with the provider as Logout Callback URL.
	# The same prefix carries the top bar and the own account as data for the application's page
	# (T-76: /.tinysesam/topbar.json, T-91: /.tinysesam/account.json), with the browser's cookies.
	handle /.tinysesam/* {
		reverse_proxy {$TS_AUTH_UPSTREAM:127.0.0.1:8000}
	}

	# OAuth for MCP clients (T-36, optional): with oauth_enabled and this application's URL in
	# oauth_resources (e.g. https://app.example.com/mcp), an MCP client such as Claude Code finds the
	# authorization server here (RFC 9728) — TinySesam answers for the resource, the application has no
	# OAuth code. Harmless without OAuth: TinySesam answers 404.
	handle /.well-known/oauth-protected-resource* {
		reverse_proxy {$TS_AUTH_UPSTREAM:127.0.0.1:8000}
	}

	# Public paths of the application (T-20), such as share links: without sign-in, without identity.
	# TS_SHARE_PREFIX is a regular expression over the beginning of the path, e.g.
	#   TS_SHARE_PREFIX='^/(s|public/share)/'
	# Without the variable `^$` applies — it matches no path, the exception is off.
	#
	# The RAW path (`orig_uri.path`) is checked, not the one cleaned up by Caddy: otherwise Caddy
	# compares `/x/../s/a` as `/s/a`, but passes `/x/../s/a` on to the application — which may
	# resolve it differently. Therefore every path with a `.` or `..` segment, also one with a
	# path parameter (`..;x`, `.;`; Tomcat/Spring read `/s/..;/admin` as `/admin`), backslash, NUL or
	# an encoded form of these (%2e %2f %5c %00; `%3b` only right behind a dot segment) is rejected.
	# Caddy matches the DECODED path: a plain `;` or `%3B` elsewhere is an ordinary file-name character
	# (`/s/<token>/file_%3B%29.bin`) and passes — rejecting every `;` sent such downloads to the login
	# (B-3). Case counts (`/S/` is not `/s/`). Measured against Caddy 2.11.7 in
	# tests/test_gate_caddy.py. Never allow by file extension (`*.js`): many
	# applications serve dynamic content under `/admin/x.css`.
	#
	# A share page usually loads its own scripts and calls its own APIs — these belong in
	# the expression too, measured per application. Whatever is listed here is publicly reachable: a vulnerability
	# of the application in these paths stays open. As narrow as possible.
	@share {
		vars_regexp share {http.request.orig_uri.path} {$TS_SHARE_PREFIX:^$}
		not vars_regexp {http.request.orig_uri.path} (?i)(^|/)\.\.?(/|;|%3b|$)|[\\\x00]|%(2e|2f|5c|00)
	}
	handle @share {
		reverse_proxy {$TS_APP_UPSTREAM:127.0.0.1:9000} {
			# The client's credentials end here (attack round 2026-11-21, A-3): TinySesam has decided, the application
			# trusts Remote-*. An app password, an OAuth access token or an API key (`tsk_…`, valid at every host and at
			# TinySesam's own API) must not reach a debug page, an error report or a header log of the application.
			# Your application checks Authorization ITSELF (its own Basic auth behind the gate)? Then delete these two
			# lines for that host — deliberately, and only there (SECURITY.md, "Credentials at the application").
			header_up -Authorization
			header_up -X-Api-Key
			# No identity on this path — not even one the browser sends along itself.
			header_up -Remote-User
			header_up -Remote-Name
			header_up -Remote-Email
			header_up -Remote-Groups
			header_up -Remote-Id
			header_up -Remote-Auth
			header_up -Remote-Kind
			header_up Cookie "(^|;)\s*(__Host-|__Secure-)?tinysesam_[^=;]*=[^;]*" ""
			header_up Cookie "^[;\s]+" ""
		}
	}

	route {
		reverse_proxy {$TS_AUTH_UPSTREAM:127.0.0.1:8000} {
			method GET
			# The sub-request goes to /auth/forward — as a `rewrite` INSIDE the block, not as a path before
			# the upstream. Until 2026-09-21 this had `reverse_proxy /auth/forward <upstream>`:
			# a leading path in Caddy is a MATCHER, not a rewrite. The check thus ran
			# only for requests whose own path is /auth/forward — every other path fell
			# straight through to the app. The template protected nothing and looked like SSO.
			# (Form as in Caddy's own expansion of `forward_auth`.)
			rewrite /auth/forward
			# Method and path of the REAL request — the rewrite above overwrote both.
			# X-Forwarded-Host/-Proto are deliberately not here: Caddy sets them on its own,
			# and `caddy validate` flags the duplication as unnecessary.
			header_up X-Forwarded-Method {method}
			header_up X-Forwarded-Uri {uri}
			# Only the proxy names the target (attack round B, F1): Caddy passes every other header of the
			# browser on, and an X-Original-URL of its own moved the check to another host up to 0.25.
			header_up -X-Original-URL
			header_up -X-Original-URI
			# header_up X-TinySesam-Roles editors,admin   # only passes with one of these roles
			# take over only the auth response headers
			# Other names (e.g. X-WEBAUTH-USER for Grafana): set TinySesamConfig(forward_headers={...})
			# and carry them along here — only what is listed here is taken over.
			#
			# Header form in `{rp.header.…}` (H-16): Caddy looks for the name character by character
			# in the form Go's textproto makes of it — each word capitalised, the rest lowercase
			# (`Remote-User`, `X-Tinysesam-Location`). Any other spelling yields an
			# EMPTY value, without error and without a log line. tests/test_legacy_data.py checks every
			# placeholder in this file against exactly this form.
			#
			# Each header only when the answer carries it (T-58), the way Caddy's own `forward_auth … copy_headers`
			# does it: a placeholder of a header that is MISSING from the answer stays as literal text, and the
			# application received `{http.reverse_proxy.header.Remote-Email}` as the address (measured with 2.11.9,
			# e.g. after `forward_headers` was reduced). Together with the strip above the application gets
			# TinySesam's value or no header at all.
			@ok status 200
			handle_response @ok {
				@ts_user not vars {rp.header.Remote-User} ""
				@ts_groups not vars {rp.header.Remote-Groups} ""
				@ts_email not vars {rp.header.Remote-Email} ""
				@ts_name not vars {rp.header.Remote-Name} ""
				@ts_id not vars {rp.header.Remote-Id} ""
				@ts_auth not vars {rp.header.Remote-Auth} ""
				@ts_kind not vars {rp.header.Remote-Kind} ""
				request_header @ts_user Remote-User {rp.header.Remote-User}
				request_header @ts_groups Remote-Groups {rp.header.Remote-Groups}
				request_header @ts_email Remote-Email {rp.header.Remote-Email}
				request_header @ts_name Remote-Name {rp.header.Remote-Name}
				request_header @ts_id Remote-Id {rp.header.Remote-Id}
				request_header @ts_auth Remote-Auth {rp.header.Remote-Auth}
				request_header @ts_kind Remote-Kind {rp.header.Remote-Kind}
			}
			# not signed in → redirect to the login URL from the header
			#
			# `X-Tinysesam-Location` with a lowercase s: Caddy stores the response headers under the
			# name Go's HTTP client makes of them (textproto canonicalisation — each word
			# capitalised, the rest lowercase), and the placeholder is looked up character by character. With
			# the repo spelling X-TinySesam-Location it matched nothing: a 302 with an EMPTY
			# Location header, the browser stood still instead of going to the login. On the
			# wire the name is still case-insensitive — only this placeholder is
			# not. nginx (lowercase) and Traefik are not affected.
			# An OAuth resource (T-36): TinySesam answers 401 with `WWW-Authenticate: Bearer resource_metadata=…`
			# and `X-TinySesam-Reason: oauth` — the MCP client needs exactly that 401, not a redirect to a login
			# page it cannot show. BEFORE @denied: the first matching handle_response wins.
			@oauth {
				status 401
				header X-Tinysesam-Reason oauth
			}
			handle_response @oauth {
				header WWW-Authenticate {rp.header.Www-Authenticate}
				respond 401
			}
			# App passwords (T-66): a client without a browser (WebDAV, CalDAV/CardDAV, Git) gets TinySesam's 401 with
			# `WWW-Authenticate: Basic`, not a login page — only at a host with forward_apps[host]["app_passwords"]; TinySesam
			# sends this reason nowhere else. The application's reverse_proxy below drops Authorization (A-3): it
			# trusts Remote-User and does not need the app password.
			@basic {
				status 401
				header X-Tinysesam-Reason basic
			}
			handle_response @basic {
				header WWW-Authenticate {rp.header.Www-Authenticate}
				respond 401
			}
			@denied status 401
			handle_response @denied {
				redir {rp.header.X-Tinysesam-Location} 302
			}
			# signed in, but role missing → leave the 403 standing. Do NOT send to the login:
			# it sends the same user straight back, who still lacks the same role.
			@norole status 403
			handle_response @norole {
				respond "Access denied: missing role." 403
			}
		}
		# The actual upstream app — WITHOUT TinySesam's cookies (B-20).
		# The browser sends it to every host under cookie_domain, and unfiltered it was read by
		# every protected app: a compromised or simply chatty app (debug
		# page, error report, log with request headers) would thereby leak a session valid for
		# ALL other apps and for the account at TinySesam. The app does not need the cookie
		# — who is signed in is told to it by the Remote-* headers.
		# The same goes for the approval cookie `tinysesam_runlock` (unlocked resources), and
		# the CSRF cookie is just as little meant for the app — so all `tinysesam_*`.
		# The first line removes every occurrence (also with the __Host-/__Secure- prefix), the
		# second a leading `; ` left over from that. Other cookies stay untouched.
		# Renamed cookies (TinySesamConfig(session_cookie=…, resource_cookie=…,
		# csrf_cookie=…)) must be carried along into the pattern here.
		reverse_proxy {$TS_APP_UPSTREAM:127.0.0.1:9000} {
			# The client's credentials end here (A-3, see the first application upstream above).
			header_up -Authorization
			header_up -X-Api-Key
			header_up Cookie "(^|;)\s*(__Host-|__Secure-)?tinysesam_[^=;]*=[^;]*" ""
			header_up Cookie "^[;\s]+" ""
		}
	}
}
