roas-http-validator 0.2.0

Validates HTTP requests against an OpenAPI description, with adapters for axum, actix-web, poem, salvo and rocket
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
//! The validator itself: a description, prepared once, judging many
//! requests.

use std::collections::BTreeMap;
use std::fmt;

use roas::v3_2::operation::Operation;
use roas::v3_2::parameter::Parameter;
use roas::v3_2::path_item::PathItem;
use roas::v3_2::spec::Spec;

use crate::body;
use crate::decoder::Decoders;
use crate::parameter;
use crate::paths;
use crate::report::{ErrorKind, Location, RoutingError, ValidationError, ValidationReport};
use crate::request::{RequestView, decode_path_segment};
use crate::router::Router;

/// What to check, and where the description's paths start.
///
/// ```
/// use roas_http_validator::Options;
///
/// let options = Options::new().base_path("/api/v1").reject_undescribed_query_parameters();
/// ```
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct Options {
    base_path: Option<String>,
    skip_body: bool,
    reject_undescribed_query_parameters: bool,
    pub(crate) decoders: Decoders,
}

/// Written out by hand because a decoder is a function, and a function
/// has nothing useful to print. The media types it was registered for
/// do.
impl fmt::Debug for Options {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Options")
            .field("base_path", &self.base_path)
            .field("skip_body", &self.skip_body)
            .field(
                "reject_undescribed_query_parameters",
                &self.reject_undescribed_query_parameters,
            )
            .field("decoders", &self.decoders.media_types().collect::<Vec<_>>())
            .finish()
    }
}

impl Options {
    /// Everything checked, base path taken from the Server Objects.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The prefix a request path carries before the description's own
    /// paths begin, overriding whatever `servers` implies.
    #[must_use]
    pub fn base_path(mut self, base_path: impl Into<String>) -> Self {
        self.base_path = Some(base_path.into());
        self
    }

    /// Leave the body alone. Useful in a middleware that would rather
    /// not buffer one, and in a client-side check of a request that has
    /// not been serialized yet.
    #[must_use]
    pub fn skip_body(mut self) -> Self {
        self.skip_body = true;
        self
    }

    /// Read a media type this crate does not know how to read.
    ///
    /// The built-in decoders cover JSON,
    /// `application/x-www-form-urlencoded` and `text/*`; anything else
    /// is reported as unchecked rather than guessed at. Register a
    /// decoder and its media type joins them — the bytes become a
    /// value, and the Schema Object judges it like any other.
    ///
    /// This is how `multipart/form-data` and XML are meant to be
    /// handled: see [`crate::Decoder`] for why they are a hook rather
    /// than more built-ins.
    ///
    /// Looked up the way a Media Type Object is — exact match, then a
    /// `type/*` range, then `*/*` — and a registration takes precedence
    /// over the built-in for the same media type, so a caller who wants
    /// their own JSON reader can have one.
    ///
    /// ```
    /// use roas_http_validator::Options;
    ///
    /// let options = Options::new().decoder("text/csv", |bytes, _media_type| {
    ///     let text = std::str::from_utf8(bytes).map_err(|error| error.to_string())?;
    ///     Ok(serde_json::Value::Array(
    ///         text.lines().map(|line| line.into()).collect(),
    ///     ))
    /// });
    /// ```
    #[must_use]
    pub fn decoder<F>(mut self, media_type: &str, decoder: F) -> Self
    where
        F: Fn(&[u8], &str) -> Result<serde_json::Value, String> + Send + Sync + 'static,
    {
        self.decoders
            .insert(media_type, std::sync::Arc::new(decoder));
        self
    }

    /// Report a query parameter the operation does not describe.
    ///
    /// Off by default: OpenAPI does not forbid undescribed query
    /// parameters, and plenty of real clients send tracking parameters
    /// that no description mentions. On, it catches the typo in
    /// `?limti=10` that would otherwise silently do nothing.
    #[must_use]
    pub fn reject_undescribed_query_parameters(mut self) -> Self {
        self.reject_undescribed_query_parameters = true;
        self
    }
}

