Skip to main content

laravel_rust_devtools/
provider.rs

1//! The service provider that turns the developer tools on in an application.
2
3use std::fmt;
4#[cfg(debug_assertions)]
5use std::sync::Arc;
6
7use laravel::config::{Config, Env, Section};
8use laravel::foundation::ServiceProvider;
9
10#[cfg(debug_assertions)]
11use crate::gate::AnyGate;
12use crate::gate::DevtoolsGate;
13
14/// The developer tools' settings, read from the environment.
15///
16/// An application may change them in `src/app.rs`, after they are read:
17///
18/// ```
19/// use laravel_rust_devtools::DevtoolsConfig;
20///
21/// laravel::Application::configure().with_config(|config, _| {
22///     config.section_mut::<DevtoolsConfig>().error_text = true;
23/// });
24/// ```
25#[derive(Clone, Section)]
26#[non_exhaustive]
27pub struct DevtoolsConfig {
28    /// `DEVTOOLS_ENABLED`: `false` turns the developer tools off where they would run. Unset, they
29    /// run in a build with debug assertions with `APP_ENV=local`. `true` asks for them: such a
30    /// build that runs anywhere else, except in the application's tests, then refuses to start
31    /// rather than run without them unnoticed. A build without debug assertions has none of the
32    /// developer tools and ignores it.
33    #[env("DEVTOOLS_ENABLED")]
34    pub enabled: Option<bool>,
35    /// `DEVTOOLS_ERROR_TEXT`: whether traces record what an error says, which may quote a value.
36    /// Off by default: a trace then keeps an error's kind, where it was raised and when, and records
37    /// its text as `[masked]`, in a reported error, a job that will be retried and every field
38    /// named `error`. Turn it on while looking for a bug. Everyone who can read the traces sees
39    /// those texts, as the developer tools' API at `/_devtools/api` gives them.
40    #[env("DEVTOOLS_ERROR_TEXT", default = false)]
41    pub error_text: bool,
42    /// `DEVTOOLS_KEY`: the key that opens the developer tools to someone who isn't on the
43    /// application's own machine, such as a browser behind a proxy. They enter it once at
44    /// `/_devtools/login`, and a cookie signed with `APP_KEY` lets them in for 12 hours, which the
45    /// application checks itself; a new key shuts out every cookie made with the old one. Between
46    /// 32 and 72 bytes: the application doesn't start with a shorter or longer one. Unset, only the
47    /// machine itself gets in.
48    #[env("DEVTOOLS_KEY")]
49    pub key: Option<String>,
50    /// `DEVTOOLS_LOCAL`: whether a browser on the application's own machine gets in without the
51    /// key. On by default; turn it off where a proxy or tunnel on the same machine forwards to the
52    /// application, such as nginx with `proxy_pass http://127.0.0.1:8000`: its requests look
53    /// local.
54    #[env("DEVTOOLS_LOCAL", default = true)]
55    pub local: bool,
56}
57
58/// The key stays out of logs and error messages.
59impl fmt::Debug for DevtoolsConfig {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.debug_struct("DevtoolsConfig")
62            .field("enabled", &self.enabled)
63            .field("error_text", &self.error_text)
64            .field("key", &self.key.as_ref().map(|_| "[masked]"))
65            .field("local", &self.local)
66            .finish()
67    }
68}
69
70/// Turns the developer tools on in an application that registers it.
71///
72/// They run only in a build with debug assertions, with `APP_ENV=local`, and unless
73/// `DEVTOOLS_ENABLED=false`: there the provider records every request, console command, queued
74/// job and scheduled task into `storage/devtools`, which belongs in the application's
75/// `.gitignore`. Everywhere else, in its tests too, the provider adds nothing. A build without
76/// debug assertions, as Cargo's release profile is by default, has nothing of the developer tools
77/// compiled in but [`DevtoolsConfig`], so that an application's configuration of it builds either
78/// way. What decides is `debug-assertions`, not the profile's name.
79///
80/// Who sees them: a browser on the application's own machine, unless `DEVTOOLS_LOCAL=false`, and
81/// anyone else who entered `DEVTOOLS_KEY`; of those, only whom a [`DevtoolsGate`] lets in, if the
82/// application sets one. Everyone else gets neither the toolbar nor its routes, which answer `404`.
83///
84/// ```no_run
85/// use laravel_rust_devtools::DevtoolsServiceProvider;
86///
87/// laravel::Application::configure().with_providers(|providers| {
88///     providers.add(DevtoolsServiceProvider::new());
89/// });
90/// ```
91#[derive(Clone, Default)]
92#[must_use]
93pub struct DevtoolsServiceProvider {
94    #[cfg(debug_assertions)]
95    gate: Option<Arc<dyn AnyGate>>,
96    #[cfg(debug_assertions)]
97    crates: Vec<String>,
98}
99
100impl DevtoolsServiceProvider {
101    /// The provider, letting in whom the rules above let in.
102    ///
103    /// ```
104    /// let provider = laravel_rust_devtools::DevtoolsServiceProvider::new();
105    /// # let _ = provider;
106    /// ```
107    pub fn new() -> Self {
108        Self::default()
109    }
110
111    /// Let in only whom `gate` allows, of those the rules above let in. A build without debug
112    /// assertions has no developer tools, and drops the gate.
113    ///
114    /// ```
115    /// use laravel::http::Request;
116    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
117    ///
118    /// struct Nobody;
119    ///
120    /// impl DevtoolsGate for Nobody {
121    ///     async fn allows(&self, _request: &Request) -> laravel::Result<bool> {
122    ///         Ok(false)
123    ///     }
124    /// }
125    ///
126    /// let provider = DevtoolsServiceProvider::new().with_gate(Nobody);
127    /// # let _ = provider;
128    /// ```
129    pub fn with_gate(self, gate: impl DevtoolsGate) -> Self {
130        #[cfg(debug_assertions)]
131        {
132            Self {
133                gate: Some(Arc::new(gate)),
134                ..self
135            }
136        }
137        #[cfg(not(debug_assertions))]
138        {
139            drop(gate);
140            self
141        }
142    }
143
144    /// Also record the spans and lines of these downloaded crates, such as packages the
145    /// application installed from crates.io. Without them, the developer tools record the
146    /// framework and the application's own crates, and the packages it builds from a path. Names
147    /// may be written with `-` or `_`.
148    ///
149    /// A line belongs to a crate by its target's first part, which is the crate's name unless the
150    /// crate sets targets of its own: name those instead.
151    ///
152    /// A named crate's lines are recorded by the same rules as the application's: a field whose
153    /// name suggests a secret, such as `password`, `token` or `session_id`, as `[masked]`, and
154    /// everything else as it was written, the line's message and every field with an ordinary
155    /// name. Name only crates whose lines don't carry values that everyone who can read the traces
156    /// may not see. Libraries whose lines carry values stay out even when named: `sqlx` and every
157    /// crate named `sqlx_*`, `lettre` and `aws_smithy_runtime`. A build without debug assertions has
158    /// no developer tools, and drops the names.
159    ///
160    /// ```
161    /// use laravel_rust_devtools::DevtoolsServiceProvider;
162    ///
163    /// let provider = DevtoolsServiceProvider::new().with_crates(["laravel-rust-permissions"]);
164    /// # let _ = provider;
165    /// ```
166    pub fn with_crates<I>(self, crates: I) -> Self
167    where
168        I: IntoIterator,
169        I::Item: Into<String>,
170    {
171        #[cfg(debug_assertions)]
172        {
173            let mut provider = self;
174            provider.crates.extend(crates.into_iter().map(Into::into));
175            provider
176        }
177        #[cfg(not(debug_assertions))]
178        {
179            drop(crates);
180            self
181        }
182    }
183}
184
185impl fmt::Debug for DevtoolsServiceProvider {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        let mut debug = f.debug_struct("DevtoolsServiceProvider");
188        #[cfg(debug_assertions)]
189        debug.field("gate", &self.gate.as_ref().map(|_| "[set]"));
190        #[cfg(debug_assertions)]
191        debug.field("crates", &self.crates);
192        debug.finish()
193    }
194}
195
196impl ServiceProvider for DevtoolsServiceProvider {
197    fn config(&self, config: &mut Config, env: &Env) {
198        config.discover(env!("CARGO_CRATE_NAME"), env);
199    }
200
201    #[cfg(debug_assertions)]
202    fn register(&self, app: &mut laravel::container::Registrar) {
203        debug::register(app, self.gate.clone(), &self.crates);
204    }
205
206    #[cfg(debug_assertions)]
207    fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
208        std::future::ready(debug::boot(app.config()))
209    }
210}
211
212/// What the provider does in a build with debug assertions; a build without them has none of it.
213#[cfg(debug_assertions)]
214mod debug {
215    use std::fmt;
216
217    use laravel::config::Config;
218    use laravel::config::app::Environment;
219    use laravel::container::Registrar;
220
221    use super::{Arc, DevtoolsConfig};
222    use crate::collector::Collector;
223    use crate::file_store::FileStore;
224    use crate::gate::AnyGate;
225    use crate::http::Access;
226    use crate::store::Store;
227
228    /// The key's shortest length, and its longest, which is the most a password field takes.
229    const KEY_LENGTH: std::ops::RangeInclusive<usize> = 32..=laravel::hash::MAX_PASSWORD_BYTES;
230
231    pub(super) fn register(app: &mut Registrar, gate: Option<Arc<dyn AnyGate>>, crates: &[String]) {
232        let config = app.config();
233        if !runs(config) {
234            return;
235        }
236        let section = config.section::<DevtoolsConfig>();
237        let store = Arc::new(FileStore::new(config.app.storage_path("devtools")));
238        let collector = Collector::shared(Arc::clone(&store) as Arc<dyn Store>)
239            .with_error_text(section.error_text)
240            .with_crates(crates.iter().cloned());
241        let access = Access::new(section.key.as_deref(), section.local, gate);
242
243        crate::http::register(app, store, collector.key(), access);
244        app.logging().layer(collector);
245    }
246
247    pub(super) fn boot(config: &Config) -> laravel::Result<()> {
248        let environment = &config.app.env;
249        let section = config.section::<DevtoolsConfig>();
250        let asked = section.enabled == Some(true);
251        if asked && !matches!(environment, Environment::Local | Environment::Testing) {
252            return Err(EnabledOutsideLocal(environment.as_str().to_owned()).into());
253        }
254        let key = section.key.as_deref();
255        if runs(config) && key.is_some_and(|key| !KEY_LENGTH.contains(&key.len())) {
256            return Err(KeyLength.into());
257        }
258
259        Ok(())
260    }
261
262    /// Whether the developer tools run: with `APP_ENV=local`, unless turned off.
263    fn runs(config: &Config) -> bool {
264        config.app.env.is_local() && config.section::<DevtoolsConfig>().enabled != Some(false)
265    }
266
267    /// `DEVTOOLS_ENABLED=true` in an environment other than `local`, named here.
268    #[derive(Debug)]
269    struct EnabledOutsideLocal(String);
270
271    impl fmt::Display for EnabledOutsideLocal {
272        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273            write!(
274                f,
275                "DEVTOOLS_ENABLED=true, but the developer tools only run with APP_ENV=local, and \
276                 this application runs with APP_ENV={}{}. Remove DEVTOOLS_ENABLED or set it to false.",
277                self.0,
278                if self.0 == "production" {
279                    " (also what an unset APP_ENV means)"
280                } else {
281                    ""
282                }
283            )
284        }
285    }
286
287    impl std::error::Error for EnabledOutsideLocal {}
288
289    /// `DEVTOOLS_KEY` too short to resist guessing, or too long to enter.
290    #[derive(Debug)]
291    struct KeyLength;
292
293    impl fmt::Display for KeyLength {
294        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295            write!(
296                f,
297                "DEVTOOLS_KEY must be between {} and {} bytes long. Generate one with \
298                 `openssl rand -hex 24`.",
299                KEY_LENGTH.start(),
300                KEY_LENGTH.end()
301            )
302        }
303    }
304
305    impl std::error::Error for KeyLength {}
306}