#!/usr/bin/env bash
# Proves the class-1 resource ceilings actually bind, by hitting them from inside a
# live sandbox. Every attempt is bounded by the test program itself — the process count
# and the byte count are both capped well below anything the box would notice, so this
# is not exhaustion-class code and does not need the danger lab. If a ceiling were
# missing the test would still stop at its own cap, and report the ceiling as unproven.
set -uo pipefail

HOST="${1:-debian1}"
SSH=(ssh -F "$HOME/.ssh/config" -o BatchMode=yes "$HOST")
FAILURES=0

sandbox() { # flags... -- script
  local flags=() script
  while [ "$1" != "--" ]; do flags+=("$1"); shift; done
  shift; script="$1"
  "${SSH[@]}" ".local/share/overdeck-sandbox/bin/sandbox-run --id ceilingproof ${flags[*]} -- /bin/bash -c $(printf '%q' "$script")" 2>&1
}

report() { # name ok detail
  if [ "$2" = 1 ]; then printf 'PROVEN       %-28s %s\n' "$1" "$3"
  else printf 'PROVE-FAIL   %-28s %s\n' "$1" "$3"; FAILURES=$((FAILURES + 1)); fi
}

echo "=== agent sandbox resource ceilings on $HOST ==="

out="$(sandbox --pids 64 -- 'python3 -c "
import subprocess
kids = []
for i in range(200):
    try:
        kids.append(subprocess.Popen([\"sleep\",\"60\"]))
    except OSError as e:
        print(\"forks-before-refusal\", len(kids), type(e).__name__)
        break
else:
    print(\"forks-before-refusal none-refused\", len(kids))
for k in kids: k.kill()
"')"
n="$(printf '%s' "$out" | awk '/forks-before-refusal/ {print $2}')"
if [ "$n" != "none-refused" ] && [ -n "$n" ] && [ "$n" -lt 64 ]; then
  report "pids ceiling binds" 1 "fork refused after $n processes with --pids 64"
else
  report "pids ceiling binds" 0 "$out"
fi

out="$(sandbox --memory 256m -- 'python3 -c "
blocks = []
for i in range(16):
    blocks.append(bytearray(32 * 1024 * 1024))
    print(\"allocated\", (i + 1) * 32, flush=True)
print(\"reached-512m-without-a-ceiling\")
"')"
rc=$?
if printf '%s' "$out" | grep -q 'reached-512m-without-a-ceiling'; then
  report "memory ceiling binds" 0 "512 MiB allocated inside a 256 MiB container"
else
  report "memory ceiling binds" 1 "killed at $(printf '%s' "$out" | awk '/allocated/ {n=$2} END {print n+0}') MiB with --memory 256m (rc=$rc)"
fi

out="$(sandbox --memory 256m -- 'cat /sys/fs/cgroup/memory.swap.max /sys/fs/cgroup/pids.max /sys/fs/cgroup/memory.max')"
if printf '%s' "$out" | head -1 | grep -qx 0; then
  report "swap is off" 1 "$(printf '%s' "$out" | tr '\n' ' ')"
else
  report "swap is off" 0 "$out"
fi

echo
[ "$FAILURES" -eq 0 ] && echo "all ceiling proofs held" || echo "$FAILURES ceiling proof(s) FAILED"
exit "$FAILURES"
