Author SHA1 Message Date
reviewer f8525aa64d Record the Jenkins staging failure and recovery drill
startup-product-ci/pipeline/pr-main This commit looks good
2026-11-13 22:37:55 -05:00
reviewer e55f1fcc06 Allow more time for the staging container health probe
startup-product-ci/pipeline/pr-main This commit looks good
2026-11-13 22:25:15 -05:00
reviewer 21fbf784e2 Record candidate release identities and environment configuration 2026-11-13 18:48:57 -05:00
reviewer 586e74acd3 Use scanned Alpine runtime and supported Jenkins options 2026-11-13 18:41:13 -05:00
reviewer 484e7f85b9 Release v2 pricing behavior and matching tests 2026-11-13 18:37:16 -05:00
reviewer 391007464d Implement Chapter 6 release gates and immutable deployment 2026-11-13 18:36:19 -05:00
17 changed files with 277 additions and 158 deletions
+2 -2
View File
@@ -1,9 +1,9 @@
FROM python:3.13-slim
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 -r 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
+37 -98
View File
@@ -1,126 +1,65 @@
pipeline {
agent { label 'REPLACE_TRUSTED_AGENT_LABEL' }
agent { label 'chapter6-trusted' }
options {
skipDefaultCheckout()
disableConcurrentBuilds()
timeout(time: 60, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
timestamps()
}
environment {
APP_DIR = 'secure-delivery'
IMAGE = 'git.sespinal590.dev/group10-startup/pricing'
ANSIBLE_HOST_KEY_CHECKING = 'True'
}
stages {
stage('Checkout') {
stage('Checkout and test') {
steps {
deleteDir()
checkout scm
sh '''
set -eu
git rev-parse HEAD
python3 --version
'''
sh 'bash secure-delivery/delivery.sh test'
}
}
stage('Python Syntax Check') {
stage('Dependency, secret, and image gates') {
steps { sh 'bash secure-delivery/delivery.sh scan' }
}
stage('Publish scanned image') {
steps {
dir('secure-delivery') {
sh '''
set -eu
python3 -m py_compile app.py test_app.py
'''
withCredentials([usernamePassword(credentialsId: 'chapter6-registry-write', usernameVariable: 'REG_USER', passwordVariable: 'REG_TOKEN')]) {
sh 'bash secure-delivery/delivery.sh publish'
}
}
}
stage('Unit Tests') {
stage('Deploy and verify staging') {
steps { script { deployPricing('staging') } }
}
stage('Production approval') {
steps {
dir('secure-delivery') {
sh '''
set -eu
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python -m unittest -v
'''
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('Security Gates') {
steps {
error(
'Chapter 6 security gates are not yet configured. ' +
'Sergio must integrate verified dependency and secret ' +
'scanners before enabling release execution.'
)
stage('Deploy and verify production') {
steps { script { deployPricing('production') } }
}
}
stage('Build and Publish') {
when {
branch 'main'
}
steps {
error(
'Release execution is disabled until trusted-agent, ' +
'registry, image scanning, and credential controls ' +
'have been configured and verified.'
)
}
}
stage('Deploy Staging') {
when {
branch 'main'
}
steps {
error(
'Staging deployment requires verified Ansible, SSH, ' +
'immutable image digest, and HTTPS configuration.'
)
}
}
stage('Production Approval') {
when {
branch 'main'
}
steps {
error(
'Production approval must be implemented with an ' +
'authorized submitter restriction and timeout.'
)
}
}
stage('Deploy Production') {
when {
branch 'main'
}
steps {
error(
'Production deployment is disabled until all release ' +
'gates and authorized approval are operational.'
)
}
}
}
post {
always {
echo 'Chapter 6 pipeline execution finished.'
always { archiveArtifacts artifacts: 'evidence/*', allowEmptyArchive: true }
}
success {
echo 'All configured stages passed.'
}
failure {
echo 'Pipeline failed or was blocked by an incomplete gate.'
}
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'
}
}
}
+1 -2
View File
@@ -1,3 +1,2 @@
[delivery]
# Replace address and user; verify the SSH host key before first use.
startup ansible_host=REPLACE_DROPLET_ADDRESS ansible_user=deploy
startup ansible_host=165.227.90.215 ansible_python_interpreter=/usr/bin/python3
+3 -1
View File
@@ -1,3 +1,5 @@
collections:
- name: community.docker
version: ">=4.8.0,<6.0.0"
version: "5.4.0"
- name: community.library_inventory_filtering_v1
version: "1.1.5"
@@ -3,6 +3,10 @@ services:
image: "{{ release_image }}"
restart: unless-stopped
read_only: true
{% if target_env == 'staging' %}
healthcheck:
timeout: 8s
{% endif %}
tmpfs:
- /tmp
cap_drop:
+2 -2
View File
@@ -2,8 +2,8 @@ import os
from flask import Flask, jsonify, request
app = Flask(__name__)
VERSION = "v1"
UNIT_PRICE = 10
VERSION = "v2"
UNIT_PRICE = 12
COMMIT = os.environ.get("APP_COMMIT", "development")
+83
View File
@@ -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
@@ -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.'
}
}
}
}
+14
View File
@@ -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.
+20
View File
@@ -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 }}"
+38
View File
@@ -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
+6 -8
View File
@@ -1,11 +1,9 @@
# Chapter 6 — v1 production release template
# NOT DEPLOYABLE until all REPLACE_* values are resolved.
# Must use the SAME immutable image digest as the approved v1 staging release.
# candidate only; human approval pending
target_env: production
release_image: "REPLACE_REGISTRY_IMAGE@sha256:REPLACE_V1_DIGEST"
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: "REPLACE_V1_SOURCE_COMMIT"
expected_commit: 391007464db665eca03a647801ed7ffa9ab412f7
expected_total: 30
public_url: "https://REPLACE_PRODUCTION_HOSTNAME"
proxy_network: "REPLACE_EXISTING_PROXY_NETWORK"
configuration_commit: 391007464db665eca03a647801ed7ffa9ab412f7
+6 -8
View File
@@ -1,11 +1,9 @@
# Chapter 6 — v1 staging release template
# NOT DEPLOYABLE until all REPLACE_* values are resolved.
# Use the exact image digest and source commit from the approved v1 build.
# staging rehearsal
target_env: staging
release_image: "REPLACE_REGISTRY_IMAGE@sha256:REPLACE_DIGEST"
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: "REPLACE_V1_SOURCE_COMMIT"
expected_commit: 391007464db665eca03a647801ed7ffa9ab412f7
expected_total: 30
public_url: "https://REPLACE_STAGING_HOSTNAME"
proxy_network: "REPLACE_EXISTING_PROXY_NETWORK"
configuration_commit: 391007464db665eca03a647801ed7ffa9ab412f7
+6 -8
View File
@@ -1,11 +1,9 @@
# Chapter 6 — v2 production release template
# NOT DEPLOYABLE until all REPLACE_* values are resolved.
# Must use the SAME immutable image digest as the approved v2 staging release.
# candidate only; human approval pending
target_env: production
release_image: "REPLACE_REGISTRY_IMAGE@sha256:REPLACE_V2_DIGEST"
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: "REPLACE_V2_SOURCE_COMMIT"
expected_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6
expected_total: 36
public_url: "https://REPLACE_PRODUCTION_HOSTNAME"
proxy_network: "REPLACE_EXISTING_PROXY_NETWORK"
configuration_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6
+6 -8
View File
@@ -1,11 +1,9 @@
# Chapter 6 — v2 staging release template
# NOT DEPLOYABLE until all REPLACE_* values are resolved.
# Use the approved v2 image digest and its matching source commit.
# staging rehearsal
target_env: staging
release_image: "REPLACE_REGISTRY_IMAGE@sha256:REPLACE_V2_DIGEST"
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: "REPLACE_V2_SOURCE_COMMIT"
expected_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6
expected_total: 36
public_url: "https://REPLACE_STAGING_HOSTNAME"
proxy_network: "REPLACE_EXISTING_PROXY_NETWORK"
configuration_commit: 586e74acd3f785954eb39bc74f98b1631defcbb6
+8 -2
View File
@@ -1,2 +1,8 @@
Flask==3.1.2
gunicorn==23.0.0
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
+5 -16
View File
@@ -7,29 +7,18 @@ class PricingTests(unittest.TestCase):
self.client = app.test_client()
def test_price(self):
self.assertEqual(total_price(3), 30)
self.assertEqual(total_price(3), 36)
response = self.client.get("/price?quantity=3")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json["total"], 30)
self.assertEqual(response.json["total"], 36)
def test_invalid_quantity(self):
for value in ["0", "-1", "1001", "abc", "1.5"]:
with self.subTest(quantity=value):
response = self.client.get("/price?quantity=" + value)
self.assertEqual(response.status_code, 400)
self.assertEqual(self.client.get("/price?quantity=" + value).status_code, 400)
def test_release_identity(self):
response = self.client.get("/")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json["version"], "v1")
self.assertIn("commit", response.json)
self.assertTrue(response.json["commit"])
health = self.client.get("/health")
self.assertEqual(health.status_code, 200)
self.assertEqual(health.json["status"], "ok")
self.assertEqual(self.client.get("/").json["version"], "v2")
self.assertEqual(self.client.get("/health").json["status"], "ok")
if __name__ == "__main__":