diff --git a/scripts/generate_caddy.py b/scripts/generate_caddy.py index 483b40a..57caac7 100755 --- a/scripts/generate_caddy.py +++ b/scripts/generate_caddy.py @@ -24,7 +24,8 @@ def validate_service(data: dict, source: Path) -> None: raise ValueError(f"{source.name}: missing required key '{key}'") svc_type = data["type"] - if svc_type not in {"static", "proxy"}: + + if svc_type not in {"static", "proxy", "redirect"}: raise ValueError(f"{source.name}: unsupported type '{svc_type}'") if svc_type == "static" and "root" not in data: @@ -33,6 +34,9 @@ def validate_service(data: dict, source: Path) -> None: if svc_type == "proxy" and "backend" not in data: raise ValueError(f"{source.name}: proxy service requires 'backend'") + if svc_type == "redirect" and "target" not in data: + raise ValueError(f"{source.name}: redirect service requires 'target'") + def render_service(env: Environment, data: dict) -> str: svc_type = data["type"] @@ -43,6 +47,13 @@ def render_service(env: Environment, data: dict) -> str: "real_ip": False, "health_uri": None, "health_interval": None, + "internal": False, + "internal_ranges": [ + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + ], + "redirect_code": 301, } merged = {**defaults, **data} @@ -51,6 +62,10 @@ def render_service(env: Environment, data: dict) -> str: template = env.get_template("static.caddy.j2") return template.render(**merged).strip() + "\n" + if svc_type == "redirect": + template = env.get_template("redirect.caddy.j2") + return template.render(**merged).strip() + "\n" + reverse_proxy_block = any( [ merged.get("real_ip"), diff --git a/templates/proxy.caddy.j2 b/templates/proxy.caddy.j2 index b315c99..ea6c2a3 100644 --- a/templates/proxy.caddy.j2 +++ b/templates/proxy.caddy.j2 @@ -5,6 +5,33 @@ {% if auth %} import common_auth {% endif %} +{% if internal %} + @internal { + remote_ip {% for range in internal_ranges %}{{ range }}{% if not loop.last %} {% endif %}{% endfor %} + } + + handle @internal { +{% if reverse_proxy_block %} + reverse_proxy {{ backend }} { +{% if real_ip %} + header_up X-Real-IP {remote_host} +{% endif %} +{% if health_uri %} + health_uri {{ health_uri }} +{% endif %} +{% if health_interval %} + health_interval {{ health_interval }} +{% endif %} + } +{% else %} + reverse_proxy {{ backend }} +{% endif %} + } + + handle { + respond "Forbidden" 403 + } +{% else %} {% if reverse_proxy_block %} reverse_proxy {{ backend }} { {% if real_ip %} @@ -20,4 +47,5 @@ {% else %} reverse_proxy {{ backend }} {% endif %} +{% endif %} } \ No newline at end of file diff --git a/templates/redirect.caddy.j2 b/templates/redirect.caddy.j2 new file mode 100644 index 0000000..79e868f --- /dev/null +++ b/templates/redirect.caddy.j2 @@ -0,0 +1,3 @@ +{{ domain }} { + redir {{ target }} {{ code | default(redirect_code) }} +} \ No newline at end of file