# Caddy SIP Guardian - Production Configuration
#
# This Caddyfile configures:
# 1. Layer 4 SIP proxying with rate limiting and ban management
# 2. Admin API for managing bans (internal only)
# 3. Web interface proxying for FreePBX

{
	# Enable admin API on all interfaces for docker
	admin 0.0.0.0:2019

	# Global rate limiting zones
	# These are shared across all routes

	# Layer 4 Apps - SIP Traffic
	layer4 {
		# SIP over UDP (most common)
		:5060/udp {
			@sip sip {
				methods REGISTER INVITE OPTIONS ACK BYE CANCEL INFO NOTIFY SUBSCRIBE MESSAGE
			}

			route @sip {
				sip_guardian {
					max_failures 5
					find_time 10m
					ban_time 1h
					whitelist 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
				}
				proxy udp/{$SIP_UPSTREAM_HOST:freepbx}:{$SIP_UPSTREAM_PORT:5060}
			}

			# Unknown traffic - log and drop
			route {
				# Could proxy to a honeypot or just close
			}
		}

		# SIP over TCP
		:5060/tcp {
			@sip sip

			route @sip {
				sip_guardian
				proxy tcp/{$SIP_UPSTREAM_HOST:freepbx}:{$SIP_UPSTREAM_PORT:5060}
			}
		}

		# SIP over TLS (SIPS)
		:5061/tcp {
			@sip sip

			route @sip {
				sip_guardian
				proxy tcp/{$SIP_UPSTREAM_HOST:freepbx}:{$SIP_UPSTREAM_TLS_PORT:5061} {
					tls
				}
			}
		}
	}
}

# Admin API - only accessible from internal networks
:2020 {
	@internal {
		remote_ip 127.0.0.1 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
	}

	handle @internal {
		# SIP Guardian Admin endpoints
		handle /api/sip-guardian/* {
			sip_guardian_admin
		}

		# Health check
		handle /health {
			respond "OK" 200
		}

		# Stats
		handle /stats {
			sip_guardian_admin
		}
	}

	handle {
		respond "Forbidden" 403
	}
}
