apollo-router 2.14.0-rc.2

A configurable, high-performance routing runtime for Apollo Federation 🚀
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
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
use std::fmt::Display;
use std::sync::Arc;

use apollo_compiler::ExecutableDocument;
use apollo_compiler::ast;
use apollo_compiler::collections::HashMap;
use apollo_compiler::validation::Valid;
use apollo_federation::query_plan::requires_selection;
use apollo_federation::query_plan::serializable_document::SerializableDocument;
use indexmap::IndexSet;
use serde::Deserialize;
use serde::Serialize;
use serde_json_bytes::ByteString;
use serde_json_bytes::Map;
use tokio::sync::broadcast::Sender;
use tower::ServiceExt;
use tracing::Instrument;
use tracing::instrument;

use super::rewrites;
use super::selection::execute_selection_set;
use super::subgraph_context::ContextualArguments;
use super::subgraph_context::SubgraphContext;
use crate::error::Error;
use crate::error::FetchError;
use crate::error::ValidationErrors;
use crate::graphql;
use crate::graphql::Request;
use crate::json_ext;
use crate::json_ext::Object;
use crate::json_ext::Path;
use crate::json_ext::Value;
use crate::json_ext::ValueExt;
use crate::plugins::authorization::AuthorizationPlugin;
use crate::plugins::authorization::CacheKeyMetadata;
use crate::services::SubgraphRequest;
use crate::services::fetch::ErrorMapping;
use crate::services::subgraph::BoxService;
use crate::spec::QueryHash;
use crate::spec::Schema;
use crate::spec::SchemaHash;

/// GraphQL operation type.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
#[cfg_attr(test, derive(schemars::JsonSchema))]
pub enum OperationKind {
    #[default]
    Query,
    Mutation,
    Subscription,
}

impl Display for OperationKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.default_type_name())
    }
}

impl OperationKind {
    pub(crate) const fn default_type_name(&self) -> &'static str {
        match self {
            OperationKind::Query => "Query",
            OperationKind::Mutation => "Mutation",
            OperationKind::Subscription => "Subscription",
        }
    }

    /// Only for apollo studio exporter
    pub(crate) const fn as_apollo_operation_type(&self) -> &'static str {
        match self {
            OperationKind::Query => "query",
            OperationKind::Mutation => "mutation",
            OperationKind::Subscription => "subscription",
        }
    }
}

impl From<OperationKind> for ast::OperationType {
    fn from(value: OperationKind) -> Self {
        match value {
            OperationKind::Query => ast::OperationType::Query,
            OperationKind::Mutation => ast::OperationType::Mutation,
            OperationKind::Subscription => ast::OperationType::Subscription,
        }
    }
}

impl From<ast::OperationType> for OperationKind {
    fn from(value: ast::OperationType) -> Self {
        match value {
            ast::OperationType::Query => OperationKind::Query,
            ast::OperationType::Mutation => OperationKind::Mutation,
            ast::OperationType::Subscription => OperationKind::Subscription,
        }
    }
}

pub(crate) type SubgraphSchemas = HashMap<String, SubgraphSchema>;

pub(crate) struct SubgraphSchema {
    pub(crate) schema: Arc<Valid<apollo_compiler::Schema>>,
    // TODO: Ideally should have separate nominal type for subgraph's schema hash
    pub(crate) hash: SchemaHash,
}

impl SubgraphSchema {
    pub(crate) fn new(schema: Valid<apollo_compiler::Schema>) -> Self {
        let sdl = schema.serialize().no_indent().to_string();
        Self {
            schema: Arc::new(schema),
            hash: SchemaHash::new(&sdl),
        }
    }
}

/// A fetch node.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct FetchNode {
    /// The name of the service or subgraph that the fetch is querying.
    pub(crate) service_name: Arc<str>,

    /// The data that is required for the subgraph fetch.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    pub(crate) requires: Vec<requires_selection::Selection>,

    /// The variables that are used for the subgraph fetch.
    pub(crate) variable_usages: Vec<Arc<str>>,

    /// The GraphQL subquery that is used for the fetch.
    pub(crate) operation: SerializableDocument,

    /// The GraphQL subquery operation name.
    pub(crate) operation_name: Option<Arc<str>>,

    /// The GraphQL operation kind that is used for the fetch.
    pub(crate) operation_kind: OperationKind,

    /// Optional id used by Deferred nodes
    pub(crate) id: Option<String>,

    // Optionally describes a number of "rewrites" that query plan executors should apply to the data that is sent as input of this fetch.
    pub(crate) input_rewrites: Option<Vec<rewrites::DataRewrite>>,

    // Optionally describes a number of "rewrites" to apply to the data that received from a fetch (and before it is applied to the current in-memory results).
    pub(crate) output_rewrites: Option<Vec<rewrites::DataRewrite>>,

    // Optionally describes a number of "rewrites" to apply to the data that has already been received further up the tree
    pub(crate) context_rewrites: Option<Vec<rewrites::DataRewrite>>,

    // hash for the query and relevant parts of the schema. if two different schemas provide the exact same types, fields and directives
    // affecting the query, then they will have the same hash
    #[serde(default)]
    pub(crate) schema_aware_hash: Arc<QueryHash>,

    // authorization metadata for the subgraph query
    #[serde(default)]
    pub(crate) authorization: Arc<CacheKeyMetadata>,
}

