5 Commits
13 changed files with 172 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
+39 -100
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('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.'
)
}
stage('Deploy and verify production') {
steps { script { deployPricing('production') } }
}
}
post {
always {
echo 'Chapter 6 pipeline execution finished.'
}
success {
echo 'All configured stages passed.'
}
failure {
echo 'Pipeline failed or was blocked by an incomplete gate.'
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'
}
}
}
}
+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
+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
+6 -17
View File
@@ -7,30 +7,19 @@ 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__":
unittest.main()
unittest.main()