suku 0.1.2

GraphQL over HTTP 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
//! GraphQL-over-HTTP transport tests.
//!
//! These call `suku::http::handle` directly; no socket is involved.

mod support;

use ::http::{Method, StatusCode, header};
use futures::StreamExt as _;
use serde_json::json;
use suku::{
    Context, HttpConfig, HttpError, HttpResponse, HttpResult, Server,
    http::{ContextRequest, handle},
};

fn buffered(result: HttpResult) -> HttpResponse {
    match result {
        HttpResult::Response(response) => response,
        HttpResult::Stream(_) => panic!("expected a buffered response"),
    }
}

async fn run_default(
    server: &Server,
    config: &HttpConfig,
    parts: &::http::request::Parts,
    body: &[u8],
) -> HttpResult {
    handle(server, config, parts, body, support::empty_context).await
}

fn content_type(response: &HttpResponse) -> &str {
    response
        .headers
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default()
}

#[tokio::test]
async fn get_with_html_accept_returns_graphiql() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::GET,
        "/graphql",
        &[(header::ACCEPT, "text/html,application/xhtml+xml")],
    );

    let response = buffered(run_default(&server, &config, &parts, b"").await);
    assert_eq!(response.status, StatusCode::OK);
    assert!(content_type(&response).starts_with("text/html"));
    assert!(String::from_utf8_lossy(&response.body).contains("GraphiQL"));
}

#[tokio::test]
async fn graphiql_can_be_disabled() {
    let server = support::server();
    let config = HttpConfig::default().graphiql(false);
    let parts = support::parts(Method::GET, "/graphql", &[(header::ACCEPT, "text/html")]);

    let response = buffered(run_default(&server, &config, &parts, b"").await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn get_executes_a_query_from_query_parameters() {
    let server = support::server();
    let config = HttpConfig::default();
    let query = serde_urlencoded::to_string([("query", "{ hello }")]).expect("query string");
    let uri = format!("/graphql?{query}");
    let parts = support::parts(Method::GET, &uri, &[(header::ACCEPT, "application/json")]);

    let response = buffered(run_default(&server, &config, &parts, b"").await);
    assert_eq!(response.status, StatusCode::OK);
    assert!(content_type(&response).starts_with("application/json"));
    let body = support::json_body(&response.body);
    assert_eq!(body["data"]["hello"], "world");
}

#[tokio::test]
async fn get_parses_variables() {
    let server = support::server();
    let config = HttpConfig::default();
    let query = serde_urlencoded::to_string([
        (
            "query",
            "query Echo($message: String!) { echo(message: $message) }",
        ),
        ("variables", r#"{"message":"from get"}"#),
    ])
    .expect("query string");
    let parts = support::parts(
        Method::GET,
        &format!("/graphql?{query}"),
        &[(header::ACCEPT, "application/json")],
    );

    let response = buffered(run_default(&server, &config, &parts, b"").await);
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(
        support::json_body(&response.body)["data"]["echo"],
        "from get"
    );
}

#[tokio::test]
async fn get_rejects_invalid_variables_json() {
    let server = support::server();
    let config = HttpConfig::default();
    let query = serde_urlencoded::to_string([
        (
            "query",
            "query($message: String!) { echo(message: $message) }",
        ),
        ("variables", "{not json"),
    ])
    .expect("query string");
    let parts = support::parts(
        Method::GET,
        &format!("/graphql?{query}"),
        &[(header::ACCEPT, "application/json")],
    );

    let response = buffered(run_default(&server, &config, &parts, b"").await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
    assert!(support::json_body(&response.body)["errors"].is_array());
}

#[tokio::test]
async fn post_executes_a_json_request() {
    let server = support::server();
    let config = HttpConfig::default();
    let body = br#"{"query":"{ hello }"}"#;
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/json"),
        ],
    );

    let response = buffered(run_default(&server, &config, &parts, body).await);
    assert_eq!(response.status, StatusCode::OK);
    assert!(content_type(&response).starts_with("application/json"));
    assert_eq!(support::json_body(&response.body)["data"]["hello"], "world");
}

#[tokio::test]
async fn post_executes_a_batch_in_order() {
    let server = support::server();
    let config = HttpConfig::default();
    let body = br#"[{"query":"{ hello }"},{"query":"{ echo(message: \"two\") }"}]"#;
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let response = buffered(run_default(&server, &config, &parts, body).await);
    assert_eq!(response.status, StatusCode::OK);
    let body = support::json_body(&response.body);
    let batch = body.as_array().expect("batch array");
    assert_eq!(batch.len(), 2);
    assert_eq!(batch[0]["data"]["hello"], "world");
    assert_eq!(batch[1]["data"]["echo"], "two");
}

#[tokio::test]
async fn rejects_empty_batches() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let response = buffered(run_default(&server, &config, &parts, b"[]").await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
    assert!(support::json_body(&response.body)["errors"].is_array());
}

#[tokio::test]
async fn rejects_batches_over_the_limit() {
    let server = support::server().max_batch_size(1);
    let config = HttpConfig::default();
    let body = br#"[{"query":"{ hello }"},{"query":"{ hello }"}]"#;
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let response = buffered(run_default(&server, &config, &parts, body).await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
    assert!(support::json_body(&response.body)["errors"].is_array());
}

#[tokio::test]
async fn malformed_json_is_a_400_with_a_graphql_shaped_body() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/json"),
        ],
    );

    let response = buffered(run_default(&server, &config, &parts, b"{").await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
    assert!(support::json_body(&response.body)["errors"][0]["message"].is_string());
}

#[tokio::test]
async fn graphql_response_json_uses_200_for_success() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/graphql-response+json"),
        ],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ hello }"}"#).await);
    assert_eq!(response.status, StatusCode::OK);
    assert!(content_type(&response).starts_with("application/graphql-response+json"));
    assert_eq!(support::json_body(&response.body)["data"]["hello"], "world");
}