#[derive(Default)]
pub(crate) struct Variables {
    pub(crate) variables: Object,
    pub(crate) inverted_paths: Vec<Vec<Path>>,
    pub(crate) contextual_arguments: Option<ContextualArguments>,
}

impl Variables {
    #[instrument(skip_all, level = "debug", name = "make_variables")]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        requires: &[requires_selection::Selection],
        variable_usages: &[Arc<str>],
        data: &Value,
        current_dir: &Path,
        request: &Arc<http::Request<Request>>,
        schema: &Schema,
        input_rewrites: &Option<Vec<rewrites::DataRewrite>>,
        context_rewrites: &Option<Vec<rewrites::DataRewrite>>,
    ) -> Option<Variables> {
        let body = request.body();
        let mut subgraph_context = SubgraphContext::new(data, schema, context_rewrites);
        if !requires.is_empty() {
            let mut variables = Object::with_capacity(1 + variable_usages.len());

            variables.extend(variable_usages.iter().filter_map(|key| {
                body.variables
                    .get_key_value(key.as_ref())
                    .map(|(variable_key, value)| (variable_key.clone(), value.clone()))
            }));

            let mut inverted_paths: Vec<Vec<Path>> = Vec::new();
            let mut values: IndexSet<Value> = IndexSet::default();
            data.select_values_and_paths(schema, current_dir, |path, value| {
                // first get contextual values that are required
                if let Some(context) = subgraph_context.as_mut() {
                    context.execute_on_path(path);
                }

                let mut value = execute_selection_set(value, requires, schema, None);
                if value.as_object().map(|o| !o.is_empty()).unwrap_or(false) {
                    rewrites::apply_rewrites(schema, &mut value, input_rewrites);
                    match values.get_index_of(&value) {
                        Some(index) => {
                            inverted_paths[index].push(path.clone());
                        }
                        None => {
                            inverted_paths.push(vec![path.clone()]);
                            values.insert(value);
                            debug_assert!(inverted_paths.len() == values.len());
                        }
                    }
                }
            });

            if values.is_empty() {
                return None;
            }

            let representations = Value::Array(Vec::from_iter(values));
            let contextual_arguments = match subgraph_context.as_mut() {
                Some(context) => context.add_variables_and_get_args(&mut variables),
                None => None,
            };

            variables.insert("representations", representations);
            Some(Variables {
                variables,
                inverted_paths,
                contextual_arguments,
            })
        } else {
            // with nested operations (Query or Mutation has an operation returning a Query or Mutation),
            // when the first fetch fails, the query plan will still execute up until the second fetch,
            // where `requires` is empty (not a federated fetch), the current dir is not emmpty (child of
            // the previous operation field) and the data is null. In that case, we recognize that we
            // should not perform the next fetch
            if !current_dir.is_empty()
                && data
                    .get_path(schema, current_dir)
                    .map(|value| value.is_null())
                    .unwrap_or(true)
            {
                return None;
            }

            Some(Variables {
                variables: variable_usages
                    .iter()
                    .filter_map(|key| {
                        body.variables
                            .get_key_value(key.as_ref())
                            .map(|(variable_key, value)| (variable_key.clone(), value.clone()))
                    })
                    .collect::<Object>(),
                inverted_paths: Vec::new(),
                contextual_arguments: None,
            })
        }
    }
}

impl FetchNode {
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn subgraph_fetch(
        &self,
        service: BoxService,
        subgraph_request: SubgraphRequest,
        current_dir: &Path,
        schema: &Schema,
        paths: Vec<Vec<Path>>,
        operation_str: &str,
        variables: Map<ByteString, Value>,
        hoist_orphan_errors: bool,
    ) -> (Value, Vec<Error>) {
        let (_parts, response) = match service
            .oneshot(subgraph_request)
            .instrument(tracing::trace_span!("subfetch_stream"))
            .await
            .map_to_graphql_error(self.service_name.to_string(), current_dir)
        {
            Err(e) => {
                return (Value::default(), vec![e]);
            }
            Ok(res) => res.response.into_parts(),
        };

        super::log::trace_subfetch(&self.service_name, operation_str, &variables, &response);

        if !response.is_primary() {
            return (
                Value::default(),
                vec![
                    FetchError::SubrequestUnexpectedPatchResponse {
                        service: self.service_name.to_string(),
                    }
                    .to_graphql_error(Some(current_dir.to_owned())),
                ],
            );
        }

        let (value, errors) =
            self.response_at_path(schema, current_dir, paths, response, hoist_orphan_errors);

        (value, errors)
    }

