# graphql-ruby internals you need to argue about this class

Verified against **graphql 2.6.x** (read from source at 2.6.7; the finding this skill
generalizes was against 2.6.3). Cite by method and branch name, **not** line number — line
numbers move between patch releases.

## Execution pipeline and its hooks

`GraphQL::Tracing::Trace` defines, in call order:

```
lex(query_string:)
parse(query_string:)                  -> returns the AST document
validate(query:, validate:)           -> static rules run here
begin_validate(query, validate)
analyze_multiplex(multiplex:)
analyze_query(query:)                 -> query analyzers, complexity, depth, logging
execute_multiplex(multiplex:)
execute_query(query:)                 -> the interpreter
execute_query_lazy(query:, multiplex:)
execute_field(...)  /  authorized(...)  /  resolve_type(...)
```

Registered with `trace_with SomeModule` (2.x) or the deprecated `tracer` (1.x-style,
`trace(key, data)` with keys like `"parse"`, `"execute_query"`). Both are seats for P1.

**The security-relevant consequence:** everything that protects the endpoint statically —
the `StaticValidation` rule set, `max_depth`, `max_complexity`, every `query_analyzer`, and
the query log — runs strictly between `parse` and `execute_query`. Anything that changes the
document in that window changes what runs without changing what was checked.

## Trace instances are shared across a multiplex

```ruby
# lib/graphql/query.rb
def current_trace
  @current_trace ||= context[:trace] || (multiplex ? multiplex.current_trace : schema.new_trace(multiplex: multiplex, query: self))
end
```

One trace object serves every query in a multiplex. Instance variables on a trace module are
therefore **cross-query state**, not per-query state (P8).

## Field resolution — the `public_send` chain

`GraphQL::Schema::Field#initialize`:

```ruby
method_name = method || hash_key || name_s      # name_s is the field name, verbatim
@method_str = -method_name.to_s
@method_sym = method_name.to_sym
@resolver_method = (resolver_method || name_s).to_sym
```

and the default `@execution_mode` is `:direct_send` with key `@method_sym` when none of
`resolve_static`/`resolve_batch`/`resolve_each`/`hash_key`/`dig`/`resolver_class`/
`resolve_legacy_instance_method`/`dataload` is configured.

`GraphQL::Schema::Field#resolve`, after `authorized?` and extensions, dispatches in this
order — the order matters for the receiver census:

```ruby
inner_object = obj.object

if hash_key configured           -> hash lookup, then fallback_value
elsif obj.respond_to?(resolver_method)
  obj.public_send(resolver_method)          # (1) the Types::* WRAPPER
elsif inner_object.is_a?(Hash)              -> dig / key lookup, then fallback_value
elsif inner_object.respond_to?(@method_sym)
  inner_object.public_send(@method_sym)     # (2) the APPLICATION OBJECT
elsif @fallback_value != NOT_CONFIGURED
  @fallback_value                           # (3) only now
else
  raise "Failed to implement ..."
end
```

Three facts to carry into any report:

1. **`fallback_value:` is the last resort, not a short-circuit.** A field with
   `fallback_value: nil` and no `method:` still attempts two `public_send`s first.
2. **The wrapper is tried first.** A dangerous public zero-arg method on a base type class,
   a mixin, or a presenter that replaces `@object` is reachable on *every* type at once —
   far higher value than any single model's method.
3. **`ruby_kwargs` is spliced in when non-empty** (`public_send(m, **ruby_kwargs)`). Zero
   arguments is what keeps this out of RCE territory; see below.

## Why zero arguments is the whole ballgame

`public_send` is **not** a visibility boundary. On a `Delegator` receiver, a name that has
been `undef`'d falls into `method_missing`, and ActiveSupport's `delegate` does
`::Kernel.instance_method(m).bind_call(self, ...)` — executing a **private** `Kernel` method:

```ruby
d = SimpleDelegator.new(obj)
d.respond_to?(:srand)   # => false
d.public_send(:srand)   # => executes private Kernel#srand
```

