# Pattern catalog — P1..P10

Each pattern: **signal** (what `scan.sh` matches) → **mechanics** (why the gem makes it
dangerous) → **decide** (the questions that separate a finding from a false positive) →
**seen in the wild** where there is a confirmed instance.

Patterns compose. P1 + P2 is the critical one: P1 removes the validation that would reject an
unknown field name, P2 turns that name into a method call. Either alone is usually a
medium; together they are unauthenticated arbitrary method invocation.

---

## P1 — Validate one document, execute another

**Signal**

```
instance_variable_set(:@document
send(:prepare_ast)  |  prepare_ast
@original_query_document  |  @unfiltered_document  |  @full_document
def parse(query_string:)      # in a module, alongside...
def execute_query(query:)     # ...this one, in the same file
Query.new(..., validate: false)  |  validate: false
```

**Mechanics**

graphql-ruby's event order is fixed: `lex` → `parse` → `validate` → `analyze_multiplex` →
`analyze_query` → `execute_multiplex` → `execute_query`. A trace module that returns a
*filtered* document from `parse` and then restores the *original* into `query`'s `@document`
in `execute_query` gets every static rule and every analyzer to inspect a document that the
interpreter never runs. What that switches off, in one move:

| Blinded | Consequence |
|---|---|
| `FieldsAreDefinedOnType` | unknown field names are never rejected — the prerequisite for P2 |
| `FragmentsAreFinite` | mutual fragment recursion → `SystemStackError` from a tiny anonymous document, *before any field resolves*, so authorization and cost analysis structurally cannot see it |
| `DirectivesAreDefined` | unknown directive → `KeyError` out of `Hash#fetch` → HTTP 500 |
| `FieldsWillMerge` | two selections can share an alias; the runtime is first-selection-wins for the field definition, union for sub-selections — a field validated against type A executes against type B |
| `ArgumentsAreDefined`, `RequiredArgumentsArePresent`, `ArgumentLiteralsAreCompatible` | resolvers invoked with argument sets the schema declares impossible (required arg absent; wrong-typed literal coerced to `nil` and delivered with the key present) |
| `max_depth`, `max_complexity`, custom analyzers | cost controls bypassed → unauthenticated resource exhaustion |
| the query logger | executed fields never appear in `used_fields` and contribute nothing to logged cost — **detection and abuse analytics are blind to the attack** |

**Decide**

- Does anything restore, re-assign or re-parse a document after `parse` returned? Follow
  `@document`, `@query_string`, and any call to `prepare_ast`.
- Is the swap conditional on a client-controlled signal (a directive in the query, a header,
  a param)? If yes, the client chooses when validation is skipped.
- Does the same trace object also carry per-query state? See P8.
- Even with P2 fixed, P1 alone is a finding: recursion DoS + 500s + cost-control bypass.

**Seen in the wild** — GitLab `lib/gitlab/graphql/version_filter/introduced_tracer.rb`
(introduced 2025-07, live ~13 months). `parse` returns a `FutureFieldFilter`-stripped
document; `execute_query` does `query.instance_variable_set(:@document, @original_query_document)`
then `query.send(:prepare_ast)`.

---

## P2 — Field definition synthesized from a client-supplied name

**Signal**

```
GraphQL::Schema::Field.new(          # then check whether name: is a literal
fallback_value:
field(field_name,  |  field(name,    # field() called with a variable
```

**Mechanics**

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

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

With no `method:`, `hash_key:`, `dig:` or `resolver_method:`, **the field name is the method
name**. `Field#resolve` then walks, in order:

1. `hash_key` branch — only if `hash_key:` was configured
2. `obj.respond_to?(resolver_method)` → **`obj.public_send(resolver_method)`** — `obj` is the
   `Types::*` wrapper instance
3. `inner_object.is_a?(Hash)` branch
4. `inner_object.respond_to?(@method_sym)` → **`inner_object.public_send(@method_sym)`** —
   the application object (an ActiveRecord model, typically)
5. `@fallback_value` — **only here**
6. `raise`

So `fallback_value: nil` reads like "this field returns null" and is actually "return null
only if two `public_send` attempts both found nothing". This is the single most common
misreading of the API.

GraphQL Names match `/[_A-Za-z][_0-9A-Za-z]*/`, which includes `_`, so essentially every Ruby
method name without `!`, `?` or `=` is addressable. Underscored names reach ActiveRecord and
Ruby internals directly; there is no camelCase→snake_case barrier because the name is used
verbatim.

**Decide**

- Is `name:` a literal, or does it come from the query? Only the latter is a finding.
- Does the synthesized field carry `method:`/`hash_key:`/`dig:`/`resolver_method:`/`resolver:`?
  Any of them redirects dispatch away from the attacker's string.
