use std::convert::Infallible;
use std::fmt;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use bytes::Bytes;
use http::header::UPGRADE;
use http::uri::PathAndQuery;
use http::{Method, StatusCode, Uri};
use navree_kernel::{AppContext, BoxError, BoxFuture, ModuleBuilder};
use tower::util::BoxCloneSyncService;
use tower::{Service, ServiceExt};
use crate::body::{Body, BodyLimit, HttpBody, body_error_in};
use crate::error::AppError;
use crate::extract::Request;
use crate::pipeline::AsWritten;
use crate::response::{IntoResponse, Response};
use crate::router::access_problems;
use crate::routing::{PathParams, PathPattern, Segment};
use crate::{CanSpec, Guard, RouteMeta, Throttle};
pub(crate) type MountService = BoxCloneSyncService<Request, Response, BoxError>;
const PREFIX_RULE: &str = "a prefix starts with `/` but not with `/_`, has no `{`, `}`, `*`, `..` or `//`, and does not end with `/`";
const TAKES_OVER: &str =
"A mounted service answers requests; it does not take over the connection.";
const EMPTY_SEGMENT: &str = "Invalid URL: the path has an empty segment";
#[derive(Clone)]
pub struct Mount {
prefix: String,
service: MountService,
meta: RouteMeta,
methods: Option<Vec<Method>>,
}
impl Mount {
pub fn new<S, B>(prefix: &str, service: S) -> Mount
where
S: Service<Request, Response = http::Response<B>> + Clone + Send + Sync + 'static,
S::Error: Into<BoxError>,
S::Future: Send + 'static,
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
let service = service
.map_response(|response: http::Response<B>| response.map(Body::new))
.map_err(|error: S::Error| -> BoxError { error.into() });
Mount {
prefix: prefix.to_owned(),
service: BoxCloneSyncService::new(service),
meta: RouteMeta::default(),
methods: None,
}
}
pub fn public(mut self) -> Mount {
self.meta.access.public = true;
self
}
pub fn authenticated(mut self) -> Mount {
self.meta.access.authenticated = true;
self
}
pub fn roles(mut self, roles: &[&str]) -> Mount {
self.meta
.access
.roles
.extend(roles.iter().map(|role| (*role).to_owned()));
self
}
pub fn permissions(mut self, permissions: &[&str]) -> Mount {
self.meta.access.permissions.extend(
permissions
.iter()
.map(|permission| (*permission).to_owned()),
);
self
}
pub fn can(mut self, action: &str, subject: &str) -> Mount {
self.meta.access.can = Some(CanSpec {
action: action.to_owned(),
subject: subject.to_owned(),
from: None,
});
self
}
pub fn guard(mut self, guard: Arc<dyn Guard>) -> Mount {
self.meta.guards.push(guard);
self
}
pub fn throttle(mut self, limit: u32, per: Duration) -> Mount {
self.meta.throttle = Some(Throttle { limit, per });
self
}
pub fn timeout(mut self, d: Duration) -> Mount {
self.meta.timeout = Some(d);
self
}
pub fn body_limit(mut self, bytes: usize) -> Mount {
self.meta.body_limit = Some(bytes);
self
}
pub fn name(mut self, name: &str) -> Mount {
self.meta.name = Some(name.to_owned());
self
}
pub fn methods(mut self, methods: &[Method]) -> Mount {
let mut kept: Vec<Method> = Vec::with_capacity(methods.len());
for method in methods {
if !kept.contains(method) {
kept.push(method.clone());
}
}
self.methods = Some(kept);
self
}
}
impl fmt::Debug for Mount {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Mount")
.field("prefix", &self.prefix)
.field("methods", &self.methods)
.field("access", &self.meta.access.describe())
.finish_non_exhaustive()
}
}
pub trait ModuleBuilderMountExt {
fn mount(&mut self, mount: Mount) -> &mut Self;
}
impl ModuleBuilderMountExt for ModuleBuilder {
fn mount(&mut self, mount: Mount) -> &mut Self {
self.contribute(MountRegistration(mount))
}
}
#[derive(Clone)]
pub(crate) struct MountRegistration(pub(crate) Mount);
pub(crate) struct MountEntry {
pub(crate) prefix: String,
pub(crate) service: MountService,
pub(crate) meta: RouteMeta,
pub(crate) methods: Option<Vec<Method>>,
pub(crate) module: &'static str,
}
pub(crate) fn collect_mounts(ctx: &AppContext) -> Vec<MountEntry> {
ctx.contributions::<MountRegistration>()
.into_iter()
.map(|contributed| {
let mount = contributed.value.0.clone();
let mut meta = mount.meta;
meta.full_path = format!("{}/{{*rest}}", mount.prefix);
meta.method = match &mount.methods {
None => "*".to_owned(),
Some(methods) => methods
.iter()
.map(Method::as_str)
.collect::<Vec<_>>()
.join(","),
};
meta.module = Some(contributed.module.name);
meta.module_id = Some(contributed.module.id);
MountEntry {
prefix: mount.prefix,
service: mount.service,
meta,
methods: mount.methods,
module: contributed.module.name,
}
})
.collect()
}
pub(crate) fn mount_table(ctx: &AppContext) -> Vec<RouteMeta> {
collect_mounts(ctx)
.into_iter()
.map(|entry| entry.meta)
.collect()
}
pub(crate) fn check_prefix(prefix: &str) -> Result<Vec<&str>, Option<String>> {
let in_grammar = prefix.starts_with('/')
&& !prefix.starts_with("/_")
&& !prefix.contains(['{', '}', '*'])
&& !prefix.contains("..")
&& !prefix.contains("//")
&& !prefix.ends_with('/');
if !in_grammar {
return Err(None);
}
if let Err(error) = PathPattern::parse(prefix) {
return Err(Some(error.to_string()));
}
Ok(prefix.split('/').skip(1).collect())
}
pub(crate) fn overlaps(route: &PathPattern, prefix: &[&str]) -> bool {
for (index, segment) in route.segments().iter().enumerate() {
if index == prefix.len() {
return true;
}
match segment {
Segment::CatchAll => return true,
Segment::Param => {}
Segment::Static(text) => {
if &**text != prefix[index] {
return false;
}
}
}
}
route.segments().len() == prefix.len()
}
pub(crate) fn check_mounts(
routes: &[&RouteMeta],
mounts: &[MountEntry],
authenticator: bool,
authorizer: bool,
) -> Vec<String> {
let mut errors = Vec::new();
let mut checked: Vec<(&str, Vec<&str>, &str)> = Vec::new();
for mount in mounts {
let label = format!("mount `{}` in `{}`", mount.prefix, mount.module);
let segments = match check_prefix(&mount.prefix) {
Ok(segments) => segments,
Err(detail) => {
let detail = detail
.map(|detail| format!(" ({detail})"))
.unwrap_or_default();
errors.push(format!("{label}: {}{detail}", PREFIX_RULE));
continue;
}
};
if mount.methods.as_ref().is_some_and(Vec::is_empty) {
errors.push(format!(
"{label} takes no method: leave out .methods(..) for every method, or name at least one"
));
}
errors.extend(access_problems(
&label,
"mount",
&mount.meta,
authenticator,
authorizer,
));
for route in routes {
let Ok(pattern) = PathPattern::parse(&route.full_path) else {
continue;
};
if overlaps(&pattern, &segments) {
errors.push(format!(
"{label} overlaps the route {} {} of `{}`; give the mount a prefix of its own",
route.method,
route.full_path,
route.module.unwrap_or("?")
));
}
}
for (earlier, earlier_segments, earlier_module) in &checked {
let shared = earlier_segments.len().min(segments.len());
if earlier_segments[..shared] == segments[..shared] {
errors.push(format!(
"mounts `{earlier}` ({earlier_module}) and `{}` ({}) overlap",
mount.prefix, mount.module
));
}
}
checked.push((mount.prefix.as_str(), segments, mount.module));
}
errors
}
#[derive(Clone)]
pub(crate) struct MountEndpoint {
prefix: Arc<str>,
service: MountService,
}
impl MountEndpoint {
pub(crate) fn new(prefix: &str, service: MountService) -> Self {
Self {
prefix: Arc::from(prefix),
service,
}
}
}
impl Service<Request> for MountEndpoint {
type Response = Response;
type Error = Infallible;
type Future = BoxFuture<'static, Result<Response, Infallible>>;
#[inline]
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Infallible>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request) -> Self::Future {
let prefix = self.prefix.clone();
let service = self.service.clone();
Box::pin(async move { Ok(serve_mounted(&prefix, service, request).await) })
}
}
async fn serve_mounted(prefix: &str, service: MountService, mut request: Request) -> Response {
if takes_over(&request) {
return AppError::from_status(StatusCode::NOT_IMPLEMENTED)
.with_detail(TAKES_OVER)
.into_response();
}
let uri = match under(request.uri(), prefix) {
Ok(uri) => uri,
Err(error) => return error.into_response(),
};
*request.uri_mut() = uri;
request
.extensions_mut()
.remove::<hyper::upgrade::OnUpgrade>();
request.extensions_mut().remove::<PathParams>();
let limit = BodyLimit::of(request.extensions());
let request = request.map(|body| Body::new(http_body_util::Limited::new(body, limit)));
match service.oneshot(request).await {
Ok(mut response) => {
if !response.status().is_server_error() {
response.extensions_mut().insert(AsWritten);
}
response
}
Err(error) => match body_error_in(&*error) {
Some(body) => AppError::rejection(body.status(), body.to_string()).into_response(),
None => AppError::internal(error).into_response(),
},
}
}
fn takes_over(request: &Request) -> bool {
request.method() == Method::CONNECT || request.headers().contains_key(UPGRADE)
}
pub(crate) fn under(uri: &Uri, prefix: &str) -> Result<Uri, AppError> {
let rest = uri
.path()
.strip_prefix(prefix)
.ok_or_else(AppError::not_found)?;
let rest = match rest {
"" => "/",
rest if rest.starts_with('/') => rest,
_ => return Err(AppError::not_found()),
};
if rest.contains("//") || rest.replace("%2F", "/").replace("%2f", "/").contains("//") {
return Err(AppError::bad_request(EMPTY_SEGMENT));
}
let target = match uri.query() {
Some(query) => format!("{rest}?{query}"),
None => rest.to_owned(),
};
let mut parts = uri.clone().into_parts();
parts.path_and_query = Some(
target
.parse::<PathAndQuery>()
.map_err(|_| AppError::bad_request("Invalid URL"))?,
);
Uri::from_parts(parts).map_err(|_| AppError::bad_request("Invalid URL"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_route_overlaps_a_mount_when_it_matches_the_prefix_or_a_path_under_it() {
let prefix = ["admin"];
for (route, expected) in [
("/admin", true),
("/admin/reports", true),
("/admin/{*rest}", true),
("/{workspace}", true),
("/{workspace}/dashboard", true),
("/{*path}", true),
("/", false),
("/adminx", false),
("/api/admin", false),
("/files/{*path}", false),
] {
assert_eq!(
overlaps(&PathPattern::parse(route).unwrap(), &prefix),
expected,
"{route}"
);
}
let deeper = ["admin", "reports"];
assert!(
!overlaps(&PathPattern::parse("/admin").unwrap(), &deeper),
"a route above the prefix"
);
assert!(!overlaps(
&PathPattern::parse("/admin/{id}").unwrap(),
&["admin", "reports", "daily"]
));
assert!(overlaps(
&PathPattern::parse("/admin/{id}/daily").unwrap(),
&["admin", "reports", "daily"]
));
}
}