rustango_cms/api/mod.rs
1//! REST API v2 — public reads plus member login.
2//!
3//! Lets headless frontends (Next.js / Nuxt / Astro / SvelteKit) read
4//! pages, images, and documents over JSON — pagination, sparse-field
5//! selection, tree filters
6//! (child_of / descendant_of / ancestor_of), translation siblings,
7//! locale, search, ordering.
8//!
9//! ## Mounting
10//!
11//! Host apps build the API router alongside the public CMS router:
12//!
13//! ```ignore
14//! use std::sync::Arc;
15//! use axum::Router;
16//!
17//! let api = rustango_cms::api::router();
18//! let public = rustango_cms::router_at("/p", tera);
19//! let app = Router::new().merge(api).merge(public);
20//! ```
21//!
22//! All routes live under `/api/v2/…`.
23//!
24//! ## Endpoints
25//!
26//! The core routes are below; [`ROUTE_PATHS`] and
27//! `GET /api/v2/openapi.json` are the complete list (tree, menus,
28//! locales, search, changes).
29//!
30//! | Path | Returns |
31//! |---|---|
32//! | `GET /api/v2/pages/` | paginated page list (published only) |
33//! | `GET /api/v2/pages/find/?html_path=…` | resolve a URL path → 302 to its detail |
34//! | `GET /api/v2/pages/{id}/` | single page + extension fields |
35//! | `GET /api/v2/images/` | paginated image list |
36//! | `GET /api/v2/images/{id}/` | single image metadata |
37//! | `GET /api/v2/documents/` | paginated document list |
38//! | `GET /api/v2/documents/{id}/` | single document metadata |
39//! | `GET /api/v2/snippets/` | paginated snippet list (`?type=` to filter) |
40//! | `GET /api/v2/snippets/{id}/` | single snippet |
41//! | `POST /api/v2/auth/login` | member bearer token (see [`auth`]) |
42//!
43//! ## Response shape
44//!
45//! Every list response carries `{ meta: { total_count, limit, offset }, items: [...] }`.
46//! Per-row shape: a `meta` sub-object
47//! with `type`, `detail_url`, plus the content fields hoisted to the
48//! top level. Sparse selection (`?fields=`) filters which content
49//! fields appear; `meta` is always present.
50//!
51//! View-restricted pages are gated by the same `view_restriction_guard`
52//! the public renderer uses; a member authenticates with the session
53//! cookie or the bearer token from `auth/login`.
54//!
55//! ## Not provided
56//!
57//! - Write API (`POST`/`PUT`/`PATCH` on content)
58//! - GraphQL
59//! - Browsable HTML renderer
60
61use axum::routing::get;
62use axum::Router;
63use rustango::cors::CorsRouterExt as _;
64
65pub mod auth;
66pub mod changes;
67pub mod documents;
68pub mod error;
69pub mod http_cache;
70pub mod images;
71pub mod locales;
72pub mod menus;
73pub mod pages;
74pub mod openapi;
75pub mod query;
76pub mod search;
77pub mod snippets;
78pub mod tree;
79
80/// Path prefix every v2 endpoint lives under.
81///
82/// Hosts pass this to `CsrfConfig::exempt_prefix`. Apart from the
83/// credential-based member login, the API registers only `GET`, so
84/// there is no cookie-authenticated write for CSRF to protect. Without
85/// the exemption the layer rejects unsafe verbs *before* routing, and a
86/// client attempting a write is told `403 Forbidden` rather than
87/// `405 Method Not Allowed`: it goes looking for a permissions problem
88/// instead of concluding the endpoint does not exist.
89pub const PREFIX: &str = "/api/v2";
90
91/// Response headers a cross-origin browser client is allowed to read.
92///
93/// Only a handful of headers are readable from JavaScript by default
94/// (`Cache-Control`, `Content-Type`, `Last-Modified`, and a couple
95/// more); everything else is hidden unless the server names it here.
96/// `ETag` and `Allow` were both hidden, which quietly disabled two
97/// features for the exact audience CORS exists to serve:
98///
99/// * **Conditional requests.** The API attaches a weak `ETag` to every
100/// cacheable body and answers `If-None-Match` with a 304 — but a SPA
101/// that cannot *read* the `ETag` can never send it back, so a polling
102/// client re-transferred the whole body every tick.
103/// * **`Allow` on a 405.** The refusal names the verbs that would have
104/// worked, and a cross-origin client could not see them.
105const EXPOSED_HEADERS: [&str; 2] = ["etag", "allow"];
106
107/// Cross-origin policy for [`router_with`].
108///
109/// Off by default, and deliberately so. Turning this on makes every
110/// endpoint readable by any page on the internet that a browser will
111/// load — including the ones that still leak gated content — so it stays
112/// a decision a host makes explicitly rather than one it inherits.
113#[derive(Debug, Clone, Default)]
114pub enum Cors {
115 /// No CORS headers at all. A browser SPA must be same-origin, or sit
116 /// behind a reverse proxy that makes it so.
117 #[default]
118 Disabled,
119 /// Allow exactly these origins. Credentials are permitted, so the
120 /// member session cookie can travel — which is why a wildcard is not
121 /// offered here.
122 Origins(Vec<String>),
123 /// Reflect any origin. Development only: combined with credentials
124 /// this would let any site read a signed-in member's content, so
125 /// credentials are *not* enabled in this mode.
126 Any,
127}
128
129impl Cors {
130 /// Read an allowlist from `RCMS_API_CORS_ORIGINS` — comma-separated,
131 /// or the literal `*` for [`Cors::Any`]. Absent or empty is
132 /// [`Cors::Disabled`], so an unset environment changes nothing.
133 #[must_use]
134 pub fn from_env() -> Self {
135 Self::parse(crate::config::var("API_CORS_ORIGINS").as_deref())
136 }
137
138 /// The parsing half of [`Self::from_env`], split out so it can be tested.
139 ///
140 /// Process environment is global mutable state, and Rust runs tests
141 /// in parallel threads — a test that sets a variable races every
142 /// other test that reads one. Keeping the logic pure sidesteps that
143 /// instead of papering over it with a mutex.
144 #[must_use]
145 pub fn parse(raw: Option<&str>) -> Self {
146 let Some(raw) = raw else {
147 return Self::Disabled;
148 };
149 if raw.trim() == "*" {
150 return Self::Any;
151 }
152 let origins: Vec<String> = raw
153 .split(',')
154 .map(str::trim)
155 .filter(|s| !s.is_empty())
156 .map(str::to_owned)
157 .collect();
158 if origins.is_empty() {
159 Self::Disabled
160 } else {
161 Self::Origins(origins)
162 }
163 }
164}
165
166/// Build the public JSON API router rooted at `/api/v2`, with no CORS.
167///
168/// Returns an [`axum::Router`] host apps can merge / nest at the root
169/// of their application Router.
170pub fn router() -> Router {
171 router_with(&Cors::Disabled)
172}
173
174/// Every path this router serves, in one list.
175///
176/// Shared with [`openapi`] so the published schema cannot describe a
177/// different API than the one running: `router_with` zips this against
178/// its handler array, and a length mismatch is a compile error, while
179/// `openapi::document` is built from the same constant.
180pub const ROUTE_PATHS: [&str; 15] = [
181 "/api/v2/pages/",
182 // `find/` and `tree/` are static segments, so axum matches them ahead
183 // of the `{id}` capture regardless of registration order.
184 "/api/v2/pages/find/",
185 "/api/v2/pages/tree/",
186 "/api/v2/pages/{id}/",
187 "/api/v2/images/",
188 "/api/v2/images/{id}/",
189 "/api/v2/documents/",
190 "/api/v2/documents/{id}/",
191 // #431 — snippets (the admin "Library" rows).
192 "/api/v2/snippets/",
193 "/api/v2/snippets/{id}/",
194 // #584 — navigation menus (resolved trees) for headless navbars.
195 "/api/v2/menus/",
196 "/api/v2/menus/{slug}/",
197 // Locale discovery: without it a headless client has to hard-code the
198 // tenant's language list and cannot tell a typo from a real code,
199 // because an unknown one falls back silently.
200 "/api/v2/locales/",
201 // One search box across pages, images, documents and snippets.
202 "/api/v2/search/",
203 // The cheap polling tick: what changed, without asking every
204 // collection in turn.
205 "/api/v2/changes/",
206];
207
208/// [`router`], with a cross-origin policy.
209///
210/// Every route is registered twice, with and without the trailing slash.
211/// axum does not redirect between them, so `/api/v2/pages` used to fall
212/// through to the host's catch-all and answer a JSON client with the
213/// CMS 404 *page*. Accepting both is cheaper than teaching every client
214/// a rule it will get wrong once.
215pub fn router_with(cors: &Cors) -> Router {
216 // Same order as `ROUTE_PATHS`; the array lengths must match, so
217 // adding a route without listing its path fails to compile.
218 let handlers = [
219 get(pages::list),
220 get(pages::find),
221 get(tree::tree),
222 get(pages::detail),
223 get(images::list),
224 get(images::detail),
225 get(documents::list),
226 get(documents::detail),
227 get(snippets::list),
228 get(snippets::detail),
229 get(menus::list),
230 get(menus::detail),
231 get(locales::list),
232 get(search::search),
233 get(changes::changes),
234 ];
235
236 let mut r = Router::new();
237 for (path, route) in ROUTE_PATHS.iter().zip(handlers) {
238 r = r
239 .route(path, route.clone())
240 .route(path.trim_end_matches('/'), route);
241 }
242 // The schema itself, so a client can discover the API without one.
243 r = r.route(openapi::PATH, get(openapi::serve));
244
245 // The only write on the whole surface, and the only reason a browser
246 // SPA on another origin can read gated content at all: the member
247 // session cookie is `SameSite=Lax` and simply is not sent
248 // cross-site. Accepts JSON or form encoding.
249 r = r.route(auth::LOGIN_PATH, axum::routing::post(auth::login));
250
251 let r = r
252 // Inner: fills in the body of a 405 the MethodRouter
253 // produced, so a write attempt is refused in JSON like
254 // every other failure.
255 .layer(axum::middleware::from_fn(error::method_not_allowed_json))
256 .layer(axum::middleware::from_fn(http_cache::layer));
257
258 // `POST` is for the member login (`auth::LOGIN_PATH`) and
259 // `authorization` for the bearer token it returns — the way a SPA on
260 // another origin reads gated content, since the session cookie is
261 // `SameSite=Lax` and never rides a cross-site fetch. Without them the
262 // browser's preflight refuses both before the request is sent.
263 const ALLOWED_METHODS: [&str; 4] = ["GET", "HEAD", "OPTIONS", "POST"];
264 const ALLOWED_HEADERS: [&str; 3] = ["content-type", "if-none-match", "authorization"];
265
266 match cors {
267 Cors::Disabled => r,
268 Cors::Any => r.cors(
269 rustango::cors::CorsLayer::new()
270 .allow_methods(ALLOWED_METHODS.to_vec())
271 .allow_headers(ALLOWED_HEADERS.to_vec())
272 .expose_headers(EXPOSED_HEADERS),
273 ),
274 Cors::Origins(origins) => r.cors(
275 rustango::cors::CorsLayer::new()
276 .allow_origins(origins.clone())
277 .allow_methods(ALLOWED_METHODS.to_vec())
278 .allow_headers(ALLOWED_HEADERS.to_vec())
279 .expose_headers(EXPOSED_HEADERS)
280 // The member session is a cookie, so a cross-origin SPA
281 // needs credentials to fetch gated content at all.
282 .allow_credentials(true)
283 .max_age(std::time::Duration::from_secs(3600)),
284 ),
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291
292 #[test]
293 fn an_absent_value_leaves_cors_off() {
294 // The safety property: deploying this release must not open the
295 // API to other origins by itself.
296 assert!(matches!(Cors::parse(None), Cors::Disabled));
297 }
298
299 #[test]
300 fn an_empty_or_whitespace_value_is_also_off() {
301 assert!(matches!(Cors::parse(Some("")), Cors::Disabled));
302 assert!(matches!(Cors::parse(Some(" , ,")), Cors::Disabled));
303 }
304
305 #[test]
306 fn a_comma_separated_list_is_parsed_and_trimmed() {
307 match Cors::parse(Some("https://a.example.com, https://b.example.com")) {
308 Cors::Origins(o) => {
309 assert_eq!(o, ["https://a.example.com", "https://b.example.com"]);
310 }
311 other => panic!("expected an allowlist, got {other:?}"),
312 }
313 }
314
315 #[test]
316 fn a_literal_star_is_the_reflect_any_mode() {
317 assert!(matches!(Cors::parse(Some("*")), Cors::Any));
318 assert!(matches!(Cors::parse(Some(" * ")), Cors::Any));
319 }
320
321 #[test]
322 fn the_default_is_disabled() {
323 assert!(matches!(Cors::default(), Cors::Disabled));
324 }
325}