#!/bin/bash
# Installs the sandbox's fail-closed egress policy inside its own network
# namespace, then permanently sheds every capability before starting the
# requested command. The nft transaction is atomic: an invalid or unavailable
# ruleset leaves no window in which the agent command can run unrestricted.
#
# This runs as the keep-id user, never root: under --userns=keep-id the container
# process is pinned to the host uid, and nft works because podman grants
# --cap-add=NET_ADMIN as an ambient capability to non-root users. A uid switch
# here (setpriv --reuid) is impossible without CAP_SETUID and killed every
# launch with setresuid EPERM. For the same reason /usr/sbin/nft must stay
# world-executable (0755): the boundary is the NET_ADMIN capability, which the
# agent command loses below — a 0700 nft just kills the launch as non-root.
set -euo pipefail

RULES=/run/overdeck-egress/rules.nft
[ -r "$RULES" ] || { echo "sandbox-egress-init: egress rules are unavailable; refusing launch" >&2; exit 12; }

/usr/sbin/nft -f "$RULES" || {
  echo "sandbox-egress-init: could not install the egress firewall; refusing launch" >&2
  exit 12
}
installed="$(/usr/sbin/nft list chain inet overdeck_egress output 2>/dev/null)" || {
  echo "sandbox-egress-init: could not verify the egress firewall; refusing launch" >&2
  exit 12
}
grep -Eq 'type filter hook output .*policy drop' <<<"$installed" || {
  echo "sandbox-egress-init: egress firewall is not default-deny; refusing launch" >&2
  exit 12
}
git_path="$(command -v git 2>/dev/null || true)"
[ "$git_path" = /usr/local/bin/git ] && git --deny-gate-selftest || {
  echo "sandbox-egress-init: git deny gate is unavailable; refusing launch" >&2
  exit 12
}

exec /usr/bin/setpriv \
  --bounding-set=-all --inh-caps=-all --ambient-caps=-all \
  -- /usr/bin/tini -- "$@"
