PlotDirector.Website/Tools/consume_help.py

41 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Verify and install an explicitly published help directory; never contacts the app."""
import argparse,hashlib,json,os,shutil,tempfile
from pathlib import Path,PurePosixPath
def consume(source,store,channel,expected):
source,store=Path(source).resolve(),Path(store).resolve()
manifest=(source/'manifest.json').read_bytes()
if hashlib.sha256(manifest).hexdigest()!=expected:raise ValueError('Approved manifest digest differs')
m=json.loads(manifest)
if m['format']!=1 or m['channel']!=channel:raise ValueError('Wrong content publication channel')
if not m['files'] or 'articles.json' not in m['files']:raise ValueError('Missing article inventory')
store.mkdir(parents=True,exist_ok=True)
version=store/expected
if version.exists():raise ValueError('Publication already installed; select its retained directory explicitly')
with tempfile.TemporaryDirectory(prefix='.incoming-',dir=store) as temp:
temp=Path(temp)
for name,digest in m['files'].items():
path=PurePosixPath(name)
if path.is_absolute() or '..' in path.parts or '\\' in name:raise ValueError('Unsafe package member')
src=source/name
if src.is_symlink() or not src.is_file() or not src.resolve().is_relative_to(source):raise ValueError('Unsafe publication file')
data=src.read_bytes()
if hashlib.sha256(data).hexdigest()!=digest:raise ValueError('Publication checksum mismatch')
out=temp/name;out.parent.mkdir(parents=True,exist_ok=True);out.write_bytes(data)
articles=json.loads((temp/'articles.json').read_text())
urls=[a['CategorySlug']+'/'+a['Slug'] for a in articles]
if len(urls)!=len(set(urls)) or any(a['Category'].lower()=='internal' for a in articles):raise ValueError('Invalid public articles')
(temp/'manifest.json').write_bytes(manifest)
for file in temp.rglob('*'):
file.chmod(0o755 if file.is_dir() else 0o444)
temp.chmod(0o755)
os.rename(temp,version)
# TemporaryDirectory cleanup tolerates the directory being atomically moved.
link=store/('.current-'+expected)
link.symlink_to(version)
os.replace(link,store/'current')
print(json.dumps({'channel':channel,'version':m['version'],'manifestSha256':expected,'articles':len(articles)}))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('source');p.add_argument('--store',required=True);p.add_argument('--channel',choices=['Development','Production'],required=True);p.add_argument('--manifest-sha256',required=True);a=p.parse_args();consume(a.source,a.store,a.channel,a.manifest_sha256)