laravel-rust-devtools 0.2.1

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! The middleware that marks each page with its trace and adds the toolbar to it.

use std::fmt::Write as _;
use std::sync::atomic::{AtomicBool, Ordering};

use axum::body::{Body, HttpBody};
use axum::http::HeaderMap;
use laravel::http::{Middleware, Next, Request, Response, StatusCode, header};

use super::access::Access;
use crate::collector::{Running, running};

/// The largest HTML page the toolbar is added to; a larger one passes untouched.
const MAX_PAGE: u64 = 5 * 1024 * 1024;

/// The header that names a response's trace.
pub(crate) const TRACE_HEADER: &str = "x-devtools-trace";

/// What [`Access::allows`] said of a request, for the `Guard` behind the toolbar.
#[derive(Clone, Copy)]
pub(crate) struct Allowed(pub(crate) bool);

/// Adds `x-devtools-trace` and `Server-Timing` to each response of someone who may see the
/// developer tools, and the toolbar's script to each HTML page among them. It asks whether they
/// may for every request, and leaves the answer to the developer tools' own routes.
pub(crate) struct Toolbar {
    pub(crate) access: Access,
    /// The key of the collector whose traces the responses name.
    pub(crate) collector: u64,
}

impl Middleware for Toolbar {
    async fn handle(&self, mut request: Request, next: Next) -> laravel::Result<Response> {
        // Asked once for every path, the developer tools' own too, so that what the gate costs
        // doesn't tell their routes from paths that don't exist; the `Guard` takes the answer.
        let allowed = self.access.allows(&request).await;
        request.extensions_mut().insert(Allowed(allowed));
        if super::under(request.path(), super::PREFIX).is_some() || !allowed {
            return Ok(next.run(request).await);
        }
        let head = request.method() == laravel::http::Method::HEAD;

        let response = next.run(request).await;
        let Some(running) = running(self.collector) else {
            return Ok(response);
        };
        let response = marked(response, running);
        if head {
            return Ok(response);
        }

        Ok(with_toolbar(response, running).await)
    }
}

/// The response with its trace's ID and what the trace measured so far.
fn marked(mut response: Response, running: Running) -> Response {
    let mut timing = format!(
        "db;dur={:.1};desc=\"{} {}\"",
        running.query_time.as_secs_f64() * 1000.0,
        running.queries,
        if running.queries == 1 { "query" } else { "queries" }
    );
    let _ = write!(timing, ", app;dur={:.1}", running.elapsed.as_secs_f64() * 1000.0);

    let headers = response.headers_mut();
    if let Ok(value) = running.id.to_string().parse() {
        headers.insert(TRACE_HEADER, value);
    }
    if let Ok(value) = timing.parse() {
        headers.append("server-timing", value);
    }

    response
}

/// The response with the toolbar's script before `</body>`, if it's an HTML page the toolbar can
/// be added to without waiting for a stream or changing a download.
async fn with_toolbar(response: Response, running: Running) -> Response {
    if !takes_toolbar(&response) {
        return response;
    }
    let (mut parts, body) = response.into_http().into_parts();
    // The body is gone once it couldn't be read; there is no page left to send.
    let Ok(page) = axum::body::to_bytes(body, usize::MAX).await else {
        return Response::new(StatusCode::INTERNAL_SERVER_ERROR);
    };
    let Some(at) = closing_body(&page) else {
        return Response::new(axum::http::Response::from_parts(parts, Body::from(page)));
    };

    let nonce = nonce(&parts.headers, &page);
    if nonce.is_none() && blocks_without_nonce(&parts.headers) {
        warn_once();
    }
    let script = format!(
        "<script type=\"module\" src=\"{}/launcher.js?v={}\"{} data-devtools-trace=\"{}\"></script>",
        super::PREFIX,
        super::assets::LAUNCHER.version(),
        nonce.map_or_else(String::new, |nonce| format!(" nonce=\"{nonce}\"")),
        running.id
    );
    let page = [&page[..at], script.as_bytes(), &page[at..]].concat();
    // The page is no longer the one its length and entity tag describe.
    parts.headers.remove(header::CONTENT_LENGTH);
    parts.headers.remove(header::ETAG);

    Response::new(axum::http::Response::from_parts(parts, Body::from(page)))
}

