Prepare Assignment 8 secure delivery and rollback
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good

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.
This commit is contained in:
2026-11-14 17:09:25 -05:00
parent 8beefde2a4
commit bf28adc7fb
51 changed files with 2091 additions and 14 deletions
@@ -0,0 +1,79 @@
// One-time bootstrap loaded from Jenkins home after an authorized host setup.
// Never print secret values. Scope release credentials to the delivery folder.
import jenkins.model.Jenkins
import hudson.model.Node
import hudson.slaves.DumbSlave
import hudson.slaves.JNLPLauncher
import hudson.slaves.RetentionStrategy
import com.cloudbees.hudson.plugins.folder.Folder
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.CredentialsScope
import com.cloudbees.plugins.credentials.SecretBytes
import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl
import org.jenkinsci.plugins.workflow.job.WorkflowJob
import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition
import hudson.plugins.git.GitSCM
import hudson.plugins.git.UserRemoteConfig
import hudson.plugins.git.BranchSpec
import groovy.json.JsonOutput
def j = Jenkins.get()
def inputs = new File(j.rootDir, 'delivery-bootstrap')
def done = new File(inputs, 'configured.json')
if (done.exists()) return
assert j.getItem('secure-delivery') == null : 'Existing folder requires review'
assert j.getNode('ssw590-vince-delivery') == null : 'Existing node requires review'
def folder = j.createProject(Folder, 'secure-delivery')
folder.description = 'Assignment 8: reviewed releases only; folder-scoped deployment credentials.'
folder.save()
def store = CredentialsProvider.lookupStores(folder).find { it.context == folder }
assert store != null : 'Folder credential store unavailable'
def scope = CredentialsScope.GLOBAL
def credential = new UsernamePasswordCredentialsImpl(scope, 'delivery-registry-write',
'Assignment 8 package-write only; vsun1; revoke after grading', 'vsun1',
new File(inputs, 'registry-write').text.trim())
assert store.addCredentials(Domain.global(), credential)
def key = new BasicSSHUserPrivateKey(scope, 'delivery-deploy-ssh', 'deploy',
new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(new File(inputs, 'deploy_ed25519').text),
'', 'Assignment 8 deploy account; root sudo; reviewed releases only')
assert store.addCredentials(Domain.global(), key)
def knownHosts = new FileCredentialsImpl(scope, 'delivery-known-hosts',
'The-Ocean ED25519 host key verified through existing pinned administrator SSH',
'known_hosts', SecretBytes.fromBytes(new File(inputs, 'known_hosts').bytes))
assert store.addCredentials(Domain.global(), knownHosts)
def launcher = new JNLPLauncher()
launcher.setWebSocket(true)
def node = new DumbSlave('ssw590-vince-delivery', 'Trusted laptop Docker/Ansible delivery agent',
'/home/jenkins/agent', '1', Node.Mode.EXCLUSIVE, 'delivery-trusted', launcher,
new RetentionStrategy.Always(), [])
j.addNode(node)
def secret = new File(inputs, 'agent-secret')
secret.text = node.toComputer().getJnlpMac() + '\n'
secret.setReadable(false, false)
secret.setWritable(false, false)
secret.setReadable(true, true)
secret.setWritable(true, true)
def job = folder.createProject(WorkflowJob, 'pricing')
def scm = new GitSCM(
[new UserRemoteConfig('https://git.yebilly.me/ssw590-group1/vpn-dns-gateway.git', null, null, 'gitea-jenkins-bot')],
[new BranchSpec('*/main')], false, [], null, null, [])
def definition = new CpsScmFlowDefinition(scm, 'delivery/Jenkinsfile')
definition.lightweight = true
job.definition = definition
job.description = 'Reviewed protected-main code only. Enable after the Assignment 8 source is reviewed and merged.'
job.disabled = true
job.save()
done.text = JsonOutput.prettyPrint(JsonOutput.toJson([
configured_at: new Date().format("yyyy-MM-dd'T'HH:mm:ssXXX", TimeZone.getTimeZone('UTC')),
node: node.nodeName, label: 'delivery-trusted', executors: 1, exclusive: true,
job: job.fullName, disabled: true, credential_scope: folder.fullName,
credential_ids: ['delivery-registry-write', 'delivery-deploy-ssh', 'delivery-known-hosts']
])) + '\n'
['registry-write', 'deploy_ed25519', 'known_hosts'].each { name ->
assert new File(inputs, name).delete() : "Could not remove transient bootstrap input ${name}"
}
assert new File(j.rootDir, 'init.groovy.d/ssw590-delivery.groovy').delete()
println('Assignment 8 delivery configuration complete; secret values were not printed; job is disabled.')
+34
View File
@@ -0,0 +1,34 @@
// Administrator preparation only: no checkout, image publication or deployment.
pipeline {
agent { label 'delivery-trusted' }
options { disableConcurrentBuilds(); timeout(time: 5, unit: 'MINUTES') }
stages {
stage('Tool and target prerequisites') {
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
]) {
sh '''set -eu
set +x
mkdir -p build/preflight
{
date -u
id
python3 --version
ansible --version
ansible-galaxy collection list
docker --version
docker compose version
trivy --version
pip-audit --version
ssh -i "$DEPLOY_KEY" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS" deploy@147.182.178.136 'id; sudo -n true; python3 --version; sudo -n docker --version; sudo -n docker compose version; free -m; nproc; df -h /'
} > build/preflight/tools-and-target.txt
cat build/preflight/tools-and-target.txt
'''
}
}
}
}
post { always { archiveArtifacts(artifacts: 'build/preflight/**', allowEmptyArchive: true) } }
}
+129
View File
@@ -0,0 +1,129 @@
"""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()
+24
View File
@@ -0,0 +1,24 @@
param(
[string]$Droplet = '147.182.178.136',
[string]$IdentityFile = (Join-Path $env:USERPROFILE '.ssh/digitalocean')
)
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
$repoPath = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
$sshArguments = @('-i', $IdentityFile, '-o', 'IdentitiesOnly=yes', '-o', 'BatchMode=yes',
'-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10', "root@$Droplet")
& ssh @sshArguments 'docker exec -u jenkins gitea-jenkins-1 test -f /var/jenkins_home/delivery-bootstrap/configured.json'
& docker volume create ssw590-delivery-identity | Out-Null
# The generated identity flows directly from pinned administrator SSH into a
# protected Docker volume. No secret enters command arguments, output or Git.
& ssh @sshArguments 'docker exec -u jenkins gitea-jenkins-1 cat /var/jenkins_home/delivery-bootstrap/agent-secret' |
& docker run --rm -i --network none --user 0:0 --entrypoint sh `
--mount 'type=volume,source=ssw590-delivery-identity,target=/identity' `
ssw590-delivery-agent:20261114 -c 'set -eu; umask 077; cat > /identity/agent-secret; test -s /identity/agent-secret; chown 1000:1000 /identity /identity/agent-secret; chmod 700 /identity; chmod 400 /identity/agent-secret'
Push-Location $repoPath
try {
& docker compose -f delivery/agent/compose.yaml up -d
& docker compose -f delivery/agent/compose.yaml ps
} finally {
Pop-Location
}