apollo-router 2.15.0

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
use std::ops::ControlFlow;
use std::sync::Arc;

use futures::FutureExt;
use http::HeaderName;
use http::HeaderValue;
use http::StatusCode;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use mediatype::MediaType;
use mediatype::ReadParams;
use mediatype::names::BOUNDARY;
use mediatype::names::FORM_DATA;
use mediatype::names::MULTIPART;
use tower::BoxError;
use tower::ServiceBuilder;
use tower::ServiceExt;

use self::config::FileUploadsConfig;
use self::config::MultipartRequestLimits;
use self::error::FileUploadError;
use self::map_field::MapField;
use self::multipart_form_data::MultipartFormData;
use self::multipart_request::MultipartRequest;
use self::rearrange_query_plan::rearrange_query_plan;
use crate::graphql;
use crate::json_ext;
use crate::layers::ServiceBuilderExt;
use crate::plugin::PluginInit;
use crate::plugin::PluginPrivate;
use crate::plugins::limits::BodyLimitControl;
use crate::services::execution;
use crate::services::router;
use crate::services::router::body::RouterBody;
use crate::services::subgraph;
use crate::services::supergraph;

mod config;
mod error;
mod map_field;
mod multipart_form_data;
mod multipart_request;
mod rearrange_query_plan;

type Result<T> = std::result::Result<T, error::FileUploadError>;

struct FileUploadsPlugin {
    enabled: bool,
    limits: MultipartRequestLimits,
}

register_private_plugin!("apollo", "preview_file_uploads", FileUploadsPlugin);

#[async_trait::async_trait]
impl PluginPrivate for FileUploadsPlugin {
    type Config = FileUploadsConfig;

    async fn new(init: PluginInit<Self::Config>) -> std::result::Result<Self, BoxError> {
        let config = init.config;
        let enabled = config.enabled && config.protocols.multipart.enabled;
        let limits = config.protocols.multipart.limits;
        Ok(Self { enabled, limits })
    }

    fn router_service(&self, service: router::BoxService) -> router::BoxService {
        if !self.enabled {
            return service;
        }
        let limits = self.limits;
        let operation_body_timeout = limits.operation_body_timeout;
        ServiceBuilder::new()
            .checkpoint_async(move |req: router::Request| {
                async move {
                    let context = req.context.clone();
                    let layer_task = router_layer(req, limits);
                    let layer_result = if let Some(timeout) = operation_body_timeout {
                        match tokio::time::timeout(timeout, layer_task).await {
                            Ok(result) => result,
                            Err(_elapsed) => {
                                return Ok(ControlFlow::Break(operation_body_timeout_error(
                                    context,
                                )?));
                            }
                        }
                    } else {
                        layer_task.await
                    };
                    Ok(match layer_result {
                        Ok(req) => ControlFlow::Continue(req),
                        Err(err) => ControlFlow::Break(
                            router::Response::error_builder()
                                .status_code(err.http_status_code())
                                .errors(vec![err.into()])
                                .context(context)
                                .build()?,
                        ),
                    })
                }
                .boxed()
            })
            .buffered()
            .service(service)
            .boxed()
    }

    fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
        if !self.enabled {
            return service;
        }
        ServiceBuilder::new()
            .checkpoint_async(move |req: supergraph::Request| {
                async move {
                    let context = req.context.clone();
                    Ok(match supergraph_layer(req).await {
                        Ok(req) => ControlFlow::Continue(req),
                        Err(err) => ControlFlow::Break(
                            supergraph::Response::error_builder()
                                .errors(vec![err.into()])
                                .context(context)
                                .build()?,
                        ),
                    })
                }
                .boxed()
            })
            .buffered()
            .service(service)
            .boxed()
    }

    fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
        if !self.enabled {
            return service;
        }
        ServiceBuilder::new()
            .checkpoint(|req: execution::Request| {
                let context = req.context.clone();
                Ok(match execution_layer(req) {
                    Ok(req) => ControlFlow::Continue(req),
                    Err(err) => ControlFlow::Break(
                        execution::Response::error_builder()
                            .errors(vec![err.into()])
                            .context(context)
                            .build()?,
                    ),
                })
            })
            .service(service)
            .boxed()
    }

    fn subgraph_service(
        &self,
        _subgraph_name: &str,
        service: subgraph::BoxService,
    ) -> subgraph::BoxService {
        if !self.enabled {
            return service;
        }
        ServiceBuilder::new()
            .checkpoint_async(|req: subgraph::Request| {
                subgraph_layer(req)
                    .boxed()
                    .map(|req| Ok(ControlFlow::Continue(req)))
                    .boxed()
            })
            .buffered()
            .service(service)
            .boxed()
    }
}

