#!/usr/bin/env bash
# Proves the permitted-root containment seam, the external-workspace flag and exit
# attribution of sandbox-run, from a live sandbox on a buildbox.
set -uo pipefail

HOST="${1:-debian1}"
SSH=(ssh -F "$HOME/.ssh/config" -o BatchMode=yes "$HOST")
ID="containproof"
MARKER="containproof-marker-verified"
REASON_FILE=".local/share/overdeck-sandbox/runs/$ID/reason"
FAILURES=0

run_in_sandbox() { # script [extra-flags]
  local script=$1 extra_flags=${2-}
  "${SSH[@]}" ".local/share/overdeck-sandbox/bin/sandbox-run --id $ID${extra_flags:+ }$extra_flags -- /bin/bash -c $(printf '%q' "$script")" </dev/null 2>&1
}

run_host() { "${SSH[@]}" "$1" </dev/null 2>&1; }

proven() { printf 'PROVEN       %-28s %s\n' "$1" "$2"; }

failed() { # name detail...
  local name=$1; shift
  printf 'PROVE-FAIL   %-28s %s\n' "$name" "$1"; shift
  [ $# -eq 0 ] || printf '%s\n' "$@"
  FAILURES=$((FAILURES + 1))
}

setup() { # name command
  local out
  if ! out="$(run_host "$2")"; then
    printf 'SETUP-FAIL   %-28s %s\n' "$1" "$out"
    FAILURES=$((FAILURES + 1))
    return 1
  fi
  return 0
}

CRED_DIR='$HOME/.local/state/overdeck-sandbox/creds/containproof'
CRED_SIBLING='$HOME/.local/state/overdeck-sandbox/containproof-sibling'
CRED_MARKER="containproof-credential-marker"

cleanup_host() {
  run_host 'rm -f "$HOME/sandbox/containproof-link"; rm -rf "$HOME/cdx-offload/containproof-ws" /tmp/containproof-escape' >/dev/null 2>&1 || true
  run_host "rm -rf \"$CRED_DIR\" \"$CRED_SIBLING\" \"\$HOME/.local/state/overdeck-sandbox/creds/containproof-ws\"" >/dev/null 2>&1 || true
}
trap cleanup_host EXIT

echo "=== agent sandbox containment proofs on $HOST ==="

out="$(run_in_sandbox true '--mount /etc:/sandbox-secrets/evil:ro')"
rc=$?
if [ "$rc" -eq 12 ]; then
  proven "mount source outside roots" "rc=$rc"
else
  failed "mount source outside roots" "rc=$rc (wanted 12)" "$out"
fi

if setup "escape workspace cleanup" 'rm -rf /tmp/containproof-escape'; then
  out="$(run_in_sandbox true '--workspace /tmp/containproof-escape')"
  rc=$?
  absent=0
  run_host 'test ! -e /tmp/containproof-escape' >/dev/null 2>&1 && absent=1
  if [ "$rc" -eq 12 ] && [ "$absent" -eq 1 ]; then
    proven "workspace outside roots" "rc=$rc, host path never created"
  else
    failed "workspace outside roots" "rc=$rc (wanted 12), host-path-absent=$absent (wanted 1)" "$out"
  fi
fi

if setup "symlink escape prep" 'mkdir -p "$HOME/sandbox" && ln -sfn /etc "$HOME/sandbox/containproof-link"'; then
  out="$(run_in_sandbox true '--mount "$HOME/sandbox/containproof-link:/sandbox-secrets/evil:ro"')"
  rc=$?
  if [ "$rc" -eq 12 ]; then
    proven "symlink source escape" "rc=$rc"
  else
    failed "symlink source escape" "rc=$rc (wanted 12)" "$out"
  fi
fi

out="$(run_in_sandbox true '--mount "$HOME/sandbox:/sandbox:rw"')"
rc=$?
if [ "$rc" -eq 2 ]; then
  proven "reserved destination" "rc=$rc"
else
  failed "reserved destination" "rc=$rc (wanted 2)" "$out"
fi

out="$(run_in_sandbox true "--mount \"\$HOME/sandbox:/sandbox/workspaces/$ID:rw\"")"
rc=$?
if [ "$rc" -eq 2 ]; then
  proven "workspace dest not shadowable" "rc=$rc"
else
  failed "workspace dest not shadowable" "rc=$rc (wanted 2)" "$out"
fi

if setup "external workspace prep" \
  "mkdir -p \"\$HOME/cdx-offload/containproof-ws\" && printf '%s\\n' $MARKER > \"\$HOME/cdx-offload/containproof-ws/marker\""; then
  out="$(run_in_sandbox 'pwd; cat marker' '--workspace "$HOME/cdx-offload/containproof-ws"')"
  rc=$?
  if [ "$rc" -eq 0 ] \
    && printf '%s' "$out" | grep -qF "/sandbox/workspaces/$ID" \
    && printf '%s' "$out" | grep -qF "$MARKER"; then
    proven "external workspace mounts" "rc=$rc, workdir and marker both correct"
  else
    failed "external workspace mounts" "rc=$rc (wanted 0) or workdir/marker missing" "$out"
  fi
