#!/usr/bin/env bash
# scan.sh — lead generator for graphql-ruby unsafe-dispatch / validate-vs-execute bugs.
#
# Read-only. Emits grouped hits keyed to the pattern IDs in references/patterns.md.
# This is NOT a verdict: every hit is triaged by hand against the five questions in SKILL.md.
#
# Noisy patterns (send/constantize, validate:false, trace ivars) are scoped to the repo's
# GraphQL surface — files under a graphql/ directory or mentioning GraphQL:: — because
# app-wide they match thousands of irrelevant ActiveRecord and migration lines.
#
# Usage:  scan.sh [repo_root] [--paths] [--all]
#           repo_root   default: .
#           --paths     print only the deduplicated file list (for feeding into reads)
#           --all       do not scope the noisy patterns to the GraphQL surface

set -uo pipefail

ROOT="."; PATHS_ONLY=0; NO_SCOPE=0
for a in "$@"; do
  case "$a" in
    --paths) PATHS_ONLY=1 ;;
    --all)   NO_SCOPE=1 ;;
    -*)      echo "unknown flag: $a" >&2; exit 2 ;;
    *)       ROOT="$a" ;;
  esac
done

command -v rg >/dev/null || { echo "scan.sh needs ripgrep (rg)" >&2; exit 1; }
[[ -d "$ROOT" ]] || { echo "not a directory: $ROOT" >&2; exit 1; }

RGOPTS=(--no-messages --line-number --color never
        --glob '!vendor/**' --glob '!node_modules/**' --glob '!tmp/**' --glob '!log/**'
        --glob '!.git/**' --glob '!db/migrate/**' --glob '!db/post_migrate/**'
        --glob '*.rb' --glob '*.rake' --glob 'Gemfile*')

TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
HITFILES="$TMP/hits"; GQLLIST="$TMP/gqlfiles"; : > "$HITFILES"

# ── the GraphQL surface: files under a graphql/ dir, or mentioning GraphQL:: ─────
{
  rg "${RGOPTS[@]}" --files "$ROOT" 2>/dev/null | grep -E '/graphql/|_schema\.rb$' || true
  rg "${RGOPTS[@]}" -l -e 'GraphQL::' "$ROOT" 2>/dev/null || true
} | sort -u > "$GQLLIST"
GQLN="$(grep -c . "$GQLLIST" || echo 0)"

# search <scope: all|gql> <pattern...>  -> "file:line:text" lines on stdout
search() {
  local scope="$1"; shift
  local args=(); local p; for p in "$@"; do args+=(-e "$p"); done
  if [[ "$scope" == gql && $NO_SCOPE -eq 0 && "$GQLN" != 0 ]]; then
    tr '\n' '\0' < "$GQLLIST" | xargs -0 --no-run-if-empty \
      rg "${RGOPTS[@]}" "${args[@]}" -- 2>/dev/null || true
  else
    rg "${RGOPTS[@]}" "${args[@]}" "$ROOT" 2>/dev/null || true
  fi
}

TOTAL=0
sec() { # sec <id> <title> <why> <scope> <pattern...>
  local id="$1" title="$2" why="$3" scope="$4"; shift 4
  local out n; out="$(search "$scope" "$@")"; n="$(printf '%s' "$out" | grep -c . || true)"
  TOTAL=$((TOTAL + n))
  [[ -n "$out" ]] && printf '%s\n' "$out" | cut -d: -f1 >> "$HITFILES"
  (( PATHS_ONLY )) && return 0
  printf '\n\033[1m── %s  %s\033[0m  (%s hit%s%s)\n' "$id" "$title" "$n" \
    "$([[ $n == 1 ]] || echo s)" "$([[ $scope == gql && $NO_SCOPE -eq 0 ]] && echo ', graphql surface only')"
  printf '   %s\n' "$why"
  if [[ -n "$out" ]]; then printf '%s\n' "$out" | sed 's/^/   /'; else printf '   —\n'; fi
}

both() { # both <id> <title> <why> <scope> <pat_a> <pat_b>  -- files matching BOTH
  local id="$1" title="$2" why="$3" scope="$4" a="$5" b="$6"
  local files n
  files="$(comm -12 <(search "$scope" "$a" | cut -d: -f1 | sort -u) \
                    <(search "$scope" "$b" | cut -d: -f1 | sort -u) 2>/dev/null || true)"
  n="$(printf '%s' "$files" | grep -c . || true)"
  TOTAL=$((TOTAL + n))
  [[ -n "$files" ]] && printf '%s\n' "$files" >> "$HITFILES"
  (( PATHS_ONLY )) && return 0
  printf '\n\033[1m── %s  %s\033[0m  (%s file%s)\n' "$id" "$title" "$n" "$([[ $n == 1 ]] || echo s)"
  printf '   %s\n' "$why"
  if [[ -n "$files" ]]; then printf '%s\n' "$files" | sed 's/^/   /'; else printf '   —\n'; fi
}

