laravel-rust-devtools 0.3.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! Who may see the developer tools: someone on the application's own machine, or with the key,
//! and of those whom the application's gate lets in; or whom its admitting gate lets in.

use std::fmt::Write as _;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;

use axum::extract::ConnectInfo;
use hmac::{Hmac, KeyInit, Mac};
use laravel::http::{Request, header};
use sha2::Sha256;
use subtle::ConstantTimeEq;

use crate::gate::{AnyGate, Gate};

/// The cookie that says someone entered the key: when, and a signature over that time and the key
/// with the application's `APP_KEY`. The `web` group's `EncryptCookies` encrypts it as well.
pub(crate) const COOKIE: &str = "devtools_key";

/// How long the cookie lets someone in. The application checks it, not only the browser.
pub(crate) const COOKIE_HOURS: i64 = 12;

/// Headers a proxy adds that the framework's trusted-proxy check leaves in place. The headers it
/// removes from a proxy it doesn't trust, such as `X-Forwarded-For`, are gone before any middleware
/// runs, so they can't tell a proxied request from a local one: these sometimes can.
const PROXY_HEADERS: [&str; 13] = [
    "forwarded",
    "x-forwarded-for",
    "x-forwarded-host",
    "x-forwarded-port",
    "x-forwarded-prefix",
    "x-forwarded-proto",
    "x-forwarded-server",
    "x-real-ip",
    "via",
    "cf-connecting-ip",
    "true-client-ip",
    "x-client-ip",
    "fastly-client-ip",
];

/// The rules, as the application's configuration sets them.
#[derive(Clone)]
pub(crate) struct Access {
    pub(crate) key: Option<Arc<str>>,
    local: bool,
    gate: Option<Gate>,
}

impl Access {
    pub(crate) fn new(key: Option<&str>, local: bool, gate: Option<Gate>) -> Self {
        Self {
            key: key.map(Arc::from),
            local,
            gate,
        }
    }

    /// Whether `request` may see the developer tools. A gate that fails says no.
    pub(crate) async fn allows(&self, request: &Request) -> bool {
        let by_the_rules = self.this_machine_or_key(request, Some);

        match &self.gate {
            None => by_the_rules,
            Some(Gate::Narrowing(gate)) => by_the_rules && asked(gate.as_ref(), request).await,
            Some(Gate::Admitting(gate)) => by_the_rules || asked(gate.as_ref(), request).await,
        }
    }

    /// Whether the gate may let in whom the rules keep out, which only it can tell once the session
    /// has started.
    pub(crate) fn gate_admits(&self) -> bool {
        matches!(self.gate, Some(Gate::Admitting(_)))
    }

    /// Whether `request` comes from this machine or with the key's cookie, before the `web` group
    /// has decrypted its cookies: what [`allows`](Self::allows) asks short of the gate, which may
    /// need the session.
    pub(crate) fn admits(&self, request: &Request) -> bool {
        self.this_machine_or_key(request, |cookie| {
            // `EncryptCookies` puts a MAC of the cookie's name before the value. A value that
            // doesn't decrypt is taken as it came, as from an application that leaves the cookie
            // unencrypted: either way, its own signature proves it.
            let encrypter = request.encrypter().ok()?;
            Some(
                encrypter
                    .decrypt_string(&cookie)
                    .ok()
                    .and_then(|plain| plain.split_once('|').map(|(_, value)| value.to_owned()))
                    .unwrap_or(cookie),
            )
        })
    }

    /// Whether `request` comes from this machine, or with a cookie whose value, as `value` reads it
    /// from what the browser sent, carries the key's signature.
    fn this_machine_or_key(&self, request: &Request, value: impl FnOnce(String) -> Option<String>) -> bool {
        (self.local && on_this_machine(request))
            || request.cookie(COOKIE).and_then(value).is_some_and(|value| {
                request
                    .encrypter()
                    .is_ok_and(|encrypter| self.signed_and_fresh(&value, encrypter.key()))
            })
    }