    pub(crate) fn deferred_fetches(
        current_dir: &Path,
        id: &Option<String>,
        deferred_fetches: &std::collections::HashMap<String, Sender<(Value, Vec<Error>)>>,
        value: &Value,
        errors: &[Error],
    ) {
        if let Some(id) = id
            && let Some(sender) = deferred_fetches.get(id.as_str())
        {
            u64_counter!(
                "apollo.router.operations.defer.fetch",
                "Number of deferred responses fetched from subgraphs",
                1
            );
            if let Err(e) = sender.clone().send((value.clone(), Vec::from(errors))) {
                tracing::error!(
                    "error sending fetch result at path {} and id {:?} for deferred response building: {}",
                    current_dir,
                    id,
                    e
                );
            }
        }
    }

    /// Maps a subgraph's response into what can be merged in the overall supergraph response. It
    /// does this by making sure both the data and errors from a subgraph's response can be plugged
    /// into the right slots for the supergraph response, and it does that by a bit of path
    /// handling and manipulation
    ///
    /// When `hoist_orphan_errors` is true, entity-less errors are assigned to the nearest
    /// non-array ancestor of `current_dir`, preventing error multiplication across array
    /// elements. When false, they are assigned to `current_dir` as-is.
    #[instrument(skip_all, level = "debug", name = "response_insert")]
    pub(crate) fn response_at_path<'a>(
        &'a self,
        schema: &Schema,
        current_dir: &'a Path,
        inverted_paths: Vec<Vec<Path>>,
        response: graphql::Response,
        hoist_orphan_errors: bool,
    ) -> (Value, Vec<Error>) {
        if !self.requires.is_empty() {
            let entities_path = Path(vec![json_ext::PathElement::Key(
                "_entities".to_string(),
                None,
            )]);

            // when hoist_orphan_errors is enabled, the fallback_dir is the immediate parent of
            // the current_dir when the current_dir is wildcarded (ie, @, which is PathElement::Flatten)
            //
            // this prevents error multiplication across array elements
            let error_dir = if hoist_orphan_errors {
                let pos = current_dir
                    .0
                    .iter()
                    .position(|e| matches!(e, json_ext::PathElement::Flatten(_)));
                match pos {
                    Some(i) => Path(current_dir.0[..i].to_vec()),
                    None => current_dir.clone(),
                }
            } else {
                current_dir.clone()
            };

            let mut errors: Vec<Error> = vec![];
            for mut error in response.errors {
                // the locations correspond to the subgraph query and cannot be linked to locations
                // in the client query, so we remove them
                error.locations = Vec::new();

                // errors with path should be updated to the path of the entity they target
                if let Some(ref path) = error.path {
                    if path.starts_with(&entities_path) {
                        // the error's path has the format '/_entities/1/other' so we ignore the
                        // first element and then get the index
                        match path.0.get(1) {
                            Some(json_ext::PathElement::Index(i)) => {
                                for values_path in
                                    inverted_paths.get(*i).iter().flat_map(|v| v.iter())
                                {
                                    errors.push(
                                        Error::builder()
                                            .locations(error.locations.clone())
                                            // append to the entity's path the error's path without
                                            //`_entities` and the index
                                            .path(Path::from_iter(
                                                values_path.0.iter().chain(&path.0[2..]).cloned(),
                                            ))
                                            .message(error.message.clone())
                                            .and_extension_code(error.extension_code())
                                            .extensions(error.extensions.clone())
                                            // re-use the original ID so we don't double count this error
                                            .apollo_id(error.apollo_id())
                                            .build(),
                                    )
                                }
                            }
                            _ => {
                                error.path = Some(error_dir.clone());
                                errors.push(error)
                            }
                        }
                    } else {
                        error.path = Some(error_dir.clone());
                        errors.push(error);
                    }
                } else {
                    error.path = Some(error_dir.clone());
                    errors.push(error);
                }
            }

            // we have to nest conditions and do early returns here
            // because we need to take ownership of the inner value
            if let Some(Value::Object(mut map)) = response.data
                && let Some(entities) = map.remove("_entities")
            {
                tracing::trace!("received entities: {:?}", &entities);

                if let Value::Array(array) = entities {
                    let mut value = Value::default();

                    for (index, mut entity) in array.into_iter().enumerate() {
                        rewrites::apply_rewrites(schema, &mut entity, &self.output_rewrites);

                        if let Some(paths) = inverted_paths.get(index) {
                            if paths.len() > 1 {
                                for path in &paths[1..] {
                                    let _ = value.insert(path, entity.clone());
                                }
                            }

                            if let Some(path) = paths.first() {
                                let _ = value.insert(path, entity);
                            }
                        }
                    }
                    return (value, errors);
                }
            }

            // if we get here, it means that the response was missing the `_entities` key
            // This can happen if the subgraph failed during query execution e.g. for permissions checks.
            // In this case we should add an additional error because the subgraph should have returned an error that will be bubbled up to the client.
            // However, if they have not then print a warning to the logs.
            if errors.is_empty() {
                tracing::warn!(
                    "Subgraph response from '{}' was missing key `_entities` and had no errors. This is likely a bug in the subgraph.",
                    self.service_name
                );
            }

            (Value::Null, errors)
        } else {
            let current_slice =
                if matches!(current_dir.last(), Some(&json_ext::PathElement::Flatten(_))) {
                    &current_dir.0[..current_dir.0.len() - 1]
                } else {
                    &current_dir.0[..]
                };

            let errors: Vec<Error> = response
                .errors
                .into_iter()
                .map(|error| {
                    let path = error
                        .path
                        .as_ref()
                        .map(|path| {
                            Path::from_iter(current_slice.iter().chain(path.iter()).cloned())
                        })
                        .unwrap_or_else(|| current_dir.clone());

                    Error::builder()
                        .locations(error.locations.clone())
                        .path(path)
                        .message(error.message.clone())
                        .and_extension_code(error.extension_code())
                        .extensions(error.extensions.clone())
                        .apollo_id(error.apollo_id())
                        .build()
                })
                .collect();
            let mut data = response.data.unwrap_or_default();
            rewrites::apply_rewrites(schema, &mut data, &self.output_rewrites);
            (Value::from_path(current_dir, data), errors)
        }
    }

    #[cfg(test)]
    pub(crate) fn service_name(&self) -> &str {
        &self.service_name
    }

    pub(crate) fn operation_kind(&self) -> &OperationKind {
        &self.operation_kind
    }

    pub(crate) fn init_parsed_operation(
        &mut self,
        subgraph_schemas: &SubgraphSchemas,
    ) -> Result<(), ValidationErrors> {
        let schema = &subgraph_schemas[self.service_name.as_ref()];
        self.operation.init_parsed(&schema.schema)?;
        Ok(())
    }

    pub(crate) fn init_parsed_operation_and_hash_subquery(
        &mut self,
        subgraph_schemas: &SubgraphSchemas,
    ) -> Result<(), ValidationErrors> {
        let schema = &subgraph_schemas[self.service_name.as_ref()];
        self.operation.init_parsed(&schema.schema)?;
        self.schema_aware_hash = Arc::new(schema.hash.operation_hash(
            self.operation.as_serialized(),
            self.operation_name.as_deref(),
        ));
        Ok(())
    }

    pub(crate) fn extract_authorization_metadata(
        &mut self,
        schema: &Valid<apollo_compiler::Schema>,
        global_authorisation_cache_key: &CacheKeyMetadata,
    ) {
        let doc = ExecutableDocument::parse(
            schema,
            self.operation.as_serialized().to_string(),
            "query.graphql",
        )
        // Assume query planing creates a valid document: ignore parse errors
        .unwrap_or_else(|invalid| invalid.partial);
        let subgraph_query_cache_key = AuthorizationPlugin::generate_cache_metadata(
            &doc,
            self.operation_name.as_deref(),
            schema,
            !self.requires.is_empty(),
        );

        // we need to intersect the cache keys because the global key already takes into account
        // the scopes and policies from the client request
        self.authorization = Arc::new(AuthorizationPlugin::intersect_cache_keys_subgraph(
            global_authorisation_cache_key,
            &subgraph_query_cache_key,
        ));
    }
}

