apollo-router 3.0.0-alpha.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
use std::sync::Arc;

use futures::StreamExt as _;
use futures::future::BoxFuture;
use tower::Service;

use crate::graphql;
use crate::plugins::limits::RouterLimitsConfig;
use crate::plugins::limits::operation_limits;
use crate::plugins::limits::operation_limits::OperationLimits;
use crate::services::query_parsing::ParsedDocument;
use crate::services::supergraph;

/// Layer that enforces operation limits and rejects GraphQL requests that exceed the limits.
///
/// # Context
/// This layer requires the following context values to be available on the request:
/// - [`ParsedDocument`] - An error is returned if the document is missing.
///
/// This layer populates the following context values on the request:
/// - [`OperationLimits`] - This can then be used to report telemetry.
pub(crate) struct EnforceOperationLimitsLayer {
    config: Arc<RouterLimitsConfig>,
}

impl EnforceOperationLimitsLayer {
    /// Create an operation limit enforcement layer based on router limits configuration.
    pub(crate) fn new(config: &RouterLimitsConfig) -> Self {
        Self {
            config: Arc::new(config.clone()),
        }
    }
}

impl<S> tower::Layer<S> for EnforceOperationLimitsLayer {
    type Service = EnforceOperationLimits<S>;

    fn layer(&self, inner: S) -> Self::Service {
        EnforceOperationLimits {
            inner,
            config: self.config.clone(),
        }
    }
}

/// Service that enforces operation limits.
#[derive(Clone)]
pub(crate) struct EnforceOperationLimits<S> {
    inner: S,
    config: Arc<RouterLimitsConfig>,
}

impl<S> Service<supergraph::Request> for EnforceOperationLimits<S>
where
    S: Service<supergraph::Request, Response = supergraph::Response> + Clone + Send + 'static,
    S::Error: From<http::Error> + Send + 'static,
    S::Future: Send + 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: supergraph::Request) -> Self::Future {
        let config = self.config.clone();
        let inner = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, inner);

        Box::pin(async move {
            let Some(document) = req
                .context
                .extensions()
                .with_lock(|lock| lock.get::<ParsedDocument>().cloned())
            else {
                // We shouldn't ever reach here unless the pipeline was set up
                // improperly (i.e. programmer error), but do something better than
                // panicking just in case.
                return Ok(supergraph::Response::error_builder()
                    .status_code(http::StatusCode::INTERNAL_SERVER_ERROR)
                    .context(req.context)
                    .error(
                        graphql::Error::builder()
                            .message("Cannot find executable document")
                            .extension_code("MISSING_EXECUTABLE_DOCUMENT")
                            .build(),
                    )
                    .build()
                    .expect("body is valid"));
            };

            let mut query_metrics = OperationLimits::default();

            let max = OperationLimits {
                depth: config.max_depth,
                height: config.max_height,
                root_fields: config.max_root_fields,
                aliases: config.max_aliases,
            };
            let result = operation_limits::check(
                &mut query_metrics,
                max,
                &document.executable,
                document.operation.name.as_deref(),
            );

            // Stash the measurements in context so they can be used for telemetry.
            req.context.extensions().with_lock(|lock| {
                let _ = lock.insert(query_metrics);
            });

            if let Err(OperationLimits {
                depth,
                height,
                root_fields,
                aliases,
            }) = result
                && !config.warn_only
            {
                let mut errors = Vec::new();
                let mut build = |exceeded, code, message| {
                    if exceeded {
                        errors.push(
                            graphql::Error::builder()
                                .message(message)
                                .extension_code(code)
                                .build(),
                        )
                    }
                };
                build(
                    depth,
                    "MAX_DEPTH_LIMIT",
                    "Maximum depth limit exceeded in this operation",
                );
                build(
                    height,
                    "MAX_HEIGHT_LIMIT",
                    "Maximum height (field count) limit exceeded in this operation",
                );
                build(
                    root_fields,
                    "MAX_ROOT_FIELDS_LIMIT",
                    "Maximum root fields limit exceeded in this operation",
                );
                build(
                    aliases,
                    "MAX_ALIASES_LIMIT",
                    "Maximum aliases limit exceeded in this operation",
                );
                let graphql_response = graphql::Response::builder().errors(errors).build();

                return http::Response::builder()
                    .status(http::StatusCode::BAD_REQUEST)
                    .body(futures::stream::once(std::future::ready(graphql_response)).boxed())
                    .map_err(Self::Error::from)
                    .map(|http_response| supergraph::Response {
                        response: http_response,
                        context: req.context,
                    });
            }

            inner.call(req).await
        })
    }
}

