| 1 | #!/usr/bin/env python3 |
| 2 | import argparse |
| 3 | from http.client import HTTPConnection |
| 4 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 5 | import json |
| 6 | import os |
| 7 | from pathlib import Path |
| 8 | import socket |
| 9 | import subprocess |
| 10 | import tempfile |
| 11 | import threading |
| 12 | import time |
| 13 | from unittest.mock import patch |
| 14 | |
| 15 | import router |
| 16 | |
| 17 | |
| 18 | class Cookies(BaseHTTPRequestHandler): |
| 19 | def do_GET(self): |
| 20 | self.send_response(204 if self.path == '/logout' else 200) |
| 21 | self.send_header('Set-Cookie', 'session=fixture; HttpOnly; Path=/') |
| 22 | self.send_header('Set-Cookie', 'other=fixture; SameSite=Lax') |
| 23 | self.send_header('X-Fixture-Referer', self.headers.get('Referer', '')) |
| 24 | self.end_headers() |
| 25 | |
| 26 | def log_message(self, *_): |
| 27 | pass |
| 28 | |
| 29 | |
| 30 | def main(): |
| 31 | parser = argparse.ArgumentParser() |
| 32 | parser.add_argument('--caddy', required=True, type=Path) |
| 33 | args = parser.parse_args() |
| 34 | with tempfile.TemporaryDirectory(prefix='snowglobe-router-cookies-') as temporary, ThreadingHTTPServer(('127.0.0.1', 0), Cookies) as backend: |
| 35 | root = Path(temporary) |
| 36 | (root / 'stages').mkdir() |
| 37 | (root / 'stages/shale-preview-1234abcd.json').write_text(json.dumps({'sourceId': 'shale'})) |
| 38 | static = root / 'static' |
| 39 | static.mkdir() |
| 40 | (static / 'nsv.woff2').write_bytes(b'public font fixture') |
| 41 | (static / 'font.css').write_text('@font-face { font-family: fixture; }') |
| 42 | routes = root / 'routes' |
| 43 | routes.mkdir() |
| 44 | for service in ('copyparty', 'copyparty-preview-1234abcd', 'plain'): |
| 45 | (routes / (service + '.json')).write_text(json.dumps({'dirs': {'/.static/': str(static)}})) |
| 46 | proof = root / 'proof' |
| 47 | proof.write_text('a' * 64) |
| 48 | environment = {**os.environ, 'SNOWGLOBE_DOMAIN': 'snowglobe.test', 'SNOWGLOBE_DASHBOARD_PORT': str(backend.server_port), |
| 49 | 'SNOWGLOBE_STATE': str(root), |
| 50 | 'SNOWGLOBE_PROXY_TOKEN_FILE': str(proof), 'XDG_DATA_HOME': str(root / 'data'), |
| 51 | 'XDG_CONFIG_HOME': str(root / 'config')} |
| 52 | environment.pop('SNOWGLOBE_INTERNAL_PORT', None) |
| 53 | |
| 54 | def nomad(path, _): |
| 55 | if path == '/v1/services': |
| 56 | return [{'Namespace': 'default', 'Services': [{'ServiceName': name} for name in ('knife', 'plain', 'shale', 'shale-preview-1234abcd', 'copyparty', 'copyparty-preview-1234abcd')]}] |
| 57 | if path.startswith('/v1/service/'): |
| 58 | service = path.rsplit('/', 1)[1] |
| 59 | return [{'ServiceName': service, 'JobID': service, 'AllocID': service, 'Address': '127.0.0.1', |
| 60 | 'Port': backend.server_port, 'Tags': ['caddy-host=' + service + '.snowglobe.test'] + |
| 61 | (['caddy-secure-cookies=true'] if service == 'knife' else [])}] |
| 62 | return {'http': {'Status': 'success'}} |
| 63 | |
| 64 | with patch.dict(os.environ, environment, clear=True), patch.object(router, 'nomad', nomad), patch.object(router, 'ROUTE_DIR', str(root / 'routes')): |
| 65 | rendered = router.render('fixture') |
| 66 | assert rendered.count('header >Set-Cookie') == 1 |
| 67 | configuration = root / 'routes.caddy' |
| 68 | configuration.write_text('{\n admin off\n auto_https off\n skip_install_trust\n}\n' + rendered) |
| 69 | adapted = subprocess.run([str(args.caddy), 'adapt', '--config', str(configuration), '--adapter', 'caddyfile'], check=True, capture_output=True, text=True, env=environment) |
| 70 | assert '"deferred":true' in adapted.stdout.replace(' ', '') |
| 71 | subprocess.run([str(args.caddy), 'validate', '--config', str(configuration), '--adapter', 'caddyfile'], check=True, capture_output=True, env=environment) |
| 72 | with socket.socket() as listener: |
| 73 | listener.bind(('127.0.0.1', 0)) |
| 74 | port = listener.getsockname()[1] |
| 75 | runtime = root / 'Caddyfile' |
| 76 | sites = rendered.split('auth.snowglobe.test {', 1)[0] |
| 77 | sites = sites.replace('knife.snowglobe.test {', f'http://127.0.0.1:{port} {{').replace('plain.snowglobe.test {', f'http://localhost:{port} {{').replace(' tls internal\n', '') |
| 78 | sites = sites.replace('shale.snowglobe.test {', f'http://shale.localhost:{port} {{').replace('shale-preview-1234abcd.snowglobe.test {', f'http://preview.localhost:{port} {{') |
| 79 | sites = sites.replace('copyparty.snowglobe.test {', f'http://files.localhost:{port} {{').replace('copyparty-preview-1234abcd.snowglobe.test {', f'http://preview-files.localhost:{port} {{') |
| 80 | runtime.write_text('{\n admin off\n auto_https off\n}\n' + sites) |
| 81 | threading.Thread(target=backend.serve_forever, daemon=True).start() |
| 82 | with (root / 'caddy.log').open('w') as log: |
| 83 | caddy = subprocess.Popen([str(args.caddy), 'run', '--config', str(runtime), '--adapter', 'caddyfile'], stdout=log, stderr=log, env=environment) |
| 84 | try: |
| 85 | deadline = time.monotonic() + 10 |
| 86 | while True: |
| 87 | try: |
| 88 | connection = HTTPConnection('127.0.0.1', port, timeout=1) |
| 89 | connection.request('GET', '/') |
| 90 | response = connection.getresponse() |
| 91 | response.read() |
| 92 | connection.close() |
| 93 | break |
| 94 | except OSError: |
| 95 | assert caddy.poll() is None and time.monotonic() < deadline, (root / 'caddy.log').read_text() |
| 96 | time.sleep(0.05) |
| 97 | for host in ('127.0.0.1', 'localhost'): |
| 98 | for path in ('/', '/logout'): |
| 99 | connection = HTTPConnection('127.0.0.1', port, timeout=2) |
| 100 | connection.request('GET', path, headers={'Host': f'{host}:{port}'}) |
| 101 | response = connection.getresponse() |
| 102 | cookies = [value for key, value in response.getheaders() if key.lower() == 'set-cookie'] |
| 103 | assert response.status == (204 if path == '/logout' else 200) |
| 104 | assert cookies == ['session=fixture; HttpOnly; Path=/' + ('; Secure' if host == '127.0.0.1' else ''), |
| 105 | 'other=fixture; SameSite=Lax' + ('; Secure' if host == '127.0.0.1' else '')], cookies |
| 106 | response.read() |
| 107 | connection.close() |
| 108 | for host in ('files.localhost', 'preview-files.localhost', 'localhost'): |
| 109 | for path in ('/.static/nsv.woff2', '/.static/font.css', '/media/nsv.woff2'): |
| 110 | for method in ('GET', 'HEAD') if path.startswith('/.static/') else ('GET',): |
| 111 | connection = HTTPConnection('127.0.0.1', port, timeout=2) |
| 112 | connection.request(method, path, headers={'Host': f'{host}:{port}', 'Origin': 'https://sign-in.example'}) |
| 113 | response = connection.getresponse() |
| 114 | assert response.status == 200 |
| 115 | expected = '*' if host != 'localhost' and path == '/.static/nsv.woff2' else None |
| 116 | assert response.getheader('Access-Control-Allow-Origin') == expected, (host, path, method) |
| 117 | assert response.getheader('Access-Control-Allow-Credentials') is None |
| 118 | body = response.read() |
| 119 | if path == '/.static/nsv.woff2': |
| 120 | assert body == (b'public font fixture' if method == 'GET' else b'') |
| 121 | connection.close() |
| 122 | for service, host in (('shale', 'shale.localhost'), ('shale-preview-1234abcd', 'preview.localhost')): |
| 123 | origin = f'https://{service}.snowglobe.test/' |
| 124 | for referer in (None, '', '/', 'https://foreign.invalid/', origin[:-1] + '.foreign.invalid/', origin + 'bad%escape', origin, origin + 'home-infra/issues/50?q=is%3Aopen&limit=10'): |
| 125 | for path in ('/-/login', '/-/settings'): |
| 126 | headers = {'Host': f'{host}:{port}', 'Accept': 'application/json'} |
| 127 | if referer is not None: |
| 128 | headers['Referer'] = referer |
| 129 | connection = HTTPConnection('127.0.0.1', port, timeout=2) |
| 130 | connection.request('GET', path, headers=headers) |
| 131 | response = connection.getresponse() |
| 132 | expected = referer or '' |
| 133 | if path == '/-/login' and referer not in (origin, origin + 'home-infra/issues/50?q=is%3Aopen&limit=10'): |
| 134 | expected = origin |
| 135 | assert response.status == 200 |
| 136 | assert response.getheader('X-Fixture-Referer') == expected, (service, path, referer) |
| 137 | response.read() |
| 138 | connection.close() |
| 139 | finally: |
| 140 | caddy.terminate() |
| 141 | caddy.wait(timeout=10) |
| 142 | backend.shutdown() |
| 143 | print(json.dumps({'generated_config': 'validated', 'multiple_cookies': 'secure', 'logout_cookies': 'secure', 'default_route': 'unchanged', 'shale_login_return': 'same-origin URL or home', 'font_cors': 'public Copyparty static fonts only'})) |
| 144 | |
| 145 | |
| 146 | if __name__ == '__main__': |
| 147 | main() |