#[cfg(test)]
mod tests {
    use apollo_compiler::name;
    use apollo_federation::query_plan::requires_selection;
    use apollo_federation::query_plan::serializable_document::SerializableDocument;
    use rstest::rstest;
    use serde_json_bytes::json;

    use super::*;
    use crate::Configuration;

    fn test_schema() -> Schema {
        let sdl = r#"
            schema
                @link(url: "https://specs.apollo.dev/link/v1.0")
                @link(url: "https://specs.apollo.dev/join/v0.3", for: EXECUTION)
            {
                query: Query
            }
            directive @link(url: String, as: String, for: link__Purpose, import: [link__Import]) repeatable on SCHEMA
            directive @join__type(graph: join__Graph!, key: join__FieldSet, extension: Boolean! = false, resolvable: Boolean! = true, isInterfaceObject: Boolean! = false) repeatable on OBJECT | INTERFACE | UNION | ENUM | INPUT_OBJECT | SCALAR
            directive @join__graph(name: String!, url: String!) on ENUM_VALUE

            scalar link__Import
            scalar join__FieldSet

            enum link__Purpose { SECURITY EXECUTION }

            enum join__Graph {
                TEST @join__graph(name: "test", url: "http://localhost:4001/graphql")
            }

            type Query {
                me: String
            }
        "#;
        Schema::parse(sdl, &Configuration::default()).unwrap()
    }

