laravel-rust-devtools 0.4.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! The service provider that turns the developer tools on in an application.

use std::fmt;
use std::str::FromStr;
use std::sync::Arc;

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

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

/// 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`: whether the developer tools run where they may, as [`Enabled`] says.
    #[env("DEVTOOLS_ENABLED")]
    pub enabled: Enabled,
    /// `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: a build with debug assertions doesn't start with a shorter or longer one.
    /// Unset, only the machine itself gets in. A build without debug assertions has none of the
    /// developer tools, ignores the key and logs a warning that it is set.
    #[env("DEVTOOLS_KEY")]
    pub key: Option<DevtoolsKey>,
    /// `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,
}

/// `DEVTOOLS_ENABLED`, read as `true` or `false`, or the framework's other ways to write them,
/// such as `1` or `off`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Enabled {
    /// Unset: the developer tools run in a build with debug assertions with `APP_ENV=local`.
    #[default]
    Auto,
    /// `false`: they don't run, wherever they would.
    Off,
    /// `true`: they must run. A build with debug assertions that runs with any `APP_ENV` but
    /// `local` then refuses to start rather than run without them unnoticed, except in the
    /// application's tests. A build without debug assertions has none of the developer tools: it
    /// starts without them and logs a warning that they were asked for.
    Required,
}

impl FromStr for Enabled {
    type Err = ParseEnabledError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "true" => Ok(Self::Required),
            "false" => Ok(Self::Off),
            _ => Err(ParseEnabledError),
        }
    }
}

/// `DEVTOOLS_ENABLED` is neither `true` nor `false`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseEnabledError;

impl fmt::Display for ParseEnabledError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("expected `true` or `false`, or leave it unset")
    }
}

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

/// `DEVTOOLS_KEY`, the key that opens the developer tools to a browser on another machine.
///
/// It shows as `[masked]` in debug output and has no `Display`, so it stays out of logs and error
/// messages. A build without debug assertions has no developer tools, and drops the key.
///
/// ```
/// use laravel_rust_devtools::{DevtoolsConfig, DevtoolsKey};
///
/// laravel::Application::configure().with_config(|config, _| {
///     config.section_mut::<DevtoolsConfig>().key = Some(DevtoolsKey::new("a key from a secret store"));
/// });
/// ```
#[derive(Clone)]
pub struct DevtoolsKey {
    #[cfg(debug_assertions)]
    key: Arc<str>,
}

impl DevtoolsKey {
    /// The key `key`.
    pub fn new(key: impl Into<Arc<str>>) -> Self {
        #[cfg(debug_assertions)]
        {
            Self { key: key.into() }
        }
        #[cfg(not(debug_assertions))]
        {
            drop(key);
            Self {}
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn expose(&self) -> &str {
        &self.key
    }
}

/// Any text is a key: its length is checked where the developer tools run, when the application
/// boots, so that a build without them never refuses to start for it.
impl FromStr for DevtoolsKey {
    type Err = std::convert::Infallible;

    fn from_str(key: &str) -> Result<Self, Self::Err> {
        Ok(Self::new(key))
    }
}

impl fmt::Debug for DevtoolsKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("DevtoolsKey([masked])")
    }
}

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)
            .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 with [`with_gate`](Self::with_gate). A gate set with
