interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / test-agora-deploy.py

147 lines · 7666 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Isolated local integration oracle; starts only loopback test listeners.
3NGINX_BIN names an installed nginx binary. Optional argv[1] replaces the route snippet.
4No live configuration, profile data or recovery material is read or changed.
5"""
6import http.server
7import os
8from pathlib import Path
9import socket
10import subprocess
11import sys
12import tempfile
13import threading
14import time
15
16ROOT = Path(__file__).resolve().parents[1]
17DEPLOY = ROOT / 'om/agora/deploy'
18seen = []
19
20class Upstream(http.server.BaseHTTPRequestHandler):
21 def do_GET(self):
22 seen.append((self.command, self.path, dict(self.headers), getattr(self, 'body', b'')))
23 self.send_response(200)
24 self.end_headers()
25 self.wfile.write(b'registration oracle\n')
26 def do_POST(self):
27 self.body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
28 self.do_GET()
29 def log_message(self, *_):
30 pass
31
32def port():
33 with socket.socket() as s:
34 s.bind(('127.0.0.1', 0))
35 return s.getsockname()[1]
36
37with tempfile.TemporaryDirectory(prefix='agora-nginx-') as td:
38 tmp = Path(td)
39 backend = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Upstream)
40 threading.Thread(target=backend.serve_forever, daemon=True).start()
41 proxy, plain = port(), port()
42 routes = Path(sys.argv[1]).read_text() if len(sys.argv) > 1 else (DEPLOY / 'nginx-agora.conf').read_text()
43 (tmp / 'upstream.conf').write_text(f'server 127.0.0.1:{backend.server_port};\n')
44 http = (DEPLOY / 'nginx-agora-http.conf').read_text().replace('/etc/nginx/snippets/agora-upstream.conf', str(tmp / 'upstream.conf'))
45 config = tmp / 'nginx.conf'
46 config.write_text(f'''pid {tmp}/pid;
47error_log {tmp}/error.log debug;
48worker_processes 1;
49events {{ worker_connections 128; }}
50http {{
51fastcgi_temp_path {tmp}/fastcgi;
52uwsgi_temp_path {tmp}/uwsgi;
53scgi_temp_path {tmp}/scgi;
54access_log {tmp}/access.log;
55client_body_temp_path {tmp}/body;
56proxy_temp_path {tmp}/proxy;
57{http}
58server {{
59listen 127.0.0.1:{proxy} proxy_protocol;
60listen 127.0.0.1:{plain};
61server_name localhost;
62{routes}
63# A hostile sibling regex must not override the API prefix boundary.
64location ~ /agora/api/ {{ return 418; }}
65location / {{ return 200 'logging control'; }}
66}}
67}}
68''')
69 nginx = os.environ.get('NGINX_BIN', 'nginx')
70 version = subprocess.run([nginx, '-V'], capture_output=True, text=True, check=True)
71 assert '--with-debug' in version.stderr, 'INVALID: debug-capable nginx required'
72 args = [nginx, '-p', td + '/', '-c', str(config)]
73 subprocess.run(args + ['-t'], check=True)
74 proc = subprocess.Popen(args + ['-g', 'daemon off;'], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
75 def request(path, method='GET', identity='198.51.100.7', body=b'', spoof='203.0.113.99'):
76 target = proxy if identity is not None else plain
77 with socket.create_connection(('127.0.0.1', target), timeout=5) as s:
78 if identity is not None:
79 s.sendall(f'PROXY TCP4 {identity} 127.0.0.1 12345 {proxy}\r\n'.encode())
80 s.sendall((f'{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nX-Real-IP: {spoof}\r\nX-Forwarded-For: {spoof}\r\nContent-Length: {len(body)}\r\n\r\n').encode() + body)
81 data = b''
82 while True:
83 chunk = s.recv(65536)
84 if not chunk:
85 break
86 data += chunk
87 head = data.split(b'\r\n\r\n')[0].decode()
88 return int(head.split()[1]), head.lower()
89 def expect(path, status, **kwargs):
90 before = len(seen)
91 actual, headers = request(path, **kwargs)
92 assert actual == status, (path, kwargs, status, actual)
93 assert 'cache-control: no-store' in headers, (path, headers)
94 assert 'x-content-type-options: nosniff' in headers, (path, headers)
95 assert len(seen) == before + (1 if status == 200 else 0), (path, 'unexpected upstream traffic')
96 try:
97 for _ in range(100):
98 try:
99 with socket.create_connection(('127.0.0.1', plain), timeout=.1):
100 break
101 except OSError:
102 if proc.poll() is not None:
103 raise RuntimeError(proc.stderr.read().decode())
104 time.sleep(.02)
105 allowed = [('/agora/api/challenge', 'GET'), ('/agora/api/hello', 'POST'), ('/agora/api/agent/0123456789abcdef', 'GET')]
106 for path, method in allowed:
107 expect(path, 200, method=method)
108 assert seen[-1][2]['X-Real-IP'] == '198.51.100.7'
109 assert 'X-Forwarded-For' not in seen[-1][2]
110 expect(path, 503, method=method, identity=None)
111 for wrong in ['HEAD', 'PUT', 'DELETE', 'OPTIONS', 'GET' if method == 'POST' else 'POST']:
112 expect(path, 405, method=wrong)
113 for path in ['/agora/api', '/agora/api/post', '/agora/api/import', '/agora/api/note', '/agora/api/peer', '/agora/api/stream', '/agora/api/challenge/extra', '/agora/api/hello/', '/agora/api/agent/0123456789abcdef/extra', '/agora/api/agent/ABCDEF0123456789', '/agora/api/agent/0123']:
114 expect(path, 404)
115 accepted = b'public-accepted-profile-sentinel;synthetic-recovery-sentinel=' + b'x' * 100
116 expect('/agora/api/hello', 200, method='POST', body=accepted)
117 assert seen[-1][3] == accepted, 'accepted body changed upstream'
118 bounded = accepted.ljust(16384, b'x')
119 expect('/agora/api/hello', 200, method='POST', body=bounded)
120 assert seen[-1][3] == bounded, 'upper-bound accepted body changed upstream'
121 expect('/agora/api/hello', 413, method='POST', body=b'public-privacy-sentinel' * 1024)
122 for i in range(25):
123 before = len(seen)
124 status, headers = request('/agora/api/challenge', identity='198.51.100.8', spoof=f'203.0.113.{i}')
125 assert status in (200, 429)
126 assert len(seen) == before + (1 if status == 200 else 0), 'rate refusal reached upstream'
127 if status == 429:
128 assert 'cache-control: no-store' in headers and 'x-content-type-options: nosniff' in headers
129 break
130 else:
131 raise AssertionError('forged headers escaped same-client quota')
132 expect('/agora/api/challenge', 200, identity='198.51.100.9')
133 request('/logging-control', identity=None)
134 # nginx flushes the unbuffered access log before the response is complete.
135 access = (tmp / 'access.log').read_text()
136 assert '/logging-control' in access, 'logging negative control did not log'
137 assert '/agora/api' not in access, 'API leaked into inherited access log'
138 debug = (tmp / 'error.log').read_text()
139 assert 'http request line: "GET /logging-control HTTP/1.1"' in debug, 'INVALID: debug logging control inactive'
140 for sentinel in ['public-privacy-sentinel', 'public-accepted-profile-sentinel', 'synthetic-recovery-sentinel']:
141 assert sentinel not in debug, 'synthetic request body leaked to debug log'
142 assert not list((tmp / 'body').glob('*')), 'retained temporary request body'
143 print('AGORA DEPLOY PASS exact routes/methods, no upstream on refusal, non-PROXY refusal, spoof identity/quota, response privacy headers, API access-log exclusion. Synthetic request-body sentinels absent from observed debug log; debug active. Suppression causality not established (override-removal mutant survived). No retained body files; transient spill and secret-bearing response logs not qualified.')
144 finally:
145 proc.terminate()
146 proc.communicate(timeout=10)
147 backend.shutdown()