#!/usr/bin/env bash
#
# Check 3 — production behavioral RLS probe (admin-gated).
#
# Runs POST /api/internal/rls-diagnostic against the live deployment as an admin,
# handling login + CSRF token automatically, and prints a plain PASS/FAIL summary
# plus the full JSON to paste back to the agent.
#
# Requires: RLS_DIAGNOSTIC_ENABLED=true in the prod scope (enabled for this probe)
#           and your PRODUCTION ADMIN login (the one you use for the deployed app).
#
# Usage:
#   bash scripts/rls-check3-prod.sh
#
set -euo pipefail

BASE="${AEGIS_PROD_URL:-https://aegis-cyber.replit.app}"
JAR="$(mktemp)"; RESP="$(mktemp)"; CSRFJSON="$(mktemp)"
cleanup() { rm -f "$JAR" "$RESP" "$CSRFJSON"; }
trap cleanup EXIT

echo "Target: $BASE"
read -rp "Admin username: " ADMIN_USER
read -rsp "Admin password: " ADMIN_PASS; echo
export ADMIN_USER ADMIN_PASS

# Build + send the login body. The JSON (with proper escaping) is generated by node
# reading the creds from the environment and STREAMED to curl over stdin (--data @-),
# so the password is never written to a temp file, a command line, or shell history.
# Bounded, accepted residual: the password transits the short-lived node child-process
# environment (readable only by the same OS user via /proc during the call). Run this
# only on a machine you trust, as that user.
login() {
  node -e 'const b={username:process.env.ADMIN_USER,password:process.env.ADMIN_PASS};if(process.env.TOTP)b.totpToken=process.env.TOTP;process.stdout.write(JSON.stringify(b));' \
    | curl -s -c "$JAR" -H "Content-Type: application/json" --data @- -o "$RESP" -w "%{http_code}" "$BASE/api/auth/login"
}

echo "--- logging in ---"
code=$(login)
echo "login HTTP: $code"

if grep -q '"requires2FA":true' "$RESP"; then
  read -rp "2FA code: " TOTP; export TOTP
  code=$(login)
  echo "login (2FA) HTTP: $code"
fi
unset ADMIN_PASS TOTP

if ! grep -q '"success":true' "$RESP"; then
  echo "LOGIN FAILED — server said:"; cat "$RESP"; echo; exit 1
fi

echo "--- fetching CSRF token ---"
curl -s -b "$JAR" -c "$JAR" "$BASE/api/csrf-token" -o "$CSRFJSON"
CSRF=$(node -e 'try{console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8")).csrfToken||"")}catch{console.log("")}' "$CSRFJSON")
if [ -z "$CSRF" ]; then echo "Could not obtain CSRF token; response was:"; cat "$CSRFJSON"; echo; exit 1; fi

echo "--- running RLS diagnostic (POST /api/internal/rls-diagnostic) ---"
code=$(curl -s -b "$JAR" -X POST -H "X-CSRF-Token: $CSRF" -H "Content-Type: application/json" -o "$RESP" -w "%{http_code}" "$BASE/api/internal/rls-diagnostic")
echo "diagnostic HTTP: $code"
if [ "$code" = "404" ]; then
  echo "Got 404 — RLS_DIAGNOSTIC_ENABLED is not active on the running deployment."
  echo "(The flag must be set in the prod scope BEFORE the deploy that serves this request.)"
  exit 1
fi
if [ "$code" = "403" ]; then
  echo "Got 403 — that account is not an admin. Use your platform ADMIN login."
  exit 1
fi

echo ""
echo "================= CHECK 3 RESULT ================="
node -e '
const d=JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"));
if(d.summary){
  console.log("environment :", d.environment);
  console.log("result      :", d.summary.passed+"/"+d.summary.total+" passed, "+d.summary.failed+" failed, cleanupFailures="+d.summary.cleanupFailures);
  console.log("allPass     :", d.summary.allPass);
  const fails=(d.probes||[]).filter(p=>p.result!=="PASS");
  if(fails.length){console.log("FAILED probes:");fails.forEach(p=>console.log("  - "+p.probe+(p.detail?(" | "+p.detail):"")));}
  else{console.log("every probe PASSED (including cross-tenant DENIED).");}
}else{console.log("Unexpected response:");console.log(JSON.stringify(d,null,2));}
' "$RESP"
echo "=================================================="
echo ""
echo ">>> Copy everything below and paste it back to the agent <<<"
echo "----------------------------------------------------------------"
cat "$RESP"; echo
echo "----------------------------------------------------------------"
