---
name: graphql-ruby-unsafe-dispatch
description: Audit any Ruby repo using graphql-ruby (Rails, Sinatra/Rack, Hanami, or a plain gem) for unsafe-dispatch and validate-vs-execute divergence bugs — attacker-named synthesized fields, get_field/fields overrides, trace hooks that swap the document between validation and execution, client-usable directives that rewrite the AST, and reflection in resolvers/type-resolution. Use when asked to review, audit, threat-model or bug-hunt a GraphQL API, when reviewing a diff that touches a GraphQL schema's base object/interface/field classes, tracers, analyzers or directives, or when checking whether a codebase repeats the known @gl_introduced / FutureFieldFallback pattern (unauthenticated arbitrary public_send). Ships a repo sweep, a reachable-method census and a live control/test prober.
---

# Auditing graphql-ruby for unsafe dispatch

## The bug class in one paragraph

graphql-ruby resolves a field by calling a **method named after the field** on the type
wrapper and then on the application object (`public_send`). The only thing that keeps a
client from choosing that method name is the static validation rule
`FieldsAreDefinedOnType`, which runs against the **parsed document** before execution.
Any app-level customization that (a) lets a field definition be *fabricated from a name the
client supplied*, or (b) makes the document that **validates** differ from the document that
**executes**, converts that into *client-chosen method invocation on server objects*. Field
and type authorization do not stop it — the fabricated field carries no `authorize`, and the
call happens on a parent object that was already authorized. This is CWE-470 (unsafe
reflection) reachable over plain HTTP, and in the known real-world instance it was reachable
**unauthenticated**.

**The invariant to test the repo against:**

> The document that static validation and every query analyzer inspect must be
> byte-for-byte the document the interpreter executes, and no field definition may ever be
> derived from a name that was not in the schema at boot.

## Step 0 — Confirm the target actually uses graphql-ruby

```bash
rg -n '^\s+graphql \(' Gemfile.lock          # gem + exact version
rg -n "gem ['\"]graphql" Gemfile
rg -l 'GraphQL::Schema' --type ruby | head
```

If `graphql` is absent, stop and say so. If `graphql-c_parser` is present, note it: that is
a separate native-parser attack surface, not this class.

Record the version. Everything below is stable across **2.x**; `references/gem-internals.md`
notes where 1.x and 2.6+ differ.

## Step 1 — Map the extension points before grepping

**Do not assume a layout.** `app/graphql/` is a Rails convention, not a requirement — the
same code lives in `lib/`, `graph/`, `api/`, an engine, or a gem. Find these by *definition*,
not by path (`scan.sh` prints all of it as P0, but know what you are looking at):

| What | How to find it | Why it matters |
|---|---|---|
| Schema class | `class X < GraphQL::Schema` | `trace_with` / `tracer` / `query_analyzer` / `directive` / `max_complexity` / `validate` registrations, all in one place |
| Entry points | `Schema.execute(` / `Schema.multiplex(` | where `context:` (current_user, scopes) is built — this decides *who can trigger it*. Expect several: HTTP controller, websocket channel, an internal service, a background job |
| Base object / interface / mutation / subscription | `class X < GraphQL::Schema::Object` etc. | a module mixed in here applies to **every** type at once |
| Base field | `class X < GraphQL::Schema::Field` | overrides of `resolve`, `initialize`, `authorized?` |
| Trace modules | `def parse(query_string:)` / `def execute_query(query:)` | the document-swap seat |
| Custom directives | `< GraphQL::Schema::Directive` | the client-reachable trigger |
| AST visitors | `< GraphQL::Language::Visitor` | document rewriting |
| Analyzers | `< GraphQL::Analysis::Analyzer` | what security telemetry sees (and misses) |

The schema class is the single highest-value file: whatever it registers is what a client can
reach. The entry points are second: a repo with more than one (an HTTP endpoint *and* a
websocket channel *and* an internal tool wrapper) usually builds `context` differently in
each, and the weakest one sets the reporter position.

In a monorepo or an app with engines, expect **more than one schema**. Enumerate them all;
`trace_with` on one is not `trace_with` on another.

## Step 2 — Sweep

Scripts live beside this file; `SKILL_DIR` below is this skill's directory.

```bash
"$SKILL_DIR"/scripts/scan.sh <repo_root>            # sweep, grouped by pattern ID
"$SKILL_DIR"/scripts/scan.sh <repo_root> --paths    # file list only, for feeding into reads
"$SKILL_DIR"/scripts/scan.sh <repo_root> --all      # don't scope noisy patterns to graphql files
```

