laravel-rust-devtools 0.1.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! The service provider that turns the developer tools on in an application.

use std::fmt;
#[cfg(debug_assertions)]
use std::sync::Arc;

use laravel::config::{Config, Env, Section};
use laravel::foundation::ServiceProvider;

#[cfg(debug_assertions)]
use crate::gate::AnyGate;
use crate::gate::DevtoolsGate;

/// The developer tools' settings, read from the environment.
///
/// An application may change them in `src/app.rs`, after they are read:
///
/// ```
/// use laravel_rust_devtools::DevtoolsConfig;
///
/// laravel::Application::configure().with_config(|config, _| {
///     config.section_mut::<DevtoolsConfig>().error_text = true;
/// });
/// ```
#[derive(Clone, Section)]
#[non_exhaustive]
pub struct DevtoolsConfig {
    /// `DEVTOOLS_ENABLED`: `false` turns the developer tools off where they would run. Unset, they
    /// run in a build with debug assertions with `APP_ENV=local`. `true` asks for them: such a
    /// build that runs anywhere else, except in the application's tests, then refuses to start
    /// rather than run without them unnoticed. A build without debug assertions has none of the
    /// developer tools and ignores it.
    #[env("DEVTOOLS_ENABLED")]
    pub enabled: Option<bool>,
    /// `DEVTOOLS_ERROR_TEXT`: whether traces record what an error says, which may quote a value.
    /// Off by default: a trace then keeps an error's kind, where it was raised and when, and records
    /// its text as `[masked]`, in a reported error, a job that will be retried and every field
    /// named `error`. Turn it on while looking for a bug. Everyone who can read the traces sees
    /// those texts, as the developer tools' API at `/_devtools/api` gives them.
    #[env("DEVTOOLS_ERROR_TEXT", default = false)]
    pub error_text: bool,
    /// `DEVTOOLS_KEY`: the key that opens the developer tools to someone who isn't on the
    /// application's own machine, such as a browser behind a proxy. They enter it once at
    /// `/_devtools/login`, and a cookie signed with `APP_KEY` lets them in for 12 hours, which the
    /// application checks itself; a new key shuts out every cookie made with the old one. Between
    /// 32 and 72 bytes: the application doesn't start with a shorter or longer one. Unset, only the
    /// machine itself gets in.
    #[env("DEVTOOLS_KEY")]
    pub key: Option<String>,
    /// `DEVTOOLS_LOCAL`: whether a browser on the application's own machine gets in without the
    /// key. On by default; turn it off where a proxy or tunnel on the same machine forwards to the
    /// application, such as nginx with `proxy_pass http://127.0.0.1:8000`: its requests look
    /// local.
    #[env("DEVTOOLS_LOCAL", default = true)]
    pub local: bool,
}

/// The key stays out of logs and error messages.
impl fmt::Debug for DevtoolsConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DevtoolsConfig")
            .field("enabled", &self.enabled)
            .field("error_text", &self.error_text)
            .field("key", &self.key.as_ref().map(|_| "[masked]"))
            .field("local", &self.local)
            .finish()
    }
}

/// Turns the developer tools on in an application that registers it.
///
/// They run only in a build with debug assertions, with `APP_ENV=local`, and unless
/// `DEVTOOLS_ENABLED=false`: there the provider records every request, console command, queued
/// job and scheduled task into `storage/devtools`, which belongs in the application's
/// `.gitignore`. Everywhere else, in its tests too, the provider adds nothing. A build without
/// debug assertions, as Cargo's release profile is by default, has nothing of the developer tools
/// compiled in but [`DevtoolsConfig`], so that an application's configuration of it builds either
/// way. What decides is `debug-assertions`, not the profile's name.
///
/// Who sees them: a browser on the application's own machine, unless `DEVTOOLS_LOCAL=false`, and
/// anyone else who entered `DEVTOOLS_KEY`; of those, only whom a [`DevtoolsGate`] lets in, if the
/// application sets one. Everyone else gets neither the toolbar nor its routes, which answer `404`.
///
/// ```no_run
/// use laravel_rust_devtools::DevtoolsServiceProvider;
///
/// laravel::Application::configure().with_providers(|providers| {
///     providers.add(DevtoolsServiceProvider::new());
/// });
/// ```
#[derive(Clone, Default)]
#[must_use]
pub struct DevtoolsServiceProvider {
    #[cfg(debug_assertions)]
    gate: Option<Arc<dyn AnyGate>>,
    #[cfg(debug_assertions)]
    crates: Vec<String>,
}

impl DevtoolsServiceProvider {
    /// The provider, letting in whom the rules above let in.
    ///
    /// ```
    /// let provider = laravel_rust_devtools::DevtoolsServiceProvider::new();
    /// # let _ = provider;
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Let in only whom `gate` allows, of those the rules above let in. A build without debug
    /// assertions has no developer tools, and drops the gate.
    ///
    /// ```
    /// use laravel::http::Request;
    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
    ///
    /// struct Nobody;
    ///
    /// impl DevtoolsGate for Nobody {
    ///     async fn allows(&self, _request: &Request) -> laravel::Result<bool> {
    ///         Ok(false)
    ///     }
    /// }
    ///
    /// let provider = DevtoolsServiceProvider::new().with_gate(Nobody);
    /// # let _ = provider;
    /// ```
    pub fn with_gate(self, gate: impl DevtoolsGate) -> Self {
        #[cfg(debug_assertions)]
        {
            Self {
                gate: Some(Arc::new(gate)),
                ..self
            }
        }
        #[cfg(not(debug_assertions))]
        {
            drop(gate);
            self
        }
    }