fn get_multipart_mime(req: &router::Request) -> Option<MediaType<'_>> {
    req.router_request
        .headers()
        .get(CONTENT_TYPE)
        // Ignore parsing error, since they are reported by content_negotiation layer.
        .and_then(|header| header.to_str().ok())
        .and_then(|str| MediaType::parse(str).ok())
        .filter(|mime| mime.ty == MULTIPART && mime.subty == FORM_DATA)
}

fn operation_body_timeout_error(
    context: crate::Context,
) -> std::result::Result<router::Response, tower::BoxError> {
    router::Response::error_builder()
        .status_code(StatusCode::GATEWAY_TIMEOUT)
        .errors(vec![
            graphql::Error::builder()
                .message("The file upload operation body took too long to arrive")
                .extension_code("GATEWAY_TIMEOUT")
                .build(),
        ])
        .context(context)
        .build()
}

/// Takes in multipart request bodies, and turns them into serialized JSON bodies that the rest of the router
/// pipeline can understand.
///
/// # Context
/// Adds a [`MultipartRequest`] value to context.
async fn router_layer(
    req: router::Request,
    limits: MultipartRequestLimits,
) -> Result<router::Request> {
    if let Some(mime) = get_multipart_mime(&req) {
        let boundary = mime
            .get_param(BOUNDARY)
            .ok_or_else(|| FileUploadError::InvalidMultipartRequest(multer::Error::NoBoundary))?
            .to_string();

        let (mut request_parts, request_body) = req.router_request.into_parts();

        // Disable the global stream-level limit before multer reads anything.
        // limited::poll_frame fires when a single HTTP frame exceeds the remaining budget, but
        // hyper can deliver large frames on the first read (e.g. the entire multipart body). That
        // would trigger a spurious 413 before multer has extracted the small operations field.
        // Instead, we enforce http_max_request_bytes via multer's per-field SizeLimit on the
        // "operations" field (passed as operations_size_limit below), which counts content bytes
        // incrementally during streaming.
        let operations_size_limit = request_parts
            .extensions
            .get::<BodyLimitControl>()
            .and_then(|control| {
                let limit = control.limit();
                // update_limit asserts new > current, so skip if already at usize::MAX.
                if limit < usize::MAX {
                    control.update_limit(usize::MAX);
                }
                u64::try_from(limit).ok()
            })
            .unwrap_or(u64::MAX);

        let mut multipart =
            MultipartRequest::new(request_body, boundary, limits, operations_size_limit);
        let operations_stream = multipart.operations_field().await?;

        req.context
            .extensions()
            .with_lock(|lock| lock.insert(multipart));

        let content_type = operations_stream
            .headers()
            .get(CONTENT_TYPE)
            .cloned()
            .unwrap_or_else(|| HeaderValue::from_static("application/json"));

        // override Content-Type to content type of 'operations' field
        request_parts.headers.insert(CONTENT_TYPE, content_type);
        request_parts.headers.remove(CONTENT_LENGTH);

        let operations_bytes = operations_stream
            .bytes()
            .await
            .map_err(FileUploadError::InvalidMultipartRequest)?;

        let request_body = router::body::from_bytes(operations_bytes);
        return Ok(router::Request::from((
            http::Request::from_parts(request_parts, request_body),
            req.context,
        )));
    }

    Ok(req)
}

/// Patch up the variable values in file upload requests.
///
/// File uploads do something funky: They use *required* GraphQL field arguments (`file: Upload!`),
/// but then pass `null` as the variable value. This is invalid GraphQL, but it is how the file
/// uploads spec works.
///
/// To make all this work in the router, we stick some placeholder value in the variables used for
/// file uploads, and then remove them before we pass on the files to subgraphs.
async fn supergraph_layer(mut req: supergraph::Request) -> Result<supergraph::Request> {
    let multipart = req
        .context
        .extensions()
        .with_lock(|lock| lock.get::<MultipartRequest>().cloned());

    if let Some(mut multipart) = multipart {
        let map_field = multipart.map_field().await?;
        let variables = &mut req.supergraph_request.body_mut().variables;

        // patch variables to pass validation
        for variable_map in map_field.per_variable.values() {
            for (filename, paths) in variable_map.iter() {
                for variable_path in paths.iter() {
                    replace_value_at_path(
                        variables,
                        variable_path,
                        serde_json_bytes::Value::String(
                            format!("<Placeholder for file '{filename}'>").into(),
                        ),
                    )
                    .map_err(|path| FileUploadError::InputValueNotFound(path.join(".")))?;
                }
            }
        }

        req.context.extensions().with_lock(|lock| {
            lock.insert(SupergraphLayerResult {
                multipart,
                map: Arc::new(map_field),
            })
        });
    }
    Ok(req)
}

