396 lines
24 KiB
Python

#!/usr/bin/python3 -I
"""Restricted activation entry point; install with release.py in a root-owned directory."""
import fcntl
import grp
import json
import os
from pathlib import Path
import pwd
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import time
import uuid
import math
import re
from contextlib import nullcontext
from receipt import Receipt, summary, sanitized
from release import Refused, canonical, file_digest, keys, load, require, safe_name, verify_bundle
CONFIG = Path('/etc/plotdirector-deployment/target.json')
RECEIPT_DIRECTORY = Path('/srv/plotdirector/deployment-receipts')
SAFE_ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LANG': 'C.UTF-8', 'HOME': '/nonexistent', 'DOTNET_NOLOGO': '1'}
def protected(path, directory=False, secret=False):
path = Path(path)
require(path.is_absolute(), 'Absolute protected path required')
for parent in reversed(path.parents):
info = parent.lstat()
require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022, 'Untrusted protected path ancestor')
info = path.lstat()
require(info.st_uid == 0 and not info.st_mode & 0o022 and info.st_nlink == 1 if not directory else info.st_uid == 0 and not info.st_mode & 0o022, 'Protected path ownership/permissions invalid')
require(stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode), 'Protected path type invalid')
if secret:
require(not info.st_mode & 0o007, 'Secret readable by other users')
def command(args, *, account=None, timeout=120):
options = {}
if account:
user = pwd.getpwnam(account)
options = {'user': user.pw_uid, 'group': user.pw_gid, 'extra_groups': []}
result = subprocess.run(args, env=SAFE_ENV, cwd='/', capture_output=True, timeout=timeout, **options)
require(result.returncode == 0, Path(args[0]).name + ' failed; diagnostic values suppressed')
return result.stdout.decode().strip()
class Worker:
def __init__(self, config):
protected(config['worker'])
protected(Path(config['worker']).parent, directory=True)
for dependency in Path(config['worker']).parent.rglob('*'):
protected(dependency, directory=dependency.is_dir())
protected(config['database_config'], secret=True)
database_config = load(config['database_config'])
require(database_config['database'] == config['database'], 'Database configuration target mismatch')
require(database_config['expected_host'] == config['host'] and database_config['expected_server'] == '127.0.0.1,1433', 'SQL server identity mismatch')
user = pwd.getpwnam(config['migration_account'])
self.process = subprocess.Popen(['/usr/bin/dotnet', config['worker'], config['database_config']],
env=SAFE_ENV, cwd='/', user=user.pw_uid, group=user.pw_gid, extra_groups=[],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
self.last_error = None
self.read()
def read(self):
# poll/read timeout is enforced at the subprocess level by an alarm below;
# SQL operations additionally have finite command timeouts in the worker.
line = self.process.stdout.readline(65537)
require(bool(line) and len(line) <= 65536, 'Database worker unavailable')
answer = json.loads(line)
if not answer.get('ok'):
# SQL workers emit codes, never exception text. Reject accidental secret-bearing diagnostics.
if not isinstance(answer.get('error'),str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,80}',answer['error']):
answer={'ok':False,'error':'invalid-worker-error','migration':None,'batch':0}
if answer.get('migration') is not None and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,199}',str(answer['migration'])):
answer['migration']=None
self.last_error = answer
require(answer.get('ok'), 'Database operation refused: ' + str(answer.get('error', 'unknown'))
+ ' migration=' + str(answer.get('migration', 'none')) + ' batch=' + str(answer.get('batch', 0)))
return answer.get('result', answer)
def call(self, op, **values):
self.process.stdin.write(json.dumps({'op': op, **values}) + '\n')
self.process.stdin.flush()
return self.read()
def close(self):
if self.process.poll() is None:
self.process.stdin.close()
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
def configuration():
require(os.geteuid() == 0, 'Restricted sudo invocation required')
protected(CONFIG, secret=True)
cfg = load(CONFIG)
keys(cfg, ('format', 'host', 'environment', 'database', 'root', 'inbox', 'evidence', 'backup',
'service', 'runtime_account', 'migration_account', 'worker', 'database_config',
'public_key', 'minimum_free_bytes', 'health_base', 'runtime_config'))
require(cfg['format'] == 1 and cfg['host'] == socket.gethostname(), 'Wrong deployment host')
require(cfg['environment'] in ('Production', 'Test', 'Development'), 'Invalid environment')
require(cfg['root'] == '/srv/plotdirector' and cfg['inbox'] == '/srv/plotdirector/incoming'
and cfg['evidence'] == '/srv/plotdirector/deployment-evidence'
and cfg['service'] == 'plotdirector.service' and cfg['runtime_account'] == 'plotdirector'
and cfg['migration_account'] == 'plotdirector-migrate'
and cfg['database'] == 'PlotLine' and cfg['backup'] == '/srv/backups/sql'
and cfg['runtime_config'] == '/etc/plotdirector/plotdirector.env'
and cfg['health_base'] == 'http://127.0.0.1:5001', 'Unexpected target layout')
require(cfg['environment'] == 'Production', 'This installed entry point is production-specific; use the same core in the isolated qualification driver')
for p in (cfg['root'], cfg['root'] + '/releases', cfg['evidence']):
protected(p, directory=True)
for p in (cfg['public_key'], cfg['worker']):
protected(p)
protected(cfg['runtime_config'], secret=True)
for p in ('/usr/bin/dotnet', '/usr/bin/openssl', '/usr/bin/systemctl', '/usr/bin/curl'):
require(os.access(p, os.X_OK), 'Required executable unavailable')
require(isinstance(cfg['minimum_free_bytes'], int) and cfg['minimum_free_bytes'] >= 1024**3, 'Invalid disk-space floor')
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'User', '--value']) == cfg['runtime_account'], 'Runtime identity mismatch')
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'WorkingDirectory', '--value']) == cfg['root'] + '/current', 'Service content root mismatch')
executable = command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'ExecStart', '--value'])
require('path=/usr/bin/dotnet ;' in executable and
'argv[]=/usr/bin/dotnet ' + cfg['root'] + '/current/PlotLine.dll' in executable,
'Service executable mismatch')
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'EnvironmentFiles', '--value']).split()[0] == cfg['runtime_config'], 'Service environment file mismatch')
protected(cfg['database_config'], secret=True)
database_config = load(cfg['database_config'])
require(database_config['database'] == cfg['database'], 'Database configuration target mismatch')
for base in (cfg['root'], cfg['backup']):
require(shutil.disk_usage(base).free >= cfg['minimum_free_bytes'], 'Insufficient free space')
return cfg
def install(payload, destination, runtime_group):
require(not destination.exists() and not destination.is_symlink(), 'Release already installed; use a new release identifier')
gid = grp.getgrnam(runtime_group).gr_gid
destination.mkdir(mode=0o750)
destination.chmod(0o750) # The launcher deliberately sets umask 077.
for source in sorted(payload.rglob('*')):
relative = source.relative_to(payload)
target = destination / relative
if source.is_dir():
target.mkdir(mode=0o750)
target.chmod(0o750)
else:
require(source.is_file() and not source.is_symlink(), 'Invalid payload entry')
with source.open('rb') as src, target.open('xb') as out:
shutil.copyfileobj(src, out)
target.chmod(0o440)
os.chown(target, 0, gid)
os.chown(destination, 0, gid)
def switch(root, target, deployment):
current = root / 'current'
if current.exists() or current.is_symlink():
require(current.is_symlink(), 'current must be a symlink; initial provisioning is separate')
old = current.resolve(strict=True)
require(old.is_relative_to(root / 'releases') and old.name == 'app', 'Unsafe previous release')
pending = root / ('.current-' + deployment)
os.symlink(str(target), pending)
os.replace(pending, current)
fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def health(cfg, destination, manifest, worker, meter=None):
require(command(['/usr/bin/systemctl', 'is-active', cfg['service']]) == 'active', 'Service inactive')
for path in ('/', '/Account/Login'):
for attempt in range(20):
try:
status = command(['/usr/bin/curl', '--silent', '--show-error', '--noproxy', '*',
'--header', 'Host: ' + cfg.get('health_host', 'plotdirector.com'), '--header', 'X-Forwarded-Proto: https', '--connect-timeout', '2',
'--max-time', '5', '--output', '/dev/null', '--write-out', '%{http_code}', cfg['health_base'] + path], account=cfg['runtime_account'], timeout=10)
if status in ('200', '301', '302', '307', '308'):
break
except Refused:
pass
time.sleep(1)
else:
raise Refused('Application HTTP health check failed')
require((Path(cfg['root']) / 'current').resolve(strict=True) == destination / 'app', 'Active release identity mismatch')
require(file_digest(destination / 'app/PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Installed DLL checksum mismatch')
identity = json.loads(command(['/usr/bin/curl', '--silent', '--show-error', '--fail', '--noproxy', '*',
'--header', 'Host: ' + cfg.get('health_host', 'plotdirector.com'), '--header', 'X-Forwarded-Proto: https',
'--connect-timeout', '2', '--max-time', '10', cfg['health_base'] + '/_deployment/health'],
account=cfg['runtime_account'], timeout=15))
require(identity.get('healthy') is True and identity.get('version') == manifest['version']
and identity.get('sourceCommit') == manifest['source_commit'] and identity.get('database') == cfg['database'],
'Running application/database identity mismatch')
require(identity.get('environment') == cfg['environment'], 'Running application environment mismatch')
with meter.phase('postactivation_verification') if meter else nullcontext():
database = worker.call('health')
if meter and isinstance(database,dict) and 'history_verification_seconds' in database:
meter.component('migration_history_verification',database['history_verification_seconds'],'postactivation_verification')
application={k:identity[k] for k in ('healthy','version','sourceCommit','database','environment')}
return {'application':application,'database':database,'http_root':True,'http_login':True,'binary_identity':True}
def persist_receipt(cfg, meter):
directory=Path(cfg['root'])/'deployment-receipts'
protected(directory,directory=True)
gid=grp.getgrnam(cfg.get('deployment_group', 'plotdirector-deploy')).gr_gid
require(directory.stat().st_gid==gid and not directory.stat().st_mode&0o007,'Unsafe receipt directory')
identifier=safe_name(meter.data['deployment_id'])
clean=sanitized(meter.data)
data=canonical(clean);require(len(data)<=1024**2,'Receipt exceeds safe size limit')
pending=directory/('.receipt-'+uuid.uuid4().hex)
with pending.open('xb') as stream:stream.write(data);stream.flush();os.fsync(stream.fileno())
os.chown(pending,0,gid);pending.chmod(0o640)
os.replace(pending,directory/(identifier+'.json'))
pending=directory/('.summary-'+uuid.uuid4().hex)
with pending.open('xb') as stream:stream.write((summary(clean)+'\n').encode());stream.flush();os.fsync(stream.fileno())
os.chown(pending,0,gid);pending.chmod(0o640);os.replace(pending,directory/(identifier+'.txt'))
def read_receipt(identifier):
require(os.geteuid()==0,'Restricted sudo invocation required')
identifier=safe_name(identifier)
directory=RECEIPT_DIRECTORY;protected(directory,directory=True)
path=directory/(identifier+'.json');protected(path,secret=True)
require(path.stat().st_size<=1024**2,'Oversized receipt')
value=load(path);require(value.get('format')==1 and value.get('deployment_id')==identifier,'Receipt identity mismatch')
print(canonical(value).decode(),end='')
def import_upload_metrics(source, work, meter):
try:
from release import snapshot
target=Path(work)/'upload-metrics.json'
snapshot(Path(source)/'transfer-metrics.json',target,16384)
data=load(target)
keys(data,('source','started_utc','completed_utc','bytes','seconds','mib_per_second'))
require(data['source']=='ssh-receiver-unprivileged','Unknown transfer provenance')
require(type(data['seconds']) in (int,float) and math.isfinite(data['seconds']) and 0<data['seconds']<7200,'Invalid upload timing')
require(type(data['bytes']) is int and 0<data['bytes']<=4*1024**3+65536,'Invalid upload byte count')
require(math.isfinite(data['bytes']/data['seconds']/1024**2),'Invalid throughput measurement')
# Receiver metrics are unprivileged telemetry, never authorisation inputs.
meter.data['transfer']={'source':data['source'],'bytes':data['bytes'],'seconds':data['seconds'],
'mib_per_second':data['bytes']/data['seconds']/1024**2}
except (OSError,ValueError,Refused,TypeError):
meter.data['warnings'].append('upload-metrics-unavailable; sender receipt may provide transfer measurements')
def activate(package_id, validate=False, rollback=False, profile=None):
safe_name(package_id)
meter=Receipt();deployment=time.strftime('%Y%m%dT%H%M%SZ',time.gmtime())+'-'+uuid.uuid4().hex[:12]
meter.data.update(deployment_id=deployment,operation='validate' if validate else 'rollback' if rollback else 'activate')
cfg=None;lock_fd=None;worker=None;evidence=None;stopped=False;status='failed';stop_started=None
try:
cfg=profile.configuration() if profile else configuration();root=Path(cfg['root'])
lock_path=root/'deployment.lock';protected(lock_path,secret=True)
lock_fd=os.open(lock_path,os.O_RDWR|os.O_NOFOLLOW)
try:fcntl.flock(lock_fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError:raise Refused('Concurrent deployment')
source=Path(cfg['inbox'])/package_id
incoming=source/('package.tar.zst' if (source/'transport.json').exists() else 'package.tar')
info=incoming.lstat();require(stat.S_ISREG(info.st_mode) and info.st_nlink==1,'Unsafe incoming package')
require(shutil.disk_usage(root).free>=cfg['minimum_free_bytes']+4*info.st_size,'Insufficient snapshot/extraction/installation space')
with tempfile.TemporaryDirectory(prefix='.deployment-',dir=str(root)) as work:
os.chmod(work,0o750);os.chown(work,0,grp.getgrnam(cfg['migration_account']).gr_gid)
manifest,authorization,payload=verify_bundle(source,work,cfg['public_key'],meter=meter)
require(manifest['release_id']==package_id,'Package identifier mismatch')
meter.data['release']={'id':package_id,'version':manifest['version'],'source_commit':manifest['source_commit'],
'package_sha256':authorization['package_sha256'],'manifest_sha256':authorization['manifest_sha256'],
'application_sha256':manifest['application_sha256'],'dll_sha256':manifest['files']['app/PlotLine.dll']}
import_upload_metrics(source,work,meter)
size=sum(x.stat().st_size for x in payload.rglob('*') if x.is_file())
require(shutil.disk_usage(root).free>=cfg['minimum_free_bytes']+2*size,'Insufficient release/snapshot space')
for path in [payload,*payload.rglob('*')]:
os.chown(path,0,grp.getgrnam(cfg['migration_account']).gr_gid);path.chmod(0o750 if path.is_dir() else 0o640)
evidence=Path(cfg['evidence'])/(deployment+'.jsonl')
meter.data['protected_evidence_reference']=str(evidence)
def event(phase,**data):
with evidence.open('a') as stream:
stream.write(canonical({'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'deployment':deployment,'release':package_id,'phase':phase,**data}).decode());stream.flush();os.fsync(stream.fileno())
event('validated',package_sha256=authorization['package_sha256'])
worker=profile.worker(cfg) if profile else Worker(cfg)
with meter.phase('database_state_verification'):
beginning=worker.call('begin',package_root=str(payload),deployment_id=deployment,package_sha256=authorization['package_sha256'])
meter.data['migration_history']=beginning
if 'history_verification_seconds' in beginning:
meter.component('migration_history_verification',beginning['history_verification_seconds'],'database_state_verification')
if rollback:require(beginning.get('complete') is True,'Rollback requires all migration history already present; SQL changes are forbidden')
active_file=root/'active-deployment.json'
marker=load(active_file) if active_file.exists() else None
if marker:
prior=safe_name(marker['release']);prior_manifest=root/'releases'/prior/'manifest.json'
meter.data['previous_release']={k:marker[k] for k in ('deployment','release','package_sha256') if k in marker}
if prior_manifest.exists():
pm=load(prior_manifest);meter.data['previous_release'].update(version=pm['version'],source_commit=pm['source_commit'])
else:meter.data['previous_release']=None
if validate:
event('validation-only');status='validated'
print('VALIDATED '+package_id+'; no backup, migrations or service operations performed')
return
backup=Path(cfg['backup'])/(cfg['database']+'-predeploy-'+deployment+'.bak')
database_bytes=beginning.get('database_bytes')
require(isinstance(database_bytes,int) and database_bytes>0,'Database size unavailable for backup-space check')
require(shutil.disk_usage(cfg['backup']).free>=cfg['minimum_free_bytes']+2*database_bytes,'Insufficient verified database-backup space')
require(not backup.exists() and not backup.is_symlink(),'Backup path already exists')
event('backup-start')
with meter.phase('database_backup'):
backup_result=worker.call('backup',path=str(Path(cfg.get('database_backup_directory',cfg['backup']))/backup.name))
require(backup.is_file() and backup.stat().st_size>0,'Verified backup file unavailable')
meter.data['database_backup']={'path':str(backup),'verified':True,'options':['COPY_ONLY','CHECKSUM','VERIFYONLY']}
event('backup-verified',path=str(backup));worker.call('idle')
stop_started=time.monotonic()
with meter.phase('service_stop'):
command(['/usr/bin/systemctl','stop',cfg['service']]);stopped=True
require(command(['/usr/bin/systemctl','show',cfg['service'],'-p','ActiveState','--value'])=='inactive','Service did not stop')
stop_complete=time.monotonic()
worker.call('idle');event('migration-start')
with meter.phase('migration_execution'):migration=worker.call('migrate')
meter.data['migrations']=migration if isinstance(migration,dict) else {}
event('migration-complete')
destination=root/'releases'/package_id
with meter.phase('release_installation'):
if profile:profile.install(payload,destination,cfg['runtime_account'])
else:install(payload,destination,cfg['runtime_account'])
previous=marker['deployment'] if marker else None
event('activation-start',previous_deployment=previous)
with meter.phase('release_activation'):switch(root,destination/'app',deployment)
with meter.phase('service_start'):command(['/usr/bin/systemctl','start',cfg['service']])
meter.data['availability']={'service_stop_to_start_seconds':time.monotonic()-stop_complete,
'stop_request_to_start_command_complete_seconds':time.monotonic()-stop_started,
'definition':'Monotonic intervals include stop/start commands; observed public outage measured separately on Atlas.'}
with meter.phase('application_health_readiness'):checks=health(cfg,destination,manifest,worker,meter)
meter.data['checks']=checks;meter.data['availability']['stop_request_to_health_ready_seconds']=time.monotonic()-stop_started
meter.data['availability']['confirmed_inactive_to_health_ready_seconds']=time.monotonic()-stop_complete
event('health-passed')
with meter.phase('postactivation_verification'):
record=worker.call('activated',evidence=str(evidence),kind='Rollback' if rollback else 'Deploy',previous_deployment=previous)
pending=root/('.active-'+deployment);pending.write_bytes(canonical({'deployment':deployment,'release':package_id,'package_sha256':authorization['package_sha256']}));os.replace(pending,active_file)
meter.data['release_history']=record;meter.data['checks']['activation']=True
event('successful');stopped=False;status='activated'
print('ACTIVATED '+package_id+' deployment='+deployment+' evidence='+str(evidence))
except Exception as error:
if stopped:
try:command(['/usr/bin/systemctl','stop',cfg['service']])
except Exception:pass
meter.data['failures'].append({'code':type(error).__name__,'service_stop_requested':stopped})
if worker is not None and getattr(worker,'last_error',None):
safe=worker.last_error
meter.data['worker_failure']={k:safe[k] for k in ('error','migration','batch','executed','baselined') if k in safe}
if evidence is not None:
with evidence.open('a') as stream:stream.write(canonical({'phase':'failed','error':type(error).__name__,'service_stop_requested':stopped,'recovery':'Operator review required; no automatic database rollback.'}).decode())
raise
finally:
if worker is not None:worker.close()
if lock_fd is not None:os.close(lock_fd)
with meter.phase('receipt_generation'):
meter.finish(status)
if cfg is not None:persist_receipt(cfg,meter)
meter.finish(status)
if cfg is not None:persist_receipt(cfg,meter)
print('RECEIPT '+deployment)
def public_error(error):
return sanitized(str(error)) if isinstance(error,Refused) else type(error).__name__
def main():
os.umask(0o077)
# Ignore inherited Python/environment search paths; installed launcher uses -I.
import signal
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(Refused('Deployment timeout')))
signal.alarm(7200)
args = sys.argv[1:]
if len(args)==2 and args[0]=='--receipt':
read_receipt(args[1]);return
validate = len(args) == 2 and args[0] == '--validate'
rollback = len(args) == 2 and args[0] == '--rollback'
require(len(args) == 1 or validate or rollback, 'Usage: deploy-plotdirector [--validate|--rollback] <release-id>')
activate(args[-1], validate, rollback)
if __name__ == '__main__':
try:
main()
except Exception as error:
print('DEPLOYMENT REFUSED: ' + public_error(error))
sys.exit(1)