diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a05388f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,5 @@ +# Docker/Jenkins shell scripts require Unix line endings on Windows checkouts. +delivery/**/*.sh text eol=lf + +# Preserve spaces emitted by tools in captured evidence. +delivery/evidence/*.txt -whitespace diff --git a/.gitignore b/.gitignore index 54d9b9a..a1b95c2 100644 --- a/.gitignore +++ b/.gitignore @@ -95,3 +95,9 @@ secrets.* # 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 diff --git a/Jenkinsfile b/Jenkinsfile index 979f6dc..df1dad5 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -6,10 +6,22 @@ pipeline { steps { checkout scm } } stage('Syntax check') { - steps { sh 'python3 -m py_compile pricing.py' } + 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' } + steps { + sh 'python3 -m unittest discover -s tests -v' + sh 'python3 -B -m unittest discover -s delivery/ci -p "test_controls.py" -v' + } } } } diff --git a/delivery/.dockerignore b/delivery/.dockerignore new file mode 100644 index 0000000..404f8bc --- /dev/null +++ b/delivery/.dockerignore @@ -0,0 +1,4 @@ +**/__pycache__ +**/.venv +**/*.pyc +agent/.env diff --git a/delivery/EVIDENCE.md b/delivery/EVIDENCE.md new file mode 100644 index 0000000..22bd696 --- /dev/null +++ b/delivery/EVIDENCE.md @@ -0,0 +1,36 @@ +# Preparation evidence — not completed release evidence + +All timestamps below are UTC on 14 November 2026. No assessed application +release, image publication, production approval or rollback has occurred yet. + +| Check | Actual result | +|---|---| +| 19:50 user-run original target baseline | 961 MiB RAM, 126 MiB available, 752 MiB swap used; deploy account absent | +| 20:15 post-resize SSH check | 1,967 MiB RAM, 1,008 MiB available, 101 MiB swap used; disk unchanged; seven containers up; zero failed systemd units | +| Post-maintenance external HTTPS | Gitea, Jenkins and Grafana login routes each returned HTTP 200 from laptop | +| 20:04 local runtime smoke | Gunicorn, UID 10001, read-only root/capability drops, 64 MiB cap; health v1, explicit `uncommitted-preflight` identity, total 30, invalid input HTTP 400 | +| 19:55 synthetic secret gate | Blocked; actual scanner detected the generated fixture; exit status 1 | +| 20:27 controlled wrong-price test | Three original tests passed; extra expected=-1 assertion failed; exit status 1 | +| 20:40 restored local app baseline | Three tests passed; exit status 0 | +| 20:32 full runtime image gate | Passed, zero HIGH/CRITICAL findings; full JSON and tool/database metadata retained | +| 21:00–21:01 final source/dependency gate | Passed; source scanner and pip-audit exit status 0 | +| Linux regression/syntax checks | Existing two tests and 12 delivery-control tests passed; Ansible syntax passed | +| Jenkins/Compose validation | Dedicated delivery pipeline validated using installed declarative parser; final agent Compose configuration validated | +| Proxy/monitoring candidates | Installed Caddy validation and Prometheus promtool syntax checks passed; candidates were not reloaded or applied | +| 20:40:49 Jenkins bootstrap | Exclusive node and folder-scoped credentials created; pricing release job disabled; earlier jobs retained | +| 20:42:28 agent connection | WebSocket opened; agent connected; no agent host port published | +| 20:46 agent prerequisite build 1 | SUCCESS; real Jenkins credential binding, pinned SSH host key, deploy login, sudo, Python/Docker/Compose prerequisites | + +The final preflight image was local only, tagged +`ssw590-pricing:preflight-v1-runtime`. It is not a reviewed source release or +published registry RepoDigest. Earlier Debian and installer-containing Alpine +image scans were blocked and retained; no security exception was added. + +Raw local reports: ignored `build/evidence/assignment8-local/`. Publicly +versioned prerequisite inventory: `evidence/agent-preflight-1.txt`. +Jenkins evidence: [build 1](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/) +and its [tool inventory artifact](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/artifact/build/preflight/tools-and-target.txt). +Jenkins requires existing approved-network access and login as applicable. + +Remaining assessed evidence must come from actual reviewed v1/v2 pipeline +runs, not these local checks. See `ISSUE.md` and `RUNBOOKS.md`. diff --git a/delivery/ISSUE.md b/delivery/ISSUE.md new file mode 100644 index 0000000..0cae33f --- /dev/null +++ b/delivery/ISSUE.md @@ -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. diff --git a/delivery/Jenkinsfile b/delivery/Jenkinsfile new file mode 100644 index 0000000..4045998 --- /dev/null +++ b/delivery/Jenkinsfile @@ -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) + } + } +} diff --git a/delivery/PR.md b/delivery/PR.md new file mode 100644 index 0000000..d10156f --- /dev/null +++ b/delivery/PR.md @@ -0,0 +1,20 @@ +# Prepare secure delivery and rollback for Assignment 8 + +The existing CI checks code but does not publish or promote an application. +Add the instructor's pricing service with locked inputs and a trusted-agent +pipeline for security gates, digest-based staging/production deployment, +unchanged Ansible reruns, recorded human approval and recovery operations. +Keep the earlier PR job separate from folder-scoped deployment credentials. + +Include the reproducible agent/bootstrap, scan policy, runbooks, actual +prerequisite evidence and a clearly marked preparation chapter. Proxy and +monitoring additions are prepared for later application after DNS and health +are ready. The release job is configured but disabled until reviewed source +reaches main. Assessed v1/v2 promotions and both recovery exercises remain +pending and will require separate reviewed changes and execution evidence. + +Validation: two existing tests, three Flask tests, twelve control tests; +controlled test/secret blocks; passing source/dependency and runtime-image +gates; Ansible syntax, agent Compose and installed Jenkins parser checks; +successful trusted-agent prerequisite build 1, including pinned deployment SSH +and noninteractive sudo. No production approval or completed release is claimed. diff --git a/delivery/README.md b/delivery/README.md new file mode 100644 index 0000000..4145b1a --- /dev/null +++ b/delivery/README.md @@ -0,0 +1,88 @@ +# Secure Delivery and Rollback — Assignment 8 + +The active application starts with the instructor's Startup Pricing Service +v1 from `Examples.zip`, `Examples/dosSecureDelivery/v1/`. The deployment +starters come from that bundle's `ansible/` directory. The task follows +Chapter 6 of instructor manual version 1.43. + +`app/` contains the Flask/Gunicorn service, nine exact direct/transitive +dependencies, and a pinned Python 3.13 Alpine base digest for Linux/amd64. +The inventory selects The-Ocean's dedicated deploy account. The example +release record remains explicitly an example; real registry digests will be +generated by Jenkins after the source has been reviewed and merged. + +Run the tests from `app/` after installing its requirements into the selected +Linux test environment. The expected v1 result for three units is USD 30. +The later v2 source/test change will be a separate reviewed commit and will +return USD 36. The source commit must be baked into each built image. + +Deployment work uses a dedicated trusted Jenkins agent, immutable images +in the existing Gitea registry, and separate Ansible-managed staging and +production Compose projects. The agent requires Docker build capability, +Python, Ansible, the Docker collection, and the selected security scanners. +Registry publication, staging deployment, approval, production promotion, +and both recovery exercises require dated execution evidence. + +## Attribution and preparation record + +On 14 November 2026 Vincent asked Codex to review the assignment and begin +preparation while he started Docker Desktop. Codex checked the repository's +AI requirements and usage guide, read Chapter 6 and the example sources, +verified remote main `8beefde`, and created branch +`codex/assignment8-secure-delivery`. It copied the v1 and Ansible starters +without changing their contents and checked Python syntax. This preparation +record will be consolidated into the manual's AI assistance log when the +assignment chapter is authored. The instructor retains authorship of the +starter application and playbook. + +## Verified preparation, 14 November 2026 + +The existing two pricing tests, three new Flask tests and twelve release/control +tests passed. The deliberate wrong-price assertion failed as intended; the +synthetic secret fixture blocked its gate. Pip-audit passed for the nine locked +application dependencies. The full Trivy runtime-image gate reported no HIGH +or CRITICAL findings. Earlier failed scans remain in ignored local evidence; +no scanner exception was introduced. A non-root Gunicorn container passed +health, identity, pricing and invalid-input checks with a 64 MiB memory cap. + +The droplet now has 2 GiB RAM and its original 25 GB plan disk. Vincent resized +it and installed package updates. The existing seven service containers and +their HTTPS routes were verified after maintenance. + +The trusted laptop node `ssw590-vince-delivery` is online over outbound +HTTPS/WebSocket, with one exclusive executor and label `delivery-trusted`. +[Agent prerequisite build 1](https://ci.yebilly.me/job/secure-delivery/job/agent-preflight/1/) +passed using the dedicated deploy key, pinned host key and root sudo. Its +non-secret tool inventory is versioned in `evidence/agent-preflight-1.txt`. +The `secure-delivery/pricing` job loads `delivery/Jenkinsfile` from protected +main and is disabled pending reviewed source. Release credentials are scoped +to that Jenkins folder; the PR job does not bind them or the Docker socket. + +The deployment account has root-only passwordless sudo: effective host +administration privileges, restricted to reviewed delivery code. Distinct +package-write and package-read tokens under `vsun1` are stored in Jenkins and +root's target Docker configuration respectively. No values are in Git. +Local agent identity and workspace live in named Docker volumes outside Git. +Run `./delivery/bootstrap/start-agent.ps1` with Docker Desktop and the SSH key +loaded in Windows ssh-agent to reconnect. Stop with +`docker compose -f delivery/agent/compose.yaml stop` when unused. + +Ansible syntax, agent Compose configuration, and the installed Jenkins +controller's declarative parser checks passed. These are preparation checks; +**v1/v2 registry releases, promotion and recovery are not yet demonstrated**. + +## Remaining checkpoints + +Vincent creates the issue, commits/pushes this branch, and obtains Billy's PR +review. Keep main protection. Billy/domain owner must add A records `staging` +and `app`, both pointing to `147.182.178.136`; distinct DNS names are required. +The prepared Caddy additions are not yet applied to the server. Enable the +release job after the reviewed source reaches main, then follow `RUNBOOKS.md`. +Keep the laptop awake during runs. Production approval requires an authorized +human; an agent must not approve unattended. + +`SECURITY.md` defines the gate policy. `bootstrap/` makes administrator setup +reviewable; its one-time script refuses to overwrite existing deployment state. +Raw local reports remain under ignored `build/evidence/assignment8-local/`. +The manual records material AI assistance and distinguishes pending work from +actual evidence. This preparation is not ready for assignment submission. diff --git a/delivery/RUNBOOKS.md b/delivery/RUNBOOKS.md new file mode 100644 index 0000000..f85653e --- /dev/null +++ b/delivery/RUNBOOKS.md @@ -0,0 +1,124 @@ +# Release, recovery and cleanup + +These are execution instructions, not completed release evidence. + +## Authority and preparation + +Billy reviews code; Vincent commits/pushes. Jenkins users `billy` or `vsun1` +may approve production interactively; administrators retain override authority. +The laptop agent must be online and source/configuration commits reviewed and +merged into protected main. Do not run untrusted PR/fork code with its Docker +socket or the delivery folder's credentials. Exclusive scheduling alone does +not prevent someone authorized to alter jobs from selecting the node. + +Confirm A records `staging` and `app` point to The-Ocean. Validate and reload +the prepared additions to `/root/gitea/Caddyfile`, preserving the earlier file, +allowlist environment and volumes. Publish no application host port. The +applications join the existing `gitea_web` network with different aliases. +Enable `secure-delivery/pricing` after reviewed source reaches main. + +The installed-binary validation commands are: + +```text +docker exec gitea-caddy-1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile +docker exec gitea-caddy-1 caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile +docker exec monitoring-prometheus-1 promtool check config /etc/prometheus/prometheus.yml +``` + +Preserve bind-mounted file inodes when copying new contents. Apply monitoring +only after healthy production, then reload using its existing documented +procedure. The temporary candidate checks already passed without a reload. + +## v1 and v2 + +1. Run MODE `blocked-test`: the wrong-price fixture must fail and prevent + publication/deployment. Run MODE `blocked-secret`: the generated synthetic + fixture must block the scanner gate. Fixtures exist only during those runs. +2. Run MODE `release` with the full reviewed v1 SOURCE_COMMIT if needed. Tests, + dependency/secret checks and image gates must pass. The commit-tagged image + is built once, scanned, pushed/pulled, and selected by exact registry digest. + Existing commit tags are reused, not overwritten. Full reports are archived. +3. Staging checks health, version, source SHA and total 30. Its unchanged rerun + must report changed=0; the pipeline blocks otherwise. +4. Review the presented release metadata, archived scans and staging results. + An authorized human approves within 20 minutes. Rejection/timeout stops + production. The actual approval identity/UTC is archived. Production uses + the same digest and verifies all three endpoints; it does not rebuild. +5. Save both generated v1 JSON records from Jenkins into `delivery/releases/` + and review/commit them before recovery. Never invent a digest or commit SHA. +6. Apply the supplied v2 application/test changes in a separate reviewed commit: + VERSION=v2, UNIT_PRICE=12, expected total=36. Repeat the complete release and + real approval. Preserve v1 images/configuration/records; save v2 records. + +## Healthy production rollback + +Record the detection/decision UTC and reason. Before approval, start the laptop +observer, for example: + +```text +python delivery/ci/observe.py --url https://app.yebilly.me --seconds 600 --output build/evidence/assignment8/rollback-health.csv +``` + +Run MODE `rollback-production` with committed +`delivery/releases/v1-production.json`. SOURCE_COMMIT can stay on main: the +record selects the exact historical image and configuration. Review/approve +the input. Ansible restores playbook/template using `git archive` of the +configuration commit, then verifies v1, its original SHA and total 30. +Archive decision, approval, deployment start/completion/elapsed time and the +observer CSV. Report failed samples and gaps; no failed samples does not prove +zero interruption between requests. Correlate the 30-second monitoring samples. + +## Failed staging deployment and recovery + +After v2 succeeds, add this staging-only override to the app service in +`ansible/templates/compose.yaml.j2` in a separate reviewed configuration commit: + +```jinja2 +{% if target_env == 'staging' %} + command: ["gunicorn", "--bind", "0.0.0.0:8001", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"] +{% endif %} +``` + +The image's healthcheck still probes 8000. Select MODE `staging-failure`, the +committed good v2 staging record, and full STAGING_FAILURE_CONFIG SHA. Compose +wait must fail within its 90-second bound and stop Jenkins before production. +Do not use MODE `release` to build an image for this configuration exercise. +Restore/review the correct template, then use MODE `recover-staging` with the +original good v2 staging record and matching configuration commit. Verify +health, exact source SHA, total 36 and changed=0. Retain failure, restoration, +recovery reports and observer timing. Do not alter earlier infrastructure to +manufacture a failure. + +## Monitoring and limits + +After production is healthy, add `https://app.yebilly.me/health` to the existing +Prometheus `https` job and display it in Grafana. Keep Gitea/Jenkins probes and +host metrics. Validate configuration before reload. Record actual samples and +alerts around releases/recovery; a short failure can fall between scrapes or +below the alert duration. HTTP status cannot validate the expected price. + +Each stateless app is capped at 64 MiB RAM, 96 MiB RAM+swap, 0.25 CPU and 64 +PIDs, with a read-only root filesystem, 16 MiB /tmp tmpfs, UID 10001 and all +capabilities dropped. The laptop agent is capped at 2 GiB/2 CPU. One droplet +and a shared proxy network provide neither high availability nor strong lateral +isolation. A real database migration or external payment can invalidate image +rollback; use compatible expand/migrate/contract changes and tested backups. + +## After grading, only when instructed + +Archive required evidence first. Remove only the two pricing Compose projects, +their routes, monitoring additions and test DNS names. Revoke the two named +Assignment 8 package tokens, then remove the deploy key/sudo grant and its +Jenkins folder/node when no longer needed. Preserve required job history before +removing configuration. Stop the local agent; remove only its identity/workspace +volumes after approval. Preserve Gitea, Jenkins home, proxy storage, monitoring +volumes and earlier assignments. Never system-prune or use `down -v` here. + +## Bootstrap recovery + +The protected `/root/ssw590-delivery-bootstrap/` directory contains metadata, +a consistent Jenkins-home archive and a Gitea SQLite backup taken before token +creation. Metadata records token names, not values. Transient private inputs +are erased after Jenkins encrypts them. If setup fails partway, inspect its +marker/logs and existing state rather than rerunning or rotating credentials. +Do not restore entire volumes/databases over later work without a reviewed plan. diff --git a/delivery/SECURITY.md b/delivery/SECURITY.md new file mode 100644 index 0000000..3e69cce --- /dev/null +++ b/delivery/SECURITY.md @@ -0,0 +1,31 @@ +# Release security policy + +Policy selected before the assessed scans on 14 November 2026. + +- Block every detected repository secret. Use Trivy's built-in rules together + with the course synthetic-fixture rule in `trivy-secret.yaml`. +- Block HIGH and CRITICAL image vulnerabilities, including issues without a + published fix. Retain the full report, including lower severities, for review. +- Block every Python dependency advisory reported by pip-audit. Review direct + and transitive dependencies and update the exact lock before rebuilding. +- A scanner execution error, unavailable advisory service, unavailable + vulnerability database, malformed report, or missing report fails the gate. +- No exceptions are currently approved. An exception requires instructor + acceptance, an advisory identifier, owner, rationale, compensating controls, + and expiry recorded with the release. Findings must never be silently ignored. +- For a suspected false positive, retain the report and record the evidence + used for triage. Keep the release blocked until the finding is resolved or + an instructor-approved exception is recorded. + +Each release archives UTC scan times, tool versions, Trivy database metadata, +commands, exit codes, reports, source commit, and the selected image digest. +Rebuild and rescan after changing a dependency or base image. + +The synthetic fixture is generated only for a deliberate blocked-gate run. +Its label identifies course test data and has no credential authority. Remove +the fixture and repeat the gate before a release can proceed. + +The deployment agent has administrative Docker access to the laptop's Linux +VM and deployment privileges on the droplet. Run reviewed delivery code on +this agent. Pull-request jobs must not receive its Docker socket or release +credentials. The agent connects to Jenkins over outbound HTTPS/WebSocket. diff --git a/delivery/agent/Dockerfile b/delivery/agent/Dockerfile new file mode 100644 index 0000000..9ee1c17 --- /dev/null +++ b/delivery/agent/Dockerfile @@ -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 diff --git a/delivery/agent/compose.yaml b/delivery/agent/compose.yaml new file mode 100644 index 0000000..c580e80 --- /dev/null +++ b/delivery/agent/compose.yaml @@ -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 diff --git a/delivery/agent/requirements.in b/delivery/agent/requirements.in new file mode 100644 index 0000000..bd67867 --- /dev/null +++ b/delivery/agent/requirements.in @@ -0,0 +1,2 @@ +ansible-core==2.21.6 +pip-audit==2.10.1 diff --git a/delivery/agent/requirements.txt b/delivery/agent/requirements.txt new file mode 100644 index 0000000..00e377a --- /dev/null +++ b/delivery/agent/requirements.txt @@ -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 diff --git a/delivery/agent/resolve-tools.sh b/delivery/agent/resolve-tools.sh new file mode 100644 index 0000000..0aa70c7 --- /dev/null +++ b/delivery/agent/resolve-tools.sh @@ -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 diff --git a/delivery/ansible/deploy.yml b/delivery/ansible/deploy.yml new file mode 100644 index 0000000..7f738f6 --- /dev/null +++ b/delivery/ansible/deploy.yml @@ -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" diff --git a/delivery/ansible/inventory.ini b/delivery/ansible/inventory.ini new file mode 100644 index 0000000..184c7b8 --- /dev/null +++ b/delivery/ansible/inventory.ini @@ -0,0 +1,3 @@ +[delivery] +# The SSH host key must be verified and supplied by the trusted delivery job. +startup ansible_host=147.182.178.136 ansible_user=deploy ansible_python_interpreter=/usr/bin/python3 diff --git a/delivery/ansible/release.example.yml b/delivery/ansible/release.example.yml new file mode 100644 index 0000000..42cee62 --- /dev/null +++ b/delivery/ansible/release.example.yml @@ -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 diff --git a/delivery/ansible/requirements.yml b/delivery/ansible/requirements.yml new file mode 100644 index 0000000..0206fe4 --- /dev/null +++ b/delivery/ansible/requirements.yml @@ -0,0 +1,5 @@ +collections: + - name: community.docker + version: "5.4.0" + - name: community.library_inventory_filtering_v1 + version: "1.1.5" diff --git a/delivery/ansible/templates/compose.yaml.j2 b/delivery/ansible/templates/compose.yaml.j2 new file mode 100644 index 0000000..033995f --- /dev/null +++ b/delivery/ansible/templates/compose.yaml.j2 @@ -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 }}" diff --git a/delivery/app/.dockerignore b/delivery/app/.dockerignore new file mode 100644 index 0000000..e1b2920 --- /dev/null +++ b/delivery/app/.dockerignore @@ -0,0 +1,4 @@ +__pycache__ +.venv +.git +*.pyc diff --git a/delivery/app/Dockerfile b/delivery/app/Dockerfile new file mode 100644 index 0000000..5c1cccd --- /dev/null +++ b/delivery/app/Dockerfile @@ -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"] diff --git a/delivery/app/app.py b/delivery/app/app.py new file mode 100644 index 0000000..1ea1194 --- /dev/null +++ b/delivery/app/app.py @@ -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") diff --git a/delivery/app/requirements.in b/delivery/app/requirements.in new file mode 100644 index 0000000..a01e4ac --- /dev/null +++ b/delivery/app/requirements.in @@ -0,0 +1,3 @@ +# Instructor compatibility ranges. requirements.txt locks the assessed versions. +Flask>=3.1,<3.2 +gunicorn>=23,<24 diff --git a/delivery/app/requirements.txt b/delivery/app/requirements.txt new file mode 100644 index 0000000..2a49561 --- /dev/null +++ b/delivery/app/requirements.txt @@ -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 diff --git a/delivery/app/test_app.py b/delivery/app/test_app.py new file mode 100644 index 0000000..40b4207 --- /dev/null +++ b/delivery/app/test_app.py @@ -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() diff --git a/delivery/bootstrap/configure_jenkins.groovy b/delivery/bootstrap/configure_jenkins.groovy new file mode 100644 index 0000000..dc2ac0b --- /dev/null +++ b/delivery/bootstrap/configure_jenkins.groovy @@ -0,0 +1,79 @@ +// One-time bootstrap loaded from Jenkins home after an authorized host setup. +// Never print secret values. Scope release credentials to the delivery folder. +import jenkins.model.Jenkins +import hudson.model.Node +import hudson.slaves.DumbSlave +import hudson.slaves.JNLPLauncher +import hudson.slaves.RetentionStrategy +import com.cloudbees.hudson.plugins.folder.Folder +import com.cloudbees.plugins.credentials.CredentialsProvider +import com.cloudbees.plugins.credentials.CredentialsScope +import com.cloudbees.plugins.credentials.SecretBytes +import com.cloudbees.plugins.credentials.domains.Domain +import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl +import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey +import org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl +import org.jenkinsci.plugins.workflow.job.WorkflowJob +import org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition +import hudson.plugins.git.GitSCM +import hudson.plugins.git.UserRemoteConfig +import hudson.plugins.git.BranchSpec +import groovy.json.JsonOutput + +def j = Jenkins.get() +def inputs = new File(j.rootDir, 'delivery-bootstrap') +def done = new File(inputs, 'configured.json') +if (done.exists()) return +assert j.getItem('secure-delivery') == null : 'Existing folder requires review' +assert j.getNode('ssw590-vince-delivery') == null : 'Existing node requires review' +def folder = j.createProject(Folder, 'secure-delivery') +folder.description = 'Assignment 8: reviewed releases only; folder-scoped deployment credentials.' +folder.save() +def store = CredentialsProvider.lookupStores(folder).find { it.context == folder } +assert store != null : 'Folder credential store unavailable' +def scope = CredentialsScope.GLOBAL +def credential = new UsernamePasswordCredentialsImpl(scope, 'delivery-registry-write', + 'Assignment 8 package-write only; vsun1; revoke after grading', 'vsun1', + new File(inputs, 'registry-write').text.trim()) +assert store.addCredentials(Domain.global(), credential) +def key = new BasicSSHUserPrivateKey(scope, 'delivery-deploy-ssh', 'deploy', + new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(new File(inputs, 'deploy_ed25519').text), + '', 'Assignment 8 deploy account; root sudo; reviewed releases only') +assert store.addCredentials(Domain.global(), key) +def knownHosts = new FileCredentialsImpl(scope, 'delivery-known-hosts', + 'The-Ocean ED25519 host key verified through existing pinned administrator SSH', + 'known_hosts', SecretBytes.fromBytes(new File(inputs, 'known_hosts').bytes)) +assert store.addCredentials(Domain.global(), knownHosts) +def launcher = new JNLPLauncher() +launcher.setWebSocket(true) +def node = new DumbSlave('ssw590-vince-delivery', 'Trusted laptop Docker/Ansible delivery agent', + '/home/jenkins/agent', '1', Node.Mode.EXCLUSIVE, 'delivery-trusted', launcher, + new RetentionStrategy.Always(), []) +j.addNode(node) +def secret = new File(inputs, 'agent-secret') +secret.text = node.toComputer().getJnlpMac() + '\n' +secret.setReadable(false, false) +secret.setWritable(false, false) +secret.setReadable(true, true) +secret.setWritable(true, true) +def job = folder.createProject(WorkflowJob, 'pricing') +def scm = new GitSCM( + [new UserRemoteConfig('https://git.yebilly.me/ssw590-group1/vpn-dns-gateway.git', null, null, 'gitea-jenkins-bot')], + [new BranchSpec('*/main')], false, [], null, null, []) +def definition = new CpsScmFlowDefinition(scm, 'delivery/Jenkinsfile') +definition.lightweight = true +job.definition = definition +job.description = 'Reviewed protected-main code only. Enable after the Assignment 8 source is reviewed and merged.' +job.disabled = true +job.save() +done.text = JsonOutput.prettyPrint(JsonOutput.toJson([ + configured_at: new Date().format("yyyy-MM-dd'T'HH:mm:ssXXX", TimeZone.getTimeZone('UTC')), + node: node.nodeName, label: 'delivery-trusted', executors: 1, exclusive: true, + job: job.fullName, disabled: true, credential_scope: folder.fullName, + credential_ids: ['delivery-registry-write', 'delivery-deploy-ssh', 'delivery-known-hosts'] +])) + '\n' +['registry-write', 'deploy_ed25519', 'known_hosts'].each { name -> + assert new File(inputs, name).delete() : "Could not remove transient bootstrap input ${name}" +} +assert new File(j.rootDir, 'init.groovy.d/ssw590-delivery.groovy').delete() +println('Assignment 8 delivery configuration complete; secret values were not printed; job is disabled.') diff --git a/delivery/bootstrap/preflight.Jenkinsfile b/delivery/bootstrap/preflight.Jenkinsfile new file mode 100644 index 0000000..34ef202 --- /dev/null +++ b/delivery/bootstrap/preflight.Jenkinsfile @@ -0,0 +1,34 @@ +// Administrator preparation only: no checkout, image publication or deployment. +pipeline { + agent { label 'delivery-trusted' } + options { disableConcurrentBuilds(); timeout(time: 5, unit: 'MINUTES') } + stages { + stage('Tool and target prerequisites') { + steps { + withCredentials([ + sshUserPrivateKey(credentialsId: 'delivery-deploy-ssh', keyFileVariable: 'DEPLOY_KEY'), + file(credentialsId: 'delivery-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS') + ]) { + sh '''set -eu +set +x +mkdir -p build/preflight +{ +date -u +id +python3 --version +ansible --version +ansible-galaxy collection list +docker --version +docker compose version +trivy --version +pip-audit --version +ssh -i "$DEPLOY_KEY" -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o "UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS" deploy@147.182.178.136 'id; sudo -n true; python3 --version; sudo -n docker --version; sudo -n docker compose version; free -m; nproc; df -h /' +} > build/preflight/tools-and-target.txt +cat build/preflight/tools-and-target.txt +''' + } + } + } + } + post { always { archiveArtifacts(artifacts: 'build/preflight/**', allowEmptyArchive: true) } } +} diff --git a/delivery/bootstrap/prepare_host.py b/delivery/bootstrap/prepare_host.py new file mode 100644 index 0000000..5d7f2cb --- /dev/null +++ b/delivery/bootstrap/prepare_host.py @@ -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() diff --git a/delivery/bootstrap/start-agent.ps1 b/delivery/bootstrap/start-agent.ps1 new file mode 100644 index 0000000..f83da97 --- /dev/null +++ b/delivery/bootstrap/start-agent.ps1 @@ -0,0 +1,24 @@ +param( + [string]$Droplet = '147.182.178.136', + [string]$IdentityFile = (Join-Path $env:USERPROFILE '.ssh/digitalocean') +) +$ErrorActionPreference = 'Stop' +$PSNativeCommandUseErrorActionPreference = $true +$repoPath = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path +$sshArguments = @('-i', $IdentityFile, '-o', 'IdentitiesOnly=yes', '-o', 'BatchMode=yes', + '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10', "root@$Droplet") +& ssh @sshArguments 'docker exec -u jenkins gitea-jenkins-1 test -f /var/jenkins_home/delivery-bootstrap/configured.json' +& docker volume create ssw590-delivery-identity | Out-Null +# The generated identity flows directly from pinned administrator SSH into a +# protected Docker volume. No secret enters command arguments, output or Git. +& ssh @sshArguments 'docker exec -u jenkins gitea-jenkins-1 cat /var/jenkins_home/delivery-bootstrap/agent-secret' | + & docker run --rm -i --network none --user 0:0 --entrypoint sh ` + --mount 'type=volume,source=ssw590-delivery-identity,target=/identity' ` + ssw590-delivery-agent:20261114 -c 'set -eu; umask 077; cat > /identity/agent-secret; test -s /identity/agent-secret; chown 1000:1000 /identity /identity/agent-secret; chmod 700 /identity; chmod 400 /identity/agent-secret' +Push-Location $repoPath +try { + & docker compose -f delivery/agent/compose.yaml up -d + & docker compose -f delivery/agent/compose.yaml ps +} finally { + Pop-Location +} diff --git a/delivery/ci/deploy.sh b/delivery/ci/deploy.sh new file mode 100644 index 0000000..94bf25d --- /dev/null +++ b/delivery/ci/deploy.sh @@ -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" diff --git a/delivery/ci/observe.py b/delivery/ci/observe.py new file mode 100644 index 0000000..ff29188 --- /dev/null +++ b/delivery/ci/observe.py @@ -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() diff --git a/delivery/ci/publish.sh b/delivery/ci/publish.sh new file mode 100644 index 0000000..92c2d15 --- /dev/null +++ b/delivery/ci/publish.sh @@ -0,0 +1,30 @@ +#!/bin/sh +set -eu +set +x +: "${REGISTRY_USER:?bind registry credentials}" +: "${REGISTRY_TOKEN:?bind registry credentials}" +image=git.yebilly.me/ssw590-group1/pricing +commit=$(git rev-parse HEAD) +reports=build/delivery/reports +mkdir -p "$reports" build/delivery/releases +export DOCKER_CONFIG +DOCKER_CONFIG=$(mktemp -d) +trap 'rm -rf "$DOCKER_CONFIG"' EXIT +printf '%s' "$REGISTRY_TOKEN" | docker login --username "$REGISTRY_USER" --password-stdin git.yebilly.me +# Never overwrite a source-commit tag during a retry. +if docker manifest inspect "$image:$commit" > "$reports/existing-manifest.json" 2> "$reports/manifest-check.log"; then + docker pull "$image:$commit" +else + if ! grep -Eqi 'manifest unknown|no such manifest|not found' "$reports/manifest-check.log"; then + cat "$reports/manifest-check.log" >&2 + exit 1 + fi + docker build --platform linux/amd64 --build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app + python3 delivery/ci/security.py image --image "$image:$commit" --reports "$reports/image-gate" + docker push "$image:$commit" + docker pull "$image:$commit" +fi +digest=$(docker image inspect "$image:$commit" --format '{{index .RepoDigests 0}}') +python3 delivery/ci/security.py image --image "$digest" --reports "$reports/published-image-gate" +printf '%s\n' "$digest" > "$reports/published-digest.txt" +python3 delivery/ci/release.py create --image "$digest" --build-url "$BUILD_URL" --output build/delivery/releases diff --git a/delivery/ci/release.py b/delivery/ci/release.py new file mode 100644 index 0000000..69f3242 --- /dev/null +++ b/delivery/ci/release.py @@ -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() diff --git a/delivery/ci/run-ansible.py b/delivery/ci/run-ansible.py new file mode 100644 index 0000000..b23b481 --- /dev/null +++ b/delivery/ci/run-ansible.py @@ -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()) diff --git a/delivery/ci/security.py b/delivery/ci/security.py new file mode 100644 index 0000000..0665508 --- /dev/null +++ b/delivery/ci/security.py @@ -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()) diff --git a/delivery/ci/test-app.sh b/delivery/ci/test-app.sh new file mode 100644 index 0000000..e988575 --- /dev/null +++ b/delivery/ci/test-app.sh @@ -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 diff --git a/delivery/ci/test_controls.py b/delivery/ci/test_controls.py new file mode 100644 index 0000000..192a2fd --- /dev/null +++ b/delivery/ci/test_controls.py @@ -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() diff --git a/delivery/evidence/agent-preflight-1.txt b/delivery/evidence/agent-preflight-1.txt new file mode 100644 index 0000000..f22c504 --- /dev/null +++ b/delivery/evidence/agent-preflight-1.txt @@ -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% / diff --git a/delivery/trivy-secret.yaml b/delivery/trivy-secret.yaml new file mode 100644 index 0000000..15fe537 --- /dev/null +++ b/delivery/trivy-secret.yaml @@ -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}' diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 6231fc5..96e7928 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -23,3 +23,13 @@ metrics.yebilly.me { 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 +} diff --git a/manual/latex/abstract.tex b/manual/latex/abstract.tex index 116fcfb..4a843a5 100644 --- a/manual/latex/abstract.tex +++ b/manual/latex/abstract.tex @@ -1,7 +1,12 @@ This group document records the SSW 590 coursework and its supporting -commands, designs, and evidence. Assignment 7 introduces site reliability +commands, designs, and evidence. Assignment 8 prepares secure delivery with +a trusted Jenkins agent, locked Flask/Gunicorn service, security gates, +Ansible, scoped deployment credentials and recovery runbooks. The prerequisite +job passed; reviewed v1/v2 publication, DNS/TLS, promotion, 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 1\,GiB +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 @@ -11,3 +16,5 @@ 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. diff --git a/manual/latex/devopsAIPromptLog.tex b/manual/latex/devopsAIPromptLog.tex index e1996ff..83ce298 100644 --- a/manual/latex/devopsAIPromptLog.tex +++ b/manual/latex/devopsAIPromptLog.tex @@ -779,3 +779,58 @@ 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. diff --git a/manual/latex/devopsAssignment.tex b/manual/latex/devopsAssignment.tex index 617254b..0d92b34 100644 --- a/manual/latex/devopsAssignment.tex +++ b/manual/latex/devopsAssignment.tex @@ -34,16 +34,16 @@ \definecolor{devopsLightBlue}{RGB}{232,240,247} % Replace these values for each assignment. -\newcommand{\AssignmentTitle}{Grafana and Prometheus SRE -- Group} -\newcommand{\AssignmentNumber}{7} -\newcommand{\DocumentVersion}{5.1} +\newcommand{\AssignmentTitle}{Secure Delivery and Rollback -- Group} +\newcommand{\AssignmentNumber}{8} +\newcommand{\DocumentVersion}{6.0} \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/28/2026} -\newcommand{\DueDate}{Friday by 11:59pm} +\newcommand{\DocumentDate}{11/14/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}{}{} @@ -148,6 +148,7 @@ \include{devopsAutomatedManualBuild} \include{devopsJenkins} \include{devopsSRE} +\include{devopsSecureDelivery} \include{devopsHostsPasswords} % Restore when a chapter cites devopsReferences.bib. diff --git a/manual/latex/devopsDocumentHistory.tex b/manual/latex/devopsDocumentHistory.tex index edd6042..641db93 100644 --- a/manual/latex/devopsDocumentHistory.tex +++ b/manual/latex/devopsDocumentHistory.tex @@ -12,6 +12,7 @@ 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 +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}\\ diff --git a/manual/latex/devopsHostsPasswords.tex b/manual/latex/devopsHostsPasswords.tex index 30a6294..50e3d72 100644 --- a/manual/latex/devopsHostsPasswords.tex +++ b/manual/latex/devopsHostsPasswords.tex @@ -19,6 +19,9 @@ 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 laptop Jenkins agent. Pricing DNS and deployments remain pending. \section{Hosts} \small @@ -36,8 +39,8 @@ since 28 Oct 2026 also the monitoring stack (Prometheus 3.15.1, Grafana OSS stopped with restart policy \texttt{no}; its Caddy route remains\\ Environment & Course production (team use)\\ Provider & DigitalOcean, NYC1; Ubuntu 24.04 LTS; 1 vCPU; resized from -512\,MB to the 1\,GiB Basic plan in October 2026 (961\,MiB reported, 25\,GB -plan disk); swap files \texttt{/swapfile} and \texttt{/swapfile2}, 1\,GiB +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 @@ -62,7 +65,9 @@ otherwise; monitoring ports 9090, 9100, 9115 not reachable\\ Owner & BY (server administration); VS (review)\\ HTTPS URLs & \url{https://git.yebilly.me}, \url{https://ci.yebilly.me/login}, \url{https://metrics.yebilly.me/login}\\ -Backup status & No backup job; container-replacement persistence verified for +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 @@ -89,6 +94,12 @@ Network path & Outbound HTTPS to \texttt{git.yebilly.me:443} and GitHub Actions 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\\ +Assignment 8 agent & Separate Jenkins node \texttt{ssw590-vince-delivery}, +label \texttt{delivery-trusted}, one exclusive executor; Docker/Python/Ansible/ +scanners in image \texttt{ssw590-delivery-agent:20261114}; 2\,GiB / 2 CPU cap; +outbound HTTPS/WebSocket to Jenkins. Docker socket access is administrative. +Identity in \texttt{ssw590-delivery-identity}, workspace/cache in +\texttt{ssw590-delivery-workspace}; prerequisite build 1 passed on November 14.\\ Monitoring / backup & Runner logs and Gitea Actions checked manually; no automatic backup of runner registration configured\\ \end{tabularx} \normalsize @@ -104,6 +115,18 @@ Monitoring / backup & Runner logs and Gitea Actions checked manually; no automat \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\\ +Jenkins delivery agent identity & VS & Protected Jenkins-generated identity and local Docker volume +\texttt{ssw590-delivery-identity}; outside Git & Trusted laptop agent; 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{jenkins-bot} (added 22 Oct 2026) & BY & BY's password manager; used only to create its token & Write collaborator on \texttt{vpn-dns-gateway}\\ diff --git a/manual/latex/devopsSecureDelivery.tex b/manual/latex/devopsSecureDelivery.tex new file mode 100644 index 0000000..8d8a202 --- /dev/null +++ b/manual/latex/devopsSecureDelivery.tex @@ -0,0 +1,251 @@ +\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. This version records preparation on November 14, not a completed +release exercise. \textbf{It is not ready for submission.} Reviewed v1/v2 +publication, promotion, production rollback, staging failure/recovery and +monitoring correlation remain pending. No approval, release digest or successful +deployment is inferred from a tool installation or local smoke test. + +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) {Vincent's laptop\\Trusted delivery agent\\Docker, scans and Ansible}; +\node[data,text width=3.8cm] (local) at (0,2.7) {Local Docker volumes\\\texttt{ssw590-delivery-identity}\\\texttt{ssw590-delivery-workspace}}; +\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=(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]{HTTPS}(jenkins); +\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 its Docker socket are on +the laptop, outside the droplet.} +\label{Figure:SecureDeliveryArchitecture} +\end{figure} + +The exclusive node \texttt{ssw590-vince-delivery} has one executor and label +\texttt{delivery-trusted}. It connects to Jenkins over HTTPS/WebSocket, with no +published agent or Docker API port. Docker socket membership (group 0 in the +Linux VM) grants administrative Docker control. 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. + +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 is currently disabled. +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.\\ +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.\\ +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. +Assessed Jenkins gate runs and published-image scans remain pending.\\ +\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 & Pending review and merge & Separate change pending\\ +Registry digest / Jenkins release build & Not published / not run & Not published / not run\\ +Staging + unchanged rerun & Pending & 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{Release, Recovery and Monitoring Runbooks} +The versioned \path{delivery/RUNBOOKS.md} gives the executable sequence. +Vincent handles commits/pushes; Billy reviews repository changes. Once reviewed +v1 is on main and DNS/TLS are ready, enable the delivery job, demonstrate +\texttt{blocked-test} and \texttt{blocked-secret}, then run \texttt{release}. +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} +The domain owner must create two A records: \texttt{staging} and \texttt{app}. +Both must point to \texttt{147.182.178.136}. Neither resolved during +preparation. Distinct DNS hostnames are an explicit instructor requirement, so +an existing-host path substitute is not described as equivalent. The prepared +Caddy additions must be validated and reloaded after DNS is correct, without +removing earlier routes or certificate storage. The public application port is +HTTPS 443, with internal port 8000 remaining private. + +The issue draft, feature branch and code are prepared locally. Issue creation, +commit/push, peer review/merge, both assessed 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 local agent, cache/identity volumes and protected remote backup are retained +while work and assessment remain in progress. diff --git a/monitoring/README.md b/monitoring/README.md index 79a8ed7..1f5f10b 100644 --- a/monitoring/README.md +++ b/monitoring/README.md @@ -1,5 +1,9 @@ # Monitoring (Assignment 7 / Instructor Manual Chapter 5) +Assignment 8 prepares a production pricing `/health` target and Grafana panel +in the versioned configuration. Apply those additions only after the service +is healthy; they are not yet deployed. See `../delivery/RUNBOOKS.md`. + Prometheus, Grafana OSS, Node Exporter, and Blackbox Exporter on the droplet **The-Ocean**, beside Gitea, Jenkins, and Caddy (`deploy/`). Grafana is the only web entry point: `https://metrics.yebilly.me` (same allowlist as Jenkins, then diff --git a/monitoring/grafana/dashboards/sre.json b/monitoring/grafana/dashboards/sre.json index f261489..83d7f06 100644 --- a/monitoring/grafana/dashboards/sre.json +++ b/monitoring/grafana/dashboards/sre.json @@ -12,7 +12,7 @@ "to": "now" }, "schemaVersion": 41, - "version": 1, + "version": 2, "editable": false, "graphTooltip": 1, "panels": [ @@ -557,6 +557,88 @@ "legendFormat": "{{job}} {{instance}}" } ] + }, + { + "id": 8, + "type": "timeseries", + "title": "Pricing production HTTPS availability (probe_success)", + "description": "1 = production /health returned 2xx with valid TLS; pricing and source identity are verified separately by the release pipeline.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, + "y": 30, + "w": 24, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "unit": "none", + "color": { + "mode": "palette-classic" + }, + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "lineInterpolation": "stepAfter", + "thresholdsStyle": { + "mode": "off" + } + }, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "min": 0, + "max": 1, + "mappings": [ + { + "type": "value", + "options": { + "0": { + "text": "DOWN", + "color": "red" + }, + "1": { + "text": "UP", + "color": "green" + } + } + } + ] + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "probe_success{job=\"https\",instance=\"https://app.yebilly.me/health\"}", + "legendFormat": "Pricing production" + } + ] } ], "annotations": { @@ -575,4 +657,4 @@ } ] } -} \ No newline at end of file +} diff --git a/monitoring/prometheus/prometheus.yml b/monitoring/prometheus/prometheus.yml index 76a9905..5a6167c 100644 --- a/monitoring/prometheus/prometheus.yml +++ b/monitoring/prometheus/prometheus.yml @@ -21,6 +21,8 @@ scrape_configs: - targets: - https://git.yebilly.me/user/login - https://ci.yebilly.me/login + # Apply this addition only after Assignment 8 production is healthy. + - https://app.yebilly.me/health relabel_configs: - source_labels: [__address__] target_label: __param_target