/// Whether `response` is a whole HTML page, small enough, sent as it is.
fn takes_toolbar(response: &Response) -> bool {
    let headers = response.headers();
    let html = headers
        .get(header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| value.trim_start().to_ascii_lowercase().starts_with("text/html"));
    let download = headers
        .get(header::CONTENT_DISPOSITION)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| value.trim_start().to_ascii_lowercase().starts_with("attachment"));
    let sized = response.body().size_hint().exact().is_some_and(|size| size <= MAX_PAGE);

    html && !download
        && sized
        && !headers.contains_key(header::CONTENT_ENCODING)
        && !matches!(response.status().as_u16(), 100..=199 | 204 | 206 | 304)
}

/// The directives a page's `<script>` falls under, the most specific first.
const SCRIPT_DIRECTIVES: [&str; 3] = ["script-src-elem", "script-src", "default-src"];

/// The source list of each `Content-Security-Policy` that governs the page's scripts.
fn script_sources(headers: &HeaderMap) -> impl Iterator<Item = &str> {
    headers
        .get_all(header::CONTENT_SECURITY_POLICY)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .filter_map(|policy| {
            let directives: Vec<(String, &str)> = policy
                .split(';')
                .filter_map(|directive| {
                    let directive = directive.trim();
                    let (name, sources) = directive.split_once(char::is_whitespace).unwrap_or((directive, ""));
                    (!name.is_empty()).then(|| (name.to_ascii_lowercase(), sources))
                })
                .collect();
            SCRIPT_DIRECTIVES.iter().find_map(|wanted| {
                directives
                    .iter()
                    .find(|(name, _)| name == wanted)
                    .map(|(_, sources)| *sources)
            })
        })
}

/// The nonce the page's scripts carry, so that a policy which allows them allows the launcher too:
/// from the policy's header, else from a `<script>` of the page, as a policy in a `<meta>` needs.
fn nonce(headers: &HeaderMap, page: &[u8]) -> Option<String> {
    let from_header = script_sources(headers).find_map(|sources| {
        sources.split_whitespace().find_map(|source| {
            source
                .strip_prefix("'nonce-")
                .and_then(|rest| rest.strip_suffix('\''))
                .filter(|nonce| is_nonce(nonce))
                .map(str::to_owned)
        })
    });

    from_header.or_else(|| nonce_in_page(page))
}

/// The first nonce a `<script>` tag of `page` carries.
fn nonce_in_page(page: &[u8]) -> Option<String> {
    const SCRIPT: &[u8] = b"<script";
    const NONCE: &[u8] = b"nonce=";
    let mut rest = page;
    while let Some(at) = rest
        .windows(SCRIPT.len())
        .position(|window| window.eq_ignore_ascii_case(SCRIPT))
    {
        let tag = &rest[at + SCRIPT.len()..];
        let tag = &tag[..tag.iter().position(|&byte| byte == b'>').unwrap_or(tag.len())];
        // An attribute of its own, not the end of another's name such as `data-nonce`.
        let attribute = (1..tag.len()).find(|&at| {
            tag[at - 1].is_ascii_whitespace()
                && tag[at..]
                    .get(..NONCE.len())
                    .is_some_and(|name| name.eq_ignore_ascii_case(NONCE))
        });
        if let Some(found) = attribute {
            let value = &tag[found + NONCE.len()..];
            let value = match value.split_first() {
                Some((&quote @ (b'"' | b'\''), quoted)) => {
                    &quoted[..quoted.iter().position(|&byte| byte == quote).unwrap_or(quoted.len())]
                }
                _ => &value[..value.iter().position(u8::is_ascii_whitespace).unwrap_or(value.len())],
            };
            return std::str::from_utf8(value)
                .ok()
                .filter(|nonce| is_nonce(nonce))
                .map(str::to_owned);
        }
        rest = &rest[at + SCRIPT.len()..];
    }

    None
}

