Skip to main content

rustango_cms/api/
openapi.rs

1//! `GET /api/v2/openapi.json` — the API describing itself.
2//!
3//! There was no schema of any kind, so a client had to be hand-written
4//! from prose and re-checked by hand whenever anything moved. Response
5//! shapes are built with inline `serde_json::json!` literals, so there
6//! is no Rust struct to derive a schema from — this describes them
7//! explicitly instead.
8//!
9//! The honest limit: **the response schemas are hand-maintained and can
10//! drift from the handlers.** What cannot drift is the *route list* —
11//! it comes from [`crate::api::ROUTE_PATHS`], the same constant the
12//! router is built from, and a test asserts every path is documented. So
13//! a new endpoint can never be silently absent, and a removed one can
14//! never linger.
15//!
16//! Generate a typed client from it:
17//!
18//! ```sh
19//! npx openapi-typescript https://example.com/api/v2/openapi.json -o api.d.ts
20//! ```
21
22use axum::response::{IntoResponse, Response};
23use axum::Json;
24
25/// Where the document is served.
26pub const PATH: &str = "/api/v2/openapi.json";
27
28/// `GET /api/v2/openapi.json`
29pub async fn serve() -> Response {
30    Json(document()).into_response()
31}
32
33/// One endpoint's human- and machine-readable description.
34struct Doc {
35    path: &'static str,
36    summary: &'static str,
37    /// `(name, description)` for each query parameter.
38    params: &'static [(&'static str, &'static str)],
39    /// Component schema name for a 200 body.
40    ok: &'static str,
41    /// Extra status codes worth calling out, beyond the shared errors.
42    extra: &'static [(&'static str, &'static str)],
43}
44
45/// Shared across every list endpoint, so they are not re-listed 6 times.
46const LIST_PARAMS: &[(&str, &str)] = &[
47    ("limit", "Page size, 1–100 (default 20)."),
48    ("offset", "Rows to skip."),
49    (
50        "fields",
51        "Comma-separated allowlist; `id` and `meta` are always kept. An unknown name is a 400.",
52    ),
53    (
54        "order",
55        "Comma-separated ordering; prefix `-` to reverse, or `random`. An unknown field is a 400.",
56    ),
57    ("search", "Substring/full-text match on this collection."),
58    (
59        "updated_since",
60        "RFC 3339 instant; only rows touched at or after it. A malformed value is a 400.",
61    ),
62];
63
64const DOCS: &[Doc] = &[
65    Doc {
66        path: "/api/v2/pages/",
67        summary: "List pages (published and archived), filtered to what the caller may see.",
68        params: LIST_PARAMS,
69        ok: "PageList",
70        extra: &[],
71    },
72    Doc {
73        path: "/api/v2/pages/find/",
74        summary: "Resolve a public URL path to a page, as a redirect to its detail URL.",
75        params: &[("html_path", "The public URL path, with or without a trailing slash.")],
76        ok: "Empty",
77        extra: &[
78            ("302", "Found — `Location` is the page's detail URL."),
79            ("404", "No public page at that path, or the caller may not see it."),
80        ],
81    },
82    Doc {
83        path: "/api/v2/pages/tree/",
84        summary: "The site's page hierarchy, nested and depth-limited.",
85        params: &[
86            ("root", "Return the subtree under this page id; the page itself is excluded."),
87            ("depth", "Levels to walk, 1–10 (default 3)."),
88            ("locale", "Localize titles."),
89        ],
90        ok: "PageTree",
91        extra: &[],
92    },
93    Doc {
94        path: "/api/v2/pages/{id}/",
95        summary: "One page, with its extension data, builder body and direct children.",
96        params: &[
97            ("locale", "Content locale; echoed back as `meta.locale`."),
98            ("fields", "Comma-separated allowlist."),
99            ("preview_token", "Signed token from the admin, to read a draft."),
100        ],
101        ok: "PageDetail",
102        extra: &[
103            ("401", "Authentication required (a gated page, anonymous caller)."),
104            ("403", "Authenticated but not permitted."),
105        ],
106    },
107    Doc {
108        path: "/api/v2/images/",
109        summary: "List images the caller may see, excluding gated collections.",
110        params: LIST_PARAMS,
111        ok: "MediaList",
112        extra: &[],
113    },
114    Doc {
115        path: "/api/v2/images/{id}/",
116        summary: "One image, with rendition URLs.",
117        params: &[("fields", "Comma-separated allowlist.")],
118        ok: "Image",
119        extra: &[],
120    },
121    Doc {
122        path: "/api/v2/documents/",
123        summary: "List non-image media the caller may see.",
124        params: LIST_PARAMS,
125        ok: "MediaList",
126        extra: &[],
127    },
128    Doc {
129        path: "/api/v2/documents/{id}/",
130        summary: "One document.",
131        params: &[("fields", "Comma-separated allowlist.")],
132        ok: "Document",
133        extra: &[],
134    },
135    Doc {
136        path: "/api/v2/snippets/",
137        summary: "List snippets (the admin Library).",
138        params: LIST_PARAMS,
139        ok: "SnippetList",
140        extra: &[],
141    },
142    Doc {
143        path: "/api/v2/snippets/{id}/",
144        summary: "One snippet, including its `data` bag.",
145        params: &[("fields", "Comma-separated allowlist.")],
146        ok: "Snippet",
147        extra: &[],
148    },
149    Doc {
150        path: "/api/v2/menus/",
151        summary: "List configured menus (slug and name only).",
152        params: &[
153            ("limit", "Page size, 1–100 (default 20)."),
154            ("offset", "Rows to skip."),
155        ],
156        ok: "MenuList",
157        extra: &[],
158    },
159    Doc {
160        path: "/api/v2/menus/{slug}/",
161        summary: "One menu, resolved into a nested tree with active marking.",
162        params: &[
163            ("locale", "Localized labels; echoed as `meta.locale`."),
164            ("current", "Page id being viewed — marks the active item and its trail."),
165        ],
166        ok: "MenuDetail",
167        extra: &[],
168    },
169    Doc {
170        path: "/api/v2/locales/",
171        summary: "Content locales this tenant serves. Inactive ones are omitted.",
172        params: &[],
173        ok: "LocaleList",
174        extra: &[],
175    },
176    Doc {
177        path: "/api/v2/changes/",
178        summary: "Per-collection count and last-changed time, for cheap polling.",
179        params: &[],
180        ok: "Changes",
181        extra: &[],
182    },
183    Doc {
184        path: "/api/v2/search/",
185        summary: "Search pages, images, documents and snippets in one ranked list.",
186        params: &[
187            ("q", "The needle. Required."),
188            ("type", "Comma-separated subset of page,image,document,snippet."),
189            ("limit", "Page size, 1–100 (default 20)."),
190            ("offset", "Rows to skip."),
191        ],
192        ok: "SearchResults",
193        extra: &[],
194    },
195];
196
197/// Build the OpenAPI 3.1 document.
198#[must_use]
199pub fn document() -> serde_json::Value {
200    let mut paths = serde_json::Map::new();
201    for d in DOCS {
202        let params: Vec<serde_json::Value> = d
203            .params
204            .iter()
205            .map(|(name, desc)| {
206                serde_json::json!({
207                    "name": name,
208                    "in": "query",
209                    "required": false,
210                    "description": desc,
211                    "schema": { "type": "string" },
212                })
213            })
214            .chain(path_params(d.path))
215            .collect();
216
217        let mut responses = serde_json::Map::new();
218        responses.insert(
219            "200".to_owned(),
220            serde_json::json!({
221                "description": "Success",
222                "content": { "application/json": {
223                    "schema": { "$ref": format!("#/components/schemas/{}", d.ok) }
224                }},
225            }),
226        );
227        responses.insert("304".to_owned(), serde_json::json!({
228            "description": "Not Modified — the `If-None-Match` validator still matches.",
229        }));
230        for (code, desc) in d.extra {
231            responses.insert(
232                (*code).to_owned(),
233                serde_json::json!({
234                    "description": desc,
235                    "content": { "application/json": {
236                        "schema": { "$ref": "#/components/schemas/Error" }
237                    }},
238                }),
239            );
240        }
241        for (code, desc) in [
242            ("400", "Malformed request — see `error.code`."),
243            ("404", "No such resource, or the caller may not see it."),
244            ("405", "Write verb on a read-only API. `Allow` names what this path serves."),
245            ("500", "Server error."),
246        ] {
247            responses.entry(code.to_owned()).or_insert_with(|| {
248                serde_json::json!({
249                    "description": desc,
250                    "content": { "application/json": {
251                        "schema": { "$ref": "#/components/schemas/Error" }
252                    }},
253                })
254            });
255        }
256
257        paths.insert(
258            d.path.to_owned(),
259            serde_json::json!({ "get": {
260                "summary": d.summary,
261                "parameters": params,
262                "responses": responses,
263            }}),
264        );
265    }
266
267    paths.insert(
268        crate::api::auth::LOGIN_PATH.to_owned(),
269        serde_json::json!({ "post": {
270            "summary": "Exchange member credentials for a bearer token.",
271            "description":
272                "The member session cookie is `SameSite=Lax` and is not sent on \
273                 cross-site fetches, so a SPA on another origin cannot use it. \
274                 This returns the same signed session value as a token to send \
275                 as `Authorization: Bearer`.",
276            "requestBody": { "required": true, "content": {
277                "application/json": {
278                    "schema": { "$ref": "#/components/schemas/LoginRequest" }
279                },
280                "application/x-www-form-urlencoded": {
281                    "schema": { "$ref": "#/components/schemas/LoginRequest" }
282                },
283            }},
284            "responses": {
285                "200": { "description": "Signed in", "content": { "application/json": {
286                    "schema": { "$ref": "#/components/schemas/LoginResponse" }
287                }}},
288                "400": { "description": "Malformed body", "content": { "application/json": {
289                    "schema": { "$ref": "#/components/schemas/Error" }
290                }}},
291                "401": { "description": "Invalid credentials", "content": { "application/json": {
292                    "schema": { "$ref": "#/components/schemas/Error" }
293                }}},
294            },
295        }}),
296    );
297
298    serde_json::json!({
299        "openapi": "3.1.0",
300        "info": {
301            "title": "rustango-cms content API",
302            "version": "2",
303            "description":
304                "Read-only JSON over the CMS's public content. Every endpoint is \
305                 viewer-aware: gated pages and assets in closed collections are \
306                 absent for callers who may not see them. Responses carry a weak \
307                 ETag and `Cache-Control: private, no-cache`; send the tag back as \
308                 `If-None-Match` for a 304.",
309        },
310        "paths": paths,
311        "components": {
312            "schemas": schemas(),
313            "securitySchemes": { "bearerAuth": { "type": "http", "scheme": "bearer" } },
314        },
315    })
316}
317
318/// `{id}` / `{slug}` captures declared as path parameters.
319fn path_params(path: &str) -> impl Iterator<Item = serde_json::Value> + '_ {
320    path.split('/')
321        .filter(|seg| seg.starts_with('{') && seg.ends_with('}'))
322        .map(|seg| {
323            let name = seg.trim_matches(|c| c == '{' || c == '}');
324            serde_json::json!({
325                "name": name,
326                "in": "path",
327                "required": true,
328                "schema": { "type": if name == "slug" { "string" } else { "integer" } },
329            })
330        })
331}
332
333fn obj(props: serde_json::Value) -> serde_json::Value {
334    serde_json::json!({ "type": "object", "properties": props })
335}
336
337fn arr(item_ref: &str) -> serde_json::Value {
338    serde_json::json!({
339        "type": "array",
340        "items": { "$ref": format!("#/components/schemas/{item_ref}") },
341    })
342}
343
344fn schemas() -> serde_json::Value {
345    let str_t = serde_json::json!({ "type": "string" });
346    let int_t = serde_json::json!({ "type": "integer" });
347    let bool_t = serde_json::json!({ "type": "boolean" });
348    let nullable_str = serde_json::json!({ "type": ["string", "null"] });
349
350    serde_json::json!({
351        "Error": obj(serde_json::json!({
352            "error": obj(serde_json::json!({
353                "code": {
354                    "type": "string",
355                    "enum": ["not_found", "bad_request", "unauthenticated",
356                             "forbidden", "password_required", "method_not_allowed",
357                             "internal_error"],
358                },
359                "message": str_t,
360            })),
361        })),
362        "ListMeta": obj(serde_json::json!({
363            "total_count": int_t, "limit": int_t, "offset": int_t,
364            "has_more": bool_t, "next_offset": int_t, "previous_offset": int_t,
365        })),
366        "PageSummary": obj(serde_json::json!({
367            "id": int_t,
368            "title": str_t,
369            "url": str_t,
370            "seo_title": str_t,
371            "seo_description": str_t,
372            "meta": obj(serde_json::json!({
373                "type": str_t, "detail_url": str_t, "html_url": str_t,
374                "slug": str_t, "depth": int_t, "parent_id": int_t,
375                "alias_of": int_t, "first_published_at": nullable_str,
376                "updated_at": nullable_str,
377            })),
378        })),
379        "PageList": obj(serde_json::json!({
380            "meta": { "$ref": "#/components/schemas/ListMeta" },
381            "items": arr("PageSummary"),
382        })),
383        "ChildSummary": obj(serde_json::json!({
384            "id": int_t, "title": str_t, "slug": str_t, "url": str_t,
385            "has_children": bool_t, "detail_url": str_t,
386        })),
387        "PageDetail": obj(serde_json::json!({
388            "id": int_t, "title": str_t, "url": str_t,
389            "meta": obj(serde_json::json!({ "type": str_t, "locale": nullable_str })),
390            "extension": { "type": "object" },
391            "builder": { "type": "object" },
392            "children": arr("ChildSummary"),
393        })),
394        "TreeNode": obj(serde_json::json!({
395            "id": int_t, "title": str_t, "type": str_t, "slug": str_t,
396            "url": str_t, "depth": int_t, "has_children": bool_t,
397            "detail_url": str_t, "alias_of": int_t,
398            "children": arr("TreeNode"),
399        })),
400        "PageTree": obj(serde_json::json!({
401            "meta": obj(serde_json::json!({
402                "depth": int_t, "root": int_t, "locale": nullable_str,
403                "total_count": int_t, "truncated": bool_t, "dropped_count": int_t,
404            })),
405            "items": arr("TreeNode"),
406        })),
407        "Image": obj(serde_json::json!({
408            "id": int_t, "title": str_t, "filename": str_t, "alt_text": str_t,
409            "mime": str_t, "size": int_t, "width": int_t, "height": int_t,
410            "collection_id": int_t,
411            "renditions": obj(serde_json::json!({
412                "thumbnail": nullable_str, "medium": nullable_str, "large": nullable_str,
413            })),
414            "meta": obj(serde_json::json!({
415                "type": str_t, "detail_url": str_t, "download_url_template": str_t,
416            })),
417        })),
418        "Document": obj(serde_json::json!({
419            "id": int_t, "title": str_t, "filename": str_t, "mime": str_t,
420            "kind": str_t, "size": int_t, "collection_id": int_t,
421            "meta": obj(serde_json::json!({ "type": str_t, "detail_url": str_t })),
422        })),
423        "MediaList": obj(serde_json::json!({
424            "meta": { "$ref": "#/components/schemas/ListMeta" },
425            "items": { "type": "array", "items": { "type": "object" } },
426        })),
427        "Snippet": obj(serde_json::json!({
428            "id": int_t, "type_name": str_t, "slug": str_t, "title": str_t,
429            "folder_path": str_t, "body_markdown": str_t,
430            "data": { "type": "object" },
431            "meta": obj(serde_json::json!({
432                "type": str_t, "type_name": str_t, "detail_url": str_t,
433                "updated_at": nullable_str,
434            })),
435        })),
436        "SnippetList": obj(serde_json::json!({
437            "meta": { "$ref": "#/components/schemas/ListMeta" },
438            "items": arr("Snippet"),
439        })),
440        "MenuSummary": obj(serde_json::json!({
441            "slug": str_t, "name": str_t, "detail_url": str_t,
442        })),
443        "MenuList": obj(serde_json::json!({
444            "meta": { "$ref": "#/components/schemas/ListMeta" },
445            "items": arr("MenuSummary"),
446        })),
447        "MenuItem": obj(serde_json::json!({
448            "id": int_t,
449            "label": str_t,
450            "url": nullable_str,
451            "is_page": bool_t,
452            "page_id": int_t,
453            "open_in_new_tab": bool_t,
454            "is_active": bool_t,
455            "in_active_trail": bool_t,
456            "children": arr("MenuItem"),
457        })),
458        "MenuDetail": obj(serde_json::json!({
459            "meta": obj(serde_json::json!({
460                "slug": str_t, "name": str_t, "locale": nullable_str,
461                "current": int_t, "total_count": int_t,
462            })),
463            "items": arr("MenuItem"),
464        })),
465        "Locale": obj(serde_json::json!({
466            "code": str_t, "name": str_t, "is_default": bool_t,
467        })),
468        "LocaleList": obj(serde_json::json!({
469            "meta": obj(serde_json::json!({ "total_count": int_t, "default": nullable_str })),
470            "items": arr("Locale"),
471        })),
472        "SearchHit": obj(serde_json::json!({
473            "type": { "type": "string", "enum": ["page", "image", "document", "snippet"] },
474            "id": int_t, "title": str_t, "url": nullable_str,
475            "detail_url": str_t, "score": { "type": "number" },
476        })),
477        "SearchResults": obj(serde_json::json!({
478            "meta": obj(serde_json::json!({
479                "q": str_t, "types": { "type": "array", "items": str_t },
480                "total_count": int_t, "limit": int_t, "offset": int_t, "has_more": bool_t,
481            })),
482            "items": arr("SearchHit"),
483        })),
484        "ChangeEntry": obj(serde_json::json!({
485            "count": int_t,
486            "latest": nullable_str,
487        })),
488        "Changes": obj(serde_json::json!({
489            "meta": obj(serde_json::json!({ "checked_at": str_t, "usage": str_t })),
490            "collections": obj(serde_json::json!({
491                "pages": { "$ref": "#/components/schemas/ChangeEntry" },
492                "images": { "$ref": "#/components/schemas/ChangeEntry" },
493                "documents": { "$ref": "#/components/schemas/ChangeEntry" },
494                "snippets": { "$ref": "#/components/schemas/ChangeEntry" },
495                "menus": { "$ref": "#/components/schemas/ChangeEntry" },
496            })),
497        })),
498        "LoginRequest": obj(serde_json::json!({
499            "identifier": str_t, "password": str_t,
500        })),
501        "LoginResponse": obj(serde_json::json!({
502            "token": str_t, "token_type": str_t, "expires_in": int_t,
503            "member": obj(serde_json::json!({
504                "id": int_t, "username": str_t, "email": nullable_str,
505            })),
506        })),
507        "Empty": { "type": "object" },
508    })
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514
515    /// The invariant that keeps this honest: the schema describes exactly
516    /// the routes the router serves. Add an endpoint without documenting
517    /// it — or document one that no longer exists — and this fails.
518    #[test]
519    fn every_route_is_documented_and_nothing_extra() {
520        let documented: std::collections::BTreeSet<&str> =
521            DOCS.iter().map(|d| d.path).collect();
522        let served: std::collections::BTreeSet<&str> =
523            crate::api::ROUTE_PATHS.iter().copied().collect();
524        assert_eq!(
525            documented, served,
526            "the OpenAPI path list and the router's ROUTE_PATHS disagree",
527        );
528    }
529
530    #[test]
531    fn every_endpoint_has_a_summary() {
532        for d in DOCS {
533            assert!(!d.summary.is_empty(), "{} has no summary", d.path);
534            assert!(
535                d.summary.ends_with('.'),
536                "{} summary should read as a sentence",
537                d.path,
538            );
539        }
540    }
541
542    #[test]
543    fn every_referenced_schema_exists() {
544        // A dangling `$ref` produces a client that fails to generate, and
545        // the failure names the ref rather than the endpoint.
546        let doc = document();
547        let defined: std::collections::BTreeSet<String> = doc["components"]["schemas"]
548            .as_object()
549            .expect("schemas")
550            .keys()
551            .cloned()
552            .collect();
553        let mut refs = Vec::new();
554        collect_refs(&doc, &mut refs);
555        for r in refs {
556            let name = r.rsplit('/').next().unwrap_or_default().to_owned();
557            assert!(defined.contains(&name), "dangling $ref: {r}");
558        }
559    }
560
561    fn collect_refs(v: &serde_json::Value, out: &mut Vec<String>) {
562        match v {
563            serde_json::Value::Object(map) => {
564                for (k, val) in map {
565                    if k == "$ref" {
566                        if let Some(s) = val.as_str() {
567                            out.push(s.to_owned());
568                        }
569                    }
570                    collect_refs(val, out);
571                }
572            }
573            serde_json::Value::Array(items) => items.iter().for_each(|i| collect_refs(i, out)),
574            _ => {}
575        }
576    }
577
578    #[test]
579    fn path_captures_become_path_parameters() {
580        let params: Vec<serde_json::Value> = path_params("/api/v2/menus/{slug}/").collect();
581        assert_eq!(params.len(), 1);
582        assert_eq!(params[0]["name"], "slug");
583        assert_eq!(params[0]["in"], "path");
584        assert_eq!(params[0]["required"], true);
585        assert_eq!(params[0]["schema"]["type"], "string");
586
587        let params: Vec<serde_json::Value> = path_params("/api/v2/pages/{id}/").collect();
588        assert_eq!(params[0]["schema"]["type"], "integer");
589
590        assert_eq!(path_params("/api/v2/pages/").count(), 0);
591    }
592
593    #[test]
594    fn the_document_is_a_usable_openapi_31_shell() {
595        let doc = document();
596        assert_eq!(doc["openapi"], "3.1.0");
597        assert!(doc["info"]["title"].is_string());
598        // Every path is a GET with responses.
599        for path in crate::api::ROUTE_PATHS {
600            let op = &doc["paths"][path]["get"];
601            assert!(op.is_object(), "{path} has no GET operation");
602            assert!(op["responses"]["200"].is_object(), "{path} has no 200");
603            assert!(op["responses"]["404"].is_object(), "{path} has no 404");
604        }
605    }
606}