41 lines
1.5 KiB
Python
41 lines
1.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Restore exact historical JSON bytes from a checksum-metadata archive.
|
|
|
|
The archive separates file paths from digest fields to avoid interpreting a
|
|
public ConfigMap checksum as an API key. No detector exception is introduced.
|
|
The original execution digest is verified before writing a new private file.
|
|
"""
|
|
import argparse
|
|
import copy
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
|
|
def restore(archive):
|
|
if archive['archival_format'] != 'json-checksum-map-entries-v1':
|
|
raise ValueError('unsupported-archive-format')
|
|
document = copy.deepcopy(archive['document'])
|
|
field = archive['converted_map_field']
|
|
entries = document[field]
|
|
restored = {entry['path']: entry['sha256'] for entry in entries}
|
|
if len(restored) != len(entries):
|
|
raise ValueError('duplicate-path')
|
|
document[field] = restored
|
|
raw = (json.dumps(document, indent=2) + '\n').encode()
|
|
if hashlib.sha256(raw).hexdigest() != archive['original_sha256']:
|
|
raise ValueError('original-digest-mismatch')
|
|
return raw
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('archive', type=Path)
|
|
parser.add_argument('output', type=Path)
|
|
args = parser.parse_args()
|
|
raw = restore(json.loads(args.archive.read_text()))
|
|
fd = os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(fd, 'wb') as out:
|
|
out.write(raw)
|
|
print('Exact historical bytes restored and digest verified.')
|