aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / scripts / test-agora-activation.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Root-only isolated activation rehearsal and private browser control. |
| 3 | |
| 4 | Only the Fixture adapter performs mutations. All observations use the same |
| 5 | file-backed code intended for live activation; no production paths are accepted. |
| 6 | """ |
| 7 | import argparse |
| 8 | from concurrent.futures import ThreadPoolExecutor |
| 9 | import hashlib |
| 10 | import json |
| 11 | import os |
| 12 | from pathlib import Path |
| 13 | import signal |
| 14 | import socket |
| 15 | import sys |
| 16 | |
| 17 | from agora_activation_namespace import Fixture |
| 18 | from agora_activation_observers import Commands, Observers, Refused, properties, save_private |
| 19 | |
| 20 | |
| 21 | class Rehearsal: |
| 22 | def __init__(self, args): |
| 23 | self.root = Path(args.root) |
| 24 | self.root.mkdir(mode=0o700, parents=True, exist_ok=False) |
| 25 | self.run = Commands() |
| 26 | self.fixture = Fixture(self.root, Path(args.backend), Path(args.nginx), self.run, |
| 27 | Path(args.page), Path(args.client)) |
| 28 | self.native, self.startup = args.native, args.startup |
| 29 | self.gates = [] |
| 30 | self.keys = [] |
| 31 | self.pre_browser_passed = False |
| 32 | self.browser_passed = False |
| 33 | self.markers = [b'ACTIVATION_PUBLIC_BODY_SENTINEL', |
| 34 | b'ACTIVATION_SYNTHETIC_KEY_SENTINEL'] |
| 35 | self.config = {} |
| 36 | prefix = self.fixture.command([]) |
| 37 | self.observer = Observers(self.run, self.native, self.startup, prefix=prefix) |
| 38 | self.pid = None |
| 39 | |
| 40 | def setup(self): |
| 41 | self.config = self.fixture.setup() |
| 42 | |
| 43 | def gate(self, name, value=None): |
| 44 | self.gates.append({'gate': name, 'status': 'PASS', 'observation': value}) |
| 45 | |
| 46 | def startup_check(self, narrow=False): |
| 47 | self.pid = self.observer.startup(self.config['unit'], |
| 48 | self.config['executable'], |
| 49 | self.config['backend_host'] + ':' + str(self.config['backend_port'])) |
| 50 | self.observer.effective(self.config, self.pid, |
| 51 | '127.0.0.1' if narrow else None) |
| 52 | return self.pid |
| 53 | |
| 54 | def direct(self, source): |
| 55 | return self.run(self.fixture.command(['curl', '--silent', '--show-error', |
| 56 | '--max-time', '5', '--interface', source, '--output', '/dev/null', |
| 57 | '--write-out', '%{http_code}', |
| 58 | 'http://' + self.config['backend_host'] + ':' + |
| 59 | str(self.config['backend_port']) + '/agora/api/challenge']), check=False) |
| 60 | |
| 61 | def request(self, path, method='GET', body=None, plain=False, headers=()): |
| 62 | base = self.config['plain_url'] if plain else self.config['tls_url'] |
| 63 | argv = ['curl', '--silent', '--show-error', '--max-time', '10', |
| 64 | '--insecure', '--noproxy', '*', '--include'] |
| 65 | if not plain and self.config.get('curl_resolve'): |
| 66 | argv += ['--resolve', self.config['curl_resolve']] |
| 67 | argv += ['--head'] if method == 'HEAD' else ['--request', method] |
| 68 | for header in headers: |
| 69 | argv += ['--header', header] |
| 70 | if body is not None: |
| 71 | argv += ['--data-binary', '@-'] |
| 72 | argv.append(base.rstrip('/') + path) |
| 73 | result = self.run(argv, input=body, private=True) |
| 74 | head, separator, content = result.stdout.partition(b'\r\n\r\n') |
| 75 | if not separator: |
| 76 | raise Refused('Incomplete actual TLS HTTP response') |
| 77 | status = int(head.splitlines()[0].split()[1]) |
| 78 | fields = {} |
| 79 | for line in head.splitlines()[1:]: |
| 80 | key, sep, value = line.partition(b':') |
| 81 | if not sep: |
| 82 | raise Refused('Malformed HTTP header') |
| 83 | fields.setdefault(key.lower(), []).append(value.strip().lower()) |
| 84 | return status, fields, content |
| 85 | |
| 86 | @staticmethod |
| 87 | def expected(response, code): |
| 88 | status, headers, _ = response |
| 89 | if status != code: |
| 90 | raise Refused('HTTP expected ' + str(code) + ', observed ' + str(status)) |
| 91 | if headers.get(b'cache-control') != [b'no-store']: |
| 92 | raise Refused('No-store absent or ambiguous') |
| 93 | if headers.get(b'x-content-type-options') != [b'nosniff']: |
| 94 | raise Refused('Nosniff absent or ambiguous') |
| 95 | |
| 96 | def no_upstream(self, request): |
| 97 | expression = 'tcp dst port ' + str(self.config['backend_port']) |
| 98 | with self.observer.capture(self.config['interface'], expression) as observed: |
| 99 | response = request() |
| 100 | import re |
| 101 | if any(int(size) > 0 for size in re.findall(r'\blength (\d+)\b', observed['packets'])): |
| 102 | raise Refused('Blocked route generated upstream payload') |
| 103 | return response |
| 104 | |
| 105 | def pre_browser(self): |
| 106 | self.observer.copied_artifacts(self.config['copied_artifacts']) |
| 107 | self.gate('copied backend/page/client exact source bytes, root ownership and regular-file modes') |
| 108 | self.startup_check() |
| 109 | self.gate('bounded startup/effective native guards/current namespace/cgroup BPF') |
| 110 | # Independently establish .3 reachability to this exact endpoint in a |
| 111 | # separate declared control phase, then restore the exact acceptance set. |
| 112 | self.fixture.set_policy(['127.0.0.1/32', '127.0.0.2/32', '127.0.0.3/32']) |
| 113 | self.observer.startup(self.config['unit'], self.config['executable'], |
| 114 | self.config['backend_host'] + ':' + str(self.config['backend_port'])) |
| 115 | reachable = self.observer.syn_probe(self.config, '127.0.0.3', |
| 116 | lambda: self.direct('127.0.0.3'), True) |
| 117 | self.gate('independent same-endpoint second-source reachability control', reachable) |
| 118 | self.fixture.set_policy(['127.0.0.1/32', '127.0.0.2/32']) |
| 119 | self.startup_check() |
| 120 | for source, accept in [('127.0.0.2', True), ('127.0.0.3', False)]: |
| 121 | observation = self.observer.syn_probe(self.config, source, |
| 122 | lambda source=source: self.direct(source), accept) |
| 123 | self.gate('actual source-bound packet allow/deny', observation) |
| 124 | self.fixture.set_policy(['127.0.0.1/32']) |
| 125 | self.startup_check(narrow=True) |
| 126 | self.observer.syn_probe(self.config, '127.0.0.2', |
| 127 | lambda: self.direct('127.0.0.2'), False) |
| 128 | self.gate('independent real BPF denial with no firewall mutation') |
| 129 | self.fixture.set_policy(['127.0.0.1/32', '127.0.0.2/32']) |
| 130 | self.startup_check() |
| 131 | self.observer.syn_probe(self.config, '127.0.0.2', |
| 132 | lambda: self.direct('127.0.0.2'), True) |
| 133 | self.gate('exact service policy restored and allowed source recovers') |
| 134 | self.observer.reload(self.config) |
| 135 | self.expected(self.observer.counted_get(self.config, |
| 136 | lambda: self.request('/agora/api/challenge')), 200) |
| 137 | self.gate('nginx active-worker adoption plus independently counted TLS GET') |
| 138 | refused = [('/agora/api/challenge', 'POST', 405), |
| 139 | ('/agora/api/hello', 'GET', 405), |
| 140 | ('/agora/api/agent/0123456789abcdef', 'POST', 405), |
| 141 | ('/agora/api/agent/ABCDEF0123456789', 'GET', 404), |
| 142 | ('/agora/api/agent/0123', 'GET', 404), |
| 143 | ('/agora/api/challenge/extra', 'GET', 404), |
| 144 | ('/agora/api/import', 'POST', 404), |
| 145 | ('/agora/api/hello/', 'POST', 404)] |
| 146 | refused += [(path, 'HEAD', 405) for path in ( |
| 147 | '/agora/api/challenge', '/agora/api/hello', |
| 148 | '/agora/api/agent/0123456789abcdef')] |
| 149 | refused += [(path, 'POST', 404) for path in ( |
| 150 | '/agora/api/post', '/agora/api/note', '/agora/api/peer', |
| 151 | '/agora/api/stream', '/agora/api/other')] |
| 152 | refused += [(path, 'GET', 404) for path in ( |
| 153 | '/agora/api', '/agora/api/agent/0123456789abcdef/extra')] |
| 154 | for path, method, code in refused: |
| 155 | response = self.no_upstream(lambda path=path, method=method: |
| 156 | self.request(path, method)) |
| 157 | self.expected(response, code) |
| 158 | for path, method in (('/agora/api/challenge', 'GET'), |
| 159 | ('/agora/api/hello', 'POST'), |
| 160 | ('/agora/api/agent/0123456789abcdef', 'GET')): |
| 161 | self.expected(self.no_upstream( |
| 162 | lambda path=path, method=method: self.request(path, method, plain=True)), 503) |
| 163 | oversized = self.markers[0] * 1024 |
| 164 | self.expected(self.no_upstream(lambda: self.request('/agora/api/hello', |
| 165 | 'POST', oversized)), 413) |
| 166 | self.gate('actual TLS method/id/trailing/disabled/oversize and non-PROXY refusals, zero upstream payload') |
| 167 | synthetic = b'ACTIVATION_PUBLIC_BODY_SENTINEL\nkey ACTIVATION_SYNTHETIC_KEY_SENTINEL\n' |
| 168 | self.observer.effective_logging(self.config) |
| 169 | self.expected(self.request('/agora/api/hello', 'POST', synthetic), 400) |
| 170 | self.gate('synthetic body/key real backend failure path') |
| 171 | # Browser gates run before quota exhaustion; these requests preserve the |
| 172 | # real client bucket rather than relying on arbitrary forged headers. |
| 173 | self.observer.privacy(self.config['logs'], self.config['temp_dirs'], self.markers) |
| 174 | self.observer.journal_privacy(self.config, self.markers) |
| 175 | self.gate('effective actual fixture access/error/temp sinks have no synthetic body/key markers') |
| 176 | # Challenge the real sink scanner, not a canned privacy verdict. |
| 177 | control = Path(self.config['temp_dirs'][0]) / ('privacy-control-' + self.fixture.ident) |
| 178 | try: |
| 179 | with control.open('xb') as stream: |
| 180 | stream.write(self.markers[0]) |
| 181 | try: |
| 182 | self.observer.privacy(self.config['logs'], self.config['temp_dirs'], self.markers) |
| 183 | except Refused: |
| 184 | self.gate('privacy scanner rejects an actual marker in an effective temporary-body sink') |
| 185 | else: |
| 186 | raise Refused('Privacy scanner accepted its marker control') |
| 187 | finally: |
| 188 | control.unlink(missing_ok=True) |
| 189 | self.pre_browser_passed = True |
| 190 | return {'gates': self.gates, 'config': self.config} |
| 191 | |
| 192 | def save_key(self, key): |
| 193 | if not isinstance(key, str) or not key or '\n' in key: |
| 194 | raise Refused('Invalid private recovery material') |
| 195 | path = self.root / ('recovery-' + str(len(self.keys)) + '.key') |
| 196 | save_private(path, key) |
| 197 | if path.stat().st_uid != 0: |
| 198 | raise Refused('Recovery file is not root-owned') |
| 199 | self.keys.append(path) |
| 200 | return {'path': str(path), 'mode': '600', 'owner': 'root'} |
| 201 | |
| 202 | def restart(self): |
| 203 | self.fixture.restart_backend() |
| 204 | self.startup_check() |
| 205 | return {'status': 'READY'} |
| 206 | |
| 207 | def read_profile(self, identity): |
| 208 | if len(identity) != 16 or any(ch not in '0123456789abcdef' for ch in identity): |
| 209 | raise Refused('Malformed public profile id') |
| 210 | response = self.request('/agora/api/agent/' + identity) |
| 211 | self.expected(response, 200) |
| 212 | return response[2].decode() |
| 213 | |
| 214 | def after_browser(self, browser_result): |
| 215 | if not self.pre_browser_passed or browser_result.get('status') != 'PASS': |
| 216 | raise Refused('Full pre-browser and browser sequence must pass') |
| 217 | if not self.keys: |
| 218 | raise Refused('Browser did not preserve actual recovery material') |
| 219 | self.gate('real browser consent/ack/readback/uncertainty/durability', browser_result) |
| 220 | def burst(): |
| 221 | def forged(index): |
| 222 | response = self.request('/agora/api/challenge', headers=( |
| 223 | 'X-Real-IP: 203.0.113.' + str(index), |
| 224 | 'X-Forwarded-For: 198.51.100.' + str(index))) |
| 225 | if response[0] not in (200, 429): |
| 226 | raise Refused('Unexpected actual TLS quota response') |
| 227 | self.expected(response, response[0]) |
| 228 | return response[0] |
| 229 | with ThreadPoolExecutor(max_workers=32) as workers: |
| 230 | return list(workers.map(forged, range(1, 33))) |
| 231 | statuses = self.observer.counted_get( |
| 232 | self.config, burst, expected=lambda rows: rows.count(200)) |
| 233 | if not statuses.count(200) or not statuses.count(429): |
| 234 | raise Refused('Forged headers did not exercise the shared real-client bucket') |
| 235 | self.gate('actual TLS forged identity headers share quota; refusals produce zero upstream requests', |
| 236 | {'accepted': statuses.count(200), 'limited': statuses.count(429)}) |
| 237 | markers = self.markers + [path.read_bytes() for path in self.keys] |
| 238 | self.observer.privacy(self.config['logs'], self.config['temp_dirs'], markers) |
| 239 | self.observer.privacy(self.config['access_logs'], [], [b'/agora/api']) |
| 240 | self.observer.journal_privacy(self.config, markers) |
| 241 | self.gate('actual response recovery keys absent from every effective log/temp-body sink') |
| 242 | self.fixture.enable_backend() |
| 243 | enabled = self.run(['systemctl', 'is-enabled', self.config['unit']]) |
| 244 | if enabled.stdout.strip() != b'enabled-runtime': |
| 245 | raise Refused('Throwaway unit did not become enabled-runtime') |
| 246 | self.gate('enable only after every acceptance gate passes, isolated runtime target only') |
| 247 | self.browser_passed = True |
| 248 | return {'status': 'PASS', 'private_recovery_paths': list(map(str, self.keys))} |
| 249 | |
| 250 | def state_hashes(self): |
| 251 | root = Path(self.config['state']) |
| 252 | return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest() |
| 253 | for path in root.rglob('*') if path.is_file()} |
| 254 | |
| 255 | def rollback_proof(self): |
| 256 | if not self.browser_passed: |
| 257 | raise Refused('Entire browser, privacy and enable sequence has not passed') |
| 258 | before = self.state_hashes() |
| 259 | try: |
| 260 | raise Refused('Intentional dry-run acceptance-failure control') |
| 261 | except Refused: |
| 262 | self.fixture.rollback() |
| 263 | disabled = self.run(['systemctl', 'is-enabled', self.config['unit']], check=False) |
| 264 | if disabled.stdout.strip() != b'disabled': |
| 265 | raise Refused('Rollback did not disable the isolated unit') |
| 266 | unit = properties(self.observer.show(self.config['unit'], 'MainPID', 'ActiveState')) |
| 267 | if int(unit['MainPID']) != 0 or unit['ActiveState'] != 'inactive': |
| 268 | raise Refused('Rollback backend not stopped') |
| 269 | if self.state_hashes() != before: |
| 270 | raise Refused('Rollback changed accepted fixture profiles/state') |
| 271 | if self.request('/')[0] != 200 or self.request('/agora/api/challenge')[0] != 404: |
| 272 | raise Refused('Rollback did not preserve ordinary site and close API') |
| 273 | self.gate('injected first-failure rollback closes API/stops backend/preserves profiles/site200') |
| 274 | return {'status': 'PASS', 'state_files_retained': len(before)} |
| 275 | |
| 276 | def receipt(self, status): |
| 277 | result = {'status': status, 'scope': 'ISOLATED_NAMESPACE_ONLY_NOT_DEPLOYED', |
| 278 | 'gates': self.gates, 'commands': self.run.records, |
| 279 | 'observations': self.observer.observations, |
| 280 | 'private_state_path': str(self.root / 'retained-state'), |
| 281 | 'private_recovery_paths': list(map(str, self.keys))} |
| 282 | (self.root / 'result.json').write_text(json.dumps(result, indent=2) + '\n') |
| 283 | os.chmod(self.root / 'result.json', 0o600) |
| 284 | return result |
| 285 | |
| 286 | |
| 287 | def control(path, action): |
| 288 | payload = {'action': action} |
| 289 | if action in ('save-key', 'read-profile', 'after-browser'): |
| 290 | payload['value'] = json.loads(sys.stdin.read()) |
| 291 | with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: |
| 292 | connection.connect(path) |
| 293 | connection.sendall(json.dumps(payload).encode() + b'\n') |
| 294 | connection.shutdown(socket.SHUT_WR) |
| 295 | answer = b'' |
| 296 | while True: |
| 297 | part = connection.recv(65536) |
| 298 | if not part: |
| 299 | break |
| 300 | answer += part |
| 301 | if not answer: |
| 302 | raise Refused('Fixture control closed without an acceptance verdict') |
| 303 | response = json.loads(answer) |
| 304 | if not response['ok']: |
| 305 | raise Refused(response['error']) |
| 306 | print(json.dumps(response['result'])) |
| 307 | |
| 308 | |
| 309 | def serve(args): |
| 310 | fixture = None |
| 311 | listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 312 | def interrupted(number, _frame): |
| 313 | raise Refused('Fixture interrupted by ' + signal.Signals(number).name) |
| 314 | |
| 315 | previous = {number: signal.signal(number, interrupted) |
| 316 | for number in (signal.SIGHUP, signal.SIGINT, signal.SIGTERM)} |
| 317 | try: |
| 318 | fixture = Rehearsal(args) |
| 319 | fixture.setup() |
| 320 | listener.bind(str(fixture.root / 'control.sock')) |
| 321 | os.chmod(fixture.root / 'control.sock', 0o600) |
| 322 | listener.listen(1) |
| 323 | print('ACTIVATION_FIXTURE_READY ' + str(fixture.root / 'control.sock'), flush=True) |
| 324 | done = False |
| 325 | while not done: |
| 326 | connection, _ = listener.accept() |
| 327 | with connection: |
| 328 | raw = b'' |
| 329 | while True: |
| 330 | part = connection.recv(65536) |
| 331 | if not part: |
| 332 | break |
| 333 | raw += part |
| 334 | if len(raw) > 1048576: |
| 335 | raise Refused('Oversized private control request') |
| 336 | request = json.loads(raw) |
| 337 | action = request['action'] |
| 338 | if action == 'ready': |
| 339 | result = fixture.config |
| 340 | elif action == 'pre-browser': |
| 341 | result = fixture.pre_browser() |
| 342 | elif action == 'save-key': |
| 343 | result = fixture.save_key(request['value']) |
| 344 | elif action == 'restart-backend': |
| 345 | result = fixture.restart() |
| 346 | elif action == 'read-profile': |
| 347 | result = fixture.read_profile(request['value']) |
| 348 | elif action == 'after-browser': |
| 349 | result = fixture.after_browser(request['value']) |
| 350 | elif action == 'finish': |
| 351 | result = fixture.rollback_proof() |
| 352 | fixture.receipt('PASS') |
| 353 | done = True |
| 354 | else: |
| 355 | raise Refused('Unknown private fixture action') |
| 356 | connection.sendall(json.dumps({'ok': True, 'result': result}).encode()) |
| 357 | except Exception as error: |
| 358 | if fixture is not None: |
| 359 | try: |
| 360 | fixture.fixture.rollback() |
| 361 | except Exception as rollback_error: |
| 362 | fixture.gates.append({'gate': 'fixture rollback unavailable', |
| 363 | 'status': 'FAIL', |
| 364 | 'error': type(rollback_error).__name__ + ': ' + str(rollback_error)}) |
| 365 | finally: |
| 366 | fixture.gates.append({'gate': 'unexpected fixture failure', |
| 367 | 'status': 'FAIL', 'error': type(error).__name__ + ': ' + str(error)}) |
| 368 | fixture.receipt('FAIL') |
| 369 | raise |
| 370 | finally: |
| 371 | try: |
| 372 | listener.close() |
| 373 | if fixture is not None: |
| 374 | fixture.fixture.cleanup() |
| 375 | finally: |
| 376 | for number, handler in previous.items(): |
| 377 | signal.signal(number, handler) |
| 378 | |
| 379 | |
| 380 | def main(): |
| 381 | parser = argparse.ArgumentParser() |
| 382 | parser.add_argument('--root') |
| 383 | parser.add_argument('--backend') |
| 384 | parser.add_argument('--nginx') |
| 385 | parser.add_argument('--native') |
| 386 | parser.add_argument('--startup') |
| 387 | parser.add_argument('--page') |
| 388 | parser.add_argument('--client') |
| 389 | parser.add_argument('--control') |
| 390 | parser.add_argument('--action') |
| 391 | args = parser.parse_args() |
| 392 | if os.geteuid() != 0: |
| 393 | raise Refused('Private fixture requires root') |
| 394 | if args.control: |
| 395 | control(args.control, args.action) |
| 396 | else: |
| 397 | if not all((args.root, args.backend, args.nginx, args.native, args.startup, |
| 398 | args.page, args.client)): |
| 399 | parser.error('serve requires explicit fixture root, published page/client and pinned binaries') |
| 400 | serve(args) |
| 401 | |
| 402 | |
| 403 | if __name__ == '__main__': |
| 404 | main() |