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;
4use std::str::FromStr;
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`: whether the developer tools run where they may, as [`Enabled`] says.
29    #[env("DEVTOOLS_ENABLED")]
30    pub enabled: Enabled,
31    /// `DEVTOOLS_ERROR_TEXT`: whether traces record what an error says, which may quote a value.
32    /// Off by default: a trace then keeps an error's kind, where it was raised and when, and records
33    /// its text as `[masked]`, in a reported error, a job that will be retried and every field
34    /// named `error`. Turn it on while looking for a bug. Everyone who can read the traces sees
35    /// those texts, as the developer tools' API at `/_devtools/api` gives them.
36    #[env("DEVTOOLS_ERROR_TEXT", default = false)]
37    pub error_text: bool,
38    /// `DEVTOOLS_KEY`: the key that opens the developer tools to someone who isn't on the
39    /// application's own machine, such as a browser behind a proxy. They enter it once at
40    /// `/_devtools/login`, and a cookie signed with `APP_KEY` lets them in for 12 hours, which the
41    /// application checks itself; a new key shuts out every cookie made with the old one. Between
42    /// 32 and 72 bytes: a build with debug assertions doesn't start with a shorter or longer one.
43    /// Unset, only the machine itself gets in. A build without debug assertions has none of the
44    /// developer tools, ignores the key and logs a warning that it is set.
45    #[env("DEVTOOLS_KEY")]
46    pub key: Option<DevtoolsKey>,
47    /// `DEVTOOLS_LOCAL`: whether a browser on the application's own machine gets in without the
48    /// key. On by default; turn it off where a proxy or tunnel on the same machine forwards to the
49    /// application, such as nginx with `proxy_pass http://127.0.0.1:8000`: its requests look
50    /// local.
51    #[env("DEVTOOLS_LOCAL", default = true)]
52    pub local: bool,
53}
54
55/// `DEVTOOLS_ENABLED`, read as `true` or `false`, or the framework's other ways to write them,
56/// such as `1` or `off`.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum Enabled {
60    /// Unset: the developer tools run in a build with debug assertions with `APP_ENV=local`.
61    #[default]
62    Auto,
63    /// `false`: they don't run, wherever they would.
64    Off,
65    /// `true`: they must run. A build with debug assertions that runs with any `APP_ENV` but
66    /// `local` then refuses to start rather than run without them unnoticed, except in the
67    /// application's tests. A build without debug assertions has none of the developer tools: it
68    /// starts without them and logs a warning that they were asked for.
69    Required,
70}
71
72impl FromStr for Enabled {
73    type Err = ParseEnabledError;
74
75    fn from_str(value: &str) -> Result<Self, Self::Err> {
76        match value {
77            "true" => Ok(Self::Required),
78            "false" => Ok(Self::Off),
79            _ => Err(ParseEnabledError),
80        }
81    }
82}
83
84/// `DEVTOOLS_ENABLED` is neither `true` nor `false`.
85#[derive(Clone, Debug, PartialEq, Eq)]
86#[non_exhaustive]
87pub struct ParseEnabledError;
88
89impl fmt::Display for ParseEnabledError {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        f.write_str("expected `true` or `false`, or leave it unset")
92    }
93}
94
95impl std::error::Error for ParseEnabledError {}
96
97/// `DEVTOOLS_KEY`, the key that opens the developer tools to a browser on another machine.
98///
99/// It shows as `[masked]` in debug output and has no `Display`, so it stays out of logs and error
100/// messages. A build without debug assertions has no developer tools, and drops the key.
101///
102/// ```
103/// use laravel_rust_devtools::{DevtoolsConfig, DevtoolsKey};
104///
105/// laravel::Application::configure().with_config(|config, _| {
106///     config.section_mut::<DevtoolsConfig>().key = Some(DevtoolsKey::new("a key from a secret store"));
107/// });
108/// ```
109#[derive(Clone)]
110pub struct DevtoolsKey {
111    #[cfg(debug_assertions)]
112    key: Arc<str>,
113}
114
115impl DevtoolsKey {
116    /// The key `key`.
117    pub fn new(key: impl Into<Arc<str>>) -> Self {
118        #[cfg(debug_assertions)]
119        {
120            Self { key: key.into() }
121        }
122        #[cfg(not(debug_assertions))]
123        {
124            drop(key);
125            Self {}
126        }
127    }
128
129    #[cfg(debug_assertions)]
130    pub(crate) fn expose(&self) -> &str {
131        &self.key
132    }
133}
134
135/// Any text is a key: its length is checked where the developer tools run, when the application
136/// boots, so that a build without them never refuses to start for it.
137impl FromStr for DevtoolsKey {
138    type Err = std::convert::Infallible;
139
140    fn from_str(key: &str) -> Result<Self, Self::Err> {
141        Ok(Self::new(key))
142    }
143}
144
145impl fmt::Debug for DevtoolsKey {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.write_str("DevtoolsKey([masked])")
148    }
149}
150
151impl fmt::Debug for DevtoolsConfig {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("DevtoolsConfig")
154            .field("enabled", &self.enabled)
155            .field("error_text", &self.error_text)
156            .field("key", &self.key)
157            .field("local", &self.local)
158            .finish()
159    }
160}
161
162/// Turns the developer tools on in an application that registers it.
163///
164/// They run only in a build with debug assertions, with `APP_ENV=local`, and unless
165/// `DEVTOOLS_ENABLED=false`: there the provider records every request, console command, queued
166/// job and scheduled task into `storage/devtools`, which belongs in the application's
167/// `.gitignore`. Everywhere else, in its tests too, the provider adds nothing. A build without
168/// debug assertions, as Cargo's release profile is by default, has nothing of the developer tools
169/// compiled in but [`DevtoolsConfig`], so that an application's configuration of it builds either
170/// way. What decides is `debug-assertions`, not the profile's name.
171///
172/// Who sees them: a browser on the application's own machine, unless `DEVTOOLS_LOCAL=false`, and
173/// anyone else who entered `DEVTOOLS_KEY`; of those, only whom a [`DevtoolsGate`] lets in, if the
174/// application sets one with [`with_gate`](Self::with_gate). A gate set with
175/// [`with_admitting_gate`](Self::with_admitting_gate) lets in whom it allows besides them. Everyone
176/// else gets neither the toolbar nor its routes, which answer `404`.
177///
178/// ```no_run
179/// use laravel_rust_devtools::DevtoolsServiceProvider;
180///
181/// laravel::Application::configure().with_providers(|providers| {
182///     providers.add(DevtoolsServiceProvider::new());
183/// });
184/// ```
185#[derive(Clone, Default)]
186#[must_use]
187pub struct DevtoolsServiceProvider {
188    #[cfg(debug_assertions)]
189    gate: Option<Gate>,
190    #[cfg(debug_assertions)]
191    crates: Vec<String>,
192}
193
194impl DevtoolsServiceProvider {
195    /// The provider, letting in whom the rules above let in.
196    ///
197    /// ```
198    /// let provider = laravel_rust_devtools::DevtoolsServiceProvider::new();
199    /// # let _ = provider;
200    /// ```
201    pub fn new() -> Self {
202        Self::default()
203    }
204
205    /// Whether the developer tools run in the application with this configuration: in a build with
206    /// debug assertions, with `APP_ENV=local`, unless `DEVTOOLS_ENABLED=false`. An application asks
207    /// this before it offers anything of its own about them, such as a switch for its gate, so that
208    /// it shows nothing where they don't run.
209    ///
210    /// In the application's tests, with `APP_ENV=testing`, the developer tools never run, but
211    /// `DEVTOOLS_ENABLED=true` makes the answer `true`, so that the tests can reach what the
212    /// application offers where they do. Without this provider among the application's, the
213    /// answer is `false`.
214    ///
215    /// ```
216    /// use laravel_rust_devtools::DevtoolsServiceProvider;
217    ///
218    /// let app = laravel::Application::configure().create();
219    /// let offered = DevtoolsServiceProvider::is_active(app.config());
220    /// # let _ = offered;
221    /// ```
222    #[must_use]
223    pub fn is_active(config: &Config) -> bool {
224        #[cfg(debug_assertions)]
225        {
226            debug::runs(config) || debug::asked_in_tests(config)
227        }
228        #[cfg(not(debug_assertions))]
229        {
230            let _ = config;
231            false
232        }
233    }
234
235    /// Let in only whom `gate` allows, of those the rules above let in. It replaces a gate set
236    /// before. A build without debug assertions has no developer tools, and drops the gate.
237    ///
238    /// ```
239    /// use laravel::http::Request;
240    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
241    ///
242    /// struct Nobody;
243    ///
244    /// impl DevtoolsGate for Nobody {
245    ///     async fn allows(&self, _request: &Request) -> laravel::Result<bool> {
246    ///         Ok(false)
247    ///     }
248    /// }
249    ///
250    /// let provider = DevtoolsServiceProvider::new().with_gate(Nobody);
251    /// # let _ = provider;
252    /// ```
253    pub fn with_gate(self, gate: impl DevtoolsGate) -> Self {
254        #[cfg(debug_assertions)]
255        {
256            Self {
257                gate: Some(Gate::Narrowing(Arc::new(gate))),
258                ..self
259            }
260        }
261        #[cfg(not(debug_assertions))]
262        {
263            drop(gate);
264            self
265        }
266    }
267
268    /// Let in whom `gate` allows as well as whom the rules above let in, such as the application's
269    /// administrators in a browser behind a proxy, without the key. It replaces a gate set before.
270    ///
271    /// The gate is asked for every request the rules keep out, after the session has started.
272    /// Before then, the developer tools can't tell whom it will let in, so their routes take
273    /// everyone's requests for the methods they have, and answer `404` to whom the gate turns away,
274    /// before any CSRF check: the answer the application gives a path that doesn't exist, as long
275    /// as its fallback answers with `laravel::abort(404)` without the CSRF check, as the README
276    /// shows. With `APP_DEBUG=true`, the error page of an error before the gate, or in it, names
277    /// the route it was meant for. A build without debug assertions has no developer tools, and
278    /// drops the gate.
279    ///
280    /// ```
281    /// use laravel::http::Request;
282    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
283    ///
284    /// /// Those logged in, wherever their browser is.
285    /// struct LoggedIn;
286    ///
287    /// impl DevtoolsGate for LoggedIn {
288    ///     async fn allows(&self, request: &Request) -> laravel::Result<bool> {
289    ///         request.authenticated().await
290    ///     }
291    /// }
292    ///
293    /// let provider = DevtoolsServiceProvider::new().with_admitting_gate(LoggedIn);
294    /// # let _ = provider;
295    /// ```
296    pub fn with_admitting_gate(self, gate: impl DevtoolsGate) -> Self {
297        #[cfg(debug_assertions)]
298        {
299            Self {
300                gate: Some(Gate::Admitting(Arc::new(gate))),
301                ..self
302            }
303        }
304        #[cfg(not(debug_assertions))]
305        {
306            drop(gate);
307            self
308        }
309    }
310
311    /// Also record the spans and lines of these downloaded crates, such as packages the
312    /// application installed from crates.io. Without them, the developer tools record the
313    /// framework and the application's own crates, and the packages it builds from a path. Names
314    /// may be written with `-` or `_`.
315    ///
316    /// A line belongs to a crate by its target's first part, which is the crate's name unless the
317    /// crate sets targets of its own: name those instead.
318    ///
319    /// A named crate's lines are recorded by the same rules as the application's: a field whose
320    /// name suggests a secret, such as `password`, `token` or `session_id`, as `[masked]`, and
321    /// everything else as it was written, the line's message and every field with an ordinary
322    /// name. Name only crates whose lines don't carry values that everyone who can read the traces
323    /// may not see. Libraries whose lines carry values stay out even when named: `sqlx` and every
324    /// crate named `sqlx_*`, `lettre` and `aws_smithy_runtime`. A build without debug assertions has
325    /// no developer tools, and drops the names.
326    ///
327    /// ```
328    /// use laravel_rust_devtools::DevtoolsServiceProvider;
329    ///
330    /// let provider = DevtoolsServiceProvider::new().with_crates(["laravel-rust-permissions"]);
331    /// # let _ = provider;
332    /// ```
333    pub fn with_crates<I>(self, crates: I) -> Self
334    where
335        I: IntoIterator,
336        I::Item: Into<String>,
337    {
338        #[cfg(debug_assertions)]
339        {
340            let mut provider = self;
341            provider.crates.extend(crates.into_iter().map(Into::into));
342            provider
343        }
344        #[cfg(not(debug_assertions))]
345        {
346            drop(crates);
347            self
348        }
349    }
350}
351
352impl fmt::Debug for DevtoolsServiceProvider {
353    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354        let mut debug = f.debug_struct("DevtoolsServiceProvider");
355        #[cfg(debug_assertions)]
356        debug.field(
357            "gate",
358            &self.gate.as_ref().map(|gate| match gate {
359                Gate::Narrowing(_) => "[narrowing]",
360                Gate::Admitting(_) => "[admitting]",
361            }),
362        );
363        #[cfg(debug_assertions)]
364        debug.field("crates", &self.crates);
365        debug.finish()
366    }
367}
368
369impl ServiceProvider for DevtoolsServiceProvider {
370    fn config(&self, config: &mut Config, env: &Env) {
371        config.discover(env!("CARGO_CRATE_NAME"), env);
372    }
373
374    #[cfg(debug_assertions)]
375    fn register(&self, app: &mut laravel::container::Registrar) {
376        debug::register(app, self.gate.clone(), &self.crates);
377    }
378
379    #[cfg(debug_assertions)]
380    fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
381        std::future::ready(debug::boot(app.config()))
382    }
383
384    #[cfg(not(debug_assertions))]
385    fn boot(&self, app: &laravel::container::Container) -> impl Future<Output = laravel::Result<()>> + Send {
386        warn_of_what_this_build_ignores(app.config().section::<DevtoolsConfig>());
387        std::future::ready(Ok(()))
388    }
389}
390
391/// A build without debug assertions has no developer tools to start. What asks for them is
392/// ignored, and the log says so, since it may be meant for another build or leak where it doesn't
393/// belong.
394#[cfg(not(debug_assertions))]
395fn warn_of_what_this_build_ignores(section: &DevtoolsConfig) {
396    if section.enabled == Enabled::Required {
397        tracing::warn!(
398            "DEVTOOLS_ENABLED=true is ignored: this build has no developer tools, as it was built \
399             without debug assertions. Remove DEVTOOLS_ENABLED from this environment."
400        );
401    }
402    if section.key.is_some() {
403        tracing::warn!(
404            "DEVTOOLS_KEY is ignored: this build has no developer tools, as it was built without \
405             debug assertions. Remove the key from this environment."
406        );
407    }
408}
409
410/// What the provider does in a build with debug assertions; a build without them has none of it.
411#[cfg(debug_assertions)]
412mod debug {
413    use std::fmt;
414
415    use laravel::config::Config;
416    use laravel::config::app::Environment;
417    use laravel::container::Registrar;
418
419    use super::{Arc, DevtoolsConfig, DevtoolsKey, Enabled};
420    use crate::collector::Collector;
421    use crate::file_store::FileStore;
422    use crate::gate::Gate;
423    use crate::http::Access;
424    use crate::store::Store;
425
426    /// The key's shortest length, and its longest, which is the most a password field takes.
427    const KEY_LENGTH: std::ops::RangeInclusive<usize> = 32..=laravel::hash::MAX_PASSWORD_BYTES;
428
429    pub(super) fn register(app: &mut Registrar, gate: Option<Gate>, crates: &[String]) {
430        let config = app.config();
431        if !runs(config) {
432            return;
433        }
434        let section = config.section::<DevtoolsConfig>();
435        let store = Arc::new(FileStore::new(config.app.storage_path("devtools")));
436        let collector = Collector::shared(Arc::clone(&store) as Arc<dyn Store>)
437            .with_error_text(section.error_text)
438            .with_crates(crates.iter().cloned());
439        let access = Access::new(section.key.clone(), section.local, gate);
440
441        crate::http::register(app, store, collector.key(), access);
442        app.logging().layer(collector);
443    }
444
445    pub(super) fn boot(config: &Config) -> laravel::Result<()> {
446        let environment = &config.app.env;
447        let section = config.section::<DevtoolsConfig>();
448        let required = section.enabled == Enabled::Required;
449        if required && !matches!(environment, Environment::Local | Environment::Testing) {
450            return Err(EnabledOutsideLocal(environment.clone()).into());
451        }
452        let key = section.key.as_ref().map(DevtoolsKey::expose);
453        if runs(config) && key.is_some_and(|key| !KEY_LENGTH.contains(&key.len())) {
454            return Err(KeyLength.into());
455        }
456
457        Ok(())
458    }
459
460    /// Whether the developer tools run: with `APP_ENV=local`, unless turned off.
461    pub(super) fn runs(config: &Config) -> bool {
462        config.app.env.is_local() && enabled(config) != Enabled::Off
463    }
464
465    /// Whether the application's tests ask for the developer tools, which don't run there.
466    pub(super) fn asked_in_tests(config: &Config) -> bool {
467        config.app.env == Environment::Testing && enabled(config) == Enabled::Required
468    }
469
470    /// `DEVTOOLS_ENABLED`. Without the provider, the configuration has no section of theirs, and
471    /// that counts as turned off.
472    fn enabled(config: &Config) -> Enabled {
473        config
474            .get::<DevtoolsConfig>()
475            .map_or(Enabled::Off, |section| section.enabled)
476    }
477
478    /// `DEVTOOLS_ENABLED=true` in an environment other than `local`, named here.
479    #[derive(Debug)]
480    struct EnabledOutsideLocal(Environment);
481
482    impl fmt::Display for EnabledOutsideLocal {
483        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
484            write!(
485                f,
486                "DEVTOOLS_ENABLED=true, but the developer tools only run with APP_ENV=local, and \
487                 this application runs with APP_ENV={}{}. Remove DEVTOOLS_ENABLED or set it to false.",
488                self.0.as_str(),
489                if matches!(self.0, Environment::Production) {
490                    " (also what an unset APP_ENV means)"
491                } else {
492                    ""
493                }
494            )
495        }
496    }
497
498    impl std::error::Error for EnabledOutsideLocal {}
499
500    /// `DEVTOOLS_KEY` too short to resist guessing, or too long to enter.
501    #[derive(Debug)]
502    struct KeyLength;
503
504    impl fmt::Display for KeyLength {
505        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506            write!(
507                f,
508                "DEVTOOLS_KEY must be between {} and {} bytes long. Generate one with \
509                 `openssl rand -hex 24`.",
510                KEY_LENGTH.start(),
511                KEY_LENGTH.end()
512            )
513        }
514    }
515
516    impl std::error::Error for KeyLength {}
517}