124 lines
7.1 KiB
Python
124 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Prepare, sign and admit code-only Development releases on Atlas; no Production access."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
import shutil
|
|
import socket
|
|
import subprocess
|
|
import tempfile
|
|
from types import SimpleNamespace
|
|
|
|
# -I protects the installed unattended entry point from inherited Python paths.
|
|
import sys
|
|
if sys.flags.isolated:
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
|
|
from release import require, load, file_digest, canonical, prepare
|
|
|
|
BASELINE = Path('/var/lib/plotdirector-dev-deployment/baseline')
|
|
INBOX = Path('/var/lib/plotdirector-dev-deployment/incoming')
|
|
HELPER = '/usr/local/sbin/deploy-plotdirector-development'
|
|
|
|
|
|
def run(args, log):
|
|
with Path(log).open('w') as stream:
|
|
result = subprocess.run(args, stdout=stream, stderr=subprocess.STDOUT)
|
|
require(result.returncode == 0, 'Release check failed; see '+str(log))
|
|
|
|
|
|
def capture_activation_receipt(output, text):
|
|
identifiers = re.findall(r'(?m)^RECEIPT ([A-Za-z0-9][A-Za-z0-9._-]{0,119})$', text)
|
|
if not identifiers:
|
|
return None
|
|
require(len(identifiers) == 1, 'Ambiguous activation receipt; reconcile protected evidence')
|
|
result = subprocess.run(['sudo', '-n', HELPER, '--receipt', identifiers[0]],
|
|
capture_output=True, text=True, check=True)
|
|
receipt = json.loads(result.stdout)
|
|
require(receipt.get('deployment_id') == identifiers[0], 'Activation receipt identity mismatch')
|
|
(Path(output)/'activation-receipt.json').write_bytes(canonical(receipt))
|
|
return receipt
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--source', required=True)
|
|
parser.add_argument('--output', required=True)
|
|
parser.add_argument('--activate', action='store_true')
|
|
parser.add_argument('--isolate-build', action='store_true', help='Run all repository build code without host secrets using Bubblewrap')
|
|
args = parser.parse_args()
|
|
require(socket.gethostname() == 'atlas' and os.geteuid() != 0, 'Run as the Atlas Development deployer')
|
|
os.umask(0o077)
|
|
for storage_path in ('/srv', '/opt/plotdirector-dev'):
|
|
storage = os.statvfs(storage_path)
|
|
available = storage.f_bavail / storage.f_blocks
|
|
if available < .20:
|
|
print(f'WARNING Development storage {storage_path}: {available:.1%} free (below 20%)', flush=True)
|
|
|
|
source = Path(args.source).resolve()
|
|
output = Path(args.output).resolve()
|
|
require(not output.exists(), 'Use a fresh output directory')
|
|
commit = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip()
|
|
require(not subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip(), 'Clean committed source required')
|
|
baseline = load(BASELINE/'manifest.json')
|
|
def build(command, log, writable):
|
|
if args.isolate_build:
|
|
from sandbox_build import run_build
|
|
run_build(command, source, writable, log)
|
|
else:
|
|
run(command, log)
|
|
changed_sql = subprocess.check_output(['git', '-C', str(source), 'diff', '--name-only', baseline['source_commit'], commit, '--', 'PlotLine/Sql'], text=True).strip()
|
|
require(not changed_sql, 'Schema changes require a separately reviewed/qualified migration plan')
|
|
require(baseline['starting_schema_sha256'] == baseline['resulting_schema_sha256'], 'Code-only Development baseline required')
|
|
output.mkdir(parents=True, mode=0o700)
|
|
release_id = 'development-'+commit[:12]+'-'+__import__('time').strftime('%Y%m%dT%H%M%SZ', __import__('time').gmtime())
|
|
# Source SQL must still match every approved immutable historical script.
|
|
for step in baseline['migrations']:
|
|
candidate = source/'PlotLine/Sql'/step['file']
|
|
if candidate.exists():require(file_digest(candidate) == step['sha256'], 'Historical SQL changed: '+step['file'])
|
|
signing = Path.home()/'.local/share/plotdirector-development/signing/private.pem'
|
|
require(signing.is_file() and signing.stat().st_mode & 0o077 == 0, 'Private Development signing key missing or exposed')
|
|
with tempfile.TemporaryDirectory(prefix='build-', dir=output) as work:
|
|
work = Path(work)
|
|
publish = work/'publish'
|
|
build(['dotnet', 'publish', str(source/'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId='+commit], output/'qualification-build.log', work)
|
|
build(['dotnet', 'run', '--project', str(source/'PlotLine.Tests/PlotLine.Tests.csproj')], output/'regression.log', work)
|
|
evidence = work/'evidence'
|
|
shutil.copytree(BASELINE/'evidence', evidence)
|
|
plan = {k:baseline[k] for k in ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations', 'omitted_migrations', 'prerequisites', 'postconditions', 'qualification')}
|
|
plan['qualification'] = {'status':'passed', 'evidence':'evidence/development-code-only.json'}
|
|
(evidence/'development-code-only.json').write_bytes(canonical({
|
|
'status':'passed', 'source_commit':commit, 'application_dll_sha256':file_digest(publish/'PlotLine.dll'),
|
|
'starting_schema_sha256':plan['starting_schema_sha256'], 'resulting_schema_sha256':plan['resulting_schema_sha256'],
|
|
'checks':['clean-committed-source', 'unchanged-reviewed-sql', 'release-publish', 'full-regression-harness'],
|
|
'target':'Development on Atlas only', 'production_access':False,
|
|
}))
|
|
plan_file = output/'plan.json'
|
|
plan_file.write_bytes(canonical(plan))
|
|
prepare(SimpleNamespace(source=str(source), plan=str(plan_file), sql=str(BASELINE/'sql'), evidence=str(evidence),
|
|
output=str(output/'bundle'), release_id=release_id, signing_key=str(signing), compression='none', scope_base=baseline['source_commit']),
|
|
publish_runner=build if args.isolate_build else None)
|
|
# Unprivileged submission; privileged helper snapshots and verifies it again.
|
|
destination = INBOX/release_id
|
|
require(not destination.exists(), 'Release identifier already submitted')
|
|
shutil.copytree(output/'bundle', destination)
|
|
result = subprocess.run(['sudo', '-n', HELPER, '--validate', release_id])
|
|
require(result.returncode == 0, 'Development validation refused')
|
|
activation_receipt = None
|
|
if args.activate:
|
|
result = subprocess.run(['sudo', '-n', HELPER, '--activate', release_id], capture_output=True, text=True)
|
|
print(result.stdout, end='')
|
|
activation_receipt = capture_activation_receipt(output, result.stdout)
|
|
require(result.returncode == 0, 'Development activation refused; inspect protected receipt')
|
|
(output/'submission.json').write_bytes(canonical({'release_id':release_id, 'source_commit':commit, 'operation':'activate' if args.activate else 'validate', 'target':'Development', 'receipt':activation_receipt}))
|
|
print(json.dumps({'release_id':release_id, 'source_commit':commit, 'status':'activated' if args.activate else 'validated'}))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try:main()
|
|
except Exception as error:
|
|
from activate import public_error
|
|
print('Development release refused: '+public_error(error));raise SystemExit(1)
|