Skip to main content

navree_http/
mount.rs

1//! [`Mount`]: any tower service under a path prefix, inside the app's
2//! pipeline, and [`ModuleBuilderMountExt`], how a module declares one.
3
4use std::convert::Infallible;
5use std::fmt;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8use std::time::Duration;
9
10use bytes::Bytes;
11use http::header::UPGRADE;
12use http::uri::PathAndQuery;
13use http::{Method, StatusCode, Uri};
14use navree_kernel::{AppContext, BoxError, BoxFuture, ModuleBuilder};
15use tower::util::BoxCloneSyncService;
16use tower::{Service, ServiceExt};
17
18use crate::body::{Body, BodyLimit, HttpBody, body_error_in};
19use crate::error::AppError;
20use crate::extract::Request;
21use crate::pipeline::AsWritten;
22use crate::response::{IntoResponse, Response};
23use crate::router::access_problems;
24use crate::routing::{PathParams, PathPattern, Segment};
25use crate::{CanSpec, Guard, RouteMeta, Throttle};
26
27/// A mounted service as the app holds it: the app's request and response,
28/// any error.
29pub(crate) type MountService = BoxCloneSyncService<Request, Response, BoxError>;
30
31/// What a prefix must look like: the text of every refused prefix.
32const PREFIX_RULE: &str = "a prefix starts with `/` but not with `/_`, has no `{`, `}`, `*`, `..` or `//`, and does not end with `/`";
33
34/// The message of a request that would take over the connection.
35const TAKES_OVER: &str =
36    "A mounted service answers requests; it does not take over the connection.";
37
38/// The message of a path with an empty segment below a prefix.
39const EMPTY_SEGMENT: &str = "Invalid URL: the path has an empty segment";
40
41/// Any tower service under a path prefix, inside the app's pipeline.
42///
43/// A module declares it with
44/// [`m.mount(..)`](ModuleBuilderMountExt::mount). It answers the prefix
45/// itself and every path below it, for every method unless
46/// [`methods`](Mount::methods) names some, behind the pipeline a route has:
47/// request id, request context and client address, the app's global layers
48/// (session and CSRF among them), authentication, then on every request the
49/// mount's access check, guards, throttle, timeout and body limit. One of
50/// [`public`](Mount::public), [`authenticated`](Mount::authenticated),
51/// [`roles`](Mount::roles), [`permissions`](Mount::permissions) or
52/// [`can`](Mount::can) is required, as for a route: a mount without an access
53/// declaration fails the boot, and so does one whose prefix is malformed,
54/// starts with `/_` (the framework's own paths), or overlaps a route or
55/// another mount.
56///
57/// The service sees the request as the app received it but for its URI:
58/// scheme and authority as received, and for the path `/` followed by the
59/// rest of the path below the prefix as written (`/` for the prefix itself),
60/// then `?` and the query as written. Nothing is decoded, so `%2F`, `%3F` and
61/// `%23` reach the service as they were sent. Before that the router has
62/// refused a `.` or `..` segment (raw, encoded, or once the rest of the path
63/// is decoded), a backslash, a NUL and bytes that are not UTF-8; the mount
64/// refuses an empty segment below the prefix (`//`, also once `%2F` is read
65/// as `/`) with 400. `/khata/` and the prefix in another case are not found.
66/// A service that decodes its own path still treats it as untrusted input.
67///
68/// A request with an `Upgrade` header (a WebSocket or h2c handshake) or the
69/// method `CONNECT` never reaches the service: a mounted service answers
70/// requests, it does not take over the connection. One that reaches the mount
71/// is answered 501 after the access check. With [`methods`](Mount::methods),
72/// a method the list leaves out, `CONNECT` among them, is the router's 405
73/// before the access check, as for a route; `HEAD` runs the `GET` answer when
74/// `GET` is listed, and `OPTIONS` is a 204 with `Allow`.
75///
76/// The body is cut off at the mount's limit also when it comes without a
77/// length. A panic in the service answers 500, as in a handler. An
78/// error of the service answers 500 with the error as its source, which the
79/// app's error mappings (`m.map_error`) see and the log records; one that
80/// comes from the body's limit or the server's read timeout answers 413 or
81/// 408, as the body extractors do. A response below 500 the service writes
82/// goes out as written, a 4xx included: its status, headers and body are the
83/// service's (a 422 with a plain-text body stays a 422 with that body). A 5xx
84/// with no body or a short plain-text one (of known length, up to 16 KiB)
85/// takes the app's JSON error shape, its text logged, never sent; any other
86/// 5xx body (JSON, a longer or streamed text) goes out as written. The
87/// pipeline adds `X-Request-Id`, and the default security headers where the
88/// service set none.
89///
90/// The service is built in `register`; it reaches the app's providers through
91/// the `AppContext` in each request's extensions.
92///
93/// ```
94/// use std::time::Duration;
95///
96/// use navree_http::extract::Request;
97/// use navree_http::{AppRouter, ModuleBuilderMountExt, Mount};
98/// use navree_kernel::{Module, ModuleBuilder};
99///
100/// struct LedgerModule;
101///
102/// impl Module for LedgerModule {
103///     fn register(&self, m: &mut ModuleBuilder) {
104///         // The service of another crate; here, one that answers every path.
105///         let khata = AppRouter::from_handler(|request: Request| async move {
106///             format!("the khata at {}", request.uri().path())
107///         });
108///         m.mount(
109///             Mount::new("/khata", khata)
110///                 .authenticated()
111///                 .throttle(60, Duration::from_secs(60)),
112///         );
113///     }
114/// }
115/// ```
116#[derive(Clone)]
117pub struct Mount {
118    /// Where the service answers: absolute, not under `http.api_prefix`.
119    prefix: String,
120    /// The service, its body taken as the app's and its error boxed.
121    service: MountService,
122    /// The access declaration and the rest of a route's metadata.
123    meta: RouteMeta,
124    /// The methods it answers; `None` for every method.
125    methods: Option<Vec<Method>>,
126}
127
128impl Mount {
129    /// `service` at `prefix` (`/khata`, absolute: not under
130    /// `http.api_prefix`): it sees requests for `prefix` and `prefix/...` with
131    /// the prefix taken off the path, raw (`/khata/v1/items%3Fx` arrives as
132    /// `/v1/items%3Fx`). Its access is declared next.
133    pub fn new<S, B>(prefix: &str, service: S) -> Mount
134    where
135        S: Service<Request, Response = http::Response<B>> + Clone + Send + Sync + 'static,
136        S::Error: Into<BoxError>,
137        S::Future: Send + 'static,
138        B: HttpBody<Data = Bytes> + Send + 'static,
139        B::Error: Into<BoxError>,
140    {
141        let service = service
142            .map_response(|response: http::Response<B>| response.map(Body::new))
143            .map_err(|error: S::Error| -> BoxError { error.into() });
144        Mount {
145            prefix: prefix.to_owned(),
146            service: BoxCloneSyncService::new(service),
147            meta: RouteMeta::default(),
148            methods: None,
149        }
150    }
151
152    /// No authentication or authorization: every request reaches the service.
153    pub fn public(mut self) -> Mount {
154        self.meta.access.public = true;
155        self
156    }
157
158    /// Any signed-in user may call the mount (no further authorization).
159    pub fn authenticated(mut self) -> Mount {
160        self.meta.access.authenticated = true;
161        self
162    }
163
164    /// Requires any of the roles (checked by the
165    /// [`RouteAuthorizer`](crate::RouteAuthorizer) on every request).
166    pub fn roles(mut self, roles: &[&str]) -> Mount {
167        self.meta
168            .access
169            .roles
170            .extend(roles.iter().map(|role| (*role).to_owned()));
171        self
172    }
173
174    /// Requires the permissions (checked by the
175    /// [`RouteAuthorizer`](crate::RouteAuthorizer) on every request).
176    pub fn permissions(mut self, permissions: &[&str]) -> Mount {
177        self.meta.access.permissions.extend(
178            permissions
179                .iter()
180                .map(|permission| (*permission).to_owned()),
181        );
182        self
183    }
184
185    /// Requires the ability `action` on the type `subject` (checked by the
186    /// [`RouteAuthorizer`](crate::RouteAuthorizer) on every request). A mount
187    /// has no path parameter, so no record is named.
188    pub fn can(mut self, action: &str, subject: &str) -> Mount {
189        self.meta.access.can = Some(CanSpec {
190            action: action.to_owned(),
191            subject: subject.to_owned(),
192            from: None,
193        });
194        self
195    }
196
197    /// Adds a guard, run on every request before authorization and the
198    /// service.
199    pub fn guard(mut self, guard: Arc<dyn Guard>) -> Mount {
200        self.meta.guards.push(guard);
201        self
202    }
203
204    /// At most `limit` requests per `per`, per user (per client IP for
205    /// guests), counted for the whole mount: every path and method under the
206    /// prefix takes from one budget.
207    pub fn throttle(mut self, limit: u32, per: Duration) -> Mount {
208        self.meta.throttle = Some(Throttle { limit, per });
209        self
210    }
211
212    /// Overrides the app-wide request timeout (shorter or longer).
213    pub fn timeout(mut self, d: Duration) -> Mount {
214        self.meta.timeout = Some(d);
215        self
216    }
217
218    /// Overrides the app-wide request body limit: a request that declares a
219    /// longer body is refused before the service is called, and a body sent
220    /// without a length ends in an error once it passes the limit.
221    pub fn body_limit(mut self, bytes: usize) -> Mount {
222        self.meta.body_limit = Some(bytes);
223        self
224    }
225
226    /// The mount's name, for logs and the `routes` command.
227    pub fn name(mut self, name: &str) -> Mount {
228        self.meta.name = Some(name.to_owned());
229        self
230    }
231
232    /// Only these methods (default: every method, extension methods such as
233    /// `PROPFIND` included; an empty list fails the boot). A method named
234    /// twice is kept once. With a list, `HEAD` runs the `GET` answer without
235    /// its body and `OPTIONS` lists the methods, as for a route.
236    pub fn methods(mut self, methods: &[Method]) -> Mount {
237        let mut kept: Vec<Method> = Vec::with_capacity(methods.len());
238        for method in methods {
239            if !kept.contains(method) {
240                kept.push(method.clone());
241            }
242        }
243        self.methods = Some(kept);
244        self
245    }
246}
247
248impl fmt::Debug for Mount {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        f.debug_struct("Mount")
251            .field("prefix", &self.prefix)
252            .field("methods", &self.methods)
253            .field("access", &self.meta.access.describe())
254            .finish_non_exhaustive()
255    }
256}
257
258/// Mounting tower services on a [`ModuleBuilder`].
259///
260/// ```
261/// use std::convert::Infallible;
262///
263/// use http::Method;
264/// use navree_http::body::Body;
265/// use navree_http::extract::Request;
266/// use navree_http::{ModuleBuilderMountExt, Mount};
267/// use navree_kernel::{Module, ModuleBuilder};
268///
269/// struct BalanceModule;
270///
271/// impl Module for BalanceModule {
272///     fn register(&self, m: &mut ModuleBuilder) {
273///         // A service of another crate, written with tower alone.
274///         let balance = tower::service_fn(|_request: Request| async {
275///             Ok::<_, Infallible>(http::Response::new(Body::from("₹1,00,000")))
276///         });
277///         m.mount(
278///             Mount::new("/balance", balance)
279///                 .public()
280///                 .methods(&[Method::GET]),
281///         );
282///     }
283/// }
284/// ```
285pub trait ModuleBuilderMountExt {
286    /// Serves `mount`'s service under its prefix. The boot checks the mount
287    /// with the app's routes and other mounts (see [`Mount`]).
288    fn mount(&mut self, mount: Mount) -> &mut Self;
289}
290
291impl ModuleBuilderMountExt for ModuleBuilder {
292    fn mount(&mut self, mount: Mount) -> &mut Self {
293        self.contribute(MountRegistration(mount))
294    }
295}
296
297/// A mount declared by a module (a contribution).
298#[derive(Clone)]
299pub(crate) struct MountRegistration(pub(crate) Mount);
300
301/// A mount ready to check and serve: its metadata names it as one route,
302/// `{prefix}/{*rest}`, of the module that declared it.
303pub(crate) struct MountEntry {
304    pub(crate) prefix: String,
305    pub(crate) service: MountService,
306    pub(crate) meta: RouteMeta,
307    pub(crate) methods: Option<Vec<Method>>,
308    pub(crate) module: &'static str,
309}
310
311/// Every mount of the app, modules in dependency order, each module's in the
312/// order declared.
313pub(crate) fn collect_mounts(ctx: &AppContext) -> Vec<MountEntry> {
314    ctx.contributions::<MountRegistration>()
315        .into_iter()
316        .map(|contributed| {
317            let mount = contributed.value.0.clone();
318            let mut meta = mount.meta;
319            meta.full_path = format!("{}/{{*rest}}", mount.prefix);
320            meta.method = match &mount.methods {
321                None => "*".to_owned(),
322                Some(methods) => methods
323                    .iter()
324                    .map(Method::as_str)
325                    .collect::<Vec<_>>()
326                    .join(","),
327            };
328            meta.module = Some(contributed.module.name);
329            meta.module_id = Some(contributed.module.id);
330            MountEntry {
331                prefix: mount.prefix,
332                service: mount.service,
333                meta,
334                methods: mount.methods,
335                module: contributed.module.name,
336            }
337        })
338        .collect()
339}
340
341/// The metadata of every mount, for the `routes` command: method `*` (or the
342/// declared methods), path `{prefix}/{*rest}`, access and module.
343pub(crate) fn mount_table(ctx: &AppContext) -> Vec<RouteMeta> {
344    collect_mounts(ctx)
345        .into_iter()
346        .map(|entry| entry.meta)
347        .collect()
348}
349
350/// The segments of a good prefix (`/khata/reports` is `["khata",
351/// "reports"]`). `Err(None)` for a prefix outside the grammar
352/// (`PREFIX_RULE`); `Err(Some(..))` with the router's own text for one
353/// inside it whose segment a route path may not hold (`%`, a space, a `.`
354/// segment, a segment starting with `:`).
355pub(crate) fn check_prefix(prefix: &str) -> Result<Vec<&str>, Option<String>> {
356    let in_grammar = prefix.starts_with('/')
357        && !prefix.starts_with("/_")
358        && !prefix.contains(['{', '}', '*'])
359        && !prefix.contains("..")
360        && !prefix.contains("//")
361        && !prefix.ends_with('/');
362    if !in_grammar {
363        return Err(None);
364    }
365    if let Err(error) = PathPattern::parse(prefix) {
366        return Err(Some(error.to_string()));
367    }
368    // Parsed without a parameter: every segment is static, as written.
369    Ok(prefix.split('/').skip(1).collect())
370}
371
372/// Whether `route` matches the path `prefix` names or a path below it: a
373/// `{param}` matches any one segment, a `{*rest}` any path.
374pub(crate) fn overlaps(route: &PathPattern, prefix: &[&str]) -> bool {
375    for (index, segment) in route.segments().iter().enumerate() {
376        if index == prefix.len() {
377            return true;
378        }
379        match segment {
380            Segment::CatchAll => return true,
381            Segment::Param => {}
382            Segment::Static(text) => {
383                if &**text != prefix[index] {
384                    return false;
385                }
386            }
387        }
388    }
389    route.segments().len() == prefix.len()
390}
391
392/// The problems of every mount, in order: a bad prefix (and then nothing
393/// else for that mount), an empty method list, the access rule routes are
394/// checked by, each route that overlaps it, and each earlier mount at or
395/// under its prefix, or above it.
396pub(crate) fn check_mounts(
397    routes: &[&RouteMeta],
398    mounts: &[MountEntry],
399    authenticator: bool,
400    authorizer: bool,
401) -> Vec<String> {
402    let mut errors = Vec::new();
403    // The earlier mounts with a good prefix: (prefix, segments, module).
404    let mut checked: Vec<(&str, Vec<&str>, &str)> = Vec::new();
405    for mount in mounts {
406        let label = format!("mount `{}` in `{}`", mount.prefix, mount.module);
407        let segments = match check_prefix(&mount.prefix) {
408            Ok(segments) => segments,
409            Err(detail) => {
410                let detail = detail
411                    .map(|detail| format!(" ({detail})"))
412                    .unwrap_or_default();
413                errors.push(format!("{label}: {}{detail}", PREFIX_RULE));
414                continue;
415            }
416        };
417        if mount.methods.as_ref().is_some_and(Vec::is_empty) {
418            errors.push(format!(
419                "{label} takes no method: leave out .methods(..) for every method, or name at least one"
420            ));
421        }
422        errors.extend(access_problems(
423            &label,
424            "mount",
425            &mount.meta,
426            authenticator,
427            authorizer,
428        ));
429        for route in routes {
430            // A route path that does not parse is reported with the routes.
431            let Ok(pattern) = PathPattern::parse(&route.full_path) else {
432                continue;
433            };
434            if overlaps(&pattern, &segments) {
435                errors.push(format!(
436                    "{label} overlaps the route {} {} of `{}`; give the mount a prefix of its own",
437                    route.method,
438                    route.full_path,
439                    route.module.unwrap_or("?")
440                ));
441            }
442        }
443        for (earlier, earlier_segments, earlier_module) in &checked {
444            let shared = earlier_segments.len().min(segments.len());
445            if earlier_segments[..shared] == segments[..shared] {
446                errors.push(format!(
447                    "mounts `{earlier}` ({earlier_module}) and `{}` ({}) overlap",
448                    mount.prefix, mount.module
449                ));
450            }
451        }
452        checked.push((mount.prefix.as_str(), segments, mount.module));
453    }
454    errors
455}
456
457/// A mount's service as the endpoint of its route. The route's pipeline has
458/// run before it: authentication, the access check, guards, the throttle, the
459/// timeout and the declared body length. It refuses a request that would take
460/// over the connection, hands the service the path below the prefix and a
461/// body cut off at the route's limit, and turns the service's error into the
462/// app's.
463#[derive(Clone)]
464pub(crate) struct MountEndpoint {
465    prefix: Arc<str>,
466    service: MountService,
467}
468
469impl MountEndpoint {
470    /// The endpoint of `service` at `prefix`.
471    pub(crate) fn new(prefix: &str, service: MountService) -> Self {
472        Self {
473            prefix: Arc::from(prefix),
474            service,
475        }
476    }
477}
478
479impl Service<Request> for MountEndpoint {
480    type Response = Response;
481    type Error = Infallible;
482    type Future = BoxFuture<'static, Result<Response, Infallible>>;
483
484    /// Always ready: the service's readiness is asked for each call.
485    #[inline]
486    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
487        Poll::Ready(Ok(()))
488    }
489
490    fn call(&mut self, request: Request) -> Self::Future {
491        let prefix = self.prefix.clone();
492        let service = self.service.clone();
493        Box::pin(async move { Ok(serve_mounted(&prefix, service, request).await) })
494    }
495}
496
497/// One request to a mount, after its route's pipeline let it in.
498async fn serve_mounted(prefix: &str, service: MountService, mut request: Request) -> Response {
499    if takes_over(&request) {
500        return AppError::from_status(StatusCode::NOT_IMPLEMENTED)
501            .with_detail(TAKES_OVER)
502            .into_response();
503    }
504    let uri = match under(request.uri(), prefix) {
505        Ok(uri) => uri,
506        Err(error) => return error.into_response(),
507    };
508    *request.uri_mut() = uri;
509    // No request passed on can take the connection over, whatever it says.
510    request
511        .extensions_mut()
512        .remove::<hyper::upgrade::OnUpgrade>();
513    // The router's decoded capture of the rest of the path goes too: the
514    // service reads its path from the URI, as written.
515    request.extensions_mut().remove::<PathParams>();
516    // The pipeline checked a declared length; a body sent without one stops
517    // at the same limit, whoever reads it.
518    let limit = BodyLimit::of(request.extensions());
519    let request = request.map(|body| Body::new(http_body_util::Limited::new(body, limit)));
520    match service.oneshot(request).await {
521        Ok(mut response) => {
522            // An answer below 500 the service writes goes out as written; a
523            // bodyless or plain-text 5xx still takes the app's shape, its text
524            // logged, never sent.
525            if !response.status().is_server_error() {
526                response.extensions_mut().insert(AsWritten);
527            }
528            response
529        }
530        Err(error) => match body_error_in(&*error) {
531            Some(body) => AppError::rejection(body.status(), body.to_string()).into_response(),
532            None => AppError::internal(error).into_response(),
533        },
534    }
535}
536
537/// Whether `request` would take over the connection: `CONNECT` (a tunnel, or
538/// an HTTP/2 extended `CONNECT` such as a WebSocket), or an `Upgrade` header
539/// (a WebSocket or h2c handshake).
540fn takes_over(request: &Request) -> bool {
541    request.method() == Method::CONNECT || request.headers().contains_key(UPGRADE)
542}
543
544/// The URI a mounted service gets for `uri`: scheme and authority as
545/// received, the path below `prefix` as written (`/` for the prefix itself),
546/// then the query as written. A path below the prefix with an empty segment,
547/// raw or once `%2F` (either case) is read as `/`, is a 400.
548pub(crate) fn under(uri: &Uri, prefix: &str) -> Result<Uri, AppError> {
549    let rest = uri
550        .path()
551        .strip_prefix(prefix)
552        .ok_or_else(AppError::not_found)?;
553    let rest = match rest {
554        "" => "/",
555        rest if rest.starts_with('/') => rest,
556        // The router sends a mount only its prefix and the paths below it;
557        // the endpoint does not count on that.
558        _ => return Err(AppError::not_found()),
559    };
560    // Raw, then as decoded: `%2F` in either case is a `/` to a service that
561    // decodes its path. No other escape decodes to `/`, and `%252F` stays a
562    // name.
563    if rest.contains("//") || rest.replace("%2F", "/").replace("%2f", "/").contains("//") {
564        return Err(AppError::bad_request(EMPTY_SEGMENT));
565    }
566    let target = match uri.query() {
567        Some(query) => format!("{rest}?{query}"),
568        None => rest.to_owned(),
569    };
570    let mut parts = uri.clone().into_parts();
571    parts.path_and_query = Some(
572        target
573            .parse::<PathAndQuery>()
574            .map_err(|_| AppError::bad_request("Invalid URL"))?,
575    );
576    Uri::from_parts(parts).map_err(|_| AppError::bad_request("Invalid URL"))
577}
578
579#[cfg(test)]
580mod tests {
581    use super::*;
582
583    #[test]
584    fn a_route_overlaps_a_mount_when_it_matches_the_prefix_or_a_path_under_it() {
585        let prefix = ["admin"];
586        for (route, expected) in [
587            ("/admin", true),
588            ("/admin/reports", true),
589            ("/admin/{*rest}", true),
590            ("/{workspace}", true),
591            ("/{workspace}/dashboard", true),
592            ("/{*path}", true),
593            ("/", false),
594            ("/adminx", false),
595            ("/api/admin", false),
596            ("/files/{*path}", false),
597        ] {
598            assert_eq!(
599                overlaps(&PathPattern::parse(route).unwrap(), &prefix),
600                expected,
601                "{route}"
602            );
603        }
604        let deeper = ["admin", "reports"];
605        assert!(
606            !overlaps(&PathPattern::parse("/admin").unwrap(), &deeper),
607            "a route above the prefix"
608        );
609        assert!(!overlaps(
610            &PathPattern::parse("/admin/{id}").unwrap(),
611            &["admin", "reports", "daily"]
612        ));
613        assert!(overlaps(
614            &PathPattern::parse("/admin/{id}/daily").unwrap(),
615            &["admin", "reports", "daily"]
616        ));
617    }
618}