1#!/usr/bin/env python3
2import argparse
3from contextlib import ExitStack
4from html.parser import HTMLParser
5from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6import json
7import os
8from pathlib import Path
9import socket
10import sqlite3
11import subprocess
12import tempfile
13import threading
14import time
15import urllib.error
16import urllib.request
17
18import router
19
20
21class Links(HTMLParser):
22 def __init__(self, html):
23 super().__init__()
24 self.links = []
25 self.feed(html)
26
27 def handle_starttag(self, tag, attrs):
28 if tag == 'a':
29 self.links.append(dict(attrs))
30
31
32def port():
33 with socket.socket() as sock:
34 sock.bind(('127.0.0.1', 0))
35 return sock.getsockname()[1]
36
37
38def main():
39 parser = argparse.ArgumentParser()
40 parser.add_argument('--caddy', required=True, type=Path)
41 parser.add_argument('--binary', type=Path, default=Path(__file__).resolve().parent.parent / 'dashboard/target/debug/home-dashboard')
42 parser.add_argument('--page', type=Path)
43 parser.add_argument('--browser-ready-file', type=Path)
44 args = parser.parse_args()
45 repo = Path(__file__).resolve().parent.parent
46 observations = []
47 issue = args.page.read_bytes() if args.page else b'<html><head></head><body><a href="/~guest-github-24465214"><img src="avatar"><span>~guest-github-24465214</span></a></body></html>'
48 sample = b'<a href="/~guest-astheno-abc">guest</a><a href="/~guest-github-unknown">unknown</a><a href="/~guest-github-24465214/repo">repo</a>'
49 blob = bytes(range(256)) * 65536
50
51 class Fixture(BaseHTTPRequestHandler):
52 protocol_version = 'HTTP/1.1'
53
54 def do_GET(self):
55 observations.append((self.command, self.path, {key.lower(): value for key, value in self.headers.items()}))
56 if self.path == '/binary':
57 return self.respond(blob, 'application/octet-stream')
58 if self.path == '/json':
59 return self.respond(b'{"issue":{"title":"<angle> & Unicode"}}', 'application/json; charset=utf-8')
60 if self.path == '/large':
61 return self.respond(b' ' * (9 * 1024 * 1024), 'text/html')
62 if self.path == '/-/login':
63 callback = 'https://' + self.headers['Host'] + '/-/callback'
64 return self.respond(b'', 'text/plain', 302, [('Location', 'https://snowglobe.snowglobe.test/auth/oidc/authorize?redirect_uri=' + urllib.parse.quote(callback, safe=''))])
65 if self.path == '/redirect':
66 return self.respond(b'', 'text/plain', 302, [('Location', '/snowbound/issues/26'), ('Set-Cookie', 'SessionID=new; Path=/; HttpOnly'), ('Set-Cookie', 'other=kept; Path=/')])
67 if self.path.startswith('/-/') and args.page:
68 with urllib.request.urlopen('https://shale.paperclover.net' + self.path, timeout=15) as response:
69 return self.respond(response.read(), response.headers['Content-Type'])
70 return self.respond(issue + sample, 'text/html; charset=utf-8', headers=[('ETag', '"stale"'), ('Last-Modified', 'Mon, 05 Oct 2026 00:00:00 GMT')])
71
72 def do_HEAD(self):
73 self.respond(b'', 'text/html')
74
75 def do_POST(self):
76 body = self.rfile.read(int(self.headers.get('Content-Length', 0)))
77 observations.append((self.command, self.path, {key.lower(): value for key, value in self.headers.items()}, body))
78 self.respond(body, 'application/octet-stream', 201)
79
80 def respond(self, body, content_type, status=200, headers=()):
81 self.send_response(status)
82 self.send_header('Content-Type', content_type)
83 self.send_header('Content-Length', str(len(body)))
84 for key, value in headers:
85 self.send_header(key, value)
86 self.end_headers()
87 self.wfile.write(body)
88
89 def log_message(self, *args):
90 pass
91
92 class NoRedirect(urllib.request.HTTPRedirectHandler):
93 def redirect_request(self, *args):
94 return None
95
96 opener = urllib.request.build_opener(NoRedirect)
97 with tempfile.TemporaryDirectory(prefix='shale-page-') as temporary, ExitStack() as stack:
98 root = Path(temporary).resolve()
99 fixture = ThreadingHTTPServer(('127.0.0.1', 0), Fixture)
100 stack.callback(fixture.server_close)
101 stack.callback(fixture.shutdown)
102 threading.Thread(target=fixture.serve_forever, daemon=True).start()
103 dashboard_port, gateway_port, internal_port = port(), port(), port()
104 proof = 'a' * 64
105 token = root / 'proxy.token'
106 token.write_text(proof)
107 certificate, gateway_key = root / 'gateway.pem', root / 'gateway.key'
108 subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost', '-addext', 'basicConstraints=CA:FALSE', '-keyout', str(gateway_key), '-out', str(certificate)], check=True, capture_output=True)
109 data = root / 'data'
110 data.mkdir()
111 environment = {**os.environ, 'PORT': str(dashboard_port), 'SNOWGLOBE_DOMAIN': 'snowglobe.test', 'SNOWGLOBE_DATA_DIR': str(data), 'SNOWGLOBE_PROXY_TOKEN_FILE': str(token), 'SNOWGLOBE_INTERNAL_URL': f'https://localhost:{internal_port}', 'SNOWGLOBE_CA_BUNDLE': str(certificate), 'SNOWGLOBE_REPO': str(repo), 'SNOWGLOBE_WEB_DIR': str(repo / 'dashboard/dist')}
112 for key in ['SNOWGLOBE_INDEX_POOL', 'SNOWGLOBE_AUTH_REQUIRED', 'SNOWGLOBE_YT_STATE']:
113 environment.pop(key, None)
114 log = stack.enter_context((root / 'dashboard.log').open('w'))
115 dashboard = subprocess.Popen([str(args.binary)], env=environment, stdout=log, stderr=log)
116 stack.callback(lambda: dashboard.wait(timeout=10))
117 stack.callback(dashboard.terminate)
118 deadline = time.monotonic() + 15
119 while True:
120 assert dashboard.poll() is None, (root / 'dashboard.log').read_text()
121 try:
122 with socket.create_connection(('127.0.0.1', dashboard_port), timeout=.1):
123 break
124 except OSError:
125 assert time.monotonic() < deadline
126 time.sleep(.05)
127 with sqlite3.connect(data / 'accounts.sqlite') as db:
128 for provider, subject, suffix, name in [('github', '24465214', '24465214', 'paperclover'), ('astheno', 'pairwise-astheno-subject', 'abc', 'Astheno user'), ('github', '777', '777', None), ('astheno', 'unmapped-pairwise-subject', 'unknown', 'Unmapped guest')]:
129 username = f'guest-{provider}-{suffix}'
130 profile = {'kind': 'guest', 'enabled': True, 'username': username, 'guestProvider': provider, 'firstName': name}
131 db.execute('INSERT INTO users(id,profile) VALUES (?,?)', [username, json.dumps(profile)])
132 db.execute('INSERT INTO external_identities VALUES (?,?,?)', [provider, subject, username])
133 (root / 'stages').mkdir()
134 (root / 'stages/shale-preview-12345678.json').write_text(json.dumps({'sourceId': 'shale'}))
135 os.environ.update(SNOWGLOBE_DOMAIN='snowglobe.test', SNOWGLOBE_DASHBOARD_PORT=str(dashboard_port), SNOWGLOBE_PROXY_TOKEN_FILE=str(token), SNOWGLOBE_INTERNAL_PORT=str(internal_port), SNOWGLOBE_STATE=str(root))
136 router.ROUTE_DIR = str(root / 'routes')
137 Path(router.ROUTE_DIR).mkdir()
138 (Path(router.ROUTE_DIR) / 'shale.json').write_text(json.dumps({'headHtml': {'shale.snowglobe.test': {'/snowbound/*': '<meta name="rewrite-test" content="kept">'}}}))
139
140 def nomad(path, token):
141 if path == '/v1/services':
142 return [{'Namespace': 'default', 'Services': [{'ServiceName': 'shale'}, {'ServiceName': 'shale-preview-12345678'}]}]
143 if path.startswith('/v1/service/'):
144 service = path.rsplit('/', 1)[1]
145 host = 'shale.snowglobe.test' if service == 'shale' else service + '.snowglobe.test'
146 return [{'Address': '127.0.0.1', 'Port': fixture.server_port, 'ServiceName': service, 'AllocID': service, 'JobID': service, 'Tags': ['caddy-host=' + host]}]
147 return {'ready': {'Status': 'success'}}
148
149 router.nomad = nomad
150 rendered = router.render('fixture')
151 full_config = root / 'routes.caddy'
152 full_config.write_text('{\n admin off\n auto_https off\n}\n' + rendered)
153 caddy_env = {**os.environ, 'XDG_DATA_HOME': str(root / 'caddy-data'), 'XDG_CONFIG_HOME': str(root / 'caddy-config')}
154 subprocess.run([str(args.caddy), 'validate', '--config', str(full_config), '--adapter', 'caddyfile'], check=True, capture_output=True, env=caddy_env)
155 def local_site(host, listener):
156 start = rendered.index(host + ' {')
157 end = rendered.index('\n}', start) + 2
158 return rendered[start:end].replace(host + ' {', f'http://127.0.0.1:{listener} {{', 1).replace(' tls internal\n', '').replace(' route {\n', f' route {{\n request_header Host {host}\n', 1)
159
160 preview_port = port()
161 config = '{\n admin off\n auto_https off\n}\n' + local_site('shale.snowglobe.test', gateway_port) + '\n' + local_site('shale-preview-12345678.snowglobe.test', preview_port)
162 internal_host = f'dashboard.internal.snowglobe.test:{internal_port}'
163 start = rendered.index(internal_host + ' {')
164 config += '\n' + rendered[start:].replace(internal_host + ' {', f'https://localhost:{internal_port} {{', 1).replace(' tls internal\n', f' tls {certificate} {gateway_key}\n', 1)
165 config_path = root / 'Caddyfile'
166 config_path.write_text(config)
167 subprocess.run([str(args.caddy), 'validate', '--config', str(config_path), '--adapter', 'caddyfile'], check=True, capture_output=True, env=caddy_env)
168 caddy_log = stack.enter_context((root / 'caddy.log').open('w'))
169 caddy = subprocess.Popen([str(args.caddy), 'run', '--config', str(config_path), '--adapter', 'caddyfile'], stdout=caddy_log, stderr=caddy_log, env=caddy_env)
170 stack.callback(lambda: caddy.wait(timeout=10))
171 stack.callback(caddy.terminate)
172 origin = f'http://127.0.0.1:{gateway_port}'
173
174 def request(path, *, headers=None, body=None, direct=False):
175 supplied = {'Cookie': 'SessionID=preserved', 'Origin': 'https://shale.snowglobe.test', **(headers or {})}
176 url = (f'http://127.0.0.1:{dashboard_port}' if direct else origin) + path
177 try:
178 response = opener.open(urllib.request.Request(url, headers=supplied, data=body), timeout=15)
179 except urllib.error.HTTPError as error:
180 response = error
181 with response:
182 return response.status, response.headers, response.read()
183
184 deadline = time.monotonic() + 15
185 while True:
186 try:
187 status, headers, body = request('/snowbound/issues/26?query=kept')
188 break
189 except urllib.error.URLError:
190 assert time.monotonic() < deadline and caddy.poll() is None
191 time.sleep(.05)
192 assert status == 200, (status, body, (root / 'dashboard.log').read_text(), (root / 'caddy.log').read_text())
193 links = Links(body.decode()).links
194 link = next(link for link in links if link.get('href') == 'https://github.com/paperclover')
195 assert link['target'] == '_blank' and link['rel'] == 'noreferrer', link
196 assert any(link.get('href') == '/~guest-github-unknown' for link in links)
197 assert any(link.get('href') == '/~guest-github-24465214/repo' for link in links)
198 assert b'Astheno user' in body and not any(link.get('href') == '/~guest-astheno-abc' for link in links)
199 assert b'identity.astheno.software/user/' not in body and b'pairwise-astheno-subject' not in body
200 assert b'https://avatars.githubusercontent.com/u/24465214?s=64' in body
201 assert b'rewrite-test' in body
202 assert headers['Cache-Control'] == 'no-store' and headers.get('ETag') is None and headers.get('Last-Modified') is None
203 assert observations[-1][1] == '/snowbound/issues/26?query=kept', observations[-1]
204 assert observations[-1][2]['host'] == 'shale.snowglobe.test', observations[-1]
205 assert observations[-1][2]['cookie'] == 'SessionID=preserved', observations[-1]
206 status, headers, body = request('/json', headers={'Accept': 'application/json'})
207 assert status == 200 and headers['Content-Type'].startswith('application/json')
208 assert body == b'{"issue":{"title":"<angle> & Unicode"}}'
209 assert observations[-1][2]['accept'] == 'application/json'
210 assert not any(key.lower().startswith('snowglobe-') for key in observations[-1][2]), observations[-1]
211 status, headers, body = request('/~guest-github-24465214')
212 assert status == 302 and headers['Location'] == 'https://github.com/paperclover' and headers['Referrer-Policy'] == 'no-referrer'
213 assert request('/~guest-astheno-abc/')[0] == 200
214 assert observations[-1][1] == '/~guest-astheno-abc/'
215 assert request('/~guest-astheno-unknown')[0] == 200
216 status, headers, body = request('/-/login')
217 assert status == 302 and urllib.parse.parse_qs(urllib.parse.urlparse(headers['Location']).query)['redirect_uri'] == ['https://shale.snowglobe.test/-/callback']
218 status, headers, body = request('/redirect')
219 assert status == 302 and headers['Location'] == '/snowbound/issues/26' and len(headers.get_all('Set-Cookie')) == 2
220 with opener.open(f'http://127.0.0.1:{preview_port}/snowbound/issues/26') as response:
221 assert response.status == 200
222 assert observations[-1][2]['host'] == 'shale-preview-12345678.snowglobe.test'
223 assert any(link.get('href') == 'https://github.com/paperclover' for link in Links(response.read().decode()).links)
224 assert b'/~guest-github-24465214' in request('/repo/info/refs')[2]
225 assert request('/binary')[2] == blob
226 assert len(request('/large')[2]) == 9 * 1024 * 1024
227 status, headers, body = request('/submit?keep=yes', body=b'field=unchanged')
228 assert status == 201 and body == b'field=unchanged' and observations[-1][1] == '/submit?keep=yes'
229 assert request('/submit', body=b'blocked', headers={'Origin': 'https://other.example'})[0] == 403
230 assert request('/auth/shale/page', direct=True)[0] == 403
231 assert request('/auth/shale/page', direct=True, headers={'Snowglobe-Proxy-Token': proof, 'Snowglobe-Shale-Upstream': f'127.0.0.1:{fixture.server_port}', 'Snowglobe-Shale-Uri': '/', 'Host': 'snowglobe.snowglobe.test'})[0] == 403
232 print(json.dumps({'html_links': 'passed', 'provider_redirects': 'passed', 'cookies_forms_and_binary': 'passed', 'proxy_boundary': 'passed', 'head_injection': 'passed', 'origin': origin}), flush=True)
233 if args.browser_ready_file:
234 args.browser_ready_file.write_text(json.dumps({'origin': origin}))
235 stop = args.browser_ready_file.with_suffix('.stop')
236 deadline = time.monotonic() + 600
237 while not stop.exists() and time.monotonic() < deadline:
238 time.sleep(.2)
239 args.browser_ready_file.unlink(missing_ok=True)
240 stop.unlink(missing_ok=True)
241
242
243if __name__ == '__main__':
244 main()