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