/// One OpenAPI description, ready to judge requests against.
///
/// Building one walks the description's paths once; validating is then
/// a match and a handful of schema checks, so a server builds this at
/// startup and keeps it.
///
/// ```
/// use roas_http_validator::{RequestView, Validator};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let spec = serde_json::from_str(r#"{
///   "openapi": "3.2.0",
///   "info": { "title": "Pets", "version": "1.0.0" },
///   "paths": {
///     "/pets/{petId}": {
///       "get": {
///         "operationId": "getPet",
///         "parameters": [
///           { "name": "petId", "in": "path", "required": true,
///             "schema": { "type": "integer" } }
///         ]
///       }
///     }
///   }
/// }"#)?;
///
/// let validator = Validator::new(spec);
/// assert!(validator.validate(&RequestView::new("GET", "/pets/7"))?.is_valid());
/// assert!(!validator.validate(&RequestView::new("GET", "/pets/rex"))?.is_valid());
/// # Ok(()) }
/// ```
#[derive(Clone, Debug)]
pub struct Validator {
    spec: Spec,
    /// Every Path Item Object with its `$ref` followed and merged,
    /// resolved once here rather than on every request.
    path_items: BTreeMap<String, PathItem>,
    router: Router,
    options: Options,
}

impl Validator {
    /// Prepare a v3.2 description with the default [`Options`].
    #[must_use]
    pub fn new(spec: Spec) -> Self {
        Self::with_options(spec, Options::new())
    }

    /// Prepare a v3.2 description.
    #[must_use]
    pub fn with_options(spec: Spec, options: Options) -> Self {
        let path_items = paths::resolve(&spec);
        let router = Router::new(
            &path_items,
            spec.servers.as_deref(),
            options.base_path.as_deref(),
        );
        Self {
            spec,
            path_items,
            router,
            options,
        }
    }

    /// The description being validated against.
    #[must_use]
    pub fn spec(&self) -> &Spec {
        &self.spec
    }

    /// Judge one request.
    ///
    /// # Errors
    ///
    /// [`RoutingError`] when the request cannot be judged at all, which
    /// is a different answer from "the request is invalid" and usually a
    /// different response code:
    ///
    /// - [`RoutingError::PathNotFound`] — no template matches the path.
    /// - [`RoutingError::MethodNotAllowed`] — a template matches and
    ///   describes other methods, but not this one.
    /// - [`RoutingError::Unresolved`] — a template matches but its Path
    ///   Item Object could not be read, so neither of the above can be
    ///   said honestly.
    pub fn validate(&self, request: &RequestView<'_>) -> Result<ValidationReport, RoutingError> {
        let matched = self
            .router
            .route(&request.path, &request.method)
            .ok_or_else(|| RoutingError::PathNotFound {
                path: request.path.clone().into_owned(),
            })?;
        let template = matched.template.to_owned();
        let path_parameters = matched.parameters;

        let path_item = self.path_item(&template);
        // A `$ref` chain that could not be followed leaves part of this
        // Path Item Object unread.
        let unresolved = path_item.and_then(|item| item.reference.clone());
        let found = path_item.and_then(|item| self.operation(item, request));

        let Some((method, operation)) = found else {
            // With half the Path Item Object unread, "no such method"
            // is not something that can be said: the half that did not
            // arrive may well have described it.
            if let Some(reference) = unresolved {
                return Err(RoutingError::Unresolved {
                    template,
                    reference,
                });
            }
            return Err(RoutingError::MethodNotAllowed {
                template,
                // The token the request actually carried, not a
                // normalization of it: `get` was refused *because* it is
                // not `GET`, and saying "no GET here" beside an `Allow`
                // naming `GET` would be nonsense.
                method: request.method.clone().into_owned(),
                allowed: path_item.map(allowed_methods).unwrap_or_default(),
            });
        };

        let mut errors = Vec::new();
        // An operation was found, so the request can still be judged —
        // but whatever the unread half held went unapplied, and saying
        // so is the difference between "valid" and "not checked".
        if let Some(reference) = unresolved {
            errors.push(ValidationError {
                location: Location::Description,
                name: String::new(),
                pointer: String::new(),
                kind: ErrorKind::UnresolvedReference(reference),
            });
        }
        let parameters = self.parameters(path_item, operation, &mut errors);
        // Decoded once for the whole operation rather than per parameter.
        let extracted = parameter::Extracted::new(request, &path_parameters);

        for parameter in &parameters {
            parameter::validate(
                parameter,
                request,
                &extracted,
                &self.spec,
                &self.options.decoders,
                &mut errors,
            );
        }

        if self.options.reject_undescribed_query_parameters {
            check_for_strays(&extracted, &parameters, &self.spec, &mut errors);
        }

        if !self.options.skip_body
            && let Some(request_body) = &operation.request_body
        {
            match request_body.get_item(&self.spec) {
                Ok(request_body) => {
                    body::validate(
                        request_body,
                        request,
                        &self.spec,
                        &self.options.decoders,
                        &mut errors,
                    );
                }
                Err(error) => errors.push(ValidationError {
                    location: Location::Body,
                    name: String::new(),
                    pointer: String::new(),
                    kind: ErrorKind::UnresolvedReference(error.to_string()),
                }),
            }
        }

        Ok(ValidationReport {
            template,
            method,
            operation_id: operation.operation_id.clone(),
            // Decoded here and only here: validation splits before it
            // decodes, but a report is for a reader.
            path_parameters: path_parameters
                .iter()
                .map(|(name, raw)| (name.clone(), decode_path_segment(raw)))
                .collect(),
            errors,
        })
    }

