Add protected Ansible recovery transaction and verified simulation evidence
startup-product-gitea-ci/pipeline/pr-main This commit looks good

This commit is contained in:
2026-11-26 02:15:32 -05:00
parent 799a377cc0
commit 1e6842e83c
5 changed files with 414 additions and 0 deletions
@@ -0,0 +1,77 @@
---
- name: Execute protected production recovery transaction
hosts: production
gather_facts: false
any_errors_fatal: true
serial: 1
vars:
v1_release: "{{ lookup('ansible.builtin.file', playbook_dir + '/../recovery/releases/v1.yml') | from_yaml }}"
v2_release: "{{ lookup('ansible.builtin.file', playbook_dir + '/../recovery/releases/v2.yml') | from_yaml }}"
tasks:
- name: Require explicit recovery authorization
ansible.builtin.assert:
that:
- recovery_authorized | default(false) | bool
- not ansible_check_mode
- configuration_commit is defined
- configuration_commit is match('^[a-f0-9]{40}$')
- name: Generate unique recovery workspace
ansible.builtin.tempfile:
state: directory
path: /opt/secure-delivery
prefix: recovery-transaction-
register: workspace
- name: Protect recovery workspace
ansible.builtin.file:
path: "{{ workspace.path }}"
owner: root
group: root
mode: '0700'
- name: Install transaction script
ansible.builtin.copy:
src: ../recovery/production-transaction.py
dest: "{{ workspace.path }}/production-transaction.py"
owner: root
group: root
mode: '0700'
- name: Install immutable recovery configuration
ansible.builtin.copy:
content: "{{ {'v1': v1_release, 'v2': v2_release, 'configuration_commit': configuration_commit} | to_nice_json }}"
dest: "{{ workspace.path }}/releases.json"
owner: root
group: root
mode: '0600'
- name: Set unique systemd unit name
ansible.builtin.set_fact:
recovery_unit: "{{ workspace.path | basename }}"
- name: Report recovery execution identifiers
ansible.builtin.debug:
msg:
- "Workspace: {{ workspace.path }}"
- "Systemd unit: {{ recovery_unit }}"
- "Configuration commit: {{ configuration_commit }}"
- name: Start detached recovery transaction
ansible.builtin.command:
argv:
- /usr/bin/systemd-run
- "--unit={{ recovery_unit }}"
- --property=RemainAfterExit=yes
- --property=StandardOutput=journal
- --property=StandardError=journal
- /usr/bin/python3
- "{{ workspace.path }}/production-transaction.py"
- "{{ workspace.path }}/releases.json"
- AUTHORIZED
- name: Report journal retrieval command
ansible.builtin.debug:
msg: "journalctl -u {{ recovery_unit }} --no-pager -o short-iso-precise"
@@ -0,0 +1,31 @@
Thu Nov 26 07:13:31 UTC 2026
PASS: Complete V2 -> V1 -> V2 transaction
PRODUCTION_LOCK_ACQUIRED
Configuration commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
ROLLBACK_DECISION
Original V2 container: original-v2
ROLLBACK_STARTED
ROLLBACK_RECOVERED
RESTORATION_STARTED
RESTORATION_RECOVERED
Preserved V1: startup-pricing-production-drill-v1-20261126-071331
Restored original V2: original-v2
RECOVERY_TRANSACTION_SUCCESS
PRODUCTION_LOCK_RELEASED
PASS: Original V2 identity preserved
PASS: Both containers preserved
PASS: Failed V1 triggers original V2 restoration
PRODUCTION_LOCK_ACQUIRED
Configuration commit: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
ROLLBACK_DECISION
Original V2 container: original-v2
ROLLBACK_STARTED
RECOVERY_TRANSACTION_FAILED: Injected V1 verification failure
Attempting original V2 restoration
EMERGENCY_V2_RESTORATION_VERIFIED
PRODUCTION_LOCK_RELEASED
PASS: Original V2 identity preserved
PASS: Both containers preserved
SUCCESS: Both simulated recovery scenarios passed
No real Docker, SSH or HTTPS operations executed
Thu Nov 26 07:13:31 UTC 2026
@@ -0,0 +1,47 @@
=== RECOVERY RUNTIME VALIDATION ===
Thu Nov 26 07:00:37 UTC 2026
PLAY [Validate recovery inputs without deployment] *****************************
TASK [Validate immutable release records] **************************************
ok: [localhost] => {
"changed": false,
"msg": "All assertions passed"
}
TASK [Verify external production HTTPS health] *********************************
ok: [localhost]
TASK [Verify external production pricing] **************************************
ok: [localhost]
TASK [Validate actual V2 behavior] *********************************************
ok: [localhost] => {
"changed": false,
"msg": "All assertions passed"
}
TASK [Report verified release inputs] ******************************************
ok: [localhost] => {
"msg": [
"V1 image: git.nageshwaran.dev/ssw590-startup/startup-pricing@sha256:d0d0a2c2052b01a33ce12fd2b278e906552ea9797b5b918f44e5065f444d3027",
"V2 image: git.nageshwaran.dev/ssw590-startup/startup-pricing@sha256:14d520f6fbe60c9cc5e661551a03e944de3a2ad777a64c316ec397ee765db22d",
"Production health: {'status': 'healthy', 'version': 'v2'}",
"Production pricing: {'plans': [{'name': 'Starter', 'price': 5}, {'name': 'Basic', 'price': 12}, {'name': 'Pro', 'price': 30}, {'name': 'Enterprise', 'price': 60}], 'service': 'Startup Pricing Service', 'version': 'v2'}",
"SUCCESS: Recovery inputs validated"
]
}
PLAY RECAP *********************************************************************
localhost : ok=5 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
=== EXTERNAL HTTPS MONITORING TEST ===
timestamp_utc,http_status,healthy,version,latency_ms
2026-11-26T07:00:39.570+00:00,200,true,v2,101
2026-11-26T07:00:40.575+00:00,200,true,v2,153
2026-11-26T07:00:41.580+00:00,200,true,v2,328
2026-11-26T07:00:42.585+00:00,200,true,v2,104
2026-11-26T07:00:43.590+00:00,200,true,v2,112
SUCCESS: Five healthy external HTTPS probes
SUCCESS: Recovery runtime validation completed
Thu Nov 26 07:00:43 UTC 2026
@@ -0,0 +1,11 @@
Thu Nov 26 07:12:39 UTC 2026
PASS: Correct release accepted
PASS: Incorrect pricing rejected
PASS: Incorrect image ID rejected
PASS: Incorrect registry reference rejected
PASS: Unhealthy application rejected
PASS: Stopped container rejected
PASS: Incorrect release version rejected
SUCCESS: All seven verification tests passed
No real Docker or HTTPS operations executed
Thu Nov 26 07:12:39 UTC 2026
+248
View File
@@ -0,0 +1,248 @@
#!/usr/bin/env python3
import fcntl
import json
import os
import signal
import subprocess
import sys
import time
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
def log(message):
print(
datetime.now(timezone.utc).isoformat(),
message,
flush=True
)
def docker(*args):
return subprocess.check_output(
["docker", *args],
text=True,
timeout=60
).strip()
def inspect(identifier):
return json.loads(docker("inspect", identifier))[0]
def fetch(url):
with urllib.request.urlopen(url, timeout=5) as response:
if response.status != 200:
raise RuntimeError("Unexpected HTTP status")
return json.load(response)
def verify(release, container):
expected_id = json.loads(
docker("image", "inspect", release["image"])
)[0]["Id"]
for attempt in range(15):
try:
active = inspect(container)
health = fetch(release["health_url"])
pricing = fetch(release["pricing_url"])
plans = {
p["name"]: p["price"]
for p in pricing["plans"]
}
assert active["State"]["Running"]
assert active["Config"]["Image"] == release["image"]
assert active["Image"] == expected_id
assert health["status"] == release["expected_health"]
assert pricing["version"] == release["release"]
assert plans == release["expected_pricing"]
assert len(pricing["plans"]) == len(plans)
assert sum(plans.values()) == release["expected_total"]
if release["release"] == "v2":
assert health["version"] == "v2"
log("VERIFIED " + release["release"])
log("Registry reference: " + release["image"])
log("Image ID: " + active["Image"])
log("Health: " + json.dumps(health))
log("Pricing: " + json.dumps(pricing))
return
except Exception as exc:
log(f"Verification attempt {attempt + 1}: {exc}")
time.sleep(2)
raise RuntimeError("Release verification failed")
def interrupted(signum, frame):
raise RuntimeError(f"Interrupted by signal {signum}")
def main():
if not __debug__:
raise RuntimeError("Python assertions must remain enabled")
if os.geteuid() != 0:
raise RuntimeError("Root execution required")
if len(sys.argv) != 3 or sys.argv[2] != "AUTHORIZED":
raise RuntimeError("Explicit authorization required")
config = json.loads(Path(sys.argv[1]).read_text())
v1 = config["v1"]
v2 = config["v2"]
name = v2["container_name"]
assert name == "startup-pricing-production"
assert v1["container_name"] == name
assert v1["release"] == "v1"
assert v2["release"] == "v2"
assert v1["image"] != v2["image"]
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
saved_v2 = name + "-recovery-" + stamp
saved_v1 = name + "-drill-v1-" + stamp
lock = open("/run/lock/chapter6-production.lock", "a")
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError("Production deployment lock is busy")
log("PRODUCTION_LOCK_ACQUIRED")
log("Configuration commit: " + config["configuration_commit"])
signal.signal(signal.SIGTERM, interrupted)
signal.signal(signal.SIGINT, interrupted)
signal.signal(signal.SIGHUP, interrupted)
original = inspect(name)
original_id = original["Id"]
docker("image", "inspect", v1["image"])
docker("image", "inspect", v2["image"])
verify(v2, name)
existing = docker("ps", "-a", "--format", "{{.Names}}").splitlines()
if saved_v1 in existing or saved_v2 in existing:
raise RuntimeError("Preservation name already exists")
log("ROLLBACK_DECISION")
log("Original V2 container: " + original_id)
try:
log("ROLLBACK_STARTED")
docker("stop", original_id)
docker("rename", original_id, saved_v2)
docker(
"run", "-d",
"--pull=never",
"--name", name,
"--label", "chapter6.recovery=" + stamp,
"--restart", v1["restart_policy"],
"--network", v1["network"],
"--memory", v1["memory"],
"--memory-swap", v1["memory_swap"],
"--cpus", str(v1["cpus"]),
"--pids-limit", str(v1["pids_limit"]),
"--read-only",
"--tmpfs", v1["tmpfs"],
"--security-opt", "no-new-privileges:true",
"--cap-drop", "ALL",
"-p", v1["host_binding"],
v1["image"]
)
verify(v1, name)
log("ROLLBACK_RECOVERED")
time.sleep(10)
log("RESTORATION_STARTED")
replacement = inspect(name)
assert replacement["Config"]["Labels"].get(
"chapter6.recovery"
) == stamp
docker("stop", replacement["Id"])
docker("rename", replacement["Id"], saved_v1)
docker("rename", original_id, name)
docker("start", original_id)
verify(v2, name)
assert inspect(name)["Id"] == original_id
log("RESTORATION_RECOVERED")
log("Preserved V1: " + saved_v1)
log("Restored original V2: " + original_id)
log("RECOVERY_TRANSACTION_SUCCESS")
except BaseException as exc:
log("RECOVERY_TRANSACTION_FAILED: " + str(exc))
log("Attempting original V2 restoration")
try:
names = docker(
"ps", "-a", "--format", "{{.Names}}"
).splitlines()
if name in names:
current = inspect(name)
if current["Id"] != original_id:
labels = current["Config"].get("Labels") or {}
if labels.get("chapter6.recovery") != stamp:
raise RuntimeError(
"Unexpected container; refusing modification"
)
if current["State"]["Running"]:
docker("stop", current["Id"])
docker(
"rename",
current["Id"],
name + "-failed-" + stamp
)
original = inspect(original_id)
if original["Name"] != "/" + name:
docker("rename", original_id, name)
if not inspect(original_id)["State"]["Running"]:
docker("start", original_id)
verify(v2, name)
log("EMERGENCY_V2_RESTORATION_VERIFIED")
except BaseException as rescue_error:
log("MANUAL_RECOVERY_REQUIRED: " + str(rescue_error))
raise
finally:
lock.close()
log("PRODUCTION_LOCK_RELEASED")
if __name__ == "__main__":
main()