gql 0.2.0

A GraphQL reference implementation for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Security / denial-of-service regression tests.
//!
//! Each `FINDING` test demonstrates a behaviour that is unsafe for a server exposed to
//! untrusted clients and currently passes (i.e. the problem is present). The remaining tests
//! pin protections that the engine does provide, so a regression shows up here.
//!
//! The stack-bound tests run on a dedicated 2 MiB thread, the default for a Tokio worker.

use std::sync::{Arc, Mutex};

use futures::executor::block_on;
use gql::{
    AuthorizationContext, Authorizer, ExecutionOptions, Field, GraphQLError, InterfaceType,
    ObjectType, Request, Response, Schema, TypeRef, ValidationOptions, Value, validate,
};

// -------------------------------------------------------------------------------------------
// Fixtures
// -------------------------------------------------------------------------------------------

/// Records every `(parent_type, field_name)` pair the authorizer is asked about.
#[derive(Clone)]
struct RecordingAuthorizer {
    seen: Arc<Mutex<Vec<String>>>,
    deny: Arc<dyn Fn(&AuthorizationContext<'_>) -> bool + Send + Sync>,
}

impl RecordingAuthorizer {
    fn denying_all() -> Self {
        Self {
            seen: Arc::default(),
            deny: Arc::new(|_| true),
        }
    }

