300 lines
16 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
from release import Refused, canonical, file_digest, keys, load, require, safe_name, verify_bundle
CONFIG = Path('/etc/plotdirector-deployment/target.json')
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(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.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)
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)
for source in sorted(payload.rglob('*')):
relative = source.relative_to(payload)
target = destination / relative
if source.is_dir():
target.mkdir(mode=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):
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', '*', '--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', '*',
'--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')
worker.call('health')
def activate(package_id, validate=False, rollback=False):
cfg = configuration()
root = Path(cfg['root'])
# A precreated protected lock file cannot be redirected by the transfer account.
lock_path = root / 'deployment.lock'
protected(lock_path, secret=True)
lock_fd = os.open(lock_path, os.O_RDWR | os.O_NOFOLLOW)
worker = None
evidence = None
stopped = False
try:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise Refused('Concurrent deployment')
safe_name(package_id)
incoming = Path(cfg['inbox']) / package_id / 'package.tar'
incoming_info = incoming.lstat()
require(stat.S_ISREG(incoming_info.st_mode) and incoming_info.st_nlink == 1, 'Unsafe incoming package')
require(shutil.disk_usage(root).free >= cfg['minimum_free_bytes'] + 4 * incoming_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(Path(cfg['inbox']) / package_id, work, cfg['public_key'])
require(manifest['release_id'] == package_id, 'Package identifier mismatch')
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)
deployment = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + uuid.uuid4().hex[:12]
evidence = Path(cfg['evidence']) / (deployment + '.jsonl')
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 = Worker(cfg)
beginning = worker.call('begin', package_root=str(payload), deployment_id=deployment, package_sha256=authorization['package_sha256'])
if rollback:
require(beginning.get('complete') is True, 'Rollback requires all migration history already present; SQL changes are forbidden')
if validate:
event('validation-only')
print('VALIDATED ' + package_id + '; no backup, migrations or service operations performed')
return
backup_name = 'PlotLine-predeploy-' + deployment + '.bak'
backup = Path(cfg['backup']) / backup_name
require(not backup.exists() and not backup.is_symlink(), 'Backup path already exists')
event('backup-start')
worker.call('backup', path=str(backup))
require(backup.is_file() and backup.stat().st_size > 0, 'Verified backup file unavailable')
event('backup-verified', path=str(backup))
worker.call('idle')
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')
worker.call('idle')
event('migration-start')
worker.call('migrate')
event('migration-complete')
destination = root / 'releases' / package_id
install(payload, destination, cfg['runtime_account'])
# Successful release history contains the predecessor SUCCESS, not merely
# the symlink target left by a failed activation.
active_file = root / 'active-deployment.json'
previous = load(active_file)['deployment'] if active_file.exists() else None
event('activation-start', previous_deployment=previous)
switch(root, destination / 'app', deployment)
command(['/usr/bin/systemctl', 'start', cfg['service']])
health(cfg, destination, manifest, worker)
event('health-passed')
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)
event('successful')
stopped = False
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
if evidence is not None:
with evidence.open('a') as stream:
stream.write(canonical({'phase': 'failed', 'error': str(error) if isinstance(error, Refused) else 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()
os.close(lock_fd)
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:]
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: ' + (str(error) if isinstance(error, Refused) else type(error).__name__))
sys.exit(1)