    /// Also record the spans and lines of these downloaded crates, such as packages the
    /// application installed from crates.io. Without them, the developer tools record the
    /// framework and the application's own crates, and the packages it builds from a path. Names
    /// may be written with `-` or `_`.
    ///
    /// A line belongs to a crate by its target's first part, which is the crate's name unless the
    /// crate sets targets of its own: name those instead.
    ///
    /// A named crate's lines are recorded by the same rules as the application's: a field whose
    /// name suggests a secret, such as `password`, `token` or `session_id`, as `[masked]`, and
    /// everything else as it was written, the line's message and every field with an ordinary
    /// name. Name only crates whose lines don't carry values that everyone who can read the traces
    /// may not see. Libraries whose lines carry values stay out even when named: `sqlx` and every
    /// crate named `sqlx_*`, `lettre` and `aws_smithy_runtime`. A build without debug assertions has
    /// no developer tools, and drops the names.
    ///
    /// ```
    /// use laravel_rust_devtools::DevtoolsServiceProvider;
    ///
    /// let provider = DevtoolsServiceProvider::new().with_crates(["laravel-rust-permissions"]);
    /// # let _ = provider;
    /// ```
    pub fn with_crates<I>(self, crates: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        #[cfg(debug_assertions)]
        {
            let mut provider = self;
            provider.crates.extend(crates.into_iter().map(Into::into));
            provider
        }
        #[cfg(not(debug_assertions))]
        {
            drop(crates);
            self
        }
    }
}

impl fmt::Debug for DevtoolsServiceProvider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("DevtoolsServiceProvider");
        #[cfg(debug_assertions)]
        debug.field("gate", &self.gate.as_ref().map(|_| "[set]"));
        #[cfg(debug_assertions)]
        debug.field("crates", &self.crates);
        debug.finish()
    }
}

impl ServiceProvider for DevtoolsServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }

    #[cfg(debug_assertions)]
    fn register(&self, app: &mut laravel::container::Registrar) {
        debug::register(app, self.gate.clone(), &self.crates);
    }

    #[cfg(debug_assertions)]
    fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
        std::future::ready(debug::boot(app.config()))
    }
}

/// What the provider does in a build with debug assertions; a build without them has none of it.
#[cfg(debug_assertions)]
mod debug {
    use std::fmt;

    use laravel::config::Config;
    use laravel::config::app::Environment;
    use laravel::container::Registrar;

    use super::{Arc, DevtoolsConfig};
    use crate::collector::Collector;
    use crate::file_store::FileStore;
    use crate::gate::AnyGate;
    use crate::http::Access;
    use crate::store::Store;

    /// The key's shortest length, and its longest, which is the most a password field takes.
    const KEY_LENGTH: std::ops::RangeInclusive<usize> = 32..=laravel::hash::MAX_PASSWORD_BYTES;

    pub(super) fn register(app: &mut Registrar, gate: Option<Arc<dyn AnyGate>>, crates: &[String]) {
        let config = app.config();
        if !runs(config) {
            return;
        }
        let section = config.section::<DevtoolsConfig>();
        let store = Arc::new(FileStore::new(config.app.storage_path("devtools")));
        let collector = Collector::shared(Arc::clone(&store) as Arc<dyn Store>)
            .with_error_text(section.error_text)
            .with_crates(crates.iter().cloned());
        let access = Access::new(section.key.as_deref(), section.local, gate);

        crate::http::register(app, store, collector.key(), access);
        app.logging().layer(collector);
    }

    pub(super) fn boot(config: &Config) -> laravel::Result<()> {
        let environment = &config.app.env;
        let section = config.section::<DevtoolsConfig>();
        let asked = section.enabled == Some(true);
        if asked && !matches!(environment, Environment::Local | Environment::Testing) {
            return Err(EnabledOutsideLocal(environment.as_str().to_owned()).into());
        }
        let key = section.key.as_deref();
        if runs(config) && key.is_some_and(|key| !KEY_LENGTH.contains(&key.len())) {
            return Err(KeyLength.into());
        }

        Ok(())
    }

    /// Whether the developer tools run: with `APP_ENV=local`, unless turned off.
    fn runs(config: &Config) -> bool {
        config.app.env.is_local() && config.section::<DevtoolsConfig>().enabled != Some(false)
    }

    /// `DEVTOOLS_ENABLED=true` in an environment other than `local`, named here.
    #[derive(Debug)]
    struct EnabledOutsideLocal(String);

    impl fmt::Display for EnabledOutsideLocal {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                f,
                "DEVTOOLS_ENABLED=true, but the developer tools only run with APP_ENV=local, and \
                 this application runs with APP_ENV={}{}. Remove DEVTOOLS_ENABLED or set it to false.",
                self.0,
                if self.0 == "production" {
                    " (also what an unset APP_ENV means)"
                } else {
                    ""
                }
            )
        }
    }

    impl std::error::Error for EnabledOutsideLocal {}

    /// `DEVTOOLS_KEY` too short to resist guessing, or too long to enter.
    #[derive(Debug)]
    struct KeyLength;

    impl fmt::Display for KeyLength {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(
                f,
                "DEVTOOLS_KEY must be between {} and {} bytes long. Generate one with \
                 `openssl rand -hex 24`.",
                KEY_LENGTH.start(),
                KEY_LENGTH.end()
            )
        }
    }

    impl std::error::Error for KeyLength {}
}