#[tokio::test]
async fn graphql_response_json_uses_200_for_execution_errors() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/graphql-response+json"),
        ],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ boom }"}"#).await);
    assert_eq!(response.status, StatusCode::OK);
    assert!(support::json_body(&response.body)["errors"].is_array());
}

#[tokio::test]
async fn the_server_body_limit_is_used_when_the_mount_does_not_override_it() {
    let server = support::server().max_body_bytes(8);
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ hello }"}"#).await);
    assert_eq!(response.status, StatusCode::PAYLOAD_TOO_LARGE);
}

#[tokio::test]
async fn graphql_response_json_uses_400_for_request_errors() {
    let server = support::server();
    let config = HttpConfig::default();
    let body = br#"{"query":"{"}"#;
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/graphql-response+json"),
        ],
    );

    let response = buffered(run_default(&server, &config, &parts, body).await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
    assert!(content_type(&response).starts_with("application/graphql-response+json"));
}

#[tokio::test]
async fn legacy_json_uses_200_for_request_errors() {
    let server = support::server();
    let config = HttpConfig::default();
    let body = br#"{"query":"{"}"#;
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/json"),
        ],
    );

    let response = buffered(run_default(&server, &config, &parts, body).await);
    assert_eq!(response.status, StatusCode::OK);
    assert!(support::json_body(&response.body)["errors"].is_array());
}

#[tokio::test]
async fn unsupported_method_is_405() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(Method::PUT, "/graphql", &[]);

    let response = buffered(run_default(&server, &config, &parts, b"").await);
    assert_eq!(response.status, StatusCode::METHOD_NOT_ALLOWED);
    assert_eq!(
        response
            .headers
            .get(header::ALLOW)
            .and_then(|value| value.to_str().ok()),
        Some("GET, POST")
    );
}

#[tokio::test]
async fn unsupported_content_type_is_415() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "text/plain")],
    );

    let response = buffered(run_default(&server, &config, &parts, b"{ hello }").await);
    assert_eq!(response.status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
}

#[tokio::test]
async fn missing_content_type_is_415() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(Method::POST, "/graphql", &[]);

    let response = buffered(run_default(&server, &config, &parts, b"{}").await);
    assert_eq!(response.status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
}

#[tokio::test]
async fn unacceptable_accept_is_406() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "text/plain"),
        ],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ hello }"}"#).await);
    assert_eq!(response.status, StatusCode::NOT_ACCEPTABLE);
}

#[tokio::test]
async fn body_limit_is_413() {
    let server = support::server();
    let config = HttpConfig::default().max_body_bytes(8);
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ hello }"}"#).await);
    assert_eq!(response.status, StatusCode::PAYLOAD_TOO_LARGE);
}

#[tokio::test]
async fn denied_context_is_a_401_before_execution() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let result = handle(
        &server,
        &config,
        &parts,
        br#"{"query":"{ whoami }"}"#,
        |_request: ContextRequest| async move {
            Err::<Context, HttpError>(HttpError::message(
                StatusCode::UNAUTHORIZED,
                "Missing bearer token",
            ))
        },
    )
    .await;

    let response = buffered(result);
    assert_eq!(response.status, StatusCode::UNAUTHORIZED);
    assert_eq!(
        support::json_body(&response.body)["errors"][0]["message"],
        "Missing bearer token"
    );
}

