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
10use crate::gate::DevtoolsGate;
11#[cfg(debug_assertions)]
12use crate::gate::Gate;
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 with [`with_gate`](Self::with_gate). A gate set with
83/// [`with_admitting_gate`](Self::with_admitting_gate) lets in whom it allows besides them. Everyone
84/// else gets neither the toolbar nor its routes, which answer `404`.
85///
86/// ```no_run
87/// use laravel_rust_devtools::DevtoolsServiceProvider;
88///
89/// laravel::Application::configure().with_providers(|providers| {
90///     providers.add(DevtoolsServiceProvider::new());
91/// });
92/// ```
93#[derive(Clone, Default)]
94#[must_use]
95pub struct DevtoolsServiceProvider {
96    #[cfg(debug_assertions)]
97    gate: Option<Gate>,
98    #[cfg(debug_assertions)]
99    crates: Vec<String>,
100}
101
102impl DevtoolsServiceProvider {
103    /// The provider, letting in whom the rules above let in.
104    ///
105    /// ```
106    /// let provider = laravel_rust_devtools::DevtoolsServiceProvider::new();
107    /// # let _ = provider;
108    /// ```
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    /// Whether the developer tools run in the application with this configuration: in a build with
114    /// debug assertions, with `APP_ENV=local`, unless `DEVTOOLS_ENABLED=false`. An application asks
115    /// this before it offers anything of its own about them, such as a switch for its gate, so that
116    /// it shows nothing where they don't run.
117    ///
118    /// In the application's tests, with `APP_ENV=testing`, the developer tools never run, but
119    /// `DEVTOOLS_ENABLED=true` makes the answer `true`, so that the tests can reach what the
120    /// application offers where they do. Without this provider among the application's, the
121    /// answer is `false`.
122    ///
123    /// ```
124    /// use laravel_rust_devtools::DevtoolsServiceProvider;
125    ///
126    /// let app = laravel::Application::configure().create();
127    /// let offered = DevtoolsServiceProvider::is_active(app.config());
128    /// # let _ = offered;
129    /// ```
130    #[must_use]
131    pub fn is_active(config: &Config) -> bool {
132        #[cfg(debug_assertions)]
133        {
134            debug::runs(config) || debug::asked_in_tests(config)
135        }
136        #[cfg(not(debug_assertions))]
137        {
138            let _ = config;
139            false
140        }
141    }
142
143    /// Let in only whom `gate` allows, of those the rules above let in. It replaces a gate set
144    /// before. A build without debug assertions has no developer tools, and drops the gate.
145    ///
146    /// ```
147    /// use laravel::http::Request;
148    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
149    ///
150    /// struct Nobody;
151    ///
152    /// impl DevtoolsGate for Nobody {
153    ///     async fn allows(&self, _request: &Request) -> laravel::Result<bool> {
154    ///         Ok(false)
155    ///     }
156    /// }
157    ///
158    /// let provider = DevtoolsServiceProvider::new().with_gate(Nobody);
159    /// # let _ = provider;
160    /// ```
161    pub fn with_gate(self, gate: impl DevtoolsGate) -> Self {
162        #[cfg(debug_assertions)]
163        {
164            Self {
165                gate: Some(Gate::Narrowing(Arc::new(gate))),
166                ..self
167            }
168        }
169        #[cfg(not(debug_assertions))]
170        {
171            drop(gate);
172            self
173        }
174    }
175
176    /// Let in whom `gate` allows as well as whom the rules above let in, such as the application's
177    /// administrators in a browser behind a proxy, without the key. It replaces a gate set before.
178    ///
179    /// The gate is asked for every request the rules keep out, after the session has started.
180    /// Before then, the developer tools can't tell whom it will let in, so their routes take
181    /// everyone's requests for the methods they have, and answer `404` to whom the gate turns away,
182    /// before any CSRF check: the answer the application gives a path that doesn't exist, as long
183    /// as its fallback answers with `laravel::abort(404)` without the CSRF check, as the README
184    /// shows. With `APP_DEBUG=true`, the error page of an error before the gate, or in it, names
185    /// the route it was meant for. A build without debug assertions has no developer tools, and
186    /// drops the gate.
187    ///
188    /// ```
189    /// use laravel::http::Request;
190    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
191    ///
192    /// /// Those logged in, wherever their browser is.
193    /// struct LoggedIn;
194    ///
195    /// impl DevtoolsGate for LoggedIn {
196    ///     async fn allows(&self, request: &Request) -> laravel::Result<bool> {
197    ///         request.authenticated().await
198    ///     }
199    /// }
200    ///
201    /// let provider = DevtoolsServiceProvider::new().with_admitting_gate(LoggedIn);
202    /// # let _ = provider;
203    /// ```
204    pub fn with_admitting_gate(self, gate: impl DevtoolsGate) -> Self {
205        #[cfg(debug_assertions)]
206        {
207            Self {
208                gate: Some(Gate::Admitting(Arc::new(gate))),
209                ..self
210            }
211        }
212        #[cfg(not(debug_assertions))]
213        {
214            drop(gate);
215            self
216        }
217    }
218
219    /// Also record the spans and lines of these downloaded crates, such as packages the
220    /// application installed from crates.io. Without them, the developer tools record the
221    /// framework and the application's own crates, and the packages it builds from a path. Names
222    /// may be written with `-` or `_`.
223    ///
224    /// A line belongs to a crate by its target's first part, which is the crate's name unless the
225    /// crate sets targets of its own: name those instead.
226    ///
227    /// A named crate's lines are recorded by the same rules as the application's: a field whose
228    /// name suggests a secret, such as `password`, `token` or `session_id`, as `[masked]`, and
229    /// everything else as it was written, the line's message and every field with an ordinary
230    /// name. Name only crates whose lines don't carry values that everyone who can read the traces
231    /// may not see. Libraries whose lines carry values stay out even when named: `sqlx` and every
232    /// crate named `sqlx_*`, `lettre` and `aws_smithy_runtime`. A build without debug assertions has
233    /// no developer tools, and drops the names.
234    ///
235    /// ```
236    /// use laravel_rust_devtools::DevtoolsServiceProvider;
237    ///
238    /// let provider = DevtoolsServiceProvider::new().with_crates(["laravel-rust-permissions"]);
239    /// # let _ = provider;
240    /// ```
241    pub fn with_crates<I>(self, crates: I) -> Self
242    where
243        I: IntoIterator,
244        I::Item: Into<String>,
245    {
246        #[cfg(debug_assertions)]
247        {
248            let mut provider = self;
249            provider.crates.extend(crates.into_iter().map(Into::into));
250            provider
251        }
252        #[cfg(not(debug_assertions))]
253        {
254            drop(crates);
255            self
256        }
257    }
258}
259
260impl fmt::Debug for DevtoolsServiceProvider {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        let mut debug = f.debug_struct("DevtoolsServiceProvider");
263        #[cfg(debug_assertions)]
264        debug.field(
265            "gate",
266            &self.gate.as_ref().map(|gate| match gate {
267                Gate::Narrowing(_) => "[narrowing]",
268                Gate::Admitting(_) => "[admitting]",
269            }),
270        );
271        #[cfg(debug_assertions)]
272        debug.field("crates", &self.crates);
273        debug.finish()
274    }
275}
276
277impl ServiceProvider for DevtoolsServiceProvider {
278    fn config(&self, config: &mut Config, env: &Env) {
279        config.discover(env!("CARGO_CRATE_NAME"), env);
280    }
281
282    #[cfg(debug_assertions)]
283    fn register(&self, app: &mut laravel::container::Registrar) {
284        debug::register(app, self.gate.clone(), &self.crates);
285    }
286
287    #[cfg(debug_assertions)]
288    fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
289        std::future::ready(debug::boot(app.config()))
290    }
291}
292
293/// What the provider does in a build with debug assertions; a build without them has none of it.
294#[cfg(debug_assertions)]
295mod debug {
296    use std::fmt;
297
298    use laravel::config::Config;
299    use laravel::config::app::Environment;
300    use laravel::container::Registrar;
301
302    use super::{Arc, DevtoolsConfig};
303    use crate::collector::Collector;
304    use crate::file_store::FileStore;
305    use crate::gate::Gate;
306    use crate::http::Access;
307    use crate::store::Store;
308
309    /// The key's shortest length, and its longest, which is the most a password field takes.
310    const KEY_LENGTH: std::ops::RangeInclusive<usize> = 32..=laravel::hash::MAX_PASSWORD_BYTES;
311
312    pub(super) fn register(app: &mut Registrar, gate: Option<Gate>, crates: &[String]) {
313        let config = app.config();
314        if !runs(config) {
315            return;
316        }
317        let section = config.section::<DevtoolsConfig>();
318        let store = Arc::new(FileStore::new(config.app.storage_path("devtools")));
319        let collector = Collector::shared(Arc::clone(&store) as Arc<dyn Store>)
320            .with_error_text(section.error_text)
321            .with_crates(crates.iter().cloned());
322        let access = Access::new(section.key.as_deref(), section.local, gate);
323
324        crate::http::register(app, store, collector.key(), access);
325        app.logging().layer(collector);
326    }
327
328    pub(super) fn boot(config: &Config) -> laravel::Result<()> {
329        let environment = &config.app.env;
330        let section = config.section::<DevtoolsConfig>();
331        let asked = section.enabled == Some(true);
332        if asked && !matches!(environment, Environment::Local | Environment::Testing) {
333            return Err(EnabledOutsideLocal(environment.as_str().to_owned()).into());
334        }
335        let key = section.key.as_deref();
336        if runs(config) && key.is_some_and(|key| !KEY_LENGTH.contains(&key.len())) {
337            return Err(KeyLength.into());
338        }
339
340        Ok(())
341    }
342
343    /// Whether the developer tools run: with `APP_ENV=local`, unless turned off.
344    pub(super) fn runs(config: &Config) -> bool {
345        config.app.env.is_local() && enabled(config) != Some(false)
346    }
347
348    /// Whether the application's tests ask for the developer tools, which don't run there.
349    pub(super) fn asked_in_tests(config: &Config) -> bool {
350        config.app.env == Environment::Testing && enabled(config) == Some(true)
351    }
352
353    /// `DEVTOOLS_ENABLED`. Without the provider, the configuration has no section of theirs, and
354    /// that counts as turned off.
355    fn enabled(config: &Config) -> Option<bool> {
356        config
357            .get::<DevtoolsConfig>()
358            .map_or(Some(false), |section| section.enabled)
359    }
360
361    /// `DEVTOOLS_ENABLED=true` in an environment other than `local`, named here.
362    #[derive(Debug)]
363    struct EnabledOutsideLocal(String);
364
365    impl fmt::Display for EnabledOutsideLocal {
366        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367            write!(
368                f,
369                "DEVTOOLS_ENABLED=true, but the developer tools only run with APP_ENV=local, and \
370                 this application runs with APP_ENV={}{}. Remove DEVTOOLS_ENABLED or set it to false.",
371                self.0,
372                if self.0 == "production" {
373                    " (also what an unset APP_ENV means)"
374                } else {
375                    ""
376                }
377            )
378        }
379    }
380
381    impl std::error::Error for EnabledOutsideLocal {}
382
383    /// `DEVTOOLS_KEY` too short to resist guessing, or too long to enter.
384    #[derive(Debug)]
385    struct KeyLength;
386
387    impl fmt::Display for KeyLength {
388        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389            write!(
390                f,
391                "DEVTOOLS_KEY must be between {} and {} bytes long. Generate one with \
392                 `openssl rand -hex 24`.",
393                KEY_LENGTH.start(),
394                KEY_LENGTH.end()
395            )
396        }
397    }
398
399    impl std::error::Error for KeyLength {}
400}