Read-only, needs `ripgrep`. On a repo the size of GitLab it returns roughly 100 files —
triage-sized on purpose. The noisiest patterns (`send`, `constantize`, `validate: false`) are
scoped to the repo's GraphQL surface by default, since app-wide they match thousands of
irrelevant ActiveRecord lines.

The sweep is a *lead generator*, not a verdict. Expect benign hits (a `public_send` in a
legitimately dynamic resolver, a `Field.new` with a literal name). Every hit gets triaged by
hand.

The single highest-signal thing it prints is **P0c — what the schema registers**. Read that
before anything else: whatever is on that list is reachable by whoever can reach the endpoint.

## Step 3 — Triage each hit

[references/patterns.md](references/patterns.md) has the ten patterns (P1–P10) with, for
each: the grep signal, the gem-side mechanics that make it dangerous, the questions that
decide exploitability, and the confirmed real-world instance. Read it when you have hits to
classify. [references/gem-internals.md](references/gem-internals.md) has the resolution
order, the hook table and the arity argument — read it before writing any claim about what
`public_send` can and cannot reach.

For **any** candidate, five questions decide whether it is a finding:

1. **Who can trigger it?** Is the directive/header/param registered unconditionally, or
   behind a feature flag, an internal-client check, or authentication? Check the shipped
   introspection dump too — a directive in `introspection_result.json` is advertised to
   everyone. *Unauthenticated reachability is the difference between medium and critical.*
2. **Does validate-doc ≠ execute-doc?** If yes, note that this blinds **all** of:
   `FieldsAreDefinedOnType`, `FragmentsAreFinite`, `DirectivesAreDefined`, `FieldsWillMerge`,
   `ArgumentsAreDefined`, `RequiredArgumentsArePresent`, `max_depth`, `max_complexity`, every
   custom analyzer, and the query log. The `public_send` gadget is usually the sharpest
   consequence but never the only one — check for unbounded recursion and 500s too.
3. **Where does the fabricated field resolve to?** Does it carry `method:`, `hash_key:`,
   `dig:`, `resolver_method:` or `resolver:`? If none, the field name **is** the method name
   and both the wrapper and the application object are tried. `fallback_value:` does **not**
   make a field inert — it is consulted only *after* both `public_send` attempts fail.
4. **Can arguments be delivered?** This is the RCE line. Zero arguments means no
   `update_columns(admin: true)`, no `eval`, no setters. One delivered argument means
   arbitrary column writes (Ruby ≥3.0 turns kwargs into a trailing positional Hash for a
   method that declares no keyword params). Check `arguments:`, any `FieldExtension` that
   adds arguments, and whether the return type is a connection (that attaches
   `ConnectionExtension` and its four arguments).
5. **What can the principal already resolve?** Parent-object authorization normally still
   holds, so the receiver set is "whatever this principal can already reach" — which is
   larger than it looks. Author/committer paths on public content commonly expose `User`
   objects (including administrators) to anonymous callers. Enumerate it; do not assume.

## Step 4 — Turn reachability into impact

A confirmed primitive is worth nothing in a report without a named receiver × named method.
Do the census; do not guess.

```bash
# Rails
bin/rails runner "$SKILL_DIR"/scripts/census.rb > census.json
# anything else — point CENSUS_BOOT at whatever loads the app
CENSUS_BOOT=./config/environment.rb bundle exec ruby "$SKILL_DIR"/scripts/census.rb > census.json
# knobs: CENSUS_SCHEMA=MySchema  CENSUS_ROOTS=Foo,Bar  CENSUS_ALL=1
```

It is reflection-based, so it **misses** anything reachable only via `method_missing` or
ActiveSupport `delegate` — and graphql-ruby's `respond_to?` dispatch *does* follow those.
Treat the output as a lower bound and say so in the report.

It enumerates public, zero-arg, `!`/`?`/`=`-free methods (the ones addressable as a GraphQL
Name) on every reachable receiver and ranks them. It works on Rails, Sinatra/Rack, Hanami or
a plain gem; it detects `ActiveRecord`, `Sequel`, `Mongoid` and `ROM` if present, and
`state_machines`, `aasm` and `workflow` state machines. Look hard at, in rough order of payoff:

