158 lines
11 KiB
Python
158 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Audit immutable package hotfix bodies against baked DB2s; never removes rows or pushes.
|
|
|
|
Run through regression_gate.sh --hotfix-audit-only. The pinned package registry is
|
|
not a network capture: serve-time rewrites/suppression still require review before
|
|
removing a push. Row equality alone is expressly not removal approval.
|
|
"""
|
|
import argparse
|
|
import collections
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import struct
|
|
import subprocess
|
|
import tempfile
|
|
from pathlib import Path
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CATEGORIES = ('identical','different','missing','removed_absent','removed_present','uncomparable')
|
|
def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
def schema(path, layout_hash):
|
|
text=path.read_text(); kinds={}
|
|
for line in text.split('LAYOUT',1)[0].splitlines():
|
|
m=re.match(r'(int(?:<[^>]+>)?|float|string|locstring)\s+(\w+)\??',line)
|
|
if m: kinds[m[2]]=m[1].split('<')[0]
|
|
blocks=[b.strip() for b in text.split('\n\n') if b.strip().startswith('LAYOUT ')]
|
|
matching=[b for b in blocks if f'{layout_hash:08X}' in re.findall(r'\b[0-9A-F]{8}\b',b.splitlines()[0].upper())]
|
|
if len(matching)!=1: raise ValueError('Layout missing or ambiguous')
|
|
fields=[]
|
|
for line in matching[0].splitlines()[1:]:
|
|
line=line.strip()
|
|
if not line or line.startswith(('BUILD','COMMENT')): continue
|
|
m=re.fullmatch(r'(\$[^$]+\$)?(\w+)(?:<(u?)(8|16|32|64)>)?(?:\[(\d+)\])?',line)
|
|
if not m: raise ValueError('Unknown DBD syntax: '+line)
|
|
ann,name,unsigned,bits,count=m.groups(); ann=(ann or '').strip('$').split(',')
|
|
if 'noninline' in ann and 'id' in ann: continue
|
|
kind=kinds[name]
|
|
if kind=='int' and not bits: raise ValueError('Integer width absent')
|
|
fields.append(dict(name=name,kind=kind,bits=int(bits or 32),unsigned=bool(unsigned),count=int(count or 1),array=count is not None))
|
|
if not fields: raise ValueError('Empty layout')
|
|
return fields
|
|
def encode(row, fields):
|
|
out=bytearray()
|
|
for field in fields:
|
|
value=row[field['name']]; values=value if field['array'] else [value]
|
|
if not isinstance(values,list) or len(values)!=field['count']: raise ValueError('Array shape: '+field['name'])
|
|
for value in values:
|
|
if field['kind'] in ('string','locstring'):
|
|
if not isinstance(value,str) or '\0' in value: raise ValueError('Invalid string')
|
|
out.extend(value.encode('utf-8')+b'\0')
|
|
elif field['kind']=='float':
|
|
if not isinstance(value,dict) or set(value)!={'f32_bits'} or not 0<=value['f32_bits']<=0xffffffff: raise ValueError('Float bits absent')
|
|
out.extend(struct.pack('<I',value['f32_bits']))
|
|
else:
|
|
bits=field['bits']
|
|
if not isinstance(value,int) or isinstance(value,bool) or not -(1<<(bits-1))<=value<(1<<bits): raise ValueError('Integer range')
|
|
out.extend((value&((1<<bits)-1)).to_bytes(bits//8,'little'))
|
|
return bytes(out)
|
|
def validate_package(package):
|
|
if package.get('build')!='1.60.1.70334': raise ValueError('Package must target70334')
|
|
rows=package['rows']
|
|
if not isinstance(rows,list) or not 0<len(rows)<=1000000: raise ValueError('Package row bound')
|
|
seen=set()
|
|
for row in rows:
|
|
table=int(row['table_hash'],0) if isinstance(row['table_hash'],str) else row['table_hash'];rid=row['id']
|
|
if not 0<table<=0xffffffff or not isinstance(rid,int) or not 0<=rid<=0x7fffffff: raise ValueError('Row identity bound')
|
|
if (table,rid) in seen: raise ValueError('Duplicate row identity')
|
|
seen.add((table,rid))
|
|
if row['record_status'] not in ('valid','removed'): raise ValueError('Unknown row status')
|
|
wire=row['wire_hex']
|
|
if not isinstance(wire,str) or len(wire)>131070 or not re.fullmatch(r'(?:[0-9a-f]{2})*',wire): raise ValueError('Wire bound')
|
|
if row['record_status']=='removed' and wire: raise ValueError('Removed row has payload')
|
|
if row['record_status']=='valid' and not wire: raise ValueError('Valid row lacks payload')
|
|
if hashlib.sha256(bytes.fromhex(wire)).hexdigest()!=row['sha256']: raise ValueError('Wire hash mismatch')
|
|
cursor=0;push_ids=set()
|
|
for push in package['pushes']:
|
|
if push['first']!=cursor or push['count']<=0 or push['push_id'] in push_ids: raise ValueError('Push coverage/identity')
|
|
cursor+=push['count'];push_ids.add(push['push_id'])
|
|
if cursor!=len(rows): raise ValueError('Pushes do not cover package')
|
|
return rows
|
|
def classify(row, baked, fields):
|
|
if row['record_status']=='removed': return 'removed_absent' if baked is None else 'removed_present',None
|
|
if baked is None: return 'missing',None
|
|
try: body=encode(baked,fields)
|
|
except (ValueError,KeyError,TypeError,OverflowError) as error: return 'uncomparable',str(error)
|
|
return ('identical' if body==bytes.fromhex(row['wire_hex']) else 'different'),hashlib.sha256(body).hexdigest()
|
|
def audit(args):
|
|
output=args.output.resolve()
|
|
if any(output.is_relative_to(p.resolve()) for p in (args.baked_dir,args.defs,args.closure.parent)) or any(p.resolve().is_relative_to(output) for p in (args.package,args.closure,args.registry,args.reader)):
|
|
raise ValueError('Audit output must be separate from input files and source trees')
|
|
package_sha=sha(args.package);closure=json.loads(args.closure.read_text())
|
|
if closure['item_package_sha256']!=package_sha: raise ValueError('Package differs from selected codec closure')
|
|
registry_key='generated/compatibility-include/gateway/item_sparse_compat.hpp'
|
|
codec_registry=args.closure.parent/registry_key
|
|
if sha(codec_registry)!=closure['files'][registry_key]: raise ValueError('Frozen codec registry hash drift')
|
|
package=json.loads(args.package.read_text()); rows=validate_package(package)
|
|
registry=json.loads(args.registry.read_text()); names={v['table_hash']:k for k,v in registry.items()}
|
|
if len(names)!=len(registry): raise ValueError('Ambiguous table hash registry')
|
|
groups=collections.defaultdict(list)
|
|
for row in rows:
|
|
th=int(row['table_hash'],0) if isinstance(row['table_hash'],str) else row['table_hash']
|
|
if th not in names: raise ValueError(f'Unknown table hash {th:x}')
|
|
groups[names[th]].append(row)
|
|
args.output.mkdir(parents=True,exist_ok=True)
|
|
(args.output/'report.json').write_text(json.dumps({'schema':1,'complete':False,'state':'running-or-failed'})+'\n')
|
|
inputs={'package_sha256':package_sha,'closure_sha256':sha(args.closure),'registry_sha256':sha(args.registry),
|
|
'reader_sha256':sha(args.reader),'codec_registry_sha256':sha(codec_registry),
|
|
'reader_libraries_sha256':{p.name:sha(p) for p in args.reader.parent.glob('*.dll')},'tables':{}}
|
|
pins={name:(sha(args.baked_dir/(name+'.db2')) if (args.baked_dir/(name+'.db2')).exists() else None,
|
|
sha(args.defs/(name+'.dbd')) if (args.defs/(name+'.dbd')).exists() else None) for name in groups}
|
|
counts={}; total=collections.Counter(); problems=[]
|
|
with tempfile.TemporaryDirectory(prefix='db2-audit-',dir=args.output) as temp:
|
|
temp=Path(temp); requests=temp/'requests.json';requests.write_text(json.dumps({k:[r['id'] for r in v] for k,v in groups.items()}))
|
|
subprocess.run(['dotnet',str(args.reader),str(args.baked_dir),str(args.defs),str(requests),str(temp/'decoded')],check=True,stdout=subprocess.DEVNULL)
|
|
reader=json.loads((temp/'decoded/reader.json').read_text())
|
|
with (args.output/'rows.jsonl').open('w') as listing:
|
|
for name, records in sorted(groups.items()):
|
|
path=args.baked_dir/(name+'.db2');definition=args.defs/(name+'.dbd');info=reader[name];fields=None;err=info.get('error');baked={}
|
|
before=pins[name]
|
|
inputs['tables'][name]={'db2_sha256':before[0],'dbd_sha256':before[1],'reader':info}
|
|
if not err:
|
|
try:
|
|
header=path.read_bytes()[:160]
|
|
if header[:4]!=b'WDC5': raise ValueError('Only pinned WDC5 accepted')
|
|
table_hash,layout_hash=struct.unpack_from('<II',header,152)
|
|
if table_hash!=registry[name]['table_hash'] or layout_hash!=registry[name]['layout_hash']: raise ValueError('Table/layout hash drift')
|
|
fields=schema(definition,layout_hash)
|
|
for line in (temp/'decoded'/(name+'.jsonl')).open():
|
|
row=json.loads(line)
|
|
if row['id'] in baked: raise ValueError('Duplicate decoded row')
|
|
baked[row['id']]=row['fields']
|
|
except (ValueError,KeyError,OSError) as error: err=str(error)
|
|
if err: problems.append({'table':name,'error':err})
|
|
count=collections.Counter({k:0 for k in CATEGORIES})
|
|
for row in records:
|
|
category,detail=('uncomparable',err) if err else classify(row,baked.get(row['id']),fields)
|
|
count[category]+=1
|
|
listing.write(json.dumps({'table':name,'table_hash':row['table_hash'],'id':row['id'],'status':row['record_status'],
|
|
'classification':category,'codec_payload_sha256':row['sha256'],
|
|
'baked_payload_sha256':detail if category in ('identical','different') else None,
|
|
'error':detail if category=='uncomparable' else None},separators=(',',':'))+'\n')
|
|
after=(sha(path) if path.exists() else None,sha(definition) if definition.exists() else None)
|
|
if after!=before: raise ValueError('Audit input changed while reading: '+name)
|
|
counts[name]=dict(count);total.update(count)
|
|
if sha(args.package)!=package_sha or sha(args.closure)!=inputs['closure_sha256'] or sha(args.registry)!=inputs['registry_sha256'] or sha(codec_registry)!=inputs['codec_registry_sha256']: raise ValueError('Package/closure changed during audit')
|
|
if sha(args.reader)!=inputs['reader_sha256'] or {p.name:sha(p) for p in args.reader.parent.glob('*.dll')}!=inputs['reader_libraries_sha256']: raise ValueError('Reader changed during audit')
|
|
result={'schema':1,'complete':not total['uncomparable'],'scope':'immutable codec package registry versus specified baked DB2 snapshot; not a network capture or push-removal approval',
|
|
'inputs':inputs,'totals':dict(total),'tables':counts,'errors':problems}
|
|
(args.output/'report.json').write_text(json.dumps(result,indent=2)+'\n')
|
|
columns=('table',)+CATEGORIES
|
|
(args.output/'counts.tsv').write_text('\t'.join(columns)+'\n'+'\n'.join(name+'\t'+'\t'.join(str(row[k]) for k in CATEGORIES) for name,row in counts.items())+'\n')
|
|
print('Hotfix/baked audit:',json.dumps(dict(total),sort_keys=True),'tables='+str(len(counts)))
|
|
if total['uncomparable']: raise ValueError('Audit incomplete: uncomparable rows (see report)')
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
for name in ('package','closure','baked-dir','registry','defs','reader','output'):p.add_argument('--'+name,type=Path,required=True)
|
|
args=p.parse_args();audit(args)
|
|
if __name__=='__main__':main()
|