    fn seen(&self) -> Vec<String> {
        self.seen.lock().expect("authorizer log").clone()
    }
}

impl Authorizer for RecordingAuthorizer {
    fn authorize(&self, context: &AuthorizationContext<'_>) -> Result<(), GraphQLError> {
        self.seen
            .lock()
            .expect("authorizer log")
            .push(format!("{}.{}", context.parent_type, context.field_name));
        if (self.deny)(context) {
            Err(GraphQLError::new("denied"))
        } else {
            Ok(())
        }
    }
}

/// `Query { hello: String! ping: String }`.
fn simple_schema() -> Schema {
    Schema::builder()
        .object(
            ObjectType::new("Query")
                .field(
                    Field::new("hello", TypeRef::string().non_null())
                        .resolve(|_| Box::pin(async { Ok(Value::from("world")) })),
                )
                .field(
                    Field::new("ping", TypeRef::string())
                        .resolve(|_| Box::pin(async { Ok(Value::from("pong")) })),
                ),
        )
        .query("Query")
        .build()
        .expect("valid schema")
}

/// A schema where a field can be walked to any depth: `Query.a: Query`.
fn recursive_schema() -> Schema {
    Schema::builder()
        .object(
            ObjectType::new("Query")
                .field(
                    Field::new("a", TypeRef::named("Query"))
                        .resolve(|_| Box::pin(async { Ok(Value::object(gql::Object::new())) })),
                )
                .field(
                    Field::new("ping", TypeRef::string())
                        .resolve(|_| Box::pin(async { Ok(Value::from("pong")) })),
                ),
        )
        .query("Query")
        .build()
        .expect("valid schema")
}

/// `Query { node: Node!, users: [User!]!, public, secret }`, `Node { id }`,
/// `User { id name secret }`.
fn abstract_schema() -> Schema {
    let node = InterfaceType::new("Node").field(Field::new("id", TypeRef::id().non_null()));

    let user = ObjectType::new("User")
        .implements("Node")
        .field(
            Field::new("id", TypeRef::id().non_null())
                .resolve(|_| Box::pin(async { Ok(Value::from("1")) })),
        )
        .field(
            Field::new("name", TypeRef::string())
                .resolve(|_| Box::pin(async { Ok(Value::from("Ada")) })),
        )
        .field(
            Field::new("secret", TypeRef::string())
                .resolve(|_| Box::pin(async { Ok(Value::from("hunter2")) })),
        )
        .is_type_of(|value| value.as_object().is_some());

    let query = ObjectType::new("Query")
        .field(
            Field::new("users", TypeRef::named("User").non_null().list().non_null()).resolve(
                |_| {
                    Box::pin(async {
                        Ok(Value::List(vec![
                            Value::object(gql::Object::new()),
                            Value::object(gql::Object::new()),
                            Value::object(gql::Object::new()),
                        ]))
                    })
                },
            ),
        )
        .field(
            Field::new("node", TypeRef::named("Node").non_null())
                .resolve(|_| Box::pin(async { Ok(Value::object(gql::Object::new())) })),
        )
        .field(
            Field::new("public", TypeRef::string())
                .resolve(|_| Box::pin(async { Ok(Value::from("ok")) })),
        )
        .field(
            Field::new("secret", TypeRef::string())
                .resolve(|_| Box::pin(async { Ok(Value::from("hunter2")) })),
        );

    let mut builder = Schema::builder();
    builder.add_type(node.into());
    builder.add_type(user.into());
    builder.add_type(query.into());
    builder.query("Query").build().expect("valid schema")
}

fn run(schema: &Schema, query: &str, options: &ExecutionOptions) -> Response {
    block_on(gql::execute(schema, Request::new(query), options))
}

fn analyzer_options(max_complexity: u32) -> gql::complexity::ComplexityOptions {
    gql::complexity::ComplexityOptions {
        list_factor: 10,
        field_cost: 1,
        max_complexity,
        max_depth: 0,
        max_breadth: 0,
    }
}

// -------------------------------------------------------------------------------------------
// 1. Authorization
// -------------------------------------------------------------------------------------------

/// FINDING: meta-fields are resolved before the authorizer is consulted. An authorizer that
/// denies everything still answers `__typename`, `__schema` and `__type` (the introspection
/// tree's own fields are authorized). The meta-field entry points are authorized like normal
/// fields, so a deny-everything authorizer also denies `__typename`, `__schema` and `__type`.
#[test]
fn authorizer_also_covers_meta_fields() {
    let schema = simple_schema();
    let authorizer = RecordingAuthorizer::denying_all();
    let options = ExecutionOptions::default().authorizer(authorizer.clone());

    // Baseline: a normal field is denied and recorded.
    let response = run(&schema, "{ hello }", &options);
    assert_eq!(
        response.errors.first().map(GraphQLError::message),
        Some("denied")
    );
    assert!(
        authorizer.seen().iter().any(|seen| seen == "Query.hello"),
        "authorizer should have been consulted: {:?}",
        authorizer.seen()
    );

    for query in [
        "{ __typename }",
        "{ __schema { description } }",
        r#"{ __type(name: "Query") { name } }"#,
    ] {
        let response = run(&schema, query, &options);
        assert!(
            response
                .errors
                .iter()
                .any(|error| error.message() == "denied"),
            "expected meta-field in {query} to be denied: {:?}",
            response.errors
        );
    }
    assert!(
        authorizer
            .seen()
            .iter()
            .any(|seen| seen == "Query.__typename"),
        "{:?}",
        authorizer.seen()
    );
    assert!(
        authorizer
            .seen()
            .iter()
            .any(|seen| seen == "Query.__schema"),
        "{:?}",
        authorizer.seen()
    );
    assert!(
        authorizer.seen().iter().any(|seen| seen == "Query.__type"),
        "{:?}",
        authorizer.seen()
    );
}

/// Control: the authorizer runs for every field resolution reached through aliases, fragments,
/// repeated selections, list items and abstract types.
#[test]
fn authorizer_runs_for_aliases_fragments_lists_and_abstract_types() {
    let schema = abstract_schema();
    let authorizer = RecordingAuthorizer {
        seen: Arc::default(),
        deny: Arc::new(|context| context.field_name == "secret"),
    };
    let options = ExecutionOptions::default().authorizer(authorizer.clone());

    // Alias + fragment + duplicate selection under different aliases: all three resolutions of
    // `secret` must be denied.
    let response = run(
        &schema,
        "query { a: secret s: secret ...F } fragment F on Query { b: secret }",
        &options,
    );
    let data = response
        .data
        .as_ref()
        .and_then(Value::as_object)
        .expect("data");
    for key in ["a", "s", "b"] {
        assert_eq!(data.get(key), Some(&Value::Null), "alias {key}");
    }
    assert_eq!(
        response
            .errors
            .iter()
            .filter(|error| error.message() == "denied")
            .count(),
        3,
        "{:?}",
        response.errors
    );

    // List items: one authorization decision per resolved item.
    let response = run(&schema, "{ users { secret } }", &options);
    assert_eq!(
        response
            .errors
            .iter()
            .filter(|error| error.message() == "denied")
            .count(),
        3,
        "each list item must be authorized: {:?}",
        response.errors
    );
    assert!(authorizer.seen().iter().any(|seen| seen == "User.secret"));

    // Abstract type reached through an inline fragment.
    let response = run(&schema, "{ node { ... on User { secret } } }", &options);
    assert!(
        response
            .errors
            .iter()
            .any(|error| error.message() == "denied"),
        "abstract-type field must be authorized: {:?}",
        response.errors
    );
}

// -------------------------------------------------------------------------------------------
// 2. Parsing / validation limits (regressions)
// -------------------------------------------------------------------------------------------

/// The parser caps nesting, so a deep document is rejected instead of exhausting the stack.
#[test]
fn deeply_nested_query_is_rejected_by_the_parser() {
    let schema = recursive_schema();
    let depth = 10_000;
    let mut query = String::new();
    for _ in 0..depth {
        query.push_str("{ a ");
    }
    query.push_str("{ ping }");
    for _ in 0..depth {
        query.push_str(" }");
    }

    let response = run(&schema, &query, &ExecutionOptions::default());
    assert_eq!(response.data, None);
    assert!(
        response
            .errors
            .iter()
            .any(|error| error.message().contains("nested more than")),
        "{:?}",
        response.errors
    );
}

/// List/object literals are depth-limited too, so a deeply nested input value cannot overflow
/// the stack in the parser.
#[test]
fn deeply_nested_input_literal_is_rejected_by_the_parser() {
    let mut query = String::from("{ ping(n: ");
    for _ in 0..10_000 {
        query.push('[');
    }
    for _ in 0..10_000 {
        query.push(']');
    }
    query.push_str(") }");

    let error = gql::parser::parse_query(&query).expect_err("parser rejects the document");
    assert!(
        error.message().contains("nested more than"),
        "{}",
        error.message()
    );
}

/// A long chain of fragment spreads is rejected before validation recurses through it.
#[test]
fn long_fragment_chain_is_rejected() {
    fn chain(n: usize) -> String {
        let mut query = String::new();
        for level in 1..n {
            query.push_str(&format!(
                "fragment F{level} on Query {{ ...F{} }}\n",
                level + 1
            ));
        }
        query.push_str(&format!("fragment F{n} on Query {{ ping }}\n{{ ...F1 }}"));
        query
    }

    let schema = recursive_schema();
    let response = run(&schema, &chain(2_000), &ExecutionOptions::default());
    assert_eq!(response.data, None);
    assert!(
        response
            .errors
            .iter()
            .any(|error| error.message().contains("Fragment nesting")),
        "{:?}",
        response.errors
    );
}

/// Validation errors obey `max_errors` (an unbounded error vector is itself a DoS vector).
#[test]
fn validation_errors_respect_max_errors() {
    let schema = simple_schema();
    let mut query = String::from("{");
    for index in 0..20_000 {
        query.push_str(&format!(" unknown{index}"));
    }
    query.push_str(" }");

    let response = run(&schema, &query, &ExecutionOptions::default().max_errors(1));
    assert_eq!(response.errors.len(), 1, "validation errors are capped");
}

/// `max_depth` is enforced by validation as well as by the analyzer.
#[test]
fn max_depth_is_enforced_by_validation() {
    let schema = recursive_schema();
    let document = gql::parser::parse_query("{ a { a { a { ping } } } }").expect("parses");
    let errors = validate(
        &schema,
        &document,
        &ValidationOptions {
            introspection: true,
            max_depth: 2,
            max_errors: 0,
        },
    );
    assert!(
        errors
            .iter()
            .any(|error| error.message().contains("depth exceeds")),
        "{errors:?}"
    );
}

/// A valid but deeply nested query is rejected by the validation depth limit before execution.
/// The document stays under `gql::parser::MAX_DEPTH` (96) so this exercises the configurable
/// `max_depth` path rather than the parser's hard backstop.
#[test]
fn deep_query_is_rejected_by_max_depth_before_execution() {
    let schema = recursive_schema();
    let depth = 50;
    assert!(
        depth < gql::parser::MAX_DEPTH,
        "keep this test under the parser limit"
    );
    let mut query = String::new();
    for _ in 0..depth {
        query.push_str("{ a ");
    }
    query.push_str("{ ping }");
    for _ in 0..depth {
        query.push_str(" }");
    }

    // The document parses; only `max_depth` rejects it.
    let document = gql::parser::parse_query(&query).expect("parses");
    assert!(
        validate(
            &schema,
            &document,
            &ValidationOptions {
                introspection: true,
                max_depth: 10,
                max_errors: 0,
            },
        )
        .iter()
        .any(|error| error.message().contains("depth exceeds"))
    );

    let response = run(&schema, &query, &ExecutionOptions::default().max_depth(10));
    assert_eq!(response.data, None);
    assert!(
        response
            .errors
            .iter()
            .any(|error| error.message().contains("depth exceeds")),
        "{:?}",
        response.errors
    );
}

/// A doubling-fragment document is analysed in bounded work because fragment expansion is
/// memoised by `(fragment, scope)`. 60 levels would be 2^60 leaf visits without the cache, so a
/// regression hangs here rather than merely running slowly.
#[test]
fn fragment_expansion_is_memoised() {
    fn doubling_query(n: usize) -> String {
        let mut query = String::from("fragment F0 on Query { ping hello }\n");
        for level in 1..=n {
            query.push_str(&format!(
                "fragment F{level} on Query {{ ...F{} ...F{} }}\n",
                level - 1,
                level - 1
            ));
        }
        query.push_str(&format!("{{ ...F{n} }}"));
        query
    }

    let schema = simple_schema();
    let source = doubling_query(60);
    let document = gql::parser::parse_query(&source).expect("parses");
    let complexity = gql::complexity::analyze(
        &schema,
        &document,
        None,
        &gql::Object::new(),
        &analyzer_options(10),
    )
    .expect("cost 2 is under the limit");

    // Both leaves merge into one response key each, so the cost is 2 however many levels the
    // fragments nest: the analyzer did not expand every path.
    assert_eq!(complexity.cost, 2, "{complexity:?}");
    assert_eq!(complexity.depth, 1, "{complexity:?}");
}

/// Sibling fields are merged through a hash index, so a flat document of aliases is analysed in
/// bounded work and reports the exact cost.
#[test]
fn analyzing_many_sibling_aliases_is_bounded() {
    let mut query = String::from("{");
    for index in 0..8_000 {
        query.push_str(&format!(" a{index}: ping"));
    }
    query.push_str(" }");

    let schema = simple_schema();
    let document = gql::parser::parse_query(&query).expect("parses");
    let complexity = gql::complexity::analyze(
        &schema,
        &document,
        None,
        &gql::Object::new(),
        &analyzer_options(0),
    )
    .expect("analysis succeeds");

    assert_eq!(complexity.cost, 8_000, "{complexity:?}");
    assert_eq!(complexity.depth, 1, "{complexity:?}");
}

// -------------------------------------------------------------------------------------------
// 3. Execution: stack and CPU exhaustion
// -------------------------------------------------------------------------------------------

/// A document that the parser accepts can always be executed on a 2 MiB stack.
///
/// The executor recurses once per selection-set level through boxed futures, so a deep enough
/// document would exhaust a Tokio worker's 2 MiB stack. `gql::parser::MAX_DEPTH` (96) is
/// deliberately below that point: nesting beyond it is a syntax error, so no document that
/// parses can abort the process during execution.
#[test]
fn deep_query_is_rejected_before_execution_on_a_small_stack() {
    let depth = gql::parser::MAX_DEPTH * 4;
    let schema = recursive_schema();
    let mut query = String::new();
    for _ in 0..depth {
        query.push_str("{ a ");
    }
    query.push_str("{ ping }");
    for _ in 0..depth {
        query.push_str(" }");
    }

    // Run on a 2 MiB stack, the default for a Tokio worker thread.
    std::thread::Builder::new()
        .stack_size(2 * 1024 * 1024)
        .spawn(move || {
            let response = run(&schema, &query, &ExecutionOptions::default());
            assert_eq!(response.data, None, "the document must not execute");
            assert_eq!(response.errors.len(), 1, "{:?}", response.errors);
            assert!(
                response.errors[0].message().contains("nested more than"),
                "{:?}",
                response.errors
            );
        })
        .expect("spawn")
        .join()
        .expect("join");
}

/// A prepared document must keep the same stack guarantee as normal execution.
///
/// Preparation is iterative, but executing a plan recurses through larger async frames than the
/// dynamic collection path. Execution therefore drops a plan deeper than a safe threshold and
/// collects dynamically, so a prepared document at the parser's depth limit still runs on a 2 MiB
/// stack (the default for a Tokio worker).
#[test]
fn prepared_execute_on_a_2_mib_stack() {
    let depth = gql::parser::MAX_DEPTH - 2;
    let schema = recursive_schema();
    let mut query = String::new();
    for _ in 0..depth {
        query.push_str("{ a ");
    }
    query.push_str("{ ping }");
    for _ in 0..depth {
        query.push_str(" }");
    }
    let prepared = gql::prepared::PreparedQuery::new(&schema, "deep", &query, None)
        .expect("valid prepared query");

    std::thread::Builder::new()
        .stack_size(2 * 1024 * 1024)
        .spawn(move || {
            let response = block_on(prepared.execute(
                None,
                &ExecutionOptions::default().root_value(gql::Object::new()),
            ));
            assert!(response.errors.is_empty(), "{:?}", response.errors);
            assert!(response.data.is_some());
            std::mem::forget(prepared);
        })
        .expect("spawn")
        .join()
        .expect("join");
}

/// The shallow side of the planned-path threshold still executes on a 2 MiB stack.
///
/// This walks the last depth that keeps the precompiled plan; the next level falls back to
/// dynamic collection (covered by `prepared_execute_on_a_2_mib_stack`). Both sides of the
/// threshold must stay within a worker's stack.
#[test]
fn prepared_planned_nesting_near_the_threshold_runs_on_a_small_stack() {
    let depth = 47;
    let schema = recursive_schema();
    let mut query = String::new();
    for _ in 0..depth {
        query.push_str("{ a ");
    }
    query.push_str("{ ping }");
    for _ in 0..depth {
        query.push_str(" }");
    }
    let prepared = gql::prepared::PreparedQuery::new(&schema, "near", &query, None)
        .expect("valid prepared query");

    std::thread::Builder::new()
        .stack_size(2 * 1024 * 1024)
        .spawn(move || {
            let response = block_on(prepared.execute(
                None,
                &ExecutionOptions::default().root_value(gql::Object::new()),
            ));
            assert!(response.errors.is_empty(), "{:?}", response.errors);
            assert!(response.data.is_some());
            std::mem::forget(prepared);
        })
        .expect("spawn")
        .join()
        .expect("join");
}

/// A document exactly at the parser's limit still executes, so the backstop is not overly
/// aggressive: parse/validate/analyse/execute all succeed at `MAX_DEPTH - 1` levels of nesting.
#[test]
fn query_at_the_parser_depth_limit_executes() {
    let depth = gql::parser::MAX_DEPTH - 2;
    let schema = recursive_schema();
    let mut query = String::new();
    for _ in 0..depth {
        query.push_str("{ a ");
    }
    query.push_str("{ ping }");
    for _ in 0..depth {
        query.push_str(" }");
    }

    std::thread::Builder::new()
        .stack_size(2 * 1024 * 1024)
        .spawn(move || {
            let response = run(&schema, &query, &ExecutionOptions::default());
            assert!(response.errors.is_empty(), "{:?}", response.errors);
            assert!(response.data.is_some());
        })
        .expect("spawn")
        .join()
        .expect("join");
}