navree-http 1.1.0

Navree HttpModule: Navree's router and extractors, default Tower layers, JSON errors, controllers and route metadata.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! [`RouteDef`] and its metadata: access declaration, guards, throttle,
//! timeout, body limit, audit action and OpenAPI metadata.

use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use http::Method;
use navree_kernel::ModuleId;

use crate::Guard;
use crate::error_pages::RouteKind;
use crate::handler::{Endpoint, Handler};

/// One route: a method, a path, a [`Handler`] and its metadata.
///
/// The path is relative to the controller (`/{id}`), with `{param}` and
/// `{*rest}` captures (see [`routing`](crate::routing)). A path starting with
/// `!` is absolute: it is mounted as written, without the API prefix,
/// version or controller prefix (`!/csrf-cookie`, `!/health/live`).
///
/// Every route must declare its access ([`public`](RouteDef::public),
/// [`authenticated`](RouteDef::authenticated), [`roles`](RouteDef::roles),
/// [`permissions`](RouteDef::permissions) or [`can`](RouteDef::can)); the app
/// refuses to boot otherwise.
///
/// ```
/// use http::Method;
/// use navree_http::RouteDef;
///
/// let route = RouteDef::on(Method::GET, "/{id}", || async { "deal" })
///     .name("deals.show")
///     .can("read", "Deal", Some("id"));
/// assert!(route.meta.access.is_declared());
/// ```
#[derive(Clone)]
pub struct RouteDef {
    /// The HTTP method the route answers.
    pub method: Method,
    /// The path relative to the controller, or absolute when it starts with `!`.
    pub path: String,
    /// The handler, ready to mount.
    pub handler: Endpoint,
    /// Access declaration, guards, limits and documentation.
    pub meta: RouteMeta,
}

impl RouteDef {
    /// A route answering `method` on `path` with `handler`, with no access
    /// declaration yet.
    pub fn on<H, T>(method: Method, path: impl Into<String>, handler: H) -> Self
    where
        H: Handler<T>,
        T: 'static,
    {
        Self::with_endpoint(method, path, Endpoint::new(handler))
    }

    /// A route at `method` and `path` that answers a guest with `guest` and a request
    /// someone is signed in on with `signed_in`: a public site's home page and the app's
    /// own home at the same address, say. Each handler takes its own extractors, so the
    /// signed-in one may take an extractor that refuses guests (the user, their unit of
    /// work) and the guest one is never asked for it. The route is public.
    ///
    /// The answer varies by `Cookie` and `Authorization`, and a signed-in reader's answer
    /// goes out as `Cache-Control: private, no-store` unless its handler kept it private
    /// itself (`private` or `no-store`, without `public` or `s-maxage`). `Vary` alone is
    /// not enough: several CDNs ignore `Vary: Cookie`, so a CDN or proxy in front must
    /// also skip its cache for any request that carries the session cookie (or an
    /// `Authorization` header), or the guest's page must not be cached at the edge.
    ///
    /// ```
    /// use http::Method;
    /// use navree_http::{CurrentPrincipal, RouteDef};
    ///
    /// let home = RouteDef::on_guest_or(
    ///     Method::GET,
    ///     "!/",
    ///     || async { "the public site" },
    ///     |CurrentPrincipal(who): CurrentPrincipal| async move { format!("hello, {}", who.user_id) },
    /// )
    /// .name("home");
    /// assert!(home.meta.access.public);
    /// ```
    pub fn on_guest_or<G, TG, S, TS>(
        method: Method,
        path: impl Into<String>,
        guest: G,
        signed_in: S,
    ) -> Self
    where
        G: Handler<TG>,
        TG: 'static,
        S: Handler<TS>,
        TS: 'static,
    {
        Self::with_endpoint(
            method,
            path,
            Endpoint::guest_or(Endpoint::new(guest), Endpoint::new(signed_in)),
        )
        .public()
    }

    /// A route answering `method` with `endpoint`.
    pub fn with_endpoint(method: Method, path: impl Into<String>, endpoint: Endpoint) -> Self {
        Self {
            meta: RouteMeta {
                method: method.to_string(),
                ..RouteMeta::default()
            },
            method,
            path: path.into(),
            handler: endpoint,
        }
    }

    /// No authentication or authorization needed.
    pub fn public(mut self) -> Self {
        self.meta.access.public = true;
        self
    }

    /// Any signed-in user may call the route (no further authorization).
    pub fn authenticated(mut self) -> Self {
        self.meta.access.authenticated = true;
        self
    }

    /// Requires any of the roles (checked by the [`RouteAuthorizer`](crate::RouteAuthorizer)).
    pub fn roles(mut self, roles: &[&str]) -> Self {
        self.meta
            .access
            .roles
            .extend(roles.iter().map(|r| (*r).to_owned()));
        self
    }