#[cfg(test)]
mod tests {
    use tower::ServiceBuilder;
    use tower::ServiceExt as _;

    use super::*;
    use crate::Context;
    use crate::services::supergraph;
    use crate::spec::Query;
    use crate::spec::Schema;
    use crate::test_harness::tracing_test;

    /// Build a supergraph request for a query.
    fn make_request(schema: &Schema, query: &str) -> supergraph::Request {
        // In the future, we can hopefully just use a query parsing tower layer here...
        let doc = Query::parse_document(query, None, schema, &Default::default()).unwrap();
        let ctx = Context::new();
        ctx.extensions()
            .with_lock(|lock| lock.insert::<ParsedDocument>(doc));
        supergraph::Request::fake_builder()
            .query(query)
            .context(ctx)
            .build()
            .unwrap()
    }

    fn error_codes(response: &graphql::Response) -> Vec<&str> {
        response
            .errors
            .iter()
            .filter_map(|e| e.extensions.get("code")?.as_str())
            .collect()
    }

    #[tokio::test]
    async fn test_under_limits() {
        let schema = Schema::parse(
            include_str!("../../testdata/supergraph.graphql"),
            &Default::default(),
        )
        .unwrap();
        let config = RouterLimitsConfig {
            max_root_fields: Some(1),
            max_aliases: Some(2),
            max_depth: Some(3),
            max_height: Some(4),
            ..Default::default()
        };

        let (mock, mut handle) =
            tower_test::mock::pair::<supergraph::Request, supergraph::Response>();
        let driver = tokio::spawn(async move {
            let (_req, responder) = handle.next_request().await.unwrap();
            responder.send_response(supergraph::Response::fake_builder().build().unwrap());
        });

        let service = ServiceBuilder::new()
            .layer(EnforceOperationLimitsLayer::new(&config))
            .service(mock);

        let mut response = service
            .oneshot(make_request(&schema, "{ me { id } }"))
            .await
            .unwrap();

        let body = response.next_response().await.unwrap();
        assert!(body.errors.is_empty());

        crate::plugin::test::await_mock_driver(driver).await;
    }

    #[tokio::test]
    async fn test_max_root_fields() {
        let schema = Schema::parse(
            include_str!("../../testdata/supergraph.graphql"),
            &Default::default(),
        )
        .unwrap();
        let config = RouterLimitsConfig {
            max_root_fields: Some(1),
            ..Default::default()
        };

        let (mock, handle) = tower_test::mock::pair::<supergraph::Request, supergraph::Response>();

        let service = ServiceBuilder::new()
            .layer(EnforceOperationLimitsLayer::new(&config))
            .service(mock);

        let query = "{ me { id } topProducts { name } }";
        let mut response = service.oneshot(make_request(&schema, query)).await.unwrap();
        let body = response.next_response().await.unwrap();
        assert_eq!(error_codes(&body), &["MAX_ROOT_FIELDS_LIMIT"]);

        crate::plugin::test::assert_no_mock_calls(handle).await;
    }

