aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / om / hive-render / test-render.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Independent Python/HTML parser oracle; never part of the serving path.""" |
| 3 | import copy |
| 4 | import datetime |
| 5 | import html |
| 6 | from html.parser import HTMLParser |
| 7 | import json |
| 8 | from pathlib import Path |
| 9 | import subprocess |
| 10 | import sys |
| 11 | |
| 12 | BINARY, OMC, SCRATCH = map(Path, sys.argv[1:]) |
| 13 | BINARY, OMC = BINARY.resolve(), OMC.resolve() |
| 14 | |
| 15 | |
| 16 | def canonical(value): |
| 17 | return (json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')) + '\n').encode() |
| 18 | |
| 19 | |
| 20 | def agent(identity='a1', parent=None): |
| 21 | return dict(id=identity, parent_id=parent, name='Worker', runtime='OMP', provider='provider', |
| 22 | model='model', role='worker', task='A public task', status='working', activity='A public action', |
| 23 | activity_state='running', started_at='2026-10-25T23:59:59.900Z', |
| 24 | updated_at=None, observed_at='2026-10-26T00:00:00.100Z') |
| 25 | |
| 26 | |
| 27 | def snapshot(): |
| 28 | return dict(schema_version=1, generated_at='2026-10-26T00:00:01.100Z', sequence='snapshot', |
| 29 | poll_ms=1000, stale_after_ms=15000, |
| 30 | coverage=dict(label='OMP', roots=1, agents=1, complete=False, notice='Partial observation'), |
| 31 | agents=[agent()], interactions=[]) |
| 32 | |
| 33 | |
| 34 | def run(raw, good=True): |
| 35 | result = subprocess.run([BINARY], input=raw, capture_output=True, timeout=30) |
| 36 | if good: |
| 37 | assert result.returncode == 0, (result.returncode, result.stderr) |
| 38 | assert result.stdout.startswith(b'<!doctype html>') |
| 39 | assert result.stdout.endswith(b'</html>\n') |
| 40 | else: |
| 41 | assert result.returncode != 0, 'invalid input was accepted' |
| 42 | assert result.stdout == b'', 'refusal leaked partial output' |
| 43 | return result.stdout |
| 44 | |
| 45 | |
| 46 | class Document(HTMLParser): |
| 47 | def __init__(self, value): |
| 48 | super().__init__(convert_charrefs=True) |
| 49 | self.ids, self.tags, self.text, self.attrs = [], [], [], [] |
| 50 | self.feed(value.decode()) |
| 51 | |
| 52 | def handle_starttag(self, tag, attrs): |
| 53 | attrs = dict(attrs) |
| 54 | self.tags.append(tag) |
| 55 | self.attrs.append(attrs) |
| 56 | if 'id' in attrs: |
| 57 | self.ids.append(attrs['id']) |
| 58 | assert not any(key.startswith('on') for key in attrs), attrs |
| 59 | assert not any('javascript:' in value for value in attrs.values() if value), attrs |
| 60 | |
| 61 | def handle_data(self, data): |
| 62 | self.text.append(data) |
| 63 | |
| 64 | |
| 65 | base = snapshot() |
| 66 | raw = canonical(base) |
| 67 | first = run(raw) |
| 68 | assert first == run(raw), 'render depends on wall clock or mutable state' |
| 69 | # Receiver sequence is arbitrary text: encode it, never widen attribute grammar. |
| 70 | for sequence in ['', '\"><script>alert(1)</script>', 'é' * 64]: |
| 71 | value = snapshot() |
| 72 | value['sequence'] = sequence |
| 73 | parsed = Document(run(canonical(value))) |
| 74 | root = next(a for a in parsed.attrs if a.get('id') == 'hive-board') |
| 75 | assert root['data-sequence'] == 's-' + sequence.encode().hex() |
| 76 | doc = Document(first) |
| 77 | assert len(doc.ids) == len(set(doc.ids)), 'duplicate DOM id' |
| 78 | assert '1s' in ''.join(doc.text) # Subsecond timestamps must not round up. |
| 79 | assert 'script' not in doc.tags |
| 80 | assert next(a for a in doc.attrs if a.get('id') == 'hive-board')['data-generated'] == base['generated_at'] |
| 81 | |
| 82 | # Every byte is tested through the exact production escaper, without the JSON |
| 83 | # parser (which correctly refuses invalid UTF-8 and disallowed controls). |
| 84 | source = Path('render.om').read_text().split('fn main to int\n')[0] |
| 85 | escape_main = '''fn main to int |
| 86 | n = ulong 0 |
| 87 | while lt n 16000 |
| 88 | r = read 0 dec n sub ulong 16000 n |
| 89 | if lt r 0 |
| 90 | ret 1 |
| 91 | end |
| 92 | if eq r 0 |
| 93 | break |
| 94 | end |
| 95 | n = add n ulong r |
| 96 | end |
| 97 | escape 0 n |
| 98 | r = write 1 out 0 get st 5 |
| 99 | if ne r long get st 5 |
| 100 | ret 2 |
| 101 | end |
| 102 | ret 0 |
| 103 | end |
| 104 | ''' |
| 105 | probe = SCRATCH / 'escape' |
| 106 | compiled = subprocess.run([OMC], input=(source + escape_main).encode(), capture_output=True) |
| 107 | assert compiled.returncode == 0, compiled.stderr |
| 108 | probe.write_bytes(compiled.stdout) |
| 109 | probe.chmod(0o700) |
| 110 | for value in [bytes([i]) for i in range(256)] + [bytes(range(256)), b"&<>\"'" * 144, b"&<>\"'" * 3200]: |
| 111 | escaped = subprocess.run([probe], input=value, capture_output=True, check=True).stdout |
| 112 | expected = html.escape(value.decode('latin1'), quote=True).encode('latin1') |
| 113 | assert escaped == expected, (value[:20], escaped[:100], expected[:100]) |
| 114 | if b'<' in value: |
| 115 | assert escaped != expected.replace(b'<', b'<'), 'negative escaper oracle did not discriminate' |
| 116 | |
| 117 | probes = ['<img src=x onerror=alert(1)>', '</li><script>alert(1)</script>', |
| 118 | '\"><a href="javascript:alert(1)">', '</details>'] |
| 119 | for payload in probes + ['\b\f\n\r\t\\"', 'é 🐝 漢字', "&<>\"'" * 3200]: |
| 120 | value = snapshot() |
| 121 | value['agents'][0]['activity'] = payload |
| 122 | value['interactions'] = [dict(id='m1', agent_id='a1', role='assistant', text=payload, |
| 123 | at=value['generated_at'], runtime='OMP', provider='provider', model='model')] |
| 124 | output = run(canonical(value)) |
| 125 | assert html.escape(payload).encode() in output |
| 126 | parsed = Document(output) |
| 127 | assert not {'img', 'script'} & set(parsed.tags) |
| 128 | assert payload in parsed.text |
| 129 | if payload in probes: |
| 130 | (SCRATCH / ('xss-' + str(probes.index(payload)) + '.html')).write_bytes(output) |
| 131 | |
| 132 | # Agent replies only: any human role is a schema refusal with no partial output. |
| 133 | for role in ('drake', 'user', 'guest', 'Assistant'): |
| 134 | value = snapshot() |
| 135 | value['interactions'] = [dict(id='m1', agent_id='a1', role=role, text='HUMAN_MESSAGE_CANARY', |
| 136 | at=value['generated_at'], runtime='OMP', provider='provider', model='model')] |
| 137 | run(canonical(value), False) |
| 138 | value = snapshot() |
| 139 | value['interactions'] = [dict(id='m1', agent_id='a1', role='assistant', text='Agent reply', |
| 140 | at=value['generated_at'], runtime='OMP', provider='provider', model='model')] |
| 141 | output = run(canonical(value)) |
| 142 | assert b'<h2>What the agents are saying, live</h2><ol class="hive-chat"' in output |
| 143 | assert b'Drake' not in output |
| 144 | |
| 145 | for field, size in [('name', 720), ('task', 16000), ('activity', 16000)]: |
| 146 | value = snapshot() |
| 147 | value['agents'][0][field] = 'x' * size |
| 148 | run(canonical(value)) |
| 149 | value['agents'][0][field] += 'x' |
| 150 | run(canonical(value), False) |
| 151 | |
| 152 | bad = [raw[:-2], raw.replace(b'"Worker"', b'"unterminated'), b'x' * (2097152 + 1), |
| 153 | raw.replace(b'"Worker"', b'"\\u0001"'), raw.replace(b'"Worker"', b'"\\q"'), |
| 154 | raw.replace(b'"Worker"', b'"\\u0041"'), raw.replace(b'"Worker"', b'"\xc0\xbc"'), |
| 155 | raw.replace(b'"agents":[', b'"agents":[],"agents":['), |
| 156 | raw.replace(b'"coverage":{', b'"unknown":0,"coverage":{')] |
| 157 | for encoded in bad: |
| 158 | run(encoded, False) |
| 159 | for mutation in ['bad-id', 'parent', 'cycle', 'count', 'date', 'enum', 'fraction', 'duplicate-id']: |
| 160 | value = snapshot() |
| 161 | if mutation == 'bad-id': value['agents'][0]['id'] = 'a" onclick="x' |
| 162 | if mutation == 'parent': value['agents'][0]['parent_id'] = 'missing' |
| 163 | if mutation == 'cycle': |
| 164 | value['agents'][0]['parent_id'] = 'a1' |
| 165 | value['coverage']['roots'] = 0 |
| 166 | if mutation == 'count': value['coverage']['agents'] = 2 |
| 167 | if mutation == 'date': value['generated_at'] = '2026-02-29T00:00:01Z' |
| 168 | if mutation == 'enum': value['agents'][0]['status'] = 'invented' |
| 169 | if mutation == 'fraction': value['generated_at'] = '2026-10-26T00:00:01.Z' |
| 170 | if mutation == 'duplicate-id': |
| 171 | value['agents'].append(agent()) |
| 172 | value['coverage'].update(agents=2, roots=2) |
| 173 | run(canonical(value), False) |
| 174 | |
| 175 | # Deep valid trees are traversed iteratively, not via the process stack. |
| 176 | value = snapshot() |
| 177 | value['agents'] = [agent('a' + str(i), 'a' + str(i - 1) if i else None) for i in range(500)] |
| 178 | value['coverage']['agents'] = 500 |
| 179 | output = run(canonical(value)) |
| 180 | assert output.count(b'<summary class="hive-record">') == 500 |
| 181 | assert output.count(b'</ul></details></li>') == 500 |
| 182 | |
| 183 | # Receiver maximum byte budget with worst-case escaping can exceed one output |
| 184 | # pool. This fixture exercises both pools rather than silently reducing scope. |
| 185 | value = snapshot() |
| 186 | value['agents'] = [agent('a' + str(i)) for i in range(60)] |
| 187 | for item in value['agents']: |
| 188 | item['activity'] = "'" * 16000 |
| 189 | item['task'] = "'" * 16000 |
| 190 | value['coverage'].update(agents=60, roots=60) |
| 191 | encoded = canonical(value) |
| 192 | assert len(encoded) < 2097152 |
| 193 | output = run(encoded) |
| 194 | assert len(output) > 16777216 |
| 195 | Document(output) |
| 196 | |
| 197 | # Date arithmetic independently compared with Python's datetime oracle. |
| 198 | for year in [1900, 2000, 2024, 2026]: |
| 199 | value = snapshot() |
| 200 | value['generated_at'] = f'{year}-03-01T00:00:00Z' |
| 201 | value['agents'][0]['started_at'] = f'{year}-02-28T00:00:00Z' |
| 202 | value['agents'][0]['observed_at'] = value['generated_at'] |
| 203 | expected = int((datetime.datetime(year, 3, 1) - datetime.datetime(year, 2, 28)).total_seconds()) |
| 204 | assert f'>{expected}s</span>'.encode() in run(canonical(value)) |
| 205 | |
| 206 | (SCRATCH / 'fixture.json').write_bytes(raw) |
| 207 | (SCRATCH / 'fixture.html').write_bytes(first) |
| 208 | print('renderer oracle checks passed (byte escaper, Unicode, XSS, limits, negative controls, dates, deep tree, two output pools)') |