    /// Requires the permissions (checked by the [`RouteAuthorizer`](crate::RouteAuthorizer)).
    pub fn permissions(mut self, permissions: &[&str]) -> Self {
        self.meta
            .access
            .permissions
            .extend(permissions.iter().map(|p| (*p).to_owned()));
        self
    }

    /// Requires the ability `action` on `subject`; with `from`, on the record
    /// whose id is the path parameter `from`.
    pub fn can(mut self, action: &str, subject: &str, from: Option<&str>) -> Self {
        self.meta.access.can = Some(CanSpec {
            action: action.to_owned(),
            subject: subject.to_owned(),
            from: from.map(str::to_owned),
        });
        self
    }

    /// The route name (e.g. `deals.show`).
    pub fn name(mut self, name: &str) -> Self {
        self.meta.name = Some(name.to_owned());
        self
    }

    /// The code that handles the route, for route listings
    /// (`DealsController::index`; `#[controller]` sets it).
    pub fn handler_name(mut self, handler: &str) -> Self {
        self.meta.handler = Some(handler.to_owned());
        self
    }

    /// At most `limit` requests per `per`, per user (per client IP for guests).
    pub fn throttle(mut self, limit: u32, per: Duration) -> Self {
        self.meta.throttle = Some(Throttle { limit, per });
        self
    }

    /// Overrides the app-wide request timeout (shorter or longer).
    pub fn timeout(mut self, d: Duration) -> Self {
        self.meta.timeout = Some(d);
        self
    }

    /// Marks the handler as transactional. Informational (route table,
    /// OpenAPI, logs): navree-db runs every request in a lazy unit of work
    /// whatever this flag says.
    pub fn transactional(mut self) -> Self {
        self.meta.transactional = true;
        self
    }

    /// Adds a guard, run before authorization and the handler.
    pub fn guard(mut self, guard: Arc<dyn Guard>) -> Self {
        self.meta.guards.push(guard);
        self
    }

    /// OpenAPI metadata.
    pub fn api(mut self, meta: ApiMeta) -> Self {
        self.meta.api = Some(meta);
        self
    }

    /// Writes a custom audit entry with this action after a 2xx response
    /// (when an `AuditSink` is registered).
    pub fn audit(mut self, action: &str) -> Self {
        self.meta.audit_action = Some(action.to_owned());
        self
    }

    /// Overrides the app-wide request body limit.
    pub fn body_limit(mut self, bytes: usize) -> Self {
        self.meta.body_limit = Some(bytes);
        self
    }

    /// Sends the route's responses uncompressed, whatever the client accepts:
    /// for a page with a secret and reflected input in one body, which a
    /// compressed length can give away (BREACH).
    pub fn no_compression(mut self) -> Self {
        self.meta.no_compression = true;
        self
    }

    /// Marks the route as a page. Its errors are pages (a 404 inside the shell, a
    /// sign-in prompt for a guest) for every client that doesn't ask for JSON
    /// alone, whatever the client's `Accept` says. Without a mark the `Accept`
    /// header decides, and a route under `http.api_prefix` is JSON.
    ///
    /// Only an app with a module that renders error pages (navree-ui's
    /// `UiModule`) changes anything.
    pub fn page(mut self) -> Self {
        self.meta.kind = RouteKind::Page;
        self
    }

    /// Marks the route as data: its errors are always the JSON error body, for
    /// every client, even one that asks for HTML.
    pub fn json_only(mut self) -> Self {
        self.meta.kind = RouteKind::Json;
        self
    }

    /// Adds an OpenAPI specification extension to the route's operation
    /// (`name` should start with `x-`), such as navree-flags'
    /// `x-navree-flag`. navree-api renders it as a member of the operation
    /// object; a second call with the same name replaces the value.
    pub fn extension(
        mut self,
        name: impl Into<String>,
        value: impl Into<serde_json::Value>,
    ) -> Self {
        self.meta.extensions.insert(name.into(), value.into());
        self
    }
}

impl fmt::Debug for RouteDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RouteDef")
            .field("method", &self.method)
            .field("path", &self.path)
            .field("meta", &self.meta)
            .finish_non_exhaustive()
    }
}