    fn make_fetch_node(requires: Vec<requires_selection::Selection>) -> FetchNode {
        FetchNode {
            service_name: "test".into(),
            requires,
            variable_usages: vec![],
            operation: SerializableDocument::from_string("{ me }"),
            operation_name: None,
            operation_kind: OperationKind::Query,
            id: None,
            input_rewrites: None,
            output_rewrites: None,
            context_rewrites: None,
            schema_aware_hash: Default::default(),
            authorization: Default::default(),
        }
    }

    fn make_requires() -> Vec<requires_selection::Selection> {
        vec![requires_selection::Selection::InlineFragment(
            requires_selection::InlineFragment {
                type_condition: Some(name!("T")),
                selections: vec![requires_selection::Selection::Field(
                    requires_selection::Field {
                        alias: None,
                        name: name!("id"),
                        selections: Vec::new(),
                    },
                )],
            },
        )]
    }

    fn key(name: &str) -> json_ext::PathElement {
        json_ext::PathElement::Key(name.to_string(), None)
    }

    fn index(i: usize) -> json_ext::PathElement {
        json_ext::PathElement::Index(i)
    }

    fn flatten() -> json_ext::PathElement {
        json_ext::PathElement::Flatten(None)
    }

    fn make_error(path: Option<Path>) -> graphql::Error {
        match path {
            Some(p) => graphql::Error::builder().message("err").path(p).build(),
            None => graphql::Error::builder().message("err").build(),
        }
    }

