83 lines
4.1 KiB
Python
83 lines
4.1 KiB
Python
"""Publish only the selected immutable CI menu ZIP into the verified existing nginx downloads contract."""
|
|
import argparse
|
|
import datetime
|
|
import json
|
|
from pathlib import Path
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
from plugin_menu_pack import load_menu, menu_url, sha
|
|
|
|
|
|
def control(*args):
|
|
return subprocess.run(args, capture_output=True, text=True, check=False)
|
|
|
|
|
|
def publish(artifacts, source, store, snippet, apply=False, run=control):
|
|
pack, data = load_menu(artifacts, source)
|
|
store, snippet = Path(store).resolve(strict=True), Path(snippet).resolve(strict=True)
|
|
if not store.is_dir() or not snippet.is_file():
|
|
raise ValueError('Verified downloads store and included snippet must already exist')
|
|
destination = store / pack.name
|
|
if destination.is_symlink() or (destination.exists() and sha(destination) != data['sha256']):
|
|
raise ValueError('Immutable publication filename has conflicting bytes')
|
|
before = snippet.read_bytes()
|
|
route = ('\n# DuneRealms CI menu overlay ' + source + '\nlocation = /downloads/' + pack.name + ' {\n'
|
|
' alias ' + json.dumps(str(destination)) + ';\n'
|
|
' add_header Cache-Control "public, max-age=31536000, immutable" always;\n'
|
|
' add_header X-Content-Type-Options "nosniff" always;\n}\n').encode()
|
|
old = before.decode('utf-8')
|
|
if 'location = /downloads/' + pack.name in old and route not in before:
|
|
raise ValueError('Existing route differs from the reviewed immutable publication')
|
|
after = before if route in before else before + route
|
|
report = {'sourceCommit': source, 'url': menu_url(source,data.get('unified',False)), 'sha1': data['sha1'], 'sha256': data['sha256'],
|
|
'destination': str(destination), 'snippetBeforeSha256': __import__('hashlib').sha256(before).hexdigest(),
|
|
'snippetAfterSha256': __import__('hashlib').sha256(after).hexdigest(), 'applied': False}
|
|
if not apply:
|
|
return report
|
|
if after == before and destination.exists():
|
|
report.update(applied=True, unchanged=True); return report
|
|
backup = snippet.with_name(snippet.name + '.before-menu-' + datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ'))
|
|
backup.write_bytes(before)
|
|
if sha(backup) != report['snippetBeforeSha256']:
|
|
raise RuntimeError('Nginx snippet backup differs')
|
|
created = not destination.exists()
|
|
try:
|
|
if created:
|
|
with tempfile.NamedTemporaryFile(dir=store, prefix='.dune-menu-', suffix='.tmp', delete=False) as stream:
|
|
temp = Path(stream.name)
|
|
try:
|
|
shutil.copy2(pack, temp)
|
|
if sha(temp) != data['sha256']:
|
|
raise RuntimeError('Staged client ZIP differs')
|
|
temp.chmod(0o644); temp.replace(destination)
|
|
finally:
|
|
temp.unlink(missing_ok=True)
|
|
snippet.write_bytes(after)
|
|
if sha(snippet) != report['snippetAfterSha256']:
|
|
raise RuntimeError('Written nginx route differs')
|
|
if run('nginx', '-t').returncode:
|
|
raise RuntimeError('Nginx configuration validation failed')
|
|
if run('systemctl', 'reload', 'nginx').returncode:
|
|
raise RuntimeError('Nginx reload failed')
|
|
except Exception:
|
|
snippet.write_bytes(before)
|
|
if sha(snippet) != report['snippetBeforeSha256']:
|
|
raise RuntimeError('Nginx snippet rollback differs')
|
|
if created:
|
|
destination.unlink(missing_ok=True)
|
|
if run('nginx', '-t').returncode == 0:
|
|
run('systemctl', 'reload', 'nginx')
|
|
raise
|
|
report.update(applied=True, backup=str(backup)); return report
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--artifacts', required=True); parser.add_argument('--expected-source', required=True)
|
|
parser.add_argument('--store', required=True); parser.add_argument('--snippet', required=True)
|
|
parser.add_argument('--apply', action='store_true'); args = parser.parse_args()
|
|
print(json.dumps(publish(args.artifacts, args.expected_source, args.store, args.snippet, args.apply), indent=2))
|
|
|
|
|
|
if __name__ == '__main__': main()
|

Staff