laravel-rust-devtools 0.2.1

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::middleware::PreventRequestForgery;
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";

/// A route behind the `Guard`: its method and its path after the prefix, where `{..}` stands for
/// one segment. A `GET` route takes `HEAD` too.
type Guarded = (Method, &'static str);

const PANEL: Guarded = (Method::GET, "/");
const LAUNCHER: Guarded = (Method::GET, "/launcher.js");
const PANEL_SCRIPT: Guarded = (Method::GET, "/panel.js");
const PANEL_STYLES: Guarded = (Method::GET, "/panel.css");
const LOGOUT: Guarded = (Method::POST, "/logout");
const TRACES: Guarded = (Method::GET, "/api/traces");
const CLEAR: Guarded = (Method::DELETE, "/api/traces");
const TRACE: Guarded = (Method::GET, "/api/traces/{id}");
const SUMMARY: Guarded = (Method::GET, "/api/traces/{id}/summary");

/// Every route behind the `Guard`: `register` adds them, and with an admitting gate, `Hidden`
/// lets each through for its method.
const GUARDED: [Guarded; 9] = [
    PANEL,
    LAUNCHER,
    PANEL_SCRIPT,
    PANEL_STYLES,
    LOGOUT,
    TRACES,
    CLEAR,
    TRACE,
    SUMMARY,
];

/// 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(move |web| {
        web.append(toolbar::Toolbar { access, collector });
    });
    app.routing().web(move |route| {
        route.prefix(INTERNAL).group(|route| {
            if login {
                route.get("/login", login::show);
                route.post("/login", login::store);
            }
            // The `Guard` checks the CSRF token itself, after the gate, so that whom it turns away
            // gets the `404` and none of the check's cookie or `419`.
            route
                .middleware(Guard)
                .without_middleware::<PreventRequestForgery>()
                .group(|route| {
                    route.on(&[PANEL.0], PANEL.1, panel::show);
                    route.on(&[LAUNCHER.0], LAUNCHER.1, assets::launcher);
                    route.on(&[PANEL_SCRIPT.0], PANEL_SCRIPT.1, assets::panel_script);
                    route.on(&[PANEL_STYLES.0], PANEL_STYLES.1, assets::panel_styles);
                    route.on(&[LOGOUT.0], LOGOUT.1, login::destroy);
                    route.on(&[TRACES.0], TRACES.1, api::index);
                    route.on(&[CLEAR.0], CLEAR.1, api::destroy);
                    route.on(&[TRACE.0], TRACE.1, api::show);
                    route.on(&[SUMMARY.0], SUMMARY.1, 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. An admitting gate may let in anyone, so with one, each route behind the
/// `Guard` is open to everyone for the methods it has, and the `Guard` decides: the methods it
/// doesn't have go on as they came, so the router's `405` and `Allow` don't give the routes away.
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);
            let guarded = self.0.gate_admits() && is_guarded(request.method(), rest);
            (login || guarded || 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 a route behind the `Guard` takes `method` for `rest`, the path after the prefix.
fn is_guarded(method: &Method, rest: &str) -> bool {
    let rest = if rest.is_empty() { "/" } else { rest };
    GUARDED.iter().any(|(takes, path)| {
        let method_fits = takes == method || (*takes == Method::GET && *method == Method::HEAD);
        method_fits && fits(path, rest)
    })
}

/// Whether `rest` is `path`, where a `{..}` segment of `path` stands for any one that isn't empty.
fn fits(path: &str, rest: &str) -> bool {
    let mut wanted = path.split('/');
    let mut given = rest.split('/');
    loop {
        match (wanted.next(), given.next()) {
            (None, None) => return true,
            (Some(want), Some(give)) if want == give || (want.starts_with('{') && !give.is_empty()) => {}
            _ => return false,
        }
    }
}

/// 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, as the `Toolbar` in the `web` group found, and to
/// every request it didn't see, before any CSRF check: the routes run without the `web` group's,
/// and the `Guard` runs the framework's own, [`PreventRequestForgery::new`], for whom it lets in,
/// whatever the application set in its place, such as `origin_only`.
/// With a narrowing gate, `Hidden` has let in only those on this machine or with the key, and the
/// answer hides what the developer tools hold, not that they are there. With an admitting gate,
/// `Hidden` has let in everyone for the routes' methods, and the answer is the `404` a path that
/// doesn't exist gets from the application's own fallback, if that answers with
/// `laravel::abort(404)` without the CSRF check.
struct Guard;

impl Middleware for Guard {
    async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
        if !matches!(request.extension(), Some(toolbar::Allowed(true))) {
            laravel::abort!(404);
        }

        PreventRequestForgery::new().handle(request, next).await
    }
}

#[cfg(test)]
mod tests {
    use laravel::http::Method;

    use super::is_guarded;

    #[test]
    fn only_a_guarded_route_s_own_methods_pass_before_the_gate() {
        for (method, rest) in [
            (Method::GET, ""),
            (Method::HEAD, "/"),
            (Method::GET, "/launcher.js"),
            (Method::GET, "/panel.js"),
            (Method::GET, "/panel.css"),
            (Method::POST, "/logout"),
            (Method::GET, "/api/traces"),
            (Method::DELETE, "/api/traces"),
            (Method::GET, "/api/traces/0123456789abcdef0123456789abcdef"),
            (Method::HEAD, "/api/traces/0123456789abcdef0123456789abcdef/summary"),
        ] {
            assert!(is_guarded(&method, rest), "{method} {rest}");
        }
        for (method, rest) in [
            (Method::POST, ""),
            (Method::OPTIONS, "/"),
            (Method::GET, "/login"),
            (Method::GET, "/logout"),
            (Method::PUT, "/api/traces"),
            (Method::DELETE, "/api/traces/0123456789abcdef0123456789abcdef"),
            (Method::GET, "/api/traces/"),
            (Method::GET, "/api/traces/a/b"),
            (Method::GET, "/api/traces//summary"),
            (Method::GET, "/api/tracesx"),
            (Method::GET, "/nothing"),
        ] {
            assert!(!is_guarded(&method, rest), "{method} {rest}");
        }
    }
}