#!/usr/bin/env bash
# test-gate.sh -- exercise the /private/ signed-token gate.
#
# Usage:
#   BASE=https://guerin.acequia.org \
#   FILE=/private/.agents/5b58043a-0677-4d60-bf36-62d51f2bafa9/about.md \
#   VALID_TOKEN="<a freshly minted PS256 JWT>" \
#   ./test-gate.sh
#
# Cases:
#   1. no token          -> expect 403
#   2. bad/garbage token -> expect 403
#   3. valid token       -> expect 200  (only if VALID_TOKEN is set)
#
# Everything is parameterized so it runs once deployed. Mint VALID_TOKEN with
# the recipe in ../.well-known/KEYGEN.md (Step 3). Leave VALID_TOKEN empty to
# run only the negative cases.

set -u

BASE="${BASE:-https://guerin.acequia.org}"
FILE="${FILE:-/private/.agents/5b58043a-0677-4d60-bf36-62d51f2bafa9/about.md}"
VALID_TOKEN="${VALID_TOKEN:-}"
URL="${BASE}${FILE}"

pass=0
fail=0

# check <label> <expected-code> <actual-code>
check() {
  local label="$1" expected="$2" actual="$3"
  if [ "$actual" = "$expected" ]; then
    echo "PASS  $label  (got $actual)"
    pass=$((pass + 1))
  else
    echo "FAIL  $label  (expected $expected, got $actual)"
    fail=$((fail + 1))
  fi
}

echo "Target: $URL"
echo

# 1. no token -> 403
code=$(curl -s -o /dev/null -w '%{http_code}' "$URL")
check "no token -> 403" 403 "$code"

# 2. bad token -> 403  (well-formed-looking garbage, and via ?token= too)
code=$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer not.a.jwt" "$URL")
check "bad bearer -> 403" 403 "$code"
code=$(curl -s -o /dev/null -w '%{http_code}' "${URL}?token=aaa.bbb.ccc")
check "bad ?token= -> 403" 403 "$code"

# 3. valid token -> 200  (only if provided)
if [ -n "$VALID_TOKEN" ]; then
  code=$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $VALID_TOKEN" "$URL")
  check "valid bearer -> 200" 200 "$code"
  code=$(curl -s -o /dev/null -w '%{http_code}' "${URL}?token=${VALID_TOKEN}")
  check "valid ?token= -> 200" 200 "$code"
else
  echo "SKIP  valid-token cases (set VALID_TOKEN to run them)"
fi

echo
echo "Results: $pass passed, $fail failed"
[ "$fail" -eq 0 ]
