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        // "id" is auto_generate=true, should be excluded from create schema
440        assert!(!create_props.contains_key("id"));
441        assert!(create_props.contains_key("title"));
442    }
443
444    #[test]
445    fn test_custom_routes() {
446        let mut manifest = test_manifest();
447        manifest.custom_routes.push(CustomRouteDefinition {
448            method: "POST".into(),
449            path: "/complete/:id".into(),
450            handler: "complete_todo".into(),
451            job: None,
452            posture: None,
453            forward_auth: false,
454            ..Default::default()
455        });
456
457        let spec =
458            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
459        let paths = spec["paths"].as_object().unwrap();
460        assert!(paths.contains_key("/svc/acme/test-service/_fn/complete_todo"));
461    }
462
463    #[test]
464    fn test_default_version() {
465        let mut manifest = test_manifest();
466        manifest.version = None;
467        let spec =
468            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
469        assert_eq!(spec["info"]["version"], "0.1.0");
470    }
471
472    #[test]
473    fn output_matches_the_golden_specs() {
474        for (manifest, golden) in [
475            (
476                include_str!("../../fixtures/starmoire_manifest.json"),
477                include_str!("../../fixtures/openapi/starmoire.json"),
478            ),
479            (
480                include_str!("../../fixtures/todo_manifest.json"),
481                include_str!("../../fixtures/openapi/todo.json"),
482            ),
483            (
484                include_str!("../../fixtures/blog_manifest.json"),
485                include_str!("../../fixtures/openapi/blog.json"),
486            ),
487        ] {
488            let manifest: ServiceManifest = serde_json::from_str(manifest).expect("manifest");
489            let golden: Value = serde_json::from_str(golden).expect("golden");
490            assert_eq!(
491                generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec"),
492                golden,
493                "{}",
494                manifest.name
495            );
496        }
497    }
498
499    #[test]
500    fn test_local_slug() {
501        let manifest = test_manifest();
502        let spec =
503            generate_openapi(&manifest, PathStyle::Absolute { tenant: "local" }).expect("spec");
504
505        let paths = spec["paths"].as_object().unwrap();
506        assert!(paths.contains_key("/svc/local/test-service/todos"));
507    }
508
509    fn documented_route(
510        method: &str,
511        path: &str,
512        handler: &str,
513        posture: Option<crate::RoutePosture>,
514        doc: crate::RouteDoc,
515    ) -> CustomRouteDefinition {
516        CustomRouteDefinition {
517            method: method.into(),
518            path: path.into(),
519            handler: handler.into(),
520            posture,
521            doc: Some(doc),
522            ..Default::default()
523        }
524    }
525
526    fn relative(manifest: &ServiceManifest) -> Value {
527        generate_openapi(manifest, PathStyle::ServerRelative { tenant: "acme" }).expect("spec")
528    }
529
530    #[test]
531    fn documented_services_default_to_server_relative_paths() {
532        let mut manifest = test_manifest();
533        assert_eq!(
534            default_style(&manifest, "acme"),
535            PathStyle::Absolute { tenant: "acme" }
536        );
537        manifest.custom_routes.push(documented_route(
538            "GET",
539            "/x",
540            "x",
541            None,
542            crate::RouteDoc::default(),
543        ));
544        assert_eq!(
545            default_style(&manifest, "acme"),
546            PathStyle::ServerRelative { tenant: "acme" }
547        );
548    }
549
550    #[test]
551    fn server_relative_specs_default_their_server_and_use_3_1_nullability() {
552        let mut manifest = test_manifest();
553        manifest.tables[0].columns[1].nullable = true;
554        manifest.openapi = Some(crate::OpenApiOptions::default());
555        let spec = relative(&manifest);
556        assert_eq!(
557            spec["servers"],
558            json!([{"url": "{origin}/svc/{tenant}/test-service",
559                "variables": {"origin": {"default": ""}, "tenant": {"default": "acme"}}}])
560        );
561        let paths = spec["paths"].as_object().expect("paths");
562        assert!(paths.contains_key("/todos") && paths.contains_key("/todos/{id}"));
563        assert_eq!(
564            spec["components"]["schemas"]["Todos"]["properties"]["title"],
565            json!({"type": ["string", "null"]})
566        );
567        assert!(spec.get("tags").is_none());
568        assert!(spec["components"].get("securitySchemes").is_none());
569
570        manifest.openapi = Some(crate::OpenApiOptions {
571            title: Some("Notes".into()),
572            version: Some("2.0.0".into()),
573            description: Some(String::new()),
574            servers: vec![crate::ServerDoc {
575                url: "https://api.example.com/api".into(),
576                description: Some("Production".into()),
577            }],
578            tags: vec![crate::TagDoc {
579                name: "Notes Service".into(),
580                description: Some("Notes Service API".into()),
581            }],
582            security_scheme: None,
583        });
584        let spec = relative(&manifest);
585        assert_eq!(
586            spec["info"],
587            json!({"title": "Notes", "version": "2.0.0", "description": ""})
588        );
589        assert_eq!(
590            spec["servers"],
591            json!([{"url": "https://api.example.com/api", "description": "Production"}])
592        );
593        assert_eq!(
594            spec["tags"],
595            json!([{"name": "Notes Service", "description": "Notes Service API"}])
596        );
597    }
598
599    #[test]
600    fn documented_routes_carry_parameters_bodies_responses_and_security() {
601        use crate::{BodyDoc, MediaDoc, ResponseDoc, RouteDoc, RoutePosture, RoutingMode};
602        let mut manifest = test_manifest();
603        manifest.tables.clear();
604        manifest.routing = RoutingMode::Strict;
605        manifest.components.insert(
606            "ApiNote".into(),
607            json!({"type": "object", "properties": {"id": {"type": "string"}}}),
608        );
609        let doc = RouteDoc {
610            tags: vec!["note".into()],
611            summary: Some("Update a note".into()),
612            deprecated: true,
613            path_params: Some(json!({"type": "object", "required": ["note_id"],
614                "properties": {"note_id": {"type": "string", "description": "Note identifier"}}})),
615            query: Some(
616                json!({"type": "object", "required": ["force"], "properties": {
617                "force": {"type": "boolean"}, "page": {"type": ["integer", "null"], "format": "int32"}}}),
618            ),
619            request: Some(BodyDoc {
620                content_type: "application/json".into(),
621                schema: Some(json!({"$ref": "#/components/schemas/ApiNote"})),
622                required: true,
623            }),
624            responses: [
625                (
626                    200,
627                    ResponseDoc {
628                        description: "Updated".into(),
629                        content: vec![MediaDoc {
630                            content_type: "application/json".into(),
631                            schema: Some(json!({"$ref": "#/components/schemas/ApiNote"})),
632                        }],
633                    },
634                ),
635                (
636                    403,
637                    ResponseDoc {
638                        description: "Forbidden".into(),
639                        content: vec![],
640                    },
641                ),
642            ]
643            .into(),
644            ..Default::default()
645        };
646        manifest.custom_routes = vec![
647            documented_route(
648                "PUT",
649                "/notes/{note_id}",
650                "update_note",
651                Some(RoutePosture::Permission {
652                    area: "notes".into(),
653                    operation: "edit".into(),
654                }),
655                doc,
656            ),
657            documented_route(
658                "GET",
659                "/notes/{note_id}/pdf",
660                "note_pdf",
661                Some(RoutePosture::Public {
662                    reason: "shared link".into(),
663                }),
664                RouteDoc {
665                    responses: [(
666                        200,
667                        ResponseDoc {
668                            description: "PDF".into(),
669                            content: vec![MediaDoc {
670                                content_type: "application/pdf".into(),
671                                schema: None,
672                            }],
673                        },
674                    )]
675                    .into(),
676                    ..Default::default()
677                },
678            ),
679        ];
680        let spec = relative(&manifest);
681        let update = &spec["paths"]["/notes/{note_id}"]["put"];
682        assert_eq!(update["operationId"], "update_note");
683        assert_eq!(update["tags"], json!(["note"]));
684        assert_eq!(update["summary"], "Update a note");
685        assert_eq!(update["deprecated"], true);
686        assert_eq!(
687            update["parameters"],
688            json!([
689                {"name": "note_id", "in": "path", "required": true, "schema": {"type": "string"},
690                    "description": "Note identifier"},
691                {"name": "force", "in": "query", "required": true, "schema": {"type": "boolean"}},
692                {"name": "page", "in": "query", "required": false,
693                    "schema": {"type": ["integer", "null"], "format": "int32"}},
694            ])
695        );
696        assert_eq!(
697            update["requestBody"],
698            json!({"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiNote"}}}, "required": true})
699        );
700        assert_eq!(
701            update["responses"]["403"],
702            json!({"description": "Forbidden"})
703        );
704        assert_eq!(update["security"], json!([{"bearer_auth": []}]));
705
706        let pdf = &spec["paths"]["/notes/{note_id}/pdf"]["get"];
707        assert_eq!(pdf["tags"], json!(["test-service"]));
708        assert_eq!(pdf["parameters"][0]["schema"], json!({"type": "string"}));
709        assert_eq!(
710            pdf["responses"]["200"],
711            json!({"description": "PDF", "content": {"application/pdf": {}}})
712        );
713        assert!(
714            pdf.get("security").is_none(),
715            "public routes need no credentials"
716        );
717        assert!(pdf.get("requestBody").is_none());
718        assert_eq!(
719            spec["components"]["securitySchemes"],
720            json!({"bearer_auth": {"type": "http", "scheme": "bearer"}})
721        );
722        assert_eq!(spec["components"]["schemas"]["ApiNote"]["type"], "object");
723    }
724
725    #[test]
726    fn legacy_routes_of_a_documented_service_use_their_fn_alias() {
727        let mut manifest = test_manifest();
728        manifest.custom_routes.push(CustomRouteDefinition {
729            method: "POST".into(),
730            path: "/complete/:id".into(),
731            handler: "complete_todo".into(),
732            posture: Some(crate::RoutePosture::Authenticated),
733            ..Default::default()
734        });
735        manifest.openapi = Some(crate::OpenApiOptions::default());
736        let spec = relative(&manifest);
737        let operation = &spec["paths"]["/_fn/complete_todo"]["post"];
738        assert_eq!(operation["operationId"], "complete_todo");
739        assert_eq!(operation["requestBody"]["required"], false);
740        assert_eq!(operation["responses"]["200"]["description"], "Success");
741        assert_eq!(
742            spec["paths"]["/todos"]["get"]["operationId"], "list_todos",
743            "CRUD operations are server-relative too"
744        );
745    }
746
747    #[test]
748    fn internal_routes_are_left_out_of_both_specs() {
749        let mut manifest = test_manifest();
750        manifest.custom_routes.push(CustomRouteDefinition {
751            method: "POST".into(),
752            path: "/reprice".into(),
753            handler: "reprice".into(),
754            posture: Some(crate::RoutePosture::Internal {
755                callers: vec!["pricing".into()],
756            }),
757            ..Default::default()
758        });
759        let absolute =
760            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
761        assert!(absolute["paths"]
762            .get("/svc/acme/test-service/_fn/reprice")
763            .is_none());
764        manifest.openapi = Some(crate::OpenApiOptions::default());
765        assert!(relative(&manifest)["paths"].get("/_fn/reprice").is_none());
766    }
767
768    #[test]
769    fn api_key_routes_require_the_api_key_scheme() {
770        let mut manifest = test_manifest();
771        manifest.openapi = Some(crate::OpenApiOptions::default());
772        manifest.custom_routes.push(CustomRouteDefinition {
773            method: "POST".into(),
774            path: "/ingest".into(),
775            handler: "ingest_lead".into(),
776            posture: Some(crate::RoutePosture::ApiKey {
777                scope: "leads:ingest".into(),
778            }),
779            ..Default::default()
780        });
781        let spec = relative(&manifest);
782        assert_eq!(
783            spec["paths"]["/_fn/ingest_lead"]["post"]["security"],
784            json!([{"api_key": []}])
785        );
786        assert_eq!(
787            spec["components"]["securitySchemes"],
788            json!({"api_key": {"type": "apiKey", "in": "header", "name": "X-Api-Key"}})
789        );
790    }
791
792    #[test]
793    fn a_crud_operation_id_clash_is_a_generation_error() {
794        let mut manifest = test_manifest();
795        manifest.custom_routes.push(documented_route(
796            "GET",
797            "/x",
798            "list_todos",
799            None,
800            crate::RouteDoc::default(),
801        ));
802        assert_eq!(
803            generate_openapi(&manifest, PathStyle::ServerRelative { tenant: "acme" }),
804            Err(OpenApiError(
805                "operation id 'list_todos' is used more than once".into()
806            ))
807        );
808        assert!(
809            generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).is_ok(),
810            "the absolute spec is today's and never refused"
811        );
812    }
813
814    fn private_notes() -> crate::TableDefinition {
815        serde_json::from_value(json!({
816            "name": "notes", "managed": false,
817            "columns": [{"name": "id", "column_type": "uuid", "primary_key": true}]
818        }))
819        .expect("table")
820    }
821
822    #[test]
823    fn a_private_table_has_no_paths_schemas_or_operation_ids() {
824        let served = test_manifest();
825        let mut manifest = served.clone();
826        manifest.private_tables = vec![private_notes()];
827        manifest.custom_routes.push(documented_route(
828            "GET",
829            "/notes",
830            "list_notes",
831            None,
832            crate::RouteDoc::default(),
833        ));
834        for style in [
835            PathStyle::Absolute { tenant: "acme" },
836            PathStyle::ServerRelative { tenant: "acme" },
837        ] {
838            let spec = generate_openapi(&manifest, style).expect("list_notes is the route's alone");
839            let text = spec.to_string();
840            for absent in [
841                "\"Notes\"",
842                "NotesCreate",
843                "create_note",
844                "/notes/{id}",
845                "/notes/:id",
846            ] {
847                assert!(!text.contains(absent), "{absent} in {text}");
848            }
849            let mut without = manifest.clone();
850            without.private_tables.clear();
851            assert_eq!(spec, generate_openapi(&without, style).expect("spec"));
852        }
853
854        let only_private = ServiceManifest {
855            tables: vec![],
856            ..manifest.clone()
857        };
858        let undeclared = ServiceManifest {
859            private_tables: vec![],
860            ..only_private.clone()
861        };
862        for style in [
863            PathStyle::Absolute { tenant: "acme" },
864            PathStyle::ServerRelative { tenant: "acme" },
865        ] {
866            assert_eq!(
867                generate_openapi(&only_private, style),
868                generate_openapi(&undeclared, style)
869            );
870        }
871    }
872}