    /// The cookie's content for someone who entered the key: when, and the signature under
    /// `app_key` of that time and the key. It holds nothing that gives the key away, and a new key
    /// shuts out every cookie made with the old one.
    pub(crate) fn cookie(&self, app_key: &[u8]) -> Option<String> {
        let issued = laravel::now().timestamp().as_second().to_string();
        let signature = self.signature(app_key, &issued)?;
        Some(format!("{issued}.{signature}"))
    }

    /// Whether the cookie's content was made with the current key and `app_key` less than
    /// [`COOKIE_HOURS`] ago, whatever the browser does with its `Max-Age`.
    fn signed_and_fresh(&self, cookie: &str, app_key: &[u8]) -> bool {
        let Some((issued, signature)) = cookie.split_once('.') else {
            return false;
        };
        let now = laravel::now().timestamp().as_second();
        let fresh = issued
            .parse::<i64>()
            .is_ok_and(|issued| issued <= now && now - issued < COOKIE_HOURS * 60 * 60);
        let signed = self.key.is_some()
            && self
                .signature(app_key, issued)
                .is_some_and(|expected| bool::from(expected.as_bytes().ct_eq(signature.as_bytes())));
        fresh && signed
    }

    /// HMAC-SHA256 under `app_key` of the time a cookie was issued and the key, in hex. `None`
    /// only if the HMAC refused the key, which it does for no length.
    fn signature(&self, app_key: &[u8], issued: &str) -> Option<String> {
        let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(app_key).ok()?;
        mac.update(issued.as_bytes());
        mac.update(b".");
        mac.update(self.key.as_deref().unwrap_or_default().as_bytes());
        Some(
            mac.finalize()
                .into_bytes()
                .iter()
                .fold(String::with_capacity(64), |mut hex, byte| {
                    let _ = write!(hex, "{byte:02x}");
                    hex
                }),
        )
    }

    /// Whether `given` is the key, compared in constant time. Without a key, nothing is.
    pub(crate) fn is_key(&self, given: &str) -> bool {
        self.key
            .as_deref()
            .is_some_and(|key| bool::from(key.as_bytes().ct_eq(given.as_bytes())))
    }
}

/// What `gate` says of `request`, where failing says no.
async fn asked(gate: &dyn AnyGate, request: &Request) -> bool {
    gate.allows(request).await.unwrap_or_else(|error| {
        tracing::warn!(%error, "the developer tools' gate failed, so it counts as no");
        false
    })
}

/// The address the connection comes from, as the server saw it: not a client a proxy names.
pub(crate) fn peer(request: &Request) -> Option<IpAddr> {
    request
        .extension::<ConnectInfo<SocketAddr>>()
        .map(|info| info.0.ip().to_canonical())
}

/// Whether the request comes from the machine the application runs on, with nothing between: a
/// loopback peer, for a loopback host name, with no sign of a proxy.
///
/// The host is the one `Host` header as it came, not `request.host()`, which stands in `localhost`
/// for a missing or invalid one. A request without the header, such as over HTTP/2, which a browser
/// speaks only over TLS and so through a proxy, counts as someone else's; so does one with two. A
/// target that names a host (`GET http://localhost/ HTTP/1.1`) comes before the header in HTTP, and
/// the framework reads the header: the two have to name the same host.
fn on_this_machine(request: &Request) -> bool {
    // A trusted proxy's client comes with the proxy's `X-Forwarded-For`, which counts as a proxy.
    peer(request).is_some_and(|peer| peer.is_loopback())
        && the_host(request).is_some_and(loopback_host)
        && PROXY_HEADERS.iter().all(|name| request.header(*name).is_none())
}

