navree_http/route.rs
1//! [`RouteDef`] and its metadata: access declaration, guards, throttle,
2//! timeout, body limit, audit action and OpenAPI metadata.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use http::Method;
10use navree_kernel::ModuleId;
11
12use crate::Guard;
13use crate::error_pages::RouteKind;
14use crate::handler::{Endpoint, Handler};
15
16/// One route: a method, a path, a [`Handler`] and its metadata.
17///
18/// The path is relative to the controller (`/{id}`), with `{param}` and
19/// `{*rest}` captures (see [`routing`](crate::routing)). A path starting with
20/// `!` is absolute: it is mounted as written, without the API prefix,
21/// version or controller prefix (`!/csrf-cookie`, `!/health/live`).
22///
23/// Every route must declare its access ([`public`](RouteDef::public),
24/// [`authenticated`](RouteDef::authenticated), [`roles`](RouteDef::roles),
25/// [`permissions`](RouteDef::permissions) or [`can`](RouteDef::can)); the app
26/// refuses to boot otherwise.
27///
28/// ```
29/// use http::Method;
30/// use navree_http::RouteDef;
31///
32/// let route = RouteDef::on(Method::GET, "/{id}", || async { "deal" })
33/// .name("deals.show")
34/// .can("read", "Deal", Some("id"));
35/// assert!(route.meta.access.is_declared());
36/// ```
37#[derive(Clone)]
38pub struct RouteDef {
39 /// The HTTP method the route answers.
40 pub method: Method,
41 /// The path relative to the controller, or absolute when it starts with `!`.
42 pub path: String,
43 /// The handler, ready to mount.
44 pub handler: Endpoint,
45 /// Access declaration, guards, limits and documentation.
46 pub meta: RouteMeta,
47}
48
49impl RouteDef {
50 /// A route answering `method` on `path` with `handler`, with no access
51 /// declaration yet.
52 pub fn on<H, T>(method: Method, path: impl Into<String>, handler: H) -> Self
53 where
54 H: Handler<T>,
55 T: 'static,
56 {
57 Self::with_endpoint(method, path, Endpoint::new(handler))
58 }
59
60 /// A route at `method` and `path` that answers a guest with `guest` and a request
61 /// someone is signed in on with `signed_in`: a public site's home page and the app's
62 /// own home at the same address, say. Each handler takes its own extractors, so the
63 /// signed-in one may take an extractor that refuses guests (the user, their unit of
64 /// work) and the guest one is never asked for it. The route is public.
65 ///
66 /// The answer varies by `Cookie` and `Authorization`, and a signed-in reader's answer
67 /// goes out as `Cache-Control: private, no-store` unless its handler kept it private
68 /// itself (`private` or `no-store`, without `public` or `s-maxage`). `Vary` alone is
69 /// not enough: several CDNs ignore `Vary: Cookie`, so a CDN or proxy in front must
70 /// also skip its cache for any request that carries the session cookie (or an
71 /// `Authorization` header), or the guest's page must not be cached at the edge.
72 ///
73 /// ```
74 /// use http::Method;
75 /// use navree_http::{CurrentPrincipal, RouteDef};
76 ///
77 /// let home = RouteDef::on_guest_or(
78 /// Method::GET,
79 /// "!/",
80 /// || async { "the public site" },
81 /// |CurrentPrincipal(who): CurrentPrincipal| async move { format!("hello, {}", who.user_id) },
82 /// )
83 /// .name("home");
84 /// assert!(home.meta.access.public);
85 /// ```
86 pub fn on_guest_or<G, TG, S, TS>(
87 method: Method,
88 path: impl Into<String>,
89 guest: G,
90 signed_in: S,
91 ) -> Self
92 where
93 G: Handler<TG>,
94 TG: 'static,
95 S: Handler<TS>,
96 TS: 'static,
97 {
98 Self::with_endpoint(
99 method,
100 path,
101 Endpoint::guest_or(Endpoint::new(guest), Endpoint::new(signed_in)),
102 )
103 .public()
104 }
105
106 /// A route answering `method` with `endpoint`.
107 pub fn with_endpoint(method: Method, path: impl Into<String>, endpoint: Endpoint) -> Self {
108 Self {
109 meta: RouteMeta {
110 method: method.to_string(),
111 ..RouteMeta::default()
112 },
113 method,
114 path: path.into(),
115 handler: endpoint,
116 }
117 }
118
119 /// No authentication or authorization needed.
120 pub fn public(mut self) -> Self {
121 self.meta.access.public = true;
122 self
123 }
124
125 /// Any signed-in user may call the route (no further authorization).
126 pub fn authenticated(mut self) -> Self {
127 self.meta.access.authenticated = true;
128 self
129 }
130
131 /// Requires any of the roles (checked by the [`RouteAuthorizer`](crate::RouteAuthorizer)).
132 pub fn roles(mut self, roles: &[&str]) -> Self {
133 self.meta
134 .access
135 .roles
136 .extend(roles.iter().map(|r| (*r).to_owned()));
137 self
138 }
139
140 /// Requires the permissions (checked by the [`RouteAuthorizer`](crate::RouteAuthorizer)).
141 pub fn permissions(mut self, permissions: &[&str]) -> Self {
142 self.meta
143 .access
144 .permissions
145 .extend(permissions.iter().map(|p| (*p).to_owned()));
146 self
147 }
148
149 /// Requires the ability `action` on `subject`; with `from`, on the record
150 /// whose id is the path parameter `from`.
151 pub fn can(mut self, action: &str, subject: &str, from: Option<&str>) -> Self {
152 self.meta.access.can = Some(CanSpec {
153 action: action.to_owned(),
154 subject: subject.to_owned(),
155 from: from.map(str::to_owned),
156 });
157 self
158 }
159
160 /// The route name (e.g. `deals.show`).
161 pub fn name(mut self, name: &str) -> Self {
162 self.meta.name = Some(name.to_owned());
163 self
164 }
165
166 /// The code that handles the route, for route listings
167 /// (`DealsController::index`; `#[controller]` sets it).
168 pub fn handler_name(mut self, handler: &str) -> Self {
169 self.meta.handler = Some(handler.to_owned());
170 self
171 }
172
173 /// At most `limit` requests per `per`, per user (per client IP for guests).
174 pub fn throttle(mut self, limit: u32, per: Duration) -> Self {
175 self.meta.throttle = Some(Throttle { limit, per });
176 self
177 }
178
179 /// Overrides the app-wide request timeout (shorter or longer).
180 pub fn timeout(mut self, d: Duration) -> Self {
181 self.meta.timeout = Some(d);
182 self
183 }
184
185 /// Marks the handler as transactional. Informational (route table,
186 /// OpenAPI, logs): navree-db runs every request in a lazy unit of work
187 /// whatever this flag says.
188 pub fn transactional(mut self) -> Self {
189 self.meta.transactional = true;
190 self
191 }
192
193 /// Adds a guard, run before authorization and the handler.
194 pub fn guard(mut self, guard: Arc<dyn Guard>) -> Self {
195 self.meta.guards.push(guard);
196 self
197 }
198
199 /// OpenAPI metadata.
200 pub fn api(mut self, meta: ApiMeta) -> Self {
201 self.meta.api = Some(meta);
202 self
203 }
204
205 /// Writes a custom audit entry with this action after a 2xx response
206 /// (when an `AuditSink` is registered).
207 pub fn audit(mut self, action: &str) -> Self {
208 self.meta.audit_action = Some(action.to_owned());
209 self
210 }
211
212 /// Overrides the app-wide request body limit.
213 pub fn body_limit(mut self, bytes: usize) -> Self {
214 self.meta.body_limit = Some(bytes);
215 self
216 }
217
218 /// Sends the route's responses uncompressed, whatever the client accepts:
219 /// for a page with a secret and reflected input in one body, which a
220 /// compressed length can give away (BREACH).
221 pub fn no_compression(mut self) -> Self {
222 self.meta.no_compression = true;
223 self
224 }
225
226 /// Marks the route as a page. Its errors are pages (a 404 inside the shell, a
227 /// sign-in prompt for a guest) for every client that doesn't ask for JSON
228 /// alone, whatever the client's `Accept` says. Without a mark the `Accept`
229 /// header decides, and a route under `http.api_prefix` is JSON.
230 ///
231 /// Only an app with a module that renders error pages (navree-ui's
232 /// `UiModule`) changes anything.
233 pub fn page(mut self) -> Self {
234 self.meta.kind = RouteKind::Page;
235 self
236 }
237
238 /// Marks the route as data: its errors are always the JSON error body, for
239 /// every client, even one that asks for HTML.
240 pub fn json_only(mut self) -> Self {
241 self.meta.kind = RouteKind::Json;
242 self
243 }
244
245 /// Adds an OpenAPI specification extension to the route's operation
246 /// (`name` should start with `x-`), such as navree-flags'
247 /// `x-navree-flag`. navree-api renders it as a member of the operation
248 /// object; a second call with the same name replaces the value.
249 pub fn extension(
250 mut self,
251 name: impl Into<String>,
252 value: impl Into<serde_json::Value>,
253 ) -> Self {
254 self.meta.extensions.insert(name.into(), value.into());
255 self
256 }
257}
258
259impl fmt::Debug for RouteDef {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 f.debug_struct("RouteDef")
262 .field("method", &self.method)
263 .field("path", &self.path)
264 .field("meta", &self.meta)
265 .finish_non_exhaustive()
266 }
267}
268
269/// Everything known about a route besides its handler. The pipeline inserts
270/// the matched route's `Arc<RouteMeta>` into the request and response
271/// extensions.
272#[derive(Clone, Debug, Default)]
273pub struct RouteMeta {
274 /// The route name.
275 pub name: Option<String>,
276 /// The code that handles it (`DealsController::index`), set by
277 /// `#[controller]` ([`RouteDef::handler_name`]).
278 pub handler: Option<String>,
279 /// Who may call the route.
280 pub access: AccessSpec,
281 /// Custom guards, in order.
282 pub guards: Vec<Arc<dyn Guard>>,
283 /// Per-user rate limit.
284 pub throttle: Option<Throttle>,
285 /// Request timeout override.
286 pub timeout: Option<Duration>,
287 /// Declared transactional (informational; see [`RouteDef::transactional`]).
288 pub transactional: bool,
289 /// OpenAPI metadata.
290 pub api: Option<ApiMeta>,
291 /// Custom audit action written after a 2xx response.
292 pub audit_action: Option<String>,
293 /// Request body limit override.
294 pub body_limit: Option<usize>,
295 /// Responses go out uncompressed (see [`RouteDef::no_compression`]).
296 pub no_compression: bool,
297 /// Whether its errors are pages or JSON (see [`RouteDef::page`]).
298 pub kind: RouteKind,
299 /// The module that registered the route (set when mounted).
300 pub module: Option<&'static str>,
301 /// The id of that module (set when mounted): [`Scoped`](crate::Scoped)
302 /// resolves providers with its visibility.
303 pub module_id: Option<ModuleId>,
304 /// The mounted path, e.g. `/api/v1/deals/{id}` (set when mounted).
305 pub full_path: String,
306 /// The HTTP method, e.g. `GET`.
307 pub method: String,
308 /// OpenAPI specification extensions of the route's operation
309 /// (`x-...` members; see [`RouteDef::extension`]).
310 pub extensions: BTreeMap<String, serde_json::Value>,
311}
312
313/// Who may call a route. A route must declare at least one of these.
314#[derive(Clone, Debug, Default)]
315pub struct AccessSpec {
316 /// No authentication or authorization.
317 pub public: bool,
318 /// Any signed-in user.
319 pub authenticated: bool,
320 /// Any of these roles.
321 pub roles: Vec<String>,
322 /// All of these permissions.
323 pub permissions: Vec<String>,
324 /// An ability check.
325 pub can: Option<CanSpec>,
326}
327
328impl AccessSpec {
329 /// Whether the route declares its access at all (deny by default).
330 pub fn is_declared(&self) -> bool {
331 self.public || self.authenticated || self.needs_authorizer()
332 }
333
334 /// Whether the route declares roles, permissions or an ability, which the
335 /// [`RouteAuthorizer`](crate::RouteAuthorizer) checks.
336 pub fn needs_authorizer(&self) -> bool {
337 !self.roles.is_empty() || !self.permissions.is_empty() || self.can.is_some()
338 }
339
340 /// A short description for `routes` output (`public`, `auth`,
341 /// `roles:admin|manager`, `can:update Deal from id`, ...).
342 pub fn describe(&self) -> String {
343 let mut parts = Vec::new();
344 if self.public {
345 parts.push("public".to_owned());
346 }
347 if self.authenticated {
348 parts.push("auth".to_owned());
349 }
350 if !self.roles.is_empty() {
351 parts.push(format!("roles:{}", self.roles.join("|")));
352 }
353 if !self.permissions.is_empty() {
354 parts.push(format!("permissions:{}", self.permissions.join(",")));
355 }
356 if let Some(can) = &self.can {
357 let mut s = format!("can:{} {}", can.action, can.subject);
358 if let Some(from) = &can.from {
359 s.push_str(" from ");
360 s.push_str(from);
361 }
362 parts.push(s);
363 }
364 if parts.is_empty() {
365 "none".to_owned()
366 } else {
367 parts.join(" ")
368 }
369 }
370}
371
372/// An ability check: `action` on `subject`, optionally on the record whose id
373/// is the path parameter `from`.
374#[derive(Clone, Debug)]
375pub struct CanSpec {
376 /// The action, e.g. `update`.
377 pub action: String,
378 /// The subject type, e.g. `Deal`.
379 pub subject: String,
380 /// The path parameter holding the record id.
381 pub from: Option<String>,
382}
383
384/// A rate limit: `limit` requests per `per`.
385#[derive(Clone, Copy, Debug)]
386pub struct Throttle {
387 /// Requests allowed per window.
388 pub limit: u32,
389 /// The window.
390 pub per: Duration,
391}
392
393/// OpenAPI metadata of a route (read by navree-api).
394#[derive(Clone, Debug, Default)]
395pub struct ApiMeta {
396 /// One-line summary.
397 pub summary: Option<String>,
398 /// Longer description.
399 pub description: Option<String>,
400 /// Tags (groups in the docs UI).
401 pub tags: Vec<String>,
402 /// Documented error statuses (rendered as JSON error
403 /// responses).
404 pub responses: Vec<u16>,
405 /// The success status; `0` means the method's default (200).
406 pub success_status: u16,
407 /// The request body schema.
408 pub request: Option<SchemaFn>,
409 /// The response body schema.
410 pub response: Option<SchemaFn>,
411 /// The list query of a route that takes `List<R>` (`#[api(query = R)]`):
412 /// the document describes its `filter`, `sort`, `search` and paging
413 /// parameters. See [`list_spec`].
414 pub query: Option<ListSpecFn>,
415}
416
417/// Returns `(schema name, JSON schema)`; see [`schema_fn`].
418pub type SchemaFn = fn() -> (String, serde_json::Value);
419
420/// Returns the [`ListSpec`](crate::list::ListSpec) of a list query; see
421/// [`list_spec`].
422pub type ListSpecFn = fn() -> crate::list::ListSpec;
423
424/// The list query `R` allows, usable as a [`ListSpecFn`]
425/// (`list_spec::<Deals>`), so route macros never need navree-api.
426pub fn list_spec<R: crate::list::ListResource>() -> crate::list::ListSpec {
427 R::SPEC
428}
429
430/// The OpenAPI schema of `T` as `(name, JSON schema)`, usable as a
431/// [`SchemaFn`] (`schema_fn::<CreateDeal>`), so route macros never need navree-api.
432///
433/// Schemas that `T` references (`$ref: "#/components/schemas/Inner"`) are
434/// carried in the extension member `x-navree-components` (`{name: schema}`);
435/// navree-api hoists them into `components.schemas` and removes the member.
436pub fn schema_fn<T: navree_openapi::ToSchema>() -> (String, serde_json::Value) {
437 let mut schema = serde_json::to_value(T::schema()).unwrap_or_default();
438 let mut referenced = Vec::new();
439 T::schemas(&mut referenced);
440 navree_openapi::__private::attach_components(&mut schema, referenced);
441 if let Some(object) = schema.as_object_mut() {
442 object.insert(
443 "x-navree-type".to_owned(),
444 std::any::type_name::<T>().into(),
445 );
446 }
447 (T::name().into_owned(), schema)
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 #[test]
455 fn builders_fill_the_access_spec() {
456 let route = RouteDef::on(Method::POST, "/", || async {})
457 .roles(&["admin", "manager"])
458 .permissions(&["deals.manage"])
459 .can("update", "Deal", Some("id"));
460 assert_eq!(route.meta.method, "POST");
461 assert!(route.meta.access.is_declared());
462 assert!(route.meta.access.needs_authorizer());
463 assert_eq!(
464 route.meta.access.describe(),
465 "roles:admin|manager permissions:deals.manage can:update Deal from id"
466 );
467 }
468
469 #[tokio::test]
470 async fn on_routes_exactly_the_declared_method() {
471 use tower::ServiceExt;
472
473 let route = RouteDef::on(Method::PATCH, "/x", || async { "patched" }).public();
474 assert_eq!(route.method, Method::PATCH);
475 assert_eq!(route.meta.method, "PATCH");
476 let mut router = crate::routing::Router::new();
477 router
478 .try_route(route.method.clone(), "/x", route.handler.clone())
479 .unwrap();
480 let call = |method: Method| {
481 let router = router.clone();
482 async move {
483 let request = http::Request::builder()
484 .method(method)
485 .uri("/x")
486 .body(crate::body::Body::empty())
487 .unwrap();
488 router.oneshot(request).await.unwrap().status()
489 }
490 };
491 assert_eq!(call(Method::PATCH).await, http::StatusCode::OK);
492 assert_eq!(
493 call(Method::GET).await,
494 http::StatusCode::METHOD_NOT_ALLOWED
495 );
496 }
497
498 #[test]
499 fn extensions_are_collected_by_name() {
500 let route = RouteDef::on(Method::GET, "/", || async {})
501 .public()
502 .extension("x-navree-flag", "new-pipeline")
503 .extension("x-internal", serde_json::json!({"team": "deals"}))
504 .extension("x-navree-flag", "ai-summaries");
505 assert_eq!(route.meta.extensions.len(), 2);
506 assert_eq!(
507 route.meta.extensions["x-navree-flag"],
508 serde_json::json!("ai-summaries")
509 );
510 assert_eq!(
511 route.meta.extensions["x-internal"]["team"],
512 serde_json::json!("deals")
513 );
514 assert!(RouteMeta::default().extensions.is_empty());
515 }
516
517 #[test]
518 fn nothing_declared_is_not_declared() {
519 let route = RouteDef::on(Method::GET, "/", || async {}).name("x");
520 assert!(!route.meta.access.is_declared());
521 assert_eq!(route.meta.access.describe(), "none");
522 let route = route.authenticated();
523 assert!(route.meta.access.is_declared() && !route.meta.access.needs_authorizer());
524 }
525
526 #[derive(navree_openapi::ToSchema)]
527 #[allow(dead_code)]
528 struct Owner {
529 id: String,
530 }
531
532 #[derive(navree_openapi::ToSchema)]
533 #[allow(dead_code)]
534 struct Deal {
535 title: String,
536 owner: Owner,
537 }
538
539 #[test]
540 fn schema_fn_returns_name_schema_and_referenced_components() {
541 let f: SchemaFn = schema_fn::<Deal>;
542 let (name, schema) = f();
543 assert_eq!(name, "Deal");
544 assert_eq!(schema["type"], "object");
545 assert!(schema["properties"]["title"].is_object());
546 assert_eq!(
547 schema["properties"]["owner"]["$ref"],
548 "#/components/schemas/Owner"
549 );
550 assert_eq!(
551 schema["x-navree-components"]["Owner"]["properties"]["id"]["type"],
552 "string"
553 );
554
555 let (name, schema) = schema_fn::<Owner>();
556 assert_eq!(name, "Owner");
557 assert!(schema.get("x-navree-components").is_none());
558 }
559}