/// Everything known about a route besides its handler. The pipeline inserts
/// the matched route's `Arc<RouteMeta>` into the request and response
/// extensions.
#[derive(Clone, Debug, Default)]
pub struct RouteMeta {
    /// The route name.
    pub name: Option<String>,
    /// The code that handles it (`DealsController::index`), set by
    /// `#[controller]` ([`RouteDef::handler_name`]).
    pub handler: Option<String>,
    /// Who may call the route.
    pub access: AccessSpec,
    /// Custom guards, in order.
    pub guards: Vec<Arc<dyn Guard>>,
    /// Per-user rate limit.
    pub throttle: Option<Throttle>,
    /// Request timeout override.
    pub timeout: Option<Duration>,
    /// Declared transactional (informational; see [`RouteDef::transactional`]).
    pub transactional: bool,
    /// OpenAPI metadata.
    pub api: Option<ApiMeta>,
    /// Custom audit action written after a 2xx response.
    pub audit_action: Option<String>,
    /// Request body limit override.
    pub body_limit: Option<usize>,
    /// Responses go out uncompressed (see [`RouteDef::no_compression`]).
    pub no_compression: bool,
    /// Whether its errors are pages or JSON (see [`RouteDef::page`]).
    pub kind: RouteKind,
    /// The module that registered the route (set when mounted).
    pub module: Option<&'static str>,
    /// The id of that module (set when mounted): [`Scoped`](crate::Scoped)
    /// resolves providers with its visibility.
    pub module_id: Option<ModuleId>,
    /// The mounted path, e.g. `/api/v1/deals/{id}` (set when mounted).
    pub full_path: String,
    /// The HTTP method, e.g. `GET`.
    pub method: String,
    /// OpenAPI specification extensions of the route's operation
    /// (`x-...` members; see [`RouteDef::extension`]).
    pub extensions: BTreeMap<String, serde_json::Value>,
}

/// Who may call a route. A route must declare at least one of these.
#[derive(Clone, Debug, Default)]
pub struct AccessSpec {
    /// No authentication or authorization.
    pub public: bool,
    /// Any signed-in user.
    pub authenticated: bool,
    /// Any of these roles.
    pub roles: Vec<String>,
    /// All of these permissions.
    pub permissions: Vec<String>,
    /// An ability check.
    pub can: Option<CanSpec>,
}

impl AccessSpec {
    /// Whether the route declares its access at all (deny by default).
    pub fn is_declared(&self) -> bool {
        self.public || self.authenticated || self.needs_authorizer()
    }

    /// Whether the route declares roles, permissions or an ability, which the
    /// [`RouteAuthorizer`](crate::RouteAuthorizer) checks.
    pub fn needs_authorizer(&self) -> bool {
        !self.roles.is_empty() || !self.permissions.is_empty() || self.can.is_some()
    }

    /// A short description for `routes` output (`public`, `auth`,
    /// `roles:admin|manager`, `can:update Deal from id`, ...).
    pub fn describe(&self) -> String {
        let mut parts = Vec::new();
        if self.public {
            parts.push("public".to_owned());
        }
        if self.authenticated {
            parts.push("auth".to_owned());
        }
        if !self.roles.is_empty() {
            parts.push(format!("roles:{}", self.roles.join("|")));
        }
        if !self.permissions.is_empty() {
            parts.push(format!("permissions:{}", self.permissions.join(",")));
        }
        if let Some(can) = &self.can {
            let mut s = format!("can:{} {}", can.action, can.subject);
            if let Some(from) = &can.from {
                s.push_str(" from ");
                s.push_str(from);
            }
            parts.push(s);
        }
        if parts.is_empty() {
            "none".to_owned()
        } else {
            parts.join(" ")
        }
    }
}

/// An ability check: `action` on `subject`, optionally on the record whose id
/// is the path parameter `from`.
#[derive(Clone, Debug)]
pub struct CanSpec {
    /// The action, e.g. `update`.
    pub action: String,
    /// The subject type, e.g. `Deal`.
    pub subject: String,
    /// The path parameter holding the record id.
    pub from: Option<String>,
}

/// A rate limit: `limit` requests per `per`.
#[derive(Clone, Copy, Debug)]
pub struct Throttle {
    /// Requests allowed per window.
    pub limit: u32,
    /// The window.
    pub per: Duration,
}

/// OpenAPI metadata of a route (read by navree-api).
#[derive(Clone, Debug, Default)]
pub struct ApiMeta {
    /// One-line summary.
    pub summary: Option<String>,
    /// Longer description.
    pub description: Option<String>,
    /// Tags (groups in the docs UI).
    pub tags: Vec<String>,
    /// Documented error statuses (rendered as JSON error
    /// responses).
    pub responses: Vec<u16>,
    /// The success status; `0` means the method's default (200).
    pub success_status: u16,
    /// The request body schema.
    pub request: Option<SchemaFn>,
    /// The response body schema.
    pub response: Option<SchemaFn>,
    /// The list query of a route that takes `List<R>` (`#[api(query = R)]`):
    /// the document describes its `filter`, `sort`, `search` and paging
    /// parameters. See [`list_spec`].
    pub query: Option<ListSpecFn>,
}

/// Returns `(schema name, JSON schema)`; see [`schema_fn`].
pub type SchemaFn = fn() -> (String, serde_json::Value);