    /// The operation a request's method names, and the key the Path
    /// Item Object files it under.
    ///
    /// See [`crate::method`] for why `get` does not find `get`.
    fn operation<'i>(
        &self,
        path_item: &'i PathItem,
        request: &RequestView<'_>,
    ) -> Option<(String, &'i Operation)> {
        // Each map is searched with its own key and never the other's.
        if let Some(key) = crate::method::standard(&request.method)
            && let Some((key, operation)) = path_item
                .operations
                .as_ref()
                .and_then(|operations| operations.get_key_value(&key))
        {
            return Some((crate::method::from_standard_key(key), operation));
        }
        path_item
            .additional_operations
            .as_ref()?
            .get_key_value(request.method.as_ref())
            // Already a method token: `additionalOperations` is keyed by
            // the method itself.
            .map(|(key, operation)| (key.clone(), operation))
    }

    /// The Path Item Object for a template, already resolved.
    fn path_item(&self, template: &str) -> Option<&PathItem> {
        self.path_items.get(template)
    }

    /// The parameters that apply to one operation: the Path Item
    /// Object's, overridden by the Operation Object's where both name
    /// the same `name` and `in`.
    fn parameters(
        &self,
        path_item: Option<&PathItem>,
        operation: &Operation,
        errors: &mut Vec<ValidationError>,
    ) -> Vec<Parameter> {
        let mut merged: BTreeMap<(String, Location), Parameter> = BTreeMap::new();
        let inherited = path_item.and_then(|item| item.parameters.as_deref());
        let declared = operation.parameters.as_deref();

        for source in [inherited, declared].into_iter().flatten() {
            for parameter in source {
                match parameter.get_item(&self.spec) {
                    Ok(parameter) => {
                        merged.insert(identity(parameter), parameter.clone());
                    }
                    // The parameter cannot be read, so it cannot be
                    // checked — which is the description's fault, not
                    // the request's, and says so.
                    Err(error) => errors.push(ValidationError {
                        location: Location::Description,
                        name: String::new(),
                        pointer: String::new(),
                        kind: ErrorKind::UnresolvedReference(error.to_string()),
                    }),
                }
            }
        }
        merged.into_values().collect()
    }
}

/// Report query parameters the operation says nothing about.
fn check_for_strays(
    extracted: &parameter::Extracted<'_>,
    parameters: &[Parameter],
    spec: &Spec,
    errors: &mut Vec<ValidationError>,
) {
    // `in: querystring` describes the query string whole, so there is no
    // such thing as a stray parameter alongside one.
    if parameters
        .iter()
        .any(|parameter| matches!(parameter, Parameter::Querystring(_)))
    {
        return;
    }
    for (name, _) in &extracted.query {
        if !parameters
            .iter()
            .any(|parameter| parameter::accounts_for(parameter, name, spec))
        {
            errors.push(ValidationError {
                location: Location::Query,
                name: name.clone(),
                pointer: String::new(),
                kind: ErrorKind::Undescribed,
            });
        }
    }
}

/// Every method a Path Item Object describes, as method tokens — which
/// is what an `Allow` header wants, and what `operations`' lowercase
/// keys are not.
fn allowed_methods(path_item: &PathItem) -> Vec<String> {
    let standard = path_item
        .operations
        .iter()
        .flatten()
        .map(|(key, _)| crate::method::from_standard_key(key));
    let additional = path_item
        .additional_operations
        .iter()
        .flatten()
        .map(|(key, _)| key.clone());
    standard.chain(additional).collect()
}

/// What makes a parameter unique: its name and its location.
fn identity(parameter: &Parameter) -> (String, Location) {
    match parameter {
        Parameter::Path(path) => (path.name.clone(), Location::Path),
        Parameter::Query(query) => (query.name.clone(), Location::Query),
        Parameter::Querystring(querystring) => (querystring.name.clone(), Location::Querystring),
        Parameter::Header(header) => (header.name.clone(), Location::Header),
        Parameter::Cookie(cookie) => (cookie.name.clone(), Location::Cookie),
    }
}