/// [`with_admitting_gate`](Self::with_admitting_gate) lets in whom it allows besides them. 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<Gate>,
    #[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()
    }

    /// Whether the developer tools run in the application with this configuration: in a build with
    /// debug assertions, with `APP_ENV=local`, unless `DEVTOOLS_ENABLED=false`. An application asks
    /// this before it offers anything of its own about them, such as a switch for its gate, so that
    /// it shows nothing where they don't run.
    ///
    /// In the application's tests, with `APP_ENV=testing`, the developer tools never run, but
    /// `DEVTOOLS_ENABLED=true` makes the answer `true`, so that the tests can reach what the
    /// application offers where they do. Without this provider among the application's, the
    /// answer is `false`.
    ///
    /// ```
    /// use laravel_rust_devtools::DevtoolsServiceProvider;
    ///
    /// let app = laravel::Application::configure().create();
    /// let offered = DevtoolsServiceProvider::is_active(app.config());
    /// # let _ = offered;
    /// ```
    #[must_use]
    pub fn is_active(config: &Config) -> bool {
        #[cfg(debug_assertions)]
        {
            debug::runs(config) || debug::asked_in_tests(config)
        }
        #[cfg(not(debug_assertions))]
        {
            let _ = config;
            false
        }
    }

    /// Let in only whom `gate` allows, of those the rules above let in. It replaces a gate set
    /// before. 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(Gate::Narrowing(Arc::new(gate))),
                ..self
            }
        }
        #[cfg(not(debug_assertions))]
        {
            drop(gate);
            self
        }
    }

    /// Let in whom `gate` allows as well as whom the rules above let in, such as the application's
    /// administrators in a browser behind a proxy, without the key. It replaces a gate set before.
    ///
    /// The gate is asked for every request the rules keep out, after the session has started.
    /// Before then, the developer tools can't tell whom it will let in, so their routes take
    /// everyone's requests for the methods they have, and answer `404` to whom the gate turns away,
    /// before any CSRF check: the answer the application gives a path that doesn't exist, as long
    /// as its fallback answers with `laravel::abort(404)` without the CSRF check, as the README
    /// shows. With `APP_DEBUG=true`, the error page of an error before the gate, or in it, names
    /// the route it was meant for. A build without debug assertions has no developer tools, and
    /// drops the gate.
    ///
    /// ```
    /// use laravel::http::Request;
    /// use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};
    ///
    /// /// Those logged in, wherever their browser is.
    /// struct LoggedIn;
    ///
    /// impl DevtoolsGate for LoggedIn {
    ///     async fn allows(&self, request: &Request) -> laravel::Result<bool> {
    ///         request.authenticated().await
    ///     }
    /// }
    ///
    /// let provider = DevtoolsServiceProvider::new().with_admitting_gate(LoggedIn);
    /// # let _ = provider;
    /// ```
    pub fn with_admitting_gate(self, gate: impl DevtoolsGate) -> Self {
        #[cfg(debug_assertions)]
        {
            Self {
                gate: Some(Gate::Admitting(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(|gate| match gate {
                Gate::Narrowing(_) => "[narrowing]",
                Gate::Admitting(_) => "[admitting]",
            }),
        );
        #[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()))
    }

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

/// A build without debug assertions has no developer tools to start. What asks for them is
/// ignored, and the log says so, since it may be meant for another build or leak where it doesn't
/// belong.
#[cfg(not(debug_assertions))]
fn warn_of_what_this_build_ignores(section: &DevtoolsConfig) {
    if section.enabled == Enabled::Required {
        tracing::warn!(
            "DEVTOOLS_ENABLED=true is ignored: this build has no developer tools, as it was built \
             without debug assertions. Remove DEVTOOLS_ENABLED from this environment."
        );
    }
    if section.key.is_some() {
        tracing::warn!(
            "DEVTOOLS_KEY is ignored: this build has no developer tools, as it was built without \
             debug assertions. Remove the key from this environment."
        );
    }
}

/// 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, DevtoolsKey, Enabled};
    use crate::collector::Collector;
    use crate::file_store::FileStore;
    use crate::gate::Gate;
    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<Gate>, 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.clone(), 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 required = section.enabled == Enabled::Required;
        if required && !matches!(environment, Environment::Local | Environment::Testing) {
            return Err(EnabledOutsideLocal(environment.clone()).into());
        }
        let key = section.key.as_ref().map(DevtoolsKey::expose);
        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.
    pub(super) fn runs(config: &Config) -> bool {
        config.app.env.is_local() && enabled(config) != Enabled::Off
    }

    /// Whether the application's tests ask for the developer tools, which don't run there.
    pub(super) fn asked_in_tests(config: &Config) -> bool {
        config.app.env == Environment::Testing && enabled(config) == Enabled::Required
    }

    /// `DEVTOOLS_ENABLED`. Without the provider, the configuration has no section of theirs, and
    /// that counts as turned off.
    fn enabled(config: &Config) -> Enabled {
        config
            .get::<DevtoolsConfig>()
            .map_or(Enabled::Off, |section| section.enabled)
    }

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

    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.as_str(),
                if matches!(self.0, Environment::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 {}
}