laravel-rust-devtools 0.1.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! What the developer tools add to an application's HTTP side: the toolbar on its pages, and the
//! routes under `/_devtools` that the toolbar reads.

mod access;
mod api;
mod assets;
mod login;
mod panel;
mod toolbar;

use std::sync::Arc;

use axum::http::Uri;
use laravel::container::Registrar;
use laravel::http::{Method, Middleware, Next, Request, Response};

pub(crate) use access::Access;

use crate::store::Store;

/// Where the developer tools' routes start.
pub(crate) const PREFIX: &str = "/_devtools";

/// Where the routes really are. A request reaches them only through `Hidden`, which sends one for
/// this path itself on as unknown, so the path needs no secret: only no route of the application
/// may take it.
const INTERNAL: &str = "/_devtools-routes";

/// Add the toolbar, its API over `store` and its login page to the application, for the
/// collector with the key `collector`.
pub(crate) fn register(app: &mut Registrar, store: Arc<dyn Store>, collector: u64, access: Access) {
    let login = access.key.is_some();

    app.instance(api::History(store));
    app.instance(access.clone());
    app.middleware().append(Hidden(access.clone()));
    app.middleware().web(|web| {
        web.append(toolbar::Toolbar {
            access: access.clone(),
            collector,
        });
    });
    app.routing().web(move |route| {
        route.prefix(INTERNAL).group(|route| {
            if login {
                route.get("/login", login::show);
                route.post("/login", login::store);
            }
            route.middleware(Guard(access)).group(|route| {
                route.get("/", panel::show);
                route.get("/launcher.js", assets::launcher);
                route.get("/panel.js", assets::panel_script);
                route.get("/panel.css", assets::panel_styles);
                route.post("/logout", login::destroy);
                route.get("/api/traces", api::index);
                route.delete("/api/traces", api::destroy);
                route.get("/api/traces/{id}", api::show);
                route.get("/api/traces/{id}/summary", api::summary);
            });
        });
    });
}

/// Lets a request under `/_devtools` reach the developer tools' routes only if it may: it runs
/// before routing, the session and every group, and sends the request on to the routes' internal
/// path. Any other request goes on as it came, to a path no route takes, so the application
/// answers it as it answers every path that doesn't exist: its fallback, its session cookie, its
/// CSRF check, its `Allow` header. A request for the internal path itself goes on as one under
/// `/_devtools`, unknown alike.
///
/// The login page is open to everyone when the application has a key, for the methods it has.
/// Everything else needs this machine or the key's cookie; the gate, which may need the session,
/// is the `Guard`'s.
struct Hidden(Access);

impl Middleware for Hidden {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        let path = request.uri().path();
        let target = if let Some(rest) = under(path, INTERNAL) {
            Some(format!("{PREFIX}{rest}"))
        } else if let Some(rest) = under(path, PREFIX) {
            let login = self.0.key.is_some()
                && rest == "/login"
                && matches!(*request.method(), Method::GET | Method::HEAD | Method::POST);
            (login || self.0.admits(&request)).then(|| format!("{INTERNAL}{rest}"))
        } else {
            None
        };
        let Some(target) = target else {
            return Ok(next.run(request).await);
        };

        let mut request = request.into_http();
        let uri = match request.uri().query() {
            Some(query) => format!("{target}?{query}"),
            None => target,
        };
        // A path that isn't one goes on unchanged, to no route.
        if let Ok(uri) = uri.parse::<Uri>() {
            *request.uri_mut() = uri;
        }
        Ok(next.run(Request::from_http(request)).await)
    }
}

/// Whether `path` is one of the developer tools' own, as a request names it or as `Hidden` sends it on.
pub(crate) fn is_own(path: &str) -> bool {
    under(path, PREFIX).is_some() || under(path, INTERNAL).is_some()
}

/// What follows `prefix` in `path`, if `path` is `prefix` or under it.
fn under<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
    path.strip_prefix(prefix)
        .filter(|rest| rest.is_empty() || rest.starts_with('/'))
}

/// Answers `404` to whom the rules turn away, here only the application's gate: `Hidden` has let in
/// only those on this machine or with the key. So the answer hides what the developer tools hold,
/// not that they are there.
struct Guard(Access);

impl Middleware for Guard {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        if !self.0.allows(&request).await {
            laravel::abort!(404);
        }

        Ok(next.run(request).await)
    }
}