Files
mtusi2026lab4/scripts/audit.py
T

33 lines
1.6 KiB
Python

import ast
import hashlib
import io
import json
from pathlib import Path
import subprocess
import tokenize
ROOT = Path(__file__).resolve().parents[1]
def main():
paths = []
for directory in ('src', 'migrations', 'infra', 'student-tests'):
paths.extend(path for path in (ROOT / directory).rglob('*') if path.is_file() and '__pycache__' not in path.parts)
paths.extend(ROOT / name for name in ('Dockerfile', 'compose.yaml', 'requirements.txt'))
for directory in ('src', 'student-tests'):
for path in (ROOT / directory).glob('*.py'):
code = path.read_text(encoding='utf-8')
ast.parse(code)
assert not any(token.type == tokenize.COMMENT for token in tokenize.generate_tokens(io.StringIO(code).readline)), str(path)
manifest = {path.relative_to(ROOT).as_posix(): hashlib.sha256(path.read_bytes()).hexdigest() for path in sorted(paths)}
code = "import hashlib,json; from pathlib import Path; print(json.dumps({p.as_posix():hashlib.sha256(p.read_bytes()).hexdigest() for p in Path('src').glob('*.py')}))"
result = subprocess.check_output(['docker', 'compose', 'exec', '-T', 'api', 'python', '-c', code], cwd=ROOT, text=True)
container = json.loads(result)
assert container and all(manifest[name] == digest for name, digest in container.items()), 'Container sources differ'
(ROOT / 'evidence/source-manifest.json').write_text(json.dumps({'sha256': manifest, 'container_sources_match': True}, indent=2), encoding='utf-8')
print('PASS: application Python has no comments; running container matches final source hashes')
if __name__ == '__main__':
main()