hive-router 0.2.0

GraphQL router for Federation, part of the Hive platform
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
pub mod cache_control;
pub mod compile;
pub mod errors;
pub mod expression;
pub mod plan;
pub mod request;
pub mod response;
pub mod sanitizer;

#[cfg(test)]
mod tests {
    use crate::config::parse_yaml_config;
    use crate::executor::{
        execution::client_request_details::{
            ClientRequestDetails, JwtRequestDetails, OperationDetails,
        },
        headers::{
            compile::compile_headers_plan,
            request::modify_subgraph_request_headers,
            response::{apply_subgraph_response_headers, ResponseHeaderAggregator},
        },
    };
    use http::{HeaderMap, HeaderName, HeaderValue};
    use ntex::http::HeaderMap as NtexHeaderMap;

    fn header_name_owned(s: &str) -> HeaderName {
        HeaderName::from_bytes(s.as_bytes()).unwrap()
    }
    fn header_value_owned(s: &str) -> HeaderValue {
        HeaderValue::from_str(s).unwrap()
    }

    trait HeaderMapAsStringExt {
        fn to_string(&self) -> String;
    }

    impl HeaderMapAsStringExt for HeaderMap {
        fn to_string(&self) -> String {
            let mut buffer = String::new();

            for (name, value) in self.iter() {
                buffer.push_str(&format!(
                    "{}: {}\n",
                    name.as_str(),
                    value.to_str().unwrap_or("<invalid utf8>")
                ));
            }

            buffer
        }
    }

    impl HeaderMapAsStringExt for ntex::http::HeaderMap {
        fn to_string(&self) -> String {
            let mut buffer = String::new();

            for (name, value) in self.iter() {
                buffer.push_str(&format!(
                    "{}: {}\n",
                    name.as_str(),
                    value.to_str().unwrap_or("<invalid utf8>")
                ));
            }

            buffer
        }
    }

    #[test]
    fn test_build_subgraph_headers_propagate_and_set() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - propagate:
                    named: x-prop
                    rename: x-renamed
                - insert:
                    name: x-set
                    value: set-value
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();

        let plan = compile_headers_plan(&config.headers).unwrap();

