🗝
summary refs log tree commit diff
path: root/nginx/sync.py
blob: b715d41c394a29836c44649654e1275950d616cb (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
import re

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

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;
        }
        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=/; samesite=strict; httponly; secure";
                return 200;
            }"""
)

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

ssh_prewarm("asylum", "secrets@bearer")
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"]))