# 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 {
	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 {
	# 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.
	handle /.tinysesam/* {
		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} {
			# 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 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}
			# 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.
			@ok status 200
			handle_response @ok {
				request_header Remote-User {rp.header.Remote-User}
				request_header Remote-Groups {rp.header.Remote-Groups}
				request_header Remote-Email {rp.header.Remote-Email}
				request_header Remote-Name {rp.header.Remote-Name}
				request_header Remote-Id {rp.header.Remote-Id}
			}
			# 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.
			@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} {
			header_up Cookie "(^|;)\s*(__Host-|__Secure-)?tinysesam_[^=;]*=[^;]*" ""
			header_up Cookie "^[;\s]+" ""
		}
	}
}