        let mut client_headers = NtexHeaderMap::new();
        client_headers.insert(
            header_name_owned("x-prop"),
            header_value_owned("abc").into(),
        );

        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut out = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "any", &client_details, &mut out).unwrap();

        insta::assert_snapshot!(out.to_string(), @r#"
          x-renamed: abc
          x-set: set-value
        "#);
    }

    #[test]
    fn test_build_subgraph_headers_with_default() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - propagate:
                    named: x-missing
                    default: default-value
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };
        let mut out = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "any", &client_details, &mut out).unwrap();

        insta::assert_snapshot!(out.to_string(), @r#"
          x-missing: default-value
        "#);
    }

    // Tests that `matching` and `exclude` rules are correctly applied for propagation.
    #[test]
    fn test_propagate_with_matching_and_exclude() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - propagate:
                    matching: "^x-.*"
                    exclude: ["^x-secret-.*"]
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();

        let mut client_headers = NtexHeaderMap::new();
        client_headers.insert(
            header_name_owned("x-forward-this"),
            header_value_owned("value1").into(),
        );
        client_headers.insert(
            header_name_owned("x-secret-header"),
            header_value_owned("value2").into(),
        );
        client_headers.insert(
            header_name_owned("authorization"),
            header_value_owned("value3").into(),
        );

        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut out = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "any", &client_details, &mut out).unwrap();

        assert_eq!(out.get("x-forward-this").unwrap(), "value1");
        assert!(out.get("x-secret-header").is_none());
        assert!(out.get("authorization").is_none());

        insta::assert_snapshot!(out.to_string(), @r#"
          x-forward-this: value1
        "#);
    }

    // Tests inserting a header with a value from a VRL expression.
    #[test]
    fn test_insert_request_header_with_expression() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - insert:
                    name: x-operation-name
                    expression: '.request.operation.name || "unknown"'
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: Some("MyQuery"),
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut out = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "any", &client_details, &mut out).unwrap();

        insta::assert_snapshot!(out.to_string(), @r#"
          x-operation-name: MyQuery
        "#);
    }

    // Tests VRL expression fallback to a default value when a field is null.
    #[test]
    fn test_insert_request_header_with_expression_fallback() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - insert:
                    name: x-operation-name
                    expression: '.request.operation.name || "unknown"'
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut out = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "any", &client_details, &mut out).unwrap();

        insta::assert_snapshot!(out.to_string(), @r#"
          x-operation-name: unknown
        "#);
    }

    // Tests that subgraph-specific rules override global `all` rules.
    #[test]
    fn test_subgraph_specific_request_rules() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - insert:
                    name: x-scope
                    value: all
            subgraphs:
              accounts:
                request:
                  - insert:
                      name: x-scope
                      value: accounts
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        // For "accounts" subgraph, the specific rule should apply.
        let mut out_accounts = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "accounts", &client_details, &mut out_accounts)
            .unwrap();

        insta::assert_snapshot!(out_accounts.to_string(), @r#"
          x-scope: accounts
        "#);

        // For any other subgraph, the `all` rule should apply.
        let mut out_other = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "products", &client_details, &mut out_other)
            .unwrap();

        insta::assert_snapshot!(out_other.to_string(), @r#"
          x-scope: all
        "#);
    }

    #[test]
    fn test_apply_subgraph_response_headers_and_finalize() {
        let yaml_str = r#"
          headers:
            all:
              response:
                - propagate:
                    named: x-resp
                    algorithm: last
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut accumulator = ResponseHeaderAggregator::default();

        let mut subgraph_headers = HeaderMap::new();
        subgraph_headers.insert(
            header_name_owned("x-resp"),
            header_value_owned("resp-value-1"),
        );
        apply_subgraph_response_headers(
            &plan,
            "any",
            &subgraph_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut subgraph_headers = HeaderMap::new();
        subgraph_headers.insert(
            header_name_owned("x-resp"),
            header_value_owned("resp-value-2"),
        );

        apply_subgraph_response_headers(
            &plan,
            "any",
            &subgraph_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut response = ntex::http::Response::Ok().finish();
        accumulator
            .modify_client_response_headers(response.headers_mut())
            .unwrap();
        let final_headers = response.headers();

        insta::assert_snapshot!(final_headers.to_string(), @r#"
          x-resp: resp-value-2
        "#);
    }

    // Tests the `first` algorithm for response header propagation.
    #[test]
    fn test_response_propagate_first() {
        let yaml_str = r#"
          headers:
            all:
              response:
                - propagate:
                    named: x-resp
                    algorithm: first
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut accumulator = ResponseHeaderAggregator::default();

        let mut subgraph_headers_1 = HeaderMap::new();
        subgraph_headers_1.insert(
            header_name_owned("x-resp"),
            header_value_owned("resp-value-1"),
        );
        apply_subgraph_response_headers(
            &plan,
            "any",
            &subgraph_headers_1,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut subgraph_headers_2 = HeaderMap::new();
        subgraph_headers_2.insert(
            header_name_owned("x-resp"),
            header_value_owned("resp-value-2"),
        );
        apply_subgraph_response_headers(
            &plan,
            "any",
            &subgraph_headers_2,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut response = ntex::http::Response::Ok().finish();
        accumulator
            .modify_client_response_headers(response.headers_mut())
            .unwrap();
        let final_headers = response.headers();

        insta::assert_snapshot!(final_headers.to_string(), @r#"
          x-resp: resp-value-1
        "#);
    }

    // Tests the `append` algorithm for response header propagation.
    #[test]
    fn test_response_propagate_append() {
        let yaml_str = r#"
          headers:
            all:
              response:
                - propagate:
                    named: x-stuff
                    algorithm: append
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };
        let mut accumulator = ResponseHeaderAggregator::default();

        let mut subgraph1_headers = HeaderMap::new();
        subgraph1_headers.insert(header_name_owned("x-stuff"), header_value_owned("val1"));
        apply_subgraph_response_headers(
            &plan,
            "subgraph1",
            &subgraph1_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut subgraph2_headers = HeaderMap::new();
        subgraph2_headers.insert(header_name_owned("x-stuff"), header_value_owned("val2"));
        apply_subgraph_response_headers(
            &plan,
            "subgraph2",
            &subgraph2_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut response = ntex::http::Response::Ok().finish();
        accumulator
            .modify_client_response_headers(response.headers_mut())
            .unwrap();
        let final_headers = response.headers();

        insta::assert_snapshot!(final_headers.to_string(), @r#"
          x-stuff: val1, val2
        "#);
    }

    // Tests that "never-join" headers like set-cookie are appended as separate fields.
    #[test]
    fn test_response_propagate_append_never_join() {
        let yaml_str = r#"
          headers:
            all:
              response:
                - propagate:
                    named: set-cookie
                    algorithm: append
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };
        let mut accumulator = ResponseHeaderAggregator::default();

        let mut subgraph1_headers = HeaderMap::new();
        subgraph1_headers.insert(header_name_owned("set-cookie"), header_value_owned("a=1"));
        apply_subgraph_response_headers(
            &plan,
            "subgraph1",
            &subgraph1_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut subgraph2_headers = HeaderMap::new();
        subgraph2_headers.insert(header_name_owned("set-cookie"), header_value_owned("b=2"));
        apply_subgraph_response_headers(
            &plan,
            "subgraph2",
            &subgraph2_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut response = ntex::http::Response::Ok().finish();
        accumulator
            .modify_client_response_headers(response.headers_mut())
            .unwrap();
        let final_headers = response.headers();

        insta::assert_snapshot!(final_headers.to_string(), @r#"
          set-cookie: a=1
          set-cookie: b=2
        "#);
    }

    // Tests inserting a response header with a value from a VRL expression.
    #[test]
    fn test_insert_response_header_with_expression() {
        let yaml_str = r#"
          headers:
            all:
              response:
                - insert:
                    name: x-original-forwarded-for
                    expression: '.response.headers."x-forwarded-for"'
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();
        let client_headers = NtexHeaderMap::new();
        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut accumulator = ResponseHeaderAggregator::default();

        let mut subgraph_headers = HeaderMap::new();
        subgraph_headers.insert(
            header_name_owned("x-forwarded-for"),
            header_value_owned("1.2.3.4"),
        );

        apply_subgraph_response_headers(
            &plan,
            "any",
            &subgraph_headers,
            &client_details,
            &mut accumulator,
        )
        .unwrap();

        let mut response = ntex::http::Response::Ok().finish();
        accumulator
            .modify_client_response_headers(response.headers_mut())
            .unwrap();
        let final_headers = response.headers();

        insta::assert_snapshot!(final_headers.to_string(), @r#"
          x-original-forwarded-for: 1.2.3.4
        "#);
    }

    #[test]
    fn test_remove_header() {
        let yaml_str = r#"
          headers:
            all:
              request:
                - propagate:
                    named: x-keep
                - remove:
                    named: x-remove
        "#;
        let config = parse_yaml_config(String::from(yaml_str)).unwrap();
        let plan = compile_headers_plan(&config.headers).unwrap();

        let mut client_headers = NtexHeaderMap::new();

        client_headers.insert(
            header_name_owned("x-remove"),
            header_value_owned("bye").into(),
        );
        client_headers.insert(header_name_owned("x-keep"), header_value_owned("hi").into());

        let client_details = ClientRequestDetails {
            method: &http::Method::POST,
            url: &"http://example.com".parse().unwrap(),
            headers: client_headers.into(),
            operation: OperationDetails {
                name: None,
                query: "{ __typename }",
                kind: "query",
            },
            jwt: JwtRequestDetails::Unauthenticated.into(),
            path_params: Default::default(),
        };

        let mut out = HeaderMap::new();
        modify_subgraph_request_headers(&plan, "any", &client_details, &mut out).unwrap();

        insta::assert_snapshot!(out.to_string(), @r#"
          x-keep: hi
        "#);
    }
}