- Which types get it? A module mixed into `Types::BaseObject` / `BaseInterface` /
  `BaseMutation` / `BaseSubscription` covers most of the schema — but **not** connection
  types, edge types, `PageInfo` or mutation payload types, which descend from
  `GraphQL::Types::Relay::*`. On those the same query is a plain validation error (or an
  unhandled 500 when the P1 trigger is present).
- **Arguments.** `@own_arguments == nil` is what stands between this and arbitrary column
  writes. The only writers are `initialize(arguments:)` and a `FieldExtension#apply`. Note
  `ConnectionExtension` attaches automatically when `connection?` is true, and `connection?`
  is derived from the **return type name** — so a hardcoded scalar return type is load-bearing
  for more than exfiltration width.
- **Return type** bounds exfiltration. `Boolean` gives a three-state oracle
  (`true`/`false`/`null`) over any attribute — enough to prove a secret is set, not enough to
  read it. `String` or `JSON` would be full disclosure.

**Seen in the wild** — GitLab `future_field_fallback.rb`: `GraphQL::Schema::Field.new(owner:
self, name: field_name, type: GraphQL::Types::Boolean, fallback_value: nil)`.

---

## P3 — `get_field` / `fields` overrides (the "dynamic types" API)

**Signal**

```
def get_field(field_name, context
def fields(context
Schema::Member::HasFields
```

**Mechanics**

graphql-ruby documents `fields(context)` / `get_field(name, context)` as the supported way to
build per-request dynamic types. It is a legitimate API, and it is also the exact seat where
a "just return null for unknown fields" convenience gets written. An override that
**fabricates** a definition for a name `super` did not find has removed
`FieldsAreDefinedOnType` for that type — the same effect as P1, scoped to one type.

Note the override runs during **both** validation and execution, so unlike P1 it does not by
itself blind analyzers — but it does make unknown names resolvable.

**Decide**

- Does the override ever return non-nil for a name the schema does not define?
- Is the fabrication gated on something a client controls (a context key set from a header,
  a directive, a param)?
- Does the fabricated field go through P2's checklist?
- A `visible?`/`fields` override that only *hides* is fine. Only fabrication widens.

---

## P4 — Dispatch target taken from request data

**Signal**

```
(method|hash_key|resolver_method|dig):\s*(params|args|arguments|context|field_name|name|input|attribute)
```

**Mechanics**

Same endpoint as P2 but without needing a validation hole: if `method:` is computed from an
argument, the client picks the method on a field that is legitimately in the schema and
passes validation cleanly. Often shows up as a generic `Types::AttributeType` or a
"metrics"/"properties" field.

**Decide** — is the value constrained to a closed allowlist *before* it reaches `method:`? An
enum type is a real constraint (unknown literals coerce to `nil`); a `String` argument with a
regex check is weaker; no check is a finding.

---

## P5 — Client-usable custom directives

**Signal**

```
< GraphQL::Schema::Directive
locations(
directive(
```

**Mechanics**

A custom directive is a *client-supplied instruction to the server*, present in every query
string, requiring no authentication to write. `locations(FIELD, INLINE_FRAGMENT,
FRAGMENT_SPREAD, QUERY, ...)` all put it in the client's hands. If the directive's handling
mutates the document, changes execution mode, or sets a context key that other code branches
on, then the client controls that branch.

**Decide**

- Is it registered on the schema unconditionally, or behind a feature flag / trusted-client
  check? Grep the schema class.
- Does it appear in the shipped introspection dump (`introspection_result.json`, SDL
  artifacts)? If so it is advertised, and "nobody knows about it" is not a mitigation.
- What is it *for*? Deploy coordination, canary routing, and A/B mechanisms are meant for
  first-party clients and are routinely reachable by anyone. Those are worth reading closely.
- Does its handling touch the document, `@document`, or a context key consumed elsewhere?

**Seen in the wild** — `@gl_introduced(version:)`, `locations(FIELD, INLINE_FRAGMENT)`,
registered unconditionally, shipped in the public introspection dump, no feature flag, CE
default. Intent: rolling-deploy tolerance for a newer frontend against an older backend.

---

## P6 — AST rewriting visitors

**Signal**

```
< GraphQL::Language::Visitor
DELETE_NODE
def on_field(node, parent)
```

**Mechanics**

A `Language::Visitor` that deletes or inserts nodes is fine *if* the result is what both
validates and executes. It becomes P1 the moment the rewritten and original documents are
used at different stages. Deletion is more dangerous than it looks: whatever is inside the
deleted subtree is invisible to every rule, including the ones that bound recursion and cost.

