Prepare Assignment 8 secure delivery and rollback
vpn-dns-gateway/pipeline/head This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good

Add the locked pricing service, trusted-agent pipeline, Ansible deployments, security gates, recovery runbooks, prerequisite evidence, and preparation manual.

Prepared with Codex assistance. Vincent explicitly authorized this local commit and will handle the push. Assessed releases and recovery exercises remain pending.
This commit is contained in:
2026-11-14 17:09:25 -05:00
parent 8beefde2a4
commit bf28adc7fb
51 changed files with 2091 additions and 14 deletions
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
record=$1
environment=$2
operation=${3:-deploy}
case "$record" in
build/delivery/releases/*.json|delivery/releases/*.json) ;;
*) echo 'Release record must be in the release metadata directory' >&2; exit 1 ;;
esac
python3 delivery/ci/release.py verify "$record" --environment "$environment"
config=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["configuration_commit"])' "$record")
scratch=$(mktemp -d)
trap 'rm -rf "$scratch"' EXIT
# Recover both playbook and template from the configuration recorded with this image.
git archive "$config" delivery/ansible | tar -x -C "$scratch"
: "${DEPLOY_KEY:?bind the deployment SSH key as a Jenkins file credential}"
: "${DEPLOY_KNOWN_HOSTS:?bind the verified known_hosts as a Jenkins file credential}"
export ANSIBLE_HOST_KEY_CHECKING=True
export ANSIBLE_SSH_ARGS="-o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DEPLOY_KNOWN_HOSTS"
export ANSIBLE_PRIVATE_KEY_FILE="$DEPLOY_KEY"
ansible-playbook -i "$scratch/delivery/ansible/inventory.ini" \
"$scratch/delivery/ansible/deploy.yml" --syntax-check -e "@$record"
python3 delivery/ci/run-ansible.py "$record" "$operation" \
-i "$scratch/delivery/ansible/inventory.ini" \
"$scratch/delivery/ansible/deploy.yml" -e "@$record"
+48
View File
@@ -0,0 +1,48 @@
"""Sample public HTTPS health during release/recovery; failures are evidence."""
import argparse
import csv
from datetime import datetime, timezone
import json
from pathlib import Path
import time
import urllib.error
import urllib.request
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--url', choices=['https://app.yebilly.me', 'https://staging.yebilly.me'], required=True)
parser.add_argument('--seconds', type=int, default=600)
parser.add_argument('--interval', type=float, default=1)
parser.add_argument('--output', required=True)
args = parser.parse_args()
if not 1 <= args.seconds <= 1800 or args.interval < 0.5:
parser.error('Use 1-1800 seconds and at least 0.5 seconds between samples')
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
deadline = time.monotonic() + args.seconds
with output.open('w', newline='') as stream:
writer = csv.writer(stream)
writer.writerow(['started_utc', 'elapsed_seconds', 'http_status', 'status', 'version', 'error'])
while time.monotonic() < deadline:
started = datetime.now(timezone.utc).isoformat()
clock = time.monotonic()
code, status, version, error = '', '', '', ''
try:
with urllib.request.urlopen(args.url + '/health', timeout=2) as response:
code = response.status
body = json.load(response)
status, version = body.get('status', ''), body.get('version', '')
except urllib.error.HTTPError as failure:
code, error = failure.code, type(failure).__name__
except (OSError, ValueError, urllib.error.URLError) as failure:
error = type(failure).__name__
writer.writerow([started, round(time.monotonic() - clock, 3), code, status, version, error])
stream.flush()
time.sleep(max(0, args.interval - (time.monotonic() - clock)))
print(f'Saved samples to {output}; inspect failed samples and gaps, not just the exit status')
if __name__ == '__main__':
main()
+30
View File
@@ -0,0 +1,30 @@
#!/bin/sh
set -eu
set +x
: "${REGISTRY_USER:?bind registry credentials}"
: "${REGISTRY_TOKEN:?bind registry credentials}"
image=git.yebilly.me/ssw590-group1/pricing
commit=$(git rev-parse HEAD)
reports=build/delivery/reports
mkdir -p "$reports" build/delivery/releases
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
printf '%s' "$REGISTRY_TOKEN" | docker login --username "$REGISTRY_USER" --password-stdin git.yebilly.me
# Never overwrite a source-commit tag during a retry.
if docker manifest inspect "$image:$commit" > "$reports/existing-manifest.json" 2> "$reports/manifest-check.log"; then
docker pull "$image:$commit"
else
if ! grep -Eqi 'manifest unknown|no such manifest|not found' "$reports/manifest-check.log"; then
cat "$reports/manifest-check.log" >&2
exit 1
fi
docker build --platform linux/amd64 --build-arg "APP_COMMIT=$commit" -t "$image:$commit" delivery/app
python3 delivery/ci/security.py image --image "$image:$commit" --reports "$reports/image-gate"
docker push "$image:$commit"
docker pull "$image:$commit"
fi
digest=$(docker image inspect "$image:$commit" --format '{{index .RepoDigests 0}}')
python3 delivery/ci/security.py image --image "$digest" --reports "$reports/published-image-gate"
printf '%s\n' "$digest" > "$reports/published-digest.txt"
python3 delivery/ci/release.py create --image "$digest" --build-url "$BUILD_URL" --output build/delivery/releases
+77
View File
@@ -0,0 +1,77 @@
"""Create and verify non-secret release records used by Ansible."""
import argparse
import ast
import json
import re
import subprocess
from datetime import datetime, timezone
from pathlib import Path
URLS = {"staging": "https://staging.yebilly.me", "production": "https://app.yebilly.me"}
IMAGE = re.compile(r"git\.yebilly\.me/ssw590-group1/pricing@sha256:[0-9a-f]{64}")
COMMIT = re.compile(r"[0-9a-f]{40}")
def verify(record):
required = {"release_image", "expected_commit", "configuration_commit",
"expected_version", "expected_total", "proxy_network", "target_env", "public_url"}
if not required <= record.keys() or record.keys() - required - {"build_url", "created_at"}:
raise ValueError("Missing or unexpected release fields")
if not IMAGE.fullmatch(record["release_image"]):
raise ValueError("Release requires the team registry image and exact digest")
for name in ("expected_commit", "configuration_commit"):
value = record[name]
if not COMMIT.fullmatch(value):
raise ValueError(f"Invalid {name}")
subprocess.run(["git", "merge-base", "--is-ancestor", value, "origin/main"], check=True)
version = record["expected_version"]
if version not in {"v1", "v2"}:
raise ValueError("Unsupported application release")
if record["expected_total"] != {"v1": 30, "v2": 36}[version]:
raise ValueError("Unexpected business result")
environment = record["target_env"]
if record["public_url"] != URLS[environment] or record["proxy_network"] != "gitea_web":
raise ValueError("Unexpected deployment target")
def main():
parser = argparse.ArgumentParser()
commands = parser.add_subparsers(dest="action", required=True)
create = commands.add_parser("create")
create.add_argument("--image", required=True)
create.add_argument("--build-url", required=True)
create.add_argument("--output", required=True)
check = commands.add_parser("verify")
check.add_argument("record")
check.add_argument("--environment", choices=["staging", "production"])
args = parser.parse_args()
if args.action == "verify":
record = json.loads(Path(args.record).read_text())
verify(record)
if args.environment and record["target_env"] != args.environment:
raise ValueError("Release environment does not match the authorized pipeline stage")
return
values = {}
for node in ast.parse(Path("delivery/app/app.py").read_text()).body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in {"VERSION", "UNIT_PRICE"}:
values[target.id] = ast.literal_eval(node.value)
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
record = {
"release_image": args.image, "expected_commit": commit,
"configuration_commit": commit, "expected_version": values["VERSION"],
"expected_total": values["UNIT_PRICE"] * 3, "proxy_network": "gitea_web",
"build_url": args.build_url, "created_at": datetime.now(timezone.utc).isoformat(),
}
output = Path(args.output)
output.mkdir(parents=True, exist_ok=True)
for environment, url in URLS.items():
target = dict(record, target_env=environment, public_url=url)
verify(target)
(output / f"{values['VERSION']}-{environment}.json").write_text(json.dumps(target, indent=2))
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
"""Archive deployment timing/recaps and enforce the unchanged-rerun gate."""
import json
import os
import re
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
def main():
record = json.loads(Path(sys.argv[1]).read_text())
operation = sys.argv[2]
if operation not in {"deploy", "rerun"}:
raise ValueError("Unknown deployment operation")
reports = Path("build/delivery/reports")
reports.mkdir(parents=True, exist_ok=True)
stem = f"ansible-{record['target_env']}-{operation}"
started = datetime.now(timezone.utc).isoformat()
clock = time.monotonic()
process = subprocess.Popen(
["ansible-playbook", *sys.argv[3:]], text=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=dict(os.environ, ANSIBLE_NOCOLOR="1"),
)
lines = []
with (reports / f"{stem}.txt").open("w") as log:
for line in process.stdout:
print(line, end="", flush=True)
log.write(line)
lines.append(line)
status = process.wait()
recaps = []
for line in lines:
match = re.match(r"^(\S+)\s+:\s+ok=(\d+)\s+changed=(\d+)\s+unreachable=(\d+)\s+failed=(\d+)", line)
if match:
recaps.append(dict(zip(
["host", "ok", "changed", "unreachable", "failed"],
[match[1], *map(int, match.groups()[1:])],
)))
passed = status == 0 and bool(recaps) and all(
row["failed"] == 0 and row["unreachable"] == 0
and (operation != "rerun" or row["changed"] == 0)
for row in recaps
)
report = {
"started": started, "completed": datetime.now(timezone.utc).isoformat(),
"elapsed_seconds": round(time.monotonic() - clock, 3),
"operation": operation, "release": record,
"ansible_exit_code": status, "recaps": recaps,
"result": "passed" if passed else "blocked",
}
(reports / f"{stem}.json").write_text(json.dumps(report, indent=2))
if not passed:
print("Deployment gate blocked: inspect the archived Ansible recap", file=sys.stderr)
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())
+127
View File
@@ -0,0 +1,127 @@
"""Run release gates and preserve reports, tool versions, and process exit codes."""
import argparse
import json
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
def now():
return datetime.now(timezone.utc).isoformat()
def check_report(report, kind):
if kind == "dependencies":
dependencies = report["dependencies"]
if not dependencies:
raise ValueError("Dependency audit returned no packages")
return [v for package in dependencies for v in package["vulns"]]
if report["SchemaVersion"] != 2 or "ArtifactName" not in report:
raise ValueError("Unrecognized Trivy report")
results = report["Results"]
if not isinstance(results, list):
raise ValueError("Trivy Results must be a list")
if kind == "image" and not results:
raise ValueError("Image scan returned no analyzed targets")
if kind == "secrets":
return [secret for result in results for secret in result.get("Secrets", [])]
return [
vulnerability
for result in results
for vulnerability in result.get("Vulnerabilities", [])
if vulnerability["Severity"] in {"HIGH", "CRITICAL"}
]
def redact_secret_matches(report):
for result in report.get("Results", []):
for secret in result.get("Secrets", []):
secret["Match"] = "[REDACTED]"
for line in secret.get("Code", {}).get("Lines", []):
line["Content"] = "[REDACTED]"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("phase", choices=["source", "image"])
parser.add_argument("--image")
parser.add_argument("--fixture", action="store_true")
parser.add_argument("--reports", default="build/delivery/reports")
args = parser.parse_args()
reports = Path(args.reports).resolve()
reports.mkdir(parents=True, exist_ok=True)
execution = {"started": now(), "phase": args.phase, "steps": []}
def run(command, label, accepted=(0,)):
result = subprocess.run(command, text=True, capture_output=True)
(reports / f"{label}.log").write_text(result.stdout + result.stderr)
execution["steps"].append({
"label": label, "command": command, "completed": now(),
"exit_code": result.returncode,
})
if result.returncode not in accepted:
raise RuntimeError(f"{label} failed with exit code {result.returncode}")
return result
def scan_secrets(target, label):
output = reports / f"{label}.json"
run([
"trivy", "fs", "--scanners", "secret", "--secret-config",
"delivery/trivy-secret.yaml", "--format", "json", "--output", str(output),
"--skip-dirs", ".git", "--skip-dirs", "build", "--skip-dirs", "work",
"--skip-dirs", ".venv", str(target),
], label)
report = json.loads(output.read_text())
redact_secret_matches(report)
output.write_text(json.dumps(report, indent=2))
if check_report(report, "secrets"):
raise RuntimeError(f"{label}: detected secrets block delivery")
try:
run(["trivy", "--version"], "trivy-version")
run(["pip-audit", "--version"], "pip-audit-version")
if args.phase == "source":
scan_secrets(".", "source-secrets")
output = reports / "dependencies.json"
result = run([
"pip-audit", "-r", "delivery/app/requirements.txt", "--no-deps",
"--disable-pip", "--format", "json", "--output", str(output),
], "dependencies", accepted=(0, 1))
findings = check_report(json.loads(output.read_text()), "dependencies")
if result.returncode or findings:
raise RuntimeError("Dependency findings or audit errors block delivery")
if args.fixture:
with tempfile.TemporaryDirectory(prefix="ssw590-scan-") as directory:
# Construct the nonfunctional course fixture only in the test run.
value = "SSW590_SYNTHETIC_SECRET_" + "0" * 16
Path(directory, "fixture.txt").write_text(value)
scan_secrets(directory, "synthetic-secret")
raise RuntimeError("Synthetic fixture was not detected")
else:
if not args.image:
raise ValueError("--image is required for the image gate")
output = reports / "image.json"
run([
"trivy", "image", "--scanners", "vuln", "--format", "json",
"--output", str(output), args.image,
], "image")
run(["trivy", "--version"], "trivy-database-version")
if check_report(json.loads(output.read_text()), "image"):
raise RuntimeError("HIGH/CRITICAL image findings block delivery")
execution["result"] = "passed"
print(f"{args.phase} gate passed")
except (OSError, ValueError, KeyError, TypeError, RuntimeError) as error:
execution["result"] = "blocked"
execution["reason"] = str(error)
print(f"{args.phase} gate blocked: {error}")
return 1
finally:
execution["completed"] = now()
(reports / f"{args.phase}-execution.json").write_text(json.dumps(execution, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
reports=${REPORTS_DIR:-build/delivery/reports}
mkdir -p "$reports"
reports=$(cd "$reports" && pwd)
test_dir=$(mktemp -d)
trap 'rm -rf "$test_dir"' EXIT
python3 -m venv "$test_dir/venv"
test_python="$test_dir/venv/bin/python"
"$test_python" -m pip install -r delivery/app/requirements.txt
cp delivery/app/app.py delivery/app/test_app.py "$test_dir/"
if [ "${TEST_FAILURE:-false}" = true ]; then
cat > "$test_dir/test_gate_fixture.py" <<'PY'
import unittest
from app import app
class ControlledWrongPrice(unittest.TestCase):
def test_deliberately_wrong_expected_price(self):
response = app.test_client().get('/price?quantity=3')
self.assertEqual(response.json['total'], -1, 'Controlled test must block delivery')
PY
fi
cd "$test_dir"
"$test_python" -B - "$reports" <<'PY'
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
started = datetime.now(timezone.utc).isoformat()
result = subprocess.run([sys.executable, '-B', '-m', 'unittest', '-v'], text=True, capture_output=True)
output = result.stdout + result.stderr
print(output, end='')
reports = Path(sys.argv[1])
(reports / 'unit-tests.txt').write_text(output)
(reports / 'unit-tests.json').write_text(json.dumps({
'started': started, 'completed': datetime.now(timezone.utc).isoformat(),
'exit_code': result.returncode,
'result': 'passed' if result.returncode == 0 else 'blocked',
}, indent=2))
raise SystemExit(result.returncode)
PY
+112
View File
@@ -0,0 +1,112 @@
"""Regression checks for fail-closed release and scan boundaries."""
import importlib.util
import io
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
import release
import security
spec = importlib.util.spec_from_file_location('run_ansible', Path(__file__).with_name('run-ansible.py'))
run_ansible = importlib.util.module_from_spec(spec)
spec.loader.exec_module(run_ansible)
class SecurityGateTests(unittest.TestCase):
def test_empty_dependency_audit_is_not_clean_evidence(self):
with self.assertRaises(ValueError):
security.check_report({"dependencies": []}, "dependencies")
def test_incomplete_or_unrecognized_scan_is_rejected(self):
for report in [{}, {"SchemaVersion": 2, "ArtifactName": "."},
{"SchemaVersion": 3, "ArtifactName": ".", "Results": []}]:
with self.subTest(report=report), self.assertRaises((ValueError, KeyError)):
security.check_report(report, "secrets")
def test_high_findings_and_secrets_block(self):
report = {"SchemaVersion": 2, "ArtifactName": "image", "Results": [{
"Vulnerabilities": [{"Severity": "LOW"}, {"Severity": "HIGH"}, {"Severity": "CRITICAL"}],
"Secrets": [{"Severity": "LOW", "Match": "test-data"}],
}]}
self.assertEqual(len(security.check_report(report, "image")), 2)
self.assertEqual(len(security.check_report(report, "secrets")), 1)
security.redact_secret_matches(report)
self.assertEqual(report["Results"][0]["Secrets"][0]["Match"], "[REDACTED]")
def test_image_without_analyzed_targets_is_rejected(self):
with self.assertRaises(ValueError):
security.check_report({"SchemaVersion": 2, "ArtifactName": "image", "Results": []}, "image")
class ReleaseBoundaryTests(unittest.TestCase):
def setUp(self):
self.record = {
"release_image": "git.yebilly.me/ssw590-group1/pricing@sha256:" + "a" * 64,
"expected_commit": "b" * 40, "configuration_commit": "c" * 40,
"expected_version": "v1", "expected_total": 30,
"proxy_network": "gitea_web", "target_env": "staging",
"public_url": "https://staging.yebilly.me",
}
@patch("release.subprocess.run")
def test_both_commits_must_be_reviewed_main_ancestors(self, run):
release.verify(self.record)
self.assertEqual([call.args[0][-2] for call in run.call_args_list], ["b" * 40, "c" * 40])
self.assertTrue(all(call.kwargs["check"] for call in run.call_args_list))
@patch("release.subprocess.run")
def test_cross_environment_url_is_rejected(self, run):
self.record["public_url"] = "https://app.yebilly.me"
with self.assertRaises(ValueError):
release.verify(self.record)
def test_mutable_tag_or_other_registry_is_rejected(self):
for image in ["git.yebilly.me/ssw590-group1/pricing:latest", "example.com/pricing@sha256:" + "a" * 64]:
self.record["release_image"] = image
with self.assertRaises(ValueError):
release.verify(self.record)
def test_unexpected_ansible_variables_are_rejected(self):
self.record["ansible_host"] = "unapproved-host"
with self.assertRaises(ValueError):
release.verify(self.record)
class UnchangedRerunTests(unittest.TestCase):
def check_recap(self, text, exit_code=0):
original = Path.cwd()
with tempfile.TemporaryDirectory() as directory:
try:
os.chdir(directory)
Path('release.json').write_text(json.dumps({'target_env': 'staging'}))
with patch('sys.argv', ['run-ansible.py', 'release.json', 'rerun', 'playbook.yml']), \
patch.object(run_ansible.subprocess, 'Popen') as launch, \
patch('sys.stdout', new_callable=io.StringIO), \
patch('sys.stderr', new_callable=io.StringIO):
launch.return_value.stdout = io.StringIO(text)
launch.return_value.wait.return_value = exit_code
return run_ansible.main()
finally:
os.chdir(original)
def test_unchanged_success_passes(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=0 unreachable=0 failed=0 skipped=0\n'), 0)
def test_success_with_unnecessary_changes_blocks(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=1 unreachable=0 failed=0 skipped=0\n'), 1)
def test_missing_recap_is_not_a_success(self):
self.assertEqual(self.check_recap('No deployment results\n'), 1)
def test_ansible_error_blocks_even_with_good_looking_recap(self):
self.assertEqual(self.check_recap('startup : ok=9 changed=0 unreachable=0 failed=0\n', 1), 1)
if __name__ == "__main__":
unittest.main()