laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
Documentation
//! Studio's settings, and who may open it.

use std::fmt;
use std::sync::Arc;

use laravel::config::Section;
use laravel::http::Request;

/// Studio's settings, read from the environment.
///
/// An application changes them in `.env`, or in `src/app.rs`:
///
/// ```no_run
/// use laravel::Application;
/// use laravel_rust_studio::StudioConfig;
///
/// Application::configure().with_config(|config, _| {
///     config.section_mut::<StudioConfig>().slow_query_ms = 25;
/// });
/// ```
#[derive(Debug, Clone, Section)]
pub struct StudioConfig {
    /// Whether Studio is installed at all. When it's off, Studio has no routes and captures nothing.
    #[env("STUDIO_ENABLED", default = true)]
    pub enabled: bool,

    /// The path Studio is served at, such as `studio` for `/studio`.
    #[env("STUDIO_PATH", default = "studio")]
    pub path: String,

    /// Open Studio outside the `local` and `testing` environments to every request, without an
    /// [`authorize`](crate::StudioServiceProvider::authorize) callback. Set it only when something
    /// in front of the application, such as a private network, already decides who gets in.
    #[env("STUDIO_ALLOW_IN_PRODUCTION", default = false)]
    pub allow_in_production: bool,

    /// Whether the MCP server answers at `/studio/mcp`.
    #[env("STUDIO_MCP_ENABLED", default = true)]
    pub mcp_enabled: bool,

    /// How many traces Studio keeps: requests, jobs, workflow advances, commands, and scheduled tasks.
    #[env("STUDIO_MAX_TRACES", default = 500)]
    pub max_traces: usize,

    /// How many queries Studio keeps.
    #[env("STUDIO_MAX_QUERIES", default = 2000)]
    pub max_queries: usize,

    /// How many log lines Studio keeps.
    #[env("STUDIO_MAX_LOGS", default = 2000)]
    pub max_logs: usize,

    /// How many errors and panics Studio keeps.
    #[env("STUDIO_MAX_EXCEPTIONS", default = 500)]
    pub max_exceptions: usize,

    /// How many emails and text messages Studio keeps.
    #[env("STUDIO_MAX_MAILS", default = 200)]
    pub max_mails: usize,

    /// How many outgoing HTTP requests Studio keeps.
    #[env("STUDIO_MAX_HTTP_CLIENT", default = 500)]
    pub max_http_client: usize,

    /// How many cache operations Studio keeps.
    #[env("STUDIO_MAX_CACHE", default = 1000)]
    pub max_cache: usize,

    /// How many milliseconds a query takes before it counts as slow.
    #[env("STUDIO_SLOW_QUERY_MS", default = 100)]
    pub slow_query_ms: u64,

    /// How many milliseconds a request takes before it counts as slow.
    #[env("STUDIO_SLOW_REQUEST_MS", default = 500)]
    pub slow_request_ms: u64,

    /// Request paths to leave out of the traces, with everything under them, separated by commas.
    #[env("STUDIO_IGNORE_PATHS", separator = ",")]
    pub ignore_paths: Vec<String>,

    /// Whether processes share what they capture through journal files in `storage/studio`, so
    /// the web server's Studio shows what queue workers and console commands did, and what was
    /// captured survives a restart. The journal is always off in the `testing` environment.
    #[env("STUDIO_JOURNAL", default = true)]
    pub journal: bool,

    /// How much disk space the journal may use, in megabytes, before its oldest files go.
    #[env("STUDIO_JOURNAL_MAX_MB", default = 32)]
    pub journal_max_mb: u64,

    /// How many hours a journal file is kept after its last write.
    #[env("STUDIO_JOURNAL_HOURS", default = 24)]
    pub journal_hours: u64,

    /// Host names Studio answers to in the `local` environment, separated by commas, besides
    /// `localhost`, IP addresses, `*.localhost`, `*.test`, and `APP_URL`'s host. `*` allows any.
    #[env("STUDIO_ALLOWED_HOSTS", separator = ",")]
    pub allowed_hosts: Vec<String>,
}

impl StudioConfig {
    /// The path Studio is served at, with one leading slash and no trailing one, as `/studio`.
    #[must_use]
    pub fn mount_path(&self) -> String {
        match self.path.trim().trim_matches('/') {
            "" => "/studio".to_owned(),
            path => format!("/{path}"),
        }
    }

    /// Whether requests to `path` stay out of the traces: Studio's own pages, API, and assets,
    /// which would bury the application's requests, and the paths in `ignore_paths`.
    #[must_use]
    pub fn should_ignore_path(&self, path: &str) -> bool {
        let under = |prefix: &str| {
            path.strip_prefix(prefix)
                .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
        };

        under(&self.mount_path())
            || under("/vendor/studio")
            || self
                .ignore_paths
                .iter()
                .map(|ignored| ignored.trim().trim_matches('/'))
                .any(|ignored| !ignored.is_empty() && under(&format!("/{ignored}")))
    }
}

/// Decides whether a request may reach Studio.
pub type AuthorizeFn = Arc<dyn Fn(&Request) -> bool + Send + Sync + 'static>;

/// Who may open Studio, as its middleware checks each request.
#[derive(Clone)]
pub struct StudioGate {
    pub(crate) enabled: bool,
    pub(crate) is_local_or_testing: bool,
    pub(crate) allow_in_production: bool,
    pub(crate) authorize: Option<AuthorizeFn>,
    /// Host names allowed besides the built-in local ones, lowercased. `*` allows any.
    pub(crate) allowed_hosts: Vec<String>,
}

impl StudioGate {
    /// Returns whether the incoming request is allowed to access Studio.
    ///
    /// A custom authorizer decides alone. Without one, Studio is open in the `local` and `testing`
    /// environments to requests for a local host name, and elsewhere only when
    /// `STUDIO_ALLOW_IN_PRODUCTION` is set.
    #[must_use]
    pub fn is_authorized(&self, request: &Request) -> bool {
        if let Some(check) = &self.authorize {
            return check(request);
        }
        if self.allow_in_production {
            return true;
        }

        self.is_local_or_testing && self.is_local_host(&request.host())
    }

    /// Whether `host` names this machine or a development domain. A page on another site can make
    /// a browser send requests to a local server under that site's own name (DNS rebinding), and
    /// this is what turns those requests away: their `Host` header names the other site.
    #[must_use]
    pub fn is_local_host(&self, host: &str) -> bool {
        let host = host.trim().to_ascii_lowercase();
        let name = strip_port(&host);
        if name.is_empty() || name == "localhost" || name.parse::<std::net::IpAddr>().is_ok() {
            return true;
        }
        if name.ends_with(".localhost") || name.ends_with(".test") {
            return true;
        }

        self.allowed_hosts
            .iter()
            .any(|allowed| allowed == "*" || allowed == name || strip_port(allowed) == name)
    }
}

/// The host of `host:port`, with an IPv6 address's brackets removed.
fn strip_port(host: &str) -> &str {
    if let Some(rest) = host.strip_prefix('[') {
        return rest.split(']').next().unwrap_or(rest);
    }
    match host.rsplit_once(':') {
        Some((name, port)) if !name.contains(':') && port.chars().all(|c| c.is_ascii_digit()) => name,
        _ => host,
    }
}

impl fmt::Debug for StudioGate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StudioGate")
            .field("enabled", &self.enabled)
            .field("is_local_or_testing", &self.is_local_or_testing)
            .field("allow_in_production", &self.allow_in_production)
            .field("has_custom_authorizer", &self.authorize.is_some())
            .field("allowed_hosts", &self.allowed_hosts)
            .finish()
    }
}