laravel-rust-devtools 0.2.1

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation

laravel-rust-devtools

Developer tools for Laravel for Rust applications.

This is a community package. It is not made, maintained or endorsed by Laravel.

Deutsch: README.de.md

A floating toolbar for applications in development: a pill at the bottom of each page with its last request, and a panel with the history of the application's requests, console commands, queued jobs and scheduled tasks, each with its timeline, queries, log lines, outgoing HTTP, cache, mail and errors. It runs only in development: release builds contain none of it.

The panel: the history on the left, a request's queries on the right, with a likely N+1 pointed out

Planned for later versions: an inspector for the application itself (routes, pages, schema, migrations, queues, feature flags, translations), Inertia props, and EXPLAIN for a query.

Installing

Add the crate:

cargo add laravel-rust-devtools

and register its service provider in src/app.rs. A new application's src/app.rs has no with_providers yet: add it to the chain that starts with Application::configure().

use laravel::Application;
use laravel_rust_devtools::DevtoolsServiceProvider;

Application::configure()
    .with_providers(|providers| {
        providers.add(DevtoolsServiceProvider::new());
    })

The developer tools run only in a build with debug assertions, such as cargo run and cargo build by default, with APP_ENV=local, and unless DEVTOOLS_ENABLED=false. There they record each request, console command, queued job and scheduled task into storage/devtools, which every process of the application shares. Add it to the application's .gitignore:

/storage/devtools

Everywhere else the provider adds nothing: not in the application's tests, and not in a build without debug assertions, such as cargo build --release by default, which contains none of the developer tools: no recording, no routes, no toolbar, no script. Only DevtoolsConfig stays, with the names of its settings, so that an application that sets them in src/app.rs builds either way. What decides is debug-assertions, not the profile's name: a profile that turns them on, release or not, compiles the developer tools in, and then only APP_ENV=local keeps them off.

Who sees them

