Compare commits

...
Author SHA1 Message Date
vsun1 a19fab34e3 Merge pull request 'Fix noninteractive Ansible deployment and record delivery gates' (#25) from codex/assignment8-release-evidence into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 2m7s
Reviewed-on: #25
Reviewed-by: bill <yebilly4@gmail.com>
2026-11-16 01:51:04 +00:00
vsun1 5b703edc79 Fix noninteractive Ansible deployment and record delivery gates
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-11-15 18:07:48 -05:00
vsun1 09731acb03 Merge pull request 'Prepare Assignment 8 secure delivery and rollback' (#24) from codex/assignment8-secure-delivery into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 2m25s
Reviewed-on: #24
Reviewed-by: bill <yebilly4@gmail.com>
2026-11-15 21:59:30 +00:00
vsun1 ed0a862657 Move CI runners to Droplet and enable application HTTPS
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-11-15 12:49:06 -05:00
vsun1 bf28adc7fb 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.
2026-11-14 17:09:25 -05:00
vsun1 8beefde2a4 Merge pull request 'Finalize Assignment 7 evidence and documentation (refs #19)' (#23) from codex/assignment7-final-corrections into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 4m32s
Reviewed-on: #23
Reviewed-by: bill <yebilly4@gmail.com>
2026-10-28 20:34:40 +00:00
vsun1 4d1996c0ab Finalize Assignment 7 evidence and local manual builds (refs #19)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-10-28 16:23:42 -04:00
bill 34c4c7488a Merge pull request 'Add Prometheus/Grafana monitoring and SRE manual chapter (Assignment 7)' (#22) from feature/issue-19-monitoring into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 45s
Reviewed-on: #22
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-28 18:18:35 +00:00
billandClaude Opus 5.5 11270cfced Address second chapter audit: accuracy and presentation (refs #19)
vpn-dns-gateway/pipeline/pr-main This commit looks good
A second independent, grader-style review of the built PDF found smaller
gaps; all fixed except template-wide items left unchanged.

- Build comparison: phase labels match the 1-minute rate windows
  (15:17:30 is before the build), 15:19:30 row added, Phase header,
  2-minute vs 1-minute rate difference explained, no-annotation reason,
  and the baseline-build deviation from Step 1 stated.
- Full image digests listed; metric inventory gains a labels column;
  collection-test figure adds the HTTPS resolved capture.
- Corrections: network membership of the exporters, dashboard version
  wording, "two and a half minutes", diagram network name, "A SLO/SLA",
  -- rendering in retention flags, dashboard capture predating the
  I/O-wait line.
- Presentation: login URLs as a list, floats for DNS/dashboard figures,
  split wrapped queries, unbroken restart policy, Grafana OSS casing in
  the bibliography, Windows taskbar cropped from Grafana screenshots.
- Starting commit linked; backup pins alpine:3.22 and documents restore;
  MFA recorded for Billy's Discord and GitHub; EVIDENCE.md records the
  PR #22 approvals, pr-main checks, and the live verification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 14:13:51 -04:00
billandClaude Opus 5.5 249488d6fc Address chapter audit: collection-health alert, hardening, citations (refs #19)
vpn-dns-gateway/pipeline/pr-main This commit looks good
An independent review of the SRE chapter against the instructor's rubric
found gaps; each was fixed and, where operational, tested on the droplet.

Monitoring:
- New Grafana rule "Monitoring target down" (up < 1 for 1 m, no data ->
  Alerting). Tested by stopping Blackbox Exporter 17:34:44-17:37:52 UTC:
  it fired and resolved, and "HTTPS service down" fired on NoData when
  every probe series disappeared.
- Blackbox Exporter runs as nobody (65534) instead of the image's root.
- README: runbook for the new rule; contact-point test prompts for the
  password; secrets section reflects the replaced admin password.

Manual (v5.0):
- Alert table with all three rules and their summaries; runbooks in the
  PDF; accurate no-data description; collection-test figure.
- Diagram shows networks per container and the existing volumes.
- Targets table, CPU counters vs /proc/stat, probe module excerpt,
  container identities and mounts, backup command, exposure commands,
  replaced Grafana admin credential, PR #22 and review gate.
- Bibliography enabled with SRE Workbook and tool documentation.
- Corrected baseline memory figures, Jenkins start-up length, dashboard
  version wording, and start-up order; links point to main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:52:13 -04:00
billandClaude Opus 5.5 336eaaefa7 Add SRE monitoring chapter and manual v5.0 (refs #19)
vpn-dns-gateway/pipeline/pr-main This commit looks good
New chapter "Introduction to SRE: Monitoring and Reliability" covering the
eight Assignment 7 rubric rows: deployment and capacity trial, metrics and
probes, HTTPS and exposure tests, dashboard and build comparison, SLI/SLO
worked example and measured window, alert rules and tests, the Jenkins
outage exercise with blameless review (#20, #21), and controls.

- Title page and abstract for Assignment 7 "Grafana and Prometheus SRE --
  Group", version 5.0; Document History entry.
- Hosts table: monitoring containers, ports, volumes, metrics DNS, swap,
  disabled host services, monitoring and backup status.
- Passwords table: Grafana billy and vsun1, monitoring secrets file,
  Discord webhook (hints only).
- Glossary: SLI, SLA, SRE, error budget, exporter, scrape, contact point,
  blameless review. AI prompt log record.
- EVIDENCE.md: SLO window, post-recovery build, probe status codes,
  improvement issues, Grafana accounts. Outage dashboard figure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 13:08:23 -04:00
billandClaude Opus 5.5 b6cf080618 Record alert tests, Jenkins outage drill, and restart persistence (refs #19)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
- Dashboard: CPU panel adds an I/O wait series; the background CPU on
  the 1 GiB droplet is mostly swap-in wait, not computation.
- EVIDENCE.md: normal Jenkins build #1 vs host metrics (no attributable
  change), Discord contact-point test, capacity alert test (threshold
  raised to 70% on the droplet, fired after 5 m, restored to 15%),
  controlled Jenkins outage timeline (firing ~2 m after injection,
  recovery ~1 m after restart), and Prometheus/Grafana restart
  persistence with no collection gap.
- Screenshots: build window, disk alert firing/resolved, Jenkins alert
  firing/resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 12:30:30 -04:00
billandClaude Opus 5.5 d3a5e6bc73 Add Prometheus/Grafana monitoring stack (refs #19)
vpn-dns-gateway/pipeline/head This commit looks good
Assignment 7 (instructor manual v1.42, Chapter 5): Prometheus, Grafana OSS,
Node Exporter and Blackbox Exporter beside Gitea/Jenkins on The-Ocean, pinned
by tag and digest, memory-capped for the 1 GiB droplet, no host ports.

- monitoring/: compose, scrape and probe config, Grafana provisioning
  (data source, Group 1 SRE dashboard, two alert rules, Discord contact
  point via env var), README with deploy/backup/rollback and runbooks,
  EVIDENCE.md with the deploy, capacity and exposure test records.
- deploy/: private probe network (172.30.90.0/28) with Caddy aliases;
  ci allowlist admits only the Blackbox address 172.30.90.10; new
  metrics.yebilly.me route behind the same allowlist.
- manual images: DNS record, Discord webhook, contact-point test, dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 11:11:02 -04:00
vsun1 9b0dc4dc52 Merge pull request 'Finalize Assignment 6 documentation corrections' (#18) from codex/assignment6-final-corrections into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 34s
Reviewed-on: #18
Reviewed-by: bill <yebilly4@gmail.com>
2026-10-23 23:15:45 +00:00
vsun1 d54d801020 Finalize Assignment 6 documentation corrections
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
2026-10-23 18:06:07 -04:00
bill ac18f11186 Merge pull request 'Manual 4.1: access path, campus test, audit fixes' (#17) from docs/history-initials into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 34s
Reviewed-on: #17
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-23 20:55:12 +00:00
billandClaude Opus 5.5 6152f4777b Address re-audit findings in the Jenkins chapter (v4.1)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
- Add a table of all 14 Gitea webhook deliveries with commits and
  results, and diagnose the real timed-out delivery #3 (Jenkins still
  queued the build two seconds later).
- Redraw the deployment figure as a UML deployment diagram with
  <<device>>/<<container>>/<<artifact>>/<<executionEnvironment>>
  stereotypes; route checkout and status through Caddy.
- Show the stored Jenkins URL, free disk space, and reconciled plugin
  counts (59 tested, 63 locked, 66 installed).
- Correct wording on push rights (jenkins-bot also has Write), the
  resource-limit change, five corrective actions, startup timings, and
  the AI log's backup statement; quote the run-1 checkout.
- Fix the stray tab that printed "extttStevens-Net", the stale
  "version 4.0" sentence, and the overflowing VPN table row; note that
  grader IPs are removed from .env after grading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:01:00 -04:00
billandClaude Opus 5.5 34bd5e6146 Correct Jenkins instructor access path and record campus test (v4.1)
The manual said the instructor could reach ci.yebilly.me from campus or
the Stevens VPN. A GlobalProtect test (sitvpn.stevens.edu, the only
gateway) showed the VPN is split-tunnel: only 155.246.0.0/16 is routed
through it, so off-campus visitors keep their own ISP address and get
403. The approved path is now the campus network (Stevens-Net), with
off-campus graders' addresses added to CI_TEAM_IPS on request.

Vincent's campus test on Stevens-Net (155.246.151.38) loaded the Jenkins
sign-in page; it is added as a figure and a PASS row in the exposure
table alongside the VPN finding. Password field and personal addresses
are redacted. Bumps the manual to 4.1 with a history row and AI log
entry, and updates the Caddyfile comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:46:41 -04:00
billandClaude Opus 5.5 92bc9545e2 Use short AI initials in Document History (CDX, CD)
Replace the tool names in the Author Initials column with initials:
OpenAI Codex -> CDX (matching the existing DDM, CDX rows) and Anthropic
Claude -> CD. GEM is reserved for Google Gemini; no row uses it yet.
Only the initials column changes; dates, versions, and change text are
untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 14:23:33 -04:00
bill e4f3ce5dfb Merge pull request 'Document Assignment 6 Jenkins CI in the manual' (#16) from docs/assignment6-jenkins-manual into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 32s
Reviewed-on: #16
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-23 01:24:41 +00:00
billandClaude Opus 5.5 1149e9fbc3 Document Assignment 6 Jenkins CI in the manual (refs #14)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Add the Continuous Integration with Jenkins chapter in the eight rubric
sections: deployment and persistence (capacity test, memory-limit fix,
restart test), HTTPS/access/firewall with IPv4 and IPv6 exposure checks,
webhook traceability with an actual deployment diagram, pipeline stages,
the required pr-main merge gate, PR #15's failure/repair/review/merge
sequence, credentials and controller build boundary, and controls.

Update the Hosts and Passwords tables (1 GiB resize, Jenkins and
ci.yebilly.me, jenkins-bot account and token hints), the title page,
abstract, Document History, glossary, and AI prompt log (including
Vincent's prepared Oct 19-21 record). Note that Assignment 5's PR #13
merged.

Also version pipeline-graph-view and its dependencies in the Jenkins
plugin lockfile, and add Vincent's source-only ci/jenkins-capacity test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:20:31 -04:00
bill 420ba4c56b Merge pull request 'Add Jenkins CI with required merge check' (#15) from feature/issue-14 into main
vpn-dns-gateway/pipeline/head This commit looks good
Automated Manual Build / manual (push) Successful in 30s
Reviewed-on: #15
Reviewed-by: vsun1 <vsun4046@gmail.com>
2026-10-23 00:55:20 +00:00
billandClaude Opus 5.5 9381d2aa9a Repair total_price: restore multiplication (refs #14)
vpn-dns-gateway/pipeline/pr-main This commit looks good
Reverts the controlled failure from 52b297c so the Jenkins Test stage
passes again and the required check on PR #15 turns green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:15:06 -04:00
billandClaude Opus 5.5 52b297c2f3 Controlled failure: add instead of multiply in total_price (refs #14)
vpn-dns-gateway/pipeline/pr-main There was a failure building this commit
Deliberately breaks the pricing calculation so the Jenkins Test stage
fails (10 + 3 = 13, expected 30) and the required Gitea check blocks
merging PR #15. The next commit restores multiplication.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:10:28 -04:00
billandClaude Opus 5.5 ad35197ee4 Add Jenkins CI service, pricing app, tests and Jenkinsfile (refs #14)
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
Deploy Jenkins LTS 2.580.1 beside Gitea on The-Ocean:
- deploy/jenkins: official image pinned by digest plus python3 and a
  hashed 60-plugin lockfile (Pipeline + Gitea bundle tested by
  ci/jenkins-capacity, plus matrix-auth for named roles)
- compose: jenkins service with persistent jenkins-home, no published
  ports, 512 MiB RAM / 768 MiB RAM+swap / 0.75 CPU, 256 MiB heap
- Gitea webhooks restricted to the private jenkins host; Caddy alias
  keeps Jenkins->Gitea checkout and status traffic on the droplet
- Caddy serves ci.yebilly.me only to Stevens 155.246.0.0/16 and team
  IPs from the untracked .env

Add the instructor's pricing example, unit tests and Declarative
Jenkinsfile (checkout, syntax check, unit tests).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:55:59 -04:00
vsun1 1389c53165 Merge pull request 'Automate LaTeX manual builds with Gitea Actions' (#13) from codex/assignment5-manual-build into main
Automated Manual Build / manual (push) Successful in 36s
Reviewed-on: #13
Reviewed-by: bill <yebilly4@gmail.com>
2026-10-08 05:19:02 +00:00
136 changed files with 8347 additions and 70 deletions
+7
View File
@@ -0,0 +1,7 @@
# Docker/Jenkins shell scripts require Unix line endings on Windows checkouts.
delivery/**/*.sh text eol=lf
delivery/agent/ssh_config.droplet text eol=lf
gitea/droplet-runner/*.sh text eol=lf
# Preserve spaces emitted by tools in captured evidence.
delivery/evidence/*.txt -whitespace
+10 -2
View File
@@ -91,5 +91,13 @@ Thumbs.db
*.key
secrets.*
# Source images, the reference template, and the reviewed root submission PDF
# are intentionally not ignored.
# Source images and the reference template remain versioned.
# Local manual builds replace one deliverable; do not commit generated PDFs.
/manual/2026F-SSW-590-DevOps-Group-1.pdf
/manual/latex/devopsAssignment.pdf
# Python test environments and bytecode
.venv/
.ansible-venv/
__pycache__/
*.pyc
Vendored
+27
View File
@@ -0,0 +1,27 @@
pipeline {
agent any
options { skipDefaultCheckout() }
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Syntax check') {
steps {
sh 'python3 -m py_compile pricing.py'
sh '''python3 -B - <<'PY'
import ast
from pathlib import Path
for source in Path('delivery').rglob('*.py'):
ast.parse(source.read_text(), filename=str(source))
print('Delivery Python syntax: passed')
PY'''
}
}
stage('Test') {
steps {
sh 'python3 -m unittest discover -s tests -v'
sh 'python3 -B -m unittest discover -s delivery/ci -p "test_controls.py" -v'
}
}
}
}
+202
View File
@@ -0,0 +1,202 @@
# Jenkins plugin and pipeline capacity experiment
Prepared for Vincent Sun and Billy Ye on October 21, 2026. This disposable test
passed locally in Docker Desktop; it has NOT run on The-Ocean and is not the
Assignment 6 deployment. See `VALIDATION.md` for the evidence and limitations.
## The question we are answering
Can The-Ocean's existing 512 MB plan run the Jenkins features we need, together
with Gitea, under the limits used in the earlier core-only experiment?
Jenkins core is the base server. Plugins add features to it. Pipeline supplies
the job execution engine and steps; the Gitea connector supplies integration
with Gitea. A plugin can download successfully but fail to load because of
incompatible dependencies or insufficient memory. Loading successfully also
does not prove that a build can run. We check these separately.
The previous core-only experiment started Jenkins, but its final accounting
included about 212 MiB swap as well as 80 MiB RAM. Its raw 60-second PASS was
qualified because the successful HTTP samples spanned only 54 seconds.
## What, why and how
| Check | Why it matters | How we test / pass criterion |
|---|---|---|
| Fresh baseline | Yesterday's resources may differ today | Correct hostname/root session, available RAM >=128 MiB, swap free >=512 MiB, enough Docker disk, unused test port, Gitea HTTP 200 |
| Prepare plugins on the laptop | Catalog processing exceeded the old 128 MiB installer heap locally | Official installer resolves the selected plugins in a separate laptop container with 768 MiB RAM / 512 MiB heap; exact roots, all resolved versions and archive hashes recorded |
| Tools and plugin installation on the target | The useful system needs more than Jenkins core | In a fresh capped container, install Python/Git and copy the verified prepared archives; inspect the installed versions before Jenkins starts |
| Plugin loading | Files on disk are not evidence that Jenkins loaded them | After initialization, verify requested plugins at expected versions, every installed plugin active and no failed-plugin entries |
| Healthy idle | A momentary login response is too weak | HTTP `/login` returns 200 over >=60 seconds of sampled observations AFTER initialization and plugin verification; any failed probe resets the clock |
| Passing pipeline | Exercise actual execution and unit tests | One executor runs dependency checks, a fresh local fixture, Python syntax checking and two unit tests; Jenkins reports SUCCESS |
| Controlled failure | Prove the tests actually detect a defect | Change multiplication to addition only in the disposable workspace; Jenkins reports FAILURE and console proves the intended `13 != 30` assertion, not an unrelated infrastructure error |
| Repair | Prove recovery works without restarting the service | Recreate the original fixture in a fresh workspace on the same job; the two tests run and Jenkins reports SUCCESS |
| Shared-host protection | Jenkins must not consume all the host's resources | Repeatedly check host available RAM/free swap, Gitea HTTP 200, container RAM/swap, CPU throttling and OOM counters; abort on guard failure |
| Cleanup | Leave existing coursework services intact | Remove only this owner-labelled test container and its anonymous home volume; preserve evidence and the base image; check Gitea afterward |
This is a small selected plugin set, not the smallest theoretically possible
dependency graph. `workflow-aggregator` is a suite, so two requested IDs will
produce more than two installed plugins. The current root requests are:
```text
workflow-aggregator:608.v67378e9d3db_1
gitea:286.v0740a_413c1eb_
```
The prepared local bundle contains 59 plugin archives (45,336,313 bytes). Two
requested features therefore do not mean two loaded files. The official plugin
pages checked October 21 list minimum Jenkins versions
2.479.3 and 2.528.3 respectively, below the recorded 2.580.1 core. That baseline
comparison is only a preliminary check; dependency resolution and actual loading
are still tested. Laptop preparation uses the official bundled `jenkins-plugin-cli`.
Current dependencies are resolved (`--latest true`) rather than deliberately
installing the old aggregator's minimum dependency versions. Requested roots
are checked for an exact match; every resolved archive version and SHA-256 goes
into the prepared `manifest.json`, with a full `plugins.lock` beside it. The
target verifies the hashes before starting Docker, then inventories the copied
archives again as `plugins-resolved.json` / `plugins-resolved.lock`.
Keep installer security warnings visible in prepared `installer.txt` and review them before
any real deployment. No flag hides warnings or skips failed plugins.
New dependency preparation and Debian package versions can change between runs.
Reusing the SAME prepared bundle fixes the plugin archives and hashes for the
target comparison; Python/Git apt versions remain recorded, not fully locked.
Retain the lock file/hashes and package-version output. Do not silently
substitute a different image/plugin set and compare it as the same experiment.
## Isolation and resource limits
- Same official core image tag as before, now also pinned to its recorded digest:
`jenkins/jenkins:2.580.1-jdk21@sha256:a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1`.
- 256 MiB container RAM; 512 MiB combined RAM plus swap, allowing up to 256 MiB
container swap. Half one CPU, 256 processes, Java heap 32-128 MiB and Serial GC.
- These target limits cover Python/Git installation, copying the prepared
plugins, AND Jenkins/Python pipeline runtime. Plugin catalog resolution and
downloads are a SEPARATE laptop-only preparation: 768 MiB RAM, 1 GiB combined
RAM+swap, 512 MiB Java heap, one CPU, no service port, fifteen-minute timeout.
Those preparation limits are not proposed for the 512 MB droplet. The base-image
pull is also separate, reused if cached, and bounded to five minutes.
- Existing host swap, packages, proxy, firewall, Gitea data and containers are
not changed. The installer runs as root inside the temporary container only;
the Jenkins process and its builds then run as the container's `jenkins` user.
- Only this source directory and the prepared plugin directory are mounted,
both read-only. No Docker socket, real
credential, runner registration, production checkout or existing Jenkins home.
- Only `127.0.0.1:18080` is published. Nothing is attached to Caddy or a public
Jenkins hostname. The disposable instance has authentication enabled and
anonymous read disabled. Its random test-account password is generated inside
Jenkins, never printed/read/exported, and discarded with the temporary home.
Setup-wizard automation is specific to this disposable instance.
- One built-in executor runs only this reviewed local fixture. This is an explicit
capacity-test choice, not approval to run arbitrary PR code on a production
controller. No separate agent is tested here.
- A sampled host floor of 48 MiB available RAM or 128 MiB free swap aborts the
run; any sampled Gitea non-200, container OOM event or unexpected exit also
aborts. These are sampled best-effort guards, not a guarantee that Gitea can
never be affected between probes. A failed health request alone does not
establish that Jenkins caused the failure.
- Installation timeout: 20 minutes. Startup/idle timeout: 15 minutes. Pipeline
phase: 10 minutes; each build has a three-minute outer wait. Overall: 45 minutes.
A detached watchdog attempts targeted cleanup after 46 minutes if SSH drops.
Normal interruption also runs cleanup. Check `cleanup_ok` and inspect leftovers
after machine/Docker failure; no script can guarantee cleanup of a stopped host.
- Requires Linux cgroup v2, Docker, Python 3.8+ on the HOST and root on The-Ocean.
Ubuntu 24.04 normally provides Python, but the preflight must confirm it.
The explicit Windows `--local-smoke-test` mode applies the same CONTAINER runtime
limits but does not run the droplet host RAM/swap/disk guards or Gitea checks.
Those fields are recorded as null, not invented measurements. Docker Desktop's
VM has different resources and does not host the real Gitea service, so local
success does not answer whether Jenkins and Gitea can share the droplet.
The experiment adds no cloud instance, subscription or resize. It uses the team's
existing droplet, disk and ordinary package/plugin/image download traffic; provider
transfer billing, if applicable, remains subject to the existing account plan.
Vincent/Billy own execution and cleanup. No maintenance/reboot is performed.
## Run when SSH access is restored
For the local regression checks only, run `python ci/jenkins-capacity/test_harness.py`
from the repository on Windows, or use `python3` on Linux. These standard-library
tests need no Docker or cloud access and do not launch Jenkins. They cannot
replace the real experiment below.
First collect/review the baseline as discussed. This script intentionally refuses
the `--run-on-the-ocean` option on Vincent's laptop or a differently named host.
Do not change that guard to obtain a false droplet PASS. Docker Desktop is not
needed to upload/run the PREPARED package; Docker on the droplet is needed.
Use the prepared ZIP, which includes a `jenkins-capacity` directory with its
`prepared-plugins` subdirectory. Extract it to a new task-local folder. From
**PowerShell in the extracted ZIP's parent folder**:
```powershell
scp -i "$env:USERPROFILE\.ssh\digitalocean" -r .\jenkins-capacity root@147.182.178.136:/root/ssw590-plugin-test
ssh -i "$env:USERPROFILE\.ssh\digitalocean" root@147.182.178.136
```
The SCP command assumes `/root/ssw590-plugin-test` does not already exist. If it
does, inspect its contents before copying; SCP may nest the source directory.
Upload the whole directory, not only `run_test.py`. Billy uses his own trusted
SSH key, not Vincent's key path.
Then **inside the droplet's Linux terminal**:
```sh
cd /root/ssw590-plugin-test
python3 --version
python3 run_test.py --help
python3 run_test.py --run-on-the-ocean
```
Expect progress lines naming `tools`, `plugins`, `startup/ready`, and
`startup/pipelines`, followed by `result.json` and the evidence path. During
installation, Jenkins HTTP is reported as 0 because Jenkins has not started;
Gitea should remain 200. You can stop with Ctrl+C; let cleanup finish.
Evidence goes under `/root/ssw590-capacity-evidence/plugins-<UTC>-<PID>/`.
Download that exact printed directory with SCP for review. It contains baseline,
input hashes, base-image identity, resource samples, checkpoint duration, resolved
plugins, controlled build logs, final state and result. It deliberately excludes
raw Jenkins controller logs, the credential-bearing home and private keys.
For a NEW bundle from source on Windows (not needed to use the packaged one):
```powershell
python ci/jenkins-capacity/prepare_plugins.py --output build/jenkins-plugin-bundle
python ci/jenkins-capacity/run_test.py --local-smoke-test --plugin-bundle build/jenkins-plugin-bundle
```
The preparation command refuses to overwrite an existing bundle. Preserve or
review the old bundle first. In the repository the archives live under ignored
`build/`; they are packaged into `prepared-plugins` for upload, not committed.
Interpret the result by phase. Preparation failure can be a download, dependency,
disk or memory problem; it does not automatically mean Jenkins cannot run.
Target installation failure may come from apt/tools or copying/unpacking plugins.
Startup failure can be plugin compatibility or resource pressure. An intentional
fixture FAILURE is expected only if the correct unit-test assertion is present.
Check OOM/CPU/swap and installer output before attributing a cause. A PASS with
heavy swap or throttling demonstrates feasibility under this small test, not
comfortable capacity, long-term reliability, concurrency or production readiness.
## What a PASS does not prove
The Gitea plugin must load here, but this experiment does not configure or exercise
Gitea discovery, SCM checkout, PR head selection, webhooks, credentials, status
reporting or branch protection. Git is installed and its version checked; no
repository is cloned. The pipeline is the bundled local fixture, not yet the
assignment's root repository Jenkinsfile. The fixture's repair is not a real
issue-linked reviewed PR. No HTTPS deployment, restart persistence, real admin
accounts, concurrent runner test, final report chapter or assignment completion
is claimed. Those are subsequent implementation/evidence steps.
## Primary references
- [Official Jenkins Docker image and plugin customization](https://github.com/jenkinsci/docker)
- [Plugin installation manager options and dependency behavior](https://github.com/jenkinsci/plugin-installation-manager-tool)
- [Pipeline suite](https://plugins.jenkins.io/workflow-aggregator/)
- [Gitea connector](https://plugins.jenkins.io/gitea/)
- [Groovy initialization hooks](https://www.jenkins.io/doc/book/managing/groovy-hook-scripts/)
- [Controller isolation and built-in executor risks](https://www.jenkins.io/doc/book/security/controller-isolation/)
- [Docker RAM, swap and CPU constraints](https://docs.docker.com/engine/containers/resource_constraints/)
+73
View File
@@ -0,0 +1,73 @@
# Verification, October 21, 2026
**Prepared and passed in Windows Docker Desktop. NOT run on The-Ocean.**
## Actual Docker results
1. Initial all-in-one local attempt, `plugins-20261021T232534Z-28212`: Python/Git
installation succeeded, but `jenkins-plugin-cli` failed with Java heap space
exhaustion while fetching the plugin-version catalog at the original 128 MiB
heap. Container exit code was 1; Docker `OOMKilled` was false. This was a JVM
heap failure, not a kernel container kill and not a Jenkins runtime test.
Cleanup succeeded. Original installer output/result were preserved.
2. Separate local plugin preparation: official installer, 768 MiB container RAM,
1 GiB combined RAM+swap, 512 MiB Java heap, one CPU. Successfully resolved 59
archives totaling 45,336,313 bytes, with exact requested root versions and a
SHA-256/version manifest. The preparation container was removed. This proves
that these preparation bounds worked, not the minimum memory the installer
needs. It did not start Jenkins.
3. Revised runtime test, `plugins-20261021T233125Z-27744`: SAME original runtime
limits (256 MiB RAM, 512 MiB combined RAM+swap, half a CPU, 128 MiB Java heap).
All 59 plugins were active, no failed plugins were reported, and healthy HTTP
samples spanned **65.39 seconds** before jobs started. Build 1 was SUCCESS;
build 2 was FAILURE with the intended `13 != 30` assertion and two unit tests
executed; build 3 repaired the calculation and was SUCCESS. Final result PASS,
cleanup true. A subsequent owner-label query found no experiment containers.
Twenty runtime samples recorded peak cgroup RAM 255.99 MiB, peak swap 137.63 MiB,
and peak SIMULTANEOUS RAM+swap 389.51 MiB. The maxima of RAM and swap need not occur
at the same time. Container OOM/OOM-kill events were zero; the RAM cap was reached
repeatedly and CPU throttling occurred. These results demonstrate this small
runtime exercise on the laptop, not spare capacity or concurrent Gitea safety.
Docker Desktop reported 16 CPUs and about 13.5 GiB VM memory. Local mode deliberately
did not measure the droplet's host memory, swap, disk or Gitea health: those fields
are null. The real droplet has about 458 MiB RAM and runs Gitea/Caddy. Its guarded
run remains necessary. No new cloud resource, firewall change or reboot occurred.
Raw local evidence remains under ignored `build/evidence/jenkins-plugin-local/`;
prepared binaries/manifest are under ignored `build/jenkins-plugin-bundle/`.
The shareable ZIP includes the prepared archives and selected non-secret local
evidence. No controller logs, Jenkins home, token, SSH key or generated test
password is included. The official base image is cached for reuse; the temporary
containers and anonymous homes were removed.
## Local regression and static checks
- Nine Python regression/fault checks passed: the previous 54-second false PASS,
failed-probe timer reset, monitor's complete idle gate, low memory/swap aborts,
refusal to delete another owner's container, cleanup despite diagnostic errors,
separate cgroup accounting, folded plugin manifests/exact root versions, and
actual Python fixture pass/failure/repair.
- Bash bootstrap syntax was checked and actual Docker execution succeeded.
- Opted-in droplet execution on Windows was rejected before Docker activity;
the container bootstrap also refused execution outside its test container.
- Python sources parsed and Linux inputs used LF endings.
- Plugin root versions/minimum core baselines were checked against official
Jenkins pages. Actual installation and activation supplied stronger evidence.
## Still unverified
- Droplet capacity with Gitea/Caddy, host pressure guards, site checks, target apt
availability and cleanup/watchdog behavior after a real SSH disconnect.
- Gitea discovery/SCM checkout/PR revision selection/webhooks/status reporting,
merge protection, a production build boundary, HTTPS deployment and persistence.
- The real reviewed failure/repair PR and Assignment 6 report chapter/submission.
SSH and the web console time out from school. The attached Cloud Firewall visibly
allowed the measured school IPv4; Gitea HTTPS returned 200 while direct TCP 22
timed out. This does not establish where filtering occurs. Docker was initially
off, then Vincent enabled it and authorized using it for local verification.
This directory supplements the earlier October 21 Billy/Claude handoff, which
predates this new test and manual record. No commit or push was performed.
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
# Runs INSIDE the newly created disposable container, never on the host.
set -euo pipefail
[ "${SSW590_DISPOSABLE_TEST:-}" = 1 ] && [ -f /.dockerenv ] && [ -d /opt/ssw590-input ] || {
echo 'Refusing: this bootstrap runs only inside the disposable test container.' >&2
exit 1
}
umask 022
mkdir -p /tmp/ssw590
chmod 755 /tmp/ssw590
echo tools > /tmp/ssw590/phase
{
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install --no-install-recommends -y python3 git util-linux
apt-get clean
rm -rf /var/lib/apt/lists/*
python3 --version
git --version
echo plugins > /tmp/ssw590/phase
mkdir -p /usr/share/jenkins/ref/plugins /usr/share/jenkins/ref/init.groovy.d
chown jenkins:jenkins /usr/share/jenkins/ref/plugins
# Catalog resolution is prepared on the laptop, outside the runtime limits.
# The host verifies this bundle's hashes before mounting it read-only.
cp /opt/ssw590-plugins/*.jpi /usr/share/jenkins/ref/plugins/
chown -R jenkins:jenkins /usr/share/jenkins/ref/plugins
python3 /opt/ssw590-input/inventory.py /usr/share/jenkins/ref/plugins \
/opt/ssw590-input/plugins.txt > /tmp/ssw590/plugins-resolved.json
python3 - <<'PY' > /tmp/ssw590/plugins-resolved.lock
import json
for p in json.load(open('/tmp/ssw590/plugins-resolved.json')):
print(p['id'] + ':' + p['version'])
PY
cp /opt/ssw590-input/init.groovy /usr/share/jenkins/ref/init.groovy.d/90-capacity.groovy
chown -R jenkins:jenkins /tmp/ssw590
} > /tmp/ssw590/install.txt 2>&1
echo startup > /tmp/ssw590/phase
# Replace the preparer with the normal official Jenkins launcher, as non-root.
exec runuser -u jenkins -- /usr/bin/tini -- /usr/local/bin/jenkins.sh
+27
View File
@@ -0,0 +1,27 @@
// Disposable, locally supplied fixture; no SCM credentials or production checkout.
node {
stage('Dependencies') {
sh 'python3 --version && git --version'
}
stage('Fresh fixture') {
// Delete only this disposable job workspace, inside the test container.
deleteDir()
sh 'cp -R /opt/ssw590-input/fixtures/. .'
if (params.BREAK_CALCULATION) {
sh '''python3 - <<'PY'
from pathlib import Path
p = Path('pricing.py')
s = p.read_text()
assert s.count('return unit_price * quantity') == 1
p.write_text(s.replace('return unit_price * quantity', 'return unit_price + quantity'))
PY'''
}
sh 'sha256sum pricing.py'
}
stage('Syntax') {
sh 'python3 -m py_compile pricing.py'
}
stage('Unit tests') {
sh 'python3 -m unittest discover -s tests -v'
}
}
+4
View File
@@ -0,0 +1,4 @@
def total_price(unit_price, quantity):
if quantity < 1:
raise ValueError("Quantity must be positive")
return unit_price * quantity
@@ -0,0 +1,12 @@
import unittest
from pricing import total_price
class PricingTests(unittest.TestCase):
def test_total(self):
self.assertEqual(total_price(10, 3), 30)
def test_invalid_quantity(self):
with self.assertRaises(ValueError):
total_price(10, 0)
+106
View File
@@ -0,0 +1,106 @@
import groovy.json.JsonOutput
import hudson.init.InitMilestone
import hudson.model.BooleanParameterDefinition
import hudson.model.BooleanParameterValue
import hudson.model.ParametersAction
import hudson.model.ParametersDefinitionProperty
import hudson.security.FullControlOnceLoggedInAuthorizationStrategy
import hudson.security.HudsonPrivateSecurityRealm
import hudson.security.ACL
import jenkins.model.Jenkins
import java.util.concurrent.TimeUnit
// Trusted administrator bootstrap, only in a new temporary home. Never log secrets.
def j = Jenkins.get()
def realm = new HudsonPrivateSecurityRealm(false)
realm.createAccount('capacity-test', UUID.randomUUID().toString() + UUID.randomUUID().toString())
j.setSecurityRealm(realm)
def authorization = new FullControlOnceLoggedInAuthorizationStrategy()
authorization.setAllowAnonymousRead(false)
j.setAuthorizationStrategy(authorization)
j.setNumExecutors(1)
j.setQuietPeriod(0)
j.save()
def root = new File('/tmp/ssw590')
def state = [phase: 'initializing', builds: []]
def writeState = {
def temporary = new File(root, 'status.next')
temporary.text = JsonOutput.toJson(state)
java.nio.file.Files.move(temporary.toPath(), new File(root, 'status.json').toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE)
}
writeState()
Thread.startDaemon('ssw590-disposable-test') {
// The trusted bootstrap worker needs the same system identity as the init hook.
def securityContext = ACL.as2(ACL.SYSTEM2)
try {
while (j.getInitLevel() != InitMilestone.COMPLETED) { Thread.sleep(1000) }
state.plugins = j.pluginManager.plugins.collect {
[id: it.shortName, version: it.version, active: it.isActive()]
}
state.failedPlugins = j.pluginManager.failedPlugins.collect { it.name }
def requested = new File('/opt/ssw590-input/plugins.txt').readLines().findAll { it.trim() }
requested.each { entry ->
def (id, version) = entry.trim().split(':', 2)
def p = j.pluginManager.getPlugin(id)
if (p == null || !p.isActive() || p.version != version) {
throw new IllegalStateException('Requested plugin not active at expected version: ' + id)
}
}
if (state.failedPlugins || state.plugins.any { !it.active }) {
throw new IllegalStateException('Plugin load failure; inspect recorded inventory')
}
// Access plugin classes only after checking that they loaded.
def jobClass = j.pluginManager.uberClassLoader.loadClass('org.jenkinsci.plugins.workflow.job.WorkflowJob')
def definitionClass = j.pluginManager.uberClassLoader.loadClass('org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition')
def job = j.createProject(jobClass, 'capacity-pricing')
job.addProperty(new ParametersDefinitionProperty(
new BooleanParameterDefinition('BREAK_CALCULATION', false, 'Disposable failure exercise')))
job.setDefinition(definitionClass.getConstructor(String.class, Boolean.TYPE).newInstance(
new File('/opt/ssw590-input/fixtures/Jenkinsfile').text, true))
job.save()
state.phase = 'ready'
writeState()
// Host must observe >=60 seconds of healthy HTTP AFTER plugin checks first.
while (!new File(root, 'start-jobs').exists()) { Thread.sleep(1000) }
state.phase = 'pipelines'
writeState()
def cases = [[name: 'pass', broken: false, expected: 'SUCCESS'],
[name: 'intentional-failure', broken: true, expected: 'FAILURE'],
[name: 'repair', broken: false, expected: 'SUCCESS']]
for (testCase in cases) {
def future = job.scheduleBuild2(0, new ParametersAction(
new BooleanParameterValue('BREAK_CALCULATION', testCase.broken)))
if (future == null) { throw new IllegalStateException('Build could not be scheduled') }
def build = future.get(180, TimeUnit.SECONDS)
// Only these known fixture-job logs are copied, never controller logs.
def console = build.getLog(500).join('\n') + '\n'
new File(root, testCase.name + '-console.txt').text = console
def observed = build.result.toString()
state.builds << [name: testCase.name, number: build.number,
expected: testCase.expected, actual: observed]
writeState()
if (observed != testCase.expected) {
throw new IllegalStateException('Unexpected fixture build result: ' + testCase.name)
}
if (!console.contains('Ran 2 tests')) {
throw new IllegalStateException('Unit tests did not actually execute')
}
if (testCase.broken && (!console.contains('13 != 30') || !console.contains('FAILED (failures=1)'))) {
throw new IllegalStateException('Failure was not the intended calculation assertion')
}
}
state.phase = 'complete'
writeState()
} catch (Throwable failure) {
state.phase = 'failed'
// Fixed harness error text/type; do not dump arbitrary stack traces or secrets.
state.errorType = failure.class.name
writeState()
} finally {
securityContext.close()
}
}
+39
View File
@@ -0,0 +1,39 @@
"""Inspect downloaded plugin archives without loading Jenkins or reading secrets."""
import email.parser
import hashlib
import json
from pathlib import Path
import sys
import zipfile
def inventory(directory, requested):
entries = []
for path in sorted(Path(directory).glob("*.jpi")):
with zipfile.ZipFile(path) as archive:
raw = archive.read("META-INF/MANIFEST.MF").decode("utf-8")
# JAR manifests fold lines by prefixing continuation lines with one space.
unfolded = raw.replace("\r\n ", "").replace("\n ", "")
manifest = email.parser.Parser().parsestr(unfolded)
with path.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest() if hasattr(hashlib, "file_digest") else None
if digest is None:
h = hashlib.sha256()
with path.open("rb") as stream:
for block in iter(lambda: stream.read(1024 * 1024), b""):
h.update(block)
digest = h.hexdigest()
entries.append({"id": manifest["Short-Name"], "version": manifest["Plugin-Version"],
"requires_jenkins": manifest["Jenkins-Version"], "sha256": digest})
versions = {p["id"]: p["version"] for p in entries}
roots = [line.strip().split(":") for line in Path(requested).read_text().splitlines() if line.strip()]
for name, version in roots:
if versions.get(name) != version:
raise ValueError(f"Requested root version was not installed exactly: {name}:{version}")
if not entries:
raise ValueError("No plugin archives found")
return entries
if __name__ == "__main__":
print(json.dumps(inventory(sys.argv[1], sys.argv[2]), indent=2))
+2
View File
@@ -0,0 +1,2 @@
workflow-aggregator:608.v67378e9d3db_1
gitea:286.v0740a_413c1eb_
+74
View File
@@ -0,0 +1,74 @@
"""Resolve plugins on Windows Docker Desktop, never on the small droplet.
This launches only the official plugin installer, not Jenkins. The output is
non-secret plugin archives plus a hash/version manifest for the runtime test.
"""
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import subprocess
import sys
import inventory
from run_test import IMAGE, LABEL, command, remove_owned
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, required=True, help="NEW local plugin-bundle directory")
args = parser.parse_args()
if sys.platform != "win32":
parser.error("Prepare on Windows Docker Desktop; do not run this on the 512 MB droplet")
output = args.output.resolve()
if output.exists():
parser.error("Output already exists; preserve or review it before preparing another bundle")
bundle = Path(__file__).resolve().parent
owner = "prepare-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ").lower()
container = None
output.mkdir(parents=True)
metadata = {"status": "INCOMPLETE", "environment": "Windows Docker Desktop plugin preparation only",
"base_image": IMAGE, "ram_mib": 768, "ram_plus_swap_mib": 1024,
"heap_max_mib": 512, "cpu": 1, "jenkins_started": False}
try:
if command("docker", "info", "--format", "{{.OSType}}").stdout.strip() != "linux":
raise RuntimeError("Use Docker Desktop's Linux engine")
if command("docker", "image", "inspect", IMAGE, check=False).returncode:
command("docker", "pull", IMAGE, timeout=300)
container = "ssw590-jenkins-" + owner
container = command("docker", "create", "--name", container,
"--label", f"{LABEL}={owner}", "--restart", "no",
"--memory", "768m", "--memory-swap", "1024m", "--cpus", "1", "--pids-limit", "256",
"--mount", f"type=bind,src={bundle},dst=/opt/ssw590-input,readonly",
"--env", "JAVA_OPTS=-Xms32m -Xmx512m -XX:+UseSerialGC",
"--entrypoint", "/bin/bash", IMAGE, "-c",
"mkdir -p /tmp/ssw590-prepared/plugins; "
"jenkins-plugin-cli --war /usr/share/jenkins/jenkins.war "
"--plugin-file /opt/ssw590-input/plugins.txt "
"--plugin-download-directory /tmp/ssw590-prepared/plugins --latest true --list "
"> /tmp/ssw590-prepared/installer.txt 2>&1").stdout.strip()
with (output / "preparer-process.txt").open("w") as log:
subprocess.run(["docker", "start", "--attach", container], stdout=log,
stderr=subprocess.STDOUT, timeout=900, check=True)
command("docker", "cp", container + ":/tmp/ssw590-prepared/plugins/.", str(output), timeout=60)
command("docker", "cp", container + ":/tmp/ssw590-prepared/installer.txt", str(output / "installer.txt"))
plugins = inventory.inventory(output, bundle / "plugins.txt")
(output / "manifest.json").write_text(json.dumps({"base_image": IMAGE, "plugins": plugins}, indent=2) + "\n")
(output / "plugins.lock").write_text("".join(p["id"] + ":" + p["version"] + "\n" for p in plugins))
metadata.update(status="PASS", plugin_count=len(plugins))
except Exception as error:
metadata.update(status="FAILED", reason=str(error))
if container:
command("docker", "cp", container + ":/tmp/ssw590-prepared/installer.txt",
str(output / "installer.txt"), check=False)
finally:
metadata["cleanup_ok"] = remove_owned(container, owner) if container else True
if not metadata["cleanup_ok"]:
metadata["status"] = "NEEDS_ATTENTION"
(output / "preparation.json").write_text(json.dumps(metadata, indent=2) + "\n")
print(json.dumps(metadata, indent=2))
return 0 if metadata["status"] == "PASS" else 1
if __name__ == "__main__":
sys.exit(main())
+402
View File
@@ -0,0 +1,402 @@
"""Bounded, disposable Jenkins plugin/pipeline experiment for The-Ocean.
No SSH, real account credentials, production mounts or host package changes are used.
Run --help for opt-in The-Ocean execution or Windows Docker Desktop validation.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
import inventory
IMAGE = ("jenkins/jenkins:2.580.1-jdk21@sha256:"
"a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1")
LABEL = "ssw590.capacity-owner"
SITE = "https://git.yebilly.me"
PORT = 18080
BOUNDS = ["--memory", "256m", "--memory-swap", "512m", "--cpus", "0.5", "--pids-limit", "256"]
INSTALL_SECONDS = 1200
STARTUP_SECONDS = 900
PIPELINE_SECONDS = 600
TOTAL_SECONDS = 2700
IDLE_SECONDS = 60
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
class Abort(Exception):
pass
def utc():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def command(*args, timeout=15, check=True):
result = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
if check and result.returncode:
# All invoked commands have non-secret arguments and output by construction.
raise Abort(f"Command failed: {args[0]} {args[1:3]}: {result.stderr.strip()[:500]}")
return result
def http_code(url):
try:
with OPENER.open(url, timeout=6) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
except (urllib.error.URLError, TimeoutError, OSError):
return 0
def host_memory():
fields = {}
for line in Path("/proc/meminfo").read_text().splitlines():
key, value = line.split(":", 1)
fields[key] = int(value.strip().split()[0])
return fields["MemAvailable"], fields["SwapFree"]
def resource_guard(available, swap_free, initial=False):
memory_floor, swap_floor = (131072, 524288) if initial else (49152, 131072)
if available < memory_floor:
raise Abort(f"Host available RAM below {memory_floor // 1024} MiB")
if swap_free < swap_floor:
raise Abort(f"Host free swap below {swap_floor // 1024} MiB")
def advance_idle(previous, completed_at, healthy):
"""The clock starts AFTER a successful HTTP probe, and resets on failure."""
if not healthy:
return None, False
started = completed_at if previous is None else previous
return started, completed_at - started >= IDLE_SECONDS
def parse_cgroup(raw):
result = {}
section = None
for line in raw.splitlines():
if line in ("memory.current", "memory.swap.current", "memory.events", "cpu.stat"):
section = line
result[section] = {} if section in ("memory.events", "cpu.stat") else None
elif section in ("memory.events", "cpu.stat"):
key, value = line.split()
result[section][key] = int(value)
elif section:
result[section] = int(line)
if any(result.get(key) is None for key in ("memory.current", "memory.swap.current", "memory.events", "cpu.stat")):
raise Abort("Incomplete cgroup accounting")
return result
def owned_container(container, owner):
result = command("docker", "inspect", "--format", '{{index .Config.Labels "' + LABEL + '"}}',
container, check=False)
return result.returncode == 0 and result.stdout.strip() == owner
def remove_owned(container, owner):
if not owned_container(container, owner):
return False
command("docker", "stop", "--time", "10", container, timeout=20, check=False)
result = command("docker", "rm", "--force", "--volumes", container, timeout=20, check=False)
return result.returncode == 0
def watchdog(container, owner, evidence):
# Detached from SSH. This child can delete ONLY this exact, owner-labelled test.
time.sleep(TOTAL_SECONDS + 60)
if owned_container(container, owner):
removed = remove_owned(container, owner)
(evidence / "watchdog.txt").write_text(f"{utc()} deadline expired; removed={removed}\n")
class Experiment:
def __init__(self, bundle, evidence, local=False, plugin_bundle=None):
self.bundle = bundle.resolve()
self.evidence = evidence
self.local = local
self.plugin_bundle = (plugin_bundle or self.bundle / "prepared-plugins").resolve()
self.owner = evidence.name
self.name = "ssw590-jenkins-plugins-" + self.owner.lower()
self.container = None
self.guard = None
self.result = {"status": "INCOMPLETE", "started": utc(), "scope": "disposable plugin/pipeline capacity",
"environment": "local Docker Desktop; NOT droplet capacity" if local else "The-Ocean"}
def save(self, filename, value):
(self.evidence / filename).write_text(json.dumps(value, indent=2) + "\n")
def preflight(self):
manifest = json.loads((self.plugin_bundle / "manifest.json").read_text())
if manifest.get("base_image") != IMAGE:
raise Abort("Plugin bundle was prepared for a different base image")
if manifest.get("plugins") != inventory.inventory(self.plugin_bundle, self.bundle / "plugins.txt"):
raise Abort("Plugin bundle version/hash verification failed")
self.save("prepared-plugin-manifest.json", manifest)
if self.local:
if sys.platform != "win32":
raise Abort("The local smoke-test option is for Windows Docker Desktop only")
else:
if sys.platform != "linux" or os.geteuid() != 0:
raise Abort("Run as root inside the authorized The-Ocean Linux SSH session")
if socket.gethostname().lower() != "the-ocean":
raise Abort("Unexpected host; this experiment is restricted to The-Ocean")
for tool in (("docker",) if self.local else ("docker", "free", "df", "swapon")):
if not shutil.which(tool):
raise Abort("Missing host command: " + tool)
if command("docker", "info", "--format", "{{.CgroupVersion}}").stdout.strip() != "2":
raise Abort("This recorder requires cgroup version 2")
if not self.local:
resource_guard(*host_memory(), initial=True)
if http_code(SITE) != 200:
raise Abort("Baseline Gitea HTTP check failed")
with socket.socket() as probe:
probe.bind(("127.0.0.1", PORT))
# One plugin experiment at a time, even before its HTTP port is published.
existing = command("docker", "ps", "-aq", "--filter", "label=ssw590.purpose=jenkins-plugin-capacity").stdout.strip()
if existing:
raise Abort("Another plugin-test container exists; inspect it before continuing")
if ":18080->" in command("docker", "ps", "--format", "{{.Ports}}").stdout:
raise Abort("A Docker container already publishes the test port")
present = command("docker", "image", "inspect", IMAGE, check=False).returncode == 0
docker_root = command("docker", "info", "--format", "{{.DockerRootDir}}").stdout.strip()
disk_floor = (2 if present else 3) * 1024 ** 3
if not self.local and shutil.disk_usage(docker_root).free < disk_floor:
raise Abort(f"Less than {disk_floor // 1024 ** 3} GiB free in Docker storage")
self.save("baseline.json", {"utc": utc(), "hostname": socket.gethostname(),
"environment": self.result["environment"],
"memory_available_kib": None if self.local else host_memory()[0],
"swap_free_kib": None if self.local else host_memory()[1],
"docker_free_bytes": None if self.local else shutil.disk_usage(docker_root).free,
"docker_engine": command("docker", "info", "--format", "OS={{.OSType}} CPUs={{.NCPU}} MemoryBytes={{.MemTotal}}").stdout,
"containers": command("docker", "ps", "--format", "{{.Names}} {{.Image}} {{.Status}} {{.Ports}}").stdout,
"memory": None if self.local else command("free", "-m").stdout,
"swap": None if self.local else command("swapon", "--show").stdout,
"disk": None if self.local else command("df", "-h", docker_root).stdout,
"reboot_required": None if self.local else Path("/var/run/reboot-required").exists()})
if not present:
# Explicitly separate the pull from constrained plugin/runtime measurements.
with (self.evidence / "image-pull.txt").open("w") as output:
subprocess.run(["docker", "pull", IMAGE], stdout=output, stderr=subprocess.STDOUT,
timeout=300, check=True)
if not self.local:
resource_guard(*host_memory(), initial=True)
self.save("image.json", json.loads(command("docker", "image", "inspect", "--format",
'{"id":{{json .Id}},"digests":{{json .RepoDigests}},"bytes":{{.Size}}}', IMAGE).stdout))
def create(self):
# Nothing under ~/gitea, no real Jenkins home, socket, tokens or runner state.
# Preserve a cleanup handle even if Docker creates it but the CLI times out.
self.container = self.name
self.container = command("docker", "create", "--name", self.name,
"--label", "ssw590.purpose=jenkins-plugin-capacity", "--label", f"{LABEL}={self.owner}",
"--restart", "no", *BOUNDS, "--publish", f"127.0.0.1:{PORT}:8080",
"--log-driver", "json-file", "--log-opt", "max-size=1m", "--log-opt", "max-file=1",
"--mount", f"type=bind,src={self.bundle},dst=/opt/ssw590-input,readonly",
"--mount", f"type=bind,src={self.plugin_bundle},dst=/opt/ssw590-plugins,readonly",
"--env", "SSW590_DISPOSABLE_TEST=1",
"--env", "JAVA_OPTS=-Xms32m -Xmx128m -XX:+UseSerialGC -Djenkins.install.runSetupWizard=false",
"--user", "root", "--entrypoint", "/bin/bash", IMAGE,
"/opt/ssw590-input/container.sh").stdout.strip()
if not self.container:
raise Abort("Docker did not return a container ID")
self.save("test-config.json", {"base_image": IMAGE, "container_id": self.container,
"container_name": self.name, "owner": self.owner,
"ram_mib": 256, "ram_plus_swap_mib": 512, "cpu": 0.5, "pids": 256,
"heap_max_mib": 128, "idle_seconds": IDLE_SECONDS, "total_timeout_seconds": TOTAL_SECONDS,
"requested_plugins": (self.bundle / "plugins.txt").read_text().splitlines(),
"scope_excludes": ["SCM checkout", "webhook", "status reporting", "merge gate", "production deployment"]})
# Start the independent cleanup deadline before launching the container.
self.guard = subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "--watchdog",
self.container, self.owner, str(self.evidence)], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=os.name != "nt",
creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)
command("docker", "start", self.container)
def read_file(self, name):
result = command("docker", "exec", self.container, "cat", "/tmp/ssw590/" + name,
timeout=8, check=False)
return result.stdout.strip() if result.returncode == 0 else ""
def sample(self):
available, swap_free = (None, None) if self.local else host_memory()
if not self.local:
resource_guard(available, swap_free)
if http_code(SITE) != 200:
raise Abort("Gitea sampled HTTP check failed; cause not established")
running = command("docker", "inspect", "--format", "{{.State.Running}}", self.container).stdout.strip()
if running != "true":
raise Abort("Test container exited; inspect final state/install diagnostics")
phase = self.read_file("phase") or "initializing"
raw_status = self.read_file("status.json")
status = json.loads(raw_status) if raw_status else {}
code = http_code(f"http://127.0.0.1:{PORT}/login") if phase == "startup" else 0
# Timestamp AFTER the HTTP response, avoiding the prior 54-second false pass.
completed_at = time.monotonic()
http_utc = utc()
stats = command("docker", "stats", "--no-stream", "--format", "{{json .}}", self.container,
timeout=10).stdout.strip()
counters = command("docker", "exec", self.container, "sh", "-c",
'for f in memory.current memory.swap.current memory.events cpu.stat; do '
'echo "$f"; cat "/sys/fs/cgroup/$f"; done', timeout=8, check=False)
if counters.returncode:
raise Abort("Cannot read cgroup v2 memory/swap/CPU counters")
accounting = parse_cgroup(counters.stdout)
record = {"utc": http_utc, "http_completed_monotonic_seconds": completed_at,
"phase": phase, "jenkins_phase": status.get("phase"),
"host_available_kib": available, "host_swap_free_kib": swap_free,
"gitea_http": None if self.local else 200, "jenkins_login_http": code,
"docker_stats": json.loads(stats), "cgroup": accounting}
with (self.evidence / "samples.jsonl").open("a") as output:
output.write(json.dumps(record) + "\n")
if accounting["memory.events"].get("oom", 0) or accounting["memory.events"].get("oom_kill", 0):
raise Abort("Container recorded an out-of-memory event")
host_summary = "host guards/Gitea check: droplet-only" if self.local else f"available={available // 1024}MiB swap-free={swap_free // 1024}MiB GiteaHTTP=200"
print(f"{record['utc']} {phase}/{status.get('phase', '-')} JenkinsHTTP={code} {host_summary}", flush=True)
return phase, status, code, completed_at
def monitor(self):
begin = time.monotonic()
startup = pipelines = idle = None
with (self.evidence / "checkpoints.jsonl").open("a") as checkpoints:
while True:
phase, status, code, now = self.sample()
if now - begin > TOTAL_SECONDS:
raise Abort("Overall experiment deadline exceeded")
if status.get("phase") == "failed":
self.save("jenkins-status.json", status)
raise Abort("Jenkins harness failed: " + status.get("errorType", "unknown"))
if phase != "startup":
if now - begin > INSTALL_SECONDS:
raise Abort("Tool/plugin installation deadline exceeded")
else:
if startup is None:
startup = now
if pipelines is None:
healthy = status.get("phase") == "ready" and code == 200
idle, passed = advance_idle(idle, now, healthy)
if passed:
checkpoints.write(json.dumps({"checkpoint": "plugins-and-idle", "utc": utc(),
"observed_seconds": now - idle}) + "\n")
checkpoints.flush()
self.save("jenkins-status-at-idle.json", status)
command("docker", "exec", self.container, "touch", "/tmp/ssw590/start-jobs")
pipelines = now
elif now - startup > STARTUP_SECONDS:
raise Abort("Plugin startup/healthy-idle deadline exceeded")
else:
if code != 200:
raise Abort("Jenkins HTTP check failed during pipeline exercise")
if now - pipelines > PIPELINE_SECONDS:
raise Abort("Pipeline exercise deadline exceeded")
if status.get("phase") == "complete":
builds = status.get("builds", [])
if [b.get("actual") for b in builds] != ["SUCCESS", "FAILURE", "SUCCESS"]:
raise Abort("Missing expected pass/fail/repair results")
self.save("jenkins-status.json", status)
self.result.update(status="PASS", details="Plugins active; >=60-second observed healthy idle; pass/fail/repair fixture pipeline")
return
time.sleep(5)
def cleanup(self):
cleanup_ok = True
if self.container:
try:
if not owned_container(self.container, self.owner):
raise Abort("Cleanup ownership check failed; refusing container deletion")
final = command("docker", "inspect", "--format", "{{json .State}}", self.container, check=False)
if final.returncode == 0:
self.save("final-container-state.json", json.loads(final.stdout))
# Explicit allowlist; no raw controller logs or Jenkins home/credentials.
for name in ("install.txt", "plugins-resolved.json", "plugins-resolved.lock", "status.json",
"pass-console.txt", "intentional-failure-console.txt", "repair-console.txt"):
command("docker", "cp", self.container + ":/tmp/ssw590/" + name,
str(self.evidence / name), timeout=15, check=False)
# Even if a diagnostic copy failed, finally below removes owned resources.
except Exception as error:
self.result["capture_error"] = str(error)
finally:
try:
cleanup_ok = remove_owned(self.container, self.owner)
except Exception as error:
cleanup_ok = False
self.result["cleanup_error"] = str(error)
if self.guard and cleanup_ok:
self.guard.terminate()
try:
self.guard.wait(timeout=3)
except subprocess.TimeoutExpired:
self.guard.kill()
self.guard.wait()
self.result.update(finished=utc(), cleanup_ok=cleanup_ok, gitea_http_after=None if self.local else http_code(SITE))
if self.result["status"] == "PASS":
required = ("install.txt", "plugins-resolved.json", "plugins-resolved.lock", "status.json",
"pass-console.txt", "intentional-failure-console.txt", "repair-console.txt")
missing = [name for name in required if not (self.evidence / name).is_file()]
if missing or self.result.get("capture_error"):
self.result.update(status="NEEDS_ATTENTION", missing_evidence=missing)
if not cleanup_ok or (not self.local and self.result["gitea_http_after"] != 200):
self.result["status"] = "NEEDS_ATTENTION"
self.save("result.json", self.result)
print(json.dumps(self.result, indent=2), flush=True)
print("Evidence: " + str(self.evidence), flush=True)
def main():
# This internal branch is intentionally unavailable from the public parser.
if len(sys.argv) == 5 and sys.argv[1] == "--watchdog":
watchdog(sys.argv[2], sys.argv[3], Path(sys.argv[4]))
return 0
parser = argparse.ArgumentParser(description=__doc__)
modes = parser.add_mutually_exclusive_group()
modes.add_argument("--run-on-the-ocean", action="store_true", help="Execute the bounded experiment on the authorized droplet")
modes.add_argument("--local-smoke-test", action="store_true", help="Windows Docker Desktop runtime check; NOT droplet capacity")
parser.add_argument("--plugin-bundle", type=Path, help="Prepared archives directory; default: prepared-plugins beside this script")
args = parser.parse_args()
if not (args.run_on_the_ocean or args.local_smoke_test):
parser.print_help()
return 0
if args.run_on_the_ocean and (sys.platform != "linux" or os.geteuid() != 0 or socket.gethostname().lower() != "the-ocean"):
parser.error("Execution requires the root session on The-Ocean")
os.umask(0o077)
bundle = Path(__file__).resolve().parent
evidence_root = bundle.parents[1] / "build/evidence/jenkins-plugin-local" if args.local_smoke_test else Path("/root/ssw590-capacity-evidence")
evidence = evidence_root / ("plugins-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + str(os.getpid()))
evidence.mkdir(parents=True, exist_ok=False)
experiment = Experiment(bundle, evidence, local=args.local_smoke_test, plugin_bundle=args.plugin_bundle)
# Keep source versions with measurements, but never copy unrelated repository data.
experiment.save("input-hashes.json", {str(p.relative_to(bundle)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in bundle.rglob("*") if p.is_file() and "__pycache__" not in p.parts})
def interrupted(signum, frame):
raise Abort("Interrupted by signal " + str(signum))
watched_signals = [signal.SIGINT, signal.SIGTERM] + ([signal.SIGHUP] if hasattr(signal, "SIGHUP") else [])
for sig in watched_signals:
signal.signal(sig, interrupted)
try:
experiment.preflight()
experiment.create()
experiment.monitor()
except Exception as error:
experiment.result.update(status="FAILED_OR_ABORTED", reason=str(error))
finally:
# Prevent a second disconnect signal interrupting resource cleanup.
for sig in watched_signals:
signal.signal(sig, signal.SIG_IGN)
experiment.cleanup()
return 0 if experiment.result["status"] == "PASS" else 1
if __name__ == "__main__":
sys.exit(main())
+122
View File
@@ -0,0 +1,122 @@
"""Local fault/regression checks; these do not emulate a Jenkins runtime."""
import contextlib
import io
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import zipfile
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))
import run_test as harness
import inventory
class TimingAndProtectionTests(unittest.TestCase):
def test_previous_54_second_false_pass_is_rejected(self):
started, passed = harness.advance_idle(None, 100, True)
self.assertFalse(passed)
self.assertFalse(harness.advance_idle(started, 154, True)[1])
self.assertTrue(harness.advance_idle(started, 160, True)[1])
def test_failed_probe_restarts_the_idle_window(self):
started, _ = harness.advance_idle(None, 100, True)
started, passed = harness.advance_idle(started, 159, False)
self.assertIsNone(started)
started, passed = harness.advance_idle(started, 170, True)
self.assertFalse(passed)
self.assertFalse(harness.advance_idle(started, 229, True)[1])
self.assertTrue(harness.advance_idle(started, 230, True)[1])
def test_low_memory_or_swap_stops_the_experiment(self):
for available, swap in [(49151, 999999), (999999, 131071)]:
with self.assertRaises(harness.Abort):
harness.resource_guard(available, swap)
with self.assertRaises(harness.Abort):
harness.resource_guard(131071, 524288, initial=True)
harness.resource_guard(131072, 524288, initial=True)
def test_cleanup_refuses_other_owners(self):
wrong_owner = subprocess.CompletedProcess([], 0, stdout="someone-else\n", stderr="")
with patch.object(harness, "command", return_value=wrong_owner) as commands:
self.assertFalse(harness.remove_owned("unrelated-container", "our-run"))
self.assertEqual(commands.call_count, 1)
self.assertEqual(commands.call_args.args[:2], ("docker", "inspect"))
def test_cgroup_ram_swap_and_cpu_are_separate(self):
raw = "memory.current\n83513344\nmemory.swap.current\n221806592\nmemory.events\noom 0\noom_kill 0\ncpu.stat\nnr_periods 2090\nnr_throttled 1052\n"
result = harness.parse_cgroup(raw)
self.assertEqual(result["memory.current"] + result["memory.swap.current"], 305319936)
self.assertEqual(result["cpu.stat"]["nr_throttled"], 1052)
with self.assertRaises(harness.Abort):
harness.parse_cgroup("memory.current\n10\n")
class EvidenceAndFixtureTests(unittest.TestCase):
def test_monitor_waits_full_window_before_starting_jobs(self):
with tempfile.TemporaryDirectory() as temporary:
run = harness.Experiment(ROOT, Path(temporary))
run.container = 'our-test-id'
completed = {"phase": "complete", "builds": [{"actual": r} for r in ["SUCCESS", "FAILURE", "SUCCESS"]]}
samples = [("startup", {"phase": "ready"}, 200, t) for t in (100, 154, 160)]
samples.append(("startup", completed, 200, 170))
with patch.object(run, "sample", side_effect=samples), patch.object(harness.time, "monotonic", return_value=0), \
patch.object(harness.time, "sleep"), patch.object(harness, "command") as commands:
run.monitor()
commands.assert_called_once_with("docker", "exec", 'our-test-id', "touch", "/tmp/ssw590/start-jobs")
checkpoint = json.loads((Path(temporary) / "checkpoints.jsonl").read_text())
self.assertEqual(checkpoint["observed_seconds"], 60)
self.assertEqual(run.result["status"], "PASS")
def test_diagnostic_error_does_not_skip_targeted_cleanup(self):
with tempfile.TemporaryDirectory() as temporary:
run = harness.Experiment(ROOT, Path(temporary))
run.container = 'our-test-id'
with patch.object(harness, "owned_container", return_value=True), \
patch.object(harness, "command", side_effect=TimeoutError("diagnostic timed out")), \
patch.object(harness, "remove_owned", return_value=True) as remove, \
patch.object(harness, "http_code", return_value=200), contextlib.redirect_stdout(io.StringIO()):
run.cleanup()
remove.assert_called_once_with('our-test-id', run.owner)
self.assertTrue(run.result["cleanup_ok"])
def test_folded_plugin_manifest_and_root_mismatch(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
requested = root / "plugins.txt"
requested.write_text("gitea:286.v0740a_413c1eb_\n")
with zipfile.ZipFile(root / "gitea.jpi", "w") as archive:
archive.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\r\nShort-Name: gitea\r\nPlugin-Version: 286.v0740a_\r\n 413c1eb_\r\nJenkins-Version: 2.528.3\r\n\r\n")
result = inventory.inventory(root, requested)
self.assertEqual(result[0]["version"], "286.v0740a_413c1eb_")
self.assertEqual(len(result[0]["sha256"]), 64)
requested.write_text("gitea:wrong\n")
with self.assertRaises(ValueError):
inventory.inventory(root, requested)
def test_real_python_fixture_pass_failure_and_repair(self):
with tempfile.TemporaryDirectory() as temporary:
working = Path(temporary)
shutil.copytree(ROOT / "fixtures", working, dirs_exist_ok=True)
pricing = working / "pricing.py"
original = pricing.read_text()
for broken, expected in ((False, 0), (True, 1), (False, 0)):
pricing.write_text(original.replace("return unit_price * quantity", "return unit_price + quantity") if broken else original)
# Fresh process and no stale bytecode even if file timestamps collide.
shutil.rmtree(working / "__pycache__", ignore_errors=True)
run = subprocess.run([sys.executable, "-B", "-m", "unittest", "discover", "-s", "tests", "-v"],
cwd=working, capture_output=True, text=True)
self.assertEqual(run.returncode, expected, run.stderr)
self.assertIn("Ran 2 tests", run.stderr)
if broken:
self.assertIn("13 != 30", run.stderr)
self.assertIn("FAILED (failures=1)", run.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)
+11
View File
@@ -1,5 +1,16 @@
# Manual compiler and Gitea workflow
## Current runner placement
On 14 November 2026 Vincent requested moving the active Actions runner onto
The-Ocean. Its historical name/label remain `ssw590-vince-local` / `latex-local`;
the same tested compiler image below was transferred with checksum verification.
The laptop daemon is stopped. Remote jobs are capped at 512 MiB RAM / 768 MiB
RAM+swap and 0.5 CPU. Run them sequentially with Jenkins delivery work.
See [remote runner operations](../../gitea/droplet-runner/README.md).
The Docker Desktop instructions below remain useful for image reproduction
and an explicitly selected fallback, not for starting a second live runner.
## Local runner preparation
Build the job image on the runner's Docker Desktop engine from repository root:
+4
View File
@@ -0,0 +1,4 @@
**/__pycache__
**/.venv
**/*.pyc
agent/.env
+178
View File
@@ -0,0 +1,178 @@
# Billy / Claude handoff: Assignment 8 DNS
**Completed update, 15 November 2026:** Billy added both A records. Google and
Cloudflare resolve them to `147.182.178.136`; Caddy now serves trusted HTTPS and
redirects HTTP for both names. The app backends are still absent (HTTP 502).
Do not repeat DNS setup. The original handoff below is retained as the dated
November 14 preparation record; reviewed application releases remain pending.
Prepared for Billy Ye at Vincent Sun's request on **14 November 2026**.
This file is context and a proposed procedure. Billy must authorize changes
in his own session; it does not grant Claude account access or override its
active instructions. Billy handles login and MFA privately.
## Quick start for Claude
Help Billy add the two A records below to the existing `yebilly.me` DNS zone,
verify public resolution, and return a short evidence summary to Vincent.
Recheck existing records first. Preserve earlier services and stop after DNS
verification. SSH, Docker, Jenkins and application deployment are outside this
DNS task. Do not rerun the deployment bootstrap; it is already complete.
```yaml
task: assignment_8_dns_setup
scope: two_A_records_and_verification
domain: yebilly.me
expected_provider: Namecheap
droplet_name: The-Ocean
droplet_ipv4: 147.182.178.136
repository: https://git.yebilly.me/ssw590-group1/vpn-dns-gateway
prepared_branch: codex/assignment8-secure-delivery
prepared_commit: bf28adc7fb03fe25c5cc939599e34427a61ad2fc
records_to_add:
- type: A
host: staging
fqdn: staging.yebilly.me
value: 147.182.178.136
ttl: Automatic
- type: A
host: app
fqdn: app.yebilly.me
value: 147.182.178.136
ttl: Automatic
success_condition: both_names_resolve_to_the_expected_IPv4_and_existing_records_are_preserved
next_owner: Vincent_and_Codex_for_Caddy_TLS_and_reviewed_release_execution
```
## Why these records are needed
Assignment 8 follows **Chapter 6, Secure Delivery and Rollback**, in instructor
manual `dosManual-V1.43.pdf`. It requires distinct staging and production HTTPS
hostnames. Both applications will run on the same existing droplet, in separate
Docker Compose projects. Caddy selects the private application by hostname:
| Public hostname | Intended destination behind Caddy |
|---|---|
| `staging.yebilly.me` | `pricing-staging:8000` |
| `app.yebilly.me` | `pricing-production:8000` |
An A record maps a name to the droplet's IPv4 address. It does not contain a
port, URL scheme, or application path. Caddy will handle HTTPS certificates.
This task uses the existing domain and droplet; no purchase is part of it.
Preparation already completed: locked v1 pricing service, Ansible, release and
security gates, a trusted Jenkins agent now on The-Ocean (migrated from Vincent's
laptop to avoid campus SSH restrictions), dedicated deployment
access and scoped credentials. The prerequisite Jenkins job passed. The
prepared branch was pushed and its ordinary Jenkins branch check passed.
Peer review/merge, assessed releases and recovery exercises remain outstanding.
The release job is disabled pending reviewed source. The new Caddy routes and
production monitoring additions are prepared in Git but have not been applied.
## Observed baseline: recheck before making changes
Public Cloudflare DNS-over-HTTPS queries were checked on
**14 November 2026, about 20:35 America/New_York**
(15 November, about 01:35 UTC). These are observations, not a guarantee that
the zone will remain unchanged when Billy opens it.
| Query | Observed answer |
|---|---|
| `yebilly.me` NS | `dns1.registrar-servers.com`, `dns2.registrar-servers.com` |
| `staging.yebilly.me` A | NXDOMAIN: name did not exist |
| `app.yebilly.me` A | NXDOMAIN: name did not exist |
| `git.yebilly.me` A | `147.182.178.136` |
| `ci.yebilly.me` A | `147.182.178.136` |
| `metrics.yebilly.me` A | `147.182.178.136` |
The existing services are Gitea (`git`), Jenkins (`ci`) and Grafana (`metrics`).
Other zone records may also exist, including the retired Color Buttons name,
mail and verification records. Preserve them. The droplet has been resized to
2 GiB RAM with its 25 GB plan disk retained; no address change was observed.
## Namecheap procedure
1. Billy signs in to the account managing `yebilly.me`.
2. Open **Domain List > Manage** beside that domain, then **Advanced DNS**.
3. In **Host Records**, add the two rows from the YAML/table. Enter only
`staging` or `app` in the Host field. Use **A Record**, the exact IPv4 value,
and **Automatic** TTL. Save the two additions.
4. Inspect the saved rows and retain a cropped screenshot showing those rows,
with account, billing, login and secret information excluded.
If a requested record already has the correct value, reuse it. If an existing
`staging` or `app` record conflicts (including a CNAME/redirect), explain the
conflict to Billy before changing it; do not delete unrelated records. This
request is for IPv4 A records, not additional AAAA, wildcard or redirect records.
If Host Records is unavailable or nameservers differ from the baseline, identify
the active DNS provider and edit the existing zone there. Keep nameserver
delegation unchanged. Namecheap documents this distinction in its host-record
guide linked below.
## Verify and capture evidence
From PowerShell, record the actual UTC time and check public resolution:
```powershell
[DateTime]::UtcNow.ToString('o')
Resolve-DnsName staging.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName app.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName staging.yebilly.me -Type A -Server 8.8.8.8 -DnsOnly
Resolve-DnsName app.yebilly.me -Type A -Server 8.8.8.8 -DnsOnly
```
Expected A answer for both names: **147.182.178.136**. A resolver may briefly
retain the earlier negative answer; allow caches to expire and repeat. A lookup
that times out on a restricted network is inconclusive. Do not report success
from the saved dashboard rows alone.
Recheck the earlier names as well:
```powershell
Resolve-DnsName git.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName ci.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
Resolve-DnsName metrics.yebilly.me -Type A -Server 1.1.1.1 -DnsOnly
```
If direct public-resolver queries are blocked, use an available DNS lookup
method and record which resolver/method was actually used. Authoritative checks
can help distinguish an unsaved record from resolver caching; document the
actual results and any disagreement rather than assuming propagation completed.
**DNS success is not application success.** HTTPS may still be unavailable,
show a certificate problem, or return an upstream error before Vincent applies
Caddy routes and deploys the applications. Do not weaken TLS checks or alter
firewall rules to make a DNS-only check appear successful.
## Return to Vincent
Report:
- The two saved record types, hostnames, values and actual TTL selection.
- Verification UTC time, resolver(s), actual answers and any pending cache result.
- Confirmation that existing records were preserved, with the earlier-name checks.
- A cropped screenshot or text evidence containing no credentials/account details.
- Any blocker, conflicting record, or unverified assumption.
Then Vincent/Codex can finish Caddy HTTPS setup and the reviewed release tests.
Billy's separate code-review task remains: review/approve the preparation PR
if satisfied, and later review v2 and the staging failure configuration. DNS
completion does not approve code or authorize a production promotion.
For repository work, read `AGENTS.md`,
`manual/latex/devopsAIAgentRequirements.tex` and
`manual/latex/devopsAIAgentGuide.tex` first. Useful context is in
`delivery/README.md`, `delivery/RUNBOOKS.md`, `delivery/SECURITY.md`,
`deploy/Caddyfile` and `delivery/evidence/agent-preflight-1.txt`.
## Official references and provenance
- [Namecheap: add an A record](https://www.namecheap.com/support/knowledgebase/article.aspx/319/2237/how-can-i-set-up-an-a-address-record-for-my-domain/).
- [Namecheap: host records, provider selection and TTL](https://www.namecheap.com/support/knowledgebase/article.aspx/434/2237/how-do-i-set-up-host-records-for-a-domain/).
Codex prepared this handoff at Vincent's explicit request, using the repository's
prepared configuration, current public DNS observations and those official
Namecheap guides. No DNS account was opened or modified during its preparation.
The original instructor manual defines the assignment; the names/IP above are
the team's selected deployment values.
+66
View File
@@ -0,0 +1,66 @@
# Assignment 8 evidence
## Reviewed Jenkins execution, 15 November 2026
PR 24 is merged. The actual [test/secret gate demonstrations](evidence/gates-20261115.md)
blocked as intended. [Release attempt 3](evidence/release-attempt-3-20261115.md)
passed scans and published v1, then stopped before any app change at the
Ansible PTY request. The noninteractive SSH correction was verified in
agent-preflight build 3 but awaits source review/merge. No successful promotion,
production approval or recovery has occurred.
## Preparation evidence — historical baseline
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`.
## Later agent migration
The agent subsequently moved to The-Ocean at Vincent's direction to remove
campus SSH dependence. [Migration record](evidence/agent-migration-20261114.md)
distinguishes the actual remote prerequisite build 2 and bounded capacity trial
from the initial laptop checks above. UTC dates cross into November 15 while
the client's Eastern date is still November 14. At that point the PDF runner
was unchanged. It subsequently moved too; see the
[manual runner migration record](../gitea/droplet-runner/EVIDENCE.md).
Assessed releases and recovery are still pending.
## DNS and TLS readiness
On 15 November Billy's two DNS records were verified and Caddy's prepared
routes applied. Both names have trusted TLS and HTTP 308 redirects; HTTPS
returns 502 while pricing backends are absent. See the
[dated HTTPS evidence](evidence/https-20261115.md). Application deployment,
production monitoring and assessed recovery evidence remain pending.
+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)
}
}
}
+15
View File
@@ -0,0 +1,15 @@
# Fix noninteractive Ansible deployment over the restricted SSH key
The first reviewed v1 release passed its tests and security gates and published
an image, but stopped during Ansible Gathering Facts: Ansible forced a PTY
that the dedicated deploy key forbids. Set `ansible_ssh_use_tty=false` in the
delivery inventory and extend the administrator preflight to exercise Ansible's
actual SSH/sudo path. Keep the key restriction and pinned host verification.
Record the actual Jenkins test/secret blocks, passing image scans and publication,
zero-change staging connection failure, and successful connection preflight.
No app deployment or production approval is claimed. Retry v1 after merge;
v2 promotion, both recoveries and monitoring evidence still remain.
Validation: credential-bound Jenkins agent-preflight build 3 passed and returned
root UID 0 through Ansible without a PTY; twelve release-control tests passed.
+125
View File
@@ -0,0 +1,125 @@
# 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 are
generated by Jenkins from reviewed source.
Current execution status, 15 November: PR 24 is merged and the delivery job
is enabled. Real Jenkins test/secret demonstrations blocked as intended. The
first v1 image was scanned and published, but staging stopped before any app
change because Ansible requested a PTY forbidden by the deploy key. The
noninteractive inventory correction and expanded, passing Ansible preflight
await review/merge. See [gate evidence](evidence/gates-20261115.md) and
[release attempt 3](evidence/release-attempt-3-20261115.md).
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 node `ssw590-vince-delivery` now runs on The-Ocean, with one
exclusive executor and label `delivery-trusted`. Its name is retained from
the initial laptop installation. The laptop copy is stopped. The remote
agent uses private HTTP/WebSocket to `jenkins:8080`; its SSH configuration
routes the existing deployment inventory address through Docker's host gateway,
retaining `HostKeyAlias 147.182.178.136` and the pinned Jenkins known-hosts file.
No campus SSH connection is needed to run a delivery job from the browser.
[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 was enabled after PR 24 merged. Release credentials are scoped
to that Jenkins folder; the PR job does not bind them or the Docker socket.
The original inventory above is historical. [Remote prerequisite build 2](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/2/)
passed after migration; `evidence/agent-preflight-2.txt` records the tools and
target. A separate bounded capacity trial passed control/app tests, source and
dependency checks, a limited image build, image scan and temporary HTTP smoke.
It used a preparation snapshot, not a reviewed release, and published nothing.
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.
Remote agent identity and workspace live in named Docker volumes outside Git.
The agent has administrative access to the same Docker host as Jenkins and
Gitea; a container is not a security boundary against malicious trusted jobs.
Use only reviewed delivery code. `agent/compose.droplet.yaml` caps the agent
at 512 MiB RAM / 768 MiB RAM+swap and 0.5 CPU; a dedicated pinned BuildKit
builder has 256 MiB / 384 MiB and 0.5 CPU. Builds select that builder explicitly.
Agent and builder restart unless stopped. `bootstrap/start-droplet-agent.sh`
is the root-operated installation/reconnect helper in
`/opt/ssw590-delivery-agent`; it detects the Docker socket group (987 on this host).
No public agent, Docker API or app port is added.
`bootstrap/start-agent.ps1` refuses to start the laptop copy by default.
For an intentional fallback, first stop the remote agent and builder, then use
`-AllowLaptopFallback`. Never connect both copies of the same node. Preserve
their volumes. The Gitea Actions manual-build runner subsequently moved to
The-Ocean too; see `../gitea/droplet-runner/README.md`. Neither active runner
now depends on Docker Desktop. Run manual builds and delivery releases sequentially.
See `RUNBOOKS.md`.
Ansible syntax, agent Compose configuration, and the installed Jenkins
controller's declarative parser checks passed. These are preparation checks;
**successful v1/v2 deployment, promotion and recovery are not yet demonstrated**.
## Remaining checkpoints
Vincent merged PR #24, including runner migration and HTTPS, after Billy's
latest review. Review/merge the noninteractive Ansible correction before
retrying v1. Create the assignment issue if still absent. Keep main protection.
Billy added the A
records; Google and Cloudflare now resolve both names to `147.182.178.136`.
On 15 November Caddy's prepared routes were validated and gracefully reloaded;
both names have trusted HTTPS and HTTP redirects. They currently return 502
because the app containers are not deployed. See `evidence/https-20261115.md`.
The release job is enabled; follow `RUNBOOKS.md` after the corrected source reaches main.
Keep Jenkins and the remote delivery node available. 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.
+172
View File
@@ -0,0 +1,172 @@
# Release, recovery and cleanup
These are execution instructions, not completed release evidence.
Current status, 15 November 2026: Billy's DNS records resolve correctly and the
two Caddy routes are active with trusted certificates and HTTP-to-HTTPS redirects.
502 is expected while the app backends are absent. The one-time HTTPS helper
has already run; use the normal validate/reload procedure for later changes.
The reviewed preparation is merged, the release job is enabled, and real
Jenkins test/secret blocks are recorded. Release build 3 published v1 but
stopped at Ansible's PTY request before any app change. Review/merge the
noninteractive inventory correction and retry from the corrected main SHA.
The expanded Ansible/sudo preflight passed; full deployment remains unverified.
Monitoring additions and successful releases remain pending.
## Authority and preparation
Billy reviews code; Vincent commits/pushes. Jenkins users `billy` or `vsun1`
may approve production interactively; administrators retain override authority.
The Droplet delivery 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 HTTPS
observer on an available client or the remote agent, 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 remote agent is capped at 512 MiB RAM / 768 MiB
RAM+swap and 0.5 CPU; its pinned BuildKit builder at 256 MiB / 384 MiB and
0.5 CPU. The preparation trial passed but used swap and is not a full release
load test. Keep one exclusive executor and serialized delivery. 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 remote agent and dedicated builder; remove only their 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.
## Agent placement and campus demonstration
The node name `ssw590-vince-delivery` is historical; it now runs on The-Ocean.
Deployment SSH goes to `host.docker.internal` through the mounted SSH config,
with the original public-IP host-key alias and strict verification. The Jenkins
connection is private HTTP/WebSocket on `gitea_web`; public browser access
continues through Caddy HTTPS and its existing allowlist. No campus SSH is
needed for this delivery path. Rehearse campus browser access before presenting.
The Gitea Actions PDF runner now also runs on The-Ocean. Its existing label
`latex-local` is historical. Both laptop copies are stopped; run manual builds
and delivery releases sequentially. See `../gitea/droplet-runner/README.md`.
To stop the remote agent from an authorized administrator shell:
```sh
cd /opt/ssw590-delivery-agent
docker compose -f compose.droplet.yaml stop
docker stop buildx_buildkit_ssw590-delivery-limited0
```
To reconnect, run `bash /opt/ssw590-delivery-agent/start-droplet-agent.sh`.
It reuses protected identity and workspace volumes; do not rerun the original
host/account bootstrap. Agent recreation reuses the node identity. The verified
tool image was transferred from Docker Desktop and checked by archive SHA-256
and image ID before loading. It can be rebuilt from `agent/Dockerfile` on a
build-capable machine and transferred again if required.
For a laptop fallback, stop the remote copy first, load the administrator key
into Windows ssh-agent, then run
`./delivery/bootstrap/start-agent.ps1 -AllowLaptopFallback`.
Stop the laptop copy before starting the remote one again.
No new cloud instance or plan change was made; existing Droplet billing applies.
VS maintains this agent and BY retains server administration ownership.
+39
View File
@@ -0,0 +1,39 @@
# 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 now has administrative Docker access on The-Ocean,
including the host running the controller, registry and monitoring, as well as
deployment privileges. Co-location reduces isolation: the agent's container
and resource caps do not prevent a malicious Docker-authorized job from
accessing other containers or host files. This is a documented course-lab
trade-off to avoid campus SSH restrictions, not a hardened production design.
Run reviewed delivery code on
this agent. Pull-request jobs must not receive its Docker socket or release
credentials. The remote agent connects over private HTTP/WebSocket on the
existing Docker network; browser access remains HTTPS through Caddy. Strict
SSH verification retains the public-IP host-key alias while transport stays
on Docker's host gateway. No firewall, TLS, approval or credential scope was relaxed.
+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
+54
View File
@@ -0,0 +1,54 @@
name: ssw590-delivery
services:
agent:
image: ssw590-delivery-agent:20261114
restart: unless-stopped
entrypoint: ["java", "-jar", "/usr/share/jenkins/agent.jar"]
command:
- -url
- http://jenkins:8080/
- -name
- ssw590-vince-delivery
- -secret
- "@/run/delivery-identity/agent-secret"
- -webSocket
- -workDir
- /home/jenkins/agent
environment:
JAVA_TOOL_OPTIONS: "-Xms32m -Xmx96m -XX:+UseSerialGC -XX:MaxMetaspaceSize=96m"
GOMEMLIMIT: 192MiB
TRIVY_PARALLEL: "1"
BUILDX_CONFIG: /home/jenkins/agent/.buildx
DELIVERY_BUILDER: ssw590-delivery-limited
# Docker membership is host administration, including controller access.
# Only reviewed delivery jobs may select this exclusive one-executor node.
group_add: ["${DOCKER_GID:?set to the host Docker socket group}"]
extra_hosts:
- "host.docker.internal:host-gateway"
networks: [web]
volumes:
- workspace:/home/jenkins/agent
- /var/run/docker.sock:/var/run/docker.sock
- identity:/run/delivery-identity:ro
- ./ssh_config.droplet:/etc/ssh/ssh_config.d/90-delivery-target.conf:ro
mem_limit: 512m
memswap_limit: 768m
cpus: 0.5
pids_limit: 128
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
networks:
web:
external: true
name: gitea_web
volumes:
identity:
external: true
name: ssw590-delivery-identity
workspace:
name: ssw590-delivery-workspace
+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
+6
View File
@@ -0,0 +1,6 @@
# On The-Ocean only: keep the inventory and pinned public-key identity, but
# send deployment SSH to this Docker host's gateway, never across campus Wi-Fi.
Host 147.182.178.136
HostName host.docker.internal
HostKeyAlias 147.182.178.136
ConnectTimeout 10
+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"
+7
View File
@@ -0,0 +1,7 @@
[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
[delivery:vars]
# The dedicated deploy key forbids PTY allocation; sudo is noninteractive.
ansible_ssh_use_tty=false
+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()
+57
View File
@@ -0,0 +1,57 @@
#!/bin/sh
# Run inside the idle trusted agent from a non-secret preparation snapshot.
# This is a capacity/tool trial, never a reviewed release or registry push.
set -eu
export TRIVY_CACHE_DIR=/home/jenkins/agent/.cache/trivy
mkdir -p build/delivery/reports
date -u
python3 -B -m unittest discover -s delivery/ci -p 'test_controls.py' -v
sh delivery/ci/test-app.sh
python3 delivery/ci/security.py source
: "${DELIVERY_BUILDER:?use the limited remote builder}"
docker buildx build --builder "$DELIVERY_BUILDER" --load --platform linux/amd64 \
--build-arg APP_COMMIT=uncommitted-remote-preflight \
-t ssw590-pricing:remote-preflight-v1 delivery/app
python3 delivery/ci/security.py image --image ssw590-pricing:remote-preflight-v1
name=ssw590-delivery-capacity-smoke
cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; }
# Refuse to replace any existing container, even one from an interrupted trial.
if docker container inspect "$name" >/dev/null 2>&1; then
echo 'Inspect the existing trial container before retrying' >&2
exit 1
fi
trap cleanup EXIT
docker run -d --name "$name" --network gitea_web --read-only \
--tmpfs /tmp:rw,nosuid,noexec,size=16m --memory 64m --memory-swap 96m \
--cpus .25 --pids-limit 64 --cap-drop ALL --security-opt no-new-privileges \
ssw590-pricing:remote-preflight-v1
python3 - <<'PY'
import json, time, urllib.request, urllib.error
url = 'http://ssw590-delivery-capacity-smoke:8000'
for attempt in range(30):
try:
with urllib.request.urlopen(url + '/health', timeout=2) as response:
health = json.load(response)
break
except (OSError, ValueError):
time.sleep(1)
else:
raise RuntimeError('Application failed to start')
def get(path):
with urllib.request.urlopen(url + path, timeout=5) as response:
return json.load(response)
identity, price = get('/'), get('/price?quantity=3')
assert health['status'] == 'ok' and health['version'] == 'v1', health
assert identity['commit'] == 'uncommitted-remote-preflight', identity
assert price['total'] == 30, price
try:
get('/price?quantity=-1')
raise AssertionError('Invalid quantity accepted')
except urllib.error.HTTPError as error:
assert error.code == 400, error.code
print(json.dumps({'health': health, 'identity': identity, 'price': price,
'invalid_quantity_status': 400}, indent=2))
PY
docker inspect "$name" --format 'smoke OOMKilled={{.State.OOMKilled}} memory={{.HostConfig.Memory}}'
date -u
echo 'PASS: remote capacity preparation; no image published or assessed environment deployed'
@@ -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 The-Ocean Docker/Ansible delivery agent (legacy node name)',
'/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.')
+72
View File
@@ -0,0 +1,72 @@
"""Apply only the prepared Assignment 8 proxy additions, preserving the bind inode."""
import argparse
import hashlib
import json
import os
import shutil
import socket
import subprocess
from datetime import datetime, timezone
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('--candidate', required=True, type=Path)
parser.add_argument('--backup', required=True, type=Path)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
live = Path('/root/gitea/Caddyfile')
marker = '# Assignment 8: apply after both DNS names resolve to The-Ocean.'
candidate = args.candidate.read_text()
before = live.read_bytes()
prefix, additions = candidate.split(marker, 1)
expected = '''# Assignment 8: apply after both DNS names resolve to The-Ocean. Containers
# publish no host ports; the existing proxy reaches their private aliases.
staging.yebilly.me {
\treverse_proxy pricing-staging:8000
}
app.yebilly.me {
\treverse_proxy pricing-production:8000
}'''
assert (marker + additions).strip() == expected, 'Unexpected proxy additions'
assert prefix.strip() == before.decode().replace('\r\n', '\n').strip(), 'Live earlier routes differ; inspect instead of overwriting'
for host in ('staging.yebilly.me', 'app.yebilly.me'):
addresses = {item[4][0] for item in socket.getaddrinfo(host, 443, socket.AF_INET)}
assert addresses == {'147.182.178.136'}, (host, addresses)
temp = '/tmp/ssw590-assignment8-https.Caddyfile'
subprocess.run(['docker', 'cp', str(args.candidate), 'gitea-caddy-1:' + temp], check=True)
try:
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'validate', '--config', temp, '--adapter', 'caddyfile'], check=True)
if not args.apply:
print('Candidate validated; no active configuration changed.')
raise SystemExit(0)
args.backup.mkdir(mode=0o700, parents=True, exist_ok=True)
backup = args.backup / 'Caddyfile.before'
assert not backup.exists(), 'Existing backup: inspect state before retrying'
shutil.copy2(live, backup)
prior_stat = live.stat()
try:
with live.open('wb') as stream:
stream.write(candidate.encode())
stream.flush()
os.fsync(stream.fileno())
assert live.stat().st_ino == prior_stat.st_ino, 'Bind-mounted inode changed'
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile'], check=True)
except Exception:
with live.open('wb') as stream:
stream.write(before)
stream.flush()
os.fsync(stream.fileno())
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile'], check=True)
raise
report = {'applied_at': datetime.now(timezone.utc).isoformat(),
'before_sha256': hashlib.sha256(before).hexdigest(),
'after_sha256': hashlib.sha256(live.read_bytes()).hexdigest(),
'inode_preserved': live.stat().st_ino == prior_stat.st_ino,
'prior_routes_preserved': True, 'applications_deployed': False,
'new_hosts': ['staging.yebilly.me', 'app.yebilly.me'],
'backup': str(backup), 'result': 'reloaded; certificate verification pending'}
(args.backup / 'applied.json').write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))
finally:
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'rm', '-f', temp], check=True)
+42
View File
@@ -0,0 +1,42 @@
// 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 /'
# Exercise Ansible's own SSH/become path as well as plain SSH. Its default
# PTY request is incompatible with the intentionally restricted deploy key.
export ANSIBLE_HOST_KEY_CHECKING=True
export ANSIBLE_PRIVATE_KEY_FILE="$DEPLOY_KEY"
export ANSIBLE_SSH_ARGS="-o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS"
ansible all -i '147.182.178.136,' -u deploy --become \
-e '{"ansible_ssh_use_tty":false,"ansible_python_interpreter":"/usr/bin/python3"}' \
-m ansible.builtin.command -a 'id -u'
} > 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()
+28
View File
@@ -0,0 +1,28 @@
param(
[switch]$AllowLaptopFallback,
[string]$Droplet = '147.182.178.136',
[string]$IdentityFile = (Join-Path $env:USERPROFILE '.ssh/digitalocean')
)
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true
if (-not $AllowLaptopFallback) {
throw 'The delivery node now runs on The-Ocean. Start a laptop fallback only after stopping the remote copy, then pass -AllowLaptopFallback. Never connect both copies of the same node.'
}
$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
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Run as root from /opt/ssw590-delivery-agent after stopping the laptop copy.
# Copy compose.droplet.yaml and ssh_config.droplet here first; load the verified
# agent image. Never copy any identity file into this directory or into Git.
set -euo pipefail
test "$(id -u)" = 0
cd /opt/ssw590-delivery-agent
export DOCKER_GID
DOCKER_GID=$(stat -c '%g' /var/run/docker.sock)
# Numeric group only, not a credential. Keep it available for later Compose use.
printf 'DOCKER_GID=%s\n' "$DOCKER_GID" > .env
chmod 644 .env
docker image inspect ssw590-delivery-agent:20261114 >/dev/null
docker compose -f compose.droplet.yaml config --quiet
docker exec -u jenkins gitea-jenkins-1 test -s /var/jenkins_home/delivery-bootstrap/agent-secret
docker volume create ssw590-delivery-identity >/dev/null
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'
docker compose -f compose.droplet.yaml up -d --pull never
agent=ssw590-delivery-agent-1
# BuildKit's own container must be limited too: the socket mount does not make
# child build containers inherit the agent's resource caps.
if ! docker exec "$agent" docker buildx inspect ssw590-delivery-limited >/dev/null 2>&1; then
docker exec "$agent" docker buildx create --name ssw590-delivery-limited \
--driver docker-container \
--driver-opt image=moby/buildkit@sha256:c5f8862f52499773af85bc07695b2379ef08e8002352b0df2c4864c91d78dabe,memory=256m,memory-swap=384m,cpu-period=100000,cpu-quota=50000,restart-policy=unless-stopped
fi
docker exec "$agent" docker buildx inspect ssw590-delivery-limited --bootstrap
docker compose -f compose.droplet.yaml ps
@@ -0,0 +1,41 @@
"""Read-only, non-secret runtime checks; run as root on The-Ocean."""
import json
import subprocess
from datetime import datetime, timezone
from pathlib import Path
def run(*args):
return subprocess.check_output(args, text=True).strip()
report = {"observed_at": datetime.now(timezone.utc).isoformat(), "containers": []}
names = ["ssw590-delivery-agent-1", "buildx_buildkit_ssw590-delivery-limited0"]
for name in names:
info = json.loads(run("docker", "inspect", name))[0]
config, state = info["HostConfig"], info["State"]
events = Path("/sys/fs/cgroup/system.slice", "docker-" + info["Id"] + ".scope", "memory.events")
report["containers"].append({
"name": name, "running": state["Running"], "oom_killed": state["OOMKilled"],
"restart_count": info["RestartCount"], "restart_policy": config["RestartPolicy"]["Name"],
"memory_bytes": config["Memory"], "memory_swap_bytes": config["MemorySwap"],
"nano_cpus": config["NanoCpus"], "cpu_quota": config["CpuQuota"],
"cpu_period": config["CpuPeriod"], "port_bindings": config["PortBindings"],
"memory_events": events.read_text().strip() if events.exists() else "unavailable",
})
assert state["Running"] and not state["OOMKilled"], name
report["private_http"] = {}
for url in ["http://jenkins:8080/login", "http://gitea:3000/", "http://monitoring-grafana-1:3000/login"]:
code = run("docker", "exec", names[0], "curl", "--silent", "--show-error", "--max-time", "15",
"-o", "/dev/null", "-w", "%{http_code}", url)
report["private_http"][url] = code
assert code == "200", (url, code)
ssh = run("docker", "exec", names[0], "ssh", "-G", "147.182.178.136")
report["deployment_ssh_route"] = [line for line in ssh.splitlines() if line.startswith(("hostname ", "hostkeyalias "))]
assert "hostname host.docker.internal" in ssh.splitlines()
assert "hostkeyalias 147.182.178.136" in ssh.splitlines()
report["memory"] = run("free", "-m")
report["disk"] = run("df", "-h", "/")
report["running_containers"] = run("docker", "ps", "--format", "{{.Names}} {{.Status}}")
report["result"] = "passed"
print(json.dumps(report, indent=2))
+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()
+35
View File
@@ -0,0 +1,35 @@
#!/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
if [ -n "${DELIVERY_BUILDER:-}" ]; then
docker buildx build --builder "$DELIVERY_BUILDER" --load --platform linux/amd64 \
--build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app
else
docker build --platform linux/amd64 --build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app
fi
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()
@@ -0,0 +1,64 @@
# Delivery agent migration — preparation evidence
Vincent selected The-Ocean instead of the laptop to avoid the previously
observed campus SSH restriction. This work occurred on November 14 Eastern;
the host's UTC timestamps below fall on November 15, 2026.
- Existing host: 1 CPU, 1,967 MiB RAM, original 25 GB plan disk, 2 GiB swap.
At 03:29 UTC, 811 MiB RAM was available and swap used was 129 MiB.
- Transferred the existing agent image, without rebuilding its toolchain:
`sha256:0752666650a3afe7b61854c1df4dca21f4ef381fab1f4fb9b042adaa203c58a8`.
Transfer archive SHA-256 matched on both machines:
`f987fdb285757aabe91fffd21a3a58da00bec975efcce7ee8ef3f127b27d0696`.
- Stopped the laptop container before connecting its replacement. Existing
node name `ssw590-vince-delivery`, label `delivery-trusted`, one exclusive
executor, folder credentials and disabled pricing job were retained.
- Remote agent: 512 MiB RAM / 768 MiB RAM+swap, 0.5 CPU, 96 MiB JVM heap,
no published port, existing `gitea_web` network, private WebSocket connection.
Socket group detected as 987; initial group-0 mismatch was corrected.
- Builder: BuildKit v0.34.2 image pinned by index digest in the start helper;
256 MiB RAM / 384 MiB RAM+swap, CPU quota 50000/100000, no published port.
The pipeline explicitly selects this builder when `DELIVERY_BUILDER` is set.
- Deployment SSH: `ssh -G` reports `hostname host.docker.internal` and
`hostkeyalias 147.182.178.136`. The existing Jenkins known-hosts credential
remains authoritative; host verification was not bypassed.
- [Jenkins prerequisite build 2](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/2/)
passed at 03:47 UTC, including real credential binding, deploy login, pinned
host key and sudo. See [inventory](agent-preflight-2.txt).
- 03:50:16–03:51:43 UTC: the separate capacity preparation trial passed 12
control tests and 3 app tests, source-secret/dependency gates, capped image
build, full image gate (zero HIGH/CRITICAL), and a temporary 64 MiB app smoke.
Health v1, identity `uncommitted-remote-preflight`, total 30 for quantity 3,
and HTTP 400 for invalid quantity were verified. The smoke container was
removed. No image was pushed and no assessed environment was deployed.
- The trial used a non-secret local snapshot of `delivery/app`, `delivery/ci`,
the scanner rule and the trial script, not a reviewed full repository checkout.
Snapshot archive SHA-256:
`2cd5d23062ff9904b48a23dfd5d9f2b9c67929cb86db006e7b2677060da3afa0`.
Gate reports retain actual timestamps and tool/database metadata.
- Observed available RAM exceeded 700 MiB; swap used increased from 263 to
372 MiB during the sampled trial. At 03:54 UTC, 861 MiB was available, swap
used was 370 MiB and root disk was 56% used (11 GiB available, rounded by df).
Agent cgroup memory-limit events were nonzero; agent and builder `oom` and
`oom_kill` counters were zero, and both reported `OOMKilled=false`.
- Gitea, Jenkins login and Grafana login returned HTTP 200 through private
Docker routes after the trial. Seven previous containers remained running.
- Restarted only the agent; logs recorded a fresh WebSocket connection and
`Connected` at 03:57:57 UTC. `unless-stopped` is configured for both agent and
builder; an entire-host reboot was not performed as part of this migration.
Raw reports, partial resource-output capture, runtime JSON and screenshot:
ignored `build/evidence/assignment8-agent-migration/`. Protected server reports:
`/root/ssw590-delivery-bootstrap/agent-migration/`. The short trial used swap
and does not prove full release, recovery or campus presentation performance.
No firewall rule, credential scope, TLS verification, peer-review requirement
or human production approval changed. Co-located Docker authority gives trusted
jobs administrative access to the shared host; this is an explicit course-lab
trade-off. The older Gitea Actions PDF runner remains on the laptop. No new
instance or cloud plan change was made. Migration changes are uncommitted;
DNS, reviewed releases, production approvals and recovery exercises remain pending.
Subsequently Vincent requested moving that Actions runner too. The statement
above describes the end of the delivery-agent migration, not current placement.
See the [later runner record](../../gitea/droplet-runner/EVIDENCE.md).
+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% /
+32
View File
@@ -0,0 +1,32 @@
Sun Nov 15 03:47:13 UTC 2026
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),987
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 1205 106 3 832 762
Swap: 2047 265 1782
1
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 24G 12G 13G 49% /
+35
View File
@@ -0,0 +1,35 @@
Sun Nov 15 22:50:10 UTC 2026
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),987
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 1239 86 3 817 728
Swap: 2047 413 1634
1
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 24G 15G 9.2G 61% /
147.182.178.136 | CHANGED | rc=0 >>
0
+31
View File
@@ -0,0 +1,31 @@
# Assessed Jenkins gate demonstrations — 15 November 2026
Reviewed source: `09731acb0370566471dd4e401e59bafe55e927dc`, the merge of
[PR 24](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/24).
Billy (`bill`) approved the latest preparation head `ed0a862` at 21:06 UTC;
Vincent merged it at 21:59 UTC. The merge-triggered manual workflow
[run 13](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/actions/runs/13)
passed in 2m25s before the delivery demonstrations began.
| Jenkins pricing run | Mode | Actual result |
|---|---|---|
| [1](https://ci.yebilly.me/job/secure-delivery/job/pricing/1/) | `blocked-test` | FAILURE as intended, 54.202 seconds. Twelve control tests and three normal Flask tests passed; the additional expected-total=-1 assertion failed against the real v1 total 30. All later security, publication, deployment and approval stages were skipped. |
| [2](https://ci.yebilly.me/job/secure-delivery/job/pricing/2/) | `blocked-secret` | FAILURE as intended, 31.375 seconds. Twelve control tests and three Flask tests passed. Clean-source scanning and all nine locked dependency audits passed; the generated synthetic-secret fixture was detected, blocking publication, deployment and approval. |
Run 1 began at 22:11:34.732 UTC. Run 2 began at 22:12:51.073 UTC;
its source gate ran from 22:13:14.233 to 22:13:20.115 UTC. The scanner itself
returned zero after writing a valid report; the gate wrapper returned one
because that report contained a finding. This is expected policy enforcement,
not a scanner execution error. The synthetic fixture is nonfunctional and
generated only in a temporary directory; captured match/code fields are redacted.
Jenkins archives the test and gate reports for each run. Exact local copies,
selected build metadata and console logs are retained in ignored
`build/evidence/assignment8-execution/jenkins-{1,2}/`. These two negative
demonstrations do not establish a successful release or production approval.
The job was enabled only after the merge. A bootstrap MODE choice parameter
allowed the first run to select `blocked-test`; the reviewed Jenkinsfile then
installed its normal four parameter definitions and retained its approval,
timeout, concurrency and ancestry checks. Existing credentials and access
permissions were unchanged.
+36
View File
@@ -0,0 +1,36 @@
# DNS and HTTPS readiness — 15 November 2026
Billy added A records for `staging.yebilly.me` and `app.yebilly.me` pointing to
`147.182.178.136`. At 06:14 UTC, Google and Cloudflare DNS-over-HTTPS both returned
that A record and no AAAA answer for each name. No DNS account was accessed or
changed by Codex.
At 06:09:34 UTC, the prepared `deploy/Caddyfile` additions were validated with
installed Caddy 2.11.4, backed up and gracefully reloaded. The helper checked
that earlier routes matched before changing anything and preserved the existing
bind-mounted inode. The first comparison stopped because of CRLF versus LF;
normalizing only that comparison allowed the matching routes to pass.
- Before SHA-256: `0197f100c5a1f2a21c6a293964fada27f61fe6f4ddf0b0c6d1ed6455f2cfbcc5`.
- After SHA-256: `7adbd9469b1e0ebcb8d6b62c8576eb4fb8b51efc70409607f604f453f8ac8187`.
- Backup: `/root/ssw590-delivery-bootstrap/https-20261115/Caddyfile.before`.
- Existing Gitea/Jenkins/Grafana routes, allowlist placeholders, volumes and
certificate storage were preserved. No firewall or published port changed.
Normal Windows curl and Ubuntu Python TLS checks passed without insecure mode.
Both hostnames negotiated TLS 1.3 with trusted hostname-matching certificates.
HTTP returned 308 with the corresponding HTTPS Location. HTTPS returned 502:
the staging/production pricing containers do not exist yet. This proves DNS,
TLS and redirects, not app health or a completed release.
All ten prior service/agent/builder containers remained running. Gitea, Jenkins
login and Grafana login returned private HTTP 200 after the reload. Production
monitoring was not enabled while the pricing service was absent.
Actual DNS answers, certificate issuer/SAN/validity/fingerprints and HTTP results
are in ignored `build/evidence/assignment8-https/verification.json`; application
and existing-service checks remain separate. No reviewed release, registry
publication, promotion, rollback, password reset or account-permission change
was performed during this work. The source changes remain uncommitted.
Caddy behavior: [Automatic HTTPS](https://caddyserver.com/docs/automatic-https).
@@ -0,0 +1,55 @@
# v1 publication and blocked deployment — 15 November 2026
[Pricing build 3](https://ci.yebilly.me/job/secure-delivery/job/pricing/3/)
ran in `release` mode from reviewed source/configuration commit
`09731acb0370566471dd4e401e59bafe55e927dc`. It began at 22:25:23.584 UTC,
took 77.799 seconds, and finished FAILURE. This was a published image followed
by a connection failure, **not a successful staging or production release**.
Tests, clean-source scanning and all nine locked dependency audits passed.
Both pre-push and registry-digest Trivy image reports analyzed two targets and
contained zero HIGH/CRITICAL findings. The agent built the image once, pushed
the source-SHA tag, pulled it back and verified this registry reference:
```text
git.yebilly.me/ssw590-group1/pricing@sha256:cccd47f112f839f3443c88c4d16fd7a1ed0fec2100a26464156526d53ccc2695
```
The generated staging/production records were timestamped 22:26:29.144 UTC.
Staging deployment began 22:26:33.530 and stopped at 22:26:39.422 UTC
(5.892 seconds), before any application configuration or container was created:
```text
TASK [Gathering Facts]
Failed to connect to the host via ssh: PTY allocation request failed on channel 0
startup : ok=0 changed=0 unreachable=1 failed=0
Ansible exit code: 4
```
Jenkins skipped the unchanged rerun and production approval/deployment.
The generated records and scans are archived in that build and copied to ignored
`build/evidence/assignment8-execution/jenkins-3/`. They are deliberately absent
from `delivery/releases/`: neither environment has been verified healthy.
## Correction and verification
Ansible's SSH connection plugin defaults to forcing a terminal. The deploy
key intentionally forbids PTY allocation. The inventory now selects
`ansible_ssh_use_tty=false` for the delivery group, matching that restriction.
See the official [Ansible 2.21 SSH connection options](https://docs.ansible.com/projects/ansible-core/2.21/collections/ansible/builtin/ssh_connection.html#parameter-use_tty).
Pinned host verification, key restrictions, credentials and sudo policy are unchanged.
The administrator-only preflight was extended to exercise Ansible's actual
SSH/become path using the same bound credentials, rather than plain SSH alone.
[Agent preflight build 3](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/3/)
passed in 17 seconds at 22:50 UTC. Its `ansible.builtin.command` invocation
of `id -u` returned `0`, proving the noninteractive module and sudo path.
The module reports CHANGED by default for a command; this is not a pricing
deployment or an unchanged-rerun result. Exact non-secret output is retained in
[`agent-preflight-3.txt`](agent-preflight-3.txt).
The source correction awaits Vincent's commit/push and Billy's review/merge.
Retry `release` from the corrected full main SHA; let the pipeline generate
fresh records for that reviewed source/configuration. Do not manually change
the failed attempt's record to imply a successful deployment or reuse it for
rollback. Retain its published image and reports as evidence.
+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}'
+27
View File
@@ -6,3 +6,30 @@ git.yebilly.me {
colors.yebilly.me {
reverse_proxy color-buttons-app:3000
}
# Jenkins: Stevens campus network (155.246.0.0/16) plus team and approved grader
# IPs from CI_TEAM_IPS in the untracked .env. Everyone else gets 403 before login.
# The Stevens VPN is split-tunnel, so it does not give visitors a 155.246.x.x address.
# 172.30.90.10 is Blackbox Exporter on the private probe network (monitoring/compose.yaml).
ci.yebilly.me {
@denied not remote_ip 155.246.0.0/16 172.30.90.10/32 {$CI_TEAM_IPS}
respond @denied 403
reverse_proxy jenkins:8080
}
# Grafana (Assignment 7): same allowlist as Jenkins, then Grafana's own login.
metrics.yebilly.me {
@denied not remote_ip 155.246.0.0/16 {$CI_TEAM_IPS}
respond @denied 403
reverse_proxy grafana:3000
}
# Assignment 8: apply after both DNS names resolve to The-Ocean. Containers
# publish no host ports; the existing proxy reaches their private aliases.
staging.yebilly.me {
reverse_proxy pricing-staging:8000
}
app.yebilly.me {
reverse_proxy pricing-production:8000
}
+36
View File
@@ -149,3 +149,39 @@ port; Caddy reaches it on the private `gitea_web` network.
```
Remove it with `docker rm -f color-buttons-app`, delete the block, and reload.
## Jenkins CI (Assignment 6 / Instructor Manual Chapter 4)
`jenkins/Dockerfile` extends the official `jenkins/jenkins:2.580.1-lts-jdk21`
image (digest pinned) with `python3` and the plugins in `jenkins/plugins.txt`.
Builds run on the controller's single executor. Jenkins publishes no port:
browsers reach it through Caddy at `https://ci.yebilly.me/login`, and the Gitea
webhook reaches `http://jenkins:8080/gitea-webhook/post` on the private network.
1. DNS: `A` record `ci` -> droplet IPv4.
2. On the droplet, put team source IPs in the untracked `~/gitea/.env`
(space separated CIDRs; Stevens 155.246.0.0/16 is already in the Caddyfile):
```bash
echo 'CI_TEAM_IPS=203.0.113.7/32' > ~/gitea/.env # example address
```
3. Copy `docker-compose.yml`, `Caddyfile` (with `cat >`, see above) and the
`jenkins/` folder, then:
```bash
cd ~/gitea
docker compose build jenkins
docker compose up -d jenkins
docker compose up -d --force-recreate gitea caddy # webhook allowlist + CI_TEAM_IPS + alias
```
4. Unlock Jenkins with `docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword`
(read it yourself; never paste it anywhere), install **no** suggested
plugins, create one named administrator per teammate, and set the Jenkins
URL to `https://ci.yebilly.me/`.
Operate:
```bash
docker compose restart jenkins # settings and jobs live in the jenkins-home volume
docker compose logs --tail 100 jenkins # failed build or webhook: check here, then
# Gitea repo Settings -> Webhooks -> Recent Deliveries
docker stats --no-stream; free -m # memory pressure on the 512 MB droplet
```
+40 -1
View File
@@ -12,6 +12,7 @@ services:
- GITEA__server__ROOT_URL=https://git.yebilly.me/
- GITEA__server__HTTP_PORT=3000
- GITEA__server__DISABLE_SSH=true # Git over HTTPS only
- GITEA__webhook__ALLOWED_HOST_LIST=jenkins # only private webhook target allowed
volumes:
- gitea-data:/data
networks: [web]
@@ -27,13 +28,51 @@ services:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data # certificates + ACME account
- caddy-config:/config
networks: [web]
environment:
- CI_TEAM_IPS=${CI_TEAM_IPS:-} # team source IPs for ci.yebilly.me, kept in untracked .env
networks:
web:
# Jenkins resolves git.yebilly.me to Caddy here, so checkout and status
# calls stay on the droplet instead of hairpinning through the public IP.
aliases: [git.yebilly.me]
probe:
# Blackbox Exporter (monitoring/compose.yaml) probes both sites through Caddy here.
aliases: [git.yebilly.me, ci.yebilly.me]
depends_on: [gitea]
# Jenkins LTS controller (Assignment 6). Builds run on its single executor.
# Bounded so Gitea keeps memory on the 512 MB droplet.
jenkins:
build: ./jenkins
image: ssw590-jenkins:2.580.1
restart: unless-stopped
environment:
# The capacity test's 128 MiB heap ran builds, but the web UI hit "OutOfMemoryError:
# Java heap space" once the update-center catalog loaded (2026-10-22), so the
# persistent service gets twice the test bounds on the 1 GiB droplet.
- JAVA_OPTS=-Xms64m -Xmx256m -XX:+UseSerialGC -Djava.awt.headless=true
volumes:
- jenkins-home:/var/jenkins_home
networks: [web]
mem_limit: 512m
memswap_limit: 768m
cpus: 0.75
pids_limit: 256
# ponytail: no ports: on purpose -- Caddy and the Gitea webhook reach jenkins:8080 privately;
# agent port 50000 is never published.
volumes:
gitea-data:
caddy-data:
caddy-config:
jenkins-home:
networks:
web:
# Fixed subnet so Blackbox Exporter can have a fixed address (172.30.90.10), the only
# private address the ci.yebilly.me allowlist admits. The web subnet stays denied:
# Docker's proxy presents IPv6 and hairpin visitors as its gateway, 172.18.0.1.
probe:
ipam:
config:
- subnet: 172.30.90.0/28
+18
View File
@@ -0,0 +1,18 @@
# Official Jenkins LTS image plus what the controller executor needs to run the
# pipeline: python3 for the tests and the pinned plugin lockfile.
FROM jenkins/jenkins:2.580.1-lts-jdk21@sha256:a660310e39ade10631f774bacd5219de767dfd08947ea5c32a739b5e5bb382c1
USER root
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3 \
&& rm -rf /var/lib/apt/lists/*
USER jenkins
# ponytail: curl + sha256sum instead of jenkins-plugin-cli, which needs >128 MiB heap
# just to parse the update-center JSON on a 512 MB droplet.
COPY plugins.txt /tmp/plugins.txt
RUN mkdir -p /usr/share/jenkins/ref/plugins && cd /usr/share/jenkins/ref/plugins \
&& tr -d '\r' < /tmp/plugins.txt | grep -Ev '^(#|$)' | while IFS=: read -r name ver sha; do \
curl -fsSL -o "$name.jpi" "https://updates.jenkins.io/download/plugins/$name/$ver/$name.hpi" \
&& echo "$sha $name.jpi" | sha256sum -c --quiet || exit 1; \
done
+71
View File
@@ -0,0 +1,71 @@
# Lockfile copied from the team's prepared plugin bundle (Vincent Sun, 2026-10-21): roots
# workflow-aggregator:608.v67378e9d3db_1 and gitea:286.v0740a_413c1eb_ plus every resolved
# dependency, the same set exercised by ci/jenkins-capacity. Format name:version:sha256.
# Regenerate the whole file from a new bundle manifest rather than hand-editing one line.
# Added 2026-10-22: matrix-auth:3.3 for named Jenkins roles (its only dependency, ionicons-api,
# was already in the bundle at the required version).
# Added 2026-10-23: pipeline-graph-view (stage view of each run) with its new dependencies
# jackson3-api and snakeyaml-engine-api; other required versions were already satisfied.
apache-httpcomponents-client-4-api:4.5.14-269.vfa_2321039a_83:cea2f61cc72890b962fd4b767c31778c6cb30015b4a8758b4c26b62e51ca9533
asm-api:9.11.1-226.vff833a_e4c58e:ba315fe727be0311cd5115205a09a2abb550b73287cc4ee07af5f7ef6502f1f8
authentication-tokens:1.144.v5ff4a_5ec5c33:8069074af688b102703410045a11394fb8d2f52c2cc2d7abd3067e3adff5fc24
bouncycastle-api:2.30.1.86.2-310.v4655f6742752:57cc5cf1585f9a8f29c5a1e3985f07dace5d5359545d788e72ecaa3636515a58
branch-api:2.1303.v9f3b_95dc329d:6ecfc3d335cec791008a2d06ca933c6ccc97db1c14a4aee5030affebb97482e0
caffeine-api:3.3.1-214.v18eb_56b_34920:768ed05774f12d85bf8ecff5d509f037810d1359de8b4fb1385624f6f547c90b
cloudbees-folder:6.1106.v3a_d9a_6d2465e:4ccfcfe145a1b36aef61f19187e8aa74eb3c90fdb9c9bfce865e09aa13c8a70a
commons-lang3-api:3.21.0-122.v6a_ea_4fd34049:4d6194f8d3b3f2b69264f0403fe5a51846236a41f4e363f6aae45f82f7761657
commons-text-api:1.15.0-218.va_61573470393:ae2abdf957694f4aa39b9ba0b539edabc384f3da277551879e34ffb22fb13764
credentials-binding:728.v902a_273b_8947:bd7d1a187e35c8e2b6619cd50f2f8c5d28aafc4ef8fd9de572fb2cfa464f466d
credentials:1514.vb_01eb_014e7d4:b6e0a05d107fe492bb57baea75fb585fb65dd90c2456a6432b90b87226997457
display-url-api:2.217.va_6b_de84cc74b_:07eeaae738b451bade4756900b48561c6c493a42c7ba07a45b22a2dce71ac0ca
durable-task:686.v80ff80875b_82:1f5bb92ee5784ee01a4e4e0307e806fa1e260db8aceba56fe8d277e939278dfa
git-client:6.6.1:69ab80e3bd51e2e4e676a18722c02c7b163eb11a758b52ecf179d58e1ca1738f
git:5.11.0:bf4639abb65e6ca210bd0d7cb9b6570e93717894bdcd008b2e7e5a916dd818f6
gitea:286.v0740a_413c1eb_:242e091be9cbbd289546c65a85cf948670de2b3020db573e162926a97c3b5837
gson-api:2.14.0-201.v8eefe5515533:6940cd0f795f72371fd5644d885db9ec0a2077985ac55de85d19ab3b1fac2bb7
handy-uri-templates-2-api:2.1.8-38.vcea_5d521d5f3:2e5881410b0bca648fb78c890bfd8b83c46e4ff4c778235cb58e28b45d89b10e
instance-identity:203.v15e81a_1b_7a_38:df2b3205a6177248f12b294650a60405f65ba2cd503ca9599b2dcb72c1de5018
ionicons-api:94.vcc3065403257:95f3504375d628d887425ccdf32d5606a230261ee42dc683f13958d8e973ac3f
jackson-annotations2-api:2.22-19.v10a_a_582ea_26e:f13d0a17af6f8c8939a6edd30952006b77dca4760b1f40e0289c363918b7d17d
jackson2-api:2.22.3-447.v6a_93ce7d2c82:ce2cfb7a5ad6e66aea9a5b6c4a5ea0622bfc5c05db5db8918581ae7f1d10ff33
jackson3-api:3.2.4-103.vf5a_b_3f4ea_cec:4397f73c11ba5085a40280555b519c9427cf8d69d63d5d60f4f623f72f953fe2
jakarta-activation-api:2.1.4-1:e62298341742f14b374045387ba641ad8a19376793c76bdafebb4a05b5099712
jakarta-mail-api:2.1.5-1:244735ea85a51332c079d235a5713e70d3810bea62332894002acc39914ce11b
jakarta-xml-bind-api:4.0.9-19.v2b_a_5b_44d9a_1c:2f59227936687ec00f7ea62b550e7a6e9c86cda3423f3567ffe66bbdf235ffb5
javax-activation-api:1.2.0-8:e96e88c52edf07ba00fb45b26cc411a7a95fa3d4491aaa1a5d36637665880560
jaxb:2.3.9-143.v5979df3304e6:38ddf4cf5db61a591044130c2f7ccb2b7aa9abebc8fcd8a6953f8da550d002ed
joda-time-api:2.15.0-208.v6b_084e7a_d9f0:427513635d122f62fcd8e52af08cc895913b9a70568e7665a3ce8fc1a4871ddf
json-api:20260814-226.v20f9685d642c:c5ac5ecfddd35c07087b3333ae05ec4167a70abae8bf0ebcb7338b6b54540889
mailer:534.v1b_36f5864073:5426a66a3f879d25fcb4baff678a28422afbabff22cd6e4f0f998fc67a3dc3fa
matrix-auth:3.3:b8f7a916f1de0872d4c16264bcf9604fdb5b2da1827764745946c7ac5f613948
mina-sshd-api-common:2.19.0-192.v2b_a_7b_2c1dc71:887ebd645e43919b6113201257821b990fc923f375382a5dada0c089e49b85bc
mina-sshd-api-core:2.19.0-192.v2b_a_7b_2c1dc71:5039ea17ea1aa9e349712ccc1e036c38ea9f20f722affc220c2c751369f32495
pipeline-build-step:601.v6d4c6d1a_9dc7:1b61a1820844f3f72f9dfcd6d7eeab66fa0fbcee5e3923b912cd1ed10fbf63c5
pipeline-graph-view:1053.v9df19e6ceed2:4a92651101fb02e0db24170211ef1b4cc14b7d3c20df51a2fa61807f75bff8ff
pipeline-groovy-lib:822.vc95f70dea_db_7:a633824da17e95fe2a9f03e8d951a771c70a729e987fc51874146723f3b6343b
pipeline-input-step:560.v56198a_642157:7c61bb745ecd1e4e5c7864dc7c8352148d9b2281bcca5a48fd3a7cca7290a135
pipeline-milestone-step:152.v6e22b_8cfc66c:cb3187809e219f01b42068f277058a818033f3cfd14da7ec59c86f028fc38386
pipeline-model-api:2.2293.v6e7193cec599:cdd72a69bf2863a1683b282febd0256d5d266111134c3803a8c4a051b6b4c133
pipeline-model-definition:2.2293.v6e7193cec599:9f4f62e0a13fefc9c5736a20ad5124af2a324357294fd8ea8d8f848b7c497f92
pipeline-model-extensions:2.2293.v6e7193cec599:00fbf0938ef13f6aedaa0900ec4cd03fcc986e34b1820bf13f761c2f29831861
pipeline-stage-step:345.va_96187909426:2eba433b28f2dfc90519e233b14264890f97b93b78e25c664d56607141fcd94b
pipeline-stage-tags-metadata:2.2293.v6e7193cec599:032f011fc50cb273b300d44fb6c2800e3dbdf0d78548b15e0f192ba7cc95d178
plain-credentials:199.v9f8e1f741799:b5e5e35cf93ad3b818a983916cbcdf3f7866699410a4df923e6a2968ecc3a448
scm-api:728.vc30dcf7a_0df5:1336472987daa2fa912210aba00e1e37b739ce03f75c973a6794d1a0f55c0326
script-security:1436.v1082791135e4:c2292e200c5796675c16d19325469aac4a5460c7ad23974952b9823f62066f6a
snakeyaml-api:2.7-152.vc672728cf536:bfa595a283634c8dd63aa8d1b039cf3d3f52e0952048058fc0b9a4826ca06508
snakeyaml-engine-api:3.2-18.v885ed7ff698f:89c14c0ac2816c1efc192dd333b4b26d97ae58d2ab1d492e8b52feca406e220e
ssh-credentials:372.va_250881b_08cd:7b4d035b05b331038f3dfa99ddfef0cabbacede8f0ad2a6ca9611fb0844108a9
structs:362.va_b_695ef4fdf9:a0a5db44f2cb082a9ec6572c088340521f033fff8c351fc7eba9ef7f07dbbf8d
variant:70.va_d9f17f859e0:12e214ea694469a4461b55881ecb4074ae5dfb04797dbc0dad390f6f4bc75aaf
woodstox-core-api:7.3.0-16.v017f30ed004c:fca0ce7cd19274833df226cd6746d71ce4025b784a81bd5b8512730f5d34a9df
workflow-aggregator:608.v67378e9d3db_1:7b94227c1afa01bb262c14919ad4a333412f1b51d947c0f21909ec2daff357dc
workflow-api:1413.v2ff1a_5e720fa_:f4adbd6b34a2a0b643a12b898110bd976350142eff6322efda21efacbccb6835
workflow-basic-steps:1098.v808b_fd7f8cf4:93449eb494658d065d097e8c54f707c98c9ce3e54da2fb98281b0a0487154eaf
workflow-cps:4395.v738456a_5da_6b_:2af278f3012f294165db715bfa608045feaf781a6c7c85b5d7ab1ee5b707f021
workflow-durable-task-step:1479.v56e587f413a_7:a0f0f1464ce3592f76d0f0079ce9fc2d4272594f995bf3d1a7ede4cd5031452e
workflow-job:1609.v8926e7962024:1f63a3dc4e9f8bfbde7b759530da4073e105a92fee3b647962d981de223ac8f5
workflow-multibranch:842.v3a_b_59b_57b_e6e:af26afd93b5d730d203d8f58d1e104712ad1a7ddcf6837886d3272b1c0057e46
workflow-scm-step:487.v41313a_96b_65d:532fc247cba83845df3c7fccaabfc3cb1f637729b145211728bcb974a3a67552
workflow-step-api:724.v538c2362b_dfb_:887491de444174228471993b0b2db958db2e7fb577857c8516c58e9618049896
workflow-support:1015.v785e5a_b_b_8b_22:914ee717ab8c1d60d0d3ea49a1af11e4ea65c1e74c0b44dc3522f9a2fe5b2a8e
+57
View File
@@ -0,0 +1,57 @@
# Manual runner migration evidence
Requested by Vincent on 14 November 2026, Eastern time. Server timestamps below
are UTC on 15 November. No commit, push, new registration or scope change occurred.
- Baseline 04:24 UTC: 1,967 MiB RAM, 860 MiB available, 338 MiB swap used;
root disk 55% used, 11 GiB available (rounded by df).
- Exported the existing compiler image, verified the transfer archive SHA-256
`faf56b61af1187b6dad0f1e27b1ec47bed282ffe52aee9c458c13a88ee02849a`,
then loaded it on The-Ocean. Image ID matches the original tested image:
`sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d`.
- Stopped the idle laptop runner before copying its existing registration
directly over pinned SSH into the remote Docker volume. Identity was
validated quietly, mode 0600; no value was output or written into the repo.
Name `ssw590-vince-local`, label `latex-local`, capacity one and repository
scope remain unchanged. The laptop volume/image are retained as fallback.
- At 04:31 UTC the remote daemon declared successfully. The initial 96 MiB
daemon cap was insufficient during action setup: Docker recorded an OOM
event at 04:32:18 and restart count 1. Run 12 attempt 2 / job 13 was canceled.
Its failure log is retained; its orphan container, network and two task-only
volumes were removed after validation, preserving shared volumes.
- Raised only the daemon to 192 MiB RAM / 256 MiB RAM+swap, with GOMEMLIMIT
128 MiB and 0.25 CPU. Compiler job caps remain 512 MiB / 768 MiB, 0.5 CPU,
256 PIDs, no published ports and no automatic job Docker socket mount.
- [Run 12, attempt 3, job 14](https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/actions/runs/12/jobs/14)
succeeded on the remote runner. Source is reviewed main commit
`8beefde2a4983888effb79526e527303e60a1a82`; this reruns Assignment 7 source,
not the uncommitted Assignment 8 preparation. Setup 2m33s, checkout 9s,
compile 1m42s, PDF upload 5s, diagnostics upload 2s, completion 1s; total 4m32s.
- Diagnostics supplied by Vincent in `build/evidence/run-12/` confirm source
SHA, run 12, suffix `+build.12.8beefde`, TeX Live 2022, latexmk 4.79,
Git 2.39.5 and Node 22.23.3. The PDF is 9,059,039 bytes and its SHA-256
matches diagnostics:
`f81fd73d8fd975d8d61164948a977c4048ee93e38b656904334835f6b5c29c8b`.
Its title was visually verified as `5.1+build.12.8beefde`.
- Browser download waiting timed out and the debugger then detached. Vincent
supplied diagnostics; the exact attempt-3 PDF was retrieved using read-only
artifact metadata and gzip payload over pinned administrator SSH, without
changing server data. Original expired attempt-1 metadata was preserved.
- At 04:41 UTC during compilation: 738 MiB host RAM available, 354 MiB swap
used; sampled compiler working set 142.4 MiB, daemon 20.43 MiB. A later
idle check found no active jobs, daemon restarts 0 and no current OOM flag.
These samples do not prove concurrency capacity or uninterrupted service.
- The idle daemon restarted and declared successfully again at 04:55:52 UTC.
`unless-stopped` is configured; a complete Droplet reboot was not performed.
- Final post-migration check: all ten service/agent/builder containers running;
Gitea, Jenkins login and Grafana login returned private HTTP 200. Host RAM
available 840 MiB, swap used 358 MiB, root disk 61% used with 9.2 GiB
available after removing the verified compiler transfer archive. Both laptop
daemons were confirmed exited. Protected identities and prior evidence remain.
Raw logs, runtime checks and artifact verification are under ignored
`build/evidence/assignment8-manual-runner/`; the user-provided diagnostics and
verified CI PDF remain in `build/evidence/run-12/`. Existing service checks and
the final local manual build are recorded separately. Both active runners
now run on The-Ocean; keep manual compilation and delivery releases sequential.
The assignment's actual app releases and recovery evidence remain pending.
+78
View File
@@ -0,0 +1,78 @@
# Manual Actions runner on The-Ocean
Vincent requested this migration on 14 November 2026 after moving the Jenkins
delivery agent. This replaces the active laptop runner; it does not create
another registration or expand its repository scope. The historical runner
name `ssw590-vince-local` and label `latex-local` remain for workflow compatibility.
The container is `ssw590-manual-runner`, under `/opt/ssw590-manual-runner`.
## Configuration and ownership
- Gitea runner 2.3.0, pinned to the same official image digest as the laptop.
- Same tested compiler image `ssw590-manual-ci:20261007`, ID
`sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d`.
- Runner: 192 MiB RAM / 256 MiB RAM+swap, 0.25 CPU, one job at a time.
The first 96 MiB trial was killed during action setup; that attempt is retained
in migration evidence. Compiler jobs have a separate 512 MiB / 768 MiB cap,
0.5 CPU and 256 PID cap. Resource limits are ceilings, not reserved memory.
- Runner and job containers publish no ports. Existing Gitea HTTPS and TLS
verification remain enabled. Cache server stays disabled.
- Registration lives in the host's `ssw590-local-runner-data` Docker volume,
`/data/.runner`, mode 0600 in a 0700 directory. Never print it, place it in
Git or share it as evidence. The stopped laptop copy is an intentional fallback.
- `unless-stopped` reconnects the daemon after Docker/host restarts. No server
reboot is needed for installation. Only restart an idle runner.
- Admission checks pause new jobs below 3 GiB free disk or 600 MiB available
host RAM. This does not reserve resources or lock Jenkins out. Run manual
builds and Jenkins delivery releases sequentially on this single-CPU host.
- VS maintains the runner; BY retains Droplet administration. Existing Droplet
billing applies; no new instance or plan change was made.
The runner can administer host Docker. Automatic socket mounting into jobs is
disabled, jobs are not privileged, capabilities are dropped, and arbitrary
workflow bind mounts remain disallowed. Runner 2.x does not comprehensively
filter workflow container options, so only the trusted team may edit these
workflows. Co-location gives a compromised Docker-authorized workflow a path
to the shared host; these settings are not strong isolation from untrusted code.
See [official runner configuration](https://docs.gitea.com/runner/2/configuration/).
## Reconnect and stop
From an authorized administrator SSH session:
```sh
sh /opt/ssw590-manual-runner/start.sh
cd /opt/ssw590-manual-runner
docker compose ps
docker compose logs --tail 30
python3 verify.py
# Only when idle:
docker compose stop
```
The start helper requires existing identity and compiler image; it never
registers a new runner. `verify.py` validates identity quietly and prints only
non-secret runtime settings. It can capture compiler-job limits while a job runs.
No account token is required in shell arguments, environment or repository.
## Migration and fallback
The migration exported the existing compiler image, verified the transfer
archive SHA-256 and loaded image ID, stopped the laptop daemon, then streamed
its existing registration directly from Docker Desktop through pinned SSH into
the remote Docker volume using `import-identity.sh`. The import refuses to
overwrite an identity. It is a one-time operation; do not rerun it here.
Original laptop volumes and images remain intact.
To return temporarily to the laptop, first stop the remote runner while idle,
then use `gitea/local-runner/runner.ps1 -Action Start -AllowLaptopFallback`.
Stop the laptop copy before restarting the remote one. Never connect both
copies of the registration. The label intentionally remains `latex-local`.
After grading, only when instructed, retain needed evidence, stop this runner
and remove only its explicitly identified container, network and state volume.
Retire the Gitea registration only when no fallback is needed. Never prune the
host or remove shared Gitea/Jenkins/proxy/monitoring state.
Source for image/state handling:
[Gitea Docker installation](https://docs.gitea.com/runner/2/installation/docker/).
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# Pause fetching new jobs when the shared host has less than 600 MiB available.
# This is admission control, not a reservation or cross-engine execution lock.
set -eu
awk '/^MemAvailable:/ { found=1; if ($2 < 614400) exit 1 } END { if (!found) exit 1 }' /proc/meminfo
+32
View File
@@ -0,0 +1,32 @@
name: ssw590-manual-runner
services:
runner:
image: docker.io/gitea/runner@sha256:66d80966792e621c9761c47919644198d35fd1c297e9a01e69ed3c1ae37db0c7
container_name: ssw590-manual-runner
working_dir: /data
entrypoint: ["gitea-runner"]
command: ["--config", "/config.yaml", "daemon"]
restart: unless-stopped
stop_grace_period: 70s
environment:
GOMEMLIMIT: 128MiB
volumes:
- runner-data:/data
- ./config.yaml:/config.yaml:ro
- ./admission-check.sh:/admission-check.sh:ro
- /var/run/docker.sock:/var/run/docker.sock
mem_limit: 192m
memswap_limit: 256m
cpus: 0.25
pids_limit: 128
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
volumes:
runner-data:
external: true
name: ssw590-local-runner-data
+24
View File
@@ -0,0 +1,24 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 30m
shutdown_timeout: 60s
insecure: false
labels:
- "latex-local:docker://ssw590-manual-ci:20261007"
cache:
enabled: false
container:
privileged: false
valid_volumes: []
docker_host: "-"
force_pull: false
options: "--memory=512m --memory-swap=768m --cpus=0.5 --pids-limit=256 --cap-drop=ALL --security-opt=no-new-privileges"
health_check:
enabled: true
min_free_disk_space_mb: 3072
script: /admission-check.sh
interval: 15s
timeout: 5s
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Root-operated, one-time stdin import. Never print or stage registration in Git.
set -eu
test "$(id -u)" = 0
docker volume create ssw590-local-runner-data >/dev/null
docker run --rm -i --network none --user 0:0 --entrypoint sh \
--mount type=volume,source=ssw590-local-runner-data,target=/data \
docker.io/gitea/runner@sha256:66d80966792e621c9761c47919644198d35fd1c297e9a01e69ed3c1ae37db0c7 \
-c 'set -eu; test ! -e /data/.runner; umask 077; cat > /data/.runner; test -s /data/.runner; chmod 700 /data; chmod 600 /data/.runner'
echo 'Registration imported into protected Docker volume; values not printed.'
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Root-operated reconnect only; an existing protected registration is required.
set -eu
cd /opt/ssw590-manual-runner
docker image inspect ssw590-manual-ci:20261007 >/dev/null
docker volume inspect ssw590-local-runner-data >/dev/null
docker compose config --quiet
docker compose run --rm -T --no-deps --entrypoint sh runner -c 'test -s /data/.runner'
docker compose up -d
docker compose ps
+59
View File
@@ -0,0 +1,59 @@
"""Read-only, non-secret runner/runtime checks. Run as root on The-Ocean."""
import json
import stat
import subprocess
from datetime import datetime, timezone
from pathlib import Path
def run(*args):
return subprocess.check_output(args, text=True).strip()
template = ('{"state":{{json .State}},"host":{{json .HostConfig}},'
'"mounts":{{json .Mounts}},"image":{{json .Config.Image}},'
'"restart_count":{{.RestartCount}}}')
def inspect(name):
# Fetch selected fields, never container environment variables.
info = json.loads(run('docker', 'inspect', '--format', template, name))
state, host = info['state'], info['host']
return {
'name': name, 'image': info['image'], 'running': state['Running'],
'oom_killed': state['OOMKilled'], 'memory_bytes': host['Memory'],
'restart_count': info['restart_count'],
'memory_swap_bytes': host['MemorySwap'], 'nano_cpus': host['NanoCpus'],
'restart_policy': host['RestartPolicy']['Name'],
'port_bindings': host['PortBindings'],
'mount_destinations': [mount['Destination'] for mount in info['mounts']],
}
root = Path(run('docker', 'volume', 'inspect', '--format', '{{.Mountpoint}}', 'ssw590-local-runner-data'))
identity = root / '.runner'
registration = json.loads(identity.read_text())
assert registration.get('name') == 'ssw590-vince-local'
assert registration.get('address', '').rstrip('/') == 'https://git.yebilly.me'
assert isinstance(registration.get('token'), str) and registration['token']
assert stat.S_IMODE(identity.stat().st_mode) == 0o600
# Registration is checked in memory only. Do not serialize any of its values.
report = {'observed_at': datetime.now(timezone.utc).isoformat(),
'registration_validated_without_output': True, 'identity_mode': '0600',
'runner': inspect('ssw590-manual-runner'), 'active_jobs': []}
assert report['runner']['running'] and not report['runner']['oom_killed']
for name in run('docker', 'ps', '--format', '{{.Names}}').splitlines():
if name.startswith('GITEA-ACTIONS-TASK-'):
job = inspect(name)
assert job['memory_bytes'] == 512 * 1024 * 1024
assert job['memory_swap_bytes'] == 768 * 1024 * 1024
assert job['nano_cpus'] == 500000000
assert '/var/run/docker.sock' not in job['mount_destinations']
report['active_jobs'].append(job)
report['admission_check'] = run('docker', 'exec', 'ssw590-manual-runner', 'sh', '-c', '/admission-check.sh && echo passed')
report['compiler_image_id'] = run('docker', 'image', 'inspect', '--format', '{{.Id}}', 'ssw590-manual-ci:20261007')
assert report['compiler_image_id'] == 'sha256:5d24657a4578977fc7709165b82fc869f09a654a58ab4a0c8defd9d2cd662d5d'
report['memory'] = run('free', '-m')
report['disk'] = run('df', '-h', '/')
report['result'] = 'passed'
print(json.dumps(report, indent=2))
+7
View File
@@ -1,5 +1,12 @@
# Local Gitea runner (Assignment 5 preparation)
**Current placement, 14 November 2026:** the active runner has moved to
The-Ocean. This directory preserves the original laptop configuration and
historical setup. See [`../droplet-runner/README.md`](../droplet-runner/README.md).
The laptop copy is stopped; Register/Start now require `-AllowLaptopFallback`
after stopping the remote copy. Never run both registrations simultaneously.
The setup instructions below describe the original October installation.
Run from the repository root in PowerShell with Docker Desktop's Linux engine running:
```powershell
+5 -1
View File
@@ -1,9 +1,13 @@
[CmdletBinding()]
param(
[ValidateSet('Check', 'Register', 'Start', 'Logs', 'Stop')]
[string]$Action = 'Check'
[string]$Action = 'Check',
[switch]$AllowLaptopFallback
)
$ErrorActionPreference = 'Stop'
if ($Action -in @('Register', 'Start') -and -not $AllowLaptopFallback) {
throw 'This runner now runs on The-Ocean. Stop the remote copy first, then pass -AllowLaptopFallback for an intentional laptop fallback. Never run both copies of the registration.'
}
$composeFile = Join-Path $PSScriptRoot 'compose.yaml'
$composeArgs = @('compose', '--project-name', 'ssw590-local-runner', '-f', $composeFile)
$runnerImage = 'docker.io/gitea/runner@sha256:66d80966792e621c9761c47919644198d35fd1c297e9a01e69ed3c1ae37db0c7'
+28 -1
View File
@@ -14,7 +14,34 @@ discuss repository visibility with the other group member before publication.
No registration token, runner identity file, private key, or account credential
is copied. Hints-only Hosts/Passwords records are retained.
## Build and status
## Local PDF for review and submission
From repository root, use the existing TinyTeX installation:
```powershell
./manual/latex/makefilePowerShell.ps1 -Action pdf
```
The helper detects the shared `../Tools/LaTeX/TinyTeX` installation. For a
different existing installation, set `DEVOPS_LATEX_BIN` to its `bin/windows`
directory first. It runs the full bibliography, glossary, acronym, index,
and cross-reference sequence and replaces
`manual/2026F-SSW-590-DevOps-Group-1.pdf`. That PDF and compiler intermediates
are ignored by Git; sources and evidence remain versioned. Docker and an
Actions artifact download are unnecessary for this local build. Local builds
show the human document version without claiming an Actions run number.
After reviewing the PDF, remove generated LaTeX intermediates with:
```powershell
./manual/latex/makefilePowerShell.ps1 -Action clean
```
The PDF is retained. Continue using Gitea Actions for automated build evidence;
keep historical run artifacts already required by the manual. New local
revisions reuse this one PDF rather than creating more run folders.
## Historical Assignment 5 build evidence
See [compiler and workflow instructions](../ci/manual/README.md).
Gitea run 1 succeeded for commit `828f6c5` (issue #12), including checkout,
+23 -8
View File
@@ -1,9 +1,24 @@
This group document records the SSW 590 coursework and its supporting
commands, designs, and evidence. Assignment 5 automates compilation of the
LaTeX manual through Gitea Actions, using a repository-scoped Docker runner
on Vincent's laptop while Gitea remains on the DigitalOcean droplet. The
workflow checks out the triggering revision, compiles with a recorded TeX
Live toolchain, adds run and commit identifiers to the PDF version, and
uploads the PDF and build diagnostics. Two successful source-change runs,
an intentional compiler failure, and a successful repair demonstrate the
workflow. Earlier chapters retain the group's prior assignment results.
commands, designs, and evidence. Assignment 8 implements secure delivery with
a trusted Jenkins agent, locked Flask/Gunicorn service, security gates,
Ansible, scoped deployment credentials and recovery runbooks. The prerequisite
jobs, DNS/TLS and deliberate Jenkins test/secret blocks passed. The reviewed v1
image was published with passing scans, but staging stopped at a terminal
request incompatible with the restricted deploy key. A noninteractive Ansible
preflight passed; its inventory correction awaits review/merge. Successful
v1/v2 deployment, approvals, rollback and staging recovery remain pending.
This draft is not ready for submission.
Assignment 7 introduced site reliability
engineering: Prometheus, Grafana OSS, Node Exporter, and Blackbox Exporter
run as four pinned containers beside Gitea and Jenkins on the originally 1\,GiB
DigitalOcean droplet, with Grafana at \url{https://metrics.yebilly.me/login}
for approved networks only. A dashboard shows host CPU, memory, and disk and
the HTTPS availability of Gitea and Jenkins. A 99\% availability objective is
defined and measured, and three alert rules (service availability, disk
space, and collection health) notify the team's Discord channel. Each was
shown firing and resolving; the availability rule through a planned Jenkins
outage that was detected in about two minutes and recovered about a minute
after restart. Earlier chapters retain the group's prior assignment
results, including the Jenkins merge gate and the Gitea Actions manual build.
On November 14 the team resized the droplet to 2\,GiB without enlarging its
disk, updated packages and verified the existing services.
+450
View File
@@ -521,3 +521,453 @@ replace review of the final workflow-generated PDF. No commit, push,
merge, issue closure, or submission was performed by Codex. Final evidence
update push, successful artifact review, group pull-request review/merge,
issue \#12 closure, and submission remain human workflow steps.
\section{Assignment 6 Jenkins Capacity and Test Preparation}
Date: October 19--21, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: instructor manual version 1.38 supplied by Vincent, the authorized
DigitalOcean droplet view, repository instructions, Vincent's reported resize
constraint and choice to test the existing droplet, terminal screenshots, and
downloaded capacity measurements. Codex prepared isolated core-only experiments;
Vincent ran them through his authenticated SSH connection. The first timed out.
After Vincent authorized stopping the graded Color Buttons app, the second
demonstrated core startup and 24 successful sampled Gitea HTTP checks. No kernel
out-of-memory event was recorded; final container accounting nevertheless
included about 80\,MiB RAM plus 212\,MiB swap. This is not evidence of plugin or
build capacity. Human/AI correction: the raw result claimed a 60-second idle
window, but recorded successful HTTP samples span only 54 seconds. Codex
preserved the evidence and prepared a corrected, unexecuted core script whose
timer starts after a successful response.
Vincent requested a portable human/Claude handoff for Billy Ye. Codex assembled
selected non-secret references, original evidence, scripts, structured state,
the prior team PDF and integrity hashes. The instructor PDF was missing at its
previous location when packaging; that limitation was identified explicitly.
On October 21, Vincent reported school-network connection timeouts. Read-only
checks confirmed that the attached Cloud Firewall allowed the measured source
IPv4, Gitea HTTPS responded, and TCP 22 timed out. The location/cause of filtering
was not proven. No firewall change, reboot or package upgrade was made by Codex.
Vincent asked Codex to prepare and explain the next test. The versioned test
sources include a host-side Python controller, disposable container
bootstrap, explicit Pipeline/Gitea plugin requests, plugin archive inventory,
trusted initialization hook, sample Python pipeline, fault/regression checks
and a readable runbook. The prepared test covers constrained installation,
plugin activation, a corrected 60-second healthy observation, then serial
passing, intentionally failing and repaired calculation tests. It retains
resource and Gitea checks, separate RAM/swap accounting, targeted cleanup and
a detached deadline. It adds no production credential, public Jenkins endpoint,
webhook, merge check, persistent service or paid resource. The controller's
single executor is restricted by the experiment's trusted local fixture; it
does not establish the final production build boundary.
Verification used: nine local Python regression/fault checks passed, including
the actual sample application's pass/failure/repair sequence; Git Bash accepted
the bootstrap syntax. Official plugin documentation supplied version/baseline
checks. Docker was initially off; Vincent then enabled it and authorized local
verification. The first local attempt exhausted the installer's 128\,MiB Java
heap while reading the plugin catalog, before Jenkins started; Docker did not
report a kernel OOM kill. Codex separated laptop-only plugin preparation
(768\,MiB RAM, 512\,MiB heap) from runtime. The official installer prepared
59 versioned and hashed plugin archives, and its temporary container was removed.
The revised runtime kept the original limits: 256\,MiB RAM, 512\,MiB for RAM
plus swap, half a CPU and a 128\,MiB heap. All 59 plugins loaded; healthy HTTP
samples spanned 65.39 seconds before the job ran. Three serial Jenkins builds
produced success, the intended unit-test failure, and repaired success. Peak
simultaneous accounted RAM plus swap was about 389.5\,MiB, with zero recorded
container OOM events. Cleanup succeeded and no experiment containers remained.
This demonstrates local Jenkins execution, not capacity beside Gitea on the
droplet. The laptop Docker VM had substantially more host resources; local mode
recorded the unmeasured droplet host/Gitea fields as null. Original failed and
successful evidence was retained. The upload package includes the resolved
plugin archives so the droplet need not repeat the larger catalog-resolution
step. Remaining work includes the guarded droplet run, actual Gitea integration and
merge-gate exercise, and the Assignment 6 report chapter. Hosts and Passwords
tables remain unchanged because no persistent service or real integration
credential was added. Existing deployment files and evidence were preserved;
no commit, push, merge or submission was performed by Codex.
\section{Assignment 6 Jenkins Deployment, Merge Gate, and Chapter}
Date: October 21--23, 2026; Tool: Anthropic Claude Code (Claude Opus 5.5);
Human: Billy Ye, with Vincent Sun as reviewer.
Inputs: instructor manual version 1.38 (Chapter 4), Vincent's two handoff
packages (capacity evidence, the prepared \texttt{ci/jenkins-capacity} test
and plugin bundle, and the patch for the preceding record), the repository
and its AI guidance, Billy's decisions (Jenkins on the existing droplet,
Claude runs droplet commands over SSH with Billy approving each step,
browser allowlist of Stevens 155.246.0.0/16 plus team addresses, and the
instructor's Python pricing example), and Billy's dated screenshots. Billy
loaded his SSH key into the Windows agent and typed its passphrase himself;
Claude never saw the passphrase, the Jenkins initial password, any account
password, or the \texttt{jenkins-bot} token.
Claude read the droplet state, ran Vincent's guarded test unchanged
(first run aborted on upload permissions it introduced; fixed with
\texttt{chmod}; second run passed), wrote the Dockerfile, plugin lockfile,
Compose, Caddy, and README changes, deployed Jenkins after backing up the Compose and Caddy files and with a
monitored rollout, and pushed the feature commits after Billy asked.
Billy performed every web-interface step (DNS, Jenkins setup and security,
bot account and token, credential, job, webhook, branch protection, PR
creation, merge); Vincent reviewed and approved PR~\#15.
Human/AI corrections: the plugin installer exhausted a 128\,MiB heap, so
Claude replaced it with hashed \texttt{curl} downloads; the 128\,MiB runtime
heap hung the web interface, so Claude doubled the container limits with a
recorded reason; Claude had dropped \texttt{matrix-auth} when adopting
Vincent's bundle, which Billy discovered when the option was missing, and
it was added; Billy's question about the build-view screenshot showed no
stage view was installed, so \texttt{pipeline-graph-view} was added. Claude
redacted a Jenkins reporting-endpoint ID and personal browser details from
screenshots.
Outputs used: the deployment files and application/test/\texttt{Jenkinsfile}
in PR~\#15; the command log retained under ignored
\texttt{build/evidence/}; \ChapterRef{JenkinsCI}; updated Hosts and Passwords
tables; glossary terms; title page, abstract, Document History; this record.
Unresolved: three theme plugins installed through the web interface are not
in the lockfile; the course deadline was reported as Friday but not checked
on the course page by Claude; the final PDF needs the Gitea Actions runner
on Vincent's laptop. No submission was performed by Claude.
\section{Assignment 6 Access-Path Correction}
Date: October 23, 2026; Tool: Anthropic Claude Code (Claude Opus 5.5);
Human: Billy Ye.
Inputs: an independent model review of the version 4.0 PDF, which noted that
the instructor access path (campus or Stevens VPN) had not been tested;
Billy's GlobalProtect connection to \texttt{sitvpn.stevens.edu} and his
redacted settings screenshot. Claude checked the public address and routing
table on Billy's laptop while the VPN was connected: the address was
unchanged and only 155.246.0.0/16 used the VPN adapter, so the VPN is
split-tunnel. Human decision: state the campus network plus addresses added
on request as the approved path. Outputs used: corrected access-path text,
an exposure-table row, the GlobalProtect figure, the Caddyfile comment,
version 4.1 and its history row. Billy's residential address was kept out of
the report. Vincent then tested from campus Wi-Fi \texttt{Stevens-Net}
(public address 155.246.151.38) and the sign-in page loaded; Claude combined
his screenshots into one figure, blurring the password field and profile
icon. A friend reportedly on campus saw a blank page (the 403); his network
and address were not recorded, so no conclusion is drawn from it.
\section{Assignment 6 Run-9 Review and Final Corrections}
Date: October 23, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: Vincent's request to review the run-9 PDF, instructor manual version
1.38, the repository's AI guidance, public Gitea commit/status/review records,
and Vincent's approval to correct the documentation while leaving the three
theme plugins unchanged. Codex reviewed the Jenkins chapter, updated tables,
history, and AI records visually; checked the artifact ZIP and PDF links;
and confirmed the recorded failed/repaired statuses, approval, and merge
against Gitea. A read-only HTTPS check returned the Jenkins sign-in page
with certificate verification passing. No authenticated Jenkins inspection
or new droplet experiment was performed during this review.
Human/AI corrections: the PDF linked a 60-plugin lockfile at the initial
deployment merge while describing the later 63-plugin set. Codex changed
that link to the recorded revision \texttt{ac18f11}, retaining historical
PR and run links. It clarified that \emph{Build Now} uses the revision
selected for that run and does not establish a clean workspace or the same
commit as an earlier run; clean local reproduction now calls for a fresh
clone and the recorded commit ID. It separated the observed delivery timeout
from the suspected CPU/discovery cause and made timeout tuning conditional.
At Vincent's direction, the theme plugins were left unchanged; the existing
security-check result is explicitly limited to its 63 checked versions.
Outputs used: these corrections in \ChapterRef{JenkinsCI}, version 4.2,
the dated Document History entry, and this record. Prior Billy/Claude
records and original run-9 evidence are preserved. Hosts and Passwords
tables are unchanged because no deployed service, account, or credential
changed. The revision is checked through the complete local TinyTeX build,
diagnostic inspection, and visual review of the affected PDF pages.
No commit, push, remote configuration change, or submission is performed
as part of this correction.
\section{Assignment 7 Monitoring Deployment, Tests, and Chapter}
Date: October 27--28, 2026; Tool: Anthropic Claude Code (Claude Opus 5.5);
Human: Billy Ye, with Vincent Sun as verifier and reviewer.
Inputs: instructor manual version 1.42 (Chapter 5), found in Billy's
downloads after Billy asked to implement ``chapter 5 of this manual''; the
repository and its AI guidance; Billy's decisions (measure capacity before
any resize and then try a capped deployment on the 1\,GiB plan, alerts to a
Discord webhook, hostname \texttt{metrics.yebilly.me}, Claude running droplet
commands over SSH with Billy approving each step, disabling four unused host
services after Claude showed the disk and boot checks); Billy's DNS record,
Discord channel and webhook, issue \#19, secrets file, Grafana login,
screenshots, pushes, and improvement issues \#20 and \#21.
Claude synced both checkouts, measured the baseline, chose and verified
pinned image digests, wrote the \texttt{monitoring/} configuration, the
Caddy and Compose changes, the dashboard, alert rules, and README runbooks;
validated them locally (Compose, \texttt{promtool}, \texttt{caddy validate},
and a throwaway Grafana run); deployed them after backing up the Caddy files;
ran the exposure, contact-point, capacity-alert, outage, persistence, and SLO
queries; and wrote \ChapterRef{SREMonitoring}, the Hosts and Passwords
updates, glossary terms, title page, abstract, and Document History. Billy
typed every secret himself: Claude never saw the Grafana password or the
webhook URL. API calls read the password from the Grafana container's
environment without printing it.
Human/AI corrections: the local Grafana run rejected an alert template
written with \texttt{\$\$labels}; the deployed Grafana could not read its
configuration after the Windows upload (fixed with \texttt{chmod}); Grafana~13
had removed the old contact-point test endpoint, so the replacement was found
from its own error message; one Grafana login from Claude failed because a
password was read from the file with untrimmed whitespace; the first
build-check before the outage matched the \texttt{ps} header and aborted
before anything was stopped; one SLO query was first evaluated at the wrong
time and was rerun; Billy's partial home IP address was removed from the
evidence file before commit; the push from Claude's shell failed
authentication, so Billy pushed and re-authorized Git Credential Manager.
Billy's questions about the CPU readings led to the I/O-wait finding and the
dashboard change.
Review and corrections: at Billy's request, Claude had an independent
subagent audit the chapter against the instructor's requirements. Claude
checked its findings against the evidence (two of its ``unsupported''
claims were supported by earlier output and a figure) and, with Billy's
approval, added a collection-health rule and tested it by stopping Blackbox
Exporter, ran Blackbox Exporter as non-root, compared CPU counters with
\texttt{/proc/stat}, and corrected four figures and the overstated
no-data claim. Billy replaced the Grafana administrator password himself;
Claude confirmed the old value was rejected and removed it from the
secrets file without printing it.
Outputs used: commits \texttt{d3a5e6b} and \texttt{b6cf080}, the chapter
commits on \texttt{feature/issue-19-monitoring} (PR \#22);
\texttt{monitoring/EVIDENCE.md}; \ChapterRef{SREMonitoring}; this record.
Assumptions and unresolved items: the title-page assignment title comes
from the Canvas page Billy showed (``\#7 Grafana and Promethous SRE --
Group''), with the spelling of Prometheus corrected; the acknowledgement was given to Claude before the restart, and
Billy's Discord reply came later; Billy created Vincent's Grafana
account \texttt{vsun1} as Viewer; the 24-hour SLO was not evaluated; the manual-PDF build needs
Vincent's runner when the branch is merged. No pull request, merge, or
submission was performed by Claude.
\section{Assignment 7 Run-11 Review, TCP Evidence, and Final Corrections}
Date: October 28, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: Vincent's request to double-check Billy's completed Assignment 7,
instructor manual version 1.42 Chapter 5, the run-11 artifact, repository AI
guidance, versioned monitoring configuration and evidence, and public Gitea
statuses and reviews. Vincent authorized the corrections and requested one
locally compiled PDF in the repository, excluded from Git. Codex inspected
the chapter and supporting figures, compared configuration and dashboard
queries with the rubric, and verified the final PR head, approval, merge,
and successful run-11 status. Chrome connected to Gitea; a subsequent
project-tab operation timed out, so no authenticated Jenkins/Grafana audit
or remote settings change was performed in this correction.
Human/AI corrections: Codex identified changing branch links, incomplete TCP
evidence from HTTP code 000, outdated review timestamps, and conclusions
stronger than the timing, sampling, or resource measurements supported.
Vincent ran the supplied external PowerShell loop on his laptop and moved
its CSV into the repository's ignored evidence directory. All 18 outcomes
matched: TCP 80/443 succeeded and seven private ports failed on both IPv4
and IPv6. Codex preserved the raw file and made a versioned copy replacing
only the local Wi-Fi name with a generic network description. The reusable
script preserves that loop with parameters; its syntax is checked without
claiming another network test. The CSV timestamps are completion times.
Outputs used: version 5.1; the new TCP table and reproduction command;
deployment links pinned to merge \texttt{34c4c74}; final approval/check and
run-11 links; qualified notification-delay, missing-sample, and memory-pressure
conclusions; a Document History entry; and this record. The local build helper
now discovers the shared TinyTeX path from the actual repository nesting;
local build instructions and PDF ignore rules retain one replaceable PDF.
The complete TinyTeX build includes the bibliography, glossary, acronym list,
index, and final reference passes, followed by diagnostic and visual review.
Billy/Claude records and original evidence are preserved. Hosts and Passwords
tables are unchanged because no deployed service, account, or credential
changed. The missed pre-deployment build observation remains a limitation;
later results do not recreate it. Commits, pushes, peer approval, and submission
remain with the group. This local revision is not described as an Actions
artifact or as already approved in Gitea.
\section{Assignment 8 Secure Delivery Preparation and Agent Setup}
Date: November 14, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Inputs: Vincent's request to implement the next assignment today, instructor
manual 1.43 Chapter 6 and Examples.zip, the Canvas assignment page, repository
AI requirements/guide, earlier configuration, and live read-only service checks.
Vincent retained commits/pushes and reported Billy unavailable until tonight.
Codex read the assignment, preserved prior work, verified remote main
\texttt{8beefde}, and created \texttt{codex/assignment8-secure-delivery}.
It adapted the instructor's v1 and Ansible starters, locked dependencies and
tool images, prepared a dedicated delivery pipeline, scan policy, immutable
release validation, idempotence gate, failure modes, observer and runbooks.
The original instructor authorship remains identified.
Human/AI corrections and execution: Vincent supplied his encrypted-key SSH
command and enabled Windows ssh-agent, initially also unloading the key; Codex
explained reloading it and keeping passphrases out of chat. Browser-console
and network limitations were distinguished from successful access. Vincent
resized The-Ocean to 2\,GiB while retaining disk size and applied host updates;
Codex verified resource and existing-service status. With authorization to
continue setup, Codex backed up Jenkins/Gitea, configured the restricted deploy
key and root sudo, separate package-scoped tokens under vsun1, folder-scoped
Jenkins credentials, exclusive laptop agent and disabled release job. Secret
values were transferred only through protected runtime storage and were not
printed or placed in Git. Agent prerequisite build 1 passed with real credential
binding, strict SSH host-key checking and noninteractive sudo.
Checks/corrections: local v1 tests passed; a generated wrong-price test failed
as intended; the scanner-supported synthetic fixture blocked delivery; the
dependency audit and final runtime-image gate passed their configured policies.
Earlier Debian and installer-containing Alpine scans failed and were retained;
Codex selected the Alpine runtime and removed unused pip/ensurepip without
adding scanner exceptions. The installed Jenkins parser rejected the initial
timestamps option because its plugin is absent; Codex removed that option and
retained explicit UTC evidence. Browser editor insertion briefly concatenated
two validation snippets; the editor was cleared and the read-only validation
repeated successfully. The host setup script compiled against installed plugin
classes before application. Ansible syntax and agent Compose checks passed.
Outputs used: \ChapterRef{SecureDelivery}, version 6.0 preparation, the adapted
application/toolchain, pipeline and control tests, bootstrap, runbooks, issue
draft, planned proxy and production-monitoring additions, actual prerequisite
inventory, Hosts/Passwords hints, history and this record. Existing Billy/Claude
records are unchanged. Source/configuration release SHAs and registry digests
have not been invented. The local preflight image explicitly identifies itself
as uncommitted preparation, not a reviewed release.
Unresolved items: application DNS requires the domain owner's access; distinct
names are explicitly required, so path-only routing was rejected as a substitute.
Vincent/Billy must create the issue, commit/push and review/merge v1 and later
changes. Real Jenkins blocked-gate runs, v1/v2 publication, interactive production
approvals, idempotence, both recovery exercises, timing/monitoring correlation
and final submission review remain pending. Proxy/monitoring additions are not
deployed before DNS and healthy production. No commit, push, peer review,
production approval or submission was performed by Codex.
Later on November 14, Vincent explicitly authorized Codex to make the local
preparation commit \texttt{bf28adc}; Vincent pushed it, and Codex verified the
remote branch and passing Jenkins head check. At Vincent's further request,
Codex prepared \path{delivery/BILLY-CLAUDE-DNS-HANDOFF.md} for Billy/Claude,
including the two selected A records, Namecheap instructions checked against
official documentation, current public DNS observations, verification commands
and a DNS-only boundary. The provider's default nameservers and existing
Gitea/Jenkins/Grafana A records were observed; the two new names still returned
NXDOMAIN. No DNS setting was changed, and the handoff itself grants no account
authorization. Billy must authorize DNS work in his own session.
Later that evening, Vincent directed moving the delivery agent onto the now
2\,GiB droplet because campus Wi-Fi had blocked SSH and the final presentation
must demonstrate the workflow. Codex checked repository state and host capacity,
transferred the existing tool image with matching archive SHA-256 and image ID,
stopped the laptop copy, and reused the protected node identity on The-Ocean.
It added a private WebSocket route, host-gateway SSH mapping with the existing
pinned key alias, 512/768 MiB agent and 256/384 MiB BuildKit RAM/RAM+swap caps,
half a CPU each, a guarded laptop fallback and versioned verification helpers.
The first builder setup exposed a socket-group mismatch (laptop 0, host 987);
the helper was corrected to detect the host group, and Docker access succeeded.
The first browser build request used stale session state; reloading allowed the
existing preflight job to run. Build 2 passed with real credential binding,
strict SSH verification and sudo. A separate 87-second preparation trial passed
control/app tests, source/dependency checks, capped build, full image gate and
temporary HTTP smoke. Swap increased and agent memory-limit events occurred;
no OOM kill was recorded. Existing services passed private HTTP checks, and
agent restart/reconnect passed. This does not establish full release performance.
An initial CLI artifact download returned HTTP 403; evidence was retrieved over
authorized SSH instead. A complex shell diagnostic had a quoting error and was
replaced by a versioned read-only Python check. No credential values were output.
Codex updated the diagram, current host/credential hints, runbooks, DNS handoff,
preparation evidence, history and this log, and rebuilt/reviewed the local manual.
The older PDF runner remains on the laptop; campus browser access still needs
rehearsal. Shared-host Docker administration is an explicit lab trade-off.
No firewall rule, credential scope, review requirement or production approval
was relaxed. DNS, assessed releases and recovery exercises remain pending.
No additional commit or push was authorized or performed for this migration.
\section{Actions Runner Migration for the Presentation}
Date requested: November 14, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Vincent then explicitly requested moving the first (Gitea Actions) runner to
the droplet too. Codex read the runner/workflow sources and repository rules,
checked headroom, and transferred the tested compiler image with matching
archive checksum and image ID. It stopped the idle laptop daemon before
streaming the existing registration over pinned SSH into protected Docker
storage. No registration value was printed, staged in the repository, or
replaced; the legacy name/label and repository scope were preserved.
Codex added versioned remote Compose, admission, reconnect/import and read-only
verification helpers plus a guarded laptop fallback. The first 96 MiB daemon
cap was too low: a real OOM event and restart occurred during action setup.
Codex canceled that attempt, retained its log and runtime evidence, raised
the daemon to 192/256 MiB RAM/RAM+swap with 0.25 CPU, and retried. Separate
compiler job limits remained 512/768 MiB and 0.5 CPU. Run 12 attempt 3, job 14,
passed checkout, compilation and both uploads in 4m32s. It used reviewed main
\texttt{8beefde}, not the uncommitted Assignment 8 source. After a browser
download-wait timeout and debugger detachment, Vincent supplied diagnostics
in run-12. Codex retrieved the exact PDF through read-only artifact metadata
and storage over SSH, verified its checksum against those diagnostics, and
visually checked \texttt{5.1+build.12.8beefde}. This does not demonstrate the
pending application releases or recovery exercises.
The corrected daemon had no restart during the successful run; idle restart
and declaration succeeded at 04:55:52 UTC on November 15. Codex identified
the canceled job's orphaned resources for cleanup, preserved registration and
shared services, and updated operations, migration evidence, host/credential
hints, history and this record. Both active runners are on The-Ocean; no new
cloud instance or resize was made. Resource admission does not coordinate
Jenkins, so manual builds and delivery releases must run sequentially. Shared
Docker authority remains a documented trust trade-off. Campus browser rehearsal,
DNS and assessed delivery remain pending. No further commit or push was requested.
\section{DNS, HTTPS and Team Account Check}
Date: November 15, 2026; Tool: OpenAI Codex; Human: Vincent Sun; DNS: Billy Ye.
Vincent reported that Billy had added the records but HTTPS was unavailable,
and asked for server-side correction. Codex checked repository instructions,
status, official Caddy HTTPS documentation, live DNS, proxy configuration and
container state. It verified that the prepared routes were absent and app
backends undeployed. A guarded helper first stopped on CRLF/LF comparison;
normalizing only line endings confirmed the earlier routes matched. Codex
validated the candidate, saved a protected backup and gracefully reloaded Caddy
while preserving the bind inode, prior routes, allowlists and certificate state.
Google/Cloudflare answers and normal curl/Python checks verified DNS, trusted
hostname-matching TLS and HTTP 308 redirects. HTTPS 502 was correctly recorded
as missing backend deployment, not a certificate failure or healthy release.
Existing service checks passed. No DNS account, firewall or application release
was changed; production monitoring remains pending.
Vincent also requested a team-account check for access recovery. Codex queried
only account IDs/status/role flags and Jenkins profile-header IDs, never password
hashes, tokens or email fields. The expected Billy accounts were present, and
the existing vsun1 Gitea site-admin role was confirmed and corrected in the
hints table. Grafana's vsun1 remains Viewer. No password was recovered or reset,
and no permission was changed. Codex explained the distinction between checking
an account, recovering a password-manager copy and resetting an existing login.
It updated current readiness records, the preserved DNS handoff, history and
this log, then rebuilt and visually checked the local manual. Source changes
remain uncommitted; peer review, app releases, approvals and recoveries remain pending.
\section{Delivery Gates and SSH Correction}
Date: November 15, 2026; Tool: OpenAI Codex; Human: Vincent Sun.
Vincent reported the merge complete and asked Codex to continue and finish the
assignment, then requested continuation after his usage limit reset. Codex read
the repository requirements and guide, verified PR~\#24's latest Billy review
and merged main \texttt{09731ac}, and synchronized a clean local branch
\texttt{codex/assignment8-release-evidence}. Vincent retains commits/pushes;
no additional commit or push was authorized or performed.
After the merge-triggered Actions manual build finished, Codex enabled the
reviewed pricing job and initialized a MODE choice parameter for its first
negative demonstration. The Jenkinsfile then installed its normal parameters.
Pricing builds 1 and 2 actually stopped the wrong-price and synthetic-secret
fixtures before publication/deployment. Build 3 passed normal tests and all
security gates and published/pulled a real v1 digest, but Ansible's default
PTY request conflicted with the deploy key's intentional no-PTY restriction.
Gathering Facts was unreachable with zero changes; no app or production
approval was reached. Earlier plain-SSH prerequisites had not exercised
Ansible's default terminal behavior, so they had missed this integration gap.
Codex checked the official Ansible 2.21 SSH option documentation, set the
inventory's \texttt{ansible\_ssh\_use\_tty=false}, and extended the administrator
preflight to bind the existing credentials and run \texttt{id -u} through
Ansible/become without a terminal. Preflight build 3 passed and returned 0.
The job's read-only command reports CHANGED by module default; this is not an
application deployment/idempotence result. No key restriction, host pin,
credential scope, review gate or human approval was weakened.
Codex preserved exact reports and metadata over pinned SSH, wrote dated
non-secret evidence and a focused PR description, updated this chapter/history
and the incomplete draft status, and rebuilt/reviewed the local PDF. The
source correction must be committed, reviewed and merged before a new v1 run.
Published-but-undeployed attempt records are not presented as known-good
rollback records. Successful promotions, human approvals, both recoveries and
monitoring correlation remain unexecuted.
+10 -7
View File
@@ -34,16 +34,16 @@
\definecolor{devopsLightBlue}{RGB}{232,240,247}
% Replace these values for each assignment.
\newcommand{\AssignmentTitle}{LaTeX Auto-Compilation with Gitea -- Group}
\newcommand{\AssignmentNumber}{5}
\newcommand{\DocumentVersion}{3.4}
\newcommand{\AssignmentTitle}{Secure Delivery and Rollback -- Group}
\newcommand{\AssignmentNumber}{8}
\newcommand{\DocumentVersion}{6.1}
\newcommand{\DocumentStatus}{Draft}
\newcommand{\CourseNumber}{SSW 590}
\newcommand{\CourseName}{DevOps}
\newcommand{\Authors}{Vincent Sun and Billy Ye}
\newcommand{\Organization}{Stevens Institute of Technology}
\newcommand{\DocumentDate}{10/7/2026}
\newcommand{\DueDate}{Wednesday by 11:59pm}
\newcommand{\DocumentDate}{11/15/2026}
\newcommand{\DueDate}{November 13, 2026 (team reports an extension)}
% CI writes this ignored file in its checkout; ordinary local builds stay unchanged.
\providecommand{\CIBuildSuffix}{}
\InputIfFileExists{ci-build-metadata.tex}{}{}
@@ -146,11 +146,14 @@
\include{devopsProjectProposal}
\include{devopsGitea}
\include{devopsAutomatedManualBuild}
\include{devopsJenkins}
\include{devopsSRE}
\include{devopsSecureDelivery}
\include{devopsHostsPasswords}
% Restore when a chapter cites devopsReferences.bib.
%\bibliographystyle{IEEEtran}
%\bibliography{devopsReferences}
\bibliographystyle{IEEEtran}
\bibliography{devopsReferences}
\appendix
\include{devopsDocumentGuide}
@@ -42,6 +42,9 @@ The runner requests work from the same HTTPS service and has no public
submission listener.
\section{Runner Setup}
This section preserves the October 7 setup. The November migration recorded
at the end of this chapter supersedes its laptop placement and start procedure.
The repository-scoped \gls{build-runner} \texttt{ssw590-vince-local}, version 2.3.0,
runs as Docker container \texttt{ssw590-local-runner} on Vincent's Windows
laptop using Docker Desktop's Linux engine. Its \texttt{latex-local} label
@@ -346,4 +349,45 @@ review the resulting successful workflow PDF and retain that final artifact
for submission. Pull-request review/merge and issue \#12 closure are still
pending; no approval or submission is claimed here.
\textbf{Status update, October 22, 2026:} the pending steps above have since
completed.
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/13}{PR~\#13}
was merged and issue \#12 is closed (re-checked in Gitea on October 22), and
the merged-\texttt{main} workflow run~6 passed (verified by Vincent on
October 21). The paragraph above is kept as the version 3.4 record.
\section{November 2026 Runner Migration}
On November 14 Vincent requested moving this runner to the existing 2\,GiB
The-Ocean droplet for the final demonstration. Codex stopped the laptop daemon,
transferred the same compiler image with archive checksum and image-ID checks,
and streamed the existing registration over pinned SSH directly into a protected
Docker volume. No registration value entered the repository or output. The
historical name \texttt{ssw590-vince-local} and label \texttt{latex-local} remain;
the active container is \texttt{ssw590-manual-runner}. Repository scope is unchanged.
The first 96 MiB daemon trial exceeded its memory cap during action setup and
restarted. Its attempt was canceled and retained as failure evidence. With the
daemon raised to 192 MiB RAM / 256 MiB RAM+swap and 0.25 CPU, the
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/actions/runs/12/jobs/14}{run 12 attempt 3 job}
passed checkout, compilation and both uploads in 4m32s (compilation 1m42s).
It rebuilt reviewed main commit \texttt{8beefde}, not Assignment 8's uncommitted
preparation. Diagnostics and the retrieved PDF checksum match; the opened title
shows \texttt{5.1+build.12.8beefde}. This is migration evidence, not an Assignment 8 release.
Compiler jobs have separate 512/768 MiB RAM/RAM+swap, 0.5 CPU and 256 PID
caps. No host port or job Docker socket mount is added. TLS checks remain
enabled. New-job admission pauses below 600 MiB available host RAM or 3 GiB
free disk; it does not reserve resources or coordinate Jenkins. Run manual
builds and delivery releases sequentially. The runner still has administrative
Docker authority over the shared host, so workflow editors remain trusted.
The daemon uses \texttt{unless-stopped}; idle restart/reconnect passed at
04:55:52 UTC on November 15 (the request was November 14 Eastern).
\path{gitea/droplet-runner/README.md} records operations and fallback;
\path{gitea/droplet-runner/EVIDENCE.md} links the dated evidence. The original
laptop identity/image are retained but inactive. Its helper requires
\texttt{-AllowLaptopFallback} after stopping the remote copy. VS maintains the
runner and BY the host; no new cloud instance or resize was made. Hosts and
hints-only Passwords tables reflect current placement.
\endgroup
+31 -20
View File
@@ -12,26 +12,37 @@ link each entry to the changed chapter, table, figure, or controlled artifact.
\multicolumn{4}{l}{\small\itshape Document Update History (continued)}\\
\toprule \textbf{Date / Version} & \textbf{Author Initials} & \textbf{Change} & \textbf{Changed At}\\ \midrule
\endhead \bottomrule \endlastfoot
October 7, 2026 / 3.4 & VS, Codex & Added the successful run-4 repair screenshots and verified its commit, PDF version, artifact contents, and SHA-256; completed the failure/repair evidence. Replaced the abstract's template instructions with an Assignment 5 summary. Hosts and Passwords tables are unchanged from 3.3; final workflow PDF review and submission remain pending. & Title and abstract, \ChapterRef{AutomatedManualBuild}, \ChapterRef{AIPromptLog}\\
October 7, 2026 / 3.3 & VS, Codex & Recorded successful run 2 and intentional failure run 3 with screenshots and downloaded diagnostic verification; removed the test error for a repair push. Updated both the Hosts section and hints-only Passwords table for the local runner; passing repair evidence and final artifact review remain pending. & \ChapterRef{AutomatedManualBuild}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
October 7, 2026 / 3.2 & VS, Codex & Set the Assignment 5 title, number, and date after successful Gitea run 1; retained its original PDF and evidence. The new title omits the duplicate LMS suffix. Added the draft Automated Manual Build chapter with the workflow and first-PDF screenshots. Hosts and Passwords tables are unchanged; remaining workflow tests and runner records are pending. & Title page, \ChapterRef{AutomatedManualBuild}, \ChapterRef{AIPromptLog}\\
October 7, 2026 / preparation & VS, Codex & Prepared the Assignment 5 local runner, compiler image, and push workflow; verified local compilation, failure/repair, and revision checks. Corrected Windows glossary/index regeneration after layout settles. Real workflow artifacts and the assignment chapter remain pending. Document version, Hosts table, and Passwords table are unchanged. & \ChapterRef{AIPromptLog}\\
September 29, 2026 / 3.1 & BY, Claude & Restored the Assignment 3 Color Buttons site at \texttt{colors.yebilly.me} behind the same Caddy proxy (no published port, 96\,MiB memory cap, graceful reload without restarting Gitea); versioned the change through reviewed PR~\#11 (closes issue~\#10); updated the Caddyfile excerpt and verification note, and \textbf{updated the Hosts table} with the new hostname, URL, and private service. The Passwords table is unchanged. & \ChapterRef{GiteaFoundation}, \ChapterRef{HostsPasswords}\\
September 28, 2026 / 3.0 & BY, VS, Claude & Assignment 4: deployed pinned Gitea 1.27.3 with SQLite behind Caddy and Let's Encrypt at \texttt{git.yebilly.me} (Student Pack domain), applied the \texttt{gitea-fw} Cloud Firewall, and recorded DNS, persistence, certificate-renewal, external-exposure, and issue-to-merge evidence; \textbf{created the Hosts table and the Passwords (hints-only) table}; added TLS, SSH, and ACME glossary terms and set the Assignment 4 title page. & \ChapterRef{GiteaFoundation}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.6 & VS, Codex & Kept each proposed SWOT table with its tool heading and removed the forced page break that separated the comparison charts. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.5 & VS, Codex & Clarified that AdGuard Home and Pi-hole can be compared through direct Ubuntu installation or containers; made Docker Compose optional and aligned the deployment workflow and SWOT wording. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.4 & VS, Codex & Removed the provisional TikZ dashboard figure and marked the dashboard approach as subject to change after the group consults the professor; retained the proposed operational checks. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.3 & VS, Codex & Simplified the proposed operations dashboard around DigitalOcean Insights and planned VPN stability-under-load and DNS ad-block tests; updated the TikZ mockup to distinguish host graphs from service-check results. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.2 & VS, Codex & Added a TikZ mockup of the proposed operational dashboard, with placeholder values and planned comparison filters; clarified that live measurements and a running dashboard remain future project work. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.1 & VS, Codex & Added second-device LaTeX Docker evidence: a versioned one-go PowerShell helper, the successful build/run screenshot, a folder listing, and the opened PDF; documented retained logs and distinct run values. & \ChapterRef{LaTeXDocker}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.0 & VS, Codex & Drafted the Project Proposal for a resource-constrained personal VPN and DNS gateway, including proposed tools, comparison tests, dashboard, security plan, feasibility limits, and four provisional SWOT charts; updated the glossary and rebuilt the report. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 1.9 & BY, Claude & Added the LaTeX Docker chapter (Assignment 3, Task 4): a Debian TeX Live Dockerfile, a sample document, and the local build and compile evidence; removed title-page placeholder brackets and corrected the due date. & \ChapterRef{LaTeXDocker}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 1.8 & BY, Claude & Added the Digital Ocean Docker Deployment chapter (Assignment 3, Tasks 1--3) with screenshots, converted Assignment 2 terminal output to framed \texttt{Verbatim} blocks, set the Assignment 3 title-page values, and added the \texttt{minted}/TikZ packages and \texttt{-shell-escape} build flag they require. & \ChapterRef{DigitalOceanDockerDeployment}, \ChapterRef{AIAgentGuide}, \ChapterRef{AIPromptLog}\\
September 20, 2026 / 1.7 & VS, Codex & Clarified that the Projects folder layout is optional, distinguished user-terminal compiler operation from AI sandbox access, and documented explicit TinyTeX path and short-path workarounds while retaining MiKTeX only as an existing fallback. & \ChapterRef{AIAgentGuide}, \ChapterRef{DocumentGuide}, \ChapterRef{AIPromptLog}\\
September 19, 2026 / 1.6 & VS, Codex & Relocated the shared TinyTeX toolchain, documented per-user TinyTeX setup, and automated complete local compilation including bibliography, glossary, acronym, and index passes. & \ChapterRef{AIAgentGuide}\\
September 19, 2026 / 1.5 & VS, Codex & Established the Group 1 repository structure, preserved the original instructor template as a separate reference snapshot, and added the AI Agent Requirements appendix and repository routing files. & \ChapterRef{AIAgentRequirements}, \ChapterRef{AIAgentGuide}, \ChapterRef{AIPromptLog}\\
September 15, 2026 / 1.4 & VS, Codex & Completed Sections C, F, G, H, I, and J (Questions 13--16 and 24--40), including verified Linux-environment evidence, explanations, compilation, visual review, and the corresponding AI prompt-log records. & \ChapterRef{LinuxCommands}, \ChapterRef{AIPromptLog}\\
September 15, 2026 / 1.3 & BY, Claude & Completed Sections A, B, D, and E (Questions 1--12 and 17--23), including environment-setup evidence, explanations, and LaTeX formatting, with the corresponding Claude assistance record retained as written. & \ChapterRef{LinuxCommands}, \ChapterRef{AIPromptLog}\\
November 15, 2026 / 6.1 & VS, CDX & Verified Billy's latest review and Vincent's merge of PR~\#24; enabled delivery and recorded real blocked-test/secret runs and the first scanned, published v1 image. Preserved the staging SSH failure before any app change. Set Ansible to avoid PTY allocation and verified its credential-bound connection/sudo path in preflight build 3; the correction awaits review/merge before a release retry. Updated current evidence and retained the incomplete-submission status. Hosts and Passwords tables are unchanged: no service, account, credential or permission was added. & \ChapterRef{SecureDelivery}, \ChapterRef{AIPromptLog}\\
November 15, 2026 / 6.0 DNS and TLS readiness & BY, VS, CDX & Billy added staging/app DNS. Codex validated and gracefully applied the prepared Caddy routes, preserving prior services and storage; verified public DNS, trusted TLS and HTTP redirects. Recorded expected 502 responses while app backends remain undeployed. Updated current DNS/HTTPS inventory and the verified vsun1 Gitea administrator role. No passwords, permissions or releases changed. & \ChapterRef{SecureDelivery}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
November 14, 2026 / 6.0 Actions runner migration & VS, CDX & Moved the existing manual runner and compiler image to The-Ocean without re-registration. Corrected an initial low-memory failure, verified reviewed-main run 12 attempt 3, artifact checksum/title and idle restart. Added daemon/job caps, admission checks and fallback guards; updated current host/credential hints and retained October evidence. Both active runners now use the droplet. & \ChapterRef{AutomatedManualBuild}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
November 14, 2026 / 6.0 agent migration & VS, CDX & At Vincent's direction, moved the trusted delivery agent to the existing 2\,GiB droplet to remove campus SSH dependence. Added agent and builder resource caps, private deployment routing with pinned host verification, restart/fallback procedures, preflight build 2 and a passing bounded build/scan/smoke trial. Documented shared-host Docker authority, swap use and the unchanged laptop PDF runner. Updated the architecture, Hosts and hints-only Passwords tables, handoff and AI log; assessed releases and campus browser rehearsal remain pending. & \ChapterRef{SecureDelivery}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
November 14, 2026 / 6.0 preparation & VS, CDX & Prepared Assignment 8 with instructor v1 source, exact dependencies/base digest, trusted laptop Jenkins agent, security gates, Ansible, restricted production approval and recovery automation. Recorded actual local checks and passing agent prerequisite build 1. Vincent resized the droplet to 2\,GiB and updated packages; Codex configured deployment access, folder-scoped credentials and a disabled release job after backups. Added planned proxy/monitoring changes, architecture and runbooks. Updated Hosts and hints-only Passwords tables. Reviewed release commits, DNS/TLS, v1/v2 promotion, both recoveries and final evidence remain pending; this is a preparation draft. & \ChapterRef{SecureDelivery}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
October 28, 2026 / 5.1 & VS, CDX & Reviewed run-11 against instructor Chapter 5; added Vincent's external IPv4/IPv6 TCP retest (18 expected outcomes), pinned deployment links to the reviewed merge, recorded final PR approval and CI/build results, and qualified timing, sampling, and memory-pressure conclusions. Documented local TinyTeX builds to one ignored PDF. Hosts and Passwords tables are unchanged because no deployed service, account, or credential changed. & \ChapterRef{SREMonitoring}, \ChapterRef{AIPromptLog}\\
October 28, 2026 / 5.0 & BY, CD & Assignment 7: added \ChapterRef{SREMonitoring}. Deployed Prometheus, Grafana OSS, Node Exporter, and Blackbox Exporter on The-Ocean (pinned by digest, memory-capped, no host ports) after a capacity trial on the 1\,GiB plan; disabled four unused host services and added a second swap file; added \texttt{metrics.yebilly.me} behind the Jenkins allowlist and a private probe network. Recorded the dashboard, normal-build comparison, SLI/SLO worked example and measured window, contact-point, capacity-alert, collection-health, and Jenkins-outage tests with Discord notifications, restart persistence, blameless review, and improvement issues \#20 and \#21. After an independent review of the draft: added the collection-health rule and its test, replaced the initial Grafana administrator password, ran Blackbox Exporter as non-root, and added runbooks, network and storage detail in the diagram, host CPU checks, a targets table, citations with a Bibliography, and four corrected figures. \textbf{Updated the Hosts table} (monitoring containers, ports, volumes, \texttt{metrics} DNS, swap, monitoring and backup status) and \textbf{the Passwords table} (Grafana accounts, monitoring secrets file, Discord webhook). Set the Assignment 7 title page and abstract; added glossary terms. & Title and abstract, \ChapterRef{SREMonitoring}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
October 23, 2026 / 4.2 & VS, CDX & Corrected the Jenkins lockfile link to the recorded 63-plugin revision; clarified clean reproduction, Jenkins revision selection, and the unconfirmed webhook-timeout cause. Scoped the existing update-check result to the 63 checked plugins. Theme plugins are unchanged at Vincent's direction. Hosts and Passwords tables are unchanged because no service, account, or credential changed. & \ChapterRef{JenkinsCI}, \ChapterRef{AIPromptLog}\\
October 23, 2026 / 4.1 & BY, CD & Corrected the Jenkins instructor access path to the Stevens campus network, with off-campus graders' addresses added on request; recorded the GlobalProtect test showing the Stevens VPN is split-tunnel and therefore not an access path, and Vincent's passing campus test on \texttt{Stevens-Net}; added the real webhook delivery table and diagnosis of one timed-out delivery, UML stereotypes on the deployment diagram, the stored Jenkins URL, free disk space, reconciled plugin counts, and corrected wording on push rights, resource limits, and corrective actions. Shortened AI initials in this table (CDX for Codex, CD for Claude). Hosts and Passwords tables are unchanged. & \ChapterRef{JenkinsCI}, \ChapterRef{AIPromptLog}\\
October 22--23, 2026 / 4.0 & BY, VS, CD & Assignment 6: ran the guarded Jenkins capacity test on the resized 1\,GiB droplet; deployed Jenkins 2.580.1 LTS with a hashed plugin lockfile behind Caddy at \texttt{ci.yebilly.me} (Stevens and team allowlist); integrated Gitea via a private webhook and the \texttt{jenkins-bot} identity; required check \texttt{vpn-dns-gateway/pipeline/pr-main} on \texttt{main}; recorded PR~\#15's pass, blocked failure, repair, review, and merge, the restart-persistence and IPv4/IPv6 exposure tests, and the plugin-update check. \textbf{Updated the Hosts table} (resize, Jenkins, \texttt{ci} DNS, Color Buttons retired) and \textbf{the Passwords table} (Jenkins administrators, \texttt{jenkins-bot} account and token, CI allowlist file). Added glossary terms, set the Assignment 6 title page and abstract, and noted the completed Assignment 5 merge. & Title and abstract, \ChapterRef{JenkinsCI}, \ChapterRef{HostsPasswords}, \ChapterRef{AutomatedManualBuild}, \ChapterRef{AIPromptLog}\\
October 21, 2026 / preparation & VS, CDX & Recorded core-test timing qualification and the Billy/Claude handoff; prepared the plugin/pipeline test and verified it locally after separating plugin resolution from runtime. The droplet run remains unverified. Hosts and Passwords tables are unchanged because no persistent Jenkins service or real integration credential was added. & \ChapterRef{AIPromptLog}\\
October 7, 2026 / 3.4 & VS, CDX & Added the successful run-4 repair screenshots and verified its commit, PDF version, artifact contents, and SHA-256; completed the failure/repair evidence. Replaced the abstract's template instructions with an Assignment 5 summary. Hosts and Passwords tables are unchanged from 3.3; final workflow PDF review and submission remain pending. & Title and abstract, \ChapterRef{AutomatedManualBuild}, \ChapterRef{AIPromptLog}\\
October 7, 2026 / 3.3 & VS, CDX & Recorded successful run 2 and intentional failure run 3 with screenshots and downloaded diagnostic verification; removed the test error for a repair push. Updated both the Hosts section and hints-only Passwords table for the local runner; passing repair evidence and final artifact review remain pending. & \ChapterRef{AutomatedManualBuild}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
October 7, 2026 / 3.2 & VS, CDX & Set the Assignment 5 title, number, and date after successful Gitea run 1; retained its original PDF and evidence. The new title omits the duplicate LMS suffix. Added the draft Automated Manual Build chapter with the workflow and first-PDF screenshots. Hosts and Passwords tables are unchanged; remaining workflow tests and runner records are pending. & Title page, \ChapterRef{AutomatedManualBuild}, \ChapterRef{AIPromptLog}\\
October 7, 2026 / preparation & VS, CDX & Prepared the Assignment 5 local runner, compiler image, and push workflow; verified local compilation, failure/repair, and revision checks. Corrected Windows glossary/index regeneration after layout settles. Real workflow artifacts and the assignment chapter remain pending. Document version, Hosts table, and Passwords table are unchanged. & \ChapterRef{AIPromptLog}\\
September 29, 2026 / 3.1 & BY, CD & Restored the Assignment 3 Color Buttons site at \texttt{colors.yebilly.me} behind the same Caddy proxy (no published port, 96\,MiB memory cap, graceful reload without restarting Gitea); versioned the change through reviewed PR~\#11 (closes issue~\#10); updated the Caddyfile excerpt and verification note, and \textbf{updated the Hosts table} with the new hostname, URL, and private service. The Passwords table is unchanged. & \ChapterRef{GiteaFoundation}, \ChapterRef{HostsPasswords}\\
September 28, 2026 / 3.0 & BY, VS, CD & Assignment 4: deployed pinned Gitea 1.27.3 with SQLite behind Caddy and Let's Encrypt at \texttt{git.yebilly.me} (Student Pack domain), applied the \texttt{gitea-fw} Cloud Firewall, and recorded DNS, persistence, certificate-renewal, external-exposure, and issue-to-merge evidence; \textbf{created the Hosts table and the Passwords (hints-only) table}; added TLS, SSH, and ACME glossary terms and set the Assignment 4 title page. & \ChapterRef{GiteaFoundation}, \ChapterRef{HostsPasswords}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.6 & VS, CDX & Kept each proposed SWOT table with its tool heading and removed the forced page break that separated the comparison charts. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.5 & VS, CDX & Clarified that AdGuard Home and Pi-hole can be compared through direct Ubuntu installation or containers; made Docker Compose optional and aligned the deployment workflow and SWOT wording. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.4 & VS, CDX & Removed the provisional TikZ dashboard figure and marked the dashboard approach as subject to change after the group consults the professor; retained the proposed operational checks. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.3 & VS, CDX & Simplified the proposed operations dashboard around DigitalOcean Insights and planned VPN stability-under-load and DNS ad-block tests; updated the TikZ mockup to distinguish host graphs from service-check results. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.2 & VS, CDX & Added a TikZ mockup of the proposed operational dashboard, with placeholder values and planned comparison filters; clarified that live measurements and a running dashboard remain future project work. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.1 & VS, CDX & Added second-device LaTeX Docker evidence: a versioned one-go PowerShell helper, the successful build/run screenshot, a folder listing, and the opened PDF; documented retained logs and distinct run values. & \ChapterRef{LaTeXDocker}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 2.0 & VS, CDX & Drafted the Project Proposal for a resource-constrained personal VPN and DNS gateway, including proposed tools, comparison tests, dashboard, security plan, feasibility limits, and four provisional SWOT charts; updated the glossary and rebuilt the report. & \ChapterRef{ProjectProposal}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 1.9 & BY, CD & Added the LaTeX Docker chapter (Assignment 3, Task 4): a Debian TeX Live Dockerfile, a sample document, and the local build and compile evidence; removed title-page placeholder brackets and corrected the due date. & \ChapterRef{LaTeXDocker}, \ChapterRef{AIPromptLog}\\
September 24, 2026 / 1.8 & BY, CD & Added the Digital Ocean Docker Deployment chapter (Assignment 3, Tasks 1--3) with screenshots, converted Assignment 2 terminal output to framed \texttt{Verbatim} blocks, set the Assignment 3 title-page values, and added the \texttt{minted}/TikZ packages and \texttt{-shell-escape} build flag they require. & \ChapterRef{DigitalOceanDockerDeployment}, \ChapterRef{AIAgentGuide}, \ChapterRef{AIPromptLog}\\
September 20, 2026 / 1.7 & VS, CDX & Clarified that the Projects folder layout is optional, distinguished user-terminal compiler operation from AI sandbox access, and documented explicit TinyTeX path and short-path workarounds while retaining MiKTeX only as an existing fallback. & \ChapterRef{AIAgentGuide}, \ChapterRef{DocumentGuide}, \ChapterRef{AIPromptLog}\\
September 19, 2026 / 1.6 & VS, CDX & Relocated the shared TinyTeX toolchain, documented per-user TinyTeX setup, and automated complete local compilation including bibliography, glossary, acronym, and index passes. & \ChapterRef{AIAgentGuide}\\
September 19, 2026 / 1.5 & VS, CDX & Established the Group 1 repository structure, preserved the original instructor template as a separate reference snapshot, and added the AI Agent Requirements appendix and repository routing files. & \ChapterRef{AIAgentRequirements}, \ChapterRef{AIAgentGuide}, \ChapterRef{AIPromptLog}\\
September 15, 2026 / 1.4 & VS, CDX & Completed Sections C, F, G, H, I, and J (Questions 13--16 and 24--40), including verified Linux-environment evidence, explanations, compilation, visual review, and the corresponding AI prompt-log records. & \ChapterRef{LinuxCommands}, \ChapterRef{AIPromptLog}\\
September 15, 2026 / 1.3 & BY, CD & Completed Sections A, B, D, and E (Questions 1--12 and 17--23), including environment-setup evidence, explanations, and LaTeX formatting, with the corresponding Claude assistance record retained as written. & \ChapterRef{LinuxCommands}, \ChapterRef{AIPromptLog}\\
September 2, 2026 / 1.2 & DDM, CDX & Added macOS MacTeX and Windows MiKTeX installation, verification, compilation, cleanup, and troubleshooting instructions to the Document Authoring Guide appendix. & \ChapterRef{DocumentGuide}\\
September 2, 2026 / 1.1 & DDM, CDX & Reorganized the example assignment as one chapter with activity, workflow, evidence, retrospective, and submission sections so each homework can follow the same chapter pattern. & Omitted chapter\\
September 2, 2026 / 1.0 & DDM, CDX & Created the reusable SSW 590 DevOps assignment template from the architecture template infrastructure; replaced requirements and design chapters with activity, workflow, evidence, retrospective, and submission chapters. & Omitted chapters, \ChapterRef{AIAgentGuide}\\
+16
View File
@@ -3,6 +3,9 @@
\newacronym{cd}{CD}{continuous delivery or continuous deployment}
\newacronym{iac}{IaC}{infrastructure as code}
\newacronym{slo}{SLO}{service-level objective}
\newacronym{sli}{SLI}{service-level indicator}
\newacronym{sla}{SLA}{service-level agreement}
\newacronym{sre}{SRE}{site reliability engineering}
\newacronym{vpn}{VPN}{virtual private network}
\newacronym{dns}{DNS}{Domain Name System}
\newacronym{swot}{SWOT}{strengths, weaknesses, opportunities, and threats}
@@ -23,3 +26,16 @@
\newglossaryentry{build-runner}{name={build runner},description={A registered worker that receives workflow jobs and executes them in its configured environment}}
\newglossaryentry{build-artifact}{name={build artifact},description={A file retained by a workflow run for download, such as a compiled PDF or diagnostic log; retention may be limited}}
\newglossaryentry{webhook}{name={webhook},description={An HTTP request that one service sends automatically to another when an event occurs, such as Gitea notifying Jenkins of a push or pull-request update}}
\newglossaryentry{status-check}{name={status check},description={A named pass/fail result that a CI system attaches to a commit through the Git server's commit-status API; Gitea shows it on pull requests}}
\newglossaryentry{branch-protection}{name={branch protection},description={Repository rules on a branch, such as disallowing direct pushes and requiring status checks and approvals before a pull request can merge}}
\newglossaryentry{jenkinsfile}{name={Jenkinsfile},description={A version-controlled file at the repository root that defines a Jenkins pipeline's stages and steps}}
\newglossaryentry{controller}{name={controller},description={The central Jenkins server that serves the web interface, stores configuration, and schedules builds; it can also run builds on its own executors}}
\newglossaryentry{build-agent}{name={build agent},description={A separate machine or container that connects to a Jenkins controller and runs builds, isolating build code from the controller}}
\newglossaryentry{error-budget}{name={error budget},description={The amount of failure an SLO still allows in its window; for a 99\% target over 2,880 probes, 28.8 failed probes}}
\newglossaryentry{exporter}{name={exporter},description={A small service that exposes measurements of another system, such as a host or a probed website, in Prometheus format for scraping}}
\newglossaryentry{scrape}{name={scrape},description={Prometheus's periodic HTTP request to a target's metrics endpoint, which records each returned value with a timestamp}}
\newglossaryentry{contact-point}{name={contact point},description={A Grafana alerting destination, such as a Discord channel, that receives firing and resolved notifications}}
\newglossaryentry{blameless-review}{name={blameless review},description={An incident review that records impact, timeline, cause, and improvements without assigning personal blame}}
+119 -28
View File
@@ -10,53 +10,118 @@ password, token, recovery code, or private key. Distinct services use distinct
credentials, which are stored outside this manual and outside every
repository. Both tables were created on 28 September 2026 for Assignment 4
(\ChapterRef{GiteaFoundation}). The local runner host and its identity hint
were added on October 7, 2026 for \ChapterRef{AutomatedManualBuild}.
were added on October 7, 2026 for \ChapterRef{AutomatedManualBuild}. On
October 22--23, 2026 (\ChapterRef{JenkinsCI}) the droplet record was updated
for the 1\,GiB resize, the Jenkins service, and \texttt{ci.yebilly.me}; the
Color Buttons app was marked retired; and the Passwords table gained the
Jenkins administrators, the \texttt{jenkins-bot} Gitea account, and its token.
On October 28, 2026 (\ChapterRef{SREMonitoring}) the droplet record gained
the four monitoring containers, \texttt{metrics.yebilly.me}, the second swap
file, and real monitoring status; the Passwords table gained the Grafana
accounts, the monitoring secrets file, and the Discord webhook.
On November 14, 2026 (\ChapterRef{SecureDelivery}), Vincent resized the droplet
to 2\,GiB and updated host packages. The tables gained deployment access and a
trusted Jenkins agent. Later that evening the agent moved from the laptop to
The-Ocean to avoid campus SSH restrictions. Vincent then requested migrating
the original Actions runner too; both laptop daemons are now stopped, with
their protected fallback state retained. On November 15 Billy added the pricing
DNS records and Codex enabled Caddy HTTPS; certificates and redirects passed,
while the undeployed application backends return 502.
\section{Hosts}
\small
\begin{tabularx}{\linewidth}{@{}L{3.3cm}Y@{}}
\caption{Hosts\label{Table:Hosts}}\\
\toprule \textbf{Field} & \textbf{Droplet The-Ocean (git.yebilly.me, colors.yebilly.me)}\\ \midrule
\toprule \textbf{Field} & \textbf{Droplet The-Ocean (git, ci, metrics .yebilly.me)}\\ \midrule
\endfirsthead
\toprule \textbf{Field} & \textbf{Droplet The-Ocean (git.yebilly.me, colors.yebilly.me)}\\ \midrule
\toprule \textbf{Field} & \textbf{Droplet The-Ocean (git, ci, metrics .yebilly.me)}\\ \midrule
\endhead
\bottomrule \endlastfoot
Role & Gitea work hub (Gitea 1.27.3 behind Caddy 2.11.4 TLS proxy); since
29 Sep 2026 also the Assignment 3 Color Buttons site\\
22 Oct 2026 also the Jenkins 2.580.1 LTS controller, which runs the CI builds;
since 28 Oct 2026 also the monitoring stack (Prometheus 3.15.1, Grafana OSS
13.2.5, Node Exporter 1.12.1, Blackbox Exporter 0.29.1). The Assignment 3 Color Buttons app (29 Sep 2026) is retired: container
stopped with restart policy \texttt{no}; its Caddy route remains\\
Delivery agent & Legacy node \texttt{ssw590-vince-delivery}, label
\texttt{delivery-trusted}, one exclusive executor; image
\texttt{ssw590-delivery-agent:20261114}. RAM / RAM+swap: 512 / 768 MiB,
0.5 CPU; separate pinned BuildKit: 256 / 384 MiB, 0.5 CPU.
Private WebSocket to Jenkins and SSH through Docker host gateway with pinned
public-IP host-key alias. Docker socket control grants host administration.
Named identity/workspace and BuildKit cache volumes stay outside Git;
configuration under \path{/opt/ssw590-delivery-agent/}; restart unless stopped.
Prerequisite build 2 and bounded build/scan/smoke trial passed; campus browser
rehearsal and assessed delivery remain pending.\\
Environment & Course production (team use)\\
Provider & DigitalOcean, NYC1; Ubuntu 24.04 LTS; 1 vCPU, 512\,MB RAM, 10\,GB disk\\
Provider & DigitalOcean, NYC1; Ubuntu 24.04 LTS; 1 vCPU; resized from
512\,MB to 1\,GiB in October, then to 2\,GiB on November 14, 2026
(1,967\,MiB reported, original 25\,GB plan disk retained); swap files \texttt{/swapfile} and \texttt{/swapfile2}, 1\,GiB
each (second added 28 Oct 2026); \texttt{multipathd}, \texttt{fwupd},
\texttt{udisks2}, and \texttt{ModemManager} disabled and masked\\
Public address / DNS & IPv4 \texttt{147.182.178.136}; \texttt{A} records
\texttt{git.yebilly.me} and \texttt{colors.yebilly.me}; public IPv6 assigned
but not published in DNS\\
Private services & Gitea \texttt{:3000} and \texttt{color-buttons-app}
\texttt{:3000} (96\,MiB memory cap) on Docker network \texttt{gitea\_web}, no
host ports; SQLite file in volume \texttt{gitea\_gitea-data}\\
\texttt{git}, \texttt{ci}, \texttt{metrics}, \texttt{colors}, \texttt{staging}
and \texttt{app} \texttt{.yebilly.me}; public
IPv6 \texttt{2604:a880:400:d1:0:5:22d:6001} assigned but not published in DNS\\
Private services & Gitea \texttt{:3000} and Jenkins \texttt{:8080} (512\,MiB
RAM, 0.75 CPU cap; agent port disabled) on Docker network \texttt{gitea\_web},
no host ports; SQLite file in volume \texttt{gitea\_gitea-data}; Jenkins state
in volume \texttt{gitea\_jenkins-home}. Monitoring (Compose project
\texttt{monitoring}, no host ports): Prometheus \texttt{:9090} (128\,MiB),
Node Exporter \texttt{:9100} and Blackbox Exporter \texttt{:9115} (32\,MiB
each; Blackbox runs as \texttt{nobody}) on network \texttt{monitoring\_monitoring}; Grafana \texttt{:3000}
(192\,MiB) also on \texttt{gitea\_web}; Blackbox at \texttt{172.30.90.10} on
\texttt{gitea\_probe} (172.30.90.0/28); volumes
\texttt{monitoring\_prometheus\_data} (7\,d / 500\,MB) and
\texttt{monitoring\_grafana\_data}\\
Exposed ports & 443/TCP and 80/TCP to all; 22/TCP to approved team addresses only
(Cloud Firewall \texttt{gitea-fw})\\
(Cloud Firewall \texttt{gitea-fw}); \texttt{ci.yebilly.me} and
\texttt{metrics.yebilly.me} answer only Stevens 155.246.0.0/16 and team
addresses (Caddy allowlist; \texttt{ci} also the probe address), 403
otherwise; monitoring ports 9090, 9100, 9115 not reachable\\
Owner & BY (server administration); VS (review)\\
HTTPS URLs & \url{https://git.yebilly.me}, \url{https://colors.yebilly.me}\\
Backup status & No backup job; container-replacement persistence verified only
(\ChapterRef{GiteaFoundation})\\
Monitoring status & No alerting configured; checked manually with
\texttt{docker compose ps}, \texttt{docker stats}, and logs\\
HTTPS URLs & \url{https://git.yebilly.me}, \url{https://ci.yebilly.me/login},
\url{https://metrics.yebilly.me/login}; \url{https://staging.yebilly.me} and
\url{https://app.yebilly.me} have trusted certificates but return 502 until
application deployment\\
Backup status & No scheduled backup job; manual Gitea SQLite and Jenkins-home
backups saved in a protected root directory before the November 14 delivery
bootstrap. Container-replacement persistence verified for
Gitea (\ChapterRef{GiteaFoundation}), restart persistence for Jenkins
(\ChapterRef{JenkinsCI}) and for Prometheus and Grafana
(\ChapterRef{SREMonitoring}); manual volume backup procedure in
\texttt{monitoring/README.md}\\
Monitoring status & Prometheus and Grafana: host CPU, memory, root disk, and
HTTPS probes of Gitea and Jenkins every 30\,s; alerts \emph{HTTPS service
down}, \emph{Root disk space low}, and \emph{Monitoring target down} to Discord \texttt{\#devops-alerts}.
Shares the droplet's failure domain; no external check yet (issue~\#20)\\
\end{tabularx}
\normalsize
\small
\begin{tabularx}{\linewidth}{@{}L{3.3cm}Y@{}}
\caption{Local build runner host, added October 7, 2026\label{Table:HostsRunner}}\\
\toprule \textbf{Field} & \textbf{Vincent's laptop (\texttt{ssw590-vince-local})}\\ \midrule
\caption{Actions runner, added October 7 and migrated November 14, 2026\label{Table:HostsRunner}}\\
\toprule \textbf{Field} & \textbf{Actions runner on The-Ocean}\\ \midrule
\endfirsthead
\toprule \textbf{Field} & \textbf{Vincent's laptop (\texttt{ssw590-vince-local})}\\ \midrule
\toprule \textbf{Field} & \textbf{Actions runner on The-Ocean}\\ \midrule
\endhead
\bottomrule \endlastfoot
Role & Repository-scoped Gitea Actions runner; manual compilation in temporary Docker job containers\\
Environment & Windows laptop, Docker Desktop Linux engine; runner 2.3.0; capacity one job\\
Provider / owner & Local device; VS maintains Docker Desktop, runner availability, and job image\\
Role & Repository-scoped Gitea Actions runner; temporary manual compiler containers;
historical registration name \texttt{ssw590-vince-local} retained\\
Environment & Docker on The-Ocean's Ubuntu 24.04 host; runner 2.3.0;
capacity one job; current container \texttt{ssw590-manual-runner}\\
Provider / owner & Existing DigitalOcean host; VS maintains runner and image;
BY retains server administration; no new instance or resize\\
Network path & Outbound HTTPS to \texttt{git.yebilly.me:443} and GitHub Actions sources; Caddy forwards to private Gitea \texttt{:3000}; no public runner or Docker daemon port\\
Execution label & \texttt{latex-local}; local image \texttt{ssw590-manual-ci:20261007}\\
Persistent state & Runner registration in named Docker volume \texttt{ssw590-local-runner-data}; compiler image retained in Docker Desktop\\
Availability & Start Docker Desktop and the versioned runner helper after reboot; laptop must remain awake for jobs\\
Persistent state & Registration in Droplet volume \texttt{ssw590-local-runner-data},
mode 0600; same tested compiler image on the host. Stopped laptop copy retains
its original image and volume outside Git\\
Availability / limits & Restart unless stopped; daemon 192/256 MiB RAM/RAM+swap,
0.25 CPU; compiler job 512/768 MiB, 0.5 CPU. New jobs pause below 600 MiB
available host RAM or 3 GiB free disk. Run manual and delivery work sequentially\\
Laptop fallback & Both original daemons are stopped. Their helpers require
\texttt{-AllowLaptopFallback} after stopping the corresponding remote copy;
never run two copies of either identity. No active runner requires Docker Desktop\\
Monitoring / backup & Runner logs and Gitea Actions checked manually; no automatic backup of runner registration configured\\
\end{tabularx}
\normalsize
@@ -71,9 +136,33 @@ Monitoring / backup & Runner logs and Gitea Actions checked manually; no automat
\toprule \textbf{Service / account} & \textbf{Owner} & \textbf{Where it is kept (hint)} & \textbf{Privilege}\\ \midrule
\endhead
\bottomrule \endlastfoot
Gitea local runner identity & VS & Docker volume \texttt{ssw590-local-runner-data}, file \texttt{/data/.runner}; generated identity, no values in Git; registration token supplied privately from repository settings & Repository runner; Docker control on VS laptop\\
Gitea Actions runner identity & VS & Droplet Docker volume \texttt{ssw590-local-runner-data},
file \texttt{/data/.runner}, mode 0600; transferred over pinned SSH, no values in Git;
stopped laptop fallback retains its copy & Repository runner; Droplet Docker control\\
Jenkins delivery agent identity & VS & Protected Jenkins-generated identity and Droplet Docker volume
\texttt{ssw590-delivery-identity}; stopped laptop fallback retains its copy; outside Git & Trusted Droplet agent; host Docker control\\
Deployment SSH key & VS & Jenkins folder \texttt{secure-delivery}, credential
\texttt{delivery-deploy-ssh}; encrypted in Jenkins home & \texttt{deploy} SSH;
passwordless root sudo for Ansible\\
Pinned deployment host key & VS & Same folder, file credential
\texttt{delivery-known-hosts}; public key verified over existing pinned SSH &
Strict host verification\\
Package-write token & VS & Same folder, credential \texttt{delivery-registry-write};
distinct named token under Gitea \texttt{vsun1}; no value in report & Package write only\\
Package-read token & VS & Root Docker login configuration on The-Ocean;
distinct named token under Gitea \texttt{vsun1}; bootstrap metadata retains name & Package read only\\
Gitea \texttt{bill} & BY & BY's password manager & Site administrator\\
Gitea \texttt{vsun1} & VS & VS's password manager & Repository administrator\\
Gitea \texttt{vsun1} & VS & VS's password manager & Site administrator (verified November 15)\\
Gitea \texttt{jenkins-bot} (added 22 Oct 2026) & BY & BY's password manager; used only to create its token & Write collaborator on \texttt{vpn-dns-gateway}\\
\texttt{jenkins-bot} token \texttt{jenkins-ci} & BY & Jenkins credential ID \texttt{gitea-jenkins-bot} (System, Global), encrypted in volume \texttt{gitea\_jenkins-home}; revoke under the bot's Gitea Applications settings & Repository read/write; organization and user read\\
Jenkins \texttt{billy} & BY & BY's password manager & Administer (all)\\
Jenkins \texttt{vsun1} & VS & VS's password manager & Administer (all)\\
Jenkins initial admin password & --- & One-time setup secret in \texttt{/var/jenkins\_home/secrets/}; read once by BY, superseded by named accounts & Setup only\\
Grafana \texttt{billy} (added 28 Oct 2026) & BY & BY's password manager; the initial value set through the monitoring secrets file was replaced in Grafana on 28 Oct 2026 and removed from the file & Grafana Admin\\
Grafana \texttt{vsun1} (added 28 Oct 2026) & VS & VS's password manager; temporary password set by BY and sent privately, to be changed by VS at first login & Viewer\\
Monitoring secrets \texttt{.env.secret} & BY & \texttt{\textasciitilde/monitoring/.env.secret} on the droplet, mode 600, root; typed by BY; holds the Discord webhook URL (the initial Grafana admin password was removed after it was replaced); never in Git & n/a\\
Discord webhook \texttt{Grafana} & BY & BY's password manager and the monitoring secrets file; revoke under \texttt{\#devops-alerts} $\rightarrow$ Integrations $\rightarrow$ Webhooks & Post to \texttt{\#devops-alerts}\\
CI allowlist \texttt{.env} & BY & \texttt{\textasciitilde/gitea/.env} on the droplet, root-only; holds team and approved grader IP addresses (personal data, not a secret); grader entries are removed after grading & n/a\\
DigitalOcean team & BY, VS & Each member's own login, in their password manager & Team member\\
Namecheap (\texttt{yebilly.me}) & BY & BY's password manager & Domain owner\\
Droplet \texttt{root} SSH & BY & Key-based only; private key \texttt{digiOcean} on BY's laptop; no password login & Root\\
@@ -82,8 +171,10 @@ Gitea database (SQLite) & --- & No credential; file access limited to droplet \t
\end{tabularx}
\normalsize
Multi-factor authentication and rotation status have not yet been recorded for
these accounts. Some credentials also have local copies on members' devices;
Multi-factor authentication: as reported by BY on 28 Oct 2026, his Discord
account (which owns the \texttt{\#devops-alerts} webhook) and his GitHub
account use MFA. MFA status for the other accounts, and rotation status for
all of them, has not yet been recorded. Some credentials also have local copies on members' devices;
moving them into the password managers is an open follow-up.
\fussy
+709
View File
@@ -0,0 +1,709 @@
\chapter{Continuous Integration with Jenkins}
\ChapterLabel{JenkinsCI}
\index{Jenkins}
\index{Jenkins!merge gate}
\index{Gitea!required status check}
\begingroup
\sloppy
This chapter records Assignment 6, \emph{Gitea + Jenkins Autobuild and
Testing -- Group} (instructor manual version 1.38, Chapter 4). Jenkins now runs
beside Gitea on the droplet \texttt{The-Ocean}. A pull request (PR) to
\texttt{main} in the
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway}{Group 1 Gitea
repository} triggers a Jenkins pipeline through a private \gls{webhook}.
Jenkins tests the PR's latest head commit and reports a named
\gls{status-check} to Gitea; \gls{branch-protection} on \texttt{main} blocks
the merge until that check passes and a teammate approves. The work was
carried out on October 21--23, 2026 (times below are UTC unless marked
Eastern). Sections~\ref{Section:JenkinsDeployment}--\ref{Section:JenkinsQuality}
follow the eight rubric rows in order.
\begin{devopsNote}[Result summary]
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/15}{PR~\#15}
(closes
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/14}{issue~\#14})
passed on its first commit, was blocked by a deliberate unit-test failure,
passed again after the repair, was approved by Vincent, and was merged as
\texttt{420ba4c}. Jenkins checked out the exact PR head for every run, and
the commit IDs match across Gitea and Jenkins (Table~\ref{Table:JenkinsSequence}).
\end{devopsNote}
%---------------------------------------------------------------
\section{Jenkins Deployment and Persistence}
\label{Section:JenkinsDeployment}
\index{Jenkins!deployment}
\paragraph{Image and plugins.}
Jenkins uses the official long-term-support (LTS) image
\texttt{jenkins/jenkins:2.580.1-lts-jdk21}, pinned by digest
\texttt{sha256:a660310e\ldots82c1}.\footnote{\url{https://www.jenkins.io/doc/book/installing/docker/}}
The versioned
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/420ba4c56b1c3efa50099a85c16c750a9815091a/deploy/jenkins/Dockerfile}{\texttt{deploy/jenkins/Dockerfile}}
adds only \texttt{python3} (Python 3.13.5; Git 2.47.3 is already in the
image) because builds run on the controller. Plugins come from the lockfile
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/ac18f1118601157da356d09d4aa28c4084dc86eb/deploy/jenkins/plugins.txt}{\texttt{deploy/jenkins/plugins.txt}},
which pins each listed plugin's version and SHA-256. The image build downloads each
archive and verifies its hash. Table~\ref{Table:JenkinsPlugins} lists the
plugins the pipeline relies on; the full lockfile holds 63 plugins including
dependencies.
\begin{table}[H]
\centering\footnotesize
\caption{Principal Jenkins plugins (core 2.580.1)\label{Table:JenkinsPlugins}}
\begin{tabular}{@{}L{4.4cm}L{4.4cm}L{6.0cm}@{}}
\toprule \textbf{Plugin} & \textbf{Version} & \textbf{Purpose}\\ \midrule
\texttt{gitea} & \texttt{286.v0740a\_413c1eb\_} & Gitea SCM source, webhook receiver, commit status\\
\texttt{workflow-aggregator} & \texttt{608.v67378e9d3db\_1} & Pipeline suite\\
\texttt{pipeline-model-definition} & \texttt{2.2293.v6e7193cec599} & Declarative \texttt{Jenkinsfile} syntax\\
\texttt{workflow-multibranch} & \texttt{842.v3a\_b\_59b\_57b\_e6e} & One job per branch / PR\\
\texttt{git} & \texttt{5.11.0} & Checkout of the selected revision\\
\texttt{matrix-auth} & \texttt{3.3} & Named user permissions\\
\texttt{pipeline-graph-view} & \texttt{1053.v9df19e6ceed2} & Stage view of each run\\
\bottomrule
\end{tabular}
\end{table}
\paragraph{Capacity preparation.}
The droplet originally had 512\,MB RAM. Vincent's October 19 core-only
experiments started Jenkins but pushed about 212\,MiB into swap, and their
recorded idle window was only 54 seconds of successful samples (see the
October 21 record in \ChapterRef{AIPromptLog}). Before this deployment the team
resized \texttt{The-Ocean} to the 1\,GiB Basic plan (Linux reports 961\,MiB RAM,
24\,GB disk, 1\,GiB swap file). On October 22 Billy ran Vincent's guarded
plugin and pipeline test, \texttt{ci/jenkins-capacity/run\_test.py}, unchanged
on the droplet:
\begin{tabularx}{\linewidth}{L{3.6cm}Y}
\caption{Guarded capacity test on The-Ocean, October 22, 2026\label{Table:JenkinsCapacity}}\\
\toprule \textbf{Record} & \textbf{Observed value}\\ \midrule
Run 1 (03:02--03:04) & Aborted: \texttt{java.io.FileNotFoundException}. All 59
plugins were active; Gitea returned 200 throughout. Cause: Windows
\texttt{scp} uploaded the test folders as root-only, so the container's
\texttt{jenkins} user could not read its fixtures. Fixed with
\texttt{chmod -R u=rwX,go=rX}; the script was not changed.\\
Run 2 (03:05--03:09) & \StatusPass: 59 plugins active, 60.6\,s healthy
idle, builds SUCCESS / FAILURE (\texttt{13 != 30}) / SUCCESS\\
Peak container memory & 252.8\,MiB RAM, 147.1\,MiB swap (393.9\,MiB together); no OOM events\\
Host minimum & 238\,MiB available RAM, 824\,MiB free swap; Gitea 200 on all 30 samples\\
CPU & Throttled in 1,689 of 2,212 periods at the 0.5-CPU limit\\
\bottomrule
\end{tabularx}
\paragraph{Compose service.}
Jenkins is a third service in the existing
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/420ba4c56b1c3efa50099a85c16c750a9815091a/deploy/docker-compose.yml}{\texttt{deploy/docker-compose.yml}}
(redacted excerpt; no secrets exist in the file):
\begin{minted}{yaml}
jenkins:
build: ./jenkins
image: ssw590-jenkins:2.580.1
restart: unless-stopped
environment:
- JAVA_OPTS=-Xms64m -Xmx256m -XX:+UseSerialGC -Djava.awt.headless=true
volumes:
- jenkins-home:/var/jenkins_home
networks: [web]
mem_limit: 512m
memswap_limit: 768m
cpus: 0.75
pids_limit: 256
# no ports: Caddy and the Gitea webhook reach jenkins:8080 privately
\end{minted}
The first deployment kept the test's limits (256\,MiB RAM, 128\,MiB heap,
0.5 CPU). Builds worked, but the setup wizard and plugin pages hung with
\texttt{OutOfMemoryError: Java heap space} once Jenkins loaded the
update-center catalog. At 03:35 the limits were raised to those shown above
(RAM and heap doubled to 512\,MiB and 256\,MiB, RAM plus swap 512 to
768\,MiB, CPU 0.5 to 0.75); Jenkins then answered in 45\,s instead of
184\,s on its next start, used about
350\,MiB, and left about 180\,MiB of host RAM available with Gitea still
returning 200. The service runs one executor so only one build uses memory
at a time.
\paragraph{Persistent state and restart test.}
Configuration, users, credentials, jobs, and build history live in the
\gls{named-volume} \texttt{gitea\_jenkins-home} mounted at
\texttt{/var/jenkins\_home}; the restart policy is \texttt{unless-stopped}.
On October 23, after the merge, Billy's session restarted the container and
compared state before and after:
\begin{minted}{text}
== BEFORE 2026-10-23T00:56:21Z started=2026-10-22T03:46:07Z
PR-15 builds=3 feature-issue-14 builds=1 main builds=1 users: billy vsun1
de35139e5c1d2510 de1a292f55d3050a e0e1e971a6f7e1c4 36bb5fd38ecf7ac6
== AFTER 2026-10-23T00:57:07Z (login 200 after ~25s) restart=unless-stopped
PR-15 builds=3 feature-issue-14 builds=1 main builds=1 users: billy vsun1
de35139e5c1d2510 de1a292f55d3050a e0e1e971a6f7e1c4 36bb5fd38ecf7ac6
IDENTICAL: jobs, builds, users, config hashes
\end{minted}
The four hashes are \texttt{config.xml}, \texttt{credentials.xml}, the Gitea
server configuration, and the job configuration. Gitea returned 200
throughout. \textbf{Restart persistence is not a backup test}: the volume
survives a container restart or replacement, but no copy of it exists
elsewhere, so losing the droplet or volume would lose Jenkins' state.
%---------------------------------------------------------------
\section{HTTPS, Access, and Firewall}
\label{Section:JenkinsAccess}
\index{Jenkins!HTTPS access}
\paragraph{Login URL and approved access path.}
The Jenkins login page is
\textbf{\url{https://ci.yebilly.me/login}}. Caddy serves it only to the Stevens
network (155.246.0.0/16, registered to Stevens Institute of Technology in
ARIN) and the team's dorm address; every other source receives HTTP 403
before reaching Jenkins.
\textbf{Instructor access:} open the URL from the Stevens campus network
(Wi-Fi \texttt{Stevens-Net}), whose public addresses fall in 155.246.0.0/16.
On October 23 Vincent tested this path from campus: on \texttt{Stevens-Net}
his public address was \texttt{155.246.151.38} and the Jenkins sign-in page
loaded (Figure~\ref{Figure:JenkinsCampus}).
Off campus, look up your public IPv4 address at \url{https://ifconfig.me}
and send it to Billy or Vincent; it is added to \texttt{CI\_TEAM\_IPS}, Caddy
is recreated, and the URL then opens. No sign-in is needed to see the login
page, and no grader account exists. This confirms web-service availability
only, not that a pipeline works.
The Stevens VPN is \emph{not} an access path. On October 23 at 18:56 UTC,
Billy connected the GlobalProtect client to \texttt{sitvpn.stevens.edu}, the
only gateway it offers (Figure~\ref{Figure:StevensVPN}). The laptop's public
address stayed the team's allowlisted residential address, and its routing
table sent only 155.246.0.0/16 through the VPN adapter, while the default
route kept using the home connection. The VPN is therefore split-tunnel:
traffic to \texttt{ci.yebilly.me} leaves through the user's own internet
provider, so an off-campus visitor on the VPN would receive 403.
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/jenkins-campus-test-2026-10-23.png}
\caption{October 23, 2026: Vincent's campus test on \texttt{Stevens-Net}.
ifconfig.me reports public address \texttt{155.246.151.38} (the second
forwarded address is ifconfig.me's own Google front end), and
\texttt{ci.yebilly.me/login} shows the Jenkins sign-in page. The screenshots
show no clock; Billy received them at 3:43 p.m.\ Eastern. The password field
and browser profile icon are blurred.}
\label{Figure:JenkinsCampus}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=0.6\linewidth]{images/stevens-vpn-split-tunnel-2026-10-23.png}
\caption{October 23, 2026: GlobalProtect connected to the single gateway
\texttt{sitvpn.stevens.edu} (IPSec, about 66\,KB received in 32 minutes,
consistent with a split tunnel). Assigned and gateway IPs redacted by Billy.}
\label{Figure:StevensVPN}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/jenkins-login-2026-10-21.png}
\caption{October 21, 2026, 11:40 p.m.\ Eastern: the Jenkins sign-in page at
\texttt{ci.yebilly.me/login} over HTTPS from the team's allowlisted address.
Bookmarks and taskbar applications are blurred.}
\label{Figure:JenkinsLogin}
\end{figure}
\paragraph{DNS, certificate, and redirect.}
Billy added an \texttt{A} record \texttt{ci} $\rightarrow$
\texttt{147.182.178.136} at Namecheap (Figure~\ref{Figure:JenkinsDNS}). No
\texttt{AAAA} record is published for \texttt{ci}. Caddy obtained the
certificate automatically at 03:17:31 on October 22 and renews it without a
cron job; its renewal window, reported by the certificate authority, is
December 20--22, 2026.\footnote{\url{https://caddyserver.com/docs/automatic-https}}
The \texttt{ci.yebilly.me} block in
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/420ba4c56b1c3efa50099a85c16c750a9815091a/deploy/Caddyfile}{\texttt{deploy/Caddyfile}} is:
\begin{minted}{text}
ci.yebilly.me {
@denied not remote_ip 155.246.0.0/16 {$CI_TEAM_IPS}
respond @denied 403
reverse_proxy jenkins:8080
}
\end{minted}
\texttt{CI\_TEAM\_IPS} is read from the untracked, root-only
\texttt{\textasciitilde/gitea/.env}, so home addresses are not in Git. Caddy's
\texttt{reverse\_proxy} forwards the \texttt{X-Forwarded-*} headers, and the
Jenkins URL (\emph{Manage Jenkins $\rightarrow$ System $\rightarrow$ Jenkins
Location}) is \texttt{https://ci.yebilly.me/}, as stored in the controller's
configuration (read on the droplet, October 23):
\begin{minted}{text}
$ docker exec gitea-jenkins-1 grep jenkinsUrl \
/var/jenkins_home/jenkins.model.JenkinsLocationConfiguration.xml
<jenkinsUrl>https://ci.yebilly.me/</jenkinsUrl>
\end{minted}
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/jenkins-dns-namecheap.png}
\caption{October 22, 2026: Namecheap Advanced DNS for \texttt{yebilly.me},
including the new \texttt{ci} \texttt{A} record to the droplet.}
\label{Figure:JenkinsDNS}
\end{figure}
\paragraph{External checks.}
All tests ran from Billy's laptop, outside the droplet
(Table~\ref{Table:JenkinsExposure}). The IPv6 tests target the droplet's
IPv6 address directly because IPv6 is enabled on the droplet, even though DNS
publishes only IPv4. The laptop's IPv6 address is not on the allowlist, so
the IPv6 HTTPS test is also the non-approved-source test.
{\small
\begin{tabularx}{\linewidth}{L{4.0cm}L{3.0cm}L{1.6cm}Y}
\caption{External exposure tests\label{Table:JenkinsExposure}}\\
\toprule \textbf{Test} & \textbf{Source / time} & \textbf{Expected} & \textbf{Actual}\\ \midrule
HTTPS \texttt{ci\ldots/login} & IPv4, allowlisted; Oct 22 03:17:56 & 200 & 200, ``Sign in -- Jenkins'' \StatusPass\\
HTTP \texttt{ci\ldots/login} & same & redirect & 308 to \texttt{https://\ldots/login} \StatusPass\\
Certificate & same & valid & Let's Encrypt \texttt{YE2}, CN \texttt{ci.yebilly.me}, Oct 22, 2026 -- Jan 20, 2027 \StatusPass\\
TCP 8080, 50000 & same & closed & closed/filtered \StatusPass\\
TCP 3000 (Gitea backend) & IPv4; Oct 23 01:02 & closed & closed/filtered \StatusPass\\
HTTPS \texttt{ci} via droplet IPv6 & IPv6, not allowlisted; Oct 23 01:02:42 & 403 & 403 \StatusPass\\
HTTP \texttt{ci} via IPv6 & same & redirect & 308 \StatusPass\\
TCP 8080, 50000, 3000 via IPv6 & same & closed & closed/filtered \StatusPass\\
HTTPS \texttt{ci\ldots/login} from campus & \texttt{Stevens-Net}, \texttt{155.246.151.38} (Vincent); Oct 23 & 200 & Sign-in page shown \StatusPass\\
Public IPv4 while on Stevens VPN & GlobalProtect connected; Oct 23 18:56:13 & Stevens address & Unchanged residential address; VPN is split-tunnel, so not offered as an access path \textbf{\footnotesize INFO}\\
\bottomrule
\end{tabularx}}
\paragraph{Firewalls and port mappings.}
The DigitalOcean \gls{cloud-firewall} \texttt{gitea-fw} is unchanged from
Assignment 4 (Figure~\ref{fig:gitea-fw-rules} in \ChapterRef{GiteaFoundation}):
TCP 80 and 443 from all IPv4/IPv6, TCP 22 from approved team addresses only.
No rule was added for Jenkins, because Jenkins publishes no port. The host
firewall (\texttt{ufw}) is inactive; exposure is controlled by the Cloud
Firewall and by Compose publishing nothing except Caddy's ports. On the
droplet, October 23:
\begin{minted}{text}
caddy caddy:2.11.4-alpine 0.0.0.0:80->80/tcp, [::]:80->80/tcp, 0.0.0.0:443->443/tcp, [::]:443->443/tcp
gitea gitea/gitea:1.27.3 22/tcp, 3000/tcp (not published)
jenkins ssw590-jenkins:2.580.1 8080/tcp, 50000/tcp (not published)
\end{minted}
The inbound agent port is also disabled in Jenkins' security settings
(\texttt{slaveAgentPort=-1}).
\paragraph{Accounts and roles.}
Jenkins uses its own user database with sign-up disabled and matrix-based
authorization (Figure~\ref{Figure:JenkinsMatrix}). \texttt{billy} (Billy Ye)
and \texttt{vsun1} (Vincent Sun) each hold \emph{Overall/Administer};
\emph{Anonymous} and \emph{Authenticated Users} hold nothing.
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/jenkins-security-matrix-2026-10-21.png}
\caption{October 21, 2026, 11:50 p.m.\ Eastern: Jenkins security with own
user database, sign-up disabled, and matrix authorization granting
\emph{Administer} only to the two named team accounts.}
\label{Figure:JenkinsMatrix}
\end{figure}
%---------------------------------------------------------------
\section{Gitea Trigger and Traceability}
\label{Section:JenkinsTrigger}
\index{webhook}
Figure~\ref{Figure:JenkinsDeployment} adapts the instructor's reference
deployment to what was built. The browser path and the webhook path are
separate: browsers reach Jenkins only through the firewall and Caddy's
allowlist, while the webhook, checkout, and status calls never leave the
droplet.
\begin{figure}[H]
\centering
\resizebox{\linewidth}{!}{%
\begin{tikzpicture}[
box/.style={draw, rounded corners, align=center, font=\small, minimum height=1.0cm},
lbl/.style={font=\scriptsize, fill=white, inner sep=1pt},
arr/.style={-{Stealth}, thick}]
\node[box] (browser) at (0,0) {\guillemotleft device\guillemotright\\Team / instructor\\browser};
\node[box, fill=devopsLightBlue] (fw) at (4.3,0) {\guillemotleft device\guillemotright\\Cloud Firewall\\\texttt{gitea-fw}, 443 / 80};
\node[box] (caddy) at (8.6,0) {\guillemotleft container\guillemotright\\Caddy TLS proxy\\allowlist for \texttt{ci}\\alias \texttt{git.yebilly.me}};
\node[box] (gitea) at (13.6,2.2) {\guillemotleft container\guillemotright\\Gitea \texttt{:3000}};
\node[box] (jenkins) at (13.6,-3.0) {\guillemotleft container\guillemotright\\Jenkins controller \texttt{:8080}\\\textbf{builds run here}\\(1 executor)};
\node[box] (gvol) at (18.4,2.2) {\guillemotleft artifact\guillemotright\\\texttt{gitea-data}\\SQLite + repos};
\node[box] (jvol) at (18.4,-3.0) {\guillemotleft artifact\guillemotright\\\texttt{jenkins-home}\\jobs, users,\\credentials};
\draw[arr] (browser) -- node[lbl, above=2pt]{HTTPS} (fw);
\draw[arr] (fw) -- (caddy);
\draw[arr] (caddy.north) |- node[lbl, pos=0.75]{HTTP} (gitea.west);
\draw[arr] (caddy.south) |- node[lbl, pos=0.75]{HTTP} (jenkins.west);
\draw[arr, dashed, devopsGreen] (gitea.south) -- node[lbl, right=2pt]{1. webhook (private)} (jenkins.north);
\draw[arr, dashed, devopsBlue] (jenkins.north west) -- node[lbl, pos=0.5, left=3pt]{2. checkout + status} (caddy.south east);
\draw[arr] (gitea) -- (gvol);
\draw[arr] (jenkins) -- (jvol);
\node[draw, dashed, rounded corners, fit=(caddy) (gitea) (jenkins) (gvol) (jvol), inner sep=10pt,
label={[font=\scriptsize]above:\guillemotleft device\guillemotright\ Droplet \texttt{The-Ocean} (1\,GiB) / \guillemotleft executionEnvironment\guillemotright\ Docker network \texttt{gitea\_web}}] {};
\end{tikzpicture}}
\caption{UML deployment diagram of the actual deployment, October 2026. Only
Caddy's 80/443 are public. (1) Gitea sends the webhook to
\texttt{http://jenkins:8080} on the private network. (2) Jenkins checks out
code and posts statuses to \texttt{https://git.yebilly.me}, which resolves to
Caddy inside the Docker network; Caddy forwards to Gitea. Builds run on the
controller; there is no separate agent.}
\label{Figure:JenkinsDeployment}
\end{figure}
\paragraph{Integration identity.}
Gitea user \texttt{jenkins-bot} is a \emph{Write} collaborator on
\texttt{ssw590-group1/vpn-dns-gateway}, the lowest repository role that can
post commit statuses. Its token \texttt{jenkins-ci} has repository
read/write and organization/user read scopes only. The token is stored in
Jenkins as credential \texttt{gitea-jenkins-bot}; Jenkins' Gitea server entry
points to \texttt{https://git.yebilly.me} with hook management disabled.
\paragraph{Job and events.}
The Multibranch Pipeline job \texttt{vpn-dns-gateway} discovers branches that
are not also PRs, and PRs from the origin repository using \emph{the current
pull request revision}, so Jenkins builds the PR head itself rather than a
temporary merge. PRs from forks are not discovered. The repository webhook
\texttt{jenkins-ci} posts JSON to
\texttt{http://jenkins:8080/gitea-webhook/post} for \emph{Push},
\emph{Pull Request}, and \emph{Pull Request Synchronized} events on all
branches. Gitea's \texttt{webhook.ALLOWED\_HOST\_LIST} is set to
\texttt{jenkins}, so Gitea may call no other private host. The first
repository scan (October 22, 22:39:55) authenticated as the bot and reported
no \texttt{Jenkinsfile} yet, as expected (Figure~\ref{Figure:JenkinsScan}).
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/jenkins-first-scan-2026-10-22.png}
\caption{October 22, 2026, 22:39 UTC: first scan of the Multibranch job; the
bot credential reaches \texttt{ssw590-group1/vpn-dns-gateway}, and the
executor count is 1.}
\label{Figure:JenkinsScan}
\end{figure}
\paragraph{Delivery evidence.}
A test delivery at 22:54:06 on October 22 returned HTTP 200 with body
\texttt{Processed} from \texttt{Server: Jetty(12.1.13)}, that is, from Jenkins
itself (Figure~\ref{Figure:JenkinsWebhook}). Real deliveries then started every
run in Table~\ref{Table:JenkinsSequence}; for example, the push of
\texttt{52b297c} produced the event ``Pull request \#15 event at 11:10:32 PM
on Oct 22, 2026'' that started \texttt{PR-15} run~2.
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/gitea-webhook-delivery-2026-10-22.png}
\caption{October 22, 2026, 22:54 UTC: Gitea webhook \texttt{jenkins-ci} with
Push, Pull Request, and Pull Request Synchronized events; test delivery
answered 200 \texttt{Processed} by Jenkins. A Jenkins reporting-endpoint ID
in one header is blurred.}
\label{Figure:JenkinsWebhook}
\end{figure}
All 14 deliveries to date, read from Gitea's delivery records on October 23,
are summarized in Table~\ref{Table:JenkinsDeliveries}.
{\small
\begin{tabularx}{\linewidth}{L{0.6cm}L{2.7cm}L{2.6cm}L{1.4cm}Y}
\caption{Gitea webhook deliveries to Jenkins (UTC)\label{Table:JenkinsDeliveries}}\\
\toprule \textbf{\#} & \textbf{Time} & \textbf{Event} & \textbf{Commit} & \textbf{Result}\\ \midrule
1 & Oct 22 22:54:06 & test push & --- & 200 \texttt{Processed}\\
2 & Oct 22 22:57:43 & push & \texttt{ad35197} & 200; started branch job\\
3 & Oct 22 23:01:59 & PR \#15 opened & \texttt{ad35197} & \textbf{failed}: client timeout awaiting headers (see below)\\
4--5 & Oct 22 23:10:32 & push, PR synchronized & \texttt{52b297c} & 200; started PR-15 run 2\\
6--7 & Oct 22 23:15:09 & push, PR synchronized & \texttt{9381d2a} & 200; started PR-15 run 3\\
8--9 & Oct 23 00:55:22 & PR closed, push & \texttt{9381d2a}, \texttt{420ba4c} & 200; started main run 1\\
10--14 & Oct 23 01:21--01:24 & push, PR \#16 events & \texttt{1149e9f}, \texttt{e4f3ce5} & 200; started PR-16 run 1 and main run 2\\
\bottomrule
\end{tabularx}}
\paragraph{Diagnosing a failed delivery.}
Delivery~3 is a real failure. Gitea recorded \texttt{Post
"http://jenkins:8080/gitea-webhook/post": context deadline exceeded
(Client.Timeout exceeded while awaiting headers)}. Diagnosis: Jenkins did
receive the event, because Gitea shows PR-15's status ``Build queued'' at
23:02:01, two seconds later, and run~1 passed at 23:02:18. Gitea did not
receive a response before its delivery timeout. PR discovery under the
0.75-CPU limit is a suspected cause of the delay, not a measured diagnosis.
No action was needed because the build completed. If a build does not
start, inspect the delivery and Jenkins logs, then use \emph{Redeliver}
or \emph{Scan Multibranch Pipeline Now} after correcting the cause.
Raising Gitea's \texttt{webhook.DELIVER\_TIMEOUT} may help if slow responses
are confirmed, but does not guarantee successful delivery.
General procedure if a push does not start a build:
(1) open \emph{Repository Settings
$\rightarrow$ Webhooks $\rightarrow$ jenkins-ci $\rightarrow$ Recent
Deliveries} and read the response; (2) ``can only call allowed HTTP
servers'' means \texttt{ALLOWED\_HOST\_LIST} was lost, so recreate the Gitea
container from Compose; (3) a connection error means Jenkins is down, so run
\texttt{docker compose ps} and \texttt{docker compose logs --tail 100 jenkins};
(4) a 200 response with no build means the branch has no \texttt{Jenkinsfile}
or the event type is not selected, so use \emph{Scan Multibranch Pipeline
Now} in Jenkins and read its log. \emph{Redeliver} on the delivery replays
the event after the fix.
%---------------------------------------------------------------
\section{Versioned Pipeline and Tests}
\label{Section:JenkinsPipeline}
\index{Jenkinsfile}
The repository root contains
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/420ba4c56b1c3efa50099a85c16c750a9815091a/Jenkinsfile}{\texttt{Jenkinsfile}},
the instructor's permitted Python example
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/420ba4c56b1c3efa50099a85c16c750a9815091a/pricing.py}{\texttt{pricing.py}},
and its unit tests in
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/src/commit/420ba4c56b1c3efa50099a85c16c750a9815091a/tests/test_pricing.py}{\texttt{tests/test\_pricing.py}}.
The Declarative \gls{jenkinsfile} is:
\begin{minted}{groovy}
pipeline {
agent any
options { skipDefaultCheckout() }
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Syntax check') {
steps { sh 'python3 -m py_compile pricing.py' }
}
stage('Test') {
steps { sh 'python3 -m unittest discover -s tests -v' }
}
}
}
\end{minted}
\begin{itemize}[nosep]
\item \textbf{Checkout} fetches the revision Jenkins selected; for PR~\#15 it
fetched \texttt{refs/pull/15/head} and checked out the PR head.
\item \textbf{Syntax check} compiles \texttt{pricing.py}; a syntax error fails here.
\item \textbf{Test} runs two unit tests: \texttt{10 * 3 == 30}, and quantity 0
raises \texttt{ValueError}. Expected passing output ends in
\texttt{Ran 2 tests \ldots OK}; any failing assertion ends in
\texttt{FAILED} and a non-zero exit, which fails the stage.
\end{itemize}
\textbf{Dependencies:} Python 3.13.5 and Git 2.47.3 come from the Debian
packages in the Jenkins image; the tests use only the standard library.
\textbf{Clean run:} on a machine with Python 3, clone the repository into a
new directory and check out the recorded commit ID of the run to reproduce.
From that repository root, run
\texttt{python3 -m py\_compile pricing.py} then
\texttt{python3 -m unittest discover -s tests -v} from the repository root.
In Jenkins, \emph{Build Now} on a branch or PR job builds the revision selected
for that run. Verify the checked-out commit ID in its log; it may differ from
an earlier run after a new push. The pipeline's \texttt{checkout scm} step
does not explicitly clean the workspace.
Figure~\ref{Figure:JenkinsStages} shows the distinct stage results of a run,
here the deliberate failure, with the tested commit identified in its log.
\begin{figure}[H]
\centering
\includegraphics[width=\linewidth]{images/jenkins-pr15-build2-failure-2026-10-22.png}
\caption{October 22, 2026: \texttt{PR-15} run~2 for commit \texttt{52b297c}
(started by the PR event at 23:10:32 UTC). Checkout and Syntax check passed;
Test failed with \texttt{AssertionError: 13 != 30} and exit code~1.}
\label{Figure:JenkinsStages}
\end{figure}
%---------------------------------------------------------------
\section{Required Merge Gate}
\label{Section:JenkinsGate}
\index{branch protection}
At 23:09:44 on October 22, Billy saved a branch-protection rule for
\texttt{main} (Figure~\ref{Figure:JenkinsProtection}). Its stored settings
are: direct push disabled; status check required with the exact context
\textbf{\texttt{vpn-dns-gateway/pipeline/pr-main}}; one approval required;
merge blocked on rejected reviews; stale approvals dismissed when new commits
are pushed; administrators may not override; no bypass list.\footnote{\url{https://docs.gitea.com/usage/access-control/protected-branches}}
\textbf{How the status reaches Gitea:} at the start and end of each run, the
Gitea plugin calls Gitea's commit-status API with the bot token for the
tested commit, for example ``\texttt{[Gitea] Notifying pull request build
status: FAILURE There was a failure building this commit}''. The context
name is built from the job and the PR target branch. Gitea compares it with
the protected branch's required context on the PR's latest head commit; a
webhook delivery or a green Jenkins page alone does not satisfy the
gate.\footnote{\url{https://plugins.jenkins.io/gitea/}}
\begin{figure}[H]
\centering
\includegraphics[width=0.85\linewidth]{images/gitea-branch-protection-2026-10-22.png}
\caption{October 22, 2026: protection rule for \texttt{main}. The required
pattern \texttt{vpn-dns-gateway/pipeline/pr-main} is marked
\emph{Matched} against checks Gitea has seen; administrators must follow
the rule.}
\label{Figure:JenkinsProtection}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=0.92\linewidth]{images/gitea-pr15-blocked-2026-10-22.png}
\caption{\textbf{Merge blocked.} October 22, 2026, about 23:11 UTC: PR~\#15
head \texttt{52b297c} fails required check
\texttt{vpn-dns-gateway/pipeline/pr-main} (Jenkins
\href{https://ci.yebilly.me/job/vpn-dns-gateway/job/PR-15/2/}{PR-15 run~2});
Gitea reports that required checks were not successful and no approval is
granted.}
\label{Figure:JenkinsBlocked}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=0.92\linewidth]{images/gitea-pr15-passing-2026-10-22.png}
\caption{\textbf{Passing after repair.} October 22, 2026, after 23:15:26 UTC:
PR~\#15 head \texttt{9381d2a} passes required check
\texttt{vpn-dns-gateway/pipeline/pr-main} (Jenkins
\href{https://ci.yebilly.me/job/vpn-dns-gateway/job/PR-15/3/}{PR-15 run~3}).
The only remaining condition is the required peer approval.}
\label{Figure:JenkinsPassing}
\end{figure}
%---------------------------------------------------------------
\section{Failure, Repair, and Review}
\label{Section:JenkinsReview}
Billy opened
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/14}{issue~\#14},
pushed branch \texttt{feature/issue-14}, and opened
\href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/pulls/15}{PR~\#15}
with \texttt{Closes \#14} in its description and Vincent as reviewer. The
controlled failure changed multiplication to addition in \texttt{pricing.py}
on the same branch; the repair restored it.
\clearpage
\begin{tabularx}{\linewidth}{L{2.6cm}L{1.6cm}L{2.0cm}L{1.9cm}Y}
\caption{PR~\#15 sequence, October 22--23, 2026 (UTC)\label{Table:JenkinsSequence}}\\
\toprule \textbf{Event} & \textbf{Commit} & \textbf{Jenkins run} & \textbf{Check} & \textbf{Detail}\\ \midrule
Initial push / PR & \href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/commit/ad35197ee4905767b0c3d74159a8dfee29d5c37a}{\texttt{ad35197}} & PR-15 \#1 & success 23:02:18 & Jenkins service, app, tests, \texttt{Jenkinsfile}\\
Controlled failure & \href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/commit/52b297c2f33881f7b483808c0040758cee2a1d8f}{\texttt{52b297c}} & PR-15 \#2 & failure 23:10:51 & \texttt{AssertionError: 13 != 30}; merge blocked\\
Repair & \href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/commit/9381d2aa9a11cb7be1b157ea5ecb1318f9a014f0}{\texttt{9381d2a}} & PR-15 \#3 & success 23:15:26 & Multiplication restored; 2 tests OK\\
Peer review & \texttt{9381d2a} & --- & --- & \texttt{vsun1} approved at 00:02:40, Oct 23\\
Merge & \href{https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/commit/420ba4c56b1c3efa50099a85c16c750a9815091a}{\texttt{420ba4c}} & main \#1 & success 00:55:37 & Merged by \texttt{bill} at 00:55:21; issue \#14 closed automatically\\
\bottomrule
\end{tabularx}
Each Jenkins log names the commit it checked out
(\texttt{Checking out Revision ad35197ee490\ldots} for run~1,
\texttt{52b297c2f338\ldots} for run~2, \texttt{9381d2aa9a11\ldots} for
run~3), and each matches the PR head shown
in Gitea at that time. The branch job \texttt{feature/issue-14}~\#1 also
passed on \texttt{ad35197} before the PR existed; its context
\texttt{vpn-dns-gateway/pipeline/head} is not the required one.
\begin{figure}[H]
\centering
\includegraphics[width=0.92\linewidth]{images/gitea-pr15-merged-2026-10-22.png}
\caption{October 23, 2026, 00:55 UTC: PR~\#15 merged into \texttt{main} as
\texttt{420ba4c}. The timeline shows the passing, failing, and repaired
commits and \texttt{vsun1}'s approval.}
\label{Figure:JenkinsMerged}
\end{figure}
%---------------------------------------------------------------
\section{Credentials and Build Boundary}
\label{Section:JenkinsBoundary}
\index{Jenkins!build boundary}
\paragraph{Secrets.}
The only integration secret is the \texttt{jenkins-bot} token, stored as
the Jenkins credential \texttt{gitea-jenkins-bot} (System, Global scope) and
encrypted in \texttt{jenkins-home}. It never appears in Git, Compose, the
console log (the log prints only the credential's description), or this
manual. The initial administrator password was read once by Billy in his own
terminal and is no longer used. Hints for all accounts are in
Table~\ref{Table:Passwords}.
\paragraph{Where builds run, and the risk.}
Builds run on the Jenkins \gls{controller} executor (one executor); there is
no separate \gls{build-agent}, controller executors are not zero, and no agent
port is open. Pipeline code runs as the container's \texttt{jenkins} user
with read access to \texttt{jenkins-home}, which holds the encrypted
credentials and their key, so a malicious \texttt{Jenkinsfile} could steal
the bot token.\footnote{\url{https://www.jenkins.io/doc/book/security/controller-isolation/}}
Compensating restrictions:
\begin{itemize}[nosep]
\item Only Billy and Vincent, plus the \texttt{jenkins-bot} identity whose
token exists only inside Jenkins, have write access to the repository, so
only they can change the \texttt{Jenkinsfile}; \texttt{main} accepts changes
only through reviewed PRs, which also applies to the bot.
\item PRs from forks are not discovered, so untrusted code never runs.
\item No Docker socket is mounted and the container is not privileged; its
memory, CPU, and process count are capped.
\item The token is limited to one repository role (Write) and read-only
organization/user scopes, and can be revoked in Gitea without touching
Jenkins.
\end{itemize}
\paragraph{Plugin-update check.}
On October 23 at 01:03, the 63 locked plugins were compared with the Jenkins
update center for core 2.580.1. (Counts: the capacity bundle had 59;
\texttt{matrix-auth} and \texttt{pipeline-graph-view} with its two
dependencies make 63 locked; Jenkins reports 66 installed, the other three
being the theme plugins described in Section~\ref{Section:JenkinsQuality},
which this check did not cover.) One newer version exists
(\texttt{workflow-api} \texttt{1413.v2ff1a\_5e720fa\_} $\rightarrow$
\texttt{1429.v7a\_1b\_efb\_a\_f7c5}); no security warning matched the 63
checked plugin versions. The update was deferred: it is not a security fix and would change
the tested set. Updates are applied by regenerating the lockfile, rebuilding
the image, and recreating the container.
\paragraph{Troubleshooting a failed build.}
Open the run's \emph{Pipeline Overview} to see which stage failed and its
log. A red \emph{Test} stage with an assertion is a code failure: fix the
code and push to the same PR. A red \emph{Checkout} usually means the token
was revoked or Gitea is unreachable: check the credential and
\texttt{curl https://git.yebilly.me} from inside the container. A run that
never starts: follow the webhook steps in
Section~\ref{Section:JenkinsTrigger}. Memory trouble (slow pages,
\texttt{OutOfMemoryError} in \texttt{docker compose logs jenkins}): check
\texttt{free -m} and \texttt{docker stats} and restart Jenkins with
\texttt{docker compose restart jenkins}.
%---------------------------------------------------------------
\section{Manual Quality and Controls}
\label{Section:JenkinsQuality}
\paragraph{Corrective actions.}
Five problems were found and fixed during this work, each recorded with its
evidence: (1) the official plugin installer ran out of its 128\,MiB heap while
reading the update-center catalog, so the Dockerfile downloads the pinned
plugins with \texttt{curl} and checks their SHA-256; (2) the first droplet
capacity run failed on upload permissions, fixed by \texttt{chmod}; (3) the
128\,MiB heap hung the web interface, fixed by the larger limits in
Section~\ref{Section:JenkinsDeployment}; (4) matrix authorization was missing
because the capacity bundle covered only Pipeline and Gitea, so
\texttt{matrix-auth} was added and the image rebuilt; (5) no stage-by-stage
run view was installed, so \texttt{pipeline-graph-view} was added the same
way. Three theme plugins
(\texttt{dark-theme}, \texttt{dracula-theme}, \texttt{theme-manager}) were
installed from the web interface during setup and are not in the lockfile;
they survive in \texttt{jenkins-home} but would be lost if the volume were
recreated.
\paragraph{Operator restart and recovery note.}
Run these on the droplet as \texttt{root}:
\begin{minted}{sh}
cd ~/gitea
docker compose ps # all three services Up
docker compose restart jenkins # state stays in the volume
docker compose logs --tail 100 jenkins # startup errors, OutOfMemoryError
# after changing deploy/jenkins/plugins.txt:
docker compose build jenkins && docker compose up -d jenkins
\end{minted}
After a droplet reboot, Docker starts all three services because of their
restart policies. Measured container starts took 25\,s (warm
\texttt{docker compose restart}) to 45\,s (first start after the limit
change); a full droplet reboot was not tested, so allow about a minute before
the login page answers. Gitea does not depend on Jenkins, so a Jenkins outage only delays
checks (PRs stay blocked until Jenkins reports).
\paragraph{Cost, ownership, and cleanup.}
Jenkins adds no paid resource; it uses the droplet's 1\,GiB Basic plan
(listed at \$6/month on DigitalOcean's pricing page on October 21, 2026; the
account's billing was not re-checked here) and about 0.9\,GB of disk for its
image. On October 23 the root filesystem had 18\,GB free of 24\,GB
(\texttt{df -h /}, 25\% used). Billy administers the droplet and Jenkins; Vincent reviews. To remove
Jenkins: delete the \texttt{main} protection's required check, stop and
remove the service (\texttt{docker compose rm -sf jenkins}), delete the volume
(\texttt{docker volume rm gitea\_jenkins-home}), remove the \texttt{ci} block
from the Caddyfile and the \texttt{ci} DNS record, delete the webhook, and
delete the \texttt{jenkins-bot} user and token.
\paragraph{Document controls.}
This chapter was introduced in version 4.0 and corrected in 4.1 (access path,
delivery evidence, wording). Document History records both and the updated
tables in \ChapterRef{HostsPasswords}: the Hosts table adds \texttt{ci.yebilly.me},
the Jenkins service, and the 1\,GiB resize; the Passwords table adds the
Jenkins administrators, the \texttt{jenkins-bot} account, and its token.
New glossary terms are indexed, and AI assistance is recorded in
\ChapterRef{AIPromptLog}.
\endgroup
+50
View File
@@ -4,3 +4,53 @@
publisher = {IT Revolution Press},
year = {2018}
}
@book{SREWorkbook,
author = {Beyer, Betsy and Murphy, Niall Richard and Rensin, David K. and Kawahara, Kent and Thorne, Stephen},
title = {The Site Reliability Workbook: Practical Ways to Implement {SRE}},
publisher = {O'Reilly Media},
year = {2018},
note = {Chapter 2, ``Implementing SLOs,'' \url{https://sre.google/workbook/implementing-slos/}, accessed Oct. 28, 2026}
}
@misc{PrometheusDocs,
author = {{Prometheus Authors}},
title = {Prometheus Documentation: Configuration, Storage, and Querying},
howpublished = {\url{https://prometheus.io/docs/prometheus/latest/}},
note = {Version 3.15; accessed Oct. 28, 2026}
}
@misc{NodeExporter,
author = {{Prometheus Authors}},
title = {Node Exporter},
howpublished = {\url{https://github.com/prometheus/node_exporter}},
note = {Release v1.12.1; accessed Oct. 28, 2026}
}
@misc{BlackboxExporter,
author = {{Prometheus Authors}},
title = {Blackbox Exporter},
howpublished = {\url{https://github.com/prometheus/blackbox_exporter}},
note = {Release v0.29.1; accessed Oct. 28, 2026}
}
@misc{GrafanaDocker,
author = {{Grafana Labs}},
title = {Run {Grafana} {Docker} Image},
howpublished = {\url{https://grafana.com/docs/grafana/latest/setup-grafana/installation/docker/}},
note = {{Grafana OSS} 13.2; accessed Oct. 28, 2026}
}
@misc{GrafanaAlerting,
author = {{Grafana Labs}},
title = {Grafana Alerting: Provision Alerting Resources and Configure Contact Points},
howpublished = {\url{https://grafana.com/docs/grafana/latest/alerting/set-up/provision-alerting-resources/file-provisioning/}},
note = {{Grafana OSS} 13.2; accessed Oct. 28, 2026}
}
@misc{MicrosoftTestNetConnection,
author = {{Microsoft}},
title = {{Test-NetConnection}},
howpublished = {\url{https://learn.microsoft.com/en-us/powershell/module/nettcpip/test-netconnection}},
note = {Accessed Oct. 28, 2026}
}
File diff suppressed because it is too large Load Diff
+364
View File
@@ -0,0 +1,364 @@
\chapter{Secure Delivery and Rollback}
\ChapterLabel{SecureDelivery}
\index{secure delivery}\index{rollback}\index{Ansible}\index{immutable image}
\section{Scope and Current Status}
Assignment 8 implements Chapter 6 of instructor manual version 1.43, using its
Startup Pricing Service and the existing Gitea, Jenkins, Caddy and monitoring
foundation. The Canvas page lists November 13, 2026 at 11:59pm; Vincent reports
an extension. Preparation began November 14; DNS/TLS and the first reviewed
Jenkins gate runs were verified November 15. PR~\#24 is merged, the delivery
job is enabled, and the first reviewed v1 image is published. Its staging
deployment stopped at SSH before creating an application container.
\textbf{It is not ready for submission.} Successful v1/v2 staging and production,
production rollback, staging failure/recovery and monitoring correlation remain
pending. Published image metadata is not evidence of a successful deployment.
The instructor's v1 source and tests were copied from
\path{Examples/dosSecureDelivery/v1/} to \path{delivery/app/}. Flask validates
requests and calculates the price; Gunicorn serves it with one worker on private
port 8000. There is no payment processing, customer data or application volume.
For three units v1 returns USD 30; the separate v2 source/test change must return
USD 36. The image embeds its actual source commit during the build. Health,
identity and pricing are verified separately.
\section{Deployment and Trust Boundaries}
\begin{figure}[htbp]
\centering
\renewcommand{\theHfigure}{delivery.\arabic{figure}}
\resizebox{\linewidth}{!}{%
\begin{tikzpicture}[
box/.style={draw=devopsBlue,rounded corners,align=center,text width=3.6cm,
minimum height=1.5cm,font=\footnotesize,fill=white},
data/.style={box,draw=devopsGray,fill=gray!12,font=\scriptsize},
planned/.style={box,dashed,fill=devopsLightBlue},
flow/.style={-{Latex},thick}, note/.style={font=\scriptsize,align=center,fill=white,inner sep=1pt}]
\node[box] (agent) at (4.8,2.7) {Droplet delivery agent\\512 MiB / 0.5 CPU\\Docker, scans and Ansible};
\node[data,text width=3.8cm] (local) at (0,2.7) {Agent volumes on droplet\\\texttt{ssw590-delivery-identity}\\\texttt{ssw590-delivery-workspace}};
\node[box] (builder) at (9.6,2.7) {Pinned BuildKit builder\\256 MiB / 0.5 CPU\\Private Docker control};
\node[box] (git) at (0,0) {Gitea + OCI registry\\\texttt{git.yebilly.me}\\SQLite retained};
\node[box] (jenkins) at (4.8,0) {Jenkins controller\\\texttt{ci.yebilly.me}\\Schedules trusted job};
\node[box] (host) at (9.6,0) {The-Ocean host\\\texttt{deploy} SSH account\\Python, Docker/Compose};
\node[box] (monitor) at (0,-2.8) {Prometheus, Grafana,\\Blackbox and Node Exporter\\Private metrics ports};
\node[box] (proxy) at (4.8,-2.8) {Caddy TLS proxy\\Public 80/443\\Private \texttt{gitea\_web} network};
\node[planned] (stage) at (9.6,-2.8) {Planned staging app\\\texttt{staging.yebilly.me}\\{\scriptsize\texttt{pricing-staging:8000}}};
\node[planned] (prod) at (9.6,-5.2) {Production app (planned)\\\texttt{app.yebilly.me}\\{\scriptsize\texttt{pricing-production:8000}}};
\node[data,text width=12.9cm,align=left] (storage) at (4.8,-8.45) {
\textbf{Persistent state and read-only mounts on The-Ocean}\\[3pt]
\begin{tabular}{@{}ll@{}}
Gitea & \texttt{gitea\_gitea-data} $\rightarrow$ \texttt{/data} (includes SQLite)\\
Jenkins & \texttt{gitea\_jenkins-home} $\rightarrow$ \texttt{/var/jenkins\_home}\\
Caddy certificates & \texttt{gitea\_caddy-data} $\rightarrow$ \texttt{/data}\\
Caddy configuration & \texttt{gitea\_caddy-config} $\rightarrow$ \texttt{/config}\\
Prometheus & \texttt{monitoring\_prometheus\_data} $\rightarrow$ \texttt{/prometheus}\\
Grafana & \texttt{monitoring\_grafana\_data} $\rightarrow$ \texttt{/var/lib/grafana}\\
Proxy bind mount & \texttt{/root/gitea/Caddyfile} $\rightarrow$ \texttt{/etc/caddy/Caddyfile} (ro)\\
Monitoring mounts & \texttt{/root/monitoring/}: configuration (ro); host \texttt{/} $\rightarrow$ \texttt{/host} (ro)\\
Planned app config & \texttt{/opt/startup/pricing-\{staging,production\}}; no app data volume
\end{tabular}};
\node[draw,dashed,rounded corners,fit=(agent)(local)(builder)(git)(host)(monitor)(prod)(storage),
inner sep=0.55cm,label={[font=\small]below:Existing droplet: 1 vCPU, 2 GiB RAM, 25 GB plan disk}] {};
\draw[flow,dotted] (local)--(agent);
\draw[flow] (agent)--node[note,right,pos=0.25]{private WS}(jenkins);
\draw[flow] (agent)--node[note,above]{build}(builder);
\draw[flow] (agent.south west)--node[note,above,sloped]{Git / OCI}(git.north east);
\draw[flow] (agent.south east)--node[note,above,sloped]{SSH}(host.north west);
\draw[flow] (git)--node[note,above]{hook}(jenkins);
\draw[flow,dashed] (host)--node[note,right]{apply}(stage);
\draw[flow,dashed] (host.east)--++(0.35,0)|-(prod.east);
\draw[flow,dashed] (monitor)--node[note,above]{probe}(proxy);
\draw[flow,dashed] (proxy)--node[note,above]{HTTP}(stage);
\draw[flow,dashed] (proxy.south east)--node[note,above,sloped]{HTTP}(prod.north west);
\end{tikzpicture}}
\caption{Preparation architecture. Solid boxes are installed; dashed blue boxes
and connections are planned application work. Gray boxes identify durable state
or read-only mounts. Pricing is stateless; each environment retains only its
Compose and release files on the host. The agent and builder now share the
droplet; deployment SSH uses Docker's host gateway with the original pinned
host-key alias. Browser access remains through Caddy HTTPS.}
\label{Figure:SecureDeliveryArchitecture}
\end{figure}
The exclusive node \texttt{ssw590-vince-delivery} has one executor and label
\texttt{delivery-trusted}. Originally installed on Vincent's laptop, it now runs
on The-Ocean because campus networking blocks SSH from the laptop. Its legacy
node name is retained and its description records the new location. It connects
to \texttt{jenkins:8080} over private HTTP/WebSocket, with no published agent
or Docker API port. Docker socket membership (group 987 on this host) grants
administrative control over the same host as Jenkins, Gitea and monitoring;
containerization is not isolation from malicious Docker-authorized jobs.
The \texttt{deploy} account's
\texttt{NOPASSWD} sudo permits root commands for Ansible; a separate account
does not remove that administrative authority. Its authorized key disables SSH
forwarding and PTY allocation. The host's ED25519 key was read through the
existing strictly pinned administrator SSH connection and stored as a Jenkins
file credential; verification is not disabled. A mounted SSH configuration
maps the existing inventory address to \texttt{host.docker.internal}, retaining
\texttt{HostKeyAlias 147.182.178.136}. Thus neither the Jenkins-agent connection
nor deployment SSH crosses campus Wi-Fi. Campus browser HTTPS access still
needs rehearsal. The Gitea Actions PDF runner subsequently moved to The-Ocean
too; \ChapterRef{AutomatedManualBuild} records its separate migration and real
workflow verification. Neither active runner now requires Docker Desktop.
Keep manual compilation and delivery releases sequential on the shared host.
The agent is capped at 512 MiB RAM / 768 MiB RAM+swap and 0.5 CPU, with a
96 MiB Java heap. Its separate pinned BuildKit container is capped at 256 MiB /
384 MiB and 0.5 CPU; builds explicitly select that builder because a Docker
socket does not make child containers inherit agent limits. Both use
\texttt{unless-stopped}. Agent restart/reconnect was verified at 03:57:57 UTC.
The laptop copy is stopped and its helper now requires an explicit fallback
switch; two copies must never connect as the same node. VS maintains the agent;
BY retains host administration. No extra instance or plan resize was made.
Deployment credentials belong to the \texttt{secure-delivery} Jenkins folder,
not the root multibranch PR job. That job retains its earlier ordinary tests,
plus Python syntax and release-control tests; it does not bind delivery
credentials or a Docker socket. The new release job loads
\path{delivery/Jenkinsfile} from protected main and was enabled after PR~\#24 merged.
Only trusted reviewed code may use the privileged node. Exclusive scheduling
is not a defense against an administrator or an author permitted to select that
node; the two-member repository and Jenkins administration remain trust boundaries.
Shared proxy-network membership is a lab simplification, not strong lateral
isolation. Both environments share the droplet's failure domain.
\section{Installation Inventory and Preparation Evidence}
\small
\begin{longtable}{@{}L{3.0cm}L{9.9cm}@{}}
\toprule Item & Verified selection or result\\\midrule\endhead
Trusted agent & Python 3.13.5; Ansible core 2.21.6 in
\texttt{/opt/delivery-tools}; community.docker 5.4.0 and its
community.library\_inventory\_filtering\_v1 dependency 1.1.5.\\
Build and scan tools & Docker 29.9.3, Compose 5.7.1, Trivy 0.76.2 and
pip-audit 2.10.1. Base tool images are pinned in the agent Dockerfile;
direct/transitive Python tools and collections are locked in Git.\\
Target & Ubuntu 24.04 LTS; Python 3.12.3; Docker 29.9.3 and Compose 5.7.1.
At 20:46 UTC: 1,967 MiB RAM, 878 MiB available, 102 MiB swap used; root
filesystem 41\% used. This is one prerequisite sample, not a load test.\\
Runtime image & Python 3.13 Alpine, Linux/amd64, selected registry digest:
\newline\texttt{sha256:9ef1a599f863231c3d91e941389bfdc4}\allowbreak%
\texttt{a2d6070557243d54df1a4e57015b960e}.\\
Application lock & Flask 3.1.3; Gunicorn 23.0.0; blinker 1.9.0; click 8.5.1;
itsdangerous 2.2.0; Jinja2 3.1.6; MarkupSafe 3.0.4; packaging 26.3;
Werkzeug 3.1.9. No claim is made that a pinned version remains vulnerability-free.\\
Runtime constraints & UID 10001; one Gunicorn worker; 64 MiB RAM / 96 MiB
RAM+swap; 0.25 CPU; 64 PIDs; read-only root; 16 MiB temporary filesystem;
all capabilities dropped and no host application port.\\
Initial Jenkins prerequisite run &
\href{https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/}{Agent preflight build 1}
passed on November 14 at 20:46 UTC, including strict-key SSH as deploy and
noninteractive sudo. \path{delivery/evidence/agent-preflight-1.txt} preserves
its non-secret inventory. This run did not deploy an application.\\
Remote agent migration &
At 03:47 UTC on November 15 (November 14 Eastern),
\href{https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/2/}{preflight build 2}
passed on The-Ocean with real credentials, pinned host verification and sudo.
\path{delivery/evidence/agent-preflight-2.txt} preserves the inventory.\\
Remote capacity trial & At 03:50--03:51 UTC, a preparation snapshot passed
12 control tests, 3 app tests, source/dependency gates, a limited image build,
the full image gate and a temporary 64 MiB HTTP smoke test. Its source identity
was \texttt{uncommitted-remote-preflight}; nothing was published or promoted.
Observed available RAM exceeded 700 MiB; swap used rose from 263 to 372 MiB.
Agent memory-limit events occurred, but no OOM kill was recorded. This short
trial does not establish full release or presentation performance.\\
Local tests & Three Flask tests passed; a generated wrong-price assertion
failed as intended; twelve release/security-control tests passed. Gunicorn
health/identity/price/invalid-input smoke checks passed under the stated cap.
Its baked identity was explicitly \texttt{uncommitted-preflight}, not a release SHA.\\
Local scans & Source/dependency gates passed; a generated synthetic secret
blocked the gate. At 20:32 UTC the complete runtime-image gate passed with no
HIGH/CRITICAL findings. Reports and exit codes remain in ignored local evidence.
Later assessed Jenkins runs and published-image scans are recorded below.\\
\bottomrule
\end{longtable}
\normalsize
Vincent resized the droplet while keeping its 25 GB plan disk, then updated
packages. Post-maintenance checks found all seven earlier containers running,
no failed systemd services, no required reboot marker, and HTTP 200 for Gitea,
Jenkins and Grafana from the laptop. Before administrator bootstrap, a protected
consistent Jenkins-home archive and an online Gitea SQLite backup were saved
under \path{/root/ssw590-delivery-bootstrap/}. The one-time setup then created
the deploy key, distinct package-only tokens under \texttt{vsun1}, the folder,
node and disabled release job. No token or private key was printed or copied
into the repository. Private bootstrap inputs were removed after Jenkins stored
the credentials; generated agent identity stays in protected named volumes.
\section{Prepared Pipeline and Release Records}
The normal release path is checkout of reviewed main ancestry, control and
application tests, repository-secret and dependency checks, build, image scan,
registry push/pull, exact digest recording, staging deployment, unchanged rerun,
human approval, and production deployment. Existing commit tags are reused on
retry rather than overwritten. A new image is scanned before push and again by
its registry digest. The same digest is promoted without rebuilding. Concurrent
delivery builds are disabled. Release and scan reports are archived on failure
and before the approval prompt.
The policy in \path{delivery/SECURITY.md} was selected before the scans: block
detected secrets, HIGH/CRITICAL image findings (including unfixed issues), all
reported Python dependency advisories, scanner errors and missing/malformed
reports. No exceptions are approved. A proposed exception requires instructor
acceptance, advisory ID, owner, rationale, controls and expiry. Earlier Debian
and installer-containing Alpine preflight scans failed; their reports were
retained. The runtime was changed to the pinned Alpine base and unneeded pip/
ensurepip were removed; the scanner policy was not weakened.
The release record contains source and configuration commits, exact registry
digest, version/expected total, environment, public URL, proxy network, build
URL and creation time. Both commits must be ancestors of protected main. Only
the expected team registry, URL/environment pair and metadata fields are
accepted. Production requires an input restricted to \texttt{billy,vsun1},
with a 20-minute timeout; the actual human approval and UTC time are recorded.
Administrators retain their normal override powers. No unattended approval is
claimed. Ansible restores the selected playbook/template from the recorded
configuration commit, deploys without rebuilding, waits for health, then checks
HTTPS health, version, source commit and price. A separate JSON recap records
timing and makes a nonzero changed count on the unchanged rerun a blocking error.
\small
\begin{tabularx}{\linewidth}{L{2.1cm}Y Y}
\toprule Traceability field & v1 & v2\\\midrule
Source / config commits & Reviewed merge \texttt{09731ac}; SSH fix awaits review & Separate change pending\\
Registry digest / Jenkins release build & Published in build 3; full digest below & Not published / not run\\
Staging + unchanged rerun & SSH blocked before deployment; rerun not reached & Pending\\
Production approval / result & No approval or promotion yet & No approval or promotion yet\\
Recovery evidence & Healthy rollback pending & Staging failure/recovery pending\\
\bottomrule
\end{tabularx}
\normalsize
\section{Reviewed Gate Runs and Deployment Correction}
Billy approved the updated PR~\#24 head \texttt{ed0a862} at 21:06 UTC on
November 15; Vincent merged it as \texttt{09731ac} at 21:59 UTC. The resulting
Actions manual build 13 passed in 2m25s. It finished before the delivery runs.
All times in this section are UTC.
\begin{itemize}
\item \href{https://ci.yebilly.me/job/secure-delivery/job/pricing/1/}{Pricing build 1},
\texttt{blocked-test}, took 54.202 seconds. Twelve control tests and the three
normal Flask tests passed. The deliberate expected-total=$-1$ assertion failed
against the actual total 30. Publication, deployment and approval were skipped.
\item \href{https://ci.yebilly.me/job/secure-delivery/job/pricing/2/}{Pricing build 2},
\texttt{blocked-secret}, took 31.375 seconds. Tests, clean-source scanning and
all nine locked dependency audits passed. The generated synthetic-secret finding
blocked the gate and all publication/deployment stages. Match/code fields in
the archived secret report are redacted; no real secret was introduced.
\item \href{https://ci.yebilly.me/job/secure-delivery/job/pricing/3/}{Pricing build 3},
\texttt{release}, took 77.799 seconds. Tests and source/dependency gates passed.
Both pre-push and registry-digest image scans analyzed two targets and found zero
HIGH/CRITICAL findings. The image was published and pulled back by exact digest.
\end{itemize}
Build 3 recorded these exact source/configuration and image identifiers:
\begin{Verbatim}[fontsize=\footnotesize,frame=single]
Source/configuration:
09731acb0370566471dd4e401e59bafe55e927dc
Image repository: git.yebilly.me/ssw590-group1/pricing
Registry digest:
sha256:cccd47f112f839f3443c88c4d16fd7a1ed0fec2100a26464156526d53ccc2695
\end{Verbatim}
Staging failed at 22:26:39 UTC during Gathering Facts:
\texttt{PTY allocation request failed on channel 0}. The recap was
\texttt{ok=0 changed=0 unreachable=1 failed=0}, Ansible exit code 4. No app
configuration or container was created, and production approval was not reached.
Its generated records are retained as attempt evidence, not known-good recovery
selections in \path{delivery/releases/}.
Ansible defaults to forcing a terminal, but the dedicated deploy key intentionally
forbids PTY allocation. The inventory correction sets
\texttt{ansible\_ssh\_use\_tty=false}; it preserves the restricted key, pinned
host verification and noninteractive sudo. The expanded administrator preflight
exercises Ansible's actual connection/become path as well as plain SSH.
\href{https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/3/}{Preflight build 3}
passed in 17 seconds at 22:50 UTC: Ansible ran \texttt{id -u} as root and
returned 0 without a terminal. Its \texttt{CHANGED} label describes the command
module's default reporting, not a pricing deployment or idempotence test.
This validates connection prerequisites only; the corrected configuration must
be reviewed and merged before the assessed release is retried.
\begin{figure}[htbp]
\centering
\renewcommand{\theHfigure}{delivery.preflight.\arabic{figure}}
\includegraphics[width=\linewidth,trim=330bp 880bp 900bp 0bp,clip]{images/assignment8-ansible-preflight-3-20261115.jpg}
\caption{Actual successful Jenkins prerequisite build 3 after adding the
noninteractive Ansible connection check. No pricing environment was deployed.}
\label{Figure:DeliveryAnsiblePreflight}
\end{figure}
Dated records under \path{delivery/evidence/} preserve the results:
\begin{itemize}
\item \path{gates-20261115.md}: deliberate blocking demonstrations.
\item \path{release-attempt-3-20261115.md}: publication and SSH failure.
\item \path{agent-preflight-3.txt}: successful noninteractive connection.
\end{itemize}
Jenkins archives the complete reports. The ignored local evidence directory is:
\begin{quote}\small
\path{build/evidence/assignment8-execution/}
\end{quote}
\section{Release, Recovery and Monitoring Runbooks}
The versioned \path{delivery/RUNBOOKS.md} gives the executable sequence.
Vincent handles commits/pushes; Billy reviews repository changes. The v1
preparation is now on main, DNS/TLS are ready, and the two deliberate gate
demonstrations have run. Review/merge the noninteractive SSH correction, then
retry \texttt{release} using the corrected full main commit.
Verify staging and changed=0 before a real human approval promotes v1. Save and
review its generated staging/production records. Apply the supplied v2 source
and test changes in another reviewed commit and repeat, expecting 36.
For healthy production rollback, record detection/decision time, start the
HTTPS observer, select the committed v1 production record and approve the
operation. Ansible restores its original image and configuration, then verifies
v1, original source SHA and total 30. Preserve start, recovery, verification and
sampled interruption. A zero-failure sample set cannot prove zero downtime
between requests.
For failed staging deployment recovery, use a separate reviewed configuration
commit to bind Gunicorn to 8001 only in staging while the image healthcheck
still probes 8000. Run \texttt{staging-failure} with the good v2 staging release
record and bad configuration SHA. Compose wait must fail and Jenkins must stop
before production. Restore/review the correct template and rerun
\texttt{recover-staging} with the original good record. Verify v2, its source,
total 36 and changed=0. Do not alter shared infrastructure or data to create
the failure.
The production \texttt{/health} probe and Grafana availability panel are prepared
in Git but not deployed while production is absent. Apply them after health is
verified, keeping existing Gitea/Jenkins probes and host metrics. Correlate real
Prometheus/Grafana samples with release/rollback times; 30-second scrapes and
alert durations can miss a brief interruption. Uptime probes do not verify
pricing. The observer in \path{delivery/ci/observe.py} records finer HTTPS
samples without treating an intended failure as an observer-script failure.
This stateless service needs no database restore. A real incompatible schema,
external payment or stored state could make image-only rollback unsafe. A
compatible expand/migrate/contract approach keeps both old and new code working
during migration and delays destructive changes until rollback is no longer
needed. This assignment does not add a database.
\section{Outstanding Work and Cleanup Boundary}
Billy added A records for \texttt{staging} and \texttt{app}. On November 15,
Google and Cloudflare both returned \texttt{147.182.178.136} for each name,
with no AAAA answer. Codex validated the prepared Caddy additions, saved the
previous configuration and gracefully reloaded it while preserving the earlier
routes, allowlists, volumes and bind-mounted inode. Normal curl and Python TLS
checks confirmed trusted hostname-matching certificates, TLS 1.3 and HTTP 308
redirects. HTTPS currently returns 502 because the pricing backends have not
been deployed; this is not evidence of application health. Certificate and DNS
details are recorded in \path{delivery/evidence/https-20261115.md}. Existing
Gitea/Jenkins/Grafana checks still passed. The public application port is HTTPS
443, with internal port 8000 remaining private. Distinct DNS hostnames satisfy
the planned routing boundary; successful application deployment remains outstanding.
PR~\#24 now includes the runner migration and HTTPS changes and is merged.
Issue creation, review/merge of the SSH correction, successful v1/v2 releases, production approvals,
both recovery demonstrations, final traceability and monitoring evidence, and
the final submission review remain outstanding. Local checks are not a
replacement for those executions.
After grading, only when instructed, retain required evidence and remove only
the two pricing projects, their routes, monitoring additions and test DNS.
Revoke their package tokens; retire deploy access and the delivery node/folder
after preserving job history. Do not prune Docker or use \texttt{down -v}.
Preserve earlier Gitea/Jenkins/proxy/monitoring services and all shared volumes.
The stopped laptop fallback, active remote agent, cache/identity volumes and protected remote backup are retained
while work and assessment remain in progress.
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Some files were not shown because too many files have changed in this diff Show More