# Global options and shared snippets. Routes are in routes.caddy; per-mode
# sites in sites/<CADDY_SITE>.caddy. {$X} is substituted at parse time and
# saved into /config, so secrets are read as {env.X} instead.
{
	# No `email`: with EMAIL unset that line is a parse error.

	# Count requests before forward_auth asks the backend.
	order rate_limit before basic_auth

	# Stops `tls internal` trying to edit the container's trust store.
	skip_install_trust

	servers {
		# Trust CF-Connecting-IP only from cloudflared's fixed IP. Trusting the
		# subnet would let direct visitors (via the bridge gateway) pick their IP.
		trusted_proxies static 172.28.255.250
		client_ip_headers CF-Connecting-IP

		# 443/udp is not published.
		protocols h1 h2
	}

	# Keep access logs out of the default logger, or bodies print unfiltered.
	log default {
		exclude http.log.access.payloads
	}

	# One JSON line per request, body included. A body mentioning a password,
	# token or secret is redacted whole: there is no JSON parser here.
	log payloads_file {
		include http.log.access.payloads
		output file /var/log/caddy/payloads.log {
			roll_size 50MiB
			roll_keep 5
			mode 0644
		}
		format filter {
			wrap json
			fields {
				req_body regexp "(?is)^.*(password|token|secret).*$" "[redacted]"
			}
		}
	}

	# One short line per request for `docker logs` and Dozzle.
	log payloads_stdout {
		include http.log.access.payloads
		output stdout
		format filter {
			wrap console
			fields {
				req_body delete
				request>headers delete
				request>tls delete
				resp_headers delete
			}
		}
	}
}

# ---- Snippets ----------------------------------------------------------------

# Overwrite X-Forwarded-For rather than append, so upstreams see only the
# visitor, not cloudflared.
(proxy) {
	header_up X-Real-IP {client_ip}
	header_up X-Forwarded-For {client_ip}
}

# import limit <zone> <events> <window>: sliding window per client IP.
# A zone name is one shared bucket, so it must always get the same numbers.
(limit) {
	rate_limit {
		zone {args[0]} {
			key {client_ip}
			events {args[1]}
			window {args[2]}
		}
	}
}

# forward_auth sends no body. orig_uri because strip_prefix runs first; the
# `*` stops redir reading the target as a path matcher.
(admin_gate) {
	forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
		uri /auth/validate-admin
		@denied status 401 403
		handle_response @denied {
			redir * /admin/login?redirect={http.request.orig_uri} 302
		}
	}
}

# import permission_gate <key>. 403 goes to /no-access, not the login page.
# copy_headers drops any client-sent X-Remote-User, so upstreams can trust it.
(permission_gate) {
	forward_auth {$BACKEND_HOST}:{$BACKEND_PORT} {
		uri /auth/validate/{args[0]}
		copy_headers X-Auth-User>X-Remote-User
		@unauthenticated status 401
		handle_response @unauthenticated {
			redir * /admin/login?redirect={http.request.orig_uri} 302
		}
		@forbidden status 403
		handle_response @forbidden {
			redir * /no-access?path={http.request.orig_uri} 302
		}
	}
}

# Production only: HSTS on localhost would affect every local project.
(security_headers) {
	header {
		X-Frame-Options "SAMEORIGIN"
		X-Content-Type-Options "nosniff"
		Referrer-Policy "strict-origin-when-cross-origin"
		Strict-Transport-Security "max-age=63072000; includeSubDomains"
	}
}

# Uploads are attacker-supplied bytes on our origin. `>` makes these win over
# Garage's headers.
(upload_headers) {
	header {
		>X-Content-Type-Options "nosniff"
		>Content-Disposition "inline"
		>Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'"
		-Server
		-Via
	}
}

# Serves /uploads/ from disk via the :2080 site. A proxy, not file_server,
# because in an error route file_server replies with the error's status.
# Error routes don't inherit deferred headers, hence the import.
(uploads_disk) {
	import upload_headers
	rewrite * {http.request.orig_uri.path}
	reverse_proxy 127.0.0.1:2080
}

(errors) {
	# 503, not 429: hotelsStream.js reads 429 as the Python service's own limit.
	handle_errors 429 {
		respond "Too many requests from your address. Wait a moment and retry." 503
	}

	# Keyed on vars set by the route, which cannot be spoofed like a path.
	handle_errors 502 504 {
		@uploads_fallback vars uploads_fallback yes
		handle @uploads_fallback {
			import uploads_disk
		}
		@receipt_offline vars receipt_upstream yes
		handle @receipt_offline {
			respond "The receipt printer machine is offline." 503
		}
		@radar_offline vars radar_upstream yes
		handle @radar_offline {
			respond "Partner Radar is offline." 503
		}
		@garage_offline vars garage_upstream yes
		handle @garage_offline {
			respond "The Garage admin UI (stpcore) is offline." 503
		}
	}
}

# Bodies are buffered in memory to log them, so only small non-upload ones.
(logging) {
	log payloads
	@small_body {
		# Spelt out: {1,5} would parse as a placeholder.
		header_regexp Content-Length ^[0-9][0-9]?[0-9]?[0-9]?[0-9]?$
		not path {$BACKEND_ENDPOINT}/uploads* /garage/* /receipt/* /v2/*
	}
	# `<` must be explicit, or the body is logged a second time, empty.
	log_append @small_body <req_body {http.request.body}
}

# Explicit types so streamed responses (ndjson, SSE, audio) are never buffered.
(encode) {
	encode zstd gzip {
		minimum_length 256
		match {
			header Content-Type text/html*
			header Content-Type text/plain*
			header Content-Type text/css*
			header Content-Type text/javascript*
			header Content-Type application/javascript*
			header Content-Type application/json*
			header Content-Type application/xml*
			header Content-Type image/svg+xml*
		}
	}
}

(common) {
	import logging
	import errors
	import encode
	header {
		-Server
		-Via
	}
}

# ---- Container healthcheck (unlogged) ----------------------------------------
http://127.0.0.1 {
	respond /caddy-health 204
	respond 404
}

# ---- Uploads disk site (loopback only, unlogged) -----------------------------
# private/ is refused here too, in case the gated route is ever reordered.
http://:2080 {
	bind 127.0.0.1
	@private path /uploads/private /uploads/private/*
	handle @private {
		respond 404
	}
	handle /uploads/* {
		root * /srv
		file_server
	}
	respond 404
}

import sites/{$CADDY_SITE:prod}.caddy
