# HTTPS in front of the server, for clients on the local network. Started
# only with the profile https of compose.yaml, which hands Caddy two values
# from .env:
#   YAHOO_FINANCE_MCP_DOMAIN  the name clients use, e.g. finance.lan
#   YAHOO_FINANCE_MCP_TLS     where the certificate comes from, one of the
#                             three snippets below, internal unless .env
#                             says otherwise
{
	# Caddy would put its own CA into the container's trust store, which is
	# read-only and trusted by nobody. The clients need it, see
	# containers/README.md.
	skip_install_trust
	# Port 80 is not published, so nothing would hear a redirect from it. A
	# client set up with http:// fails at once instead of sending its token
	# in the clear before a redirect it follows without anyone noticing.
	auto_https disable_redirects
}

# Caddy's own CA, for a name on the local network. Every client trusts its
# root once: the caddy-data volume keeps it under
# caddy/pki/authorities/local/root.crt.
(tls-internal) {
	tls internal
}

# A certificate from a public CA, Let's Encrypt or ZeroSSL, requested and
# renewed by Caddy over port 443. The name has to resolve to this host in
# public DNS and the port has to be reachable from the internet.
(tls-acme) {
}

# A certificate of your own, a company CA's for instance: secrets/tls/cert.pem,
# with its chain, and secrets/tls/key.pem beside compose.yaml.
(tls-files) {
	tls /secrets/tls/cert.pem /secrets/tls/key.pem
}

{$YAHOO_FINANCE_MCP_DOMAIN} {
	import tls-{$YAHOO_FINANCE_MCP_TLS:internal}

	# The server checks the bearer token itself. A request without any
	# Authorization header cannot pass that check and stops here, so a scan
	# of the internet never reaches the server.
	@unauthenticated not header Authorization *
	header @unauthenticated WWW-Authenticate Bearer
	respond @unauthenticated 401

	reverse_proxy benethos-yahoo-finance-mcp:8000
}
