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