#!/bin/sh
# Run the Claude Code CLI as the unprivileged `agent` user.
#
# The harness (root) invokes this as the agent binary. It hands the trial
# repo (cwd) and the fresh agent HOME to `agent`, gives traverse-only access to
# their ancestors, runs the CLI, then kills every `agent` process and returns
# ownership to root so the trusted oracle reads what the agent left, not a
# process still running. A SIGTERM from the harness timeout takes the same path.
set -u
REAL=/usr/local/bin/claude-real
AGENT=agent

# Runner egress policy: only the model provider's API host is reachable, via
# Cloudflare's HTTPS interception (its CA appears at runtime). Non-essential
# CLI traffic (telemetry, update checks) is disabled so it cannot stall on the
# blocked hosts. Both are fixed properties of this runner image.
CF_CA=/etc/cloudflare/certs/cloudflare-containers-ca.crt
[ -f "$CF_CA" ] && export NODE_EXTRA_CA_CERTS="$CF_CA"
export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 DISABLE_AUTOUPDATER=1

drop() { setpriv --reuid="$AGENT" --regid="$AGENT" --clear-groups --inh-caps=-all --bounding-set=-all -- "$@"; }

if [ "${1:-}" = "--version" ]; then
  drop "$REAL" --version
  exit $?
fi

[ "$(id -u)" = 0 ] || { echo "claude-contained: must start as root" >&2; exit 97; }
cwd=$(pwd -P)
case "$cwd" in /work/*) ;; *) echo "claude-contained: refusing cwd outside /work: $cwd" >&2; exit 97 ;; esac
case "${HOME:-}" in /work/*|/tmp/*) ;; *) echo "claude-contained: refusing HOME: ${HOME:-unset}" >&2; exit 97 ;; esac

pkill -KILL -u "$AGENT" 2>/dev/null
chown -R "$AGENT:$AGENT" "$cwd" "$HOME"
for start in "$cwd" "$HOME"; do
  d=$start
  while [ "$d" != / ]; do d=$(dirname "$d"); chmod o+x "$d" 2>/dev/null; done
done

restore() {
  pkill -KILL -u "$AGENT" 2>/dev/null
  chown -R root:root "$cwd" "$HOME"
}
child=
on_term() { [ -n "$child" ] && kill -TERM "$child" 2>/dev/null; restore; exit 143; }
trap on_term TERM INT

drop "$REAL" "$@" &
child=$!
wait "$child"
rc=$?
restore
exit "$rc"
