Files
mtusi2026lab5/scripts/audit.py
T

56 lines
2.7 KiB
Python

"""Аудит обязательных материалов, локальных секретов и предыдущей лабораторной."""
import hashlib
import json
import os
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
PREVIOUS = ROOT.parent / 'vysoko-nagr 4'
ENV = dict(os.environ, GIT_OPTIONAL_LOCKS='0')
def git(root, *args):
return subprocess.check_output(['git', '-C', str(root), *args], env=ENV).decode('utf-8').strip()
def previous():
paths = git(PREVIOUS, 'ls-files', '-z').split('\0')
files = {p: hashlib.sha256((PREVIOUS / p).read_bytes()).hexdigest() for p in paths if p}
return dict(head=git(PREVIOUS, 'rev-parse', 'HEAD'), branch=git(PREVIOUS, 'branch', '--show-current'),
status=git(PREVIOUS, 'status', '--porcelain'), files=files)
def main():
import sys
if sys.argv[1:] == ['baseline']:
(ROOT / 'evidence/lab4-baseline.json').write_text(json.dumps(previous(), ensure_ascii=False, indent=2), encoding='utf-8')
print('Сохранён read-only fingerprint лабораторной 4')
return
baseline = json.loads((ROOT / 'evidence/lab4-baseline.json').read_text(encoding='utf-8'))
unchanged = previous() == baseline
assert unchanged, 'Lab4 differs from baseline'
protected = ['README.md', 'COURSE.md', 'CONTRIBUTING.md', 'MAINTAINERS.md', 'contracts', 'tests',
'examples', 'compose.example.yaml', '.env.example', '.github']
assert not git(ROOT, 'diff', '276dbda', '--', *protected), 'Protected lab5 material changed'
paths = git(ROOT, 'ls-files', '-z').split('\0')
secret_values = [p.read_bytes().strip() for p in (ROOT / 'secrets').iterdir() if p.is_file()]
for path in paths:
if not path:
continue
assert not path.startswith('secrets/') and path != '.env', 'Tracked private state'
content = (ROOT / path).read_bytes()
assert not any(value and value in content for value in secret_values), 'Local secret leaked in ' + path
assert (b'-----BEGIN ' + b'PRIVATE KEY-----') not in content, 'Private key found in ' + path
authors = git(ROOT, 'log', '276dbda..HEAD', '--format=%h|%an|%ae|%cn|%ce').splitlines()
for row in authors:
assert row.split('|')[1:] == ['Sergey Lyakhonov', 'lyserg119@gmail.com'] * 2, 'Wrong author/committer'
report = dict(lab4_unchanged=unchanged, protected_lab5_unchanged=True, tracked_local_secrets=False,
scanned_files=len(paths), authors=authors, head=git(ROOT, 'rev-parse', 'HEAD'))
(ROOT / 'evidence/audit.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()