apollo-router 2.16.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
use std::collections::HashMap;

use apollo_compiler::ast;

use super::PersistedQueryManifest;
use crate::Configuration;

/// Describes whether the router should allow or deny a given request.
/// with an error, or allow it but log the operation as unknown.
pub(crate) struct FreeformGraphQLAction {
    pub(crate) should_allow: bool,
    pub(crate) should_log: bool,
    pub(crate) pq_id: Option<String>,
}

/// How the router should respond to requests that are not resolved as the IDs
/// of an operation in the manifest. (For the most part this means "requests
/// sent as freeform GraphQL", though it also includes requests sent as an ID
/// that is not found in the PQ manifest but is found in the APQ cache; because
/// you cannot combine APQs with safelisting, this is only relevant in "allow
/// all" and "log unknown" modes.)
#[derive(Debug)]
pub(crate) enum FreeformGraphQLBehavior {
    AllowAll {
        apq_enabled: bool,
    },
    DenyAll {
        log_unknown: bool,
    },
    AllowIfInSafelist {
        safelist: FreeformGraphQLSafelist,
        log_unknown: bool,
    },
    LogUnlessInSafelist {
        safelist: FreeformGraphQLSafelist,
        apq_enabled: bool,
    },
}

impl FreeformGraphQLBehavior {
    pub(super) fn action_for_freeform_graphql(
        &self,
        ast: Result<&ast::Document, &str>,
        client_name: Option<String>,
    ) -> FreeformGraphQLAction {
        match self {
            FreeformGraphQLBehavior::AllowAll { .. } => FreeformGraphQLAction {
                should_allow: true,
                should_log: false,
                pq_id: None,
            },
            // Note that this branch doesn't get called in practice, because we catch
            // DenyAll at an earlier phase with never_allows_freeform_graphql.
            FreeformGraphQLBehavior::DenyAll { log_unknown, .. } => FreeformGraphQLAction {
                should_allow: false,
                should_log: *log_unknown,
                pq_id: None,
            },
            FreeformGraphQLBehavior::AllowIfInSafelist {
                safelist,
                log_unknown,
                ..
            } => {
                let pq_id = safelist.get_pq_id_for_body(ast, client_name);
                if pq_id.is_some() {
                    FreeformGraphQLAction {
                        should_allow: true,
                        should_log: false,
                        pq_id,
                    }
                } else {
                    FreeformGraphQLAction {
                        should_allow: false,
                        should_log: *log_unknown,
                        pq_id: None,
                    }
                }
            }
            FreeformGraphQLBehavior::LogUnlessInSafelist { safelist, .. } => {
                let pq_id = safelist.get_pq_id_for_body(ast, client_name);
                FreeformGraphQLAction {
                    should_allow: true,
                    should_log: pq_id.is_none(),
                    pq_id,
                }
            }
        }
    }
}

/// A key into the freeform safelist: a normalized operation body scoped to an
/// optional client name. A `None` client name matches any client, mirroring the
/// client-name scoping of ID-based lookup in
/// [`super::manifest_poller::PersistedQueryManifestPoller::get_operation_body`].
#[derive(Debug, Eq, Hash, PartialEq)]
struct NormalizedBodyKey {
    /// The normalized operation body (see [`FreeformGraphQLSafelist`]).
    normalized_body: String,
    /// The client name the body is registered under; if `None`, matches any client.
    client_name: Option<String>,
}

/// The normalized bodies of all operations in the PQ manifest, mapping each
/// (normalized body, client name) pair to its PQ operation ID (usually a hash of
/// the operation body).
///
/// Normalization currently consists of:
/// - Sorting the top-level definitions (operation and fragment definitions)
///   deterministically.
/// - Printing the AST using apollo-encoder's default formatting (ie,
///   normalizing all ignored characters such as whitespace and comments).
///
/// Sorting top-level definitions is important because common clients such as
/// Apollo Client Web have modes of use where it is easy to find all the
/// operation and fragment definitions at build time, but challenging to
/// determine what order the client will put them in at run time.
///
/// Normalizing ignored characters is helpful because being strict on whitespace
/// is more likely to get in your way than to aid in security --- but more
/// importantly, once we're doing any normalization at all, it's much easier to
/// normalize to the default formatting instead of trying to preserve
/// formatting.
#[derive(Debug)]
pub(crate) struct FreeformGraphQLSafelist {
    normalized_bodies: HashMap<NormalizedBodyKey, String>,
}

impl FreeformGraphQLSafelist {
    pub(super) fn new(manifest: &PersistedQueryManifest) -> Self {
        let mut safelist = Self {
            normalized_bodies: HashMap::new(),
        };

        for (key, body) in manifest.iter() {
            safelist.insert_from_manifest(body, &key.operation_id, key.client_name.clone());
        }

        safelist
    }

