\chapter{Secure Delivery and Rollback} \ChapterLabel{SecureDelivery} \index{secure delivery}\index{rollback}\index{Ansible}\index{image digest} This chapter records how the team releases the Startup Pricing Service, proves which release is running, and recovers from a bad deployment, following Chapter~6 of \texttt{dosManual-V1.43}. It extends the Jenkins pipeline of \ChapterRef{JenkinsCI} and the monitoring stack of \ChapterRef{Monitoring} on the same AWS Lightsail instance \texttt{Gitea-Project} (\texttt{184.193.0.32}); Gitea, Jenkins, Caddy and the monitoring containers were reused, not reinstalled. Work is tracked in \href{https://git.590hcm.dev/SSW590Team/pricing-app/issues/7}{pricing-app issue~7} on branch \href{https://git.590hcm.dev/SSW590Team/pricing-app/src/branch/feature/issue-7-secure-delivery}{\texttt{feature/issue-7-secure-delivery}}. \textbf{Review status, December 1, 2026: draft. Configuration and the trusted agent are in place; no release has been deployed yet. Every result marked \StatusPending{} is still to be produced and must not be read as completed.} \begin{tabularx}{\linewidth}{L{0.5cm}L{4.4cm}L{1.9cm}Y} \caption{Chapter 6 Evidence Status by Rubric Row\label{Table:DeliveryStatus}}\\ \toprule \textbf{\#} & \textbf{Rubric row (points)} & \textbf{Status} & \textbf{Done / open}\\\midrule \endfirsthead \toprule \textbf{\#} & \textbf{Rubric row (points)} & \textbf{Status} & \textbf{Done / open}\\\midrule \endhead \bottomrule \endlastfoot 1 & Working v1/v2 service, tests, source identity, locked inputs (10) & \StatusPending & Dependencies and base image locked; v1 tests pass locally with the lock; passing and failing pipeline runs open.\\ 2 & Immutable publication and traceability; same digest promoted (10) & \StatusPending & Publish and digest-record stages written; first registry push open.\\ 3 & Ansible deployment, environment separation, HTTPS, unchanged rerun (20) & \StatusPending & Deploy account and agent ready (Dec.~1); DNS, Caddy routes, first deploy and \texttt{changed=0} rerun open.\\ 4 & Jenkins gates, restricted recorded approval, verified v2 promotion (15) & \StatusPending & Stages and approval step written; approver IDs and runs open.\\ 5 & Security scan policy, reports, blocked fixture, credential/access controls (15) & \StatusPending & Policy written (\autoref{sec:del-security}); scans, blocked fixture, tokens and Gitea account review open.\\ 6 & Both recovery cases, configuration restoration, measured verification (15) & \StatusPending & Redeploy mode and availability probe written; exercises open.\\ 7 & Monitoring correlation and operational/state limitations (5) & \StatusPending & Probe job and dashboard written, not yet applied; limitations drafted (\autoref{sec:del-limits}).\\ 8 & Manual, diagram, release records, links, runbooks (10) & \StatusPending & This draft; runbooks in \autoref{sec:del-runbooks}.\\ \end{tabularx} \section{Architecture and Access} \label{sec:del-architecture} \autoref{Figure:DeliveryArchitecture} shows the actual deployment. The Jenkins controller only schedules work (0 executors). The trusted agent container \texttt{jenkins-python-agent} runs every stage: it builds images through the host Docker socket, runs Ansible as the control node, and connects over SSH to the host's Docker bridge address \texttt{172.18.0.1} as the dedicated \texttt{deploy} account. Staging and production are separate Compose projects (\texttt{pricing-staging}, \texttt{pricing-production}) with separate directories under \path{/opt/startup/}, network aliases and HTTPS hostnames. They are stateless and have no data volume. \begin{figure}[htbp]\centering \begin{tikzpicture}[box/.style={draw,rounded corners,align=center,font=\scriptsize,inner sep=3pt,minimum width=2.4cm},new/.style={box,fill=devopsLightBlue},vol/.style={box,fill=black!8},lbl/.style={font=\tiny,inner sep=1.5pt},>=stealth] \node[box] (user) at (-6.3,0) {Team / grader\\browser}; \node[box] (caddy) at (-2.4,0) {Caddy 2.8.4\\TLS 443, routes git, ci,\\metrics, \textbf{staging, app}}; \node[box] (gitea) at (4.5,0) {Gitea 1.22.3\\source + OCI registry\\SQLite in /data}; \node[box] (jenkins) at (4.5,-1.9) {Jenkins 2.580.1\\controller, 0 executors}; \node[new] (stg) at (-4.3,-2.0) {pricing-staging\\Gunicorn :8000}; \node[new] (prd) at (-1.4,-2.0) {pricing-production\\Gunicorn :8000}; \node[new] (agent) at (4.5,-3.9) {Trusted agent \texttt{ch6-v1}\\Docker CLI, Ansible,\\Trivy, pip-audit}; \node[box,minimum width=4.4cm] (host) at (-2.9,-3.9) {Lightsail host (Ubuntu 24.04)\\Docker Engine 29.1.3, Compose 2.40.3\\\texttt{deploy} account, sshd}; \node[vol] (opt) at (-2.9,-5.7) {/opt/startup/pricing-\{env\}/compose.yaml}; \node[box] (mon) at (4.5,-5.7) {Prometheus + Blackbox\\+ Grafana (Chapter 5)}; \draw[->] (user)--node[lbl,above]{HTTPS}(caddy); \draw[->] (caddy)--node[lbl,above]{private}(gitea); \draw[->] (caddy.south)++(-0.6,0)--(stg.north); \draw[->] (caddy.south)++(0.4,0)--(prd.north); \draw[<->] (gitea)--node[lbl,right]{webhook / checkout}(jenkins); \draw[->] (jenkins)--node[lbl,right]{SSH launch}(agent); \draw[->] (agent.west)--node[lbl,above,align=center]{SSH as deploy\\to 172.18.0.1}(host.east); \draw[->,dashed] (agent.north east) to[bend right=40] node[lbl,right]{push / pull digest}(gitea.south east); \draw[->] (host.north)--++(0,0.55)-|node[lbl,above,pos=0.25]{compose up}(stg.south); \draw[->] (host.north)--++(0,0.55)-|(prd.south); \draw (host.south)--(opt.north); \draw[->,dashed] (mon.west)-|node[lbl,right,pos=0.86,align=left]{HTTPS\\/health\\probes}(1.0,-0.45)--(caddy.south east); \end{tikzpicture} \caption{Chapter 6 delivery on the existing Lightsail instance (draft; to be re-checked after the first release). Shaded: Chapter 6 additions. Gray: host bind-mount directory. Only Caddy publishes ports 80/443; Gitea, Jenkins, port~8000 of both pricing containers and the monitoring ports stay on private Docker networks.} \label{Figure:DeliveryArchitecture} \end{figure} \subsection{Public and Private Connections} \begin{tabularx}{\linewidth}{L{4.2cm}L{2.0cm}Y} \caption{Chapter 6 Connections\label{Table:DeliveryConnections}}\\ \toprule \textbf{Connection} & \textbf{Exposure} & \textbf{Control}\\\midrule \endfirsthead \toprule \textbf{Connection} & \textbf{Exposure} & \textbf{Control}\\\midrule \endhead \bottomrule \endlastfoot Browser $\rightarrow$ \texttt{staging.590hcm.dev}, \texttt{app.590hcm.dev} & Public 443 & Caddy TLS; reverse proxy to \texttt{pricing-staging:8000} / \texttt{pricing-production:8000} on \texttt{gitea-deploy\_internal}.\\ Pricing containers port 8000 & Private & Not published on the host (Compose template has no \texttt{ports}).\\ Agent $\rightarrow$ host SSH as \texttt{deploy} & Private bridge & Key accepted only \texttt{from="172.18.0.0/16"}; host key pinned in \path{ansible/known_hosts}.\\ Agent $\rightarrow$ host Docker socket & Container mount & Effectively root on the host; trusted agent only, fork pull requests never built.\\ Agent / host $\rightarrow$ Gitea registry & HTTPS & Package-write token on the agent, package-read token for root on the host.\\ \end{tabularx} \subsection{Deployment Rights} \begin{tabularx}{\linewidth}{L{3.6cm}Y} \caption{Who Can Approve, Deploy and Roll Back\label{Table:DeliveryRights}}\\ \toprule \textbf{Action} & \textbf{Who / mechanism}\\\midrule \endfirsthead \toprule \textbf{Action} & \textbf{Who / mechanism}\\\midrule \endhead \bottomrule \endlastfoot Change application or deployment files & Team members through a reviewed pull request into \texttt{main}.\\ Deploy staging & Jenkins automatically after merge to \texttt{main}; staging redeploys by a team member with Jenkins Build permission.\\ Approve production & Jenkins users listed in \texttt{APPROVERS} only (\StatusPending{} names to be recorded); 30-minute timeout.\\ Roll back production & Redeploy mode on \texttt{main} with the same restricted approval.\\ Host administration & Team members with their own SSH keys to \texttt{ubuntu}; the \texttt{deploy} account is used only by Jenkins.\\ \end{tabularx} \section{Installation and Version Inventory} \label{sec:del-inventory} Versions below were observed on December 1, 2026. The agent image writes the full list, including transitive Python packages, to \path{/opt/agent-versions.txt}. \begin{tabularx}{\linewidth}{L{4.2cm}L{4.0cm}Y} \caption{Chapter 6 Version Inventory\label{Table:DeliveryVersions}}\\ \toprule \textbf{Component} & \textbf{Version} & \textbf{Source / note}\\\midrule \endfirsthead \toprule \textbf{Component} & \textbf{Version} & \textbf{Source / note}\\\midrule \endhead \bottomrule \endlastfoot Host Docker Engine / Compose & 29.1.3 / 2.40.3 & Ubuntu packages; Compose meets the 2.18 minimum. Host has no buildx, so the agent image was built with the classic builder.\\ Host Python (Ansible target) & 3.12.3 & Ubuntu 24.04.\\ Agent base image & \texttt{jenkins/ssh-agent:jdk21} & Pinned by digest \texttt{sha256:5af828ce\ldots}.\\ Agent Python & 3.13.5 & Debian package \texttt{python3=3.13.5-1}.\\ Docker CLI / buildx & 29.10.0 / 0.39.0 & Copied from \texttt{docker:29.10.0-cli} (digest-pinned).\\ Trivy & 0.76.2 & Copied from \texttt{aquasec/trivy:0.76.2} (digest-pinned).\\ ansible-core / community.docker & 2.22.0 / 5.4.0 & Virtual environment \path{/opt/ansible-venv}.\\ pip-audit & 2.10.1 & Virtual environment \path{/opt/audit-venv}.\\ Application base image & \texttt{python:3.13.18-slim-trixie} & Pinned by index digest \texttt{sha256:e48f59cd\ldots}; Linux amd64 selected.\\ Application packages & Flask 3.1.3, gunicorn 23.0.0, Werkzeug 3.1.9, Jinja2 3.1.6, MarkupSafe 3.0.4, click 8.5.1, itsdangerous 2.2.0, blinker 1.9.0, packaging 26.3 & Hashed lock \path{app/requirements.txt}, installed with \texttt{--require-hashes}.\\ \end{tabularx} Repository files (branch \texttt{feature/issue-7-secure-delivery}; to be re-linked to \texttt{main} after merge): \href{https://git.590hcm.dev/SSW590Team/pricing-app/src/branch/feature/issue-7-secure-delivery/app}{\path{app/}} (application, tests, Dockerfile, lock), \href{https://git.590hcm.dev/SSW590Team/pricing-app/src/branch/feature/issue-7-secure-delivery/Jenkinsfile}{\path{Jenkinsfile}}, \href{https://git.590hcm.dev/SSW590Team/pricing-app/src/branch/feature/issue-7-secure-delivery/ansible}{\path{ansible/}} (playbook, inventory without secrets, Compose template), \href{https://git.590hcm.dev/SSW590Team/pricing-app/src/branch/feature/issue-7-secure-delivery/releases}{\path{releases/}} (release records) and \href{https://git.590hcm.dev/SSW590Team/pricing-app/src/branch/feature/issue-7-secure-delivery/deploy/CH6-SERVER-SETUP.md}{\path{deploy/CH6-SERVER-SETUP.md}} (server setup runbook). The unmodified instructor starter is commit \href{https://git.590hcm.dev/SSW590Team/pricing-app/commit/cca9ac5}{\texttt{cca9ac5}}, so every team change is visible as a diff from it. \section{Build Once and Trace Each Release} \label{sec:del-trace} Every branch runs the Chapter~4 tests, the application unit tests, pip-audit, a Trivy secret scan, the image build and a Trivy image scan. On \texttt{main} only, Jenkins pushes \texttt{git.590hcm.dev/ssw590team/pricing:\{commit\}}, pulls it back and records the repository digest; the staging and production release records are generated from that digest, so production receives the image staging tested, without a rebuild \cite{DockerDigests,GiteaContainerRegistry}. Concurrent builds are disabled. \begin{tabularx}{\linewidth}{L{3.4cm}YY} \caption{Release Traceability (to be completed from Jenkins reports)\label{Table:DeliveryTrace}}\\ \toprule \textbf{Item} & \textbf{v1} & \textbf{v2}\\\midrule \endfirsthead \toprule \textbf{Item} & \textbf{v1} & \textbf{v2}\\\midrule \endhead \bottomrule \endlastfoot Source commit & \StatusPending & \StatusPending\\ Configuration commit & \StatusPending & \StatusPending\\ Image digest & \StatusPending & \StatusPending\\ Jenkins build & \StatusPending & \StatusPending\\ Scan results (pip-audit, secrets, image) & \StatusPending & \StatusPending\\ Staging result (health, version, commit, total) & \StatusPending{} (expect total 30) & \StatusPending{} (expect total 36)\\ Approver / time (UTC) & \StatusPending & \StatusPending\\ Production result & \StatusPending & \StatusPending\\ Release records & \path{releases/v1-staging.yml}, \path{releases/v1-production.yml} & \path{releases/v2-staging.yml}, \path{releases/v2-production.yml}\\ \end{tabularx} \section{Security Gates and Access Controls} \label{sec:del-security} \paragraph{Policy (defined before the first release).} The build fails on: any secret detected by Trivy; any known vulnerability reported by pip-audit in the locked dependencies; any HIGH or CRITICAL image vulnerability; and any scanner error, including a vulnerability database that cannot be downloaded \cite{TrivyDocs,PipAudit}. Full reports (all severities) are archived with each build. An exception is allowed only as a dated entry in \path{.trivyignore.yaml} with the exact package, an expiry date, the reason, and the instructor's acceptance; it stops applying when it expires. Fixes are made by updating the lock or base image and rebuilding; false positives are documented the same way as exceptions. A green badge alone is not accepted as evidence. \paragraph{Blocked pipeline demonstration.} \StatusPending{} A synthetic, scanner-recognized test secret will be committed on a branch, shown to fail the secret gate, then removed, with the rerun passing. No live secret or deliberately vulnerable working image is used. \paragraph{Credentials and access.} \StatusPass{} The \texttt{deploy} account was created on December 1 with no password, a key restricted to the Docker bridge network, and \path{/etc/sudoers.d/90-ch6-deploy} (\texttt{NOPASSWD: ALL}, \texttt{visudo} parsed OK). Because Ansible runs generated Python as root, the rule cannot usefully be narrowed to single commands; the account is effectively a host administrator, limited by where its key is accepted, where it is stored (Jenkins credentials only) and which jobs use it \cite{AnsibleBecome,DockerDaemonSecurity}. \StatusPending{} Registry tokens (write for the agent, read for root on the host), Jenkins credentials \texttt{gitea-registry-write} and \texttt{lightsail-deploy-ssh}, the pinned host key, and approver IDs. \paragraph{Gitea account review.} \StatusPending{} While preparing registry tokens on December 1, the team found that Gitea self-registration is enabled and that several accounts not created by the team exist, including accounts with administrator rights. Credential setup was paused until the team confirms whether they are authorized; the outcome and any remediation will be recorded here. \section{Ansible Deployment and Idempotence} \label{sec:del-ansible} The supplied playbook validates the release record, renders \path{/opt/startup/pricing-\{env\}/compose.yaml}, applies the selected digest with \texttt{build: never} and \texttt{wait: true}, then checks HTTPS health, version, full commit and the total for three units \cite{AnsibleComposeV2}. The team added per-environment limits of 128~MB and 0.25 CPU to the Compose template for the shared 2~GB host. Each deployment runs through \path{ci/deploy_with_probe.sh}, which records start and finish times and polls \texttt{/health} every 0.5~s to measure observed interruption. \StatusPending{} v1 staging deployment; unchanged second run with \texttt{changed=0} (Jenkins redeploy mode with \path{releases/v1-staging.yml}); HTTPS health, version, commit and price evidence. \section{Approval and Promotion} \label{sec:del-approval} After staging passes, the pipeline stops at a Jenkins \texttt{input} step that shows the source commit, image digest, scan result and staging result. Only users in \texttt{APPROVERS} may answer; the step times out after 30 minutes and records the approver and UTC time \cite{JenkinsInputStep}. No agent executor is held while waiting. Rejection or timeout ends the run before production. \StatusPending{} v1 and v2 approvals and production results. \section{v2 Release and Recovery} \label{sec:del-recovery} \subsection{Healthy Release Rollback} \StatusPending{} After v2 is verified in both environments (total 36), production is rolled back by running Jenkins in redeploy mode with \texttt{RELEASE\_RECORD=releases/v1-production.yml} and \texttt{CONFIG\_COMMIT} set to the v1 configuration commit, after approval. Rollback restores the configuration as well as the image digest. \begin{tabularx}{\linewidth}{L{4.6cm}Y} \caption{Production Rollback Timeline (UTC)\label{Table:RollbackTimeline}}\\ \toprule \textbf{Event} & \textbf{Time / evidence}\\\midrule \endfirsthead \toprule \textbf{Event} & \textbf{Time / evidence}\\\midrule \endhead \bottomrule \endlastfoot Detection / decision & \StatusPending\\ Approval & \StatusPending\\ Rollback start (Ansible) & \StatusPending\\ Rollback finish & \StatusPending\\ Observed interruption (probe) & \StatusPending\\ Verification: v1, commit, health, total 30 & \StatusPending\\ Monitoring view & \StatusPending\\ \end{tabularx} \subsection{Failed Deployment Recovery (Staging Only)} \StatusPending{} In a separate configuration commit, the staging Compose service command is overridden to bind Gunicorn to port 8001 while the image healthcheck still probes 8000. The expected result is that Compose's wait fails and the Jenkins run stops. The previous reviewed configuration commit and its release record are then redeployed and HTTPS health and business behavior are re-verified. The host Docker daemon, proxy, Gitea and Jenkins are not altered, and no \texttt{docker compose down -v} or pruning is used. \section{Monitoring Correlation} \label{sec:del-monitoring} A Prometheus job \texttt{pricing} probes \texttt{https://app.590hcm.dev/health} (required) and \texttt{https://staging.590hcm.dev/health} through the existing Blackbox Exporter every 10~s, and the provisioned dashboard \path{monitoring/grafana/dashboards/chapter6.json} shows availability, HTTP status, probe duration and failed probes per environment \cite{BlackboxExporter}. The existing Gitea, Jenkins and host panels are kept. A failure shorter than the scrape interval can be missed; the pipeline's 0.5~s probe and smoke tests remain the evidence for version and price, which a status probe cannot validate. \StatusPending{} Apply after DNS and routes exist; correlate release and rollback times with observed probe results. \section{Limitations and State Compatibility} \label{sec:del-limits} \begin{itemize}[leftmargin=*] \item \textbf{Single failure domain.} Staging, production, Gitea, Jenkins and monitoring share one 2~GB Lightsail instance. Separate Compose projects do not provide high availability or tenant isolation; a host failure takes down both environments and the tools needed to recover them. On December 1 the host had about 600~MB of memory available and 0.8--1.0~GB of swap in use. \item \textbf{Shared proxy network.} Both pricing containers join \texttt{gitea-deploy\_internal}, the network that also carries Gitea and Jenkins. This is an accepted lab simplification with weaker lateral isolation than a dedicated network per environment. \item \textbf{Recreate downtime.} A deployment recreates the container, so a short interruption is expected and is measured rather than assumed to be zero. \item \textbf{Privileged automation.} The agent's Docker socket and the \texttt{deploy} account's sudo rule are both equivalent to host root. \item \textbf{Why image-only rollback can be unsafe with state.} This service is stateless, so redeploying the v1 digest and configuration fully restores v1. With a database, v2 might have run a migration (for example renaming a column or changing how a price is stored) that v1 cannot read; an external payment made under v2 cannot be undone by redeploying an image; and stored records written in a new format could be misread by old code. \item \textbf{A compatible migration approach.} Use expand and contract: first release a schema change that only adds (new nullable column or table) and code that writes both old and new forms; once every running version reads the new form, switch reads; remove the old form only in a later release after the rollback window has passed. Every release in the rollback window then works with the same data, so rolling back the image does not require rolling back the database. \end{itemize} \section{Runbooks} \label{sec:del-runbooks} \subsection{Release} \begin{enumerate}[leftmargin=*] \item Open a pull request into \texttt{main}; the branch build must pass tests and all security gates; a second team member reviews. \item Merge. Jenkins publishes the image, records the digest, deploys staging and runs smoke tests. \item An approver checks commit, digest, scan and staging results in the input prompt, then approves or rejects. \item After production smoke tests pass, commit the archived \path{reports/-.yml} files unchanged into \path{releases/} and record the release in \autoref{Table:DeliveryTrace}. \end{enumerate} \subsection{Failed Deployment} \begin{enumerate}[leftmargin=*] \item The playbook stops on a failed wait, health or behavior check; it never rolls back by itself. Read \path{reports/ansible-.log} and \path{reports/availability-.txt}. \item On the host, inspect without changing state: \texttt{sudo docker compose -p pricing- ps} and \texttt{sudo docker compose -p pricing- logs --tail 100}. \item Recover by redeploying the last good record and configuration (Rollback below). Do not change Gitea, Jenkins, Caddy or the Docker daemon. \end{enumerate} \subsection{Rollback} \begin{enumerate}[leftmargin=*] \item In Jenkins, open the \texttt{main} branch job and choose \emph{Build with Parameters}. \item Set \texttt{RELEASE\_RECORD} to the last good record (e.g.\ \path{releases/v1-production.yml}) and \texttt{CONFIG\_COMMIT} to the configuration commit that deployed it. \item For production, an approver approves the redeploy. Ansible applies the record; smoke tests verify version, commit, health and total. \item Record detection, decision, start, finish and observed interruption in \autoref{Table:RollbackTimeline}. \end{enumerate} \subsection{Cleanup (after grading, when instructed)} \begin{enumerate}[leftmargin=*] \item \texttt{sudo docker compose -p pricing-staging down} and the same for \texttt{pricing-production} (no \texttt{-v}; there are no volumes), then remove \path{/opt/startup/pricing-*}. \item Remove the two Caddy routes, validate and reload; delete the \texttt{staging} and \texttt{app} DNS records. \item Revoke both registry tokens, delete the Jenkins credentials, remove \path{/etc/sudoers.d/90-ch6-deploy} and the \texttt{deploy} account, and run \texttt{sudo docker logout git.590hcm.dev}. \item Keep Gitea, Jenkins, monitoring and every artifact needed for assessment. \end{enumerate}