    #[rstest]
    #[case::single_key(
        vec![key("topLevel")],
        Some(json!({"field": "value"})),
        json!({"topLevel": {"field": "value"}})
    )]
    #[case::no_data(
        vec![key("topLevel")],
        None,
        json!({"topLevel": null})
    )]
    #[case::empty_current_dir(
        vec![],
        Some(json!({"me": "hello"})),
        json!({"me": "hello"})
    )]
    #[case::deep_nesting(
        vec![key("a"), key("b"), key("c"), key("d")],
        Some(json!({"value": 42})),
        json!({"a": {"b": {"c": {"d": {"value": 42}}}}})
    )]
    fn root_fetch_data_wrapping(
        #[case] dir_elements: Vec<json_ext::PathElement>,
        #[case] data: Option<Value>,
        #[case] expected: Value,
    ) {
        let schema = test_schema();
        let node = make_fetch_node(vec![]);
        let current_dir = Path(dir_elements);
        let response = graphql::Response {
            data,
            ..Default::default()
        };
        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert!(errors.is_empty());
        assert_eq!(value, expected);
    }

    #[rstest]
    #[case::prepends_current_dir(
        vec![key("top"), key("nested")],
        Some(Path(vec![key("field")])),
        Path(vec![key("top"), key("nested"), key("field")])
    )]
    #[case::no_error_path_uses_current_dir(
        vec![key("top")],
        None,
        Path(vec![key("top")])
    )]
    #[case::trailing_flatten_stripped(
        vec![key("list"), flatten()],
        Some(Path(vec![key("name")])),
        Path(vec![key("list"), key("name")])
    )]
    #[case::no_error_path_keeps_flatten(
        vec![key("list"), flatten()],
        None,
        Path(vec![key("list"), flatten()])
    )]
    #[case::index_in_error_path(
        vec![key("items")],
        Some(Path(vec![index(2), key("name")])),
        Path(vec![key("items"), index(2), key("name")])
    )]
    #[case::flatten_mid_path_not_stripped(
        vec![key("a"), flatten(), key("b")],
        Some(Path(vec![key("c")])),
        Path(vec![key("a"), flatten(), key("b"), key("c")])
    )]
    fn root_fetch_error_path(
        #[case] dir_elements: Vec<json_ext::PathElement>,
        #[case] error_path: Option<Path>,
        #[case] expected_path: Path,
    ) {
        let schema = test_schema();
        let node = make_fetch_node(vec![]);
        let current_dir = Path(dir_elements);
        let response = graphql::Response::builder()
            .error(make_error(error_path))
            .build();

        let (_, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path.as_ref().unwrap(), &expected_path);
    }

    #[test]
    fn root_fetch_multiple_errors() {
        let schema = test_schema();
        let node = make_fetch_node(vec![]);
        let current_dir = Path(vec![key("root")]);
        let response = graphql::Response::builder()
            .error(
                graphql::Error::builder()
                    .message("error 1")
                    .path(Path(vec![key("a")]))
                    .build(),
            )
            .error(
                graphql::Error::builder()
                    .message("error 2")
                    .path(Path(vec![key("b")]))
                    .build(),
            )
            .error(graphql::Error::builder().message("error 3").build())
            .build();

        let (_, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(errors.len(), 3);
        assert_eq!(
            errors[0].path.as_ref().unwrap(),
            &Path(vec![key("root"), key("a")])
        );
        assert_eq!(
            errors[1].path.as_ref().unwrap(),
            &Path(vec![key("root"), key("b")])
        );
        assert_eq!(errors[2].path.as_ref().unwrap(), &Path(vec![key("root")]));
    }

    #[test]
    fn root_fetch_preserves_error_extension_code() {
        let schema = test_schema();
        let node = make_fetch_node(vec![]);
        let current_dir = Path(vec![key("root")]);
        let response = graphql::Response::builder()
            .error(
                graphql::Error::builder()
                    .message("auth error")
                    .extension_code("UNAUTHORIZED")
                    .path(Path(vec![key("field")]))
                    .build(),
            )
            .build();

        let (_, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].extension_code().as_deref(), Some("UNAUTHORIZED"));
    }

    #[rstest]
    #[case::entities_path_no_index(
        vec![key("users"), flatten()],
        Some(Path(vec![key("_entities")])),
        Path(vec![key("users")])
    )]
    #[case::non_entities_prefix(
        vec![key("a"), key("b")],
        Some(Path(vec![key("other"), key("field")])),
        Path(vec![key("a"), key("b")])
    )]
    #[case::no_path_truncates_at_flatten(
        vec![key("a"), flatten(), key("b")],
        None,
        Path(vec![key("a")])
    )]
    #[case::no_flatten_equals_current_dir(
        vec![key("a"), key("b"), key("c")],
        None,
        Path(vec![key("a"), key("b"), key("c")])
    )]
    #[case::two_flattens_truncates_at_first(
        vec![key("a"), flatten(), key("b"), flatten()],
        None,
        Path(vec![key("a")])
    )]
    #[case::entities_key_not_index(
        vec![key("root")],
        Some(Path(vec![key("_entities"), key("notAnIndex")])),
        Path(vec![key("root")])
    )]
    fn entity_error_uses_fallback_dir(
        #[case] dir_elements: Vec<json_ext::PathElement>,
        #[case] error_path: Option<Path>,
        #[case] expected_path: Path,
    ) {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(dir_elements);
        let response = graphql::Response::builder()
            .data(json!({"_entities": []}))
            .error(make_error(error_path))
            .build();

        let (_, errors) = node.response_at_path(&schema, &current_dir, vec![], response, true);

        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path.as_ref().unwrap(), &expected_path);
    }

    #[rstest]
    #[case::flatten_preserved_when_disabled(
        vec![key("users"), flatten()],
        None,
        Path(vec![key("users"), flatten()])
    )]
    #[case::nested_flatten_preserved_when_disabled(
        vec![key("a"), flatten(), key("b"), flatten()],
        None,
        Path(vec![key("a"), flatten(), key("b"), flatten()])
    )]
    #[case::non_entities_path_gets_current_dir_when_disabled(
        vec![key("items"), flatten()],
        Some(Path(vec![key("something")])),
        Path(vec![key("items"), flatten()])
    )]
    fn entity_error_uses_current_dir_when_hoist_disabled(
        #[case] dir_elements: Vec<json_ext::PathElement>,
        #[case] error_path: Option<Path>,
        #[case] expected_path: Path,
    ) {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(dir_elements);
        let response = graphql::Response::builder()
            .data(json!({"_entities": []}))
            .error(make_error(error_path))
            .build();

        let (_, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path.as_ref().unwrap(), &expected_path);
    }

    #[test]
    fn entity_fetch_basic_entities_inserted_at_inverted_paths() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("topField"), flatten()]);
        let inverted_paths = vec![
            vec![Path(vec![key("topField"), index(0)])],
            vec![Path(vec![key("topField"), index(1)])],
        ];
        let response = graphql::Response::builder()
            .data(json!({
                "_entities": [
                    {"name": "Alice"},
                    {"name": "Bob"}
                ]
            }))
            .build();

        let (value, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert!(errors.is_empty());
        let top = value.as_object().unwrap().get("topField").unwrap();
        let arr = top.as_array().unwrap();
        assert_eq!(arr[0], json!({"name": "Alice"}));
        assert_eq!(arr[1], json!({"name": "Bob"}));
    }

    #[test]
    fn entity_fetch_entity_at_multiple_inverted_paths() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("field"), flatten()]);
        let inverted_paths = vec![vec![
            Path(vec![key("field"), index(0)]),
            Path(vec![key("field"), index(2)]),
        ]];
        let response = graphql::Response::builder()
            .data(json!({
                "_entities": [{"name": "Alice"}]
            }))
            .build();

        let (value, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert!(errors.is_empty());
        let arr = value
            .as_object()
            .unwrap()
            .get("field")
            .unwrap()
            .as_array()
            .unwrap();
        assert_eq!(arr[0], json!({"name": "Alice"}));
        assert_eq!(arr[2], json!({"name": "Alice"}));
    }

    #[test]
    fn entity_fetch_empty_entities_array_returns_default_value() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("field")]);
        let response = graphql::Response::builder()
            .data(json!({"_entities": []}))
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert!(errors.is_empty());
        assert_eq!(value, Value::default());
    }

    #[test]
    fn entity_fetch_more_entities_than_inverted_paths() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("f"), flatten()]);
        let inverted_paths = vec![vec![Path(vec![key("f"), index(0)])]];
        let response = graphql::Response::builder()
            .data(json!({
                "_entities": [
                    {"name": "Alice"},
                    {"name": "Bob"},
                    {"name": "Charlie"}
                ]
            }))
            .build();

        let (value, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert!(errors.is_empty());
        let arr = value
            .as_object()
            .unwrap()
            .get("f")
            .unwrap()
            .as_array()
            .unwrap();
        assert_eq!(arr[0], json!({"name": "Alice"}));
    }

    #[test]
    fn entity_fetch_error_with_entities_path_and_index_remapped() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("users"), flatten()]);
        let inverted_paths = vec![
            vec![Path(vec![key("users"), index(0)])],
            vec![Path(vec![key("users"), index(1)])],
        ];
        let response = graphql::Response::builder()
            .data(json!({"_entities": [null, null]}))
            .error(
                graphql::Error::builder()
                    .message("entity error")
                    .path(Path(vec![key("_entities"), index(1), key("name")]))
                    .build(),
            )
            .build();

        let (_, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert_eq!(errors.len(), 1);
        assert_eq!(
            errors[0].path.as_ref().unwrap(),
            &Path(vec![key("users"), index(1), key("name")])
        );
        assert_eq!(errors[0].message, "entity error");
    }

    #[test]
    fn entity_fetch_error_locations_cleared() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("data")]);
        let response = graphql::Response::builder()
            .data(json!({"_entities": [null]}))
            .error(
                graphql::Error::builder()
                    .message("err")
                    .locations(vec![graphql::Location { line: 1, column: 5 }])
                    .path(Path(vec![key("_entities"), index(0), key("x")]))
                    .build(),
            )
            .build();

        let (_, errors) = node.response_at_path(
            &schema,
            &current_dir,
            vec![vec![Path(vec![key("data"), index(0)])]],
            response,
            false,
        );

        assert_eq!(errors.len(), 1);
        assert!(errors[0].locations.is_empty());
    }

    #[test]
    fn entity_fetch_error_index_remapped_to_multiple_inverted_paths() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("items"), flatten()]);
        let inverted_paths = vec![vec![
            Path(vec![key("items"), index(0)]),
            Path(vec![key("items"), index(3)]),
        ]];
        let response = graphql::Response::builder()
            .data(json!({"_entities": [null]}))
            .error(
                graphql::Error::builder()
                    .message("err")
                    .path(Path(vec![key("_entities"), index(0), key("name")]))
                    .build(),
            )
            .build();

        let (_, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert_eq!(errors.len(), 2);
        assert_eq!(
            errors[0].path.as_ref().unwrap(),
            &Path(vec![key("items"), index(0), key("name")])
        );
        assert_eq!(
            errors[1].path.as_ref().unwrap(),
            &Path(vec![key("items"), index(3), key("name")])
        );
    }

    #[test]
    fn entity_fetch_error_index_out_of_bounds_inverted_paths_no_panic() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("x")]);
        let response = graphql::Response::builder()
            .data(json!({"_entities": []}))
            .error(
                graphql::Error::builder()
                    .message("oob")
                    .path(Path(vec![key("_entities"), index(5), key("f")]))
                    .build(),
            )
            .build();

        let (_, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert!(errors.is_empty());
    }

    #[test]
    fn entity_fetch_preserves_extension_code_on_remapped_errors() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("users"), flatten()]);
        let inverted_paths = vec![vec![Path(vec![key("users"), index(0)])]];
        let response = graphql::Response::builder()
            .data(json!({"_entities": [null]}))
            .error(
                graphql::Error::builder()
                    .message("forbidden")
                    .extension_code("FORBIDDEN")
                    .path(Path(vec![key("_entities"), index(0)]))
                    .build(),
            )
            .build();

        let (_, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].extension_code().as_deref(), Some("FORBIDDEN"));
        assert_eq!(
            errors[0].path.as_ref().unwrap(),
            &Path(vec![key("users"), index(0)])
        );
    }

    #[test]
    fn entity_fetch_error_appends_remaining_path_after_index() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("data"), flatten()]);
        let inverted_paths = vec![vec![Path(vec![key("data"), index(0)])]];
        let response = graphql::Response::builder()
            .data(json!({"_entities": [null]}))
            .error(
                graphql::Error::builder()
                    .message("nested err")
                    .path(Path(vec![
                        key("_entities"),
                        index(0),
                        key("address"),
                        key("city"),
                    ]))
                    .build(),
            )
            .build();

        let (_, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, false);

        assert_eq!(errors.len(), 1);
        assert_eq!(
            errors[0].path.as_ref().unwrap(),
            &Path(vec![key("data"), index(0), key("address"), key("city")])
        );
    }

    #[test]
    fn entity_fetch_missing_entities_key_with_errors() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("users"), flatten()]);
        let response = graphql::Response::builder()
            .data(json!({"something": "else"}))
            .error(
                graphql::Error::builder()
                    .message("permission denied")
                    .build(),
            )
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(value, Value::Null);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].message, "permission denied");
    }

    #[test]
    fn entity_fetch_missing_entities_key_no_errors() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("users")]);
        let response = graphql::Response::builder()
            .data(json!({"something": "else"}))
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(value, Value::Null);
        assert!(errors.is_empty());
    }

    #[test]
    fn entity_fetch_null_data_returns_null_with_errors() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("field")]);
        let response = graphql::Response::builder()
            .error(graphql::Error::builder().message("subgraph error").build())
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(value, Value::Null);
        assert_eq!(errors.len(), 1);
    }

    #[test]
    fn entity_fetch_null_data_errors_get_fallback_dir() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("users"), flatten(), key("reviews")]);
        let expected_fallback = Path(vec![key("users")]);
        let response = graphql::Response::builder()
            .error(graphql::Error::builder().message("pathless error").build())
            .error(
                graphql::Error::builder()
                    .message("non-entities path")
                    .path(Path(vec![key("something")]))
                    .build(),
            )
            .error(
                graphql::Error::builder()
                    .message("entities no index")
                    .path(Path(vec![key("_entities")]))
                    .build(),
            )
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, true);

        assert_eq!(value, Value::Null);
        assert_eq!(errors.len(), 3);
        for error in &errors {
            assert_eq!(
                error.path.as_ref().unwrap(),
                &expected_fallback,
                "error '{}' did not get fallback_dir",
                error.message,
            );
        }
    }

    #[test]
    fn entity_fetch_missing_entities_key_errors_get_fallback_dir() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("items"), flatten()]);
        let expected_fallback = Path(vec![key("items")]);
        let response = graphql::Response::builder()
            .data(json!({"something": "else"}))
            .error(
                graphql::Error::builder()
                    .message("permission denied")
                    .build(),
            )
            .error(
                graphql::Error::builder()
                    .message("other error")
                    .path(Path(vec![key("unrelated")]))
                    .build(),
            )
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, true);

        assert_eq!(value, Value::Null);
        assert_eq!(errors.len(), 2);
        for error in &errors {
            assert_eq!(
                error.path.as_ref().unwrap(),
                &expected_fallback,
                "error '{}' did not get fallback_dir",
                error.message,
            );
        }
    }

    #[test]
    fn entity_fetch_entities_not_array_returns_null() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("field")]);
        let response = graphql::Response::builder()
            .data(json!({"_entities": "not_an_array"}))
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, false);

        assert_eq!(value, Value::Null);
        assert!(errors.is_empty());
    }

    #[test]
    fn entity_fetch_entities_not_array_errors_get_fallback_dir() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("products"), flatten()]);
        let expected_fallback = Path(vec![key("products")]);
        let response = graphql::Response::builder()
            .data(json!({"_entities": 42}))
            .error(graphql::Error::builder().message("bad entities").build())
            .build();

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, true);

        assert_eq!(value, Value::Null);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path.as_ref().unwrap(), &expected_fallback);
    }

    #[test]
    fn entity_fetch_data_is_non_object_returns_null_with_fallback_errors() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("orders"), flatten(), key("items")]);
        let expected_fallback = Path(vec![key("orders")]);
        let response = graphql::Response {
            data: Some(Value::Null),
            errors: vec![graphql::Error::builder().message("null data error").build()],
            ..Default::default()
        };

        let (value, errors) = node.response_at_path(&schema, &current_dir, vec![], response, true);

        assert_eq!(value, Value::Null);
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].path.as_ref().unwrap(), &expected_fallback);
    }

    #[test]
    fn entity_fetch_mixed_error_types() {
        let schema = test_schema();
        let node = make_fetch_node(make_requires());
        let current_dir = Path(vec![key("users"), flatten()]);
        let inverted_paths = vec![
            vec![Path(vec![key("users"), index(0)])],
            vec![Path(vec![key("users"), index(1)])],
        ];
        let response = graphql::Response::builder()
            .data(json!({"_entities": [{"name": "Alice"}, null]}))
            .error(
                graphql::Error::builder()
                    .message("entity 1 error")
                    .path(Path(vec![key("_entities"), index(1), key("field")]))
                    .build(),
            )
            .error(
                graphql::Error::builder()
                    .message("general error")
                    .path(Path(vec![key("other")]))
                    .build(),
            )
            .error(graphql::Error::builder().message("pathless").build())
            .build();

        let (_, errors) =
            node.response_at_path(&schema, &current_dir, inverted_paths, response, true);

        assert_eq!(errors.len(), 3);
        assert_eq!(
            errors[0].path.as_ref().unwrap(),
            &Path(vec![key("users"), index(1), key("field")])
        );
        assert_eq!(errors[1].path.as_ref().unwrap(), &Path(vec![key("users")]));
        assert_eq!(errors[2].path.as_ref().unwrap(), &Path(vec![key("users")]));
    }
}