- **State-machine events** — `state_machines`, `aasm` and `workflow` all define every
  transition as a public, zero-arg, bang-less method, which is exactly the addressable shape.
  `block`, `ban`, `close`, `archive`, `publish`, `approve`, `start_deletion` all persist and
  all bypass whatever service object and policy layer normally guards them. In the confirmed
  real-world case this was 1037 events across 170 classes — an entire dangerous method class
  surfacing from a library convention rather than from a search.
- **The ORM's persistence API** — `destroy`, `touch`, `save`, `reload` (ActiveRecord);
  `destroy`, `save`, `refresh` (Sequel); `destroy`, `save`, `touch` (Mongoid). `save` is the
  terminator that turns any in-memory mutator into a persistence primitive: fields resolve in
  document order against the **same instance**, so `{ generate_reset_token save }` is a
  two-instruction program.
- **Auth-library methods with all-optional arguments** — Devise's `confirm` / `force_confirm`
  self-persist and verify an email address without the emailed token. Check whatever
  authentication, confirmation or token library the app actually uses; the pattern is
  "a method whose entire purpose is to consume a token, invoked without the token".
- **`*_token` / `rewrite_*` / `generate_*` / `reset_*` / `rotate_*`** — credential mint and rotation.
- **`enable_*` / `disable_*` / `publish` / `share`** — persistent authorization widening. These
  are often worth more than the invocation itself, because they convert a one-shot call into
  standing unauthorized access.
- **Presenters, decorators and the type wrapper.** The wrapper is tried **first**, so a
  dangerous method on a base type class, a shared mixin, or a presenter that reassigns the
  wrapped object is reachable on *every* type at once.
- **Dev/test-group gems.** `pry-byebug` puts `Kernel#remote_byebug` (public, all args
  optional, spawns a debugger server) on every receiver. That is real RCE on a dev install
  and **must not be reported as production RCE** — check the dependency's group first. The
  census tags every method with `defined_in` so you can.

Also record what is *not* reachable, with the reason. `system`/`eval`/`exec` are private on
`Object`, so `respond_to?` is false and they fall through to the fallback — say so
explicitly so triage does not have to re-derive it.

## Step 5 — Verify live, always with a negative control

Never report a static reading of this class.

```bash
"$SKILL_DIR"/scripts/probe.sh --url <endpoint> --path '<selection>' --method <name> \
                              --trigger 'directive:<name>=<args>'   # or header:K=V, or none
```

It sends the same document twice, differing only in the trigger, and separates three
outcomes that are easy to conflate by hand:

- **METHOD INVOKED** — control rejected, test returned non-null.
- **VALIDATION HOLE CONFIRMED, gadget did not fire** — control rejected, test returned
  `null`. The field was fabricated (so the root defect is real and reportable) but that name
  fell through to `fallback_value`, meaning no such method on either receiver. **This is not
  an invocation** — pick another name from the census and re-run.
- **INCONCLUSIVE** — the control was *not* rejected, so the field genuinely exists and you
  are measuring the wrong thing. Fix that before going on.

It refuses destructive method names unless you pass `--i-know`. Omit `--auth` to prove
anonymous reach — that is the whole point of the exercise.

[references/verification.md](references/verification.md) has the rest: locating the endpoint
in an unfamiliar app, framework-agnostic out-of-band observation, the evidence to capture,
and the report skeleton.

Test against a disposable local instance you own. Do not run destructive methods against
data you did not create.

## Step 6 — Report

[references/verification.md](references/verification.md) carries the report skeleton, the
fix recommendations ranked by what each one actually closes, and pre-answered review
objections. Two things that materially change how such a report lands:

- **Lead with the root cause, not the gadget.** "Validate one document, execute another" is
  one mitigation covering several symptoms; filing the symptoms separately gets them merged
  as duplicates under most bounty programs' one-mitigation-one-report rule.
- **State the limits yourself.** Which guard still holds, which chain is code-supported but
  unverified, why it is or is not RCE. Under-claiming a critical finding costs nothing;
  over-claiming one gets the whole report discounted.

## What does *not* count

- `public_send` in a resolver where the name comes from a schema-defined enum whose values
  are a closed set — the enum coerces unknown literals to `nil`.
- `method:`/`hash_key:` pointing at a symbol literal, however dynamic the surrounding code.
- Dynamic types built at boot from a static source (a config file, a DB table of admin-defined
  metrics) that a request cannot influence.
- `fields(context)`/`get_field` overrides that only ever *hide* fields. Hiding narrows the
  addressable set; only fabricating widens it.
- A document rewrite that happens **before** parse and validate against the rewritten text.
  The bug is the split, not the rewriting.