/// The request's host, if it names one beyond doubt: exactly one `Host` header, as text, and the
/// same host in its target if the target names one.
fn the_host(request: &Request) -> Option<&str> {
    let mut hosts = request.headers().get_all(header::HOST).iter();
    let host = match (hosts.next(), hosts.next()) {
        (Some(host), None) => host.to_str().ok()?,
        _ => return None,
    };
    request
        .uri()
        .authority()
        .is_none_or(|target| target.as_str().eq_ignore_ascii_case(host))
        .then_some(host)
}

/// Whether a `Host` header names the machine itself: `localhost`, a name under it, or a loopback
/// address, with a port or without. Anything not a valid host is no one's.
fn loopback_host(host: &str) -> bool {
    if let Some(rest) = host.strip_prefix('[') {
        return rest.split_once(']').is_some_and(|(address, port)| {
            address.parse::<Ipv6Addr>().is_ok_and(|address| address.is_loopback()) && valid_port(port)
        });
    }
    let (name, port) = host.find(':').map_or((host, ""), |colon| host.split_at(colon));
    let under_localhost = name
        .len()
        .checked_sub(".localhost".len())
        .and_then(|end| {
            name.get(..end)
                .filter(|_| name[end..].eq_ignore_ascii_case(".localhost"))
        })
        .is_some_and(|labels| {
            labels.split('.').all(|label| {
                !label.is_empty() && label.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
            })
        });

    valid_port(port)
        && (name.eq_ignore_ascii_case("localhost")
            || under_localhost
            || name.parse::<Ipv4Addr>().is_ok_and(|address| address.is_loopback()))
}

/// Whether what follows a host is nothing, or `:` and a port number.
fn valid_port(rest: &str) -> bool {
    rest.is_empty()
        || rest
            .strip_prefix(':')
            .is_some_and(|port| port.bytes().all(|byte| byte.is_ascii_digit()) && port.parse::<u16>().is_ok())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn only_the_machine_s_own_names_are_loopback_hosts() {
        for host in [
            "localhost",
            "LOCALHOST:8000",
            "app.localhost",
            "my-app.dev.localhost:3000",
            "127.0.0.1",
            "127.8.0.1:8000",
            "[::1]",
            "[::1]:8000",
        ] {
            assert!(loopback_host(host), "{host}");
        }
        for host in [
            "",
            "::1",
            "example.com",
            "localhost.example.com",
            "evil example.com",
            "evil example.localhost",
            ".localhost",
            "a..localhost",
            "localhost.",
            "localhost:",
            "localhost:abc",
            "localhost:+80",
            "localhost:99999",
            "x:abc",
            "10.0.0.1",
            "0.0.0.0",
            "127.1",
            "0x7f.0.0.1",
            "[::1",
            "[::1]x",
            "[::ffff:127.0.0.1]",
            "evil-localhost",
        ] {
            assert!(!loopback_host(host), "{host}");
        }
    }

    #[test]
    fn a_cookie_holds_a_signature_not_the_key() {
        let key = "k".repeat(32);
        let access = Access::new(Some(key.as_str()), true, None);
        let app_key = [7; 32];
        let signature = |access: &Access, app_key: &[u8], issued: &str| access.signature(app_key, issued).unwrap();
        let cookie = signature(&access, &app_key, "1700000000");

        assert_eq!(cookie.len(), 64);
        assert!(!cookie.contains(&key));
        assert_ne!(cookie, signature(&access, &[8; 32], "1700000000"));
        assert_ne!(cookie, signature(&access, &app_key, "1700000001"));
        let other = Access::new(Some("j".repeat(32).as_str()), true, None);
        assert_ne!(cookie, signature(&other, &app_key, "1700000000"));
    }

    #[test]
    fn only_the_key_itself_is_the_key() {
        let access = Access::new(Some("k".repeat(32).as_str()), true, None);

        assert!(access.is_key(&"k".repeat(32)));
        assert!(!access.is_key(&"k".repeat(31)));
        assert!(!access.is_key(&"k".repeat(33)));
        assert!(!access.is_key(""));
        assert!(!Access::new(None, true, None).is_key(""));
    }
}