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
+4
View File
@@ -0,0 +1,4 @@
**/__pycache__
**/.venv
**/*.pyc
agent/.env
+36
View File
@@ -0,0 +1,36 @@
# Preparation evidence — not completed release evidence
All timestamps below are UTC on 14 November 2026. No assessed application
release, image publication, production approval or rollback has occurred yet.
| Check | Actual result |
|---|---|
| 19:50 user-run original target baseline | 961 MiB RAM, 126 MiB available, 752 MiB swap used; deploy account absent |
| 20:15 post-resize SSH check | 1,967 MiB RAM, 1,008 MiB available, 101 MiB swap used; disk unchanged; seven containers up; zero failed systemd units |
| Post-maintenance external HTTPS | Gitea, Jenkins and Grafana login routes each returned HTTP 200 from laptop |
| 20:04 local runtime smoke | Gunicorn, UID 10001, read-only root/capability drops, 64 MiB cap; health v1, explicit `uncommitted-preflight` identity, total 30, invalid input HTTP 400 |
| 19:55 synthetic secret gate | Blocked; actual scanner detected the generated fixture; exit status 1 |
| 20:27 controlled wrong-price test | Three original tests passed; extra expected=-1 assertion failed; exit status 1 |
| 20:40 restored local app baseline | Three tests passed; exit status 0 |
| 20:32 full runtime image gate | Passed, zero HIGH/CRITICAL findings; full JSON and tool/database metadata retained |
| 21:00–21:01 final source/dependency gate | Passed; source scanner and pip-audit exit status 0 |
| Linux regression/syntax checks | Existing two tests and 12 delivery-control tests passed; Ansible syntax passed |
| Jenkins/Compose validation | Dedicated delivery pipeline validated using installed declarative parser; final agent Compose configuration validated |
| Proxy/monitoring candidates | Installed Caddy validation and Prometheus promtool syntax checks passed; candidates were not reloaded or applied |
| 20:40:49 Jenkins bootstrap | Exclusive node and folder-scoped credentials created; pricing release job disabled; earlier jobs retained |
| 20:42:28 agent connection | WebSocket opened; agent connected; no agent host port published |
| 20:46 agent prerequisite build 1 | SUCCESS; real Jenkins credential binding, pinned SSH host key, deploy login, sudo, Python/Docker/Compose prerequisites |
The final preflight image was local only, tagged
`ssw590-pricing:preflight-v1-runtime`. It is not a reviewed source release or
published registry RepoDigest. Earlier Debian and installer-containing Alpine
image scans were blocked and retained; no security exception was added.
Raw local reports: ignored `build/evidence/assignment8-local/`. Publicly
versioned prerequisite inventory: `evidence/agent-preflight-1.txt`.
Jenkins evidence: [build 1](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/)
and its [tool inventory artifact](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/artifact/build/preflight/tools-and-target.txt).
Jenkins requires existing approved-network access and login as applicable.
Remaining assessed evidence must come from actual reviewed v1/v2 pipeline
runs, not these local checks. See `ISSUE.md` and `RUNBOOKS.md`.
+19
View File
@@ -0,0 +1,19 @@
# Implement Assignment 8 secure delivery and rollback
Use instructor manual 1.43 Chapter 6 and its Startup Pricing Service on the
existing Gitea/Jenkins/Caddy/monitoring foundation.
- [x] Prepare exact dependencies, base digest, trusted agent and Ansible.
- [x] Verify deploy SSH, host-key pinning, sudo and target prerequisites.
- [x] Prepare gates, pipeline, approval and recovery automation.
- [ ] Review/merge v1 source; configure staging/app DNS and TLS routes.
- [ ] Show blocked unit-test and synthetic-secret Jenkins runs, then repair.
- [ ] Publish v1; deploy staging; prove changed=0; approve production.
- [ ] Preserve v1 records; review/merge v2; promote the same v2 digest.
- [ ] Roll production back to matching v1 image/config; measure interruption.
- [ ] Review staging-only bad command; show failed wait and recovery.
- [ ] Add production monitoring and correlate actual samples/timestamps.
- [ ] Finalize traceability, runbooks, history, AI log and one PDF.
Local preparation is not assessed release evidence. Preserve branch protection
and earlier services/data; keep credentials out of Git and reports.
+146
View File
@@ -0,0 +1,146 @@
// A separate trusted delivery job loads this file from protected main.
// The existing multibranch PR job keeps its ordinary test-only Jenkinsfile.
pipeline {
agent { label 'delivery-trusted' }
options {
skipDefaultCheckout()
disableConcurrentBuilds()
timeout(time: 60, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
}
parameters {
choice(name: 'MODE', choices: ['release', 'blocked-test', 'blocked-secret', 'rollback-production', 'staging-failure', 'recover-staging'], description: 'Reviewed release or recovery operation')
string(name: 'SOURCE_COMMIT', defaultValue: '', description: 'Optional full reviewed source commit already on main')
string(name: 'RELEASE_RECORD', defaultValue: '', description: 'Reviewed delivery/releases/*.json for rollback or recovery')
string(name: 'STAGING_FAILURE_CONFIG', defaultValue: '', description: 'Only for staging-failure. Full reviewed commit of the staging-only bad command template')
}
environment {
PYTHONDONTWRITEBYTECODE = '1'
TRIVY_CACHE_DIR = '/home/jenkins/agent/.cache/trivy'
}
stages {
stage('Reviewed checkout') {
steps {
deleteDir()
checkout scm
script {
if (params.SOURCE_COMMIT) {
if (!(params.SOURCE_COMMIT ==~ /[0-9a-f]{40}/)) {
error('SOURCE_COMMIT must be a full Git commit')
}
withEnv(["RELEASE_SOURCE=${params.SOURCE_COMMIT}"]) {
sh 'git merge-base --is-ancestor "$RELEASE_SOURCE" origin/main && git checkout --detach "$RELEASE_SOURCE"'
}
}
}
sh 'git merge-base --is-ancestor HEAD origin/main'
sh 'mkdir -p build/delivery/reports && git rev-parse HEAD > build/delivery/reports/source-commit.txt'
}
}
stage('Unit tests') {
steps {
sh 'python3 -B -m unittest discover -s delivery/ci -p "test_controls.py" -v'
script {
withEnv(["TEST_FAILURE=${params.MODE == 'blocked-test'}"]) {
sh 'sh delivery/ci/test-app.sh'
}
}
}
}
stage('Source security gates') {
steps {
script {
def fixture = params.MODE == 'blocked-secret' ? ' --fixture' : ''
sh "python3 delivery/ci/security.py source${fixture}"
}
}
}
stage('Build, scan, publish') {
when { expression { params.MODE == 'release' } }
steps {
withCredentials([usernamePassword(credentialsId: 'delivery-registry-write', usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_TOKEN')]) {
sh 'sh delivery/ci/publish.sh'
}
}
}
stage('Select release record') {
steps {
script {
if (params.MODE == 'release') {
env.SELECTED_RECORD = sh(script: "find build/delivery/releases -name '*-staging.json'", returnStdout: true).trim()
} else {
if (!(params.RELEASE_RECORD ==~ /delivery\/releases\/[a-zA-Z0-9._-]+\.json/)) {
error('Choose a committed delivery/releases/*.json record')
}
env.SELECTED_RECORD = params.RELEASE_RECORD
if (params.MODE == 'staging-failure') {
if (!(params.STAGING_FAILURE_CONFIG ==~ /[0-9a-f]{40}/)) {
error('Choose the full reviewed staging failure configuration commit')
}
withEnv(["FAILURE_CONFIG=${params.STAGING_FAILURE_CONFIG}"]) {
sh '''mkdir -p build/delivery/releases
python3 - <<'PY'
import json, os
from pathlib import Path
record = json.loads(Path(os.environ['SELECTED_RECORD']).read_text())
assert record['target_env'] == 'staging', 'Failure exercise requires staging'
record['configuration_commit'] = os.environ['FAILURE_CONFIG']
Path('build/delivery/releases/failure-staging.json').write_text(json.dumps(record, indent=2))
PY'''
}
env.SELECTED_RECORD = 'build/delivery/releases/failure-staging.json'
}
}
}
sh 'python3 delivery/ci/release.py verify "$SELECTED_RECORD"'
}
}
stage('Staging deploy and unchanged rerun') {
when { expression { params.MODE == 'release' || params.MODE == 'recover-staging' || params.MODE == 'staging-failure' } }
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
]) {
sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" staging'
sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" staging rerun'
}
}
}
stage('Production approval') {
when { expression { params.MODE == 'release' || params.MODE == 'rollback-production' } }
steps {
archiveArtifacts(artifacts: 'build/delivery/reports/**,build/delivery/releases/**', allowEmptyArchive: false)
script {
if (params.MODE == 'release') {
env.SELECTED_RECORD = env.SELECTED_RECORD.replace('-staging.json', '-production.json')
}
sh 'python3 delivery/ci/release.py verify "$SELECTED_RECORD" --environment production'
def record = readFile(env.SELECTED_RECORD)
def approver
timeout(time: 20, unit: 'MINUTES') {
approver = input(message: "Approve production? Source, digest and target below. Review archived scan reports and staging console results.\n${record}", ok: 'Approve production', submitter: 'billy,vsun1', submitterParameter: 'APPROVER')
}
def approvedAt = sh(script: 'date -u +%Y-%m-%dT%H:%M:%SZ', returnStdout: true).trim()
writeFile(file: 'build/delivery/reports/production-approval.txt', text: "Approver=${approver}\nDecision=approved\nUTC=${approvedAt}\n${record}\n")
}
}
}
stage('Production deploy and verification') {
when { expression { params.MODE == 'release' || params.MODE == 'rollback-production' } }
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'),
file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')
]) {
sh 'sh delivery/ci/deploy.sh "$SELECTED_RECORD" production'
}
}
}
}
post {
always {
archiveArtifacts(artifacts: 'build/delivery/reports/**,build/delivery/releases/**', excludes: '**/test-venv/**', allowEmptyArchive: true)
}
}
}
+20
View File
@@ -0,0 +1,20 @@
# Prepare secure delivery and rollback for Assignment 8
The existing CI checks code but does not publish or promote an application.
Add the instructor's pricing service with locked inputs and a trusted-agent
pipeline for security gates, digest-based staging/production deployment,
unchanged Ansible reruns, recorded human approval and recovery operations.
Keep the earlier PR job separate from folder-scoped deployment credentials.
Include the reproducible agent/bootstrap, scan policy, runbooks, actual
prerequisite evidence and a clearly marked preparation chapter. Proxy and
monitoring additions are prepared for later application after DNS and health
are ready. The release job is configured but disabled until reviewed source
reaches main. Assessed v1/v2 promotions and both recovery exercises remain
pending and will require separate reviewed changes and execution evidence.
Validation: two existing tests, three Flask tests, twelve control tests;
controlled test/secret blocks; passing source/dependency and runtime-image
gates; Ansible syntax, agent Compose and installed Jenkins parser checks;
successful trusted-agent prerequisite build 1, including pinned deployment SSH
and noninteractive sudo. No production approval or completed release is claimed.
+88
View File
@@ -0,0 +1,88 @@
# Secure Delivery and Rollback — Assignment 8
The active application starts with the instructor's Startup Pricing Service
v1 from `Examples.zip`, `Examples/dosSecureDelivery/v1/`. The deployment
starters come from that bundle's `ansible/` directory. The task follows
Chapter 6 of instructor manual version 1.43.
`app/` contains the Flask/Gunicorn service, nine exact direct/transitive
dependencies, and a pinned Python 3.13 Alpine base digest for Linux/amd64.
The inventory selects The-Ocean's dedicated deploy account. The example
release record remains explicitly an example; real registry digests will be
generated by Jenkins after the source has been reviewed and merged.
Run the tests from `app/` after installing its requirements into the selected
Linux test environment. The expected v1 result for three units is USD 30.
The later v2 source/test change will be a separate reviewed commit and will
return USD 36. The source commit must be baked into each built image.
Deployment work uses a dedicated trusted Jenkins agent, immutable images
in the existing Gitea registry, and separate Ansible-managed staging and
production Compose projects. The agent requires Docker build capability,
Python, Ansible, the Docker collection, and the selected security scanners.
Registry publication, staging deployment, approval, production promotion,
and both recovery exercises require dated execution evidence.
## Attribution and preparation record
On 14 November 2026 Vincent asked Codex to review the assignment and begin
preparation while he started Docker Desktop. Codex checked the repository's
AI requirements and usage guide, read Chapter 6 and the example sources,
verified remote main `8beefde`, and created branch
`codex/assignment8-secure-delivery`. It copied the v1 and Ansible starters
without changing their contents and checked Python syntax. This preparation
record will be consolidated into the manual's AI assistance log when the
assignment chapter is authored. The instructor retains authorship of the
starter application and playbook.
## Verified preparation, 14 November 2026
The existing two pricing tests, three new Flask tests and twelve release/control
tests passed. The deliberate wrong-price assertion failed as intended; the
synthetic secret fixture blocked its gate. Pip-audit passed for the nine locked
application dependencies. The full Trivy runtime-image gate reported no HIGH
or CRITICAL findings. Earlier failed scans remain in ignored local evidence;
no scanner exception was introduced. A non-root Gunicorn container passed
health, identity, pricing and invalid-input checks with a 64 MiB memory cap.
The droplet now has 2 GiB RAM and its original 25 GB plan disk. Vincent resized
it and installed package updates. The existing seven service containers and
their HTTPS routes were verified after maintenance.
The trusted laptop node `ssw590-vince-delivery` is online over outbound
HTTPS/WebSocket, with one exclusive executor and label `delivery-trusted`.
[Agent prerequisite build 1](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/)
passed using the dedicated deploy key, pinned host key and root sudo. Its
non-secret tool inventory is versioned in `evidence/agent-preflight-1.txt`.
The `secure-delivery/pricing` job loads `delivery/Jenkinsfile` from protected
main and is disabled pending reviewed source. Release credentials are scoped
to that Jenkins folder; the PR job does not bind them or the Docker socket.
The deployment account has root-only passwordless sudo: effective host
administration privileges, restricted to reviewed delivery code. Distinct
package-write and package-read tokens under `vsun1` are stored in Jenkins and
root's target Docker configuration respectively. No values are in Git.
Local agent identity and workspace live in named Docker volumes outside Git.
Run `./delivery/bootstrap/start-agent.ps1` with Docker Desktop and the SSH key
loaded in Windows ssh-agent to reconnect. Stop with
`docker compose -f delivery/agent/compose.yaml stop` when unused.
Ansible syntax, agent Compose configuration, and the installed Jenkins
controller's declarative parser checks passed. These are preparation checks;
**v1/v2 registry releases, promotion and recovery are not yet demonstrated**.
## Remaining checkpoints
Vincent creates the issue, commits/pushes this branch, and obtains Billy's PR
review. Keep main protection. Billy/domain owner must add A records `staging`
and `app`, both pointing to `147.182.178.136`; distinct DNS names are required.
The prepared Caddy additions are not yet applied to the server. Enable the
release job after the reviewed source reaches main, then follow `RUNBOOKS.md`.
Keep the laptop awake during runs. Production approval requires an authorized
human; an agent must not approve unattended.
`SECURITY.md` defines the gate policy. `bootstrap/` makes administrator setup
reviewable; its one-time script refuses to overwrite existing deployment state.
Raw local reports remain under ignored `build/evidence/assignment8-local/`.
The manual records material AI assistance and distinguishes pending work from
actual evidence. This preparation is not ready for assignment submission.
+124
View File
@@ -0,0 +1,124 @@
# Release, recovery and cleanup
These are execution instructions, not completed release evidence.
## Authority and preparation
Billy reviews code; Vincent commits/pushes. Jenkins users `billy` or `vsun1`
may approve production interactively; administrators retain override authority.
The laptop agent must be online and source/configuration commits reviewed and
merged into protected main. Do not run untrusted PR/fork code with its Docker
socket or the delivery folder's credentials. Exclusive scheduling alone does
not prevent someone authorized to alter jobs from selecting the node.
Confirm A records `staging` and `app` point to The-Ocean. Validate and reload
the prepared additions to `/root/gitea/Caddyfile`, preserving the earlier file,
allowlist environment and volumes. Publish no application host port. The
applications join the existing `gitea_web` network with different aliases.
Enable `secure-delivery/pricing` after reviewed source reaches main.
The installed-binary validation commands are:
```text
docker exec gitea-caddy-1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
docker exec gitea-caddy-1 caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile
docker exec monitoring-prometheus-1 promtool check config /etc/prometheus/prometheus.yml
```
Preserve bind-mounted file inodes when copying new contents. Apply monitoring
only after healthy production, then reload using its existing documented
procedure. The temporary candidate checks already passed without a reload.
## v1 and v2
1. Run MODE `blocked-test`: the wrong-price fixture must fail and prevent
publication/deployment. Run MODE `blocked-secret`: the generated synthetic
fixture must block the scanner gate. Fixtures exist only during those runs.
2. Run MODE `release` with the full reviewed v1 SOURCE_COMMIT if needed. Tests,
dependency/secret checks and image gates must pass. The commit-tagged image
is built once, scanned, pushed/pulled, and selected by exact registry digest.
Existing commit tags are reused, not overwritten. Full reports are archived.
3. Staging checks health, version, source SHA and total 30. Its unchanged rerun
must report changed=0; the pipeline blocks otherwise.
4. Review the presented release metadata, archived scans and staging results.
An authorized human approves within 20 minutes. Rejection/timeout stops
production. The actual approval identity/UTC is archived. Production uses
the same digest and verifies all three endpoints; it does not rebuild.
5. Save both generated v1 JSON records from Jenkins into `delivery/releases/`
and review/commit them before recovery. Never invent a digest or commit SHA.
6. Apply the supplied v2 application/test changes in a separate reviewed commit:
VERSION=v2, UNIT_PRICE=12, expected total=36. Repeat the complete release and
real approval. Preserve v1 images/configuration/records; save v2 records.
## Healthy production rollback
Record the detection/decision UTC and reason. Before approval, start the laptop
observer, for example:
```text
python delivery/ci/observe.py --url https://app.yebilly.me --seconds 600 --output build/evidence/assignment8/rollback-health.csv
```
Run MODE `rollback-production` with committed
`delivery/releases/v1-production.json`. SOURCE_COMMIT can stay on main: the
record selects the exact historical image and configuration. Review/approve
the input. Ansible restores playbook/template using `git archive` of the
configuration commit, then verifies v1, its original SHA and total 30.
Archive decision, approval, deployment start/completion/elapsed time and the
observer CSV. Report failed samples and gaps; no failed samples does not prove
zero interruption between requests. Correlate the 30-second monitoring samples.
## Failed staging deployment and recovery
After v2 succeeds, add this staging-only override to the app service in
`ansible/templates/compose.yaml.j2` in a separate reviewed configuration commit:
```jinja2
{% if target_env == 'staging' %}
command: ["gunicorn", "--bind", "0.0.0.0:8001", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
{% endif %}
```
The image's healthcheck still probes 8000. Select MODE `staging-failure`, the
committed good v2 staging record, and full STAGING_FAILURE_CONFIG SHA. Compose
wait must fail within its 90-second bound and stop Jenkins before production.
Do not use MODE `release` to build an image for this configuration exercise.
Restore/review the correct template, then use MODE `recover-staging` with the
original good v2 staging record and matching configuration commit. Verify
health, exact source SHA, total 36 and changed=0. Retain failure, restoration,
recovery reports and observer timing. Do not alter earlier infrastructure to
manufacture a failure.
## Monitoring and limits
After production is healthy, add `https://app.yebilly.me/health` to the existing
Prometheus `https` job and display it in Grafana. Keep Gitea/Jenkins probes and
host metrics. Validate configuration before reload. Record actual samples and
alerts around releases/recovery; a short failure can fall between scrapes or
below the alert duration. HTTP status cannot validate the expected price.
Each stateless app is capped at 64 MiB RAM, 96 MiB RAM+swap, 0.25 CPU and 64
PIDs, with a read-only root filesystem, 16 MiB /tmp tmpfs, UID 10001 and all
capabilities dropped. The laptop agent is capped at 2 GiB/2 CPU. One droplet
and a shared proxy network provide neither high availability nor strong lateral
isolation. A real database migration or external payment can invalidate image
rollback; use compatible expand/migrate/contract changes and tested backups.
## After grading, only when instructed
Archive required evidence first. Remove only the two pricing Compose projects,
their routes, monitoring additions and test DNS names. Revoke the two named
Assignment 8 package tokens, then remove the deploy key/sudo grant and its
Jenkins folder/node when no longer needed. Preserve required job history before
removing configuration. Stop the local agent; remove only its identity/workspace
volumes after approval. Preserve Gitea, Jenkins home, proxy storage, monitoring
volumes and earlier assignments. Never system-prune or use `down -v` here.
## Bootstrap recovery
The protected `/root/ssw590-delivery-bootstrap/` directory contains metadata,
a consistent Jenkins-home archive and a Gitea SQLite backup taken before token
creation. Metadata records token names, not values. Transient private inputs
are erased after Jenkins encrypts them. If setup fails partway, inspect its
marker/logs and existing state rather than rerunning or rotating credentials.
Do not restore entire volumes/databases over later work without a reviewed plan.
+31
View File
@@ -0,0 +1,31 @@
# Release security policy
Policy selected before the assessed scans on 14 November 2026.
- Block every detected repository secret. Use Trivy's built-in rules together
with the course synthetic-fixture rule in `trivy-secret.yaml`.
- Block HIGH and CRITICAL image vulnerabilities, including issues without a
published fix. Retain the full report, including lower severities, for review.
- Block every Python dependency advisory reported by pip-audit. Review direct
and transitive dependencies and update the exact lock before rebuilding.
- A scanner execution error, unavailable advisory service, unavailable
vulnerability database, malformed report, or missing report fails the gate.
- No exceptions are currently approved. An exception requires instructor
acceptance, an advisory identifier, owner, rationale, compensating controls,
and expiry recorded with the release. Findings must never be silently ignored.
- For a suspected false positive, retain the report and record the evidence
used for triage. Keep the release blocked until the finding is resolved or
an instructor-approved exception is recorded.
Each release archives UTC scan times, tool versions, Trivy database metadata,
commands, exit codes, reports, source commit, and the selected image digest.
Rebuild and rescan after changing a dependency or base image.
The synthetic fixture is generated only for a deliberate blocked-gate run.
Its label identifies course test data and has no credential authority. Remove
the fixture and repeat the gate before a release can proceed.
The deployment agent has administrative Docker access to the laptop's Linux
VM and deployment privileges on the droplet. Run reviewed delivery code on
this agent. Pull-request jobs must not receive its Docker socket or release
credentials. The agent connects to Jenkins over outbound HTTPS/WebSocket.
+25
View File
@@ -0,0 +1,25 @@
FROM docker:29-cli@sha256:5a7af0dcb0e46c803efe9b45371dd21cb500e5b4453250394ac6f06d49b6e6f1 AS dockercli
FROM aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb AS scanner
FROM jenkins/inbound-agent:jdk21@sha256:25a3704f7de4d3d0becc441f5683a227556658df1473865ee94c5232355678ab
USER root
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3 python3-venv git openssh-client ca-certificates curl \
&& rm -rf /var/lib/apt/lists/*
COPY --from=dockercli /usr/local/bin/docker /usr/local/bin/docker
COPY --from=dockercli /usr/local/libexec/docker/cli-plugins/ /usr/local/libexec/docker/cli-plugins/
COPY --from=scanner /usr/local/bin/trivy /usr/local/bin/trivy
COPY agent/requirements.txt /tmp/requirements.txt
RUN python3 -m venv /opt/delivery-tools \
&& /opt/delivery-tools/bin/pip install --no-cache-dir -r /tmp/requirements.txt
ENV PATH="/opt/delivery-tools/bin:${PATH}" \
ANSIBLE_COLLECTIONS_PATH=/opt/ansible-collections \
PYTHONDONTWRITEBYTECODE=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
COPY ansible/requirements.yml /tmp/collections.yml
RUN ansible-galaxy collection install -r /tmp/collections.yml -p /opt/ansible-collections \
&& chmod -R a+rX /opt/ansible-collections \
&& mkdir -p /opt/delivery-tools/inventory \
&& dpkg-query -W > /opt/delivery-tools/inventory/debian-packages.txt \
&& pip freeze > /opt/delivery-tools/inventory/python-packages.txt
USER jenkins
+33
View File
@@ -0,0 +1,33 @@
name: ssw590-delivery
services:
agent:
image: ssw590-delivery-agent:20261114
restart: "no"
entrypoint: ["java", "-jar", "/usr/share/jenkins/agent.jar"]
command:
- -url
- https://ci.yebilly.me/
- -name
- ssw590-vince-delivery
- -secret
- "@/run/delivery-identity/agent-secret"
- -webSocket
- -workDir
- /home/jenkins/agent
# Docker's Linux VM socket is owned by group 0. Membership grants Docker
# administration privileges. Use this node exclusively for trusted jobs.
group_add: ["0"]
volumes:
- workspace:/home/jenkins/agent
- /var/run/docker.sock:/var/run/docker.sock
- identity:/run/delivery-identity:ro
mem_limit: 2g
cpus: 2
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
volumes:
identity:
external: true
name: ssw590-delivery-identity
workspace:
name: ssw590-delivery-workspace
+2
View File
@@ -0,0 +1,2 @@
ansible-core==2.21.6
pip-audit==2.10.1
+35
View File
@@ -0,0 +1,35 @@
ansible-core==2.21.6
boolean.py==5.0
CacheControl==0.14.4
certifi==2026.10.23
cffi==2.1.1
charset-normalizer==3.5.2
cryptography==50.0.2
cyclonedx-python-lib==11.12.0
defusedxml==0.7.1
filelock==4.2.10
idna==3.20
Jinja2==3.1.6
license-expression==30.4.4
markdown-it-py==4.3.0
MarkupSafe==3.0.4
mdurl==0.1.2
msgpack==1.2.4
packageurl-python==0.17.6
packaging==26.3
pip-requirements-parser==32.0.1
pip_api==0.0.35
pip_audit==2.10.1
platformdirs==4.14.5
py-serializable==2.2.0
pycparser==3.12
Pygments==2.21.0
pyparsing==3.3.3
PyYAML==6.0.3
requests==2.34.2
resolvelib==1.2.1
rich==15.0.0
sortedcontainers==2.4.0
tomli==2.5.0
tomli_w==1.2.0
urllib3==2.8.0
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
python -m venv /tmp/tools
/tmp/tools/bin/python -m pip install --disable-pip-version-check -r /workspace/delivery/agent/requirements.in
/tmp/tools/bin/python -m pip freeze > /workspace/delivery/agent/requirements.txt
/tmp/tools/bin/ansible-galaxy collection install -r /workspace/delivery/ansible/requirements.yml -p /tmp/collections
/tmp/tools/bin/ansible-galaxy collection list -p /tmp/collections --format json > /tmp/collections.json
/tmp/tools/bin/python - <<'PY'
import json
from pathlib import Path
data = json.loads(Path('/tmp/collections.json').read_text())
versions = {
name: metadata['version']
for collections in data.values()
for name, metadata in collections.items()
if name.startswith('community.')
}
assert 'community.docker' in versions, versions
Path('/workspace/delivery/ansible/requirements.yml').write_text(
'collections:\n' + ''.join(
f' - name: {name}\n version: "{version}"\n'
for name, version in sorted(versions.items())
)
)
print(f'Pinned collections: {versions}')
PY
+74
View File
@@ -0,0 +1,74 @@
- name: Deploy a selected immutable pricing release
hosts: delivery
become: true
vars:
project_dir: "/opt/startup/pricing-{{ target_env }}"
tasks:
- name: Validate release selection
ansible.builtin.assert:
that:
- target_env in ['staging', 'production']
- "'@sha256:' in release_image"
- expected_version in ['v1', 'v2']
- expected_total | int > 0
- public_url.startswith('https://')
- proxy_network | length > 0
- expected_commit is match('^[0-9a-f]{40}$')
- configuration_commit is match('^[0-9a-f]{40}$')
- release_image is match('^git[.]yebilly[.]me/ssw590-group1/pricing@sha256:[0-9a-f]{64}$')
- proxy_network == 'gitea_web'
- public_url == ('https://staging.yebilly.me' if target_env == 'staging' else 'https://app.yebilly.me')
- expected_total | int == (30 if expected_version == 'v1' else 36)
- name: Create deployment directory
ansible.builtin.file:
path: "{{ project_dir }}"
state: directory
mode: '0750'
- name: Render selected Compose configuration
ansible.builtin.template:
src: compose.yaml.j2
dest: "{{ project_dir }}/compose.yaml"
mode: '0640'
- name: Converge application without rebuilding
community.docker.docker_compose_v2:
project_src: "{{ project_dir }}"
project_name: "pricing-{{ target_env }}"
state: present
build: never
pull: missing
wait: true
wait_timeout: 90
- name: Verify health through public TLS endpoint
ansible.builtin.uri:
url: "{{ public_url }}/health"
return_content: true
validate_certs: true
register: health
until: health.status == 200 and health.json.status == 'ok'
retries: 12
delay: 5
changed_when: false
- name: Read release identity
ansible.builtin.uri:
url: "{{ public_url }}/"
return_content: true
register: identity
changed_when: false
- name: Exercise business behavior
ansible.builtin.uri:
url: "{{ public_url }}/price?quantity=3"
return_content: true
register: price
changed_when: false
- name: Check release identity and calculation
ansible.builtin.assert:
that:
- identity.json.version == expected_version
- health.json.version == expected_version
- identity.json.commit == expected_commit
- price.json.total | int == expected_total | int
- name: Preserve the selected non-secret release metadata
ansible.builtin.copy:
dest: "{{ project_dir }}/release.json"
mode: '0640'
content: "{{ {'release_image': release_image, 'source_commit': expected_commit, 'configuration_commit': configuration_commit, 'version': expected_version, 'expected_total': expected_total, 'public_url': public_url} | to_nice_json }}\n"
+3
View File
@@ -0,0 +1,3 @@
[delivery]
# The SSH host key must be verified and supplied by the trusted delivery job.
startup ansible_host=147.182.178.136 ansible_user=deploy ansible_python_interpreter=/usr/bin/python3
+9
View File
@@ -0,0 +1,9 @@
# Copy to a release-specific file and replace EVERY placeholder.
target_env: staging
release_image: git.yebilly.me/ssw590-group1/pricing@sha256:REPLACE_DIGEST
expected_version: v1
expected_commit: REPLACE_FULL_GIT_COMMIT
configuration_commit: REPLACE_FULL_REVIEWED_CONFIGURATION_COMMIT
expected_total: 30
public_url: https://staging.yebilly.me
proxy_network: gitea_web
+5
View File
@@ -0,0 +1,5 @@
collections:
- name: community.docker
version: "5.4.0"
- name: community.library_inventory_filtering_v1
version: "1.1.5"
@@ -0,0 +1,23 @@
services:
app:
image: "{{ release_image }}"
restart: unless-stopped
read_only: true
tmpfs:
- /tmp:size=16m,mode=1777
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
mem_limit: 64m
memswap_limit: 96m
cpus: 0.25
pids_limit: 64
networks:
edge:
aliases:
- "pricing-{{ target_env }}"
networks:
edge:
external: true
name: "{{ proxy_network }}"
+4
View File
@@ -0,0 +1,4 @@
__pycache__
.venv
.git
*.pyc
+13
View File
@@ -0,0 +1,13 @@
FROM python:3.13-alpine@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
ARG APP_COMMIT=development
ENV APP_COMMIT=$APP_COMMIT PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt \
&& python -m pip uninstall -y pip \
&& rm -rf /usr/local/lib/python3.13/ensurepip
COPY app.py .
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)"
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
+33
View File
@@ -0,0 +1,33 @@
import os
from flask import Flask, jsonify, request
app = Flask(__name__)
VERSION = "v1"
UNIT_PRICE = 10
COMMIT = os.environ.get("APP_COMMIT", "development")
def total_price(quantity):
if quantity < 1 or quantity > 1000:
raise ValueError("quantity must be between 1 and 1000")
return UNIT_PRICE * quantity
@app.get("/")
def index():
return jsonify(service="Startup Pricing", version=VERSION, commit=COMMIT)
@app.get("/health")
def health():
return jsonify(status="ok", version=VERSION)
@app.get("/price")
def price():
try:
quantity = int(request.args.get("quantity", "1"))
total = total_price(quantity)
except ValueError as error:
return jsonify(error=str(error)), 400
return jsonify(quantity=quantity, total=total, currency="USD")
+3
View File
@@ -0,0 +1,3 @@
# Instructor compatibility ranges. requirements.txt locks the assessed versions.
Flask>=3.1,<3.2
gunicorn>=23,<24
+9
View File
@@ -0,0 +1,9 @@
blinker==1.9.0
click==8.5.1
Flask==3.1.3
gunicorn==23.0.0
itsdangerous==2.2.0
Jinja2==3.1.6
MarkupSafe==3.0.4
packaging==26.3
Werkzeug==3.1.9
+25
View File
@@ -0,0 +1,25 @@
import unittest
from app import app, total_price
class PricingTests(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
def test_price(self):
self.assertEqual(total_price(3), 30)
response = self.client.get("/price?quantity=3")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json["total"], 30)
def test_invalid_quantity(self):
for value in ["0", "-1", "1001", "abc", "1.5"]:
self.assertEqual(self.client.get("/price?quantity=" + value).status_code, 400)
def test_release_identity(self):
self.assertEqual(self.client.get("/").json["version"], "v1")
self.assertEqual(self.client.get("/health").json["status"], "ok")
if __name__ == "__main__":
unittest.main()
@@ -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
}
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
record=$1
environment=$2
operation=${3:-deploy}
case "$record" in
build/delivery/releases/*.json|delivery/releases/*.json) ;;
*) echo 'Release record must be in the release metadata directory' >&2; exit 1 ;;
esac
python3 delivery/ci/release.py verify "$record" --environment "$environment"
config=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["configuration_commit"])' "$record")
scratch=$(mktemp -d)
trap 'rm -rf "$scratch"' EXIT
# Recover both playbook and template from the configuration recorded with this image.
git archive "$config" delivery/ansible | tar -x -C "$scratch"
: "${DEPLOY_KEY:?bind the deployment SSH key as a Jenkins file credential}"
: "${DEPLOY_KNOWN_HOSTS:?bind the verified known_hosts as a Jenkins file credential}"
export ANSIBLE_HOST_KEY_CHECKING=True
export ANSIBLE_SSH_ARGS="-o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS"
export ANSIBLE_PRIVATE_KEY_FILE="$DEPLOY_KEY"
ansible-playbook -i "$scratch/delivery/ansible/inventory.ini" \
"$scratch/delivery/ansible/deploy.yml" --syntax-check -e "@$record"
python3 delivery/ci/run-ansible.py "$record" "$operation" \
-i "$scratch/delivery/ansible/inventory.ini" \
"$scratch/delivery/ansible/deploy.yml" -e "@$record"
+48
View File
@@ -0,0 +1,48 @@
"""Sample public HTTPS health during release/recovery; failures are evidence."""
import argparse
import csv
from datetime import datetime, timezone
import json
from pathlib import Path
import time
import urllib.error
import urllib.request
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--url', choices=['https://app.yebilly.me', 'https://staging.yebilly.me'], required=True)
parser.add_argument('--seconds', type=int, default=600)
parser.add_argument('--interval', type=float, default=1)
parser.add_argument('--output', required=True)
args = parser.parse_args()
if not 1 <= args.seconds <= 1800 or args.interval < 0.5:
parser.error('Use 1-1800 seconds and at least 0.5 seconds between samples')
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
deadline = time.monotonic() + args.seconds
with output.open('w', newline='') as stream:
writer = csv.writer(stream)
writer.writerow(['started_utc', 'elapsed_seconds', 'http_status', 'status', 'version', 'error'])
while time.monotonic() < deadline:
started = datetime.now(timezone.utc).isoformat()
clock = time.monotonic()
code, status, version, error = '', '', '', ''
try:
with urllib.request.urlopen(args.url + '/health', timeout=2) as response:
code = response.status
body = json.load(response)
status, version = body.get('status', ''), body.get('version', '')
except urllib.error.HTTPError as failure:
code, error = failure.code, type(failure).__name__
except (OSError, ValueError, urllib.error.URLError) as failure:
error = type(failure).__name__
writer.writerow([started, round(time.monotonic() - clock, 3), code, status, version, error])
stream.flush()
time.sleep(max(0, args.interval - (time.monotonic() - clock)))
print(f'Saved samples to {output}; inspect failed samples and gaps, not just the exit status')
if __name__ == '__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
set -eu
set +x
: "${REGISTRY_USER:?bind registry credentials}"
: "${REGISTRY_TOKEN:?bind registry credentials}"
image=git.yebilly.me/ssw590-group1/pricing
commit=$(git rev-parse HEAD)
reports=build/delivery/reports
mkdir -p "$reports" build/delivery/releases
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
printf '%s' "$REGISTRY_TOKEN" | docker login --username "$REGISTRY_USER" --password-stdin git.yebilly.me
# Never overwrite a source-commit tag during a retry.
if docker manifest inspect "$image:$commit" > "$reports/existing-manifest.json" 2> "$reports/manifest-check.log"; then
docker pull "$image:$commit"
else
if ! grep -Eqi 'manifest unknown|no such manifest|not found' "$reports/manifest-check.log"; then
cat "$reports/manifest-check.log" >&2
exit 1
fi
docker build --platform linux/amd64 --build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app
python3 delivery/ci/security.py image --image "$image:$commit" --reports "$reports/image-gate"
docker push "$image:$commit"
docker pull "$image:$commit"
fi
digest=$(docker image inspect "$image:$commit" --format '{{index .RepoDigests 0}}')
python3 delivery/ci/security.py image --image "$digest" --reports "$reports/published-image-gate"
printf '%s\n' "$digest" > "$reports/published-digest.txt"
python3 delivery/ci/release.py create --image "$digest" --build-url "$BUILD_URL" --output build/delivery/releases
+77
View File
@@ -0,0 +1,77 @@
"""Create and verify non-secret release records used by Ansible."""
import argparse
import ast
import json
import re
import subprocess
from datetime import datetime, timezone
from pathlib import Path
URLS = {"staging": "https://staging.yebilly.me", "production": "https://app.yebilly.me"}
IMAGE = re.compile(r"git\.yebilly\.me/ssw590-group1/pricing@sha256:[0-9a-f]{64}")
COMMIT = re.compile(r"[0-9a-f]{40}")
def verify(record):
required = {"release_image", "expected_commit", "configuration_commit",
"expected_version", "expected_total", "proxy_network", "target_env", "public_url"}
if not required <= record.keys() or record.keys() - required - {"build_url", "created_at"}:
raise ValueError("Missing or unexpected release fields")
if not IMAGE.fullmatch(record["release_image"]):
raise ValueError("Release requires the team registry image and exact digest")
for name in ("expected_commit", "configuration_commit"):
value = record[name]
if not COMMIT.fullmatch(value):
raise ValueError(f"Invalid {name}")
subprocess.run(["git", "merge-base", "--is-ancestor", value, "origin/main"], check=True)
version = record["expected_version"]
if version not in {"v1", "v2"}:
raise ValueError("Unsupported application release")
if record["expected_total"] != {"v1": 30, "v2": 36}[version]:
raise ValueError("Unexpected business result")
environment = record["target_env"]
if record["public_url"] != URLS[environment] or record["proxy_network"] != "gitea_web":
raise ValueError("Unexpected deployment target")
def main():
parser = argparse.ArgumentParser()
commands = parser.add_subparsers(dest="action", required=True)
create = commands.add_parser("create")
create.add_argument("--image", required=True)
create.add_argument("--build-url", required=True)
create.add_argument("--output", required=True)
check = commands.add_parser("verify")
check.add_argument("record")
check.add_argument("--environment", choices=["staging", "production"])
args = parser.parse_args()
if args.action == "verify":
record = json.loads(Path(args.record).read_text())
verify(record)
if args.environment and record["target_env"] != args.environment:
raise ValueError("Release environment does not match the authorized pipeline stage")
return
values = {}
for node in ast.parse(Path("delivery/app/app.py").read_text()).body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in {"VERSION", "UNIT_PRICE"}:
values[target.id] = ast.literal_eval(node.value)
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
record = {
"release_image": args.image, "expected_commit": commit,
"configuration_commit": commit, "expected_version": values["VERSION"],
"expected_total": values["UNIT_PRICE"] * 3, "proxy_network": "gitea_web",
"build_url": args.build_url, "created_at": datetime.now(timezone.utc).isoformat(),
}
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
for environment, url in URLS.items():
target = dict(record, target_env=environment, public_url=url)
verify(target)
(output / f"{values['VERSION']}-{environment}.json").write_text(json.dumps(target, indent=2))
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
"""Archive deployment timing/recaps and enforce the unchanged-rerun gate."""
import json
import os
import re
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
def main():
record = json.loads(Path(sys.argv[1]).read_text())
operation = sys.argv[2]
if operation not in {"deploy", "rerun"}:
raise ValueError("Unknown deployment operation")
reports = Path("build/delivery/reports")
reports.mkdir(parents=True, exist_ok=True)
stem = f"ansible-{record['target_env']}-{operation}"
started = datetime.now(timezone.utc).isoformat()
clock = time.monotonic()
process = subprocess.Popen(
["ansible-playbook", *sys.argv[3:]], text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=dict(os.environ, ANSIBLE_NOCOLOR="1"),
)
lines = []
with (reports / f"{stem}.txt").open("w") as log:
for line in process.stdout:
print(line, end="", flush=True)
log.write(line)
lines.append(line)
status = process.wait()
recaps = []
for line in lines:
match = re.match(r"^(\S+)\s+:\s+ok=(\d+)\s+changed=(\d+)\s+unreachable=(\d+)\s+failed=(\d+)", line)
if match:
recaps.append(dict(zip(
["host", "ok", "changed", "unreachable", "failed"],
[match[1], *map(int, match.groups()[1:])],
)))
passed = status == 0 and bool(recaps) and all(
row["failed"] == 0 and row["unreachable"] == 0
and (operation != "rerun" or row["changed"] == 0)
for row in recaps
)
report = {
"started": started, "completed": datetime.now(timezone.utc).isoformat(),
"elapsed_seconds": round(time.monotonic() - clock, 3),
"operation": operation, "release": record,
"ansible_exit_code": status, "recaps": recaps,
"result": "passed" if passed else "blocked",
}
(reports / f"{stem}.json").write_text(json.dumps(report, indent=2))
if not passed:
print("Deployment gate blocked: inspect the archived Ansible recap", file=sys.stderr)
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())
+127
View File
@@ -0,0 +1,127 @@
"""Run release gates and preserve reports, tool versions, and process exit codes."""
import argparse
import json
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
def now():
return datetime.now(timezone.utc).isoformat()
def check_report(report, kind):
if kind == "dependencies":
dependencies = report["dependencies"]
if not dependencies:
raise ValueError("Dependency audit returned no packages")
return [v for package in dependencies for v in package["vulns"]]
if report["SchemaVersion"] != 2 or "ArtifactName" not in report:
raise ValueError("Unrecognized Trivy report")
results = report["Results"]
if not isinstance(results, list):
raise ValueError("Trivy Results must be a list")
if kind == "image" and not results:
raise ValueError("Image scan returned no analyzed targets")
if kind == "secrets":
return [secret for result in results for secret in result.get("Secrets", [])]
return [
vulnerability
for result in results
for vulnerability in result.get("Vulnerabilities", [])
if vulnerability["Severity"] in {"HIGH", "CRITICAL"}
]
def redact_secret_matches(report):
for result in report.get("Results", []):
for secret in result.get("Secrets", []):
secret["Match"] = "[REDACTED]"
for line in secret.get("Code", {}).get("Lines", []):
line["Content"] = "[REDACTED]"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("phase", choices=["source", "image"])
parser.add_argument("--image")
parser.add_argument("--fixture", action="store_true")
parser.add_argument("--reports", default="build/delivery/reports")
args = parser.parse_args()
reports = Path(args.reports).resolve()
reports.mkdir(parents=True, exist_ok=True)
execution = {"started": now(), "phase": args.phase, "steps": []}
def run(command, label, accepted=(0,)):
result = subprocess.run(command, text=True, capture_output=True)
(reports / f"{label}.log").write_text(result.stdout + result.stderr)
execution["steps"].append({
"label": label, "command": command, "completed": now(),
"exit_code": result.returncode,
})
if result.returncode not in accepted:
raise RuntimeError(f"{label} failed with exit code {result.returncode}")
return result
def scan_secrets(target, label):
output = reports / f"{label}.json"
run([
"trivy", "fs", "--scanners", "secret", "--secret-config",
"delivery/trivy-secret.yaml", "--format", "json", "--output", str(output),
"--skip-dirs", ".git", "--skip-dirs", "build", "--skip-dirs", "work",
"--skip-dirs", ".venv", str(target),
], label)
report = json.loads(output.read_text())
redact_secret_matches(report)
output.write_text(json.dumps(report, indent=2))
if check_report(report, "secrets"):
raise RuntimeError(f"{label}: detected secrets block delivery")
try:
run(["trivy", "--version"], "trivy-version")
run(["pip-audit", "--version"], "pip-audit-version")
if args.phase == "source":
scan_secrets(".", "source-secrets")
output = reports / "dependencies.json"
result = run([
"pip-audit", "-r", "delivery/app/requirements.txt", "--no-deps",
"--disable-pip", "--format", "json", "--output", str(output),
], "dependencies", accepted=(0, 1))
findings = check_report(json.loads(output.read_text()), "dependencies")
if result.returncode or findings:
raise RuntimeError("Dependency findings or audit errors block delivery")
if args.fixture:
with tempfile.TemporaryDirectory(prefix="ssw590-scan-") as directory:
# Construct the nonfunctional course fixture only in the test run.
value = "SSW590_SYNTHETIC_SECRET_" + "0" * 16
Path(directory, "fixture.txt").write_text(value)
scan_secrets(directory, "synthetic-secret")
raise RuntimeError("Synthetic fixture was not detected")
else:
if not args.image:
raise ValueError("--image is required for the image gate")
output = reports / "image.json"
run([
"trivy", "image", "--scanners", "vuln", "--format", "json",
"--output", str(output), args.image,
], "image")
run(["trivy", "--version"], "trivy-database-version")
if check_report(json.loads(output.read_text()), "image"):
raise RuntimeError("HIGH/CRITICAL image findings block delivery")
execution["result"] = "passed"
print(f"{args.phase} gate passed")
except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error:
execution["result"] = "blocked"
execution["reason"] = str(error)
print(f"{args.phase} gate blocked: {error}")
return 1
finally:
execution["completed"] = now()
(reports / f"{args.phase}-execution.json").write_text(json.dumps(execution, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
reports=${REPORTS_DIR:-build/delivery/reports}
mkdir -p "$reports"
reports=$(cd "$reports" && pwd)
test_dir=$(mktemp -d)
trap 'rm -rf "$test_dir"' EXIT
python3 -m venv "$test_dir/venv"
test_python="$test_dir/venv/bin/python"
"$test_python" -m pip install -r delivery/app/requirements.txt
cp delivery/app/app.py delivery/app/test_app.py "$test_dir/"
if [ "${TEST_FAILURE:-false}" = true ]; then
cat > "$test_dir/test_gate_fixture.py" <<'PY'
import unittest
from app import app
class ControlledWrongPrice(unittest.TestCase):
def test_deliberately_wrong_expected_price(self):
response = app.test_client().get('/price?quantity=3')
self.assertEqual(response.json['total'], -1, 'Controlled test must block delivery')
PY
fi
cd "$test_dir"
"$test_python" -B - "$reports" <<'PY'
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
started = datetime.now(timezone.utc).isoformat()
result = subprocess.run([sys.executable, '-B', '-m', 'unittest', '-v'], text=True, capture_output=True)
output = result.stdout + result.stderr
print(output, end='')
reports = Path(sys.argv[1])
(reports / 'unit-tests.txt').write_text(output)
(reports / 'unit-tests.json').write_text(json.dumps({
'started': started, 'completed': datetime.now(timezone.utc).isoformat(),
'exit_code': result.returncode,
'result': 'passed' if result.returncode == 0 else 'blocked',
}, indent=2))
raise SystemExit(result.returncode)
PY
+112
View File
@@ -0,0 +1,112 @@
"""Regression checks for fail-closed release and scan boundaries."""
import importlib.util
import io
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
import release
import security
spec = importlib.util.spec_from_file_location('run_ansible', Path(__file__).with_name('run-ansible.py'))
run_ansible = importlib.util.module_from_spec(spec)
spec.loader.exec_module(run_ansible)
class SecurityGateTests(unittest.TestCase):
def test_empty_dependency_audit_is_not_clean_evidence(self):
with self.assertRaises(ValueError):
security.check_report({"dependencies": []}, "dependencies")
def test_incomplete_or_unrecognized_scan_is_rejected(self):
for report in [{}, {"SchemaVersion": 2, "ArtifactName": "."},
{"SchemaVersion": 3, "ArtifactName": ".", "Results": []}]:
with self.subTest(report=report), self.assertRaises((ValueError, KeyError)):
security.check_report(report, "secrets")
def test_high_findings_and_secrets_block(self):
report = {"SchemaVersion": 2, "ArtifactName": "image", "Results": [{
"Vulnerabilities": [{"Severity": "LOW"}, {"Severity": "HIGH"}, {"Severity": "CRITICAL"}],
"Secrets": [{"Severity": "LOW", "Match": "test-data"}],
}]}
self.assertEqual(len(security.check_report(report, "image")), 2)
self.assertEqual(len(security.check_report(report, "secrets")), 1)
security.redact_secret_matches(report)
self.assertEqual(report["Results"][0]["Secrets"][0]["Match"], "[REDACTED]")
def test_image_without_analyzed_targets_is_rejected(self):
with self.assertRaises(ValueError):
security.check_report({"SchemaVersion": 2, "ArtifactName": "image", "Results": []}, "image")
class ReleaseBoundaryTests(unittest.TestCase):
def setUp(self):
self.record = {
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:" + "a" * 64,
"expected_commit": "b" * 40, "configuration_commit": "c" * 40,
"expected_version": "v1", "expected_total": 30,
"proxy_network": "gitea_web", "target_env": "staging",
"public_url": "https://staging.yebilly.me",
}
@patch("release.subprocess.run")
def test_both_commits_must_be_reviewed_main_ancestors(self, run):
release.verify(self.record)
self.assertEqual([call.args[0][-2] for call in run.call_args_list], ["b" * 40, "c" * 40])
self.assertTrue(all(call.kwargs["check"] for call in run.call_args_list))
@patch("release.subprocess.run")
def test_cross_environment_url_is_rejected(self, run):
self.record["public_url"] = "https://app.yebilly.me"
with self.assertRaises(ValueError):
release.verify(self.record)
def test_mutable_tag_or_other_registry_is_rejected(self):
for image in ["git.yebilly.me/ssw590-group1/pricing:latest", "example.com/pricing@sha256:" + "a" * 64]:
self.record["release_image"] = image
with self.assertRaises(ValueError):
release.verify(self.record)
def test_unexpected_ansible_variables_are_rejected(self):
self.record["ansible_host"] = "unapproved-host"
with self.assertRaises(ValueError):
release.verify(self.record)
class UnchangedRerunTests(unittest.TestCase):
def check_recap(self, text, exit_code=0):
original = Path.cwd()
with tempfile.TemporaryDirectory() as directory:
try:
os.chdir(directory)
Path('release.json').write_text(json.dumps({'target_env': 'staging'}))
with patch('sys.argv', ['run-ansible.py', 'release.json', 'rerun', 'playbook.yml']), \
patch.object(run_ansible.subprocess, 'Popen') as launch, \
patch('sys.stdout', new_callable=io.StringIO), \
patch('sys.stderr', new_callable=io.StringIO):
launch.return_value.stdout = io.StringIO(text)
launch.return_value.wait.return_value = exit_code
return run_ansible.main()
finally:
os.chdir(original)
def test_unchanged_success_passes(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=0 unreachable=0 failed=0 skipped=0\n'), 0)
def test_success_with_unnecessary_changes_blocks(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=1 unreachable=0 failed=0 skipped=0\n'), 1)
def test_missing_recap_is_not_a_success(self):
self.assertEqual(self.check_recap('No deployment results\n'), 1)
def test_ansible_error_blocks_even_with_good_looking_recap(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=0 unreachable=0 failed=0\n', 1), 1)
if __name__ == "__main__":
unittest.main()
+32
View File
@@ -0,0 +1,32 @@
Sat Nov 14 20:46:17 UTC 2026
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),0(root)
Python 3.13.5
ansible [core 2.21.6]
config file = None
configured module search path = ['/home/jenkins/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /opt/delivery-tools/lib/python3.13/site-packages/ansible
ansible collection location = /opt/ansible-collections
executable location = /opt/delivery-tools/bin/ansible
python version = 3.13.5 (main, Aug 10 2026, 12:06:59) [GCC 14.2.0] (/opt/delivery-tools/bin/python3)
jinja version = 3.1.6
pyyaml version = 6.0.3 (with libyaml v0.2.5)
# /opt/ansible-collections/ansible_collections
Collection Version
---------------------------------------- -------
community.docker 5.4.0
community.library_inventory_filtering_v1 1.1.5
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
Version: 0.76.2
pip-audit 2.10.1
uid=1000(deploy) gid=1000(deploy) groups=1000(deploy)
Python 3.12.3
Docker version 29.9.3, build 5457199
Docker Compose version v5.7.1
total used free shared buff/cache available
Mem: 1967 1089 85 4 955 878
Swap: 2047 102 1945
1
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 24G 9.5G 14G 41% /
+6
View File
@@ -0,0 +1,6 @@
rules:
- id: ssw590-synthetic-secret
category: course-test
title: SSW590 synthetic blocked-gate fixture
severity: HIGH
regex: 'SSW590_SYNTHETIC_SECRET_[A-Z0-9]{16}'