Chapter 6: Secure Delivery and Rollback Preparation #11

Open
turanisl wants to merge 27 commits from chapter6-secure-delivery into main
6 changed files with 136 additions and 106 deletions
Showing only changes of commit 391007464d - Show all commits
+2 -2
View File
@@ -1,9 +1,9 @@
FROM python:3.13-slim
FROM python:3.13.18-slim-bookworm@sha256:f3dac913ab53b78c64f26d5518fcd7043d5a1a46522d6a493b598c3ed12f62a6
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
COPY app.py .
USER 10001:10001
EXPOSE 8000
+39 -99
View File
@@ -1,126 +1,66 @@
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"
+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
+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