    #[tokio::test]
    async fn test_max_aliases() {
        let schema = Schema::parse(
            include_str!("../../testdata/supergraph.graphql"),
            &Default::default(),
        )
        .unwrap();
        let config = RouterLimitsConfig {
            max_aliases: Some(2),
            ..Default::default()
        };

        let (mock, handle) = tower_test::mock::pair::<supergraph::Request, supergraph::Response>();

        let service = ServiceBuilder::new()
            .layer(EnforceOperationLimitsLayer::new(&config))
            .service(mock);

        let query =
            "{ topProducts { productName: name productReviews: reviews { reviewBody: body } } }";
        let mut response = service.oneshot(make_request(&schema, query)).await.unwrap();
        let body = response.next_response().await.unwrap();
        assert_eq!(error_codes(&body), &["MAX_ALIASES_LIMIT"]);

        crate::plugin::test::assert_no_mock_calls(handle).await;
    }

    #[tokio::test]
    async fn test_max_depth() {
        let schema = Schema::parse(
            include_str!("../../testdata/supergraph.graphql"),
            &Default::default(),
        )
        .unwrap();
        let config = RouterLimitsConfig {
            max_depth: Some(3),
            ..Default::default()
        };

        let (mock, handle) = tower_test::mock::pair::<supergraph::Request, supergraph::Response>();

        let service = ServiceBuilder::new()
            .layer(EnforceOperationLimitsLayer::new(&config))
            .service(mock);

        let query = "{ topProducts { reviews { author { name } } } }";
        let mut response = service.oneshot(make_request(&schema, query)).await.unwrap();
        let body = response.next_response().await.unwrap();
        assert_eq!(error_codes(&body), &["MAX_DEPTH_LIMIT"]);

        crate::plugin::test::assert_no_mock_calls(handle).await;
    }

    #[tokio::test]
    async fn test_multiple_violations() {
        let schema = Schema::parse(
            include_str!("../../testdata/supergraph.graphql"),
            &Default::default(),
        )
        .unwrap();
        let config = RouterLimitsConfig {
            max_root_fields: Some(1),
            max_aliases: Some(2),
            max_depth: Some(3),
            max_height: Some(4),
            ..Default::default()
        };

        let (mock, handle) = tower_test::mock::pair::<supergraph::Request, supergraph::Response>();

        let service = ServiceBuilder::new()
            .layer(EnforceOperationLimitsLayer::new(&config))
            .service(mock);

        let query = "{
            topProducts {
                productName: name
                productReviews: reviews {
                    reviewAuthor: author {
                        name
                    }
                }
            }
        }";
        let mut response = service.oneshot(make_request(&schema, query)).await.unwrap();
        let body = response.next_response().await.unwrap();
        let mut codes = error_codes(&body);
        codes.sort();
        assert_eq!(
            codes,
            ["MAX_ALIASES_LIMIT", "MAX_DEPTH_LIMIT", "MAX_HEIGHT_LIMIT"]
        );

        crate::plugin::test::assert_no_mock_calls(handle).await;
    }

    #[tokio::test]
    async fn test_warn_only() {
        let _guard = tracing_test::dispatcher_guard();

        let schema = Schema::parse(
            include_str!("../../testdata/supergraph.graphql"),
            &Default::default(),
        )
        .unwrap();
        let config = RouterLimitsConfig {
            max_root_fields: Some(1),
            max_depth: Some(2),
            warn_only: true,
            ..Default::default()
        };

        let (mock, mut handle) =
            tower_test::mock::pair::<supergraph::Request, supergraph::Response>();
        let driver = tokio::spawn(async move {
            let (_req, responder) = handle.next_request().await.unwrap();
            responder.send_response(supergraph::Response::fake_builder().build().unwrap());
        });

        let service = ServiceBuilder::new()
            .layer(EnforceOperationLimitsLayer::new(&config))
            .service(mock);

        let query = "{ me { id } topProducts { reviews { body } } }";
        let mut response = service.oneshot(make_request(&schema, query)).await.unwrap();
        let body = response.next_response().await.unwrap();
        assert!(body.errors.is_empty());
        assert!(
            tracing_test::logs_contain("request exceeded complexity limits"),
            "expected a warning to be logged"
        );

        crate::plugin::test::await_mock_driver(driver).await;
    }
}