Files
vpn-dns-gateway/delivery/bootstrap/prepare_host.py
T
vsun1 bf28adc7fb
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Prepare Assignment 8 secure delivery and rollback
Add the locked pricing service, trusted-agent pipeline, Ansible deployments, security gates, recovery runbooks, prerequisite evidence, and preparation manual.

Prepared with Codex assistance. Vincent explicitly authorized this local commit and will handle the push. Assessed releases and recovery exercises remain pending.
2026-11-14 17:09:25 -05:00

130 lines
6.1 KiB
Python

"""One-time administrator bootstrap; run only on the authorized droplet.
Secrets stay in protected host/Jenkins storage and are never printed. This
does not deploy an application, enable the release job, commit, or push.
"""
import argparse
import json
import os
from pathlib import Path
import shutil
import sqlite3
import subprocess
from datetime import datetime, timezone
HOME = Path('/var/lib/docker/volumes/gitea_jenkins-home/_data')
STATE = Path('/root/ssw590-delivery-bootstrap')
SCRIPTS = Path(__file__).resolve().parent
def run(args, **kwargs):
return subprocess.run(args, check=True, **kwargs)
def private_file(path, content, owner=None):
path.write_text(content)
path.chmod(0o600)
if owner is not None:
os.chown(path, owner, owner)
def registry_token(name, scope):
result = subprocess.run([
'docker', 'exec', '-u', 'git', 'gitea-gitea-1', 'gitea',
'--config', '/data/gitea/conf/app.ini', 'admin', 'user',
'generate-access-token', '--username', 'vsun1', '--token-name', name,
'--scopes', scope, '--raw',
], text=True, capture_output=True)
value = result.stdout.strip()
if result.returncode or len(value) != 40 or not all(c in '0123456789abcdef' for c in value):
raise RuntimeError('Token creation did not return the expected format; no secret output emitted')
return value
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
if not args.apply:
print('Plan: back up Jenkins/Gitea; create deploy SSH/sudo access; create package-only tokens;')
print('configure folder-scoped Jenkins credentials, an exclusive agent and a DISABLED release job; restart Jenkins.')
return
if os.geteuid() != 0 or not HOME.is_dir():
raise RuntimeError('Run as root on the existing The-Ocean droplet')
if STATE.exists() or (HOME / 'delivery-bootstrap').exists():
raise RuntimeError('Bootstrap state already exists: inspect it rather than rotating or overwriting access')
if subprocess.run(['id', 'deploy'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
raise RuntimeError('An existing deploy account requires review before modification')
run(['docker', 'exec', 'gitea-jenkins-1', 'test', '-e', '/var/jenkins_home/plugins/cloudbees-folder.jpi'])
STATE.mkdir(mode=0o700)
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
backup = STATE / ('backup-' + stamp)
backup.mkdir(mode=0o700)
database = Path('/var/lib/docker/volumes/gitea_gitea-data/_data/gitea/gitea.db')
with sqlite3.connect(f'file:{database}?mode=ro', uri=True) as source:
with sqlite3.connect(backup / 'gitea.db') as target:
source.backup(target)
(backup / 'gitea.db').chmod(0o600)
run(['docker', 'stop', 'gitea-jenkins-1'], stdout=subprocess.DEVNULL)
try:
run(['tar', '-czf', str(backup / 'jenkins-home.tgz'), '-C', str(HOME), '.'])
finally:
run(['docker', 'start', 'gitea-jenkins-1'], stdout=subprocess.DEVNULL)
(backup / 'jenkins-home.tgz').chmod(0o600)
if Path('/root/.docker/config.json').exists():
shutil.copy2('/root/.docker/config.json', backup / 'docker-config.json')
(backup / 'docker-config.json').chmod(0o600)
key = STATE / 'deploy_ed25519'
run(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-C', 'ssw590-jenkins-delivery', '-f', str(key)])
run(['useradd', '--create-home', '--shell', '/bin/bash', '--comment', 'SSW590 trusted Ansible deployment', 'deploy'])
sshdir = Path('/home/deploy/.ssh')
sshdir.mkdir(mode=0o700)
run(['chown', 'deploy:deploy', str(sshdir)])
public_key = key.with_suffix('.pub').read_text().strip()
private_file(sshdir / 'authorized_keys', 'restrict ' + public_key + '\n')
run(['chown', 'deploy:deploy', str(sshdir / 'authorized_keys')])
sudoers = Path('/etc/sudoers.d/ssw590-delivery')
private_file(sudoers, '# Trusted Ansible release account: effective host administrator.\ndeploy ALL=(root) NOPASSWD: ALL\n')
sudoers.chmod(0o440)
run(['visudo', '-cf', str(sudoers)])
write_token = registry_token('ssw590-delivery-agent-' + stamp, 'write:package')
read_token = registry_token('ssw590-delivery-target-' + stamp, 'read:package')
result = subprocess.run([
'docker', 'login', '--username', 'vsun1', '--password-stdin', 'git.yebilly.me'
], input=read_token + '\n', text=True, capture_output=True)
if result.returncode:
raise RuntimeError('Target registry login failed; no secret output emitted')
inputs = HOME / 'delivery-bootstrap'
inputs.mkdir(mode=0o700)
os.chown(inputs, 1000, 1000)
private_file(inputs / 'deploy_ed25519', key.read_text(), 1000)
private_file(inputs / 'registry-write', write_token, 1000)
public_host_key = Path('/etc/ssh/ssh_host_ed25519_key.pub').read_text().split()
private_file(inputs / 'known_hosts', '147.182.178.136 ' + ' '.join(public_host_key[:2]) + '\n', 1000)
init = HOME / 'init.groovy.d'
init.mkdir(exist_ok=True)
os.chown(init, 1000, 1000)
script = init / 'ssw590-delivery.groovy'
shutil.copyfile(SCRIPTS / 'configure_jenkins.groovy', script)
script.chmod(0o600)
os.chown(script, 1000, 1000)
private_file(STATE / 'metadata.json', json.dumps({
'started': stamp, 'registry_user': 'vsun1',
'agent_token_name': 'ssw590-delivery-agent-' + stamp,
'target_token_name': 'ssw590-delivery-target-' + stamp,
'agent_scope': 'write:package', 'target_scope': 'read:package',
'backup_directory': str(backup),
'deploy_sudo_scope': 'root commands without a password; trusted code only',
}, indent=2))
run(['docker', 'restart', 'gitea-jenkins-1'], stdout=subprocess.DEVNULL)
# The private key is now the Jenkins bootstrap input; remove the duplicate.
key.unlink()
key.with_suffix('.pub').unlink()
print('Host bootstrap applied. Jenkins is restarting; verify its completion marker before starting the agent.')
print('Existing Gitea, proxy and monitoring configuration was preserved. Release job remains disabled.')
if __name__ == '__main__':
main()