370 lines
15 KiB
Python
370 lines
15 KiB
Python
"""Close out exact packaged .deb copies, never scan or expire build/runtime data.
|
|
|
|
Owner builders hold this lock from reading qualification through publication and
|
|
closeout. Persistent named holds cover consumers spanning multiple commands.
|
|
The installer and recovery pointer are durable before any source is unlinked.
|
|
"""
|
|
|
|
import argparse
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import uuid
|
|
import zipfile
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
|
|
|
|
class PayloadError(ValueError):
|
|
pass
|
|
|
|
|
|
def digest(stream):
|
|
h = hashlib.sha256()
|
|
while chunk := stream.read(1024 * 1024):
|
|
h.update(chunk)
|
|
return h.hexdigest()
|
|
|
|
|
|
def plain(path):
|
|
s = path.lstat()
|
|
if not stat.S_ISREG(s.st_mode):
|
|
raise PayloadError(f"Not a regular file: {path}")
|
|
return s
|
|
|
|
|
|
def identity(path):
|
|
s = plain(path)
|
|
# Removing another hardlink changes ctime/nlink, not this content identity.
|
|
return s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns
|
|
|
|
|
|
def checksum(path):
|
|
before = identity(path)
|
|
with path.open('rb') as stream:
|
|
value = digest(stream)
|
|
if identity(path) != before:
|
|
raise PayloadError(f"File changed while reading: {path}")
|
|
return value
|
|
|
|
|
|
def sync_directory(path):
|
|
fd = os.open(path, os.O_RDONLY)
|
|
try:
|
|
os.fsync(fd)
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def atomic_json(path, value):
|
|
if path.exists() or path.is_symlink():
|
|
plain(path)
|
|
temporary = path.with_name('.' + path.name + '.' + uuid.uuid4().hex)
|
|
try:
|
|
with temporary.open('x') as stream:
|
|
temporary.chmod(0o600)
|
|
json.dump(value, stream, indent=2)
|
|
stream.write('\n')
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temporary, path)
|
|
sync_directory(path.parent)
|
|
finally:
|
|
temporary.unlink(missing_ok=True)
|
|
|
|
|
|
def directory(path):
|
|
path = Path(path).absolute()
|
|
if path.resolve(strict=True) != path or not path.is_dir():
|
|
raise PayloadError(f"Directory must be canonical, without symlinks: {path}")
|
|
return path
|
|
|
|
|
|
def open_files(paths):
|
|
"""Conservatively defer on an unavailable ownership check; never guess."""
|
|
command = shutil.which('lsof')
|
|
if not command:
|
|
return 'open-file-check-unavailable'
|
|
try:
|
|
result = subprocess.run(
|
|
[command, '-nP', '-F', 'n', '--', *map(str, paths)],
|
|
capture_output=True, text=True, timeout=15,
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return 'open-file-check-unavailable'
|
|
if result.returncode == 0 and result.stdout.strip():
|
|
return 'payload-in-use'
|
|
if result.returncode != 1 or result.stderr.strip():
|
|
return 'open-file-check-unavailable'
|
|
return None
|
|
|
|
|
|
class QualifiedPayloads:
|
|
def __init__(self, qualified, archive_root, repository):
|
|
self.qualified = directory(qualified)
|
|
self.archive_root = directory(archive_root)
|
|
self.repository = directory(repository)
|
|
self.pointer = self.qualified / 'PAYLOAD_LOCATION.json'
|
|
self.holds = self.qualified / 'PAYLOAD_HOLDS.json'
|
|
self.verified_archives = {}
|
|
|
|
@contextmanager
|
|
def locked(self):
|
|
# One publication lock also serializes builders using the same installer
|
|
# destination from different qualification directories.
|
|
descriptors = []
|
|
try:
|
|
for p in [self.archive_root / '.payload-publication.lock',
|
|
self.qualified / '.payload-closeout.lock']:
|
|
fd = os.open(p, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
descriptors.append(fd)
|
|
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|
raise PayloadError('Invalid payload lock')
|
|
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
yield self
|
|
finally:
|
|
for fd in reversed(descriptors):
|
|
os.close(fd)
|
|
|
|
def name(self, name):
|
|
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.+~%-]*\.deb', name):
|
|
raise PayloadError('Only named .deb payloads are managed')
|
|
return name
|
|
|
|
def document(self):
|
|
if not self.pointer.exists() and not self.pointer.is_symlink():
|
|
return {'schema': 'missioncore.qualified-payload-location/v1', 'files': []}
|
|
plain(self.pointer)
|
|
doc = json.loads(self.pointer.read_text())
|
|
if doc.get('schema') != 'missioncore.qualified-payload-location/v1':
|
|
raise PayloadError('Unknown recovery pointer schema')
|
|
return doc
|
|
|
|
def relative(self, path):
|
|
if path.is_relative_to(self.repository):
|
|
return str(path.relative_to(self.repository))
|
|
return str(path)
|
|
|
|
def resolve_archive(self, record):
|
|
path = Path(record['path'])
|
|
path = path if path.is_absolute() else self.repository / path
|
|
archive_name = r'mission-core-(node|x4)-install-[a-f0-9]{24}\.pyz'
|
|
if path.parent != self.archive_root or not re.fullmatch(archive_name, path.name):
|
|
raise PayloadError('Recovery archive is outside the owner installer directory')
|
|
current = identity(path)
|
|
key = (str(path), current, record['sha256'])
|
|
if key not in self.verified_archives:
|
|
if current[2] != record['bytes'] or checksum(path) != record['sha256']:
|
|
raise PayloadError('Recovery archive changed')
|
|
self.verified_archives[key] = True
|
|
return path
|
|
|
|
def read(self, name):
|
|
name = self.name(name)
|
|
path = self.qualified / name
|
|
if path.exists() or path.is_symlink():
|
|
before = identity(path)
|
|
data = path.read_bytes()
|
|
if identity(path) != before:
|
|
raise PayloadError('Payload changed while reading')
|
|
return data
|
|
matches = [r for r in self.document()['files']
|
|
if r['path'] in (str(path), self.relative(path))]
|
|
if len(matches) != 1:
|
|
raise PayloadError(f'No unique recovery record for {name}')
|
|
record = matches[0]
|
|
if record['member'] != name:
|
|
raise PayloadError('Recovery member name changed')
|
|
archive = self.resolve_archive(record['archive'])
|
|
with zipfile.ZipFile(archive) as z:
|
|
if z.namelist().count(name) != 1 or z.getinfo(name).file_size != record['bytes']:
|
|
raise PayloadError('Invalid recovery member')
|
|
data = z.read(name)
|
|
if hashlib.sha256(data).hexdigest() != record['sha256']:
|
|
raise PayloadError('Recovery payload changed')
|
|
return data
|
|
|
|
def publish(self, output, files):
|
|
"""Publish atomically; an identical retry reuses the immutable installer."""
|
|
if output.parent != self.archive_root:
|
|
raise PayloadError('Unexpected installer destination')
|
|
for name in files:
|
|
if Path(name).name != name or name in ('.', '..'):
|
|
raise PayloadError('Unsafe installer member')
|
|
pending = self.archive_root / '.payload-publication.json'
|
|
if pending.exists() or pending.is_symlink():
|
|
plain(pending)
|
|
previous = json.loads(pending.read_text())
|
|
name = previous['temporary']
|
|
temporary_name = r'\.mission-core-(node|x4)-install-[a-f0-9]{24}\.pyz\.[a-f0-9]{32}'
|
|
if not re.fullmatch(temporary_name, name):
|
|
raise PayloadError('Unsafe interrupted publication path')
|
|
leftover = self.archive_root / name
|
|
if leftover.exists() or leftover.is_symlink():
|
|
if list(identity(leftover)[:2]) != previous['identity']:
|
|
raise PayloadError('Interrupted publication identity changed')
|
|
leftover.unlink()
|
|
pending.unlink()
|
|
sync_directory(self.archive_root)
|
|
if not output.exists() and not output.is_symlink():
|
|
temporary = output.with_name('.' + output.name + '.' + uuid.uuid4().hex)
|
|
try:
|
|
with temporary.open('xb') as stream:
|
|
temporary.chmod(0o600)
|
|
atomic_json(pending, {'temporary': temporary.name,
|
|
'identity': list(identity(temporary)[:2])})
|
|
with zipfile.ZipFile(stream, 'w') as z:
|
|
for name, data in files.items():
|
|
info = zipfile.ZipInfo(name, date_time=(2026, 9, 8, 0, 0, 0))
|
|
info.external_attr = 0o600 << 16
|
|
z.writestr(info, data)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
# Refuse replacement, including concurrent foreign writes.
|
|
os.link(temporary, output)
|
|
sync_directory(output.parent)
|
|
finally:
|
|
temporary.unlink(missing_ok=True)
|
|
pending.unlink(missing_ok=True)
|
|
sync_directory(self.archive_root)
|
|
plain(output)
|
|
with zipfile.ZipFile(output) as z:
|
|
if len(z.namelist()) != len(files) or set(z.namelist()) != set(files):
|
|
raise PayloadError('Existing installer members differ')
|
|
for name, data in files.items():
|
|
with z.open(name) as stream:
|
|
if digest(stream) != hashlib.sha256(data).hexdigest():
|
|
raise PayloadError('Published installer content differs')
|
|
return {'path': self.relative(output), 'bytes': output.stat().st_size,
|
|
'sha256': checksum(output)}
|
|
|
|
def register(self, archive, payloads, report_name, report_bytes):
|
|
"""Persist recovery before closeout; do not change foreign pointer entries."""
|
|
self.resolve_archive(archive)
|
|
if report_name not in ('qualification.json', 'package-result.json'):
|
|
raise PayloadError('Unknown qualification report')
|
|
expected_report = hashlib.sha256(report_bytes).hexdigest()
|
|
if checksum(self.qualified / report_name) != expected_report:
|
|
raise PayloadError('Qualification changed while packaging')
|
|
doc = self.document()
|
|
for name, data in payloads.items():
|
|
name = self.name(name)
|
|
path = self.qualified / name
|
|
row = {'path': self.relative(path), 'bytes': len(data),
|
|
'sha256': hashlib.sha256(data).hexdigest(),
|
|
'archive': archive, 'member': name}
|
|
doc['files'] = [r for r in doc['files'] if r['path'] not in (str(path), row['path'])]
|
|
doc['files'].append(row)
|
|
doc['managed_members'] = list(payloads)
|
|
doc['qualification'] = {'name': report_name, 'sha256': expected_report}
|
|
doc['cleanup'] = {'state': 'pending', 'removed': []}
|
|
atomic_json(self.pointer, doc)
|
|
|
|
def active_holds(self):
|
|
if not self.holds.exists() and not self.holds.is_symlink():
|
|
return {}
|
|
plain(self.holds)
|
|
return json.loads(self.holds.read_text())
|
|
|
|
def hold(self, owner):
|
|
if not owner or len(owner) > 200:
|
|
raise PayloadError('A bounded consumer name is required')
|
|
holds = self.active_holds()
|
|
token = uuid.uuid4().hex
|
|
holds[token] = owner
|
|
atomic_json(self.holds, holds)
|
|
return token
|
|
|
|
def release(self, token):
|
|
holds = self.active_holds()
|
|
if token not in holds:
|
|
raise PayloadError('Unknown consumer hold')
|
|
del holds[token]
|
|
atomic_json(self.holds, holds)
|
|
return self.closeout()
|
|
|
|
def closeout(self):
|
|
doc = self.document()
|
|
names = doc.get('managed_members', [])
|
|
if not names:
|
|
return {'state': 'unmanaged'} # Never adopt arbitrary historical directories.
|
|
report = doc['qualification']
|
|
if (report['name'] not in ('qualification.json', 'package-result.json')
|
|
or checksum(self.qualified / report['name']) != report['sha256']):
|
|
raise PayloadError('Qualification changed; closeout refused')
|
|
if self.active_holds():
|
|
doc['cleanup'] = {'state': 'deferred', 'reason': 'consumer-hold'}
|
|
atomic_json(self.pointer, doc)
|
|
return doc['cleanup']
|
|
candidates = []
|
|
recovery_identities = {}
|
|
report_path = self.qualified / report['name']
|
|
report_identity = identity(report_path)
|
|
for name in names:
|
|
path = self.qualified / self.name(name)
|
|
rows = [r for r in doc['files'] if r['path'] in (str(path), self.relative(path))]
|
|
if len(rows) != 1 or rows[0]['member'] != name:
|
|
raise PayloadError('Ambiguous closeout record')
|
|
row = rows[0]
|
|
archive = self.resolve_archive(row['archive'])
|
|
recovery_identities[archive] = identity(archive)
|
|
with zipfile.ZipFile(archive) as z:
|
|
if z.namelist().count(name) != 1 or z.getinfo(name).file_size != row['bytes']:
|
|
raise PayloadError('Recovery member changed')
|
|
with z.open(name) as stream:
|
|
if digest(stream) != row['sha256']:
|
|
raise PayloadError('Recovery member changed')
|
|
if path.exists() or path.is_symlink():
|
|
before = identity(path)
|
|
if before[2] != row['bytes'] or checksum(path) != row['sha256']:
|
|
raise PayloadError('Unpacked payload changed; closeout refused')
|
|
candidates.append((path, before))
|
|
reason = open_files([p for p, _ in candidates]) if candidates else None
|
|
if reason:
|
|
doc['cleanup'] = {'state': 'deferred', 'reason': reason}
|
|
atomic_json(self.pointer, doc)
|
|
return doc['cleanup']
|
|
removed = []
|
|
for path, before in candidates:
|
|
if identity(path) != before:
|
|
raise PayloadError('Payload changed before retirement')
|
|
if (identity(report_path) != report_identity
|
|
or any(identity(p) != stamp for p, stamp in recovery_identities.items())):
|
|
raise PayloadError('Recovery evidence changed before retirement')
|
|
doc['cleanup'] = {'state': 'removing', 'next': path.name, 'removed': removed}
|
|
atomic_json(self.pointer, doc)
|
|
path.unlink()
|
|
sync_directory(path.parent)
|
|
removed.append(path.name)
|
|
doc['cleanup'] = {'state': 'complete', 'removed': removed}
|
|
atomic_json(self.pointer, doc)
|
|
return doc['cleanup']
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=['hold', 'release', 'retry'])
|
|
parser.add_argument('--qualified', type=Path, required=True)
|
|
parser.add_argument('--archive-root', type=Path, required=True)
|
|
parser.add_argument('--repository', type=Path, required=True)
|
|
parser.add_argument('--owner')
|
|
parser.add_argument('--token')
|
|
args = parser.parse_args()
|
|
with QualifiedPayloads(args.qualified, args.archive_root, args.repository).locked() as store:
|
|
if args.action == 'hold':
|
|
result = {'token': store.hold(args.owner)}
|
|
elif args.action == 'release':
|
|
result = store.release(args.token)
|
|
else:
|
|
result = store.closeout()
|
|
print(json.dumps(result))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|