The only thing holding that line in the general case is graphql-ruby's **advisory**
`respond_to?` pre-check. **Never justify a fix with "`public_send` only reaches public
methods."**

What actually closes RCE is arity. Measured over the private `Kernel` set: the members that
execute at zero args (`caller p pp print printf puts rand srand warn loop exit abort fork
sleep gets`) and the code-executing members (`eval system exec spawn load require open
syscall`, backtick) are **disjoint** — the latter all raise `ArgumentError` at zero args. So
the ceiling of a zero-arg primitive is worker DoS, not execution.

Conversely, **one delivered argument would be enough on its own**. Ruby ≥3.0 converts keyword
arguments into a trailing positional Hash for a method declaring no keyword parameters:

```ruby
public_send(:update_columns, admin: true)   # => update_columns({admin: true})
```

— an arbitrary column write with no validations, no callbacks, no audit. So when triaging a
synthesized field, `@own_arguments == nil` is the load-bearing assertion. Its only writers are
`initialize(arguments:)` and `FieldExtension#apply`. Note also:

```ruby
if connection? && connection_extension
  self.extension(connection_extension, call_after_define: false)   # adds after/before/first/last
end
```

`connection?` is derived from the **return type name**, so a hardcoded scalar return type
suppresses that extension as a side effect. (Even if it attached, `ConnectionExtension#resolve`
deletes its four arguments before invoking the method, so no attacker-chosen key reaches
`ruby_kwargs`.) Also: the interpreter short-circuits one frame earlier on
`!field_defn.any_arguments?`, so it never reaches argument coercion at all.

## What the GraphQL grammar does and does not allow

Field/directive/argument names match `/[_A-Za-z][_0-9A-Za-z]*/`.

- **Reachable:** every Ruby method name that is only letters, digits and underscores —
  including leading-underscore names and every snake_case ActiveRecord method.
- **Not reachable:** anything with `!`, `?` or `=`. This kills bang methods and every setter,
  and it fails at the **parser**, before any app-level filter — so it holds even when
  validation is fully bypassed.

## Static validation rules worth naming in a report

From `GraphQL::StaticValidation` — these are what a P1 split switches off:

`FieldsAreDefinedOnType`, `FieldsWillMerge`, `FragmentsAreFinite`, `FragmentsAreUsed`,
`FragmentSpreadsArePossible`, `DirectivesAreDefined`, `DirectivesAreInValidLocations`,
`ArgumentsAreDefined`, `RequiredArgumentsArePresent`, `ArgumentLiteralsAreCompatible`,
`VariablesAreUsedAndDefined`, `VariableUsagesAreAllowed`.

Naming the specific rules is what turns "validation is skipped" into a reviewable claim.

## Type authorization vs. field authorization — which survives

- **Field-level `authorize`** on a synthesized field: none exists, so nothing is checked.
- **Type-level `authorize`** on the returned type: this is a **runtime** check and it
  **still runs**. It bounds the receiver set — a type carrying `authorize :read_x` will not
  hand you an object you could not otherwise read.
- **Parent-object authorization**: still holds. The primitive does not let a caller resolve an
  object they could not already resolve; it removes the *field definition* check on an object
  the schema already handed over.

That last point is the honest scope limit and belongs in any report — but do not let it
understate the finding. Enumerate the receiver set rather than assuming it is small:
authorship and commit-metadata paths on public content routinely expose `User` objects
(administrators included) to fully anonymous callers, even when a direct `user(username:)`
lookup is refused.

## Version notes

- **1.x**: hooks are `tracer` objects with `trace(key, data)`; field resolution has the same
  `public_send`-by-name default. The class applies.
- **2.0–2.5**: `trace_with`; `Field#resolve` structure as above. `fallback_value:` exists from
  2.0.
- **2.6+**: adds `@execution_mode` dispatch (`:direct_send` remains the default) and
  `resolve_static`/`resolve_batch`/`resolve_each`. None of these change the analysis; they add
  more explicit ways to redirect dispatch away from the field name, which is what a fix should
  use.
- `graphql-c_parser` in the lockfile is a **separate** attack surface (native parser memory
  safety), not this class. Note it and move on.
