🗝
summary refs log tree commit diff
path: root/nginx/sync.py
blob: 2b36c2c1fc05b6ee7834c7bcc44a23ddf573b07e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import re

from commia.bearer import get_key, keys
from commia.prelude import *
from commia.ssh import scp, ssh_args, ssh_prewarm
from commia.util import with_written

ssh_prewarm("asylum", "secrets@bearer")
spacing_pattern = re.compile(r"([;,{}])$")

handoff = Path("nginx/handoff.html").read_text().splitlines()
handoff = map(lambda line: line.lstrip("\t"), handoff)
handoff = map(lambda line: spacing_pattern.sub(r"\1 ", line), handoff)
handoff = "".join(handoff).replace('"', '\\"').replace("$", "${dollar}")

auth_check = """if ($cookie___proxy_token = "") {
            return 303 https://$host/.nginx/handoff.html#$request_uri;
        }
        auth_request /.nginx/auth;"""

auth_locations = (
    '''location /.nginx/auth {
                internal;
                js_content nginx.validate;
            }
    
            location /.nginx/scopes {
                internal;
                proxy_pass http://[::1]:8001/scopes/$arg_token;
            }
    
            location /.nginx/handoff.html {
                return 200 "'''
    + handoff
    + """";
            }

            location /.nginx/cookie {
                add_header Set-Cookie "__proxy_token=${arg_token}; max-age=${arg_max_age}; path=/; httponly; samesite=lax; secure";
                return 200;
            }"""
)

proxy = (
    """proxy_http_version 1.1;
            proxy_redirect off;
            proxy_set_header Host $http_host;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;"""
)

domains = get_key(keys.domains).splitlines()
terminate_tmpl = Path("nginx/terminate.conf").read_text()
terminate = []
for domain in domains:
    terminate.append(terminate_tmpl.replace("%HOST%", domain))
terminate_indented = "\n".join(
    map(lambda line: f"\t{line}", "\n".join(terminate).splitlines())
).strip()

nginx_conf = (
    Path("nginx/nginx.conf")
    .read_text()
    .replace("%AUTH_CHECK%", auth_check)
    .replace("%AUTH_LOCATIONS%", auth_locations)
    .replace("%PROXY%", proxy)
    .replace("%TERMINATE%", terminate_indented)
)

with_written(
    nginx_conf,
    lambda path: scp(path, "asylum:/etc/nginx/nginx.conf"),
)

for name in ["nginx.js", "mime.types", "fastcgi.conf"]:
    scp(f"nginx/{name}", f"asylum:/etc/nginx/{name}")

if run(p([*ssh_args(), "nginx", "-t"])).returncode == 0:
    run_check(p([*ssh_args(), "systemctl", "restart", "nginx"]))