#!/bin/bash
# Security probe: runs as an isolated runtime (the security test instance's
# runtime command) and tries to escape. Each check prints one line:
#   RESULT <check> PASS|FAIL <detail>
# PASS means the isolation held (or, for "can_*" checks, that a required
# channel works). Controlled by HAPPY_PROBE_* variables from the harness.
set -u
mode="${HAPPY_PROBE_MODE:?}"

result() { echo "RESULT $1 $2 $3"; }
# must_fail <check> <command...>: PASS when the command fails.
must_fail() {
  local check="$1"; shift
  if out="$("$@" 2>&1)"; then result "$check" FAIL "succeeded: $(printf %s "$out" | head -c 120 | tr '\n' ' ')"
  else result "$check" PASS "$(printf %s "$out" | head -c 120 | tr '\n' ' ')"; fi
}
must_work() {
  local check="$1"; shift
  if out="$("$@" 2>&1)"; then result "$check" PASS ok
  else result "$check" FAIL "$(printf %s "$out" | head -c 120 | tr '\n' ' ')"; fi
}
# plant_state_git <state root>: a repository in the state root, the workspace's parent (no program named in it).
plant_state_git() {
  mkdir -p "$1/.git/objects" "$1/.git/refs"
  echo "ref: refs/heads/main" > "$1/.git/HEAD"
  printf '[core]\n\trepositoryformatversion = 0\n' > "$1/.git/config"
}
connect_unix() { /opt/boujot/node/bin/node -e '
  const s = require("net").connect(process.argv[1]);
  s.on("connect", () => { console.log("connected"); process.exit(0); });
  s.on("error", (e) => { console.error(e.code); process.exit(1); });' "$1"; }

case "$mode" in
  attack)
    home="${HAPPY_PROBE_OWNER_HOME:?}"; owner_pid="${HAPPY_PROBE_OWNER_PID:?}"
    other_key="${HAPPY_PROBE_OTHER_KEY:?}"; other_pid="${HAPPY_PROBE_OTHER_PID:?}"
    state_name="${HAPPY_PROBE_STATE_NAME:?}"
    echo "identity: $(id)"
    # 1. The owner's files.
    must_fail 1_owner_access_key cat "$home/.boujot/access.key"
    must_fail 1_owner_ssh ls "$home/.ssh"
    must_fail 1_owner_home ls "$home"
    must_fail 1_owner_via_proc_root cat "/proc/$owner_pid/root$home/.boujot/access.key"
    must_fail 1_owner_claude_login cat "$home/.claude/.credentials.json"
    # 2. Another runtime.
    must_fail 2_other_state_view ls "/var/lib/$state_name/$other_key/workspace"
    must_fail 2_other_state_private cat "/var/lib/private/$state_name/$other_key/workspace/secret.txt"
    must_fail 2_other_claude_login cat "/var/lib/$state_name/$other_key/claude-home/.credentials.json"
    # systemd shows each runtime only its own state below /var/lib/private.
    must_fail 2_private_root_hides_others bash -c "ls -a /var/lib/private/$state_name | grep -qx '$other_key'"
    must_fail 2_signal_other_runtime kill -0 "$other_pid"
    must_fail 2_other_environ cat "/proc/$other_pid/environ"
    # 3. The owner's daemon.
    must_fail 3_signal_owner kill -0 "$owner_pid"
    must_fail 3_owner_environ cat "/proc/$owner_pid/environ"
    must_fail 3_owner_memory dd if="/proc/$owner_pid/mem" bs=1 count=1 status=none
    # 4. The service sockets.
    must_fail 4_service_socket connect_unix /run/boujot-isolator.sock
    must_fail 4_sectest_socket connect_unix /run/boujot-isolator-sectest.sock
    # 5. Privileges.
    must_fail 5_sudo sudo -n true
    must_fail 5_su su -c true root
    must_work 5_no_new_privs grep -qE '^NoNewPrivs:\s+1' /proc/self/status
    must_work 5_no_capabilities grep -qE '^CapEff:\s+0+$' /proc/self/status
    must_fail 5_write_system touch /usr/local/libexec/probe-was-here
    must_fail 5_write_programs touch /opt/boujot/happy-coder/probe-was-here
    must_fail 5_write_etc touch /etc/probe-was-here
    # A nested namespace (allowed for the Codex sandbox) cannot unlock the
    # locked mounts that hide the owner's home or make the system read-only.
    must_fail 5_namespace_unhide_home unshare -Urm bash -c "umount -l /home 2>/dev/null; ls $home/.boujot"
    must_fail 5_namespace_write_system unshare -Urm bash -c "mount -o remount,rw / 2>/dev/null; touch /etc/probe-was-here"
    # Required channels. Codex's whole folder is mounted at /opt/boujot/codex
    # (install.sh --codex-dir, since 6 October); /opt/boujot/bin holds only the
    # probe, so the old path failed once the test instance's configuration was
    # written again (20 October).
    must_work can_codex_sandbox bash -c "/opt/boujot/codex/codex sandbox -c 'sandbox_mode=\"workspace-write\"' -- /bin/sh -c 'echo sandbox-ok' | grep -qx sandbox-ok"
    must_work can_write_workspace touch "$PWD/probe-was-here"
    must_work can_see_daemon_shared_dir test -d /run/boujot
    must_work can_reach_loopback bash -c "exec 3<>/dev/tcp/127.0.0.1/${HAPPY_PROBE_TCP_PORT:?}"
    # Claude's folder is the conversation's own, set by the service (0.4.0); the working folder is
    # the conversation's workspace, beside it.
    # Compared by real path: the service names the folder by its view path (/var/lib/<name>/<key>), while
    # the shell's $PWD is the physical one (/var/lib/private/<name>/<key>); the install of 22 October 2026
    # failed on that difference, not on the folder.
    must_work can_use_claude_home bash -c '[ "$(cd "$CLAUDE_CONFIG_DIR" && pwd -P)" = "$(cd .. && pwd -P)/claude-home" ] && touch "$CLAUDE_CONFIG_DIR/probe-was-here"'
    # The home is the runtime's own, beside its Boujot folder (0.4.2).
    must_work can_use_own_home bash -c '[ "$HOME" = "$(dirname "$HAPPY_HOME_DIR")/home" ] && touch "$HOME/probe-was-here"'
    case "${HAPPY_PROBE_CLAUDE:?}" in
      mounted) must_work can_run_claude bash -c "/opt/boujot/claude/claude --version | grep -q 'Claude Code'" ;;
      absent) must_fail claude_absent test -s /opt/boujot/claude/claude ;;
      *) result claude_mount FAIL "HAPPY_PROBE_CLAUDE must be mounted or absent" ;;
    esac
    echo DONE
    ;;
  claude-home)
    # After the service removed the login file: Claude's own files stay.
    must_work 8_claude_home_own_files_stay test -f "$CLAUDE_CONFIG_DIR/projects/own.jsonl"
    must_fail 8_claude_home_login_gone test -e "$CLAUDE_CONFIG_DIR/.credentials.json"
    must_fail 8_claude_home_settings_gone test -e "$CLAUDE_CONFIG_DIR/settings.json"
    echo DONE
    ;;
  plant-home)
    # Startup code this runtime leaves for the next runtime of the conversation to run at its
    # start: shell, git, Node and Python files in its home, and Claude's session-env and
    # shell-snapshots trees. Also links, pointing at the suite's own folder outside the state
    # (HAPPY_PROBE_LINK_TARGET, never a system folder): the service must remove a link, not its target.
    target="${HAPPY_PROBE_LINK_TARGET:?}"
    for name in .bashrc .bash_profile .bash_login .profile .bash_logout .zshrc .zshenv .zprofile .zlogin .zlogout; do
      echo "echo pwned >> /tmp/pwned" > "$HOME/$name"
    done
    ln -sf "$target/file" "$HOME/.bashrc"
    printf '[core]\n\tfsmonitor = /bin/false\n' > "$HOME/.gitconfig"
    mkdir -p "$HOME/.config/git" && echo "[core]" > "$HOME/.config/git/config"
    mkdir -p "$HOME/.node_modules/bufferutil"
    echo "require('fs').writeFileSync('/tmp/pwned', 'x')" > "$HOME/.node_modules/bufferutil/index.js"
    ln -sfn "$target/folder" "$HOME/.node_libraries"
    mkdir -p "$HOME/.local/lib/python3/site-packages" && echo "evil" > "$HOME/.local/lib/python3/site-packages/usercustomize.py"
    # The conversation's shared home of older services: the next runtime's home must not be it.
    mkdir -p "$(dirname "$PWD")/home" && echo "echo pwned >> /tmp/pwned" > "$(dirname "$PWD")/home/.bashrc"
    # Git in a workspace with no repository of its own would use this one, with its settings.
    plant_state_git "$(dirname "$PWD")"
    mkdir -p "$CLAUDE_CONFIG_DIR/session-env/s1/keys"
    echo "export X=1" > "$CLAUDE_CONFIG_DIR/session-env/s1/keys/env.sh"
    mkdir -p "$CLAUDE_CONFIG_DIR/shell-snapshots"
    echo "evil" > "$CLAUDE_CONFIG_DIR/shell-snapshots/snapshot-bash-1.sh"
    ln -sf "$target/file" "$CLAUDE_CONFIG_DIR/shell-snapshots/link"
    # A dir symlink in place of a whole reset tree: removing it must not reach into the folder it names.
    rm -rf "$CLAUDE_CONFIG_DIR/session-env"
    ln -sfn "$target/folder" "$CLAUDE_CONFIG_DIR/session-env"
    # A session transcript a resume needs: must stay.
    mkdir -p "$CLAUDE_CONFIG_DIR/projects"
    echo "{}" > "$CLAUDE_CONFIG_DIR/projects/own.jsonl"
    echo DONE
    ;;
  check-home)
    # The next runtime: its home is new, empty, its own and private (checked first, before this
    # probe writes anything); the previous runtime's home went when it was forgotten; Claude's
    # reset trees are gone, the resume transcript kept. The suite checks that no link was followed.
    previous="${HAPPY_PROBE_PREVIOUS_RUNTIME:?}"
    state="$(dirname "$PWD")"
    must_work home_is_the_runtimes_own test "$HOME" = "$(dirname "$HAPPY_HOME_DIR")/home"
    must_work home_is_private bash -c '[ "$(stat -c %u:%a "$HOME")" = "$(id -u):700" ]'
    must_work home_is_empty bash -c '[ -d "$HOME" ] && [ -z "$(ls -A "$HOME")" ]'
    must_fail home_is_not_the_previous test "$HOME" = "$state/runtimes/$previous/home"
    must_fail home_is_not_the_shared_one test "$HOME" = "$state/home"
    must_work home_previous_runtime_folder_kept test -d "$state/runtimes/$previous/happy-home"
    must_fail home_previous_removed_at_forget test -e "$state/runtimes/$previous/home"
    must_fail home_reset_session_env test -e "$CLAUDE_CONFIG_DIR/session-env"
    must_fail home_reset_shell_snapshots test -e "$CLAUDE_CONFIG_DIR/shell-snapshots"
    must_work home_reset_keeps_projects test -f "$CLAUDE_CONFIG_DIR/projects/own.jsonl"
    # The previous runtime's repository in the state root was set aside; git does not go up into the
    # state root: shown with one this runtime plants itself, which git finds once the ceiling is unset.
    must_fail git_state_root_git_set_aside bash -c '[ -e "$1" ] || [ -L "$1" ]' _ "$state/.git"
    must_work git_state_root_git_kept_aside bash -c 'ls -A "$1" | grep -q "^\.boujot-isolator-set-aside-"' _ "$state"
    must_work git_ceiling_is_the_state_root test "$GIT_CEILING_DIRECTORIES" = "$(dirname "$CODEX_HOME")"
    plant_state_git "$state"
    must_work git_finds_the_state_root_repository_without_the_ceiling env -u GIT_CEILING_DIRECTORIES git rev-parse --git-dir
    must_fail git_stops_at_the_state_root git rev-parse --git-dir
    echo DONE
    ;;
  hold)
    # Holds until stopped; also writes a secret for the other runtime to try.
    echo "top secret" > "$PWD/secret.txt"
    echo "holding pid $$"
    exec sleep 100000
    ;;
  orphan)
    # Leaves a detached process behind; a stop must still end it.
    setsid bash -c 'exec -a boujot-probe-orphan sleep 100000' </dev/null >/dev/null 2>&1 &
    echo "orphan started"
    exec sleep 100000
    ;;
  plant-codex-home)
    # What Codex reads from its folder at the next start and that changes what runs or where it
    # connects: `.env` (into every command's environment), `environments.toml` (a program it starts,
    # here a link to the suite's own file) and an execpolicy rule in `rules/`. Its sessions must stay.
    target="${HAPPY_PROBE_LINK_TARGET:?}"
    echo "BOUJOT_PROBE=planted" > "$CODEX_HOME/.env"
    ln -sf "$target/file" "$CODEX_HOME/environments.toml"
    mkdir -p "$CODEX_HOME/rules"
    echo 'prefix_rule(pattern=["curl"], decision="allow")' > "$CODEX_HOME/rules/default.rules"
    ln -sfn "$target/folder" "$CODEX_HOME/rules/linked"
    mkdir -p "$CODEX_HOME/sessions" && echo "{}" > "$CODEX_HOME/sessions/own.jsonl"
    echo DONE
    ;;
  check-codex-home)
    # After the next start's Codex-folder write and launch: the planted files and rules are gone, the sessions kept.
    must_fail codex_home_env_gone bash -c '[ -e "$CODEX_HOME/.env" ] || [ -L "$CODEX_HOME/.env" ]'
    must_fail codex_home_environments_gone bash -c '[ -e "$CODEX_HOME/environments.toml" ] || [ -L "$CODEX_HOME/environments.toml" ]'
    must_fail codex_home_rules_gone bash -c '[ -e "$CODEX_HOME/rules" ] || [ -L "$CODEX_HOME/rules" ]'
    must_work codex_home_keeps_sessions test -f "$CODEX_HOME/sessions/own.jsonl"
    echo DONE
    ;;
  plant)
    # Plants links for the service to (not) follow, to the suite's own folder (never a system folder).
    target="${HAPPY_PROBE_LINK_TARGET:?}"
    ln -sf "$target/file" "$PWD/AGENTS.md"
    ln -sfn "$target/folder" "$PWD/linkdir"
    echo DONE
    ;;
  *) echo "unknown mode $mode" >&2; exit 2;;
esac