/// Returns the [`ListSpec`](crate::list::ListSpec) of a list query; see
/// [`list_spec`].
pub type ListSpecFn = fn() -> crate::list::ListSpec;

/// The list query `R` allows, usable as a [`ListSpecFn`]
/// (`list_spec::<Deals>`), so route macros never need navree-api.
pub fn list_spec<R: crate::list::ListResource>() -> crate::list::ListSpec {
    R::SPEC
}

/// The OpenAPI schema of `T` as `(name, JSON schema)`, usable as a
/// [`SchemaFn`] (`schema_fn::<CreateDeal>`), so route macros never need navree-api.
///
/// Schemas that `T` references (`$ref: "#/components/schemas/Inner"`) are
/// carried in the extension member `x-navree-components` (`{name: schema}`);
/// navree-api hoists them into `components.schemas` and removes the member.
pub fn schema_fn<T: navree_openapi::ToSchema>() -> (String, serde_json::Value) {
    let mut schema = serde_json::to_value(T::schema()).unwrap_or_default();
    let mut referenced = Vec::new();
    T::schemas(&mut referenced);
    navree_openapi::__private::attach_components(&mut schema, referenced);
    if let Some(object) = schema.as_object_mut() {
        object.insert(
            "x-navree-type".to_owned(),
            std::any::type_name::<T>().into(),
        );
    }
    (T::name().into_owned(), schema)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builders_fill_the_access_spec() {
        let route = RouteDef::on(Method::POST, "/", || async {})
            .roles(&["admin", "manager"])
            .permissions(&["deals.manage"])
            .can("update", "Deal", Some("id"));
        assert_eq!(route.meta.method, "POST");
        assert!(route.meta.access.is_declared());
        assert!(route.meta.access.needs_authorizer());
        assert_eq!(
            route.meta.access.describe(),
            "roles:admin|manager permissions:deals.manage can:update Deal from id"
        );
    }

    #[tokio::test]
    async fn on_routes_exactly_the_declared_method() {
        use tower::ServiceExt;

        let route = RouteDef::on(Method::PATCH, "/x", || async { "patched" }).public();
        assert_eq!(route.method, Method::PATCH);
        assert_eq!(route.meta.method, "PATCH");
        let mut router = crate::routing::Router::new();
        router
            .try_route(route.method.clone(), "/x", route.handler.clone())
            .unwrap();
        let call = |method: Method| {
            let router = router.clone();
            async move {
                let request = http::Request::builder()
                    .method(method)
                    .uri("/x")
                    .body(crate::body::Body::empty())
                    .unwrap();
                router.oneshot(request).await.unwrap().status()
            }
        };
        assert_eq!(call(Method::PATCH).await, http::StatusCode::OK);
        assert_eq!(
            call(Method::GET).await,
            http::StatusCode::METHOD_NOT_ALLOWED
        );
    }

    #[test]
    fn extensions_are_collected_by_name() {
        let route = RouteDef::on(Method::GET, "/", || async {})
            .public()
            .extension("x-navree-flag", "new-pipeline")
            .extension("x-internal", serde_json::json!({"team": "deals"}))
            .extension("x-navree-flag", "ai-summaries");
        assert_eq!(route.meta.extensions.len(), 2);
        assert_eq!(
            route.meta.extensions["x-navree-flag"],
            serde_json::json!("ai-summaries")
        );
        assert_eq!(
            route.meta.extensions["x-internal"]["team"],
            serde_json::json!("deals")
        );
        assert!(RouteMeta::default().extensions.is_empty());
    }

    #[test]
    fn nothing_declared_is_not_declared() {
        let route = RouteDef::on(Method::GET, "/", || async {}).name("x");
        assert!(!route.meta.access.is_declared());
        assert_eq!(route.meta.access.describe(), "none");
        let route = route.authenticated();
        assert!(route.meta.access.is_declared() && !route.meta.access.needs_authorizer());
    }

    #[derive(navree_openapi::ToSchema)]
    #[allow(dead_code)]
    struct Owner {
        id: String,
    }

    #[derive(navree_openapi::ToSchema)]
    #[allow(dead_code)]
    struct Deal {
        title: String,
        owner: Owner,
    }

    #[test]
    fn schema_fn_returns_name_schema_and_referenced_components() {
        let f: SchemaFn = schema_fn::<Deal>;
        let (name, schema) = f();
        assert_eq!(name, "Deal");
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["title"].is_object());
        assert_eq!(
            schema["properties"]["owner"]["$ref"],
            "#/components/schemas/Owner"
        );
        assert_eq!(
            schema["x-navree-components"]["Owner"]["properties"]["id"]["type"],
            "string"
        );

        let (name, schema) = schema_fn::<Owner>();
        assert_eq!(name, "Owner");
        assert!(schema.get("x-navree-components").is_none());
    }
}