#[tokio::test]
async fn the_extractor_can_authenticate_and_build_a_context() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::AUTHORIZATION, "Bearer secret"),
        ],
    );

    let result = handle(
        &server,
        &config,
        &parts,
        br#"{"query":"{ whoami }"}"#,
        |request: ContextRequest| async move {
            match request
                .header("authorization")
                .and_then(|value| value.to_str().ok())
            {
                Some("Bearer secret") => Ok(Context::new(support::User {
                    name: "Ada".to_owned(),
                })),
                _ => Err(HttpError::message(StatusCode::UNAUTHORIZED, "Unauthorized")),
            }
        },
    )
    .await;

    let response = buffered(result);
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(support::json_body(&response.body)["data"]["whoami"], "Ada");
}

#[tokio::test]
async fn cookies_are_visible_to_the_extractor() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::COOKIE, "theme=dark; session=abc123"),
        ],
    );

    let result = handle(
        &server,
        &config,
        &parts,
        br#"{"query":"{ hello }"}"#,
        |request: ContextRequest| async move {
            assert_eq!(request.cookie("session"), Some("abc123"));
            Ok(Context::empty())
        },
    )
    .await;

    assert_eq!(buffered(result).status, StatusCode::OK);
}

#[tokio::test]
async fn subscriptions_stream_as_server_sent_events() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "text/event-stream"),
        ],
    );

    let result = handle(
        &server,
        &config,
        &parts,
        br#"{"query":"subscription { countdown }"}"#,
        support::empty_context,
    )
    .await;

    let HttpResult::Stream(stream) = result else {
        panic!("expected an SSE stream");
    };
    assert!(content_type_from_headers(&stream.headers).starts_with("text/event-stream"));

    let mut body = String::new();
    let mut events = stream.stream;
    while let Some(chunk) = events.next().await {
        body.push_str(&String::from_utf8_lossy(&chunk.expect("chunk")));
    }

    assert!(body.contains("event: next"));
    assert!(body.contains("event: complete"));
    assert!(body.contains("\"countdown\":3"));
}

#[tokio::test]
async fn subscriptions_without_event_stream_get_a_clear_error() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "application/json"),
        ],
    );

    let response = buffered(
        run_default(
            &server,
            &config,
            &parts,
            br#"{"query":"subscription { countdown }"}"#,
        )
        .await,
    );
    assert_eq!(response.status, StatusCode::OK);
    assert!(
        support::json_body(&response.body)["errors"][0]["message"]
            .as_str()
            .unwrap_or_default()
            .contains("text/event-stream")
    );
}

#[tokio::test]
async fn malformed_subscriptions_return_json_before_streaming() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "text/event-stream"),
        ],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"subscription {"}"#).await);
    assert_eq!(response.status, StatusCode::BAD_REQUEST);
    assert!(support::json_body(&response.body)["errors"][0]["message"].is_string());
}

#[tokio::test]
async fn event_stream_is_rejected_for_non_subscriptions() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[
            (header::CONTENT_TYPE, "application/json"),
            (header::ACCEPT, "text/event-stream"),
        ],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ hello }"}"#).await);
    assert_eq!(response.status, StatusCode::NOT_ACCEPTABLE);
}

#[tokio::test]
async fn response_includes_vary_and_no_store() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );

    let response =
        buffered(run_default(&server, &config, &parts, br#"{"query":"{ hello }"}"#).await);
    assert_eq!(
        response
            .headers
            .get(header::VARY)
            .and_then(|value| value.to_str().ok()),
        Some("Accept")
    );
    assert_eq!(
        response
            .headers
            .get(header::CACHE_CONTROL)
            .and_then(|value| value.to_str().ok()),
        Some("no-store")
    );
}

#[tokio::test]
async fn request_extensions_are_accepted() {
    let server = support::server();
    let config = HttpConfig::default();
    let parts = support::parts(
        Method::POST,
        "/graphql",
        &[(header::CONTENT_TYPE, "application/json")],
    );
    let body = json!({
        "query": "{ hello }",
        "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "abc" } }
    });

    let response =
        buffered(run_default(&server, &config, &parts, body.to_string().as_bytes()).await);
    assert_eq!(response.status, StatusCode::OK);
    assert_eq!(support::json_body(&response.body)["data"]["hello"], "world");
}

fn content_type_from_headers(headers: &::http::HeaderMap) -> &str {
    headers
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or_default()
}