interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / infra / test / sandbox-integrated.py
| 1 | #!/usr/bin/env python3 |
| 2 | """External HTTP/fixture oracle for the integrated head, not product code.""" |
| 3 | import base64 |
| 4 | import hashlib |
| 5 | import http.client |
| 6 | import json |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import re |
| 10 | import shutil |
| 11 | import subprocess |
| 12 | import sys |
| 13 | import time |
| 14 | import urllib.parse |
| 15 | |
| 16 | T, ROOT, PORT = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]) |
| 17 | H, DATA = T/'home', T/'home/forge-data' |
| 18 | RID = 'z631r2JJiVT8it4tST7RK24hpowi' |
| 19 | REPO = H/'.radicle/storage'/RID |
| 20 | NID = 'z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK' |
| 21 | OMC = Path(os.environ['HOME'])/'work/flux/omega-mv/seed/out/omc' |
| 22 | PREFIX = '/drakestapleton/cuda-crack' |
| 23 | records = {} |
| 24 | |
| 25 | def git(*args, data=None): |
| 26 | return subprocess.check_output(['git', '-C', str(REPO), *args], input=data).decode().strip() |
| 27 | |
| 28 | def req(path, method='GET', fields=None, cookie=None, base='/', accept=None): |
| 29 | headers = {'X-Forge-Base': base, 'X-Real-IP': '127.0.0.1'} |
| 30 | if cookie: |
| 31 | headers['Cookie'] = cookie |
| 32 | if accept: |
| 33 | headers['Accept'] = accept |
| 34 | data = urllib.parse.urlencode(fields).encode() if fields else None |
| 35 | if data: |
| 36 | headers['Content-Type'] = 'application/x-www-form-urlencoded' |
| 37 | conn = http.client.HTTPConnection('127.0.0.1', PORT, timeout=20) |
| 38 | try: |
| 39 | conn.request(method, path, body=data, headers=headers) |
| 40 | res = conn.getresponse() |
| 41 | return res.status, dict(res.getheaders()), res.read() |
| 42 | finally: |
| 43 | conn.close() |
| 44 | |
| 45 | def start(mode, label=None): |
| 46 | label = label or mode |
| 47 | log = (T/f'integrated-{label}-server.log').open('wb') |
| 48 | command = [str(T/'forged')] |
| 49 | if mode == 'sandbox': |
| 50 | snap = Path(os.environ['FORGED_PUBLIC_DIR'])/'counts.snapshot' |
| 51 | tmp = snap.with_suffix('.new') |
| 52 | with tmp.open('wb') as out: |
| 53 | subprocess.run([T/'forged', '--counts-snapshot', T/'owner-counts.log'], stdout=out, check=True) |
| 54 | tmp.replace(snap) |
| 55 | command = ['bash', str(ROOT/'infra/spark/forged-sandbox.sh'), *command] |
| 56 | command = ['strace', '-f', '-e', 'trace=file,process,network', '-o', str(T/f'integrated-{label}.strace'), *command] |
| 57 | p = subprocess.Popen(command, stdout=log, stderr=log, start_new_session=True, |
| 58 | env=dict(os.environ, FORGE_SOCIAL_DIR=str(DATA)+'/', FORGED_LISTEN_PORT=str(PORT))) |
| 59 | for _ in range(100): |
| 60 | assert p.poll() is None |
| 61 | try: |
| 62 | if req('/')[0] == 200: |
| 63 | return p, log |
| 64 | except (OSError, http.client.HTTPException): |
| 65 | pass |
| 66 | time.sleep(.05) |
| 67 | raise AssertionError('private integrated server did not answer') |
| 68 | |
| 69 | def stop(p, log): |
| 70 | import signal |
| 71 | os.killpg(p.pid, signal.SIGTERM) |
| 72 | p.wait(timeout=10) |
| 73 | log.close() |
| 74 | for _ in range(100): |
| 75 | try: |
| 76 | req('/') |
| 77 | except (OSError, http.client.HTTPException): |
| 78 | return |
| 79 | time.sleep(.05) |
| 80 | raise AssertionError('private integrated server did not stop') |
| 81 | |
| 82 | # Minimal, inspectable Radicle COB fixture. The server replays the numeric JSON |
| 83 | # blobs from this bare repository. This does not claim Radicle signature validity. |
| 84 | head = git('rev-parse', 'main') |
| 85 | tree = git('rev-parse', 'main^{tree}') |
| 86 | canon = f'commit={head}\ntree={tree}\ncmd=fixture\nrc=0\nout={hashlib.sha256(b"fixture").hexdigest()}\nagent=fixture\n' |
| 87 | receipt = 'FORGE-EVIDENCE v1\n'+canon+'bind='+hashlib.sha256(canon.encode()).hexdigest()+'\n' |
| 88 | actions = [dict(type='edit', title='Sandbox receipt fixture'), |
| 89 | dict(type='revision', base=head, oid=head, description=receipt)] |
| 90 | entries = [] |
| 91 | for i, action in enumerate(actions): |
| 92 | blob = git('hash-object', '-w', '--stdin', data=(json.dumps(action)+'\n').encode()) |
| 93 | entries.append(f'100644 blob {blob}\t{i}\n') |
| 94 | cobtree = git('mktree', data=''.join(entries).encode()) |
| 95 | patch = git('-c', 'user.name=fixture', '-c', 'user.email=fixture@'+NID, |
| 96 | 'commit-tree', cobtree, data=b'sandbox fixture\n') |
| 97 | git('update-ref', f'refs/namespaces/{NID}/refs/cobs/xyz.radicle.patch/{patch}', patch) |
| 98 | entries = [] |
| 99 | for i, action in enumerate([dict(type='edit', title='Sandbox issue fixture'), |
| 100 | dict(type='comment', body='Private fixture issue')]): |
| 101 | blob = git('hash-object', '-w', '--stdin', data=(json.dumps(action)+'\n').encode()) |
| 102 | entries.append(f'100644 blob {blob}\t{i}\n') |
| 103 | issue_tree = git('mktree', data=''.join(entries).encode()) |
| 104 | issue = git('-c', 'user.name=fixture', '-c', 'user.email=fixture@'+NID, |
| 105 | 'commit-tree', issue_tree, data=b'sandbox issue fixture\n') |
| 106 | git('update-ref', f'refs/namespaces/{NID}/refs/cobs/xyz.radicle.issue/{issue}', issue) |
| 107 | git('tag', 'sandbox-v1', head) |
| 108 | |
| 109 | galaxy = DATA/'galaxy' |
| 110 | galaxy.mkdir(exist_ok=True) |
| 111 | with (T/'galaxy-filter').open('wb') as out: |
| 112 | source = (ROOT/'galaxy/page.om').read_bytes() + (ROOT/'galaxy/cli.om').read_bytes() |
| 113 | subprocess.run([OMC], input=source, stdout=out, check=True) |
| 114 | (T/'galaxy-filter').chmod(0o755) |
| 115 | for arg, target in [(b'R\tcuda-crack\tcore\n', 'index.html'), (b'css', 'galaxy.css')]: |
| 116 | (galaxy/target).write_bytes(subprocess.check_output([T/'galaxy-filter'], input=arg)) |
| 117 | shutil.copyfile(ROOT/'galaxy/tokens.css', galaxy/'tokens.css') |
| 118 | |
| 119 | key = T/'integrated-login-key' |
| 120 | subprocess.run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-f', str(key)], check=True) |
| 121 | raw = b'\xed\x01'+base64.b64decode(key.with_suffix('.pub').read_text().split()[1])[-32:] |
| 122 | number, encoded = int.from_bytes(raw, 'big'), '' |
| 123 | alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' |
| 124 | while number: |
| 125 | number, rem = divmod(number, 58) |
| 126 | encoded = alphabet[rem]+encoded |
| 127 | did = 'did:key:z'+encoded |
| 128 | |
| 129 | def fields(body): |
| 130 | return dict((a.decode(), b.decode()) for a, b in re.findall(rb'name="([^"]+)" value="([^"]*)"', body)) |
| 131 | |
| 132 | for mode in ('baseline', 'sandbox'): |
| 133 | p, log = start(mode) |
| 134 | try: |
| 135 | paths = ['/galaxy/', '/assets/galaxy.css', '/assets/tokens.css', '/explore.json', |
| 136 | PREFIX+'.json', PREFIX+'/patches/'+patch+'.receipt'] |
| 137 | bodies = {} |
| 138 | for path in paths: |
| 139 | status, headers, body = req(path) |
| 140 | assert status == 200, (path, status, body[:200]) |
| 141 | if path.endswith(('.json', '.receipt')): |
| 142 | doc = json.loads(body) |
| 143 | if path.endswith('.receipt'): |
| 144 | assert doc['verify'] == 'PASS', doc |
| 145 | assert doc['commit'] == head |
| 146 | bodies[path] = body |
| 147 | print('PASS', mode, path, 'sha256='+hashlib.sha256(body).hexdigest()) |
| 148 | if mode == 'baseline': |
| 149 | records = bodies |
| 150 | else: |
| 151 | for path in paths: |
| 152 | assert records[path] == bodies[path], ('parity', path) |
| 153 | print('PASS integrated public route byte parity') |
| 154 | assert req('/notifications.json')[0] == 401 |
| 155 | status, headers, body = req('/login') |
| 156 | assert status == 200 |
| 157 | f = fields(body) |
| 158 | pre = headers['Set-Cookie'].split(';')[0] |
| 159 | signature = subprocess.check_output(['ssh-keygen', '-Y', 'sign', '-f', str(key), '-n', 'interplane-forge'], |
| 160 | input=f'interplane-forge-login:{f["nonce"]}:{f["ts"]}'.encode(), stderr=subprocess.DEVNULL).decode() |
| 161 | status, headers, body = req('/login', 'POST', dict(csrf=f['csrf'], nonce=f['nonce'], ts=f['ts'], |
| 162 | did=did, sig=signature), cookie=pre) |
| 163 | assert status == 303, (status, body) |
| 164 | cookie = headers['Set-Cookie'].split(';')[0] |
| 165 | status, _, body = req('/settings', cookie=cookie) |
| 166 | assert status == 200 |
| 167 | assert req('/settings/name', 'POST', dict(csrf=fields(body)['csrf'], name='sandbox-user'), cookie=cookie)[0] == 303 |
| 168 | # Remove only this fixture's previous mode's subscription/digest. |
| 169 | shutil.rmtree(DATA/'quiet', ignore_errors=True) |
| 170 | for base in ('/', '/forge/'): |
| 171 | status, _, body = req('/notifications', cookie=cookie, base=base) |
| 172 | assert status == 200 and b'No digest file' in body |
| 173 | status, _, body = req('/notifications.json', cookie=cookie, base=base) |
| 174 | assert status == 200 and json.loads(body)['quiet'] is True |
| 175 | assert not (DATA/'quiet/out/sandbox-user').exists() |
| 176 | status, _, body = req('/notifications', cookie=cookie) |
| 177 | assert req('/notifications', 'POST', dict(csrf=fields(body)['csrf'], agent='fixture', repo='cuda-crack'), cookie=cookie)[0] == 303 |
| 178 | digest = DATA/'quiet/out/sandbox-user' |
| 179 | assert digest.is_file() |
| 180 | saved = digest.read_bytes() |
| 181 | assert req('/notifications.json', cookie=cookie)[0] == 200 |
| 182 | assert digest.read_bytes() == saved |
| 183 | print('PASS', mode, 'signed-in quiet pages, JSON, filter save and read-only digest read') |
| 184 | if mode == 'sandbox': |
| 185 | subprocess.run([sys.executable, str(ROOT/'server/tests/jsonpages.py'), str(PORT), '0', |
| 186 | str(ROOT/'docs/API.md'), 'omega-pearl,aien-crypto', '1'], check=True) |
| 187 | finally: |
| 188 | stop(p, log) |
| 189 | |
| 190 | # Compatibility challenge: the same integrated binary sees valid positive count |
| 191 | # inputs outside the sandbox. These are fixtures, never the live logs or node. |
| 192 | inputs = H/'count-inputs' |
| 193 | inputs.mkdir(exist_ok=True) |
| 194 | for prog in ('rad', 'getent'): |
| 195 | shutil.copyfile(ROOT/'server/tests/fake'/prog, inputs/prog) |
| 196 | (inputs/prog).chmod(0o755) |
| 197 | (inputs/'wal').touch() |
| 198 | (inputs/'dl.log').write_text(f'1794162545.332 203.0.113.5 200 "/rad/{RID}.git/info/refs?service=git-upload-pack" "git/2.56.0"\n') |
| 199 | (inputs/'access.log').write_text(f'127.0.0.1 - - [08/Nov/2026:05:57:35 -0600] "POST /rad/{RID}.git/git-upload-pack HTTP/2.0" 200 145 "-" "git/2.43.0"\n') |
| 200 | with (DATA/'logs/forged.log').open('a') as f: |
| 201 | f.write(f'1794162545 203.0.113.5 1 {PREFIX}/archive/refs/heads/main.zip 200 1000 5\n') |
| 202 | f.write(f'1794162546 203.0.113.6 1 {PREFIX}/releases/download/v1/asset.zip 200 1000 5\n') |
| 203 | counts = {} |
| 204 | count_html = {} |
| 205 | for mode in ('baseline', 'sandbox'): |
| 206 | (DATA/'counts.log').unlink(missing_ok=True) |
| 207 | (T/'owner-counts.log').unlink(missing_ok=True) |
| 208 | p, log = start(mode, mode+'-counts') |
| 209 | try: |
| 210 | status, _, body = req(PREFIX+'.json') |
| 211 | assert status == 200 |
| 212 | counts[mode] = json.loads(body)['counts'] |
| 213 | # Collection time can differ by the snapshot interval; every count and source is exact. |
| 214 | counts[mode]['seeds']['as_of'] = None |
| 215 | v = counts[mode] |
| 216 | assert [v['git_fetches']['count'], v['upload_pack_requests']['count'], v['downloads']['archives'], |
| 217 | v['downloads']['release_assets'], v['seeds']['count']] == [1,None,1,1,None], v |
| 218 | status, _, html = req(PREFIX) |
| 219 | assert status == 200 |
| 220 | (T/f'integrated-counts-{mode}.html').write_bytes(html) |
| 221 | count_html[mode] = re.sub(rb'read [0-9-]+ [0-9:]+ UTC', b'read COLLECTION_TIME UTC', html) |
| 222 | finally: |
| 223 | stop(p, log) |
| 224 | (T/'integrated-counts-comparison.json').write_text(json.dumps(counts, indent=2)+'\n') |
| 225 | if counts['baseline'] != counts['sandbox']: |
| 226 | # Inspect the installed Radicle command against an empty PRIVATE home only. |
| 227 | # Never lend the child an owner identity or an owner node control socket. |
| 228 | private_home = T/'routing-probe-home' |
| 229 | private_home.mkdir() |
| 230 | rad = Path(os.environ['HOME'])/'.radicle/bin/rad' |
| 231 | command = ['strace', '-f', '-e', 'trace=file,process,network', '-o', str(T/'routing-probe.strace'), |
| 232 | str(rad), 'node', 'routing', '--rid', 'rad:'+RID, '--json'] |
| 233 | r = subprocess.run(command, env=dict(HOME=str(private_home), RAD_HOME=str(private_home/'.radicle'), |
| 234 | PATH='/usr/bin:/bin'), capture_output=True, timeout=20) |
| 235 | (T/'routing-probe.command').write_text(' '.join(command)+'\n') |
| 236 | (T/'routing-probe.exit').write_text(str(r.returncode)+'\n') |
| 237 | (T/'routing-probe.log').write_bytes(r.stdout+r.stderr) |
| 238 | print('BLOCKED integrated count parity: private nginx logs and Radicle routing inputs are outside the approved export') |
| 239 | print(json.dumps(counts, sort_keys=True)) |
| 240 | sys.exit(4) |
| 241 | assert count_html['baseline'] == count_html['sandbox'], 'positive HTML count parity' |
| 242 | print('PASS integrated positive HTML and JSON count parity: git=1 upload=1 archives=1 assets=1 seeds=3') |