/// Whether `value` is a nonce as CSP writes them: base64 or base64url, which needs no escaping.
fn is_nonce(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=' | b'-' | b'_'))
}

/// Whether a policy of the response would block a script of the page's own origin without a
/// nonce: one without `'self'`, or with `'strict-dynamic'`, which ignores `'self'`.
fn blocks_without_nonce(headers: &HeaderMap) -> bool {
    script_sources(headers).any(|sources| {
        let sources: Vec<String> = sources.split_whitespace().map(str::to_ascii_lowercase).collect();
        let has = |source: &str| sources.iter().any(|given| given == source);

        has("'strict-dynamic'") || !(has("'self'") || has("*"))
    })
}

/// Says once per process that a page's policy keeps the launcher out, and what to do about it.
fn warn_once() {
    static WARNED: AtomicBool = AtomicBool::new(false);
    if !WARNED.swap(true, Ordering::Relaxed) {
        tracing::warn!(
            "a page's Content-Security-Policy blocks the developer tools' launcher: give the page's \
             scripts a nonce, which the launcher takes over, or allow 'self' in script-src"
        );
    }
}

/// Where the page's last `</body>` starts, in any case.
fn closing_body(page: &[u8]) -> Option<usize> {
    const TAG: &[u8] = b"</body";
    page.windows(TAG.len())
        .rposition(|window| window.eq_ignore_ascii_case(TAG))
}

#[cfg(test)]
mod tests {
    use axum::http::{HeaderMap, HeaderValue, header};

    use super::{blocks_without_nonce, closing_body, nonce};

    fn policy(policies: &[&'static str]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for value in policies {
            headers.append(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(value));
        }
        headers
    }

    #[test]
    fn the_nonce_comes_from_the_directive_the_script_falls_under() {
        let most_specific = policy(&["default-src 'nonce-d'; script-src 'nonce-s'; script-src-elem 'nonce-e'"]);
        assert_eq!(nonce(&most_specific, b"").as_deref(), Some("e"));
        assert_eq!(
            nonce(&policy(&["Default-Src 'self' 'nonce-d'"]), b"").as_deref(),
            Some("d")
        );
        // A policy without one leaves the page's own; a value that isn't a nonce counts as none.
        assert_eq!(
            nonce(&policy(&["script-src 'self'"]), b"<script nonce='p'>").as_deref(),
            Some("p")
        );
        assert_eq!(nonce(&policy(&["script-src 'nonce-<x>'"]), b""), None);
        assert_eq!(nonce(&HeaderMap::new(), b"<p nonce=\"p\"><script src=a.js>"), None);
        assert_eq!(
            nonce(&HeaderMap::new(), b"<script nonce=p async>").as_deref(),
            Some("p")
        );
    }

    #[test]
    fn a_policy_that_needs_a_nonce_is_told() {
        assert!(!blocks_without_nonce(&HeaderMap::new()));
        assert!(!blocks_without_nonce(&policy(&["default-src 'self'"])));
        assert!(!blocks_without_nonce(&policy(&["img-src 'none'"])));
        assert!(blocks_without_nonce(&policy(&["script-src 'self' 'strict-dynamic'"])));
        assert!(blocks_without_nonce(&policy(&["default-src 'none'"])));
        assert!(blocks_without_nonce(&policy(&[
            "default-src 'self'",
            "script-src 'sha256-x'"
        ])));
    }

    #[test]
    fn the_script_goes_before_the_last_closing_body() {
        assert_eq!(closing_body(b"<body>a</body>"), Some(7));
        assert_eq!(closing_body(b"<BODY>a</BODY >"), Some(7));
        assert_eq!(closing_body(b"<p>&lt;/body&gt;</p></body></body>"), Some(27));
        assert_eq!(closing_body(b"<p>no body</p>"), None);
        assert_eq!(closing_body(b""), None);
    }
}