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
mod layer;
mod limited;
use std::error::Error;
use async_trait::async_trait;
use bytesize::ByteSize;
use http::StatusCode;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use tower::BoxError;
use tower::ServiceBuilder;
use tower::ServiceExt;
use crate::Context;
use crate::graphql;
use crate::layers::ServiceBuilderExt;
use crate::plugin::Plugin;
use crate::plugin::PluginInit;
use crate::plugins::limits::layer::BodyLimitControl;
use crate::plugins::limits::layer::BodyLimitError;
use crate::plugins::limits::layer::RequestBodyLimitLayer;
use crate::services::router;
use crate::services::router::BoxService;
/// Configuration for operation limits, parser limits, HTTP limits, etc.
#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct Config {
/// If set, requests with operations deeper than this maximum
/// are rejected with a HTTP 400 Bad Request response and GraphQL error with
/// `"extensions": {"code": "MAX_DEPTH_LIMIT"}`
///
/// Counts depth of an operation, looking at its selection sets,Ë›
/// including fields in fragments and inline fragments. The following
/// example has a depth of 3.
///
/// ```graphql
/// query getProduct {
/// book { # 1
/// ...bookDetails
/// }
/// }
///
/// fragment bookDetails on Book {
/// details { # 2
/// ... on ProductDetailsBook {
/// country # 3
/// }
/// }
/// }
/// ```
pub(crate) max_depth: Option<u32>,
/// If set, requests with operations higher than this maximum
/// are rejected with a HTTP 400 Bad Request response and GraphQL error with
/// `"extensions": {"code": "MAX_DEPTH_LIMIT"}`
///
/// Height is based on simple merging of fields using the same name or alias,
/// but only within the same selection set.
/// For example `name` here is only counted once and the query has height 3, not 4:
///
/// ```graphql
/// query {
/// name { first }
/// name { last }
/// }
/// ```
///
/// This may change in a future version of Apollo Router to do
/// [full field merging across fragments][merging] instead.
///
/// [merging]: https://spec.graphql.org/October2021/#sec-Field-Selection-Merging]
pub(crate) max_height: Option<u32>,
/// If set, requests with operations with more root fields than this maximum
/// are rejected with a HTTP 400 Bad Request response and GraphQL error with
/// `"extensions": {"code": "MAX_ROOT_FIELDS_LIMIT"}`
///
/// This limit counts only the top level fields in a selection set,
/// including fragments and inline fragments.
pub(crate) max_root_fields: Option<u32>,
/// If set, requests with operations with more aliases than this maximum
/// are rejected with a HTTP 400 Bad Request response and GraphQL error with
/// `"extensions": {"code": "MAX_ALIASES_LIMIT"}`
pub(crate) max_aliases: Option<u32>,
/// If set to true (which is the default is dev mode),
/// requests that exceed a `max_*` limit are *not* rejected.
/// Instead they are executed normally, and a warning is logged.
pub(crate) warn_only: bool,
/// Limit recursion in the GraphQL parser to protect against stack overflow.
/// default: 500
pub(crate) parser_max_recursion: usize,
/// Limit the number of tokens the GraphQL parser processes before aborting.
pub(crate) parser_max_tokens: usize,
/// Limit the size of incoming HTTP requests read from the network,
/// to protect against running out of memory. Default: 2000000 (2 MB)
pub(crate) http_max_request_bytes: usize,
/// Limit the maximum number of headers of incoming HTTP1 requests. Default is 100.
///
/// If router receives more headers than the buffer size, it responds to the client with
/// "431 Request Header Fields Too Large".
///
pub(crate) http1_max_request_headers: Option<usize>,
/// Limit the maximum buffer size for the HTTP1 connection.
///
/// Default is ~400kib.
#[schemars(with = "Option<String>", default)]
pub(crate) http1_max_request_buf_size: Option<ByteSize>,
}
impl Default for Config {
fn default() -> Self {
Self {
// These limits are opt-in
max_depth: None,
max_height: None,
max_root_fields: None,
max_aliases: None,
warn_only: false,
http_max_request_bytes: 2_000_000,
http1_max_request_headers: None,
http1_max_request_buf_size: None,
parser_max_tokens: 15_000,
// This is `apollo-parser`’s default, which protects against stack overflow
// but is still very high for "reasonable" queries.
// https://github.com/apollographql/apollo-rs/blob/apollo-parser%400.7.3/crates/apollo-parser/src/parser/mod.rs#L93-L104
parser_max_recursion: 500,
}
}
}
struct LimitsPlugin {
config: Config,
}
#[async_trait]
impl Plugin for LimitsPlugin {
type Config = Config;
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError>
where
Self: Sized,
{
Ok(LimitsPlugin {
config: init.config,
})
}
fn router_service(&self, service: BoxService) -> BoxService {
let control = BodyLimitControl::new(self.config.http_max_request_bytes);
let control_for_context = control.clone();
ServiceBuilder::new()
.map_request(move |r: router::Request| {
let control_for_context = control_for_context.clone();
r.context
.extensions()
.with_lock(|mut lock| lock.insert(control_for_context));
r
})
.map_future_with_request_data(
|r: &router::Request| r.context.clone(),
|ctx, f| async { Self::map_error_to_graphql(f.await, ctx) },
)
// Here we need to convert to and from the underlying http request types so that we can use existing middleware.
.map_request(Into::into)
.map_response(Into::into)
.layer(RequestBodyLimitLayer::new(control))
.map_request(Into::into)
.map_response(Into::into)
.service(service)
.boxed()
}
}
impl LimitsPlugin {
fn map_error_to_graphql(
resp: Result<router::Response, BoxError>,
ctx: Context,
) -> Result<router::Response, BoxError> {
// There are two ways we can get a payload too large error:
// 1. The request body is too large and detected via content length header
// 2. The request body is and it failed at some other point in the pipeline.
// We expect that other pipeline errors will have wrapped the source error rather than throwing it away.
match resp {
Ok(r) => {
if r.response.status() == StatusCode::PAYLOAD_TOO_LARGE {
Self::increment_legacy_metric();
Ok(BodyLimitError::PayloadTooLarge.into_response(ctx))
} else {
Ok(r)
}
}
Err(e) => {
// Getting the root cause is a bit fiddly
let mut root_cause: &dyn Error = e.as_ref();
while let Some(cause) = root_cause.source() {
root_cause = cause;
}
match root_cause.downcast_ref::<BodyLimitError>() {
None => Err(e),
Some(_) => {
Self::increment_legacy_metric();
Ok(BodyLimitError::PayloadTooLarge.into_response(ctx))
}
}
}
}
}
fn increment_legacy_metric() {
// Remove this eventually
// This is already handled by the telemetry plugin via the http.server.request metric.
u64_counter!(
"apollo_router_http_requests_total",
"Total number of HTTP requests made. (deprecated)",
1,
status = StatusCode::PAYLOAD_TOO_LARGE.as_u16() as i64,
error = BodyLimitError::PayloadTooLarge.to_string()
);
}
}
impl BodyLimitError {
fn into_response(self, ctx: Context) -> router::Response {
match self {
BodyLimitError::PayloadTooLarge => router::Response::error_builder()
.error(
graphql::Error::builder()
.message(self.to_string())
.extension_code("INVALID_GRAPHQL_REQUEST")
.extension("details", self.to_string())
.build(),
)
.status_code(StatusCode::PAYLOAD_TOO_LARGE)
.context(ctx)
.build()
.unwrap(),
}
}
}
register_plugin!("apollo", "limits", LimitsPlugin);
#[cfg(test)]
mod test {
use http::StatusCode;
use tower::BoxError;
use crate::plugins::limits::LimitsPlugin;
use crate::plugins::limits::layer::BodyLimitControl;
use crate::plugins::test::PluginTestHarness;
use crate::services::router;
use crate::services::router::body::get_body_bytes;
#[tokio::test]
async fn test_body_content_length_limit_exceeded() {
let plugin = plugin().await;
let resp = plugin
.call_router(
router::Request::fake_builder()
.body("This is a test")
.build()
.unwrap(),
|r| async {
let body = r.router_request.into_body();
let _ = get_body_bytes(body).await?;
panic!("should have failed to read stream")
},
)
.await;
assert!(resp.is_ok());
let resp = resp.unwrap();
assert_eq!(resp.response.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
String::from_utf8(
get_body_bytes(resp.response.into_body())
.await
.unwrap()
.to_vec()
)
.unwrap(),
"{\"errors\":[{\"message\":\"Request body payload too large\",\"extensions\":{\"details\":\"Request body payload too large\",\"code\":\"INVALID_GRAPHQL_REQUEST\"}}]}"
);
}
#[tokio::test]
async fn test_body_content_length_limit_ok() {
let plugin = plugin().await;
let resp = plugin
.call_router(
router::Request::fake_builder().body("").build().unwrap(),
|r| async {
let body = r.router_request.into_body();
let body = get_body_bytes(body).await;
assert!(body.is_ok());
Ok(router::Response::fake_builder().build().unwrap())
},
)
.await;
assert!(resp.is_ok());
let resp = resp.unwrap();
assert_eq!(resp.response.status(), StatusCode::OK);
assert_eq!(
String::from_utf8(
get_body_bytes(resp.response.into_body())
.await
.unwrap()
.to_vec()
)
.unwrap(),
"{}"
);
}
#[tokio::test]
async fn test_header_content_length_limit_exceeded() {
let plugin = plugin().await;
let resp = plugin
.call_router(
router::Request::fake_builder()
.header("Content-Length", "100")
.body("")
.build()
.unwrap(),
|_| async { panic!("should have rejected request") },
)
.await;
assert!(resp.is_ok());
let resp = resp.unwrap();
assert_eq!(resp.response.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
String::from_utf8(
get_body_bytes(resp.response.into_body())
.await
.unwrap()
.to_vec()
)
.unwrap(),
"{\"errors\":[{\"message\":\"Request body payload too large\",\"extensions\":{\"details\":\"Request body payload too large\",\"code\":\"INVALID_GRAPHQL_REQUEST\"}}]}"
);
}
#[tokio::test]
async fn test_header_content_length_limit_ok() {
let plugin = plugin().await;
let resp = plugin
.call_router(
router::Request::fake_builder()
.header("Content-Length", "5")
.body("")
.build()
.unwrap(),
|_| async { Ok(router::Response::fake_builder().build().unwrap()) },
)
.await;
assert!(resp.is_ok());
let resp = resp.unwrap();
assert_eq!(resp.response.status(), StatusCode::OK);
assert_eq!(
String::from_utf8(
get_body_bytes(resp.response.into_body())
.await
.unwrap()
.to_vec()
)
.unwrap(),
"{}"
);
}
#[tokio::test]
async fn test_non_limit_error_passthrough() {
// We should not be translating errors that are not limit errors into graphql errors
let plugin = plugin().await;
let resp = plugin
.call_router(
router::Request::fake_builder().body("").build().unwrap(),
|_| async { Err(BoxError::from("error")) },
)
.await;
assert!(resp.is_err());
}
#[tokio::test]
async fn test_limits_dynamic_update() {
let plugin = plugin().await;
let resp = plugin
.call_router(
router::Request::fake_builder()
.body("This is a test")
.build()
.unwrap(),
|r| async move {
// Before we go for the body, we'll update the limit
r.context.extensions().with_lock(|lock| {
let control: &BodyLimitControl =
lock.get().expect("mut have body limit control");
assert_eq!(control.remaining(), 10);
assert_eq!(control.limit(), 10);
control.update_limit(100);
});
let body = r.router_request.into_body();
let _ = get_body_bytes(body).await?;
// Now let's check progress
r.context.extensions().with_lock(|lock| {
let control: &BodyLimitControl =
lock.get().expect("mut have body limit control");
assert_eq!(control.remaining(), 86);
});
Ok(router::Response::fake_builder().build().unwrap())
},
)
.await;
assert!(resp.is_ok());
let resp = resp.unwrap();
assert_eq!(resp.response.status(), StatusCode::OK);
assert_eq!(
String::from_utf8(
get_body_bytes(resp.response.into_body())
.await
.unwrap()
.to_vec()
)
.unwrap(),
"{}"
);
}
async fn plugin() -> PluginTestHarness<LimitsPlugin> {
let plugin: PluginTestHarness<LimitsPlugin> = PluginTestHarness::new(
Some(include_str!("fixtures/content_length_limit.router.yaml")),
None,
)
.await;
plugin
}
}