diff --git a/secure-delivery/.dockerignore b/secure-delivery/.dockerignore new file mode 100644 index 0000000..e1b2920 --- /dev/null +++ b/secure-delivery/.dockerignore @@ -0,0 +1,4 @@ +__pycache__ +.venv +.git +*.pyc diff --git a/secure-delivery/Dockerfile b/secure-delivery/Dockerfile new file mode 100644 index 0000000..3c8078c --- /dev/null +++ b/secure-delivery/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.13.18-alpine3.24@sha256:d76f585fb0d5107dd47143da5e61554fd9cae656a30f3470f815cb8475769b6a +ARG APP_COMMIT=development +ENV APP_COMMIT=$APP_COMMIT PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir --only-binary=:all: -r requirements.txt && python -m pip uninstall -y pip +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/secure-delivery/Jenkinsfile b/secure-delivery/Jenkinsfile new file mode 100644 index 0000000..9adb646 --- /dev/null +++ b/secure-delivery/Jenkinsfile @@ -0,0 +1,65 @@ +pipeline { + agent { label 'chapter6-trusted' } + options { + skipDefaultCheckout() + disableConcurrentBuilds() + timeout(time: 60, unit: 'MINUTES') + } + environment { + IMAGE = 'git.sespinal590.dev/group10-startup/pricing' + ANSIBLE_HOST_KEY_CHECKING = 'True' + } + stages { + stage('Checkout and test') { + steps { + deleteDir() + checkout scm + sh 'bash secure-delivery/delivery.sh test' + } + } + stage('Dependency, secret, and image gates') { + steps { sh 'bash secure-delivery/delivery.sh scan' } + } + stage('Publish scanned image') { + steps { + withCredentials([usernamePassword(credentialsId: 'chapter6-registry-write', usernameVariable: 'REG_USER', passwordVariable: 'REG_TOKEN')]) { + sh 'bash secure-delivery/delivery.sh publish' + } + } + } + stage('Deploy and verify staging') { + steps { script { deployPricing('staging') } } + } + stage('Production approval') { + steps { + script { + if (!env.CHAPTER6_APPROVERS?.trim()) { + error('Configure CHAPTER6_APPROVERS on the restricted release job') + } + def digest = readFile('evidence/digest.txt').trim() + def revision = readFile('evidence/source.txt').trim() + def approver = timeout(time: 20, unit: 'MINUTES') { + input message: "Promote ${revision} / ${digest}? Scans, staging HTTPS checks and Ansible idempotence passed.", + submitter: env.CHAPTER6_APPROVERS, submitterParameter: 'APPROVER' + } + writeFile file: 'evidence/approval.txt', text: "Approved by ${approver}\n" + sh 'date -u +%FT%TZ >> evidence/approval.txt' + } + } + } + stage('Deploy and verify production') { + steps { script { deployPricing('production') } } + } + } + post { + always { archiveArtifacts artifacts: 'evidence/*', allowEmptyArchive: true } + } +} +def deployPricing(String target) { + withEnv(["TARGET_ENV=${target}"]) { + withCredentials([sshUserPrivateKey(credentialsId: 'chapter6-deploy-ssh', keyFileVariable: 'DEPLOY_KEY', usernameVariable: 'DEPLOY_USER'), + file(credentialsId: 'chapter6-known-hosts', variable: 'DEPLOY_KNOWN_HOSTS')]) { + sh 'bash secure-delivery/delivery.sh deploy' + } + } +} diff --git a/secure-delivery/README.md b/secure-delivery/README.md new file mode 100644 index 0000000..88406d7 --- /dev/null +++ b/secure-delivery/README.md @@ -0,0 +1,129 @@ +# Chapter 6: Startup Pricing Service + +`v1/` and `v2/` are two releases of the same stateless Flask service. Version 1 +charges USD 10 per unit; version 2 charges USD 12. Three units cost 30 and 36. +Both use Gunicorn, run as a non-root container user, and expose port 8000. +No database, real customer data, payment processing, or credentials are involved. + +## Local checks + +Run from either version directory, using a disposable virtual environment: + +```sh +python3 -m venv .venv +. .venv/bin/activate +pip install -r requirements.txt +python -m unittest -v +``` + +Requirements are compatibility ranges, not a reproducible lock. Before the +assessed release, resolve, review, scan, and commit exact dependency versions +(including transitive dependencies) and an approved base-image digest. Save +scanner versions and reports. These starter files make no vulnerability claim. + +## Build and publish + +Copy v1 into the team application's working directory and commit it. Build from +that directory on the trusted Jenkins agent. Use the Gitea registry hostname +without a URL scheme; replace the owner/team with its actual lowercase name. + +```sh +COMMIT=$(git rev-parse HEAD) +IMAGE=gitea.example.edu/team/pricing +# Authenticate separately using a Jenkins credential and --password-stdin. +docker build --build-arg APP_COMMIT="$COMMIT" -t "$IMAGE:$COMMIT" . +docker push "$IMAGE:$COMMIT" +docker pull "$IMAGE:$COMMIT" +docker image inspect "$IMAGE:$COMMIT" --format '{{index .RepoDigests 0}}' +``` + +Save that repository digest in a release record. Build once; use the same digest +in staging and production. For v2, replace app.py and test_app.py with the v2 +files, commit, and repeat the pipeline. Do not build the entire parent directory. +Use a Linux image architecture compatible with the droplet. + +## One-time deployment preparation + +Install Ansible in a virtual environment on a trusted Linux Jenkins agent; use a +Python version supported by your selected ansible-core release. Record exact +resolved versions after installation. + +```sh +python3 -m venv .ansible-venv +. .ansible-venv/bin/activate +pip install ansible-core +ansible-galaxy collection install -r ansible/requirements.yml +ansible --version +ansible-galaxy collection list +``` + +On the target droplet, install Python 3, Docker Engine and the Compose v2 plugin +(at least 2.18); verify `docker compose version`. Configure a dedicated SSH +account and the approved escalation policy. The playbook uses become and needs +noninteractive sudo; this is powerful host access. Do not grant it to untrusted +pull-request jobs. Verify/pin the SSH host key in the Jenkins agent's known_hosts. +Keep private keys, sudo credentials and package tokens in Jenkins credentials. + +Identify the existing reverse proxy's Docker network with `docker network ls` +and its current Compose configuration. Both app projects join that external +network. Configure the proxy once, preserving all existing routes: + +```caddyfile +staging.example.edu { + reverse_proxy pricing-staging:8000 +} +app.example.edu { + reverse_proxy pricing-production:8000 +} +``` + +Use your real DNS names pointing to the droplet and valid TLS certificates. +The proxy must be attached to that network. For a host-based proxy, adapt the +Compose template to distinct loopback ports and proxy to those ports instead. +The supplied template is for a container-based proxy; do not publish raw 8000. + +Authenticate Docker on the target as the account used by become (normally root) +using a read-only package credential and `docker login --password-stdin` through +a protected administrator session. The Jenkins build agent separately needs a +package-write credential. Never commit either credential or Docker config.json. +Do not enable insecure registry access or disable certificate verification. + +## Deploy and roll back + +Fill inventory.ini and copy release.example.yml to releases/v1-staging.yml. +Replace every placeholder. Keep this release metadata in Git; it has no secrets. +Use the exact source commit, registry digest, proxy network, URL and expected +values. From this starter directory: + +```sh +ansible-playbook -i ansible/inventory.ini ansible/deploy.yml --syntax-check +ansible-playbook -i ansible/inventory.ini ansible/deploy.yml -e @releases/v1-staging.yml +``` + +Run again unchanged and show changed=0. If the module reports unexpected +changes, inspect Compose/plugin versions and the task diff before claiming +idempotence. Create a production record with the same image digest and the +production target and URL; deploy only after an authorized Jenkins approval. +Disable concurrent delivery builds to prevent competing releases. + +Preserve each release's Compose template/configuration commit as well as its +image digest. For rollback, check out the previous reviewed deployment files +and run its production release record again. The current playbook does not +perform an automatic rollback: a failed check fails the run and requires the +explicit rollback stage/runbook. Never use `down -v`, prune shared volumes, or +roll back Gitea/Jenkins as part of the application exercise. + +For a controlled failure, use staging only: temporarily set the service's +Compose `command` to `["gunicorn", "--bind", "0.0.0.0:8001", "app:app"]` in a +separate configuration commit. The image healthcheck still probes 8000, so +Compose wait should fail. Save the failure, restore the previous configuration +commit, and redeploy its release record. Do not stop the host Docker service. + +For the business rollback, deploy healthy v2, verify version v2 and total 36, +then redeploy v1 and verify version v1 and total 30. Measure interruption and +recovery time. This recreate strategy does not provide zero downtime. + +Implement the Jenkins stages, security policy, approval and evidence described +in Chapter 6; the examples are application/deployment starters, not a complete +Jenkins pipeline. Container builds and remote deployment were not executed by +the author in a student environment. diff --git a/secure-delivery/ansible/deploy.yml b/secure-delivery/ansible/deploy.yml new file mode 100644 index 0000000..b0c4fa2 --- /dev/null +++ b/secure-delivery/ansible/deploy.yml @@ -0,0 +1,62 @@ +- 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 + - 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 + - identity.json.commit == expected_commit + - price.json.total | int == expected_total | int diff --git a/secure-delivery/ansible/inventory.ini b/secure-delivery/ansible/inventory.ini new file mode 100644 index 0000000..0c705e4 --- /dev/null +++ b/secure-delivery/ansible/inventory.ini @@ -0,0 +1,2 @@ +[delivery] +startup ansible_host=165.227.90.215 ansible_python_interpreter=/usr/bin/python3 diff --git a/secure-delivery/ansible/release.example.yml b/secure-delivery/ansible/release.example.yml new file mode 100644 index 0000000..8e5be10 --- /dev/null +++ b/secure-delivery/ansible/release.example.yml @@ -0,0 +1,8 @@ +# Copy to a release-specific file and replace EVERY placeholder. +target_env: staging +release_image: gitea.example.edu/team/pricing@sha256:REPLACE_DIGEST +expected_version: v1 +expected_commit: REPLACE_FULL_GIT_COMMIT +expected_total: 30 +public_url: https://staging.example.edu +proxy_network: REPLACE_EXISTING_PROXY_NETWORK diff --git a/secure-delivery/ansible/requirements.yml b/secure-delivery/ansible/requirements.yml new file mode 100644 index 0000000..0206fe4 --- /dev/null +++ b/secure-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/secure-delivery/ansible/templates/compose.yaml.j2 b/secure-delivery/ansible/templates/compose.yaml.j2 new file mode 100644 index 0000000..1616e1a --- /dev/null +++ b/secure-delivery/ansible/templates/compose.yaml.j2 @@ -0,0 +1,23 @@ +services: + app: + image: "{{ release_image }}" + restart: unless-stopped + read_only: true +{% if target_env == 'staging' %} + healthcheck: + timeout: 8s +{% endif %} + tmpfs: + - /tmp + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + networks: + edge: + aliases: + - "pricing-{{ target_env }}" +networks: + edge: + external: true + name: "{{ proxy_network }}" diff --git a/secure-delivery/app.py b/secure-delivery/app.py new file mode 100644 index 0000000..a6dd3f0 --- /dev/null +++ b/secure-delivery/app.py @@ -0,0 +1,33 @@ +import os +from flask import Flask, jsonify, request + +app = Flask(__name__) +VERSION = "v2" +UNIT_PRICE = 12 +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/secure-delivery/delivery.sh b/secure-delivery/delivery.sh new file mode 100644 index 0000000..136be0f --- /dev/null +++ b/secure-delivery/delivery.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +set -euo pipefail + +scan() { + local report=$1 status=0 + shift + printf '%s %s\n' "$(date -u +%FT%TZ)" "$*" >> evidence/scans.txt + trivy "$@" --no-progress --format table --output "evidence/$report.txt" || status=$? + printf '%s exit=%s\n' "$report" "$status" >> evidence/scans.txt + trivy --version >> evidence/scans.txt + return "$status" +} + +case "${1:-}" in + test) + mkdir -p evidence + git rev-parse HEAD > evidence/source.txt + cd secure-delivery + python3 -m venv .venv + .venv/bin/pip install --only-binary=:all: -r requirements.txt + .venv/bin/pip check + .venv/bin/python -m py_compile app.py test_app.py + APP_COMMIT=$(cat ../evidence/source.txt) .venv/bin/python -m unittest -v + ;; + scan) + scan secrets fs --scanners secret --skip-dirs .git --skip-dirs secure-delivery/.venv --skip-dirs evidence --exit-code 10 . + scan dependencies fs --scanners vuln --severity HIGH,CRITICAL --exit-code 10 secure-delivery/requirements.txt + tag="$IMAGE:$(cat evidence/source.txt)" + docker build --platform linux/amd64 --build-arg APP_COMMIT="$(cat evidence/source.txt)" -t "$tag" secure-delivery + scan image image --image-src docker --scanners vuln --severity HIGH,CRITICAL --exit-code 10 "$tag" + ;; + publish) + export DOCKER_CONFIG=$(mktemp -d) + trap 'rm -f "$DOCKER_CONFIG/config.json"; rmdir "$DOCKER_CONFIG"' EXIT + printf '%s' "$REG_TOKEN" | docker login git.sespinal590.dev -u "$REG_USER" --password-stdin + tag="$IMAGE:$(cat evidence/source.txt)" + docker push "$tag" + docker pull "$tag" + docker image inspect "$tag" --format '{{range .RepoDigests}}{{println .}}{{end}}' | + awk -v prefix="$IMAGE@sha256:" 'index($0,prefix)==1 {print}' > evidence/digest.txt + test "$(wc -l < evidence/digest.txt)" -eq 1 + docker pull "$(cat evidence/digest.txt)" + ;; + deploy) + export ANSIBLE_SSH_ARGS="-o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS" + version=$(cd secure-delivery && .venv/bin/python -c 'from app import VERSION; print(VERSION)') + record="evidence/$version-$TARGET_ENV.json" + python3 - "$version" "$record" <<'PY' +import json +import os +import sys +from pathlib import Path + +version, output = sys.argv[1:] +environment = os.environ["TARGET_ENV"] +hosts = {"staging": "staging", "production": "app"} +source = Path("evidence/source.txt").read_text().strip() +record = { + "target_env": environment, + "public_url": f"https://{hosts[environment]}.165.227.90.215.sslip.io", + "proxy_network": "gitea_default", + "release_image": Path("evidence/digest.txt").read_text().strip(), + "expected_commit": source, + "expected_version": version, + "expected_total": {"v1": 30, "v2": 36}[version], + "configuration_commit": source, + "jenkins_build": os.environ["BUILD_URL"], +} +Path(output).write_text(json.dumps(record, indent=2) + "\n") +PY + playbook() { + ansible-playbook -i secure-delivery/ansible/inventory.ini secure-delivery/ansible/deploy.yml \ + --user "$DEPLOY_USER" --private-key "$DEPLOY_KEY" "$@" + } + playbook --syntax-check + playbook -e "@$record" | tee "evidence/$TARGET_ENV-deploy.txt" + if [ "$TARGET_ENV" = staging ]; then + ANSIBLE_NOCOLOR=1 playbook -e "@$record" | tee evidence/staging-idempotence.txt + grep -E '^startup[[:space:]]*:.*changed=0[[:space:]].*unreachable=0[[:space:]].*failed=0([[:space:]]|$)' evidence/staging-idempotence.txt + fi + ;; + *) echo 'Use test, scan, publish, or deploy' >&2; exit 2 ;; +esac diff --git a/secure-delivery/docs/ARCHITECTURE.md b/secure-delivery/docs/ARCHITECTURE.md new file mode 100644 index 0000000..af5f907 --- /dev/null +++ b/secure-delivery/docs/ARCHITECTURE.md @@ -0,0 +1,317 @@ +# Chapter 6 — Secure Delivery Architecture + +## 1. Overview + +Chapter 6 extends the team's existing DigitalOcean infrastructure +with a secure, reproducible delivery workflow for the Startup Pricing +Service. + +The architecture combines Jenkins, a trusted execution agent, +Docker, a Gitea container registry, Ansible, Docker Compose, +Caddy, and the existing Chapter 5 monitoring infrastructure. + +Staging and production-like environments run as separate Docker +Compose projects on the same DigitalOcean Droplet. + +This is a single-host educational deployment, not a highly +available production system. + +## 2. Existing Infrastructure + +The team previously established: + +- A DigitalOcean Droplet running Ubuntu Linux. +- Docker Engine and Docker Compose. +- Self-hosted Gitea for source control and collaboration. +- Jenkins for continuous integration. +- Caddy for HTTPS reverse proxying. +- Prometheus for metrics collection. +- Grafana for visualization. +- Node Exporter for host metrics. +- Blackbox Exporter for HTTPS availability checks. + +Chapter 6 must preserve these services, their configurations, +and their persistent data. + +## 3. Logical Architecture + +```text + Developers + | + v + Gitea Repository + | + v + Jenkins CI/CD + | + v + Trusted Jenkins Agent + / \ + / \ + v v + Docker Build Ansible / SSH + | | + v | + Security Scanning | + | | + v | + Gitea OCI Registry | + | | + +--------------+ + | + v + DigitalOcean Droplet + | + +-----------------+------------------+ + | | + v v + Pricing Staging Pricing Production + Docker Compose Docker Compose + pricing-staging pricing-production + | | + +-----------------+------------------+ + | + v + Caddy HTTPS + | + +-----------+-----------+ + | | + v v + Staging URL Production URL + | + v + Blackbox Exporter + | + v + Prometheus + | + v + Grafana +``` + +This is a logical representation. Actual host and container +boundaries must be confirmed during implementation. + +## 4. Source Control + +Gitea hosts the application's source code, deployment +configuration, Jenkins pipeline, security policy, and operational +documentation. + +The Chapter 6 feature branch is: + +`chapter6-secure-delivery` + +Changes must be reviewed before entering the protected main branch. + +The existing Chapter 4 application and CI configuration must remain +available until the new delivery workflow has been verified. + +## 5. Jenkins and Trusted Agent + +Jenkins orchestrates the delivery pipeline. + +The intended pipeline stages are: + +1. Source checkout. +2. Python syntax validation. +3. Unit testing. +4. Dependency security scanning. +5. Secret scanning. +6. Docker image build. +7. Container image vulnerability scanning. +8. Registry publication. +9. Staging deployment through Ansible. +10. Staging HTTPS verification. +11. Authorized production approval. +12. Production deployment using the same immutable image digest. +13. Production HTTPS verification. + +Privileged deployment stages must execute only on a trusted +agent with appropriately restricted credentials. + +Untrusted pull-request builds must not receive deployment +or registry-write credentials. + +The actual agent topology and installed tool versions must be +recorded after verification. + +## 6. Container Registry and Immutable Releases + +Approved container images are published to the Gitea OCI registry. + +Each release must be identified by: + +- Application source commit. +- Jenkins build number. +- Container image repository digest. +- Deployment configuration commit. +- Security scan results. + +Production must use the exact same image digest that passed +staging verification. + +Rebuilding an image during promotion is prohibited. + +## 7. Ansible Deployment + +Ansible connects to the deployment host through SSH. + +The deployment playbook: + +1. Validates the selected release. +2. Creates the target deployment directory. +3. Renders the Docker Compose configuration. +4. Deploys the selected immutable image. +5. Waits for application health. +6. Verifies HTTPS health, version, source commit, and pricing. + +Deployment configuration is maintained in Git. + +The same approved release configuration should converge +without unnecessary changes when applied repeatedly. + +## 8. Environment Separation + +The two environments use separate Docker Compose projects. + +| Environment | Compose Project | Application Port | +|---|---|---| +| Staging | pricing-staging | 8000 (internal) | +| Production-like | pricing-production | 8000 (internal) | + +Both environments share the same physical Droplet. + +They must use separate container names, network aliases, +deployment directories, and HTTPS hostnames. + +The application port must not be exposed directly to the Internet. + +## 9. HTTPS Reverse Proxy + +The existing Caddy instance terminates HTTPS and routes +requests to the appropriate application container. + +The staging and production routes must be added without +removing or changing existing Gitea, Jenkins, Grafana, +or other application routes. + +Actual DNS names and the Docker proxy network must be +verified before deployment. + +## 10. Security Boundaries + +The architecture includes several trust boundaries: + +### Source Control + +Unreviewed application changes must not receive privileged +deployment credentials. + +### Jenkins + +The Jenkins controller schedules work, while the trusted agent +executes privileged build and deployment operations. + +### Registry + +Registry-write credentials are restricted to authorized +publishing operations. + +The deployment host uses read-only registry credentials. + +### SSH and Host Access + +Ansible uses a dedicated deployment account. + +SSH host identity must be verified and pinned. + +Privilege escalation must follow an approved policy. + +### Application Containers + +Application containers run as non-root users. + +The Compose configuration uses: + +- Read-only root filesystem. +- Temporary writable storage. +- Dropped Linux capabilities. +- No-new-privileges protection. + +### HTTPS + +Public application access uses valid HTTPS certificates. + +TLS certificate verification must remain enabled. + +## 11. Monitoring + +The existing Chapter 5 monitoring stack is extended with +a production HTTPS health probe. + +Blackbox Exporter checks the production endpoint. + +Prometheus collects the probe metrics. + +Grafana displays availability and allows comparison with +release and rollback timestamps. + +Existing monitoring jobs and dashboards must be preserved. + +## 12. Rollback + +The architecture supports explicit application rollback. + +A previous release is restored using: + +- Its approved immutable image digest. +- Its matching deployment configuration. +- Its recorded application source commit. +- Its corresponding Ansible release record. + +Rollback must not rebuild the application image. + +The current deployment approach does not guarantee zero downtime. + +## 13. Infrastructure Limitations + +The architecture uses a single DigitalOcean Droplet. + +Consequently: + +- Staging and production share a failure domain. +- A host outage can affect all services. +- Resource contention can affect build and deployment performance. +- Monitoring is not independent of the application host. +- Container recreation may temporarily interrupt requests. + +The deployment demonstrates controlled software delivery, +not high availability or physical environment isolation. + +## 14. Implementation Verification + +The following information must be confirmed and recorded +during Sergio's implementation: + +- Actual Jenkins agent topology. +- Agent tool versions. +- DigitalOcean Droplet specifications. +- Available disk space and memory. +- Actual Docker network names. +- Registry hostname and repository path. +- Staging and production DNS names. +- SSH deployment account and access policy. +- Exact application image digests. +- Actual monitoring configuration. +- Final deployed container topology. + +Any differences between this planned architecture and the +implemented environment must be documented. + +## Status + +Architecture documentation prepared. + +Actual infrastructure verification, implementation, and +supporting evidence remain pending. \ No newline at end of file diff --git a/secure-delivery/drills/Jenkinsfile.staging-drill b/secure-delivery/drills/Jenkinsfile.staging-drill new file mode 100644 index 0000000..48268f7 --- /dev/null +++ b/secure-delivery/drills/Jenkinsfile.staging-drill @@ -0,0 +1,33 @@ +pipeline { + agent { label 'chapter6-trusted' } + options { + disableConcurrentBuilds() + disableRestartFromStage() + skipDefaultCheckout() + timeout(time: 10, unit: 'MINUTES') + } + stages { + stage('Exercise staging startup failure') { + steps { + script { + int result = sh(returnStatus: true, script: 'mkdir -p drill && sudo -n /opt/chapter6-tools/staging-drill fail > drill/failure.txt 2>&1') + echo "Staging drill command exited ${result}" + if (result == 42) { + error('Expected failure verified: wrong-port staging container was unhealthy. Restoring staging in post.') + } + error("Unexpected drill result: ${result}. Inspect the failure and recovery logs.") + } + } + } + } + post { + always { + script { + int restored = sh(returnStatus: true, script: 'mkdir -p drill && sudo -n /opt/chapter6-tools/staging-drill restore > drill/recovery.txt 2>&1') + archiveArtifacts artifacts: 'drill/*.txt', allowEmptyArchive: false + if (restored != 0) { error("Staging restoration failed: ${restored}") } + echo 'Staging restored and verified over HTTPS.' + } + } + } +} diff --git a/secure-delivery/drills/README.md b/secure-delivery/drills/README.md new file mode 100644 index 0000000..6589df6 --- /dev/null +++ b/secure-delivery/drills/README.md @@ -0,0 +1,14 @@ +# Jenkins staging failure drill + +The live controller runs this Pipeline on the restricted Chapter 6 agent. +Its two sudo entries permit only the literal arguments `fail` and `restore` +to the root-owned wrapper at `/opt/chapter6-tools/staging-drill`. +The root-owned deployment record is fixed to v1 staging. +The failure stage uses the ordinary Ansible playbook with the wrong-port +template from this directory. Exit 42 means Ansible rejected the unhealthy +staging container as expected. The Pipeline records FAILURE and its post +action restores and verifies the original v1 staging deployment. + +[Observed Jenkins drill #1](https://ci.165.227.90.215.sslip.io/job/chapter6-staging-drill/1/). +The checkout does not install any sudo rules. Coordinate with the controller +owner for grader access to the archived failure and recovery logs. diff --git a/secure-delivery/drills/compose.yaml.j2 b/secure-delivery/drills/compose.yaml.j2 new file mode 100644 index 0000000..0f58399 --- /dev/null +++ b/secure-delivery/drills/compose.yaml.j2 @@ -0,0 +1,20 @@ +services: + app: + image: "{{ release_image }}" + command: ["gunicorn", "--bind", "0.0.0.0:8001", "app:app"] + restart: unless-stopped + read_only: true + tmpfs: + - /tmp + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + networks: + edge: + aliases: + - "pricing-{{ target_env }}" +networks: + edge: + external: true + name: "{{ proxy_network }}" diff --git a/secure-delivery/drills/staging-drill.sh b/secure-delivery/drills/staging-drill.sh new file mode 100644 index 0000000..cd1bffe --- /dev/null +++ b/secure-delivery/drills/staging-drill.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -euo pipefail +umask 077 +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +export ANSIBLE_COLLECTIONS_PATH=/opt/chapter6-tools/collections ANSIBLE_NOCOLOR=1 +base=/opt/chapter6-tools +known=$base/v1/secure-delivery/ansible +record=$base/promotions/v1-staging.yml +[[ $# = 1 ]] || exit 64 +exec 9>/run/lock/chapter6-promote.lock +flock -n 9 +run() { + "$base/ansible/bin/ansible-playbook" -i "$known/inventory.ini" "$1" -e ansible_connection=local -e "@$record" +} +date -u +%FT%TZ +case "$1" in + fail) + [[ $(docker inspect -f '{{.State.Health.Status}}' pricing-staging-app-1) = healthy ]] + output=$(mktemp) + trap 'rm -f "$output"' EXIT + rc=0 + run "$base/failure-rehearsal/deploy.yml" >"$output" 2>&1 || rc=$? + cat "$output" + [[ $rc = 2 ]] || exit 65 + grep -q 'pricing-staging-app-1 is unhealthy' "$output" || exit 66 + docker inspect -f '{{json .Config.Cmd}}' pricing-staging-app-1 | grep -q '0.0.0.0:8001' || exit 67 + date -u +%FT%TZ + exit 42 + ;; + restore) + run "$known/deploy.yml" + for path in / /health '/price?quantity=3'; do + curl -fsS --max-time 10 "https://staging.165.227.90.215.sslip.io$path" + done + date -u +%FT%TZ + ;; + *) exit 64 ;; +esac diff --git a/secure-delivery/releases/RELEASE_TRACEABILITY.md b/secure-delivery/releases/RELEASE_TRACEABILITY.md new file mode 100644 index 0000000..e4a5d4a --- /dev/null +++ b/secure-delivery/releases/RELEASE_TRACEABILITY.md @@ -0,0 +1,89 @@ +# Chapter 6 — Release Traceability + +## Purpose + +Track the relationship between application source, build inputs, +security results, immutable container images, deployment configuration, +approval, and observed application behavior. + +All release values must come from actual Jenkins, Docker, Ansible, +and HTTPS verification results. + +Do not replace missing evidence with assumed values. + +## Release Records + +| Field | v1 | v2 | +|---|---|---| +| Application version | v1 | v2 | +| Expected total for quantity 3 | USD 30 | USD 36 | +| Application source commit | PENDING | PENDING | +| Deployment configuration commit | PENDING | PENDING | +| Jenkins build number | PENDING | PENDING | +| Jenkins build URL | PENDING | PENDING | +| Python base-image digest | PENDING | PENDING | +| Image architecture | PENDING | PENDING | +| Published registry image | PENDING | PENDING | +| Immutable repository digest | PENDING | PENDING | +| Dependency scan result | PENDING | PENDING | +| Secret scan result | PENDING | PENDING | +| Image vulnerability scan result | PENDING | PENDING | +| Staging deployment time | PENDING | PENDING | +| Staging verification result | PENDING | PENDING | +| Production approver | PENDING | PENDING | +| Production approval time | PENDING | PENDING | +| Production deployment time | PENDING | PENDING | +| Production verification result | PENDING | PENDING | +| Evidence links | PENDING | PENDING | + +## Immutable Promotion Verification + +For each release: + +1. Record the immutable repository digest produced by the approved build. +2. Deploy that digest to staging. +3. Verify the application version, source commit, health, and price. +4. Obtain authorized production approval. +5. Deploy the identical digest to production without rebuilding. +6. Verify the production application over HTTPS. +7. Record both deployment results and their timestamps. + +The staging and production image digests must match exactly. + +## Rollback Traceability + +Record the following for each recovery demonstration: + +| Field | Healthy v2-to-v1 rollback | Failed staging deployment | +|---|---|---| +| Initial release/configuration | PENDING | PENDING | +| Failure or rollback trigger | PENDING | PENDING | +| Decision timestamp | PENDING | PENDING | +| Recovery start timestamp | PENDING | PENDING | +| Recovery completion timestamp | PENDING | PENDING | +| Restored image digest | PENDING | PENDING | +| Restored configuration commit | PENDING | PENDING | +| Final HTTPS health | PENDING | PENDING | +| Final application version | PENDING | PENDING | +| Final pricing result | PENDING | PENDING | +| Measured recovery duration | PENDING | PENDING | +| Measured service interruption | PENDING | PENDING | +| Evidence links | PENDING | PENDING | + +## Evidence Requirements + +Each release must be supported by: + +- Jenkins build and security scan logs. +- Registry publication and digest evidence. +- Ansible deployment output. +- Staging and production HTTPS verification. +- Authorized production approval evidence. +- Relevant monitoring screenshots and timestamps. + +## Status + +Traceability template prepared. + +All actual release records and verification evidence remain pending +Sergio's implementation and execution. \ No newline at end of file diff --git a/secure-delivery/releases/v1-production.yml b/secure-delivery/releases/v1-production.yml new file mode 100644 index 0000000..9a5ce00 --- /dev/null +++ b/secure-delivery/releases/v1-production.yml @@ -0,0 +1,9 @@ +# candidate only; human approval pending +target_env: production +public_url: https://app.165.227.90.215.sslip.io +proxy_network: gitea_default +release_image: git.sespinal590.dev/group10-startup/pricing@sha256:7ed07339f19b22809932d12a99ed59f8f0aeff04983274af2cea43cef8a425db +expected_version: v1 +expected_commit: 391007464db665eca03a647801ed7ffa9ab412f7 +expected_total: 30 +configuration_commit: 391007464db665eca03a647801ed7ffa9ab412f7 diff --git a/secure-delivery/releases/v1-staging.yml b/secure-delivery/releases/v1-staging.yml new file mode 100644 index 0000000..0b1ec86 --- /dev/null +++ b/secure-delivery/releases/v1-staging.yml @@ -0,0 +1,9 @@ +# staging rehearsal +target_env: staging +public_url: https://staging.165.227.90.215.sslip.io +proxy_network: gitea_default +release_image: git.sespinal590.dev/group10-startup/pricing@sha256:7ed07339f19b22809932d12a99ed59f8f0aeff04983274af2cea43cef8a425db +expected_version: v1 +expected_commit: 391007464db665eca03a647801ed7ffa9ab412f7 +expected_total: 30 +configuration_commit: 391007464db665eca03a647801ed7ffa9ab412f7 diff --git a/secure-delivery/releases/v2-production.yml b/secure-delivery/releases/v2-production.yml new file mode 100644 index 0000000..aa5c172 --- /dev/null +++ b/secure-delivery/releases/v2-production.yml @@ -0,0 +1,9 @@ +# candidate only; human approval pending +target_env: production +public_url: https://app.165.227.90.215.sslip.io +proxy_network: gitea_default +release_image: git.sespinal590.dev/group10-startup/pricing@sha256:68ac9b614eca90b19b888a673b96cc3f6fce934a4e297c8a20b6cb83c6394ab8 +expected_version: v2 +expected_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6 +expected_total: 36 +configuration_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6 diff --git a/secure-delivery/releases/v2-staging.yml b/secure-delivery/releases/v2-staging.yml new file mode 100644 index 0000000..27b39fb --- /dev/null +++ b/secure-delivery/releases/v2-staging.yml @@ -0,0 +1,9 @@ +# staging rehearsal +target_env: staging +public_url: https://staging.165.227.90.215.sslip.io +proxy_network: gitea_default +release_image: git.sespinal590.dev/group10-startup/pricing@sha256:68ac9b614eca90b19b888a673b96cc3f6fce934a4e297c8a20b6cb83c6394ab8 +expected_version: v2 +expected_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6 +expected_total: 36 +configuration_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6 diff --git a/secure-delivery/requirements.txt b/secure-delivery/requirements.txt new file mode 100644 index 0000000..83bdf44 --- /dev/null +++ b/secure-delivery/requirements.txt @@ -0,0 +1,8 @@ +blinker==1.9.0 +click==8.5.1 +Flask==3.1.3 +gunicorn==27.0.1 +itsdangerous==2.2.0 +Jinja2==3.1.6 +MarkupSafe==3.0.4 +Werkzeug==3.1.9 diff --git a/secure-delivery/runbooks/CLEANUP.md b/secure-delivery/runbooks/CLEANUP.md new file mode 100644 index 0000000..f570e8d --- /dev/null +++ b/secure-delivery/runbooks/CLEANUP.md @@ -0,0 +1,167 @@ +Chapter 6 — Safe Cleanup Runbook + +1. Purpose + +Document the safe removal of Chapter 6 application resources after the assignment has been graded and cleanup has been authorized. + +Cleanup must preserve all existing infrastructure established in Chapters 3, 4, and 5. + +Do not execute these procedures before grading or without team authorization. + +2. Infrastructure That Must Be Preserved + +The following resources must remain operational: + +* Gitea and its repositories. +* Jenkins and its existing pipelines. +* Caddy and its existing HTTPS routes. +* Prometheus and its existing monitoring configuration. +* Grafana, dashboards, and persistent data. +* Node Exporter. +* Blackbox Exporter. +* Existing Docker volumes and networks. +* Previous assignment evidence and documentation. + +Chapter 6 cleanup must never involve stopping the Docker daemon or deleting shared infrastructure. + +3. Resources Eligible for Cleanup + +Only resources created specifically for Chapter 6 may be removed: + +| Resource | Cleanup Condition | +|---|---| +| `pricing-staging` Compose project | After grading and authorization | +| `pricing-production` Compose project | After grading and authorization | +| `/opt/startup/pricing-staging` | After deployment records are preserved | +| `/opt/startup/pricing-production` | After deployment records are preserved | +| Chapter 6-specific Caddy routes | After application containers are removed | +| Chapter 6-specific monitoring targets | After monitoring evidence is preserved | +| Chapter 6-specific Jenkins credentials | After confirming they are not shared | +| Chapter 6-specific registry images | Only when retention is no longer required | + +Do not assume a resource is exclusive to Chapter 6 without verifying ownership. + +4. Preconditions + +Before cleanup: + +1. Confirm that Chapter 6 grading is complete. +2. Obtain authorization from the team. +3. Preserve the final IT manual PDF. +4. Preserve Jenkins build logs and security scan reports. +5. Preserve release traceability records. +6. Preserve approval evidence. +7. Preserve staging and production verification screenshots. +8. Preserve rollback and failed-deployment evidence. +9. Record the current Docker containers, networks, and volumes. +10. Confirm which resources belong exclusively to Chapter 6. + +5. Application Container Cleanup + +Identify the actual Chapter 6 Compose project names and deployment directories. + +Expected project names: + +* pricing-staging +* pricing-production + +Verify the running containers before proceeding. + +Stop and remove only the containers associated with the selected Chapter 6 application projects. + +Do not remove shared networks or volumes. + +Never use: + +docker compose down -v +docker system prune -a +docker volume prune + +Do not use broad cleanup commands that could affect unrelated services. + +6. Deployment Directory Cleanup + +After confirming that the application containers have been removed and evidence has been preserved, remove only the verified Chapter 6 deployment directories. + +Expected directories: + +/opt/startup/pricing-staging +/opt/startup/pricing-production + +Verify the exact paths before deletion. + +Never recursively delete the parent /opt/startup directory. + +7. Reverse Proxy Cleanup + +Remove only the Chapter 6 staging and production application routes from the existing Caddy configuration. + +Preserve all existing Gitea, Jenkins, Grafana, and monitoring routes. + +Validate the updated Caddy configuration before applying it. + +After applying the change, verify that existing HTTPS services remain reachable. + +8. Monitoring Cleanup + +Remove only the Chapter 6 production application probe from the existing monitoring configuration. + +Preserve all previously configured monitoring targets. + +Validate the Prometheus configuration before applying changes. + +Confirm that existing dashboards and monitoring targets remain operational. + +9. Registry and Credentials + +Before removing any registry images or Jenkins credentials: + +1. Confirm that they belong exclusively to Chapter 6. +2. Confirm that they are not referenced by another deployment. +3. Preserve required release records. +4. Confirm that image retention is no longer necessary. +5. Obtain authorization for deletion. + +Never delete shared registry credentials or Jenkins credentials used by earlier chapters. + +10. Post-Cleanup Verification + +After cleanup, confirm: + +Component Expected Result +Gitea Operational +Jenkins Operational +Caddy Existing HTTPS routes operational +Prometheus Operational +Grafana Existing dashboards available +Node Exporter Metrics available +Blackbox Exporter Existing probes operational +Chapter 6 staging application Removed +Chapter 6 production application Removed +Shared Docker volumes Preserved +Shared Docker networks Preserved + +Record the verification results and cleanup timestamp. + +11. Evidence Requirements + +Preserve: + +* Cleanup authorization. +* Date and time of cleanup. +* Operator identity. +* List of removed resources. +* Relevant commands and outputs. +* Before-and-after container inventory. +* Verification that existing services remain operational. +* Any unexpected issues and their resolution. + +Do not claim cleanup was successful without actual verification. + +12. Status + +This cleanup runbook has been prepared for future use. + +No Chapter 6 resources have been removed as part of preparing this document. + +Actual cleanup must occur only after grading and explicit authorization. \ No newline at end of file diff --git a/secure-delivery/runbooks/MONITORING.md b/secure-delivery/runbooks/MONITORING.md new file mode 100644 index 0000000..dfdbb1d --- /dev/null +++ b/secure-delivery/runbooks/MONITORING.md @@ -0,0 +1,174 @@ +# Chapter 6 — Production Monitoring Integration + +## Purpose + +Extend the existing Chapter 5 monitoring infrastructure to observe the +Startup Pricing Service's production HTTPS endpoint. + +The monitoring configuration must preserve existing Gitea, Jenkins, +Prometheus, Grafana, Node Exporter, and Blackbox Exporter functionality. + +This document describes the required integration and verification. +Actual implementation and evidence collection remain pending. + +## Existing Infrastructure + +The team previously deployed: + +- Prometheus for metrics collection. +- Grafana for dashboard visualization. +- Node Exporter for host metrics. +- Blackbox Exporter for HTTPS availability monitoring. +- Caddy as the existing HTTPS reverse proxy. + +Chapter 6 must reuse these services rather than deploy a second +monitoring stack. + +## Monitoring Target + +The production application must expose: + +- `https://REPLACE_PRODUCTION_HOSTNAME/health` + +The endpoint must: + +1. Use HTTPS with valid certificate verification. +2. Return HTTP 200 when healthy. +3. Return JSON containing `"status": "ok"`. + +The final hostname must be confirmed from the actual deployment. + +## Prometheus Integration + +Add the production HTTPS endpoint to the existing Blackbox Exporter +probe configuration. + +Use the existing Blackbox Exporter service and its configured +HTTPS-capable probe module. + +Example Prometheus scrape configuration: + +```yaml +- job_name: pricing-production-https + metrics_path: /probe + params: + module: [http_2xx] + static_configs: + - targets: + - https://REPLACE_PRODUCTION_HOSTNAME/health + relabel_configs: + - source_labels: [__address__] + target_label: __param_target + - source_labels: [__param_target] + target_label: instance + - target_label: __address__ + replacement: blackbox-exporter:9115 +``` + +This is an example only. Adapt the job name, module, and exporter +address to the existing Chapter 5 configuration. + +Do not overwrite existing scrape jobs. + +## Required Metrics + +Verify the following: + +| Metric | Purpose | +|---|---| +| `probe_success` | Whether the production HTTPS probe succeeds | +| `probe_http_status_code` | HTTP response status | +| `probe_duration_seconds` | Probe execution duration | + +Confirm that the production target appears in Prometheus and +that the probe is returning valid results. + +## Grafana Integration + +Extend the existing Chapter 5 dashboard. + +Add a clearly labeled production application panel showing: + +- Production HTTPS availability. +- Probe status over time. +- Relevant release and rollback timestamps. + +Do not remove or replace existing dashboard panels. + +## Release Correlation + +Record the following events: + +1. Initial v1 production deployment. +2. v2 production promotion. +3. Healthy v2-to-v1 production rollback. +4. Recovery verification completion. + +For each event, record: + +- Event timestamp. +- Application version. +- Immutable image digest. +- Jenkins build or deployment reference. +- Observed production HTTPS probe status. + +Compare the deployment timeline with the monitoring timeline. + +## Staging Failure Demonstration + +The controlled configuration failure must occur in staging only. + +The existing production monitoring target should remain healthy +throughout the staging exercise. + +If production monitoring changes unexpectedly, investigate and +document the cause rather than assuming the failure is isolated. + +## Verification Procedure + +1. Confirm existing Chapter 5 monitoring services are operational. +2. Record the current Prometheus targets and Grafana dashboard. +3. Add the production pricing HTTPS target. +4. Validate the Prometheus configuration before applying it. +5. Reload or restart only the required monitoring component. +6. Verify that all preexisting monitoring targets remain present. +7. Confirm that the production pricing target reports successful probes. +8. Open the updated Grafana dashboard. +9. Capture screenshots showing the new monitoring data. +10. Record actual release and rollback timestamps. +11. Correlate those timestamps with the monitoring results. + +## Evidence Checklist + +- [ ] Existing Chapter 5 monitoring baseline captured. +- [ ] Production HTTPS probe configuration recorded. +- [ ] Prometheus configuration validation passed. +- [ ] Existing monitoring targets preserved. +- [ ] New production probe visible in Prometheus. +- [ ] New production panel visible in Grafana. +- [ ] v1 deployment timestamp recorded. +- [ ] v2 deployment timestamp recorded. +- [ ] Production rollback timestamp recorded. +- [ ] Monitoring behavior correlated with release events. +- [ ] Supporting screenshots saved. + +## Limitations + +The production application and monitoring infrastructure run +on the same DigitalOcean Droplet. + +This introduces a shared failure domain. + +A Droplet outage may simultaneously affect the application and +the monitoring services, preventing reliable external outage +detection. + +The monitoring exercise demonstrates application observability, +not independent monitoring infrastructure or high availability. + +## Status + +Monitoring integration procedure prepared. + +Sergio must implement the configuration, verify the target, +update the dashboard, and collect actual evidence. \ No newline at end of file diff --git a/secure-delivery/runbooks/RELEASE.md b/secure-delivery/runbooks/RELEASE.md new file mode 100644 index 0000000..c94952f --- /dev/null +++ b/secure-delivery/runbooks/RELEASE.md @@ -0,0 +1,237 @@ +# Chapter 6 — Release Operations Runbook + +## 1. Purpose + +Document the controlled release procedure for the Startup Pricing +Service using Jenkins, Docker, the Gitea OCI registry, Ansible, +and Docker Compose. + +This runbook covers the promotion of an approved application +release from staging to production-like deployment. + +All releases must preserve the existing Gitea, Jenkins, Caddy, +and Chapter 5 monitoring infrastructure. + +## 2. Roles and Responsibilities + +| Role | Responsibility | +|---|---| +| Developer | Prepare and review application changes | +| Jenkins | Execute tests, security gates, build, and delivery stages | +| Trusted Jenkins agent | Execute approved build and deployment operations | +| Release approver | Authorize production promotion | +| Deployment operator | Investigate failures and execute recovery procedures | + +For this assignment, Sergio will configure and execute the +delivery workflow. + +Actual production approval must be performed by an authorized +person through Jenkins and recorded in the release evidence. + +## 3. Preconditions + +Before starting a release: + +1. Confirm that the proposed changes have been reviewed. +2. Confirm that the release originates from protected `main`. +3. Confirm that the trusted Jenkins agent is available. +4. Confirm that Jenkins credentials are correctly restricted. +5. Confirm that Docker and Ansible are operational. +6. Confirm that the Gitea OCI registry is accessible. +7. Confirm that staging and production HTTPS endpoints are configured. +8. Confirm that the previous approved release is available for rollback. +9. Confirm that existing infrastructure is healthy. +10. Record the current application version and image digest. + +Do not begin a privileged deployment from an untrusted pull-request build. + +## 4. Source and Build Verification + +The Jenkins pipeline must: + +1. Check out the reviewed application source. +2. Record the full Git commit identifier. +3. Verify the Python interpreter version. +4. Run Python syntax checks. +5. Install the approved dependency set. +6. Execute the application unit tests. +7. Stop immediately if any required test fails. + +The build must use the approved Python base-image digest +and reproducible dependency versions. + +## 5. Security Gates + +Before release, execute: + +- Python dependency vulnerability scanning. +- Source-code secret scanning. +- Container image vulnerability scanning. + +Record the scanner versions, vulnerability database information, +timestamps, results, and exit codes. + +Any required scanner failure, unavailable vulnerability database, +or unapproved high/critical vulnerability must block release. + +Never bypass a failed security gate to continue deployment. + +## 6. Container Image Publication + +After successful tests and security checks: + +1. Build the application container image once. +2. Include the full application source commit in the image. +3. Tag the image using the approved registry naming convention. +4. Authenticate using protected Jenkins credentials. +5. Push the image to the Gitea OCI registry. +6. Retrieve its immutable repository digest. +7. Record the digest in the release traceability document. + +Do not use a mutable image tag as the deployment identity. + +## 7. Staging Deployment + +Use Ansible to deploy the approved immutable image to staging. + +Before deployment: + +1. Confirm the staging release record contains no placeholders. +2. Confirm the image digest matches the published image. +3. Confirm the deployment configuration commit is recorded. +4. Validate the Ansible playbook syntax. +5. Confirm the target is staging. + +Deploy using the approved staging release record. + +The deployment must not rebuild the application image. + +## 8. Staging Verification + +After deployment, verify: + +| Check | Expected Result | +|---|---| +| HTTPS certificate | Valid | +| `/health` | HTTP 200 and status `ok` | +| `/` | Correct version and source commit | +| `/price?quantity=3` for v1 | USD 30 | +| `/price?quantity=3` for v2 | USD 36 | +| Deployed image digest | Matches approved release digest | + +Capture the Ansible output and HTTPS verification evidence. + +If any check fails, stop the pipeline and follow the recovery runbook. + +## 9. Production Approval + +Production promotion requires a restricted Jenkins approval step. + +The approval must: + +1. Display the release version and immutable image digest. +2. Identify the staging verification result. +3. Require an authorized approver. +4. Enforce an approval timeout. +5. Record the actual approver and approval timestamp. + +A rejected or expired approval must block production deployment. + +Do not fabricate approval evidence. + +## 10. Production Deployment + +After approval: + +1. Select the approved production release record. +2. Verify that it uses the identical image digest as staging. +3. Record the deployment configuration commit. +4. Execute the production Ansible deployment. +5. Wait for application health verification. +6. Confirm the production HTTPS endpoint is reachable. + +The production deployment must not rebuild the image. + +## 11. Production Verification + +Verify the following: + +- HTTPS certificate validation succeeds. +- `/health` returns HTTP 200 and status `ok`. +- `/` returns the approved application version. +- `/` returns the expected application source commit. +- `/price?quantity=3` returns the expected total. +- The deployed repository digest matches the staging digest. +- Existing infrastructure remains operational. + +Record the production deployment timestamp and verification evidence. + +## 12. Release Traceability + +Update: + +`secure-delivery/releases/RELEASE_TRACEABILITY.md` + +Record: + +- Application version. +- Source commit. +- Deployment configuration commit. +- Jenkins build number and URL. +- Dependency and base-image versions. +- Security scan results. +- Published image digest. +- Staging verification. +- Production approver and approval time. +- Production verification. +- Evidence links. + +All values must be obtained from actual execution. + +## 13. Failed Release Handling + +If a required stage fails: + +1. Stop the release workflow. +2. Record the failed stage and timestamp. +3. Preserve relevant logs. +4. Confirm that production has not been unintentionally modified. +5. Determine whether staging recovery is necessary. +6. Follow the rollback and recovery runbook when applicable. +7. Correct the underlying problem in a reviewed commit. +8. Rerun the required tests and security gates. + +Do not silently retry an unsafe deployment or bypass failed checks. + +## 14. Post-Release Monitoring + +After a successful production deployment: + +1. Confirm the production HTTPS Blackbox probe is successful. +2. Confirm Prometheus receives the expected metrics. +3. Confirm the production application is visible in Grafana. +4. Record the deployment timestamp. +5. Compare monitoring observations with the release timeline. + +Preserve all existing Chapter 5 monitoring targets. + +## 15. Completion Criteria + +A release is complete only when: + +- Required tests pass. +- Required security gates pass. +- The image is published and its digest recorded. +- Staging deployment and verification succeed. +- Production approval is recorded. +- Production uses the identical approved image digest. +- Production verification succeeds. +- Monitoring remains operational. +- Release evidence is documented. + +## 16. Status + +Release operations runbook prepared. + +Actual execution, infrastructure configuration, approval, +and supporting evidence remain pending Sergio's implementation. \ No newline at end of file diff --git a/secure-delivery/runbooks/ROLLBACK.md b/secure-delivery/runbooks/ROLLBACK.md new file mode 100644 index 0000000..97580b5 --- /dev/null +++ b/secure-delivery/runbooks/ROLLBACK.md @@ -0,0 +1,209 @@ +# Chapter 6 — Rollback and Recovery Runbook + +## Purpose + +Document safe, repeatable recovery procedures for the Startup Pricing Service. + +This runbook covers: + +1. Rolling back a healthy production deployment from v2 to v1. +2. Recovering from an intentionally failed staging deployment. + +Both procedures must preserve the existing Gitea, Jenkins, Caddy, +Prometheus, Grafana, and monitoring infrastructure. + +The application is stateless. No database migration or persistent +application data restoration is required. + +## Preconditions + +Before beginning: + +- Confirm that the trusted Jenkins agent and Ansible deployment + environment are operational. +- Confirm that the previously approved image digests are available + in the container registry. +- Confirm that the corresponding reviewed deployment configuration + commits and release records are available. +- Confirm that staging and production HTTPS endpoints are reachable. +- Confirm that the operator has authorized deployment privileges. +- Record the initial application version, image digest, configuration + commit, and deployment timestamp. + +Never use an unverified image tag as a substitute for the recorded +immutable repository digest. + +## Scenario 1 — Healthy Production Rollback + +### Objective + +Demonstrate that a working v2 production release can be restored +to the previously approved v1 release. + +### Expected Application Behavior + +| Release | Version | Quantity | Expected Total | +|---|---|---|---| +| v2 | v2 | 3 | USD 36 | +| v1 | v1 | 3 | USD 30 | + +### Procedure + +1. Confirm that production is running the approved v2 image digest. +2. Verify the production HTTPS `/health` endpoint. +3. Verify that `/` reports version v2 and the expected source commit. +4. Verify that `/price?quantity=3` returns total 36. +5. Record the rollback decision timestamp. +6. Retrieve the previously approved v1 image digest and release record. +7. Restore the reviewed deployment configuration associated with v1. +8. Record the rollback execution start timestamp. +9. Execute the Ansible deployment using the v1 production release record. +10. Wait for the application health verification to complete. +11. Verify the production HTTPS `/health` endpoint. +12. Verify that `/` reports version v1 and the original v1 source commit. +13. Verify that `/price?quantity=3` returns total 30. +14. Confirm that the deployed image digest matches the approved v1 digest. +15. Record the successful recovery timestamp. +16. Calculate recovery duration and observed service interruption. +17. Capture Jenkins, Ansible, HTTPS, and monitoring evidence. + +### Acceptance Criteria + +- Production returns HTTP 200 from `/health`. +- Production reports version v1. +- Production reports the expected v1 source commit. +- Three units cost USD 30. +- The deployed image digest matches the approved v1 digest. +- Existing infrastructure remains operational. +- Recovery duration and service interruption are documented. + +## Scenario 2 — Failed Staging Deployment + +### Objective + +Demonstrate that an invalid deployment configuration is detected +and that the service can be restored using a previously reviewed +configuration. + +This exercise must run in staging only. + +### Controlled Failure + +Create a separate configuration commit that overrides the +application's Gunicorn command: + +```yaml +command: + - gunicorn + - --bind + - 0.0.0.0:8001 + - app:app +``` + +The container image healthcheck continues to probe port 8000. + +This mismatch should cause the container healthcheck to fail +and prevent the deployment from completing successfully. + +### Procedure + +1. Confirm that staging is healthy before the test. +2. Record the currently approved staging image digest. +3. Record the currently approved staging configuration commit. +4. Record the initial staging HTTPS responses. +5. Create a separate Git commit containing the controlled port mismatch. +6. Deploy the intentionally invalid configuration to staging only. +7. Confirm that the container healthcheck fails. +8. Confirm that Ansible or Jenkins reports a failed deployment. +9. Capture the failure logs, build number, and timestamp. +10. Record the recovery decision timestamp. +11. Restore the previously reviewed staging configuration. +12. Use the previously approved staging release record and image digest. +13. Execute the Ansible deployment again. +14. Verify that the application becomes healthy. +15. Verify the expected version and source commit. +16. Verify the correct pricing response. +17. Record the recovery completion timestamp. +18. Calculate recovery duration and observed interruption. +19. Capture Jenkins, Ansible, HTTPS, and monitoring evidence. + +### Acceptance Criteria + +- The intentionally invalid staging deployment is rejected. +- The failure is visible in Jenkins or Ansible output. +- No production deployment is triggered by the failed staging run. +- The previously reviewed configuration is restored. +- Staging returns HTTP 200 from `/health`. +- The restored application version and source commit are correct. +- Pricing behavior matches the restored release. +- Recovery duration and service interruption are documented. + +## Recovery Timing + +Record the following timestamps for both scenarios: + +| Measurement | Description | +|---|---| +| Decision time | When the operator decides to restore the previous release | +| Recovery start | When the recovery deployment begins | +| Recovery complete | When all required verification checks pass | +| Recovery duration | Recovery complete minus recovery start | +| Service interruption | Measured period during which the endpoint is unavailable | + +Record actual observations rather than estimated durations. + +If no interruption is observed, report that result and explain +the measurement method. + +## Safety Requirements + +- Never run the controlled failure against production. +- Never stop or restart the host Docker daemon. +- Never remove shared Docker volumes. +- Never use `docker compose down -v`. +- Never run destructive Docker cleanup commands. +- Never modify Gitea, Jenkins, Caddy, or monitoring configurations + as part of the controlled failure. +- Never rebuild an image during rollback. +- Never replace the approved digest with a mutable image tag. +- Never silently report a failed deployment as successful. + +## Limitations + +The staging and production environments share one DigitalOcean Droplet. + +Therefore: + +- The environments are logically separated but not physically isolated. +- A host failure can affect both environments. +- Container recreation can cause temporary service interruption. +- The deployment strategy does not guarantee zero downtime. +- This exercise does not demonstrate high availability. + +The application is stateless, making image rollback relatively simple. + +For a stateful application, database schema compatibility must also +be considered. A backward-compatible expand-and-contract migration +strategy would allow older and newer application versions to coexist +during a controlled rollback window. + +## Evidence Checklist + +- [ ] Healthy v2 production verification. +- [ ] Approved v1 repository digest. +- [ ] v1 rollback deployment output. +- [ ] Restored v1 production verification. +- [ ] Controlled staging configuration commit. +- [ ] Failed staging deployment output. +- [ ] Restored configuration commit. +- [ ] Successful staging recovery output. +- [ ] Recovery timestamps and calculations. +- [ ] Monitoring screenshots. +- [ ] Confirmation that existing infrastructure remains operational. + +## Status + +Runbook prepared. + +Execution, measured results, and supporting evidence remain pending +Sergio's implementation and verification. \ No newline at end of file diff --git a/secure-delivery/security/SECURITY_GATE_TEST.md b/secure-delivery/security/SECURITY_GATE_TEST.md new file mode 100644 index 0000000..42c2622 --- /dev/null +++ b/secure-delivery/security/SECURITY_GATE_TEST.md @@ -0,0 +1,61 @@ +# Chapter 6 — Security Gate Verification + +## Objective + +Demonstrate that the Jenkins delivery pipeline blocks an unsafe release +and successfully resumes after the test condition is removed. + +## Preconditions + +Before running the demonstration: + +1. The Jenkins pipeline must have working security scanners. +2. Scanner versions and detection rules must be recorded. +3. The trusted Jenkins agent must be configured. +4. Deployment credentials must be unavailable to untrusted builds. +5. The normal security checks must pass. + +## Controlled Failure Test + +1. Create a dedicated test branch from the reviewed application source. +2. Select a synthetic, nonfunctional fixture explicitly supported by + the configured security scanner. +3. Verify that the scanner detects the fixture in an isolated test. +4. Introduce the fixture into the test branch. +5. Trigger the Jenkins pipeline. +6. Confirm that the appropriate security stage fails. +7. Confirm that no image is published or deployed. +8. Capture the Jenkins build number, scanner output, exit code, + timestamp, and screenshot. +9. Remove the fixture in a separate corrective commit. +10. Rerun the pipeline and confirm the security check passes. + +## Safety Requirements + +- Never use a real credential, password, private key, or access token. +- Never introduce a deliberately vulnerable image into production. +- Never disable security checks to make the pipeline pass. +- Never expose registry-write or deployment credentials to test branches. +- Do not merge the failing fixture into protected main. +- If a scanner cannot detect the selected fixture, choose a documented + scanner-supported fixture instead of claiming a successful detection. + +## Evidence Checklist + +- [ ] Scanner name and exact version +- [ ] Scanner rules or vulnerability database version +- [ ] Synthetic fixture description +- [ ] Test branch and commit +- [ ] Jenkins build number +- [ ] Failed security stage screenshot +- [ ] Scanner exit code and report +- [ ] Confirmation that publication and deployment did not occur +- [ ] Corrective commit +- [ ] Passing rerun screenshot + +## Status + +Procedure prepared. + +The actual scanner selection, fixture verification, blocked pipeline, +corrective run, and evidence collection are assigned to Sergio. \ No newline at end of file diff --git a/secure-delivery/security/SECURITY_POLICY.md b/secure-delivery/security/SECURITY_POLICY.md new file mode 100644 index 0000000..51c236e --- /dev/null +++ b/secure-delivery/security/SECURITY_POLICY.md @@ -0,0 +1,73 @@ +# Chapter 6 — Secure Delivery Security Policy + +## Purpose + +This policy defines the security requirements for the Startup Pricing +Service CI/CD pipeline. + +The pipeline must fail closed when a required security check fails, +cannot execute, or produces an invalid result. + +## Trusted Execution + +- Pull requests and feature branches may run tests and security checks. +- Untrusted builds must not receive deployment or registry-write credentials. +- Only reviewed changes on protected main may enter the release pipeline. +- Privileged deployment stages must run on an approved trusted Jenkins agent. +- Production deployment requires an authorized human approval with a timeout. + +## Dependency Scanning + +- Scan resolved Python dependencies before release. +- Record the scanner name, version, vulnerability database information, + execution time, report, and exit status. +- Block releases containing unapproved high or critical vulnerabilities. +- Scanner failures or unavailable vulnerability data must block release. +- Any exception requires documented instructor approval, scope, + justification, and expiration. + +## Secret Scanning + +- Scan application source and relevant repository content for secrets. +- Block releases when supported secret-detection rules identify credentials. +- Use only synthetic, nonfunctional test fixtures for blocked-gate evidence. +- Never commit real passwords, API tokens, private keys, or SSH credentials. + +## Container Image Scanning + +- Scan the exact image that will be published and deployed. +- Block unapproved high or critical vulnerabilities. +- Record the image reference, scanner version, database information, + timestamp, results, and exit status. +- Do not bypass failed scans to produce a successful build. + +## Registry and Deployment Credentials + +- Store credentials in Jenkins credentials, not in Git. +- Use docker login with --password-stdin. +- Separate registry-write and registry-read permissions. +- Verify and pin the deployment server's SSH host key. +- Restrict deployment credentials to authorized trusted jobs. + +## Release Integrity + +- Record the source commit and immutable image repository digest. +- Deploy the same approved digest to staging and production. +- Do not rebuild the image between environments. +- Verify application version, source commit, health, and pricing over HTTPS. + +## Required Evidence + +Sergio must capture: + +1. Successful dependency, secret, and image scan results. +2. A blocked pipeline caused by a safe synthetic test fixture. +3. Successful pipeline execution after removing the fixture. +4. Scanner versions, database details, timestamps, and exit codes. +5. Jenkins credential and approval configuration without exposing secrets. +6. The immutable image digest used for staging and production. + +## Status + +Policy prepared. Enforcement and validation are pending implementation +and verification in Jenkins. \ No newline at end of file diff --git a/secure-delivery/test_app.py b/secure-delivery/test_app.py new file mode 100644 index 0000000..669294b --- /dev/null +++ b/secure-delivery/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), 36) + response = self.client.get("/price?quantity=3") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json["total"], 36) + + 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"], "v2") + self.assertEqual(self.client.get("/health").json["status"], "ok") + + +if __name__ == "__main__": + unittest.main()