// Replaces value at path with the provided one.
// Returns the provided path if the path is not valid for the given object
fn replace_value_at_path<'a>(
    variables: &'a mut json_ext::Object,
    path: &'a [String],
    value: serde_json_bytes::Value,
) -> std::result::Result<(), &'a [String]> {
    if let Some(v) = get_value_at_path(variables, path) {
        *v = value;
        Ok(())
    } else {
        Err(path)
    }
}

// Removes value at path.
fn remove_value_at_path<'a>(variables: &'a mut json_ext::Object, path: &'a [String]) {
    if let Some(v) = get_value_at_path(variables, path) {
        *v = serde_json_bytes::Value::Null;
    }
}

fn get_value_at_path<'a>(
    variables: &'a mut json_ext::Object,
    path: &'a [String],
) -> Option<&'a mut serde_json_bytes::Value> {
    let mut iter = path.iter();
    let variable_name = iter.next();
    if let Some(variable_name) = variable_name {
        let root = variables.get_mut(variable_name.as_str());
        if let Some(root) = root {
            return iter.try_fold(root, |parent, segment| match parent {
                serde_json_bytes::Value::Object(map) => map.get_mut(segment.as_str()),
                serde_json_bytes::Value::Array(list) => segment
                    .parse::<usize>()
                    .ok()
                    .and_then(move |x| list.get_mut(x)),
                _ => None,
            });
        }
    }
    None
}

#[test]
fn it_works_with_one_segment() {
    let mut stuff = serde_json_bytes::json! {{
        "file1": null,
        "file2": null
    }};

    let variables = stuff.as_object_mut().unwrap();

    let path = &["file1".to_string()];

    assert_eq!(
        &mut serde_json_bytes::Value::Null,
        get_value_at_path(variables, path).unwrap()
    );
}
#[derive(Clone)]
struct SupergraphLayerResult {
    multipart: MultipartRequest,
    map: Arc<MapField>,
}

fn execution_layer(req: execution::Request) -> Result<execution::Request> {
    let supergraph_result = req
        .context
        .extensions()
        .with_lock(|lock| lock.get::<SupergraphLayerResult>().cloned());
    if let Some(supergraph_result) = supergraph_result {
        let SupergraphLayerResult { map, .. } = supergraph_result;

        let query_plan = Arc::new(rearrange_query_plan(&req.query_plan, &map)?);
        return Ok(execution::Request { query_plan, ..req });
    }
    Ok(req)
}

async fn subgraph_layer(mut req: subgraph::Request) -> subgraph::Request {
    let supergraph_result = req
        .context
        .extensions()
        .with_lock(|lock| lock.get::<SupergraphLayerResult>().cloned());
    if let Some(supergraph_result) = supergraph_result {
        let SupergraphLayerResult { multipart, map } = supergraph_result;

        let variables = &mut req.subgraph_request.body_mut().variables;
        let subgraph_map = map.sugraph_map(variables.keys());
        if !subgraph_map.is_empty() {
            for variable_map in map.per_variable.values() {
                for paths in variable_map.values() {
                    for path in paths {
                        remove_value_at_path(variables, path);
                    }
                }
            }

            req.subgraph_request
                .extensions_mut()
                .insert(MultipartFormData::new(subgraph_map, multipart));
        }
    }
    req
}

static APOLLO_REQUIRE_PREFLIGHT: HeaderName = HeaderName::from_static("apollo-require-preflight");
static TRUE: http::HeaderValue = HeaderValue::from_static("true");

pub(crate) async fn http_request_wrapper(
    mut req: http::Request<RouterBody>,
) -> http::Request<RouterBody> {
    let form = req.extensions_mut().get::<MultipartFormData>().cloned();
    if let Some(form) = form {
        let (mut request_parts, operations) = req.into_parts();
        request_parts
            .headers
            .insert(APOLLO_REQUIRE_PREFLIGHT.clone(), TRUE.clone());

        // override Content-Type to be 'multipart/form-data'
        request_parts
            .headers
            .insert(CONTENT_TYPE, form.content_type());
        let request_body = router::body::from_result_stream(form.into_stream(operations).await);

        return http::Request::from_parts(request_parts, request_body);
    }
    req
}