Skip to main content

cufflink_types/openapi/
mod.rs

1//! OpenAPI spec generation from a [`ServiceManifest`].
2//!
3//! This module is used by both the platform (server-side) and the CLI
4//! (local generation without deployment).
5
6mod check;
7mod crud;
8mod custom;
9mod public;
10mod schema;
11
12pub use check::validate;
13pub use public::{mount_segments, public_doc, public_doc_spec, PublicDocError};
14
15use crate::{ServerDoc, ServiceManifest, TableDefinition};
16use custom::Components;
17use schema::Nullable;
18use serde_json::{json, Map, Value};
19use std::fmt;
20
21/// Where a spec's paths are rooted.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum PathStyle<'a> {
24    /// Full `/svc/{tenant}/{service}/…` paths: the spec of an undocumented
25    /// service, unchanged.
26    Absolute { tenant: &'a str },
27    /// Paths relative to the `servers`, which default to the service's own
28    /// base under `tenant`: what a client generator needs.
29    ServerRelative { tenant: &'a str },
30}
31
32/// Server-relative once the service documents itself (`openapi` options or
33/// any route `doc`), absolute otherwise.
34pub fn default_style<'a>(manifest: &ServiceManifest, tenant: &'a str) -> PathStyle<'a> {
35    let documented = manifest.openapi.is_some()
36        || manifest
37            .custom_routes
38            .iter()
39            .any(|route| route.doc.is_some());
40    if documented {
41        PathStyle::ServerRelative { tenant }
42    } else {
43        PathStyle::Absolute { tenant }
44    }
45}
46
47/// A manifest whose docs cannot form a spec.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct OpenApiError(pub String);
50
51impl fmt::Display for OpenApiError {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        f.write_str(&self.0)
54    }
55}
56
57impl std::error::Error for OpenApiError {}
58
59/// The service's OpenAPI 3.1 document.
60pub fn generate_openapi(
61    manifest: &ServiceManifest,
62    style: PathStyle<'_>,
63) -> Result<Value, OpenApiError> {
64    match style {
65        PathStyle::Absolute { tenant } => Ok(absolute(manifest, tenant)),
66        PathStyle::ServerRelative { tenant } => server_relative(manifest, tenant),
67    }
68}
69
70/// The spec a deployed or local service is served with: in its
71/// [`default_style`].
72pub fn service_spec(manifest: &ServiceManifest, tenant: &str) -> Result<Value, OpenApiError> {
73    generate_openapi(manifest, default_style(manifest, tenant))
74}
75
76fn insert_operations(
77    paths: &mut Map<String, Value>,
78    operations: impl IntoIterator<Item = (String, String, Value)>,
79) {
80    for (path, method, operation) in operations {
81        if let Some(obj) = paths
82            .entry(path)
83            .or_insert_with(|| json!({}))
84            .as_object_mut()
85        {
86            obj.insert(method, operation);
87        }
88    }
89}
90
91fn absolute(manifest: &ServiceManifest, tenant_slug: &str) -> Value {
92    let mut paths: Map<String, Value> = manifest
93        .tables
94        .iter()
95        .flat_map(|table| {
96            let base = format!("/svc/{}/{}/{}", tenant_slug, manifest.name, table.name);
97            crud::table_paths(base.clone(), format!("{base}/:id"), table)
98        })
99        .collect();
100    insert_operations(
101        &mut paths,
102        manifest
103            .custom_routes
104            .iter()
105            .filter(|route| custom::published(route))
106            .map(|route| custom::route_operation(tenant_slug, &manifest.name, route)),
107    );
108    let schemas: Map<String, Value> = manifest
109        .tables
110        .iter()
111        .flat_map(|table| schema::table_schemas(table, Nullable::Flag))
112        .chain(std::iter::once(("Pagination".into(), schema::pagination())))
113        .collect();
114
115    json!({
116        "openapi": "3.1.0",
117        "info": {
118            "title": manifest.name,
119            "version": manifest.version.as_deref().unwrap_or("0.1.0")
120        },
121        "paths": Value::Object(paths),
122        "components": {
123            "schemas": Value::Object(schemas)
124        }
125    })
126}
127
128/// The schemes a CRUD table's operations require.
129fn table_security(table: &TableDefinition, scheme: &str) -> Vec<Value> {
130    if table.auth_required {
131        vec![json!({ scheme: [] })]
132    } else {
133        Vec::new()
134    }
135}
136
137/// The first non-empty list of `chain`, else the service's own base under
138/// `tenant`.
139fn servers_of(chain: &[&[ServerDoc]], service: &str, tenant: &str) -> Value {
140    chain
141        .iter()
142        .find(|servers| !servers.is_empty())
143        .map_or_else(
144            || {
145                json!([{
146                    "url": format!("{{origin}}/svc/{{tenant}}/{service}"),
147                    "variables": {
148                        "origin": { "default": "" },
149                        "tenant": { "default": tenant },
150                    },
151                }])
152            },
153            |servers| json!(servers),
154        )
155}
156
157fn server_relative(manifest: &ServiceManifest, tenant: &str) -> Result<Value, OpenApiError> {
158    check::spec(manifest)?;
159    let options = manifest.openapi.clone().unwrap_or_default();
160    let scheme = options.security_scheme();
161    let components = Map::from_iter(manifest.components.clone());
162    let lookup = Components(&components);
163
164    let custom: Vec<(String, String, Value)> = manifest
165        .custom_routes
166        .iter()
167        .filter(|route| custom::published(route))
168        .map(|route| {
169            let security = check::route_security(route, scheme);
170            custom::relative_operation(manifest, route, &security, &lookup)
171        })
172        .collect();
173    let crud = manifest.tables.iter().flat_map(|table| {
174        let security = table_security(table, scheme);
175        crud::table_paths(
176            format!("/{}", table.name),
177            format!("/{}/{{id}}", table.name),
178            table,
179        )
180        .into_iter()
181        .map(move |(path, operations)| (path, with_security(operations, &security)))
182    });
183    let mut paths: Map<String, Value> = crud.collect();
184    insert_operations(&mut paths, custom);
185
186    let uses = |name: &str| {
187        paths.values().any(|operations| {
188            operations
189                .as_object()
190                .into_iter()
191                .flatten()
192                .any(|(_, operation)| {
193                    operation["security"]
194                        .as_array()
195                        .is_some_and(|requirements| {
196                            requirements.iter().any(|r| r.get(name).is_some())
197                        })
198                })
199        })
200    };
201    let security_schemes: Map<String, Value> = [
202        uses(scheme).then(|| {
203            (
204                scheme.to_string(),
205                json!({ "type": "http", "scheme": "bearer" }),
206            )
207        }),
208        uses(check::API_KEY_SCHEME).then(|| {
209            (
210                check::API_KEY_SCHEME.to_string(),
211                json!({ "type": "apiKey", "in": "header", "name": "X-Api-Key" }),
212            )
213        }),
214    ]
215    .into_iter()
216    .flatten()
217    .collect();
218    let schemas: Map<String, Value> = manifest
219        .tables
220        .iter()
221        .flat_map(|table| schema::table_schemas(table, Nullable::TypeUnion))
222        .chain(
223            (!manifest.tables.is_empty()).then(|| ("Pagination".to_string(), schema::pagination())),
224        )
225        .chain(components)
226        .collect();
227    let mut component_map = Map::from_iter([("schemas".to_string(), Value::Object(schemas))]);
228    if !security_schemes.is_empty() {
229        component_map.insert("securitySchemes".into(), Value::Object(security_schemes));
230    }
231
232    let mut info = Map::from_iter([
233        (
234            "title".to_string(),
235            json!(options.title.as_deref().unwrap_or(&manifest.name)),
236        ),
237        (
238            "version".to_string(),
239            json!(options
240                .version
241                .as_deref()
242                .or(manifest.version.as_deref())
243                .unwrap_or("0.1.0")),
244        ),
245    ]);
246    if let Some(description) = &options.description {
247        info.insert("description".into(), json!(description));
248    }
249    let servers = servers_of(&[&options.servers], &manifest.name, tenant);
250    let mut document = Map::from_iter([
251        ("openapi".to_string(), json!("3.1.0")),
252        ("info".to_string(), Value::Object(info)),
253        ("servers".to_string(), servers),
254        ("paths".to_string(), Value::Object(paths)),
255        ("components".to_string(), Value::Object(component_map)),
256    ]);
257    if !options.tags.is_empty() {
258        document.insert("tags".into(), json!(options.tags));
259    }
260    Ok(Value::Object(document))
261}
262
263/// Each operation of a path item with `security`, when there is any.
264fn with_security(mut operations: Value, security: &[Value]) -> Value {
265    if !security.is_empty() {
266        operations
267            .as_object_mut()
268            .into_iter()
269            .flat_map(|operations| operations.values_mut())
270            .filter_map(Value::as_object_mut)
271            .for_each(|operation| {
272                operation.insert("security".into(), json!(security));
273            });
274    }
275    operations
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281    use crate::{
282        ColumnDefinition, ColumnType, CustomRouteDefinition, ServiceManifest, ServiceMode,
283        TableDefinition,
284    };
285
286    fn test_manifest() -> ServiceManifest {
287        ServiceManifest {
288            name: "test-service".into(),
289            version: Some("1.0.0".into()),
290            tables: vec![TableDefinition {
291                name: "todos".into(),
292                columns: vec![
293                    ColumnDefinition {
294                        name: "id".into(),
295                        column_type: ColumnType::Uuid,
296                        primary_key: true,
297                        nullable: false,
298                        auto_generate: true,
299                        default_value: None,
300                        references: None,
301                        on_delete: None,
302                        unique: false,
303                        validations: vec![],
304                        ..Default::default()
305                    },
306                    ColumnDefinition {
307                        name: "title".into(),
308                        column_type: ColumnType::Text,
309                        primary_key: false,
310                        nullable: false,
311                        auto_generate: false,
312                        default_value: None,
313                        references: None,
314                        on_delete: None,
315                        unique: false,
316                        validations: vec![],
317                        ..Default::default()
318                    },
319                    ColumnDefinition {
320                        name: "done".into(),
321                        column_type: ColumnType::Boolean,
322                        primary_key: false,
323                        nullable: false,
324                        auto_generate: false,
325                        default_value: Some("false".into()),
326                        references: None,
327                        on_delete: None,
328                        unique: false,
329                        validations: vec![],
330                        ..Default::default()
331                    },
332                ],
333                indexes: vec![],
334                soft_delete: false,
335                owner_field: None,
336                auth_required: false,
337                permission_area: None,
338                owner_self_service: false,
339                hooks: None,
340                scoped_by: None,
341                ..Default::default()
342            }],
343            cells: vec![],
344            events: vec![],
345            subscriptions: vec![],
346            custom_routes: vec![],
347            mode: ServiceMode::Crud,
348            authorization: None,
349            on_migrate: None,
350            publishes: None,
351            required_platform_features: vec![],
352            graphql: false,
353            ..Default::default()
354        }
355    }
356
357    #[test]
358    fn test_generates_valid_openapi() {
359        let manifest = test_manifest();
360        let spec = generate_openapi(
361            &manifest,
362            PathStyle::Absolute {
363                tenant: "test-tenant",
364            },
365        )
366        .expect("spec");
367
368        assert_eq!(spec["openapi"], "3.1.0");
369        assert_eq!(spec["info"]["title"], "test-service");
370        assert_eq!(spec["info"]["version"], "1.0.0");
371    }
372
373    #[test]
374    fn test_generates_crud_paths() {
375        let manifest = test_manifest();
376        let spec =
377            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
378
379        let paths = spec["paths"].as_object().unwrap();
380        assert!(paths.contains_key("/svc/acme/test-service/todos"));
381        assert!(paths.contains_key("/svc/acme/test-service/todos/:id"));
382    }
383
384    #[test]
385    fn test_generates_schemas() {
386        let manifest = test_manifest();
387        let spec =
388            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
389
390        let schemas = spec["components"]["schemas"].as_object().unwrap();
391        assert!(schemas.contains_key("Todos"));
392        assert!(schemas.contains_key("TodosCreate"));
393        assert!(schemas.contains_key("Pagination"));
394    }
395
396    #[test]
397    fn a_restricted_column_carries_its_permissions_and_is_not_required_of_a_response() {
398        let mut manifest = test_manifest();
399        let todos = &mut manifest.tables[0];
400        todos.permission_area = Some("todos".into());
401        todos.columns[1].access = Some(crate::ColumnAccess {
402            read: Some("internal".into()),
403            write: None,
404        });
405        todos.columns[2].access = Some(crate::ColumnAccess {
406            read: None,
407            write: Some("manage".into()),
408        });
409        let spec =
410            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
411        let schemas = &spec["components"]["schemas"];
412        for schema in ["Todos", "TodosCreate"] {
413            let properties = &schemas[schema]["properties"];
414            assert_eq!(
415                properties["title"]["x-cufflink-access"],
416                serde_json::json!({"read": "todos:internal"}),
417                "{schema}"
418            );
419            assert_eq!(
420                properties["done"]["x-cufflink-access"],
421                serde_json::json!({"write": "todos:manage"}),
422                "{schema}"
423            );
424        }
425        assert_eq!(
426            schemas["Todos"]["required"],
427            serde_json::json!(["id", "done"])
428        );
429        assert_eq!(
430            schemas["TodosCreate"]["required"],
431            serde_json::json!(["title"])
432        );
433        let plain = generate_openapi(&test_manifest(), PathStyle::Absolute { tenant: "acme" })
434            .expect("spec");
435        assert_eq!(
436            plain["components"]["schemas"]["Todos"]["required"],
437            serde_json::json!(["id", "title", "done"])
438        );
439        assert!(!plain.to_string().contains("x-cufflink-access"));
440    }
441
442    #[test]
443    fn rows_require_every_column_and_bodies_follow_the_platform() {
444        let mut manifest = test_manifest();
445        let table = &mut manifest.tables[0];
446        table.owner_field = Some("owner_id".into());
447        table.columns.push(ColumnDefinition {
448            name: "owner_id".into(),
449            column_type: ColumnType::Uuid,
450            ..Default::default()
451        });
452        table.columns.push(ColumnDefinition {
453            name: "notes".into(),
454            column_type: ColumnType::Jsonb,
455            nullable: true,
456            ..Default::default()
457        });
458        let spec = generate_openapi(&manifest, PathStyle::ServerRelative { tenant: "acme" })
459            .expect("spec");
460        let schemas = &spec["components"]["schemas"];
461        assert_eq!(
462            schemas["Todos"]["required"],
463            serde_json::json!(["id", "title", "done", "owner_id", "notes"])
464        );
465        assert_eq!(
466            schemas["Todos"]["properties"]["notes"],
467            serde_json::json!({})
468        );
469        assert_eq!(
470            schemas["TodosCreate"]["required"],
471            serde_json::json!(["title"])
472        );
473        assert_eq!(schemas["TodosUpdate"]["required"], serde_json::json!([]));
474        assert!(schemas["TodosUpdate"]["properties"].get("id").is_none());
475        let put = spec["paths"]
476            .as_object()
477            .unwrap()
478            .iter()
479            .find_map(|(_, item)| item.get("put"));
480        assert_eq!(
481            put.expect("put")["requestBody"]["content"]["application/json"]["schema"]["$ref"],
482            "#/components/schemas/TodosUpdate"
483        );
484    }
485
486    #[test]
487    fn test_create_schema_excludes_auto_generated() {
488        let manifest = test_manifest();
489        let spec =
490            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
491
492        let create_props = spec["components"]["schemas"]["TodosCreate"]["properties"]
493            .as_object()
494            .unwrap();
495        assert!(!create_props.contains_key("id"));
496        assert!(create_props.contains_key("title"));
497    }
498
499    #[test]
500    fn test_custom_routes() {
501        let mut manifest = test_manifest();
502        manifest.custom_routes.push(CustomRouteDefinition {
503            method: "POST".into(),
504            path: "/complete/:id".into(),
505            handler: "complete_todo".into(),
506            job: None,
507            posture: None,
508            forward_auth: false,
509            ..Default::default()
510        });
511
512        let spec =
513            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
514        let paths = spec["paths"].as_object().unwrap();
515        assert!(paths.contains_key("/svc/acme/test-service/_fn/complete_todo"));
516    }
517
518    #[test]
519    fn test_default_version() {
520        let mut manifest = test_manifest();
521        manifest.version = None;
522        let spec =
523            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
524        assert_eq!(spec["info"]["version"], "0.1.0");
525    }
526
527    #[test]
528    fn output_matches_the_golden_specs() {
529        for (manifest, golden) in [
530            (
531                include_str!("../../fixtures/sample_manifest.json"),
532                include_str!("../../fixtures/openapi/sample.json"),
533            ),
534            (
535                include_str!("../../fixtures/todo_manifest.json"),
536                include_str!("../../fixtures/openapi/todo.json"),
537            ),
538            (
539                include_str!("../../fixtures/blog_manifest.json"),
540                include_str!("../../fixtures/openapi/blog.json"),
541            ),
542        ] {
543            let manifest: ServiceManifest = serde_json::from_str(manifest).expect("manifest");
544            let golden: Value = serde_json::from_str(golden).expect("golden");
545            assert_eq!(
546                generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec"),
547                golden,
548                "{}",
549                manifest.name
550            );
551        }
552    }
553
554    #[test]
555    fn test_local_slug() {
556        let manifest = test_manifest();
557        let spec =
558            generate_openapi(&manifest, PathStyle::Absolute { tenant: "local" }).expect("spec");
559
560        let paths = spec["paths"].as_object().unwrap();
561        assert!(paths.contains_key("/svc/local/test-service/todos"));
562    }
563
564    fn documented_route(
565        method: &str,
566        path: &str,
567        handler: &str,
568        posture: Option<crate::RoutePosture>,
569        doc: crate::RouteDoc,
570    ) -> CustomRouteDefinition {
571        CustomRouteDefinition {
572            method: method.into(),
573            path: path.into(),
574            handler: handler.into(),
575            posture,
576            doc: Some(doc),
577            ..Default::default()
578        }
579    }
580
581    fn relative(manifest: &ServiceManifest) -> Value {
582        generate_openapi(manifest, PathStyle::ServerRelative { tenant: "acme" }).expect("spec")
583    }
584
585    #[test]
586    fn documented_services_default_to_server_relative_paths() {
587        let mut manifest = test_manifest();
588        assert_eq!(
589            default_style(&manifest, "acme"),
590            PathStyle::Absolute { tenant: "acme" }
591        );
592        manifest.custom_routes.push(documented_route(
593            "GET",
594            "/x",
595            "x",
596            None,
597            crate::RouteDoc::default(),
598        ));
599        assert_eq!(
600            default_style(&manifest, "acme"),
601            PathStyle::ServerRelative { tenant: "acme" }
602        );
603    }
604
605    #[test]
606    fn server_relative_specs_default_their_server_and_use_3_1_nullability() {
607        let mut manifest = test_manifest();
608        manifest.tables[0].columns[1].nullable = true;
609        manifest.openapi = Some(crate::OpenApiOptions::default());
610        let spec = relative(&manifest);
611        assert_eq!(
612            spec["servers"],
613            json!([{"url": "{origin}/svc/{tenant}/test-service",
614                "variables": {"origin": {"default": ""}, "tenant": {"default": "acme"}}}])
615        );
616        let paths = spec["paths"].as_object().expect("paths");
617        assert!(paths.contains_key("/todos") && paths.contains_key("/todos/{id}"));
618        assert_eq!(
619            spec["components"]["schemas"]["Todos"]["properties"]["title"],
620            json!({"type": ["string", "null"]})
621        );
622        assert!(spec.get("tags").is_none());
623        assert!(spec["components"].get("securitySchemes").is_none());
624
625        manifest.openapi = Some(crate::OpenApiOptions {
626            title: Some("Loans".into()),
627            version: Some("2.0.0".into()),
628            description: Some(String::new()),
629            servers: vec![crate::ServerDoc {
630                url: "https://api.example.com/api".into(),
631                description: Some("Production".into()),
632            }],
633            tags: vec![crate::TagDoc {
634                name: "Loans Service".into(),
635                description: Some("Loans Service API".into()),
636            }],
637            security_scheme: None,
638            docs: vec![],
639        });
640        let spec = relative(&manifest);
641        assert_eq!(
642            spec["info"],
643            json!({"title": "Loans", "version": "2.0.0", "description": ""})
644        );
645        assert_eq!(
646            spec["servers"],
647            json!([{"url": "https://api.example.com/api", "description": "Production"}])
648        );
649        assert_eq!(
650            spec["tags"],
651            json!([{"name": "Loans Service", "description": "Loans Service API"}])
652        );
653    }
654
655    #[test]
656    fn documented_routes_carry_parameters_bodies_responses_and_security() {
657        use crate::{BodyDoc, MediaDoc, ResponseDoc, RouteDoc, RoutePosture, RoutingMode};
658        let mut manifest = test_manifest();
659        manifest.tables.clear();
660        manifest.routing = RoutingMode::Strict;
661        manifest.components.insert(
662            "ApiLoan".into(),
663            json!({"type": "object", "properties": {"id": {"type": "string"}}}),
664        );
665        let doc = RouteDoc {
666            tags: vec!["loan".into()],
667            summary: Some("Update a loan".into()),
668            deprecated: true,
669            path_params: Some(json!({"type": "object", "required": ["loan_id"],
670                "properties": {"loan_id": {"type": "string", "description": "Loan identifier"}}})),
671            query: Some(
672                json!({"type": "object", "required": ["force"], "properties": {
673                "force": {"type": "boolean"}, "page": {"type": ["integer", "null"], "format": "int32"}}}),
674            ),
675            request: Some(BodyDoc {
676                content_type: "application/json".into(),
677                schema: Some(json!({"$ref": "#/components/schemas/ApiLoan"})),
678                required: true,
679            }),
680            responses: [
681                (
682                    200,
683                    ResponseDoc {
684                        description: "Updated".into(),
685                        content: vec![MediaDoc {
686                            content_type: "application/json".into(),
687                            schema: Some(json!({"$ref": "#/components/schemas/ApiLoan"})),
688                        }],
689                    },
690                ),
691                (
692                    403,
693                    ResponseDoc {
694                        description: "Forbidden".into(),
695                        content: vec![],
696                    },
697                ),
698            ]
699            .into(),
700            ..Default::default()
701        };
702        manifest.custom_routes = vec![
703            documented_route(
704                "PUT",
705                "/loans/{loan_id}",
706                "update_loan",
707                Some(RoutePosture::Permission {
708                    area: "loans".into(),
709                    operation: "edit".into(),
710                }),
711                doc,
712            ),
713            documented_route(
714                "GET",
715                "/loans/{loan_id}/pdf",
716                "loan_pdf",
717                Some(RoutePosture::Public {
718                    reason: "shared link".into(),
719                }),
720                RouteDoc {
721                    responses: [(
722                        200,
723                        ResponseDoc {
724                            description: "PDF".into(),
725                            content: vec![MediaDoc {
726                                content_type: "application/pdf".into(),
727                                schema: None,
728                            }],
729                        },
730                    )]
731                    .into(),
732                    ..Default::default()
733                },
734            ),
735        ];
736        let spec = relative(&manifest);
737        let update = &spec["paths"]["/loans/{loan_id}"]["put"];
738        assert_eq!(update["operationId"], "update_loan");
739        assert_eq!(update["tags"], json!(["loan"]));
740        assert_eq!(update["summary"], "Update a loan");
741        assert_eq!(update["deprecated"], true);
742        assert_eq!(
743            update["parameters"],
744            json!([
745                {"name": "loan_id", "in": "path", "required": true, "schema": {"type": "string"},
746                    "description": "Loan identifier"},
747                {"name": "force", "in": "query", "required": true, "schema": {"type": "boolean"}},
748                {"name": "page", "in": "query", "required": false,
749                    "schema": {"type": ["integer", "null"], "format": "int32"}},
750            ])
751        );
752        assert_eq!(
753            update["requestBody"],
754            json!({"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiLoan"}}}, "required": true})
755        );
756        assert_eq!(
757            update["responses"]["403"],
758            json!({"description": "Forbidden"})
759        );
760        assert_eq!(update["security"], json!([{"bearer_auth": []}]));
761
762        let pdf = &spec["paths"]["/loans/{loan_id}/pdf"]["get"];
763        assert_eq!(pdf["tags"], json!(["test-service"]));
764        assert_eq!(pdf["parameters"][0]["schema"], json!({"type": "string"}));
765        assert_eq!(
766            pdf["responses"]["200"],
767            json!({"description": "PDF", "content": {"application/pdf": {}}})
768        );
769        assert!(
770            pdf.get("security").is_none(),
771            "public routes need no credentials"
772        );
773        assert!(pdf.get("requestBody").is_none());
774        assert_eq!(
775            spec["components"]["securitySchemes"],
776            json!({"bearer_auth": {"type": "http", "scheme": "bearer"}})
777        );
778        assert_eq!(spec["components"]["schemas"]["ApiLoan"]["type"], "object");
779    }
780
781    #[test]
782    fn a_parameters_examples_move_from_its_schema_to_the_parameter() {
783        use crate::{RouteDoc, RoutingMode};
784        let mut manifest = test_manifest();
785        manifest.tables.clear();
786        manifest.routing = RoutingMode::Strict;
787        manifest.custom_routes = vec![documented_route(
788            "GET",
789            "/products/{sku}",
790            "product",
791            None,
792            RouteDoc {
793                path_params: Some(
794                    json!({"type": "object", "required": ["sku"], "properties": {
795                    "sku": {"type": "string", "examples": ["SKU-1"]}}}),
796                ),
797                query: Some(json!({"type": "object", "properties": {
798                    "currency": {"type": "string", "examples": ["EUR", "USD"]},
799                    "page": {"type": "integer", "examples": []},
800                    "size": {"type": "integer", "description": "Per page"}}})),
801                ..Default::default()
802            },
803        )];
804        let spec = relative(&manifest);
805        assert_eq!(
806            spec["paths"]["/products/{sku}"]["get"]["parameters"],
807            json!([
808                {"name": "sku", "in": "path", "required": true, "schema": {"type": "string"},
809                    "example": "SKU-1"},
810                {"name": "currency", "in": "query", "required": false, "schema": {"type": "string"},
811                    "examples": {"0": {"value": "EUR"}, "1": {"value": "USD"}}},
812                {"name": "page", "in": "query", "required": false,
813                    "schema": {"type": "integer", "examples": []}},
814                {"name": "size", "in": "query", "required": false, "schema": {"type": "integer"},
815                    "description": "Per page"},
816            ])
817        );
818    }
819
820    #[test]
821    fn legacy_routes_of_a_documented_service_use_their_fn_alias() {
822        let mut manifest = test_manifest();
823        manifest.custom_routes.push(CustomRouteDefinition {
824            method: "POST".into(),
825            path: "/complete/:id".into(),
826            handler: "complete_todo".into(),
827            posture: Some(crate::RoutePosture::Authenticated),
828            ..Default::default()
829        });
830        manifest.openapi = Some(crate::OpenApiOptions::default());
831        let spec = relative(&manifest);
832        let operation = &spec["paths"]["/_fn/complete_todo"]["post"];
833        assert_eq!(operation["operationId"], "complete_todo");
834        assert_eq!(operation["requestBody"]["required"], false);
835        assert_eq!(operation["responses"]["200"]["description"], "Success");
836        assert_eq!(
837            spec["paths"]["/todos"]["get"]["operationId"], "list_todos",
838            "CRUD operations are server-relative too"
839        );
840    }
841
842    #[test]
843    fn internal_routes_are_left_out_of_both_specs() {
844        let mut manifest = test_manifest();
845        manifest.custom_routes.push(CustomRouteDefinition {
846            method: "POST".into(),
847            path: "/reprice".into(),
848            handler: "reprice".into(),
849            posture: Some(crate::RoutePosture::Internal {
850                callers: vec!["pricing".into()],
851            }),
852            ..Default::default()
853        });
854        let absolute =
855            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
856        assert!(absolute["paths"]
857            .get("/svc/acme/test-service/_fn/reprice")
858            .is_none());
859        manifest.openapi = Some(crate::OpenApiOptions::default());
860        assert!(relative(&manifest)["paths"].get("/_fn/reprice").is_none());
861    }
862
863    #[test]
864    fn api_key_routes_require_the_api_key_scheme() {
865        let mut manifest = test_manifest();
866        manifest.openapi = Some(crate::OpenApiOptions::default());
867        manifest.custom_routes.push(CustomRouteDefinition {
868            method: "POST".into(),
869            path: "/ingest".into(),
870            handler: "ingest_book".into(),
871            posture: Some(crate::RoutePosture::ApiKey {
872                scope: "books:ingest".into(),
873            }),
874            ..Default::default()
875        });
876        let spec = relative(&manifest);
877        assert_eq!(
878            spec["paths"]["/_fn/ingest_book"]["post"]["security"],
879            json!([{"api_key": []}])
880        );
881        assert_eq!(
882            spec["components"]["securitySchemes"],
883            json!({"api_key": {"type": "apiKey", "in": "header", "name": "X-Api-Key"}})
884        );
885    }
886
887    #[test]
888    fn a_crud_operation_id_clash_is_a_generation_error() {
889        let mut manifest = test_manifest();
890        manifest.custom_routes.push(documented_route(
891            "GET",
892            "/x",
893            "list_todos",
894            None,
895            crate::RouteDoc::default(),
896        ));
897        assert_eq!(
898            generate_openapi(&manifest, PathStyle::ServerRelative { tenant: "acme" }),
899            Err(OpenApiError(
900                "operation id 'list_todos' is used more than once".into()
901            ))
902        );
903        assert!(
904            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).is_ok(),
905            "the absolute spec is today's and never refused"
906        );
907    }
908
909    fn private_loans() -> crate::TableDefinition {
910        serde_json::from_value(json!({
911            "name": "loans", "managed": false,
912            "columns": [{"name": "id", "column_type": "uuid", "primary_key": true}]
913        }))
914        .expect("table")
915    }
916
917    #[test]
918    fn a_private_table_has_no_paths_schemas_or_operation_ids() {
919        let served = test_manifest();
920        let mut manifest = served.clone();
921        manifest.private_tables = vec![private_loans()];
922        manifest.custom_routes.push(documented_route(
923            "GET",
924            "/loans",
925            "list_loans",
926            None,
927            crate::RouteDoc::default(),
928        ));
929        for style in [
930            PathStyle::Absolute { tenant: "acme" },
931            PathStyle::ServerRelative { tenant: "acme" },
932        ] {
933            let spec = generate_openapi(&manifest, style).expect("list_loans is the route's alone");
934            let text = spec.to_string();
935            for absent in [
936                "\"Loans\"",
937                "LoansCreate",
938                "create_loan",
939                "/loans/{id}",
940                "/loans/:id",
941            ] {
942                assert!(!text.contains(absent), "{absent} in {text}");
943            }
944            let mut without = manifest.clone();
945            without.private_tables.clear();
946            assert_eq!(spec, generate_openapi(&without, style).expect("spec"));
947        }
948
949        let only_private = ServiceManifest {
950            tables: vec![],
951            ..manifest.clone()
952        };
953        let undeclared = ServiceManifest {
954            private_tables: vec![],
955            ..only_private.clone()
956        };
957        for style in [
958            PathStyle::Absolute { tenant: "acme" },
959            PathStyle::ServerRelative { tenant: "acme" },
960        ] {
961            assert_eq!(
962                generate_openapi(&only_private, style),
963                generate_openapi(&undeclared, style)
964            );
965        }
966    }
967}