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..18494a3 --- /dev/null +++ b/secure-delivery/ansible/inventory.ini @@ -0,0 +1,3 @@ +[delivery] +# Replace address and user; verify the SSH host key before first use. +startup ansible_host=REPLACE_DROPLET_ADDRESS ansible_user=deploy 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..5ccd5c4 --- /dev/null +++ b/secure-delivery/ansible/requirements.yml @@ -0,0 +1,3 @@ +collections: + - name: community.docker + version: ">=4.8.0,<6.0.0" diff --git a/secure-delivery/ansible/templates/compose.yaml.j2 b/secure-delivery/ansible/templates/compose.yaml.j2 new file mode 100644 index 0000000..7c003c7 --- /dev/null +++ b/secure-delivery/ansible/templates/compose.yaml.j2 @@ -0,0 +1,19 @@ +services: + app: + image: "{{ release_image }}" + 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/v1/.dockerignore b/secure-delivery/v1/.dockerignore new file mode 100644 index 0000000..e1b2920 --- /dev/null +++ b/secure-delivery/v1/.dockerignore @@ -0,0 +1,4 @@ +__pycache__ +.venv +.git +*.pyc diff --git a/secure-delivery/v1/Dockerfile b/secure-delivery/v1/Dockerfile new file mode 100644 index 0000000..f7212fe --- /dev/null +++ b/secure-delivery/v1/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.13-slim +ARG APP_COMMIT=development +ENV APP_COMMIT=$APP_COMMIT PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +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/v1/app.py b/secure-delivery/v1/app.py new file mode 100644 index 0000000..1ea1194 --- /dev/null +++ b/secure-delivery/v1/app.py @@ -0,0 +1,33 @@ +import os +from flask import Flask, jsonify, request + +app = Flask(__name__) +VERSION = "v1" +UNIT_PRICE = 10 +COMMIT = os.environ.get("APP_COMMIT", "development") + + +def total_price(quantity): + if quantity < 1 or quantity > 1000: + raise ValueError("quantity must be between 1 and 1000") + return UNIT_PRICE * quantity + + +@app.get("/") +def index(): + return jsonify(service="Startup Pricing", version=VERSION, commit=COMMIT) + + +@app.get("/health") +def health(): + return jsonify(status="ok", version=VERSION) + + +@app.get("/price") +def price(): + try: + quantity = int(request.args.get("quantity", "1")) + total = total_price(quantity) + except ValueError as error: + return jsonify(error=str(error)), 400 + return jsonify(quantity=quantity, total=total, currency="USD") diff --git a/secure-delivery/v1/requirements.txt b/secure-delivery/v1/requirements.txt new file mode 100644 index 0000000..81b6476 --- /dev/null +++ b/secure-delivery/v1/requirements.txt @@ -0,0 +1,9 @@ +blinker==1.9.0 +click==8.5.0 +Flask==3.1.3 +gunicorn==23.0.0 +itsdangerous==2.2.0 +Jinja2==3.1.6 +MarkupSafe==3.0.4 +packaging==26.3 +Werkzeug==3.1.9 diff --git a/secure-delivery/v1/test_app.py b/secure-delivery/v1/test_app.py new file mode 100644 index 0000000..40b4207 --- /dev/null +++ b/secure-delivery/v1/test_app.py @@ -0,0 +1,25 @@ +import unittest +from app import app, total_price + + +class PricingTests(unittest.TestCase): + def setUp(self): + self.client = app.test_client() + + def test_price(self): + self.assertEqual(total_price(3), 30) + response = self.client.get("/price?quantity=3") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json["total"], 30) + + def test_invalid_quantity(self): + for value in ["0", "-1", "1001", "abc", "1.5"]: + self.assertEqual(self.client.get("/price?quantity=" + value).status_code, 400) + + def test_release_identity(self): + self.assertEqual(self.client.get("/").json["version"], "v1") + self.assertEqual(self.client.get("/health").json["status"], "ok") + + +if __name__ == "__main__": + unittest.main()