# ── P0 ── orientation ───────────────────────────────────────────────────────────
if ! (( PATHS_ONLY )); then
  printf '\033[1mgraphql-ruby unsafe-dispatch sweep\033[0m — %s\n' "$(cd "$ROOT" && pwd)"
  printf '   graphql surface: %s files\n' "$GQLN"

  printf '\n\033[1m── P0a  gem and version\033[0m\n'
  { rg --no-messages -n '^\s+graphql(-c_parser)? \([0-9]' "$ROOT"/Gemfile.lock "$ROOT"/gems.locked 2>/dev/null
    rg --no-messages -n "gem ['\"]graphql['\"]" "$ROOT"/Gemfile "$ROOT"/gems.rb 2>/dev/null
    rg --no-messages -n "dependency ['\"]graphql['\"]" "$ROOT"/*.gemspec 2>/dev/null; } \
    | sed 's/^/   /' | sort -u \
    || printf '   none found — confirm the target uses graphql-ruby before continuing\n'

  printf '\n\033[1m── P0b  schema classes\033[0m\n'
  SCHEMAS="$(rg "${RGOPTS[@]}" -l -e 'class .*<\s*GraphQL::Schema\b' "$ROOT" 2>/dev/null | sort -u || true)"
  printf '%s\n' "${SCHEMAS:-   —}" | sed 's/^\.\//   .\//'

  printf '\n\033[1m── P0b2  base type classes (a module mixed in here hits every type at once)\033[0m\n'
  rg "${RGOPTS[@]}" -l -e 'class \w*Base(Object|Interface|Field|Mutation|Subscription)\b|module \w*Base(Object|Interface)\b|include GraphQL::Schema::Interface' "$ROOT" 2>/dev/null \
    | sort -u | sed 's/^/   /' || printf '   —\n'

  printf '\n\033[1m── P0d  entry points: where the schema actually executes\033[0m\n'
  printf '   Read the surrounding code: this is where `context:` (current_user, scopes) is\n'
  printf '   built, and therefore where "who can trigger it" is decided.\n'
  search all '\w*Schema\.(execute|multiplex)\(' \
             '(post|get|match|map|mount|run)\s+["'"'"'/][^\n]*graphql' \
             'GraphQL::Dashboard|GraphiQL' \
    | grep -Ev '/(spec|test|tooling)/|_spec\.rb:|_test\.rb:' \
    | sed 's/^/   /' | head -40 || printf '   —\n'

  printf '\n\033[1m── P0c  what the schema registers  (the highest-signal read in the repo)\033[0m\n'
  printf '   Everything here is reachable by whoever can reach the endpoint.\n'
  if [[ -n "$SCHEMAS" ]]; then
    printf '%s\n' "$SCHEMAS" | tr '\n' '\0' | xargs -0 --no-run-if-empty \
      rg --no-messages -n -e '^\s*(trace_with|tracer|directive|query_analyzer|multiplex_analyzer|instrument|use|introspection|disable_introspection|validate_|default_max_page_size|max_complexity|max_depth|complexity_cost)' \
      -- 2>/dev/null | sed 's/^/   /' || printf '   —\n'
  else printf '   —\n'; fi
fi

# ── P1 ── validate one document, execute another ────────────────────────────────
sec P1a "document swap between validate and execute" \
  "The AST handed to StaticValidation and the analyzers must be the AST the interpreter runs." all \
  'instance_variable_set\(\s*:@(document|query_string)' \
  '\bprepare_ast\b' \
  '@(original|unfiltered|full|raw|saved|pristine)_[a-z_]*(document|query)' \
  'query\.document\s*='

both P1b "trace module defining BOTH parse and execute" \
  "The canonical seat for the split. Read the whole file and follow every ivar." all \
  'def parse\(\s*query_string:' 'def (execute_query|execute_multiplex)\(\s*(query|multiplex):'

sec P1c "validation switched off" \
  "validate: false on a query path that handles client input is P1 without the subtlety." gql \
  '(Query\.new|execute|multiplex)[^#\n]*validate:\s*false' \
  '^\s*validate:\s*false'

# ── P2 ── field synthesized from a client-supplied name ─────────────────────────
sec P2 "dynamic Schema::Field construction / fallback_value" \
  "If name: is not a literal and no method:/hash_key:/dig:/resolver_method: is given, the field name IS the method name. fallback_value is the LAST resort, after two public_sends." all \
  'GraphQL::Schema::Field\.new\(' \
  'fallback_value:' \
  '\bfield\(\s*(field_)?name\b'

# ── P3 ── get_field / fields overrides ──────────────────────────────────────────
sec P3 "get_field / fields(context) overrides (the dynamic-types API)" \
  "Fabricating a definition for a name super did not find removes FieldsAreDefinedOnType for that type. Overrides that only HIDE fields are fine." all \
  'def get_field\(' \
  'def fields\(\s*context' \
  'Schema::Member::HasFields'

# ── P4 ── dispatch target from request data ─────────────────────────────────────
sec P4 "dispatch target taken from request data" \
  "method:/hash_key:/resolver_method:/dig: computed from params/args/context is a client-chosen method with no validation hole needed." all \
  '(method|hash_key|resolver_method|dig):\s*(params|args|arguments|context|field_name|input|attribute|key)\b'

# ── P5 ── client-usable directives ──────────────────────────────────────────────
sec P5 "custom directives (client-supplied server instructions)" \
  "For each: registered unconditionally or feature-flagged? in the shipped introspection dump? does its handling touch the document or a context key other code branches on?" all \
  '<\s*GraphQL::Schema::Directive' \
  '^\s*locations\('

# ── P6 ── AST rewriting ─────────────────────────────────────────────────────────
sec P6 "AST rewriting visitors" \
  "Rewriting is fine only if the result is what BOTH validates and executes. Deleted subtrees are invisible to every rule, including the recursion and cost bounds." all \
  '<\s*GraphQL::Language::Visitor' \
  '\bDELETE_NODE\b'

# ── P7 ── reflection in resolvers / type resolution ─────────────────────────────
sec P7a "type resolution hooks" \
  "An unverified constantize in object_from_id is remote class instantiation. Is the global ID signed, and is the class name checked against a registry?" all \
  'def (resolve_type|object_from_id|id_from_object)\b'

sec P7b "send / constantize on the graphql surface" \
  "For each: is the reflected string schema-constrained (an enum coerces unknown literals to nil) or free-form?" gql \
  '(public_send|__send__|\.send\()' \
  '(safe_)?constantize|const_get'

# ── P8 ── per-query state on a shared trace ─────────────────────────────────────
both P8a "instance variables in a trace hook module" \
  "One trace instance serves an entire multiplex (Query#current_trace), so trace ivars are cross-query state. A rubocop suppression on this line is a strong tell." gql \
  'def (parse|lex|validate|analyze_query|analyze_multiplex|execute_query|execute_multiplex)\(\s*[a-z_]+:' \
  '^\s*@[a-z_]+\s*='

sec P8b "multiplex / batched query handling" \
  "If a per-entry security decision (CSRF, operation allowlist, rate limit) keys off the query string or operationName, P8a makes that decision about a different document than the one that runs." gql \
  'def multiplex|multiplex\(|\bmultiplex:'

# ── P9 ── analyzers and logging ─────────────────────────────────────────────────
sec P9 "query analyzers and logging (what detection can see)" \
  "If these read the filtered document, executed fields never reach the audit trail and contribute nothing to logged cost." all \
  '<\s*GraphQL::Analysis' \
  'used_fields|graphql_logs'

# ── P10 ── switches ─────────────────────────────────────────────────────────────
sec P10 "validation / introspection / cost switches" \
  "Context. A '__'-prefix guard on a fabricated-field path is evidence the author considered reflection — read what else they did and did not guard." all \
  'disable_introspection_entry_points' \
  "start_with\?\(['\"]__"

if (( PATHS_ONLY )); then
  sort -u "$HITFILES" | grep . || true
  exit 0
fi

printf '\n\033[1m── summary\033[0m\n'
printf '   %s hits across %s distinct files\n' "$TOTAL" "$(sort -u "$HITFILES" | grep -c . || echo 0)"
cat <<'EOF'

   Triage, do not tally. The finding is a COMPOSITION —
     P1 or P3   an unknown field name survives validation
   + P2 or P4   that name becomes the method that gets called
   + P5         a trigger any client can put in a query
   = client-chosen method invocation on server objects, with no authorization in the path.

   P1 alone is still a finding: recursion DoS, unhandled 500s, cost-control bypass, blind logs.

   Work the five questions in SKILL.md for each candidate, then prove reachability with
   scripts/census.rb before writing anything down.
EOF