fi

if setup "credential fixture prep" \
  "mkdir -p \"$CRED_DIR/codex\" \"$CRED_SIBLING\" \
   && printf '%s\\n' $CRED_MARKER > \"$CRED_DIR/codex/auth.json\" \
   && printf '%s\\n' $CRED_MARKER > \"$CRED_SIBLING/auth.json\" \
   && chmod 600 \"$CRED_DIR/codex/auth.json\" \"$CRED_SIBLING/auth.json\" \
   && ln -sfn /etc \"$CRED_DIR/link\""; then

  out="$(run_in_sandbox 'cat /sandbox-secrets/credproof/auth.json
grep -F " /sandbox-secrets/credproof/auth.json " /proc/self/mountinfo
if echo tampered >> /sandbox-secrets/credproof/auth.json 2>/dev/null; then echo WRITE-SUCCEEDED; else echo write-refused; fi' \
    "--mount \"$CRED_DIR/codex/auth.json:/sandbox-secrets/credproof/auth.json:ro\"")"
  rc=$?
  if [ "$rc" -eq 0 ] \
    && printf '%s' "$out" | grep -qF "$CRED_MARKER" \
    && printf '%s' "$out" | grep -qE ' /sandbox-secrets/credproof/auth\.json ro[, ]' \
    && printf '%s' "$out" | grep -qF 'write-refused'; then
    proven "credential root ro mount" "rc=$rc, mounted ro, readable, write refused"
  else
    failed "credential root ro mount" "rc=$rc (wanted 0) or marker/ro/write-refusal missing" "$out"
  fi

  out="$(run_in_sandbox true "--mount \"$CRED_DIR/codex/auth.json:/sandbox-secrets/credproof/auth.json:rw\"")"
  rc=$?
  if [ "$rc" -eq 12 ]; then
    proven "credential root rw mount" "rc=$rc"
  else
    failed "credential root rw mount" "rc=$rc (wanted 12)" "$out"
  fi

  out="$(run_in_sandbox true "--mount \"$CRED_SIBLING/auth.json:/sandbox-secrets/credproof/auth.json:ro\"")"
  rc=$?
  if [ "$rc" -eq 12 ]; then
    proven "credential root sibling" "rc=$rc"
  else
    failed "credential root sibling" "rc=$rc (wanted 12)" "$out"
  fi

  out="$(run_in_sandbox true "--mount \"$CRED_DIR/link:/sandbox-secrets/credproof:ro\"")"
  rc=$?
  if [ "$rc" -eq 12 ]; then
    proven "credential root symlink escape" "rc=$rc"
  else
    failed "credential root symlink escape" "rc=$rc (wanted 12)" "$out"
  fi

  out="$(run_in_sandbox true "--workspace \"\$HOME/.local/state/overdeck-sandbox/creds/containproof-ws\"")"
  rc=$?
  absent=0
  run_host 'test ! -e "$HOME/.local/state/overdeck-sandbox/creds/containproof-ws"' >/dev/null 2>&1 && absent=1
  if [ "$rc" -eq 12 ] && [ "$absent" -eq 1 ]; then
    proven "credential root workspace" "rc=$rc, host path never created"
  else
    failed "credential root workspace" "rc=$rc (wanted 12), host-path-absent=$absent (wanted 1)" "$out"
  fi
fi

out="$(run_in_sandbox 'python3 -c "
blocks = []
for i in range(8):
    blocks.append(bytearray(32 * 1024 * 1024))
    print(\"allocated\", (i + 1) * 32, flush=True)
"' '--memory 64m')"
rc=$?
reason="$(run_host "cat $REASON_FILE")"
if printf '%s' "$reason" | grep -q 'oomkilled=true'; then
  proven "oom is attributable" "rc=$rc reason: $reason"
else
  failed "oom is attributable" "rc=$rc reason: $reason" "$out"
fi

out="$(run_in_sandbox 'exit 42')"
rc=$?
reason="$(run_host "cat $REASON_FILE")"
if [ "$rc" -eq 42 ] && printf '%s' "$reason" | grep -q 'exit=42 container_exit=42'; then
  proven "exit code is attributable" "rc=$rc reason: $reason"
else
  failed "exit code is attributable" "rc=$rc (wanted 42) reason: $reason" "$out"
fi

echo
if [ "$FAILURES" -eq 0 ]; then
  echo "all containment proofs held"
else
  echo "$FAILURES containment proof(s) FAILED"
fi
exit "$FAILURES"
