Skip to main content

cufflink_types/openapi/
check.rs

1//! What a documented manifest must satisfy for its spec to be generated:
2//! checked when the SDK emits the manifest, at deploy, and before
3//! generation.
4
5use super::custom::{self, Components};
6use super::schema::schema_names;
7use super::{crud, default_style, OpenApiError, PathStyle};
8use crate::{CustomRouteDefinition, RoutePosture, ServiceManifest};
9use serde_json::{Map, Value};
10use std::collections::BTreeSet;
11
12/// The security schemes `route` requires: its doc's, else its posture's.
13/// The scheme of partner-key routes: the `X-Api-Key` header.
14pub(super) const API_KEY_SCHEME: &str = "api_key";
15
16pub(super) fn route_security<'a>(
17    route: &'a CustomRouteDefinition,
18    scheme: &'a str,
19) -> Vec<&'a str> {
20    match route.doc.as_ref().and_then(|doc| doc.security.as_ref()) {
21        Some(names) => names.iter().map(String::as_str).collect(),
22        None => match &route.posture {
23            None | Some(RoutePosture::Public { .. }) | Some(RoutePosture::Internal { .. }) => {
24                Vec::new()
25            }
26            Some(RoutePosture::ApiKey { .. }) => vec![API_KEY_SCHEME],
27            Some(RoutePosture::Authenticated)
28            | Some(RoutePosture::Permission { .. })
29            | Some(RoutePosture::Owner { .. })
30            | Some(RoutePosture::Scoped { .. }) => vec![scheme],
31        },
32    }
33}
34
35/// Check a documented manifest: its spec as [`spec`] does, and its public
36/// documents. An undocumented manifest passes: its spec is today's.
37pub fn validate(manifest: &ServiceManifest) -> Result<(), OpenApiError> {
38    spec(manifest)?;
39    super::public::check(manifest)
40}
41
42/// Check what a documented manifest's spec needs: operation ids unique
43/// across its published custom and CRUD operations, no two published routes
44/// documenting the same method and path, `path = T` naming exactly the
45/// route's path parameters, query and path parameters that are scalars or
46/// arrays, security schemes the document defines, and no DTO sharing a
47/// table schema's name.
48pub(super) fn spec(manifest: &ServiceManifest) -> Result<(), OpenApiError> {
49    if matches!(default_style(manifest, ""), PathStyle::Absolute { .. }) {
50        return Ok(());
51    }
52    unique_operation_ids(manifest)?;
53    unique_operations(manifest)?;
54    let components = Map::from_iter(manifest.components.clone());
55    let lookup = Components(&components);
56    let scheme = manifest
57        .openapi
58        .as_ref()
59        .map_or(crate::OpenApiOptions::DEFAULT_SECURITY_SCHEME, |o| {
60            o.security_scheme()
61        });
62    manifest
63        .custom_routes
64        .iter()
65        .try_for_each(|route| check_route(manifest, route, &lookup, scheme))?;
66    manifest
67        .tables
68        .iter()
69        .flat_map(schema_names)
70        .chain(
71            (!manifest.tables.is_empty())
72                .then(|| "Pagination".to_string()),
73        )
74        .find(|name| manifest.components.contains_key(name))
75        .map_or(Ok(()), |name| {
76            Err(OpenApiError(format!(
77                "schema name \"{name}\" is both a table schema and a documented type; rename the type with #[schemars(rename = \"…\")]"
78            )))
79        })
80}
81
82fn unique_operation_ids(manifest: &ServiceManifest) -> Result<(), OpenApiError> {
83    let mut seen = BTreeSet::new();
84    manifest
85        .custom_routes
86        .iter()
87        .filter(|route| custom::published(route))
88        .map(|route| custom::operation_id(route).to_string())
89        .chain(manifest.tables.iter().flat_map(crud::operation_ids))
90        .find(|id| !seen.insert(id.clone()))
91        .map_or(Ok(()), |id| {
92            Err(OpenApiError(format!(
93                "operation id '{id}' is used more than once"
94            )))
95        })
96}
97
98/// A legacy route's operation is its handler's `_fn` path, so two routes of
99/// one handler and method would document one operation.
100fn unique_operations(manifest: &ServiceManifest) -> Result<(), OpenApiError> {
101    let mut seen = BTreeSet::new();
102    manifest
103        .custom_routes
104        .iter()
105        .filter(|route| custom::published(route))
106        .map(|route| {
107            (
108                route.method.to_ascii_uppercase(),
109                custom::relative_path(route, manifest.routing),
110            )
111        })
112        .find(|operation| !seen.insert(operation.clone()))
113        .map_or(Ok(()), |(method, path)| {
114            Err(OpenApiError(format!(
115                "two routes document {method} {path}; route a handler once per method"
116            )))
117        })
118}
119
120fn check_route(
121    manifest: &ServiceManifest,
122    route: &CustomRouteDefinition,
123    components: &Components<'_>,
124    scheme: &str,
125) -> Result<(), OpenApiError> {
126    let Some(doc) = &route.doc else {
127        return Ok(());
128    };
129    let name = || {
130        format!(
131            "route '{} {}' ({})",
132            route.method, route.path, route.handler
133        )
134    };
135    if let Some(path) = &doc.path_params {
136        let declared: BTreeSet<String> = custom::properties(components.resolve(path))
137            .map(|(property, _, _)| property.clone())
138            .collect();
139        let params: BTreeSet<String> = custom::path_param_names(route, manifest.routing)
140            .into_iter()
141            .collect();
142        if declared != params {
143            return Err(OpenApiError(format!(
144                "{}: path = … declares {:?} but the path has parameters {:?}",
145                name(),
146                declared,
147                params
148            )));
149        }
150    }
151    [("path", &doc.path_params), ("query", &doc.query)]
152        .into_iter()
153        .filter_map(|(location, schema)| schema.as_ref().map(|schema| (location, schema)))
154        .try_for_each(|(location, schema)| {
155            let object = components.resolve(schema);
156            if object["properties"].as_object().is_none() {
157                return Err(OpenApiError(format!(
158                    "{}: {location} = … must be a struct with named fields",
159                    name()
160                )));
161            }
162            custom::properties(object)
163                .find(|(_, property, _)| !is_parameter_schema(property, components))
164                .map_or(Ok(()), |(property, _, _)| {
165                    Err(OpenApiError(format!(
166                        "{}: {location} parameter '{property}' must be a scalar or an array",
167                        name()
168                    )))
169                })
170        })?;
171    route_security(route, scheme)
172        .into_iter()
173        .find(|security| *security != scheme && *security != API_KEY_SCHEME)
174        .map_or(Ok(()), |unknown| {
175            Err(OpenApiError(format!(
176                "{}: security scheme '{unknown}' is not defined; the document defines '{scheme}' and '{API_KEY_SCHEME}'",
177                name()
178            )))
179        })
180}
181
182/// A schema a parameter can take: scalars, arrays, enums, and their
183/// nullable forms, directly or through a `$ref`.
184fn is_parameter_schema(schema: &Value, components: &Components<'_>) -> bool {
185    let schema = components.resolve(schema);
186    let scalar = |kind: &Value| {
187        matches!(
188            kind.as_str(),
189            Some("string" | "integer" | "number" | "boolean" | "array" | "null")
190        )
191    };
192    let branches = ["anyOf", "oneOf"]
193        .iter()
194        .find_map(|key| schema[*key].as_array());
195    match (&schema["type"], branches) {
196        (Value::String(_), _) => scalar(&schema["type"]),
197        (Value::Array(kinds), _) => kinds.iter().all(scalar),
198        (_, Some(branches)) => branches
199            .iter()
200            .all(|branch| is_parameter_schema(branch, components)),
201        _ => schema.get("enum").is_some() || schema.get("const").is_some(),
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use crate::{OpenApiOptions, RouteDoc, RoutingMode};
209    use serde_json::json;
210
211    fn documented(routes: Vec<CustomRouteDefinition>) -> ServiceManifest {
212        ServiceManifest {
213            name: "notes".into(),
214            routing: RoutingMode::Strict,
215            openapi: Some(OpenApiOptions::default()),
216            custom_routes: routes,
217            ..Default::default()
218        }
219    }
220
221    fn route(method: &str, path: &str, handler: &str, doc: RouteDoc) -> CustomRouteDefinition {
222        CustomRouteDefinition {
223            method: method.into(),
224            path: path.into(),
225            handler: handler.into(),
226            posture: Some(RoutePosture::Authenticated),
227            doc: Some(doc),
228            ..Default::default()
229        }
230    }
231
232    #[test]
233    fn undocumented_manifests_are_not_checked() {
234        let mut legacy = documented(vec![
235            route("GET", "/a", "same", RouteDoc::default()),
236            route("POST", "/a", "same", RouteDoc::default()),
237        ]);
238        assert!(validate(&legacy).is_err());
239        legacy.openapi = None;
240        legacy.custom_routes.iter_mut().for_each(|r| r.doc = None);
241        assert!(validate(&legacy).is_ok());
242    }
243
244    #[test]
245    fn operation_ids_are_unique_across_routes_and_crud() {
246        let m = documented(vec![
247            route("GET", "/a", "one", RouteDoc::default()),
248            route(
249                "GET",
250                "/b",
251                "two",
252                RouteDoc {
253                    operation_id: Some("one".into()),
254                    ..Default::default()
255                },
256            ),
257        ]);
258        assert_eq!(
259            validate(&m),
260            Err(OpenApiError(
261                "operation id 'one' is used more than once".into()
262            ))
263        );
264    }
265
266    #[test]
267    fn internal_routes_are_not_published_so_share_no_operation_id() {
268        let mut internal = route("POST", "/sync", "one", RouteDoc::default());
269        internal.posture = Some(RoutePosture::Internal {
270            callers: vec!["*".into()],
271        });
272        let m = documented(vec![
273            route("GET", "/a", "one", RouteDoc::default()),
274            internal,
275        ]);
276        assert_eq!(validate(&m), Ok(()));
277    }
278
279    #[test]
280    fn a_legacy_handler_documents_one_operation_per_method() {
281        let named = |id: &str| RouteDoc {
282            operation_id: Some(id.into()),
283            ..Default::default()
284        };
285        let mut m = documented(vec![
286            route("POST", "/a", "same", named("first")),
287            route("POST", "/b", "same", named("second")),
288        ]);
289        m.routing = RoutingMode::Legacy;
290        assert_eq!(
291            validate(&m),
292            Err(OpenApiError(
293                "two routes document POST /_fn/same; route a handler once per method".into()
294            ))
295        );
296        m.custom_routes[1].method = "GET".into();
297        assert_eq!(validate(&m), Ok(()));
298    }
299
300    #[test]
301    fn path_structs_name_exactly_the_path_parameters() {
302        let path_doc = |properties: Value| RouteDoc {
303            path_params: Some(
304                json!({"type": "object", "properties": properties, "required": ["note_id"]}),
305            ),
306            ..Default::default()
307        };
308        let ok = documented(vec![route(
309            "GET",
310            "/notes/{note_id}",
311            "get_note",
312            path_doc(json!({"note_id": {"type": "string"}})),
313        )]);
314        assert!(validate(&ok).is_ok());
315        let missing = documented(vec![route(
316            "GET",
317            "/notes/{note_id}/{rev}",
318            "get_note",
319            path_doc(json!({"note_id": {"type": "string"}})),
320        )]);
321        let err = validate(&missing).unwrap_err().to_string();
322        assert!(
323            err.contains("path has parameters {\"note_id\", \"rev\"}"),
324            "{err}"
325        );
326    }
327
328    #[test]
329    fn parameters_are_scalars_or_arrays() {
330        let query = |property: Value| RouteDoc {
331            query: Some(json!({"type": "object", "properties": {"q": property}})),
332            ..Default::default()
333        };
334        let mut m = documented(vec![]);
335        m.components
336            .insert("Kind".into(), json!({"type": "string", "enum": ["a", "b"]}));
337        for property in [
338            json!({"type": ["integer", "null"], "format": "int32"}),
339            json!({"type": "array", "items": {"type": "string"}}),
340            json!({"$ref": "#/components/schemas/Kind"}),
341            json!({"anyOf": [{"$ref": "#/components/schemas/Kind"}, {"type": "null"}]}),
342            json!({"enum": ["x"]}),
343        ] {
344            m.custom_routes = vec![route("GET", "/s", "search", query(property.clone()))];
345            assert!(validate(&m).is_ok(), "{property}");
346        }
347        m.custom_routes = vec![route(
348            "GET",
349            "/s",
350            "search",
351            query(json!({"type": "object", "properties": {}})),
352        )];
353        let err = validate(&m).unwrap_err().to_string();
354        assert!(
355            err.contains("query parameter 'q' must be a scalar or an array"),
356            "{err}"
357        );
358        m.custom_routes = vec![route(
359            "GET",
360            "/s",
361            "search",
362            RouteDoc {
363                query: Some(json!({"type": "string"})),
364                ..Default::default()
365            },
366        )];
367        assert!(validate(&m).is_err());
368    }
369
370    #[test]
371    fn security_names_a_defined_scheme() {
372        let m = documented(vec![route(
373            "GET",
374            "/a",
375            "a",
376            RouteDoc {
377                security: Some(vec!["oauth".into()]),
378                ..Default::default()
379            },
380        )]);
381        let err = validate(&m).unwrap_err().to_string();
382        assert!(
383            err.contains("security scheme 'oauth' is not defined"),
384            "{err}"
385        );
386    }
387
388    #[test]
389    fn a_documented_type_may_share_a_private_tables_schema_name() {
390        let notes: crate::TableDefinition = serde_json::from_value(json!({
391            "name": "note", "managed": false,
392            "columns": [{"name": "id", "column_type": "uuid", "primary_key": true}]
393        }))
394        .expect("table");
395        let typed = |tables: Vec<crate::TableDefinition>, private_tables| ServiceManifest {
396            tables,
397            private_tables,
398            components: [("Note".to_string(), json!({"type": "object"}))].into(),
399            ..documented(vec![route("GET", "/notes", "notes", RouteDoc::default())])
400        };
401        assert_eq!(validate(&typed(vec![], vec![notes.clone()])), Ok(()));
402        assert_eq!(
403            validate(&typed(vec![notes], vec![])),
404            Err(OpenApiError(
405                "schema name \"Note\" is both a table schema and a documented type; rename the type with #[schemars(rename = \"…\")]".into()
406            ))
407        );
408    }
409}