    fn insert_from_manifest(
        &mut self,
        body_from_manifest: &str,
        operation_id: &str,
        client_name: Option<String>,
    ) {
        let normalized_body = self.normalize_body(
            ast::Document::parse(body_from_manifest, "from_manifest")
                .as_ref()
                .map_err(|_| body_from_manifest),
        );
        self.normalized_bodies.insert(
            NormalizedBodyKey {
                normalized_body,
                client_name,
            },
            operation_id.to_string(),
        );
    }

    pub(super) fn get_pq_id_for_body(
        &self,
        ast: Result<&ast::Document, &str>,
        client_name: Option<String>,
    ) -> Option<String> {
        // Note: consider adding an LRU cache that caches this function's return
        // value based solely on body_from_request without needing to normalize
        // the body.
        let normalized_body = self.normalize_body(ast);
        // Prefer an exact client-name match, then fall back to a client-agnostic
        // (`None`) entry, which matches any client. This mirrors the scoping of
        // ID-based lookup in `PersistedQueryManifestPoller::get_operation_body`.
        if client_name.is_some()
            && let Some(operation_id) =
                self.get_pq_id_for_normalized_body(&normalized_body, client_name)
        {
            return Some(operation_id);
        }
        self.get_pq_id_for_normalized_body(&normalized_body, None)
    }

    /// Looks up the operation ID for an already-normalized body registered under
    /// exactly the given client name (`None` is the client-agnostic entry).
    fn get_pq_id_for_normalized_body(
        &self,
        normalized_body: &str,
        client_name: Option<String>,
    ) -> Option<String> {
        self.normalized_bodies
            .get(&NormalizedBodyKey {
                normalized_body: normalized_body.to_owned(),
                client_name,
            })
            .cloned()
    }

    pub(super) fn normalize_body(&self, ast: Result<&ast::Document, &str>) -> String {
        match ast {
            Err(body_from_request) => {
                // If we can't parse the operation (whether from the PQ list or the
                // incoming request), then we can't normalize it. We keep it around
                // unnormalized, so that it at least works as a byte-for-byte
                // safelist entry.
                body_from_request.to_string()
            }
            Ok(ast) => {
                let mut operations = vec![];
                let mut fragments = vec![];

                for definition in &ast.definitions {
                    match definition {
                        ast::Definition::OperationDefinition(def) => operations.push(def.clone()),
                        ast::Definition::FragmentDefinition(def) => fragments.push(def.clone()),
                        _ => {}
                    }
                }

                let mut new_document = ast::Document::new();

                // First include operation definitions, sorted by name.
                operations.sort_by_key(|x| x.name.clone());
                new_document
                    .definitions
                    .extend(operations.into_iter().map(Into::into));

                // Next include fragment definitions, sorted by name.
                fragments.sort_by_key(|x| x.name.clone());
                new_document
                    .definitions
                    .extend(fragments.into_iter().map(Into::into));
                new_document.to_string()
            }
        }
    }
}

