1#!/usr/bin/env python3
2import json
3import grp
4import os
5import re
6import subprocess
7import sys
8import time
9import urllib.parse
10import urllib.request
11
12ROUTES = "/var/lib/caddy/routes.caddy"
13TOKEN = "/var/lib/snowglobe/router.token"
14ROUTE_DIR = "/var/lib/snowglobe/routes"
15HOST = re.compile(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\Z")
16# A reload closes every proxied WebSocket, so one failed check must not drop a route.
17HEALTH_GRACE = 30
18last_passing = {}
19
20
21def nomad(path, token):
22 request = urllib.request.Request(
23 "http://127.0.0.1:4646" + path,
24 headers={"X-Nomad-Token": token},
25 )
26 with urllib.request.urlopen(request, timeout=5) as response:
27 return json.load(response)
28
29
30def passive_health(upstreams, indent):
31 return [f"{indent}fail_duration 30s"] if len(upstreams.split()) > 1 else []
32
33
34def proxy(upstreams, indent, uncompressed=False, host=None):
35 lines = [f"{indent}reverse_proxy {upstreams} {{", f"{indent} lb_try_duration 5s", f"{indent} stream_close_delay 8h",
36 *passive_health(upstreams, indent + " ")]
37 if uncompressed:
38 lines.append(f"{indent} header_up Accept-Encoding identity")
39 if host:
40 lines += [f"{indent} header_up Host {host}", f"{indent} header_up X-Forwarded-Host {host}"]
41 return [*lines, f"{indent}}}"]
42
43
44def shale_mcp_routes(port):
45 return [" @shale_mcp_link path_regexp shale_mcp_link ^/-/snowglobe-mcp/([A-Za-z0-9_-]{43})$",
46 " handle @shale_mcp_link {", " rewrite * /oauth/shale/link/{re.shale_mcp_link.1}",
47 " request_header -User-Name", " request_header -User-Groups", " request_header -Snowglobe-Proxy-Token",
48 *proxy(f"127.0.0.1:{port}", " "), " }",
49 " @shale_mcp_callback {", " path /-/callback", " header Cookie *snowglobe_mcp_shale_link=*", " }",
50 " handle @shale_mcp_callback {", " rewrite * /oauth/shale/callback",
51 " request_header -User-Name", " request_header -User-Groups", " request_header -Snowglobe-Proxy-Token",
52 *proxy(f"127.0.0.1:{port}", " "), " }"]
53
54
55def shale_attachment_routes(upstreams, target="/srv/prod/shale"):
56 """Authorize retained attachments through their issue before serving bytes."""
57 manifest = os.path.join(target, "forgejo-attachments.json")
58 if not os.path.exists(manifest):
59 return []
60 with open(manifest) as source:
61 entries = json.load(source)
62 if not isinstance(entries, list) or len(entries) > 10000:
63 raise ValueError("invalid Shale attachment manifest")
64 lines = []
65 for index, entry in enumerate(entries):
66 path, filename, issue = (entry[k] for k in ("path", "file", "issue"))
67 if (not re.fullmatch(r"[0-9a-f-]{36}/[^/\\\"\r\n]+", filename)
68 or path != "/-/forgejo-attachments/" + urllib.parse.quote(filename, safe="/")
69 or not re.fullmatch(r"/(?:[a-zA-Z0-9_.-]+/)+issues/[1-9][0-9]*", issue)):
70 raise ValueError("unsafe Shale attachment route")
71 # Request cookies go to Shale as usual. A private issue yields 403/404;
72 # only Shale's successful issue response permits the local file read.
73 name = f"@shale_attachment_{index}"
74 lines += [f" {name} path {json.dumps(path)}", f" handle {name} {{",
75 " header Cache-Control private,no-store", " header X-Content-Type-Options nosniff",
76 f" reverse_proxy {upstreams} {{", " method GET", f" rewrite {issue}",
77 " @authorized status 200", " handle_response @authorized {",
78 f" root * {json.dumps(os.path.join(target, 'forgejo-attachments'))}",
79 f" rewrite * {json.dumps('/' + urllib.parse.quote(filename, safe='/'))}",
80 " file_server", " }", " }", " }"]
81 return lines
82
83
84def shale_write_routes(host):
85 # Older Shale releases predate form tokens. Browsers send Origin on POST;
86 # require the exact site origin for every cookie-authenticated mutation.
87 # HTTP Git clients use Basic authentication and do not carry this cookie.
88 return [" @shale_unsafe_origin {", " method POST PUT PATCH DELETE",
89 " header Cookie *SessionID=*", f" not header Origin https://{host}",
90 " }", ' respond @shale_unsafe_origin "Forbidden" 403']
91
92
93def shale_login_routes(host):
94 # Shale parses the login Referer as an absolute URL after OAuth.
95 return_url = rf"^https://{re.escape(host)}/(?:[A-Za-z0-9._~!$&'()*+,;=:@/?#\[\]-]|%[0-9A-Fa-f]{{2}})*$"
96 return [" @shale_login_return {", " path /-/login",
97 f" not header_regexp Referer `{return_url}`", " }",
98 f" request_header @shale_login_return Referer https://{host}/"]
99
100
101def zig_mirror_routes(service, routes):
102 if service == "copyparty":
103 mirror = "zig-mirror"
104 else:
105 state = os.environ.get("SNOWGLOBE_STATE", "/var/lib/snowglobe")
106 stages = os.path.join(state, "stages")
107 try:
108 with open(os.path.join(stages, service + ".json")) as source:
109 stage = json.load(source)
110 mirror = stage.get("mirrorStage", "")
111 if stage.get("sourceId") != "copyparty" or not isinstance(mirror, str) or not re.fullmatch(r"zig-mirror-preview-[0-9a-f]{8}", mirror):
112 mirror = None
113 if mirror:
114 with open(os.path.join(stages, mirror + ".json")) as source:
115 if json.load(source).get("sourceId") != "zig-mirror":
116 mirror = None
117 except FileNotFoundError:
118 mirror = None
119 upstreams = set().union(*(route["upstreams"] for route in routes.values() if mirror in route["services"]))
120 pattern = r"^/mirrors/zig/zig[^/]*\.(?:tar\.xz|zip)(?:\.minisig)?$"
121 lines = [" @mirror_private expression `path_regexp('^/+mirrors(?:/+[^/]*)*/+[.]') || (path_regexp('^/+mirrors(?:/|$)') && {http.request.uri.query}.matches('(?i)(^|&)doc=(?:[.]|%2e)'))`",
122 " handle @mirror_private {", " respond 404", " }",
123 " @zig_mirror {", " method GET HEAD", f" path_regexp zig_mirror {pattern}", " }",
124 " handle @zig_mirror {"]
125 if upstreams:
126 if any(not re.fullmatch(r"127\.0\.0\.1:[0-9]+|\[::1\]:[0-9]+", upstream) for upstream in upstreams):
127 raise ValueError("Zig mirror requires private loopback upstreams")
128 lines += [" request_header -Authorization", " request_header -Cookie",
129 *proxy(" ".join(sorted(upstreams)), " ")]
130 else:
131 lines.append(" respond 503")
132 return [*lines, " }"]
133
134
135def dashboard_preview_proof(service):
136 if not re.fullmatch(r"dashboard-preview-[0-9a-f]{8}", service):
137 return None
138 stages = os.path.join(os.environ.get("SNOWGLOBE_STATE", "/var/lib/snowglobe"), "stages")
139 try:
140 with open(os.path.join(stages, service + ".json")) as source:
141 stage = json.load(source)
142 mount = stage.get("mount", "")
143 if stage.get("sourceId") != "dashboard" or not os.path.isabs(mount) or os.path.basename(mount) != service or os.path.basename(os.path.dirname(mount)) != "staging":
144 return None
145 path = os.path.join(mount, "proxy.token")
146 if os.path.islink(path) or os.stat(path).st_mode & 0o077:
147 return None
148 with open(path) as source:
149 proof = source.read().strip()
150 except FileNotFoundError:
151 return None
152 if not re.fullmatch(r"[0-9a-f]{64}", proof):
153 raise ValueError("invalid dashboard preview proxy proof")
154 return proof
155
156
157def shale_gateway(service, routes, proof):
158 source = service.split("-preview-", 1)[0]
159 if source != "shale":
160 return None, None
161 stages = os.path.join(os.environ.get("SNOWGLOBE_STATE", "/var/lib/snowglobe"), "stages")
162 gateway = None
163 if service != source:
164 try:
165 with open(os.path.join(stages, service + ".json")) as file:
166 stage = json.load(file)
167 except FileNotFoundError:
168 return None, None
169 if stage.get("sourceId") != source:
170 return None, None
171 gateway = stage.get("gatewayStage")
172 if gateway is not None and (not isinstance(gateway, str) or not re.fullmatch(r"dashboard-preview-[0-9a-f]{8}", gateway)):
173 return None, None
174 if gateway is None:
175 port = int(os.environ["SNOWGLOBE_DASHBOARD_PORT"])
176 if not 1 <= port <= 65535:
177 raise ValueError("invalid dashboard port")
178 return f"127.0.0.1:{port}", proof
179 try:
180 with open(os.path.join(stages, gateway + ".json")) as file:
181 if json.load(file).get("sourceId") != "dashboard":
182 return None, None
183 except FileNotFoundError:
184 return None, None
185 upstreams = set().union(*(route["upstreams"] for route in routes.values() if gateway in route["services"]))
186 if len(upstreams) != 1:
187 return None, None
188 upstream = next(iter(upstreams))
189 if not re.fullmatch(r"127\.0\.0\.1:[0-9]+|\[::1\]:[0-9]+", upstream):
190 raise ValueError("preview gateway must bind loopback")
191 proof = dashboard_preview_proof(gateway)
192 return (upstream, proof) if proof else (None, None)
193
194
195def render(token):
196 with open(os.environ["SNOWGLOBE_PROXY_TOKEN_FILE"]) as file:
197 dashboard_proof = file.read().strip()
198 if not re.fullmatch(r"[0-9a-fA-F]{64}", dashboard_proof):
199 raise ValueError("invalid dashboard proxy token")
200 auth_host = "auth." + os.environ["SNOWGLOBE_DOMAIN"]
201 origins = json.dumps({"origins": ["https://snowglobe." + os.environ["SNOWGLOBE_DOMAIN"]]}, separators=(",", ":"))
202 webauthn = [" handle /.well-known/webauthn {", ' header Content-Type application/json',
203 f" respond {json.dumps(origins)} 200", " }"]
204 routes = {}
205 internal_services = {}
206 auth_upstreams = set()
207 allocation_checks = {}
208 for namespace in nomad("/v1/services", token):
209 if namespace["Namespace"] != "default":
210 continue
211 for service in namespace["Services"]:
212 name = urllib.parse.quote(service["ServiceName"], safe="")
213 for instance in nomad(f"/v1/service/{name}", token):
214 tags = instance.get("Tags") or []
215 if instance["ServiceName"] != "forward-auth" and not any(tag.startswith("caddy-") for tag in tags):
216 continue
217 address = instance["Address"]
218 port = instance["Port"]
219 if not re.fullmatch(r"[0-9a-fA-F:.]+", address) or type(port) is not int or not 1 <= port <= 65535:
220 continue
221 upstream = f"[{address}]:{port}" if ":" in address else f"{address}:{port}"
222 if not re.fullmatch(r"[a-z][a-z0-9-]*", instance["ServiceName"]):
223 raise ValueError("invalid internal service name")
224 internal_services.setdefault(instance["ServiceName"], set()).add(upstream)
225 alloc = instance["AllocID"]
226 if alloc not in allocation_checks:
227 allocation_checks[alloc] = nomad(f"/v1/allocation/{alloc}/checks", token)
228 service_checks = list(allocation_checks[alloc].values())
229 if service_checks and all(check["Status"] == "success" for check in service_checks):
230 last_passing[alloc] = time.monotonic()
231 elif time.monotonic() - last_passing.get(alloc, float("-inf")) > HEALTH_GRACE:
232 continue
233 if instance["ServiceName"] == "forward-auth":
234 auth_upstreams.add(upstream)
235 access = [tag.split("=", 1)[1] for tag in tags if tag.startswith("caddy-auth-role=")]
236 user_headers = [tag.split("=", 1)[1] for tag in tags if tag.startswith("caddy-user-header=")]
237 if len(access) > 1 or (access and not re.fullmatch(r"[a-z][a-z0-9-]*", access[0])):
238 raise ValueError("invalid route access role")
239 if len(user_headers) > 1 or (user_headers and (not access or not re.fullmatch(r"[A-Za-z][A-Za-z0-9-]*", user_headers[0]))):
240 raise ValueError("invalid authenticated user header")
241 if access and not any(tag.startswith("caddy-host=") for tag in tags):
242 raise ValueError("route access role has no host")
243 for tag in tags:
244 if tag.startswith(("caddy-host=", "caddy-plain-host=")):
245 host = tag.split("=", 1)[1]
246 role = access[0] if access and tag.startswith("caddy-host=") else None
247 user_header = user_headers[0] if user_headers and role else None
248 if not HOST.fullmatch(host):
249 raise ValueError(f"invalid Caddy host: {host!r}")
250 route = routes.setdefault((80, host), {"upstreams": set(), "services": set(), "authRole": None, "userHeader": None, "internal": False, "realIp": False, "secureCookies": False})
251 if role and route["authRole"] not in (None, role):
252 raise ValueError("conflicting route access roles")
253 if user_header and route["userHeader"] not in (None, user_header):
254 raise ValueError("conflicting authenticated user headers")
255 if role:
256 route["authRole"] = role
257 if user_header:
258 route["userHeader"] = user_header
259 if "caddy-internal=true" in tags:
260 route["internal"] = True
261 if "caddy-real-ip=true" in tags:
262 route["realIp"] = True
263 if "caddy-secure-cookies=true" in tags:
264 route["secureCookies"] = True
265 route["upstreams"].add(upstream)
266 route["services"].add(instance.get("JobID") or instance["ServiceName"])
267 elif tag.startswith("caddy-port="):
268 listener = int(tag.split("=", 1)[1])
269 if not 1 <= listener <= 65535:
270 raise ValueError(f"invalid Caddy port: {listener}")
271 route = routes.setdefault((listener, ""), {"upstreams": set(), "services": set()})
272 route["upstreams"].add(upstream)
273
274 for alloc in last_passing.keys() - allocation_checks.keys():
275 del last_passing[alloc]
276 lines = []
277 for (listener, host), route in sorted(routes.items()):
278 if host:
279 if host == auth_host:
280 continue
281 role = route["authRole"]
282 if role and not auth_upstreams:
283 continue
284 lines.append(f"{host if listener == 80 else f'{host}:{listener}'} {{")
285 if host.endswith(".test") or route["internal"]:
286 lines.append(" tls internal")
287 if route["secureCookies"]:
288 lines.append(' header >Set-Cookie "(.*)" "$1; Secure"')
289 if route["realIp"]:
290 lines.append(" request_header X-Real-Ip {remote_host}")
291 if len(route["services"]) != 1:
292 raise ValueError(f"multiple services claim {host}")
293 service = next(iter(route["services"]))
294 if not re.fullmatch(r"[a-z][a-z0-9-]*", service):
295 raise ValueError(f"invalid service name: {service}")
296 if service == "shale" or re.fullmatch(r"shale-preview-[0-9a-f]{8}", service):
297 # Keep the Origin guard before every static/proxy handle;
298 # otherwise Caddy sorts those handles ahead of respond.
299 lines += [" route {", *shale_write_routes(host),
300 *shale_login_routes(host)]
301 if re.fullmatch(r"shale-preview-[0-9a-f]{8}", service):
302 lines += shale_attachment_routes(" ".join(sorted(route["upstreams"])),
303 "/srv/staging/" + service)
304 if service == "shale":
305 lines += [" handle /-/logout {", f" reverse_proxy {' '.join(sorted(route['upstreams']))} {{",
306 f" header_down Location https://snowglobe.{os.environ['SNOWGLOBE_DOMAIN']}/auth/shale/sign-out",
307 " @logged_out status 200 302 303 404", " handle_response @logged_out {",
308 " copy_response 303", " }", " }", " }"]
309 lines += shale_attachment_routes(" ".join(sorted(route["upstreams"])))
310 lines += [" @userscript path_regexp userscript ^/userscripts/discord-pluralkit-predict(/.*)?$",
311 " redir @userscript /discord-pluralkit-predict{re.userscript.1}?{query} 308"]
312 port = int(os.environ["SNOWGLOBE_DASHBOARD_PORT"])
313 if not 1 <= port <= 65535:
314 raise ValueError("invalid dashboard port for Shale linking")
315 lines += shale_mcp_routes(port)
316 lines += [" tracing {", f" span {service}", " span_attributes {",
317 f" snowglobe.service {service}", " snowglobe.kind edge", " }", " }"]
318 if service == "copyparty" or re.fullmatch(r"copyparty-preview-[0-9a-f]{8}", service):
319 lines += zig_mirror_routes(service, routes)
320 manifest = os.path.join(ROUTE_DIR, service + ".json")
321 assets = {}
322 headers = {}
323 head_html = {}
324 proof = None
325 scrub = []
326 if os.path.exists(manifest):
327 with open(manifest) as file:
328 assets = json.load(file)
329 identity = assets.get("identity", {})
330 headers = identity.get(host, {})
331 head_html = assets.get("headHtml", {}).get(host, {})
332 proof = assets.get("identityProof", {}).get(host)
333 scrub = sorted({name for configured in identity.values() for name in configured} | set(assets.get("identityProof", {}).values()))
334 if any(not re.fullmatch(r"[A-Za-z][A-Za-z0-9-]*", name) for name in scrub):
335 raise ValueError(f"invalid identity header: {host}")
336 if proof and not headers:
337 raise ValueError(f"identity proof has no identity headers: {host}")
338 if any(source not in {"X-Auth-Request-User", "X-Auth-Request-Groups", "X-Auth-Request-Preferred-Username"} for source in headers.values()):
339 raise ValueError(f"invalid identity claim: {host}")
340 if role and headers:
341 raise ValueError(f"route has both required and optional auth: {host}")
342 if role and (assets.get("files") or assets.get("dirs")):
343 raise ValueError(f"authenticated route has static overrides: {host}")
344 if head_html and (role or headers):
345 raise ValueError(f"authenticated route has HTML injection: {host}")
346 for request, markup in head_html.items():
347 if not re.fullmatch(r"/[A-Za-z0-9/._*-]*", request) or not markup:
348 raise ValueError(f"invalid HTML injection: {host} {request}")
349 for request, path in assets.get("files", {}).items():
350 if not request.startswith("/") or " " in request or "\n" in request:
351 raise ValueError(f"invalid static path: {request}")
352 lines += [f" handle {request} {{", f" root * {json.dumps(os.path.dirname(path))}",
353 f" rewrite * /{os.path.basename(path)}", ' header Cache-Control "no-store"',
354 " file_server", " }"]
355 for request, path in assets.get("dirs", {}).items():
356 if not request.startswith("/") or " " in request or "\n" in request:
357 raise ValueError(f"invalid static prefix: {request}")
358 lines += [f" handle_path {request}* {{", f" root * {json.dumps(path)}"]
359 if request == "/.static/" and (service == "copyparty" or re.fullmatch(r"copyparty-preview-[0-9a-f]{8}", service)):
360 lines += [" @public_font path *.woff2", ' header @public_font Access-Control-Allow-Origin "*"']
361 lines += [" file_server", " }"]
362 metrics_path = assets.get("metricsPaths", {}).get(host)
363 if metrics_path:
364 if not re.fullmatch(r"/[A-Za-z0-9/._-]+", metrics_path):
365 raise ValueError(f"invalid metrics path: {host}")
366 lines += [f" handle {metrics_path} {{", " respond 404", " }"]
367 api_paths = assets.get("apiPaths", {}).get(host, {})
368 if api_paths:
369 if any(not re.fullmatch(r"/[A-Za-z0-9/._-]+\*?", path) or not re.fullmatch(r"[a-z][a-z0-9-]*", target)
370 or not (target == service or target.startswith(service + "-")) for path, target in api_paths.items()):
371 raise ValueError(f"invalid API routes: {host}")
372 lines += [f" log {service} {{", " output stdout", " format filter {",
373 " request delete", " resp_headers delete", " user_id delete", " }", " }",
374 " @not_api not path " + " ".join(sorted(api_paths)), " log_skip @not_api",
375 f" log_append service {service}", " log_append request_id {http.request.uuid}",
376 " log_append method {method}", " log_append path {path}", " log_append protocol {http.request.proto}",
377 " log_append content_length {http.request.header.Content-Length}",
378 " log_append client {remote}",
379 " log_append upstream {http.reverse_proxy.upstream.hostport}",
380 " log_append upstream_status {http.reverse_proxy.status_code}",
381 " log_append upstream_header_ms {http.reverse_proxy.upstream.latency_ms}",
382 " log_append proxy_ms {http.reverse_proxy.duration_ms}"]
383 lines += [" handle_errors 499 504 {", " @api_error path " + " ".join(sorted(api_paths)),
384 " handle @api_error {", " @http1 not protocol http/2+",
385 # Late body bytes must not become the next HTTP/1 request after a timeout.
386 " header @http1 Connection close", " header X-Request-ID {http.request.uuid}",
387 " header X-Should-Retry true", " }", ' respond "" {err.status_code}', " }"]
388 for index, target in enumerate(sorted(set(api_paths.values()))):
389 upstreams = set()
390 for instance in nomad("/v1/service/" + target, token):
391 address, port = instance["Address"], instance["Port"]
392 if instance.get("JobID") != service or not re.fullmatch(r"127\.0\.0\.1|::1", address) or type(port) is not int or not 1 <= port <= 65535:
393 raise ValueError(f"API upstream must belong to {service} on loopback: {target}")
394 upstreams.add(f"[{address}]:{port}" if ":" in address else f"{address}:{port}")
395 paths = " ".join(sorted(path for path in api_paths if api_paths[path] == target))
396 lines += [f" @api_{index} path {paths}", f" handle @api_{index} {{", " header >X-Request-ID {http.request.uuid}",
397 # Caddy can return 499 to a connected client when its request-body idle timer expires.
398 " header X-Should-Retry true {", " match {", " status 499",
399 " header !X-Should-Retry", " }", " }",
400 " request_header X-Request-ID {http.request.uuid}"]
401 lines += proxy(" ".join(sorted(upstreams)), " ") if upstreams else [" respond 503"]
402 lines.append(" }")
403 upstreams = " ".join(sorted(route["upstreams"]))
404 if role:
405 auth = " ".join(sorted(auth_upstreams))
406 lines += [" handle /snow.oauth2/* {", *proxy(auth, " "), " }", " handle {"]
407 if route["userHeader"]:
408 lines.append(f" request_header -{route['userHeader']}")
409 lines += [
410 f" reverse_proxy {auth} {{", " lb_try_duration 5s", *passive_health(auth, " "), " method GET",
411 " rewrite /snow.oauth2/auth", " header_up X-Forwarded-Method {method}",
412 " header_up X-Forwarded-Uri {uri}", " @unauthorized status 401",
413 " handle_response @unauthorized {",
414 " redir * /snow.oauth2/sign_in?rd={scheme}://{host}{uri}", " }",
415 f" @allowed header X-Auth-Request-Groups *role:{role}*",
416 " handle_response @allowed {", " method {method}", " rewrite {uri}",
417 ]
418 if route["userHeader"]:
419 lines.append(f" request_header {route['userHeader']} {{rp.header.X-Auth-Request-Preferred-Username}}")
420 lines += [
421 *proxy(upstreams, " "), " }",
422 " handle_response {", " respond 403", " }", " }", " }", "}",
423 ]
424 elif headers and (auth_upstreams or service == "copyparty"):
425 native = service == "copyparty"
426 auth = f"127.0.0.1:{int(os.environ['SNOWGLOBE_DASHBOARD_PORT'])}" if native else " ".join(sorted(auth_upstreams))
427 if native:
428 lines += [" handle /auth/file/* {", " request_header -User-Name", " request_header -User-Groups",
429 f" request_header Snowglobe-Proxy-Token {dashboard_proof}",
430 " request_header X-Snowglobe-Client-IP {remote_host}", *proxy(auth," "), " }"]
431 else:
432 lines += [" handle /snow.oauth2/* {", *proxy(auth," "), " }"]
433 lines += [" handle {"]
434 lines += [f" request_header -{name}" for name in scrub]
435 lines += [f" reverse_proxy {auth} {{", " lb_try_duration 5s", *passive_health(auth, " "), " method GET", " rewrite " + ("/auth/file/check" if native else "/snow.oauth2/auth"),
436 *([f" header_up Snowglobe-Proxy-Token {dashboard_proof}"] if native else []),
437 " header_up X-Forwarded-Method {method}", " header_up X-Forwarded-Uri {uri}",
438 " @authenticated status 2xx", " handle_response @authenticated {"]
439 lines += [f" request_header {name} {{rp.header.{source}}}" for name, source in headers.items()]
440 if proof:
441 lines.append(f" request_header {proof} 1")
442 lines += [" }", " @anonymous status 4xx", " handle_response @anonymous {",
443 f" request_header -{scrub[0]}", " }", " }",
444 *proxy(upstreams, " "), " }", "}"]
445 else:
446 preview_proof = dashboard_preview_proof(service)
447 if preview_proof:
448 lines.append(f" request_header Snowglobe-Proxy-Token {preview_proof}")
449 page_upstream = upstreams
450 shale_page = service == "shale" or re.fullmatch(r"shale-preview-[0-9a-f]{8}", service)
451 page_headers = []
452 if shale_page:
453 page_upstream, proof = shale_gateway(service, routes, dashboard_proof)
454 if not page_upstream:
455 lines += [" respond 503", " }", "}"]
456 continue
457 page_headers = [f" request_header Snowglobe-Proxy-Token {proof}",
458 f" request_header Snowglobe-Shale-Upstream {json.dumps(sorted(route['upstreams'])[0])}",
459 " request_header Snowglobe-Shale-Uri {uri}",
460 " rewrite * /auth/shale/page"]
461 for index, (request, markup) in enumerate(head_html.items()):
462 name = f"@snowglobe_head_{index}"
463 lines += [f" {name} path {request}", f" handle {name} {{", " route {",
464 f" replace </head> {json.dumps(markup + '</head>')} {{",
465 " match {", " header Content-Type text/html*", " }", " }",
466 *[" " + line for line in page_headers],
467 *proxy(page_upstream, " ", uncompressed=True), " }", " }"]
468 page_handler = [*page_headers, *proxy(page_upstream, " ")]
469 if shale_page:
470 page_handler = [" route {", *[" " + line for line in page_handler], " }"]
471 lines += [" handle {", *(f" request_header -{name}" for name in scrub),
472 *page_handler, " }", "}"]
473 if service == "shale" or re.fullmatch(r"shale-preview-[0-9a-f]{8}", service):
474 lines.insert(len(lines) - 1, " }")
475 else:
476 lines += [f":{listener} {{", *proxy(" ".join(sorted(route["upstreams"])), " "), "}"]
477 dashboard_host = "snowglobe." + os.environ["SNOWGLOBE_DOMAIN"]
478 if any(not HOST.fullmatch(host) for host in [auth_host, dashboard_host]):
479 raise ValueError("invalid login domain")
480 lines += [f"{auth_host} {{", *([" tls internal"] if auth_host.endswith(".test") else []),
481 *webauthn, " handle {", f" redir https://{dashboard_host}/ 308", " }", "}"]
482 traces = internal_services.get("victoria-traces")
483 if traces:
484 lines += ["http://127.0.0.1:10428 {", " bind 127.0.0.1",
485 *proxy(" ".join(sorted(traces)), " "), "}"]
486 dashboard_port = int(os.environ["SNOWGLOBE_DASHBOARD_PORT"])
487 if not 1 <= dashboard_port <= 65535:
488 raise ValueError("invalid dashboard route")
489 if (80, dashboard_host) in routes:
490 raise ValueError(f"dashboard route conflicts with a Nomad service: {dashboard_host}")
491 lines.append(f"{dashboard_host} {{")
492 if dashboard_host.endswith(".test"):
493 lines.append(" tls internal")
494 lines += [" encode zstd gzip", " tracing {", " span globe", " span_attributes {", " snowglobe.kind edge", " }", " }"]
495 lines += [" handle {", " request_header -User-Name", " request_header -User-Groups",
496 f" request_header Snowglobe-Proxy-Token {dashboard_proof}",
497 " request_header X-Snowglobe-Client-IP {remote_host}",
498 *proxy(f"127.0.0.1:{dashboard_port}", " "), " }", "}"]
499 internal_port = os.environ.get("SNOWGLOBE_INTERNAL_PORT")
500 if internal_port is not None:
501 internal_host = "dashboard.internal." + os.environ["SNOWGLOBE_DOMAIN"]
502 if not HOST.fullmatch(internal_host) or not internal_port.isdecimal() or not 1 <= int(internal_port) <= 65535:
503 raise ValueError("invalid internal dashboard route")
504 if (80, internal_host) in routes or (int(internal_port), "") in routes:
505 raise ValueError("internal dashboard route conflicts with a Nomad service")
506 lines += [f"{internal_host}:{internal_port} {{", " tls internal",
507 f" @dashboard header Snowglobe-Proxy-Token {dashboard_proof}",
508 " handle @dashboard {", " request_header -Snowglobe-Proxy-Token",
509 " request_header -User-Name", " request_header -User-Groups",
510 " handle_path /nomad/* {", *proxy("127.0.0.1:4646", " ", host="{upstream_hostport}"), " }"]
511 for service, upstreams in sorted(internal_services.items()):
512 host = f"{service}.{os.environ['SNOWGLOBE_DOMAIN']}" if service == "shale" or re.fullmatch(r"shale-preview-[0-9a-f]{8}", service) else "{upstream_hostport}"
513 lines += [f" handle_path /services/{service}/* {{",
514 *proxy(" ".join(sorted(upstreams)), " ", host=host), " }"]
515 lines += [" handle {", " respond 404", " }", " }", " handle {", " respond 403", " }", "}"]
516 return "\n".join(lines) + "\n"
517
518
519def update(content):
520 try:
521 with open(ROUTES) as file:
522 previous = file.read()
523 except FileNotFoundError:
524 previous = ""
525 if content == previous:
526 return
527 pending = ROUTES + ".pending"
528 def replace(value):
529 with open(pending, "w") as file:
530 file.write(value)
531 os.chown(pending, -1, grp.getgrnam("caddy").gr_gid)
532 os.chmod(pending, 0o640)
533 os.replace(pending, ROUTES)
534
535 replace(content)
536 result = subprocess.run(["systemctl", "reload", "caddy"], capture_output=True, text=True)
537 if result.returncode:
538 replace(previous)
539 raise RuntimeError(result.stderr.strip())
540 print("Caddy routes updated", flush=True)
541
542
543def main():
544 with open(TOKEN) as file:
545 token = file.read().strip()
546 while True:
547 try:
548 update(render(token))
549 except Exception as error:
550 print(f"Caddy route update failed: {error}", file=sys.stderr, flush=True)
551 time.sleep(5)
552
553
554if __name__ == "__main__":
555 main()