**Decide** — trace both documents to their consumers. Which one reaches
`GraphQL::StaticValidation`? Which one reaches the interpreter? If the answer differs, it is
P1 regardless of how the rewrite is spelled.

---

## P7 — Reflection in resolvers and type resolution

**Signal**

```
public_send  |  __send__  |  \.send\(
constantize  |  safe_constantize  |  const_get
def resolve_type  |  def object_from_id  |  def id_from_object
Object.const_get
```

**Mechanics**

Independent of P1/P2: any resolver that reflects on request data is the same class of bug
with a smaller blast radius. `object_from_id` is the classic — a global-ID decoder that
`constantize`s the type name from an opaque-looking but client-supplied string. `resolve_type`
returning a class derived from data is the same.

**Decide**

- Is the reflected string schema-constrained (enum, allowlist) or free?
- For `object_from_id`: is the ID signed/verified, and is the class name checked against a
  registry before `constantize`? An unverified `constantize` is remote class instantiation.
- For `public_send` in a resolver: does the name come from the field, an argument, or a
  constant?

---

## P8 — Per-query state stored on a shared trace object

**Signal**

```
@ivar =        # inside a module that defines parse/execute_query/validate/analyze_query
Gitlab/ModuleWithInstanceVariables      # rubocop suppressions are a strong tell
```

**Mechanics**

`Query#current_trace` is `context[:trace] || (multiplex ? multiplex.current_trace : schema.new_trace(...))`
— **one trace instance is shared across an entire multiplex**. State stashed in a trace ivar
during query *i*'s `parse` is still there for query *j*'s `execute_query`. With a document in
that ivar, every entry in a multiplex executes the **last-parsed** document while the
controller's per-entry logic (CSRF classification, operation-name allowlists, persisted-query
checks, rate limiting) still pairs entry *i*'s string with entry *i*'s name.

**Decide**

- Does the endpoint accept an array body (multiplex / batched queries)? Grep the controller
  for `_json`, `Array`, `multiplex`.
- Does any per-entry security decision key off the query string or operation name? That
  decision is now made about a different document than the one that runs.
- Practical severity check: what `Content-Type` does the endpoint require? A JSON-only
  endpoint is not a CORS simple request, so a document-swap CSRF is usually *not*
  browser-reachable — say so rather than overclaiming.

**Seen in the wild** — the same GitLab tracer; `@original_query_document` and
`@contain_future_fields` are trace ivars.

---

## P9 — Analyzers and logs that see a different document than executes

**Signal**

```
< GraphQL::Analysis::Analyzer
query.document
used_fields  |  graphql_logs  |  RequestStore
```

**Mechanics**

This is P1's detection-evasion half and deserves its own line in a report even when the
primitive is the headline. If the security log's `complexity`, `depth` and `used_fields` are
computed from the filtered document, then every field executed through the hole is absent
from the audit trail and contributes zero to the logged cost. Incident response and abuse
analytics built on that log cannot see the attack at all — including retroactively.

**Decide** — for each analyzer, which document does it read, and does that match the
interpreter's? Say explicitly in the report whether the attack is loggable.

---

## P10 — Validation and introspection switches

**Signal**

```
validate: false
disable_introspection_entry_points
max_complexity  |  max_depth
default_max_page_size
```

**Mechanics**

Mostly context for the above, occasionally a finding on its own. `validate: false` on a
`Query`/`Schema.execute` path that handles client input is P1 without the subtlety.
`disable_introspection_entry_points` is worth checking against P2/P3: a fabricated-field path
that special-cases `__`-prefixed names is *evidence the author considered reflection* — read
what else they did and did not guard. (In graphql-ruby, disabled entry points are deleted
from the introspection system outright, so a name-based guard on `__` genuinely cannot revive
them; the guard's existence is the tell, not a bypass.)

---

## Composition worth checking explicitly

Once P1 or P3 is confirmed, do not stop at the first gadget. Check, in order:

1. **Multi-step programs.** Selections resolve in document order against the **same instance**,
   so `{ in_memory_mutator save }` persists what `in_memory_mutator` alone discards. Every
   zero-arg `set_*`/`mark_*`/`generate_*`/`ensure_*`/`assign_*` becomes a write primitive.
2. **Connection amplification.** A trigger on a connection applies the method to **every node
   in the page** — and P1 also removed the page-size and complexity bounds.
3. **Wrapper vs. presenter vs. model.** The wrapper is tried first; if the type does anything
   like `prepend Present` that reassigns `@object`, the presenter's public surface is reachable
   too, and *which* surface you get can depend on field order in the document.
4. **Second-order authorization.** A method that persistently widens a visibility/access level
   converts a one-shot invocation into standing unauthorized access, which is usually a bigger
   number than the invocation itself.
