96 lines
6.8 KiB
Python
96 lines
6.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Independent local audit. Never mutates Git or Docker. --offline skips image inspection."""
|
|
import argparse, ast, csv, hashlib, io, json, subprocess, tarfile, zipfile
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parents[2]; E=ROOT/'evidence/grade5'
|
|
def digest(data):return hashlib.sha256(data).hexdigest()
|
|
def run(*args):return subprocess.run(args,cwd=ROOT,check=True,capture_output=True).stdout
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser();p.add_argument('--offline',action='store_true');a=p.parse_args();checks={};details={}
|
|
for version in ['baseline','candidate']:
|
|
folder=E/'raw'/version;rows=list(csv.DictReader((folder/'requests.csv').open(encoding='utf-8')));bursts=json.loads((folder/'bursts.json').read_text(encoding='utf-8'));meta=json.loads((folder/'meta.json').read_text(encoding='utf-8'))
|
|
assert len(rows)==4608 and len(bursts)==288
|
|
assert all(r['status']=='200' and not r['error'] for r in rows)
|
|
assert all(b['counts']['session_select']==16 for b in bursts)
|
|
assert all(b['all_sql']==sum(q['calls'] for q in b['queries'])==sum(b['counts'].values()) for b in bursts)
|
|
assert all(q['calls']>0 and q['exec_ms']>=0 for b in bursts for q in b['queries'])
|
|
if version=='baseline':assert all(any(b['counts']['profile_select']>1 for b in bursts if b['repeat']==r and b['mode']=='cold') for r in [1,2,3])
|
|
else:
|
|
assert all(b['counts']['profile_select']==(0 if b['mode']=='warm' else 1) for b in bursts)
|
|
frozen=json.loads((E/'source-fingerprint.json').read_text(encoding='utf-8'))
|
|
assert meta['app_src_sha256']=={Path(name).name:v['working_sha256'] for name,v in frozen.items() if name.startswith('src/')}
|
|
for name,v in frozen.items():
|
|
assert digest((ROOT/name).read_bytes().replace(b'\r\n',b'\n'))==v['lf_sha256'], name
|
|
checks[version+'_raw']='PASS'
|
|
details[version]={'requests':len(rows),'profile_select':sum(b['counts']['profile_select'] for b in bursts),'session_select':sum(b['counts']['session_select'] for b in bursts),'all_sql':sum(b['all_sql'] for b in bursts)}
|
|
original=json.loads((E/'baseline-source.json').read_text(encoding='utf-8'))['sha256']
|
|
with zipfile.ZipFile(E/'baseline-source.zip') as archive:
|
|
for name,sha in original.items():assert digest(archive.read(name))==sha,name
|
|
assert not any('.git' in Path(n).parts or 'secrets' in Path(n).parts or Path(n).name=='.env' for n in archive.namelist())
|
|
checks['baseline_archive_matches_initial_snapshot']='PASS'
|
|
teacher=['README.md','COURSE.md','CONTRIBUTING.md','Makefile','contracts','tests','.github/pull_request_template.md']
|
|
verified=[]
|
|
for entry in teacher:
|
|
path=ROOT/entry
|
|
for file in ([path] if path.is_file() else sorted(path.rglob('*'))):
|
|
if not file.is_file() or '__pycache__' in file.parts:continue
|
|
name=file.relative_to(ROOT).as_posix();old=run('git','show','HEAD:'+name)
|
|
assert file.read_bytes().replace(b'\r\n',b'\n')==old.replace(b'\r\n',b'\n'),name
|
|
verified.append(name)
|
|
checks['teacher_files_unchanged']='PASS';details['teacher_files']=verified
|
|
history=[]
|
|
for f in sorted((ROOT/'evidence').rglob('*')):
|
|
if not f.is_file() or 'grade5' in f.parts:continue
|
|
name=f.relative_to(ROOT).as_posix();old=run('git','show','HEAD:'+name)
|
|
assert f.read_bytes().replace(b'\r\n',b'\n')==old.replace(b'\r\n',b'\n'),name
|
|
history.append(name)
|
|
checks['historical_grade4_evidence_unchanged']='PASS';details['historical_files_count']=len(history)
|
|
for f in list((ROOT/'src').glob('*.py'))+list((ROOT/'student-tests/grade5').glob('*.py'))+list(E.glob('*.py')):ast.parse(f.read_text(encoding='utf-8-sig'))
|
|
for name in ['init-env.sh','restart.sh','run-checks.sh']:
|
|
content=(ROOT/'scripts'/name).read_bytes();assert b'\r' not in content and content.startswith(b'#!/bin/sh\n')
|
|
checks['syntax_and_shell_lf']='PASS'
|
|
# Real configured private values are read locally, never printed or persisted.
|
|
secret_values=[]
|
|
for directory in [ROOT/'secrets',*(ROOT/'.grade5-work').glob('*/secrets')]:
|
|
if directory.exists():
|
|
for f in directory.iterdir():
|
|
if f.is_file():
|
|
value=f.read_bytes().strip()
|
|
if len(value)>=24:secret_values.append(value)
|
|
excluded={'.git','.grade5-work','secrets','.env','.venv','__pycache__','cache','volumes','node_modules'}
|
|
scanned=0
|
|
def scan(content,label):
|
|
assert not any(s in content for s in secret_values),'Private value detected in '+label
|
|
for f in ROOT.rglob('*'):
|
|
if not f.is_file() or any(x in excluded for x in f.relative_to(ROOT).parts) or f.name.startswith('review-grade5') or f.suffix in ['.pyc']:continue
|
|
if f.suffix=='.zip':
|
|
with zipfile.ZipFile(f) as archive:
|
|
for n in archive.namelist():scan(archive.read(n),f.name+':'+n)
|
|
else:scan(f.read_bytes(),f.relative_to(ROOT).as_posix())
|
|
scanned+=1
|
|
checks['configured_private_values_absent']='PASS';details['scanned_files']=scanned
|
|
details['sources']={f.relative_to(ROOT).as_posix():{'working_sha256':digest(f.read_bytes()),'lf_sha256':digest(f.read_bytes().replace(b'\r\n',b'\n'))} for f in sorted((ROOT/'src').glob('*.py'))}
|
|
if not a.offline:
|
|
containers=['lab2-g5-20261025-final-api-1','lab2-g5-20261025-clean-api-1']
|
|
details['images']={}
|
|
expected={Path(name).name:v['working_sha256'] for name,v in frozen.items() if name.startswith('src/')}
|
|
for container in containers:
|
|
with tarfile.open(fileobj=io.BytesIO(run('docker','cp',container+':/app/src/.','-')),mode='r:*') as archive:
|
|
actual={Path(m.name).name:digest(archive.extractfile(m).read()) for m in archive.getmembers() if m.isfile() and m.name.endswith('.py') and '__pycache__' not in m.name}
|
|
assert actual==expected,container
|
|
obj=json.loads(run('docker','inspect',container))[0]
|
|
details['images'][container]={'image':obj['Image'],'cpu_nanos':obj['HostConfig']['NanoCpus'],'memory':obj['HostConfig']['Memory'],'memory_swap':obj['HostConfig']['MemorySwap']}
|
|
checks['final_and_clean_image_bytes_match_working_source']='PASS'
|
|
result={'checks':checks,'details':details}
|
|
(E/'audit.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
|
|
rawfiles=sorted((E/'raw').rglob('*'))
|
|
manifest=''.join(digest(f.read_bytes())+' '+f.relative_to(E).as_posix()+'\n' for f in rawfiles if f.is_file())
|
|
manifest_path=E/'raw-sha256.txt'
|
|
if manifest_path.exists():
|
|
assert manifest_path.read_text(encoding='utf-8')==manifest, 'Raw SHA-256 manifest mismatch'
|
|
else:
|
|
manifest_path.write_text(manifest,encoding='utf-8')
|
|
print(json.dumps(checks,indent=2));print(json.dumps(details['baseline']));print(json.dumps(details['candidate']))
|
|
if __name__=='__main__':main()
|