Whoever may see the developer tools gets, on each response of the web routes, an x-devtools-trace header with the trace's ID and a Server-Timing header with its queries and duration; an HTML page also gets the toolbar's script before </body>. Downloads, streamed responses, partial responses, compressed pages and pages over 5 MB stay as they are. Everyone else gets none of it, and to them the developer tools' own routes under /_devtools don't exist: before routing, the session and the CSRF check, the developer tools decide by the rules below whether a request reaches them, and any other request goes on as it came. The application answers it as it answers every path no route takes, with its own fallback, cookies, CSRF check and Allow header. The routes really live under /_devtools-routes, and a request for that path is sent on as unknown too: what keeps strangers out is this decision, not a secret path.

  • A browser on the application's own machine gets in: a request whose connection comes from a loopback address, with a Host header that names localhost, a name under it or a loopback address, and with none of the headers a proxy adds. A request without exactly one valid Host header doesn't, nor one whose target names another host (GET http://example.com/…), nor one through a proxy on another machine or in another container, such as in a Docker setup.

    A proxy or tunnel on the same machine that forwards to 127.0.0.1 or localhost can't be told from a local browser, though: nginx with proxy_pass http://127.0.0.1:8000;, which sends Host: 127.0.0.1:8000 (and with proxy_set_header Host $host; lets the client from outside name the host itself, localhost included), a Vite or Node dev proxy, ssh -L, socat, kubectl port-forward. Its requests come from a loopback address, and the framework removes the Forwarded and X-Forwarded-* headers of a proxy the application doesn't trust before any middleware runs. Wherever such a proxy runs, set DEVTOOLS_LOCAL=false, so that only the key, or an admitting gate, lets anyone in. Or trust the proxy, trust_proxies(["127.0.0.1"]), and have it send X-Forwarded-For (in nginx, proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;): that header then stays and shuts its requests out.

  • Anyone else enters the key, DEVTOOLS_KEY, once at /_devtools/login. The key never goes in a URL, and the cookie the browser keeps doesn't hold it: it holds when it was issued and an HMAC-SHA256 of that time and the key under APP_KEY, encrypted as well. It lets in for 12 hours, which the application checks itself, is HttpOnly, sent only to the same site and, over HTTPS, only over HTTPS; a new key, or a new APP_KEY, logs everyone out. The page takes five wrong keys a minute from one address, the one the connection comes from: behind a proxy, every client has the proxy's address, so wrong keys from anyone behind it hold everyone behind it off for that minute. It answers in German or English, whichever the browser lists first.

  • A narrowing gate (with_gate), if the application sets one, has the last word, for example to let in only its administrators. It sees the request after the session has started, so it may ask who is logged in; a gate that fails counts as no. Whom it turns away gets an answer without anything the developer tools hold: 404, before any CSRF check, or, for a method a route doesn't have, 405 and for OPTIONS 200, each with Allow. The gate keeps their contents from someone the rules let in, on this machine or with the key, not the fact that they are there:

use laravel::http::Request;
use laravel_rust_devtools::{DevtoolsGate, DevtoolsServiceProvider};

struct Administrators;

impl DevtoolsGate for Administrators {
    async fn allows(&self, request: &Request) -> laravel::Result<bool> {
        let user: Option<User> = request.user().await?;
        Ok(user.is_some_and(|user| user.is_admin))
    }
}

providers.add(DevtoolsServiceProvider::new().with_gate(Administrators));
  • An admitting gate lets in on its own: whom it allows gets in besides those on this machine or with the key, such as the application's administrators in a browser behind a proxy, without a key. This machine and the key stay a second way in, whatever the gate says. Since the gate can only be asked once the session has started, the developer tools' 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 web routes end with a fallback that answers 404 without the CSRF check, which has nothing to protect there. With another fallback, or none, whom it turns away gets nothing the developer tools hold, but can tell that they are there, as from the CSRF check's 419 or cookie for a path that doesn't exist. With APP_DEBUG=true, so does the error page of an error before the gate, or in it, such as a session store that can't be reached: it names the route:
use laravel::http::middleware::PreventRequestForgery;

providers.add(DevtoolsServiceProvider::new().with_admitting_gate(Administrators));

// At the end of src/routes/web.rs:
route
    .fallback(async || laravel::abort(404))
    .without_middleware::<PreventRequestForgery>();

Those let in pass the framework's default CSRF check on the developer tools' routes, not one the application set in its place, such as origin_only.

An application that offers something of its own about the developer tools, such as a switch for its gate, asks DevtoolsServiceProvider::is_active(config) first, so that it shows nothing where they don't run. In its tests, which never run them, DEVTOOLS_ENABLED=true makes the answer true. Set it where the tests build the application, such as with with_envs, not in .env: without a .env.testing, the tests read .env, and the answer would depend on the machine.

// Where the application offers its switch:
if DevtoolsServiceProvider::is_active(&laravel::config()) {
    // ...
}

// In tests/, where the tests build the application:
app::configure().with_envs([("DEVTOOLS_ENABLED", "true")])
Variable Default What it does
DEVTOOLS_ENABLED unset false turns the developer tools off. true asks for them: a build with debug assertions that runs with any APP_ENV other than local, except in its tests, then refuses to start. A build without them has nothing to start, and ignores it.
DEVTOOLS_ERROR_TEXT false Records what errors say, which may quote a value. Everyone who can read the traces sees those texts, as the developer tools' API at /_devtools/api gives them.
DEVTOOLS_KEY unset The key that lets in a browser on another machine, 32 to 72 bytes; openssl rand -hex 24 makes one. A build with debug assertions doesn't start with a shorter or longer one. Unset, there is no login page.
DEVTOOLS_LOCAL true false stops letting in a browser on the application's own machine without the key.

What a trace records

Each request, console command, queued job, scheduled task, workflow step and tick becomes a trace: the spans and log lines inside it, at DEBUG and above, of the framework, the application's own crates and the packages it builds from a path. A trace keeps at most 1 000 spans and 500 log lines, and counts those it leaves out; a longer value is cut after 4 KiB.

Values are recorded as they were written, with these exceptions:

  • A field whose name suggests a secret is recorded as [masked]: a name that contains password, passwd, secret, token, authorization, cookie, session, signature, api_key, apikey, private_key or credential, such as x-api-key or session_id. Masking goes by name only: a secret in a log line's message, or in a field with an ordinary name, is recorded as written.
  • What the framework's errors say, and every field named error, is recorded as [masked] until DEVTOOLS_ERROR_TEXT=true: a trace keeps an error's kind, where it was raised and when.
  • What a mail, SMS or broadcast says stays out: a trace keeps which message it was, not its recipients, subject, text or payload.
  • Libraries whose lines carry values are never recorded: sqlx and every crate named sqlx_* (a query's SQL with its literals), lettre (the SMTP conversation) and aws_smithy_runtime (an S3 object's key). They are told apart by where Cargo keeps their sources; a build that keeps them elsewhere, such as cargo vendor, Nix or --remap-path-prefix, records the lines of other downloaded crates too.

To record a crate Cargo downloaded, such as a package from crates.io, name it:

providers.add(DevtoolsServiceProvider::new().with_crates(["laravel-rust-permissions"]));

Its lines are then recorded by the same rules: masked by field name, and written as they are otherwise. Name only crates whose lines don't carry values you wouldn't show everyone who can read the traces. The libraries above stay out even when named.

A server stopped with Ctrl+C loses the traces of requests that weren't written yet. A console command or a job in a process that ends right after it may, rarely, lose its trace: the trace is handed over when the work's span closes, which a database library can delay until after the work has returned.

The pill

The script, /_devtools/launcher.js, puts a pill at the bottom of the page: the page's last request with its method, path, status, duration and number of queries, and what deserves a look (a server error, log lines at warn or above, a query run more than once). It follows each request the page makes with fetch or XMLHttpRequest, Inertia's visits among them, and counts those since the page loaded. Drag it to any edge; the arrow keys on its logo do the same, and the logo collapses it. Shift+Alt+D hides and shows it. It speaks German on a German page and English otherwise, and follows the system's light or dark mode.

The pill lives in a shadow root of its own element, which sits between <head> and <body>: the page's styles don't reach it, and its styles don't reach the page. To see the requests, it wraps the page's fetch and XMLHttpRequest, and reads only the responses of the application's own origin. The script is built into the crate; an application needs no Node for it.

Under a Content-Security-Policy the pill keeps working. Its styles are an adopted style sheet, which a style-src without 'unsafe-inline' allows. The script tag carries the nonce of the page's scripts, taken from the policy's header or, for a policy in a <meta> tag, from a <script nonce> of the page. A policy that allows neither 'self' nor a nonce, such as one with hashes only or with 'strict-dynamic' and no nonce, keeps the launcher out; the application's log then says so, once. While someone types in a field of the page, Shift+Alt+D stays the page's, and the pill doesn't print.

A wrapper the page put around fetch before the launcher sees the launcher's own requests too: up to seven per request of the page, to /_devtools/api/traces/…, while that request's trace is being written. A logger or error tracker of the page may report them.

The panel

The pill's logo opens the panel, docked to the bottom of the window, or filling a window narrower than 768 pixels. Drag its upper edge, or move it with the arrow keys, to change its height, which the browser keeps. Escape, other than in a field, its close button, the logo and Shift+Alt+D close it.

On the left is the history: every recorded trace of the application's processes, the newest first, with its kind, status, duration, queries and what deserves a look, to filter by kind, to search, and to narrow to those with hints. While the panel is open it shows the trace of the page's newest response, until another one is chosen. Clearing the history asks first. A browser the developer tools no longer let in is told so, and pointed to the login page if the application has a key.

A trace has six views:

  • Overview: what ran and what was logged, by kind and level, the work's own fields, and what the trace left out. Time the work spent outside every span, such as hashing a password, is pointed out.
  • Timeline: the spans on one time axis, nested in the span around each, with the log lines as marks. A span shows its kind, target, start, duration, fields and the lines written in it.
  • SQL: the queries in the order they ran or grouped by statement. It marks a statement that ran more than once, slow queries (100 ms or more), failed ones, and transactions with where they began, committed or rolled back. The same SELECT three times or more inside the same span, or in calls of the same function (a #[tracing::instrument] function called for each row), is pointed out as a likely N+1. The same query from functions of different names is only marked as run more than once.
  • Logs: the lines, filtered by level and text.
  • More: outgoing HTTP, cache, Redis, mail, SMS and nested work, by kind.
  • Errors: the failed work (a response with a server error counts too), its failed spans and the lines written at error.

From every view, a button opens a span in the timeline.

A request's timeline, in the dark appearance

Copy for AI puts the trace on the clipboard as Markdown, for a question to an AI: what it was and how it ended, its timeline, its queries by statement with what stands out, what failed, the lines at warn or above, and the work's fields. It keeps the first 60 spans and the first 30 statements, failed spans and lines, counts the rest, and stops at 100,000 characters, saying so. It holds what the panel shows, masked as it was recorded, and no more: a value in a message or in a field with an ordinary name is copied as written, so read it before you send it anywhere. Over plain HTTP, other than on localhost, the browser gives the panel no clipboard; it says so. Export as JSON saves the trace as the developer tools' API gave it.

The panel is a page of its own, /_devtools, in a frame: the application's styles don't reach it, and it runs under its own Content-Security-Policy, with its own script and styles only, framed by the application's own pages only. It speaks German or English and has a light, dark and system appearance. Its script and styles are built into the crate; the licences of the packages they hold are in dist/THIRD-PARTY-LICENSES.txt.

License

MIT