/// Determine behavior based on PQ configuration
pub(super) fn get_freeform_graphql_behavior(
    config: &Configuration,
    new_manifest: &PersistedQueryManifest,
) -> FreeformGraphQLBehavior {
    if config.persisted_queries.safelist.enabled {
        if config.persisted_queries.safelist.require_id {
            FreeformGraphQLBehavior::DenyAll {
                log_unknown: config.persisted_queries.log_unknown,
            }
        } else {
            FreeformGraphQLBehavior::AllowIfInSafelist {
                safelist: FreeformGraphQLSafelist::new(new_manifest),
                log_unknown: config.persisted_queries.log_unknown,
            }
        }
    } else if config.persisted_queries.log_unknown {
        FreeformGraphQLBehavior::LogUnlessInSafelist {
            safelist: FreeformGraphQLSafelist::new(new_manifest),
            apq_enabled: config.apq.enabled,
        }
    } else {
        FreeformGraphQLBehavior::AllowAll {
            apq_enabled: config.apq.enabled,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::configuration::Apq;
    use crate::configuration::PersistedQueries;
    use crate::configuration::PersistedQueriesSafelist;
    use crate::services::layers::persisted_queries::manifest::ManifestOperation;

    #[test]
    fn safelist_body_normalization() {
        let safelist = FreeformGraphQLSafelist::new(&PersistedQueryManifest::from(vec![
            ManifestOperation {
                id: "valid-syntax".to_string(),
                body: "fragment A on T { a }    query SomeOp { ...A ...B }    fragment,,, B on U{b c  } # yeah".to_string(),
                client_name: None,
            },
            ManifestOperation {
                id: "invalid-syntax".to_string(),
                body: "}}}".to_string(),
                client_name: None,
            },
            ManifestOperation {
                id: "multiple-ops".to_string(),
                body: "query Op1 { a b } query Op2 { b a }".to_string(),
                client_name: None,
            },
        ]));

        let is_allowed = |body: &str| -> bool {
            safelist
                .get_pq_id_for_body(
                    ast::Document::parse(body, "").as_ref().map_err(|_| body),
                    None,
                )
                .is_some()
        };

        // Precise string matches.
        assert!(is_allowed(
            "fragment A on T { a }    query SomeOp { ...A ...B }    fragment,,, B on U{b c  } # yeah"
        ));

        // Reordering definitions and reformatting a bit matches.
        assert!(is_allowed(
            "#comment\n  fragment, B on U  , { b    c }    query SomeOp {  ...A ...B }  fragment    \nA on T { a }"
        ));

        // Reordering operation definitions matches
        assert!(is_allowed("query Op2 { b a } query Op1 { a b }"));

        // Reordering fields does not match!
        assert!(!is_allowed(
            "fragment A on T { a }    query SomeOp { ...A ...B }    fragment,,, B on U{c b  } # yeah"
        ));

        // Documents with invalid syntax don't match...
        assert!(!is_allowed("}}}}"));

        // ... unless they precisely match a safelisted document that also has invalid syntax.
        assert!(is_allowed("}}}"));
    }

    #[test]
    fn safelist_respects_client_name() {
        let safelist = FreeformGraphQLSafelist::new(&PersistedQueryManifest::from(vec![
            // Registered for any client.
            ManifestOperation {
                id: "any-client".to_string(),
                body: "query AnyClient { a }".to_string(),
                client_name: None,
            },
            // Registered for the "web" client only.
            ManifestOperation {
                id: "web-only".to_string(),
                body: "query WebOnly { b }".to_string(),
                client_name: Some("web".to_string()),
            },
            // Same body registered under two different scopes.
            ManifestOperation {
                id: "shared-web".to_string(),
                body: "query Shared { c }".to_string(),
                client_name: Some("web".to_string()),
            },
            ManifestOperation {
                id: "shared-any".to_string(),
                body: "query Shared { c }".to_string(),
                client_name: None,
            },
        ]));

        let pq_id_for = |body: &str, client_name: Option<&str>| -> Option<String> {
            safelist.get_pq_id_for_body(
                ast::Document::parse(body, "").as_ref().map_err(|_| body),
                client_name.map(|c| c.to_string()),
            )
        };

        // A client-agnostic entry matches any client (or no client).
        assert_eq!(
            pq_id_for("query AnyClient { a }", None).as_deref(),
            Some("any-client")
        );
        assert_eq!(
            pq_id_for("query AnyClient { a }", Some("web")).as_deref(),
            Some("any-client")
        );
        assert_eq!(
            pq_id_for("query AnyClient { a }", Some("ios")).as_deref(),
            Some("any-client")
        );

        // A client-scoped entry only matches its registered client.
        assert_eq!(
            pq_id_for("query WebOnly { b }", Some("web")).as_deref(),
            Some("web-only")
        );
        assert_eq!(pq_id_for("query WebOnly { b }", Some("ios")), None);
        assert_eq!(pq_id_for("query WebOnly { b }", None), None);

        // When a body is registered under both a specific client and no client,
        // the exact client match wins and other clients fall back to the
        // client-agnostic entry.
        assert_eq!(
            pq_id_for("query Shared { c }", Some("web")).as_deref(),
            Some("shared-web")
        );
        assert_eq!(
            pq_id_for("query Shared { c }", Some("ios")).as_deref(),
            Some("shared-any")
        );
        assert_eq!(
            pq_id_for("query Shared { c }", None).as_deref(),
            Some("shared-any")
        );
    }

    fn freeform_behavior_from_pq_options(
        safe_list: bool,
        require_id: Option<bool>,
        log_unknown: Option<bool>,
    ) -> FreeformGraphQLBehavior {
        let manifest = &PersistedQueryManifest::from(vec![ManifestOperation {
            id: "valid-syntax".to_string(),
            body: "query SomeOp { a b }".to_string(),
            client_name: None,
        }]);

        let config = Configuration::builder()
            .persisted_query(
                PersistedQueries::builder()
                    .enabled(true)
                    .safelist(
                        PersistedQueriesSafelist::builder()
                            .enabled(safe_list)
                            .require_id(require_id.unwrap_or_default())
                            .build(),
                    )
                    .log_unknown(log_unknown.unwrap_or_default())
                    .build(),
            )
            .apq(Apq::fake_new(Some(false)))
            .build()
            .unwrap();
        get_freeform_graphql_behavior(&config, manifest)
    }

    #[test]
    fn test_get_freeform_graphql_behavior() {
        // safelist disabled
        assert!(matches!(
            freeform_behavior_from_pq_options(false, None, None),
            FreeformGraphQLBehavior::AllowAll { .. }
        ));

        // safelist disabled, log_unknown enabled
        assert!(matches!(
            freeform_behavior_from_pq_options(false, None, Some(true)),
            FreeformGraphQLBehavior::LogUnlessInSafelist { .. }
        ));

        // safelist enabled, id required
        assert!(matches!(
            freeform_behavior_from_pq_options(true, Some(true), None),
            FreeformGraphQLBehavior::DenyAll { .. }
        ));

        // safelist enabled, id not required
        assert!(matches!(
            freeform_behavior_from_pq_options(true, None, None),
            FreeformGraphQLBehavior::AllowIfInSafelist { .. }
        ));
    }
}