Skip to main content

lean_ctx_cli/dashboard/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::sync::Arc;
3use subtle::ConstantTimeEq;
4use tokio::io::{AsyncReadExt, AsyncWriteExt};
5use tokio::net::TcpListener;
6
7pub(crate) const DEFAULT_PORT: u16 = 3333;
8const DEFAULT_HOST: &str = "127.0.0.1";
9
10pub mod base_path;
11pub(crate) mod cockpit;
12pub(crate) mod display_snapshots;
13pub(crate) mod launch;
14pub(crate) mod project_binding;
15pub mod routes;
16pub(crate) mod vscode_open;
17
18/// Start the dashboard server — the single local entry point that hosts the
19/// Cockpit — or open the one already running. `view` is the Cockpit view to
20/// open (a hash route such as `savings`); `None` opens its start page.
21pub async fn start(
22    port: Option<u16>,
23    host: Option<String>,
24    base_path: Option<String>,
25    auth_token: Option<String>,
26    open_mode: Option<String>,
27    auth_enabled: Option<bool>,
28    view: Option<String>,
29) {
30    // Live model prices (#1179): the measured-spend card prices with the
31    // cached provider list — loaded from disk, kept fresh in the background.
32    lean_ctx::core::gain::live_pricing::spawn_background_refresh();
33
34    // How to reveal the URL once the server is up: --open= flag > env > browser.
35    let open = resolve_open_mode(open_mode.as_deref());
36    let requested_port = port.or_else(requested_port_from_env);
37    let mut port = requested_port.unwrap_or(DEFAULT_PORT);
38
39    let host = host.unwrap_or_else(|| {
40        std::env::var("LEAN_CTX_HOST")
41            .ok()
42            .unwrap_or_else(|| DEFAULT_HOST.to_string())
43    });
44
45    // Reverse-proxy subpath (e.g. `/dashboard`). Normalized to "" or "/prefix".
46    // Shared across connections behind an Arc; "" means "no subpath" (#355).
47    let base_path = Arc::new(
48        base_path
49            .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_BASE_PATH").ok())
50            .map(|b| base_path::normalize(&b))
51            .unwrap_or_default(),
52    );
53
54    let is_local = host == "127.0.0.1" || host == "localhost" || host == "::1";
55
56    // Whether the dashboard requires a Bearer token. Precedence:
57    // `--no-auth`/`--auth=` flag > LEAN_CTX_DASHBOARD_AUTH env > `dashboard_auth`
58    // config > default `true`. When disabled, no token is generated and the
59    // sensitive endpoints (`/api/*`, `/metrics`) are guarded by request-header
60    // checks (Sec-Fetch-Site / Origin / Host allowlist) instead — see
61    // `no_auth_request_ok`.
62    let auth_required = resolve_auth_enabled(auth_enabled);
63
64    // Resolve any *requested* fixed token (flag > LEAN_CTX_HTTP_TOKEN) up-front;
65    // `None` means "generate a random one". Done before the already-running check
66    // so we can warn when the requested token won't match a live instance (#377).
67    let (requested_token, token_src) = resolve_requested_token(auth_token.as_deref());
68
69    // Avoid accidental multiple dashboard instances (common source of "it
70    // hangs"): reuse this data dir's healthy instance, replace its hung or
71    // outdated background one, and move past a port someone else holds.
72    if is_local {
73        match launch::plan_now(requested_port) {
74            (
75                launch::Plan::Reuse {
76                    port,
77                    other_version,
78                },
79                record,
80            ) => {
81                let base = record
82                    .filter(|r| r.port == port)
83                    .map_or_else(|| base_path.to_string(), |r| r.base_path);
84                println!("\n  LeanCTX Cockpit already running → http://{host}:{port}{base}");
85                if let Some(version) = other_version {
86                    eprintln!(
87                        "  \x1b[33m⚠\x1b[0m The running server is version {version} (this is {}). \
88                         Restart it to update: stop it, then run lean-ctx cockpit again.",
89                        env!("CARGO_PKG_VERSION")
90                    );
91                }
92                if let Some(req) = requested_token.as_deref()
93                    && load_saved_token().as_deref() != Some(req)
94                {
95                    eprintln!(
96                        "  \x1b[33m⚠\x1b[0m The running instance uses a different token — your {token_src} \
97                         will be rejected. Stop it (Ctrl+C) and restart to apply the new token."
98                    );
99                }
100                println!(
101                    "  Tip: use Ctrl+C in its terminal (or lean-ctx cockpit stop) to stop it.\n"
102                );
103                open_dashboard_url(
104                    &launch_url(port, &base, load_saved_token().as_deref(), view.as_deref()),
105                    open,
106                );
107                return;
108            }
109            (launch::Plan::Replace { port: taken, .. }, Some(record)) => {
110                println!(
111                    "  Restarting this data dir's background Cockpit server (PID {}).",
112                    record.pid
113                );
114                if !launch::stop_instance(&record) {
115                    eprintln!(
116                        "  Could not stop the previous Cockpit server (PID {}); stop it, then retry.",
117                        record.pid
118                    );
119                    std::process::exit(1);
120                }
121                port = taken;
122            }
123            (launch::Plan::Replace { port: taken, .. }, None) => port = taken,
124            (
125                launch::Plan::Start {
126                    port: free,
127                    skipped,
128                },
129                _,
130            ) => {
131                if let Some(skipped) = skipped {
132                    println!(
133                        "  Port {skipped} is taken (another program or LeanCTX data dir) — using {free}."
134                    );
135                }
136                port = free;
137            }
138            (launch::Plan::PortTaken { port, by }, _) => {
139                eprintln!("{}", launch::port_taken_message(port, &by));
140                std::process::exit(1);
141            }
142        }
143    }
144    let addr = format!("{host}:{port}");
145
146    // Host values accepted in no-auth mode (anti-DNS-rebinding allowlist). Built
147    // once and shared with every connection.
148    let allowed_hosts = Arc::new(build_allowed_hosts(&host, port));
149
150    // Auth defaults on (even on loopback) to prevent cross-origin reads of /api/*
151    // from a malicious website (CORS is not a reliable boundary for localhost
152    // services). When explicitly disabled, run token-less: cross-origin/CSRF and
153    // DNS-rebinding attacks are blocked by `no_auth_request_ok` instead.
154    let token = if auth_required {
155        // #1281: reuse the persisted token across restarts. Rotating on every
156        // start silently 401'd any open dashboard tab — the Live view polls
157        // /api/* and just stayed empty. Precedence: --auth-token > env >
158        // saved dashboard.token (0600) > freshly generated.
159        let t = requested_token
160            .or_else(|| load_saved_token().filter(|s| !s.is_empty()))
161            .unwrap_or_else(generate_token);
162        Some(Arc::new(t))
163    } else {
164        if requested_token.is_some() {
165            eprintln!(
166                "  \x1b[33m⚠\x1b[0m Ignoring the pinned token ({token_src}) — auth is disabled."
167            );
168        }
169        None
170    };
171
172    // Bind BEFORE persisting the token: two racing `lean-ctx dashboard` starts
173    // both used to write their fresh token, the bind loser exited — leaving a
174    // token on disk that the surviving server never accepted. Every later
175    // "already running" browser open (and any tool reading dashboard.token)
176    // then got 401s. Binding first makes the loser exit without touching the
177    // file, so dashboard.token always belongs to the live listener.
178    let listener = match TcpListener::bind(&addr).await {
179        Ok(l) => l,
180        Err(e) => {
181            eprintln!(
182                "Failed to bind to {addr}: {e} — choose another port: lean-ctx cockpit --port <N>"
183            );
184            std::process::exit(1);
185        }
186    };
187    // Who serves this data dir's Cockpit now (no secret in it).
188    let record = launch::LaunchRecord::of_this_process(&host, port, &base_path);
189    launch::write_record(&record);
190
191    if let Some(t) = token.as_ref() {
192        save_token(t);
193        let masked = if t.len() > 12 {
194            format!(
195                "{}…{}",
196                &t[..t.floor_char_boundary(8)],
197                &t[t.ceil_char_boundary(t.len().saturating_sub(4))..]
198            )
199        } else {
200            t.to_string()
201        };
202        let src = if token_src.is_empty() {
203            String::new()
204        } else {
205            format!(" (from {token_src})")
206        };
207        if is_local {
208            println!("  Auth: enabled (local){src}");
209            println!("  Browser URL:  http://localhost:{port}{base_path}/?token={t}");
210        } else {
211            eprintln!(
212                "  \x1b[33m⚠\x1b[0m Binding to {host} — authentication enabled.\n  \
213                 Bearer token{src}: \x1b[1;32m{masked}\x1b[0m\n  \
214                 Browser URL:  http://<your-ip>:{port}{base_path}/?token={t}"
215            );
216        }
217    } else if is_local {
218        // No-auth on loopback: header-based CSRF protection is the boundary.
219        println!(
220            "  Auth: \x1b[1;33mDISABLED\x1b[0m (no-auth) — CSRF protected via Sec-Fetch-Site/Origin/Host"
221        );
222        println!("  Browser URL:  http://localhost:{port}{base_path}/");
223    } else {
224        // No-auth + non-loopback bind (e.g. Docker --host=0.0.0.0). Browser
225        // cross-origin/CSRF is still blocked, but non-browser clients that can
226        // reach the address have unauthenticated access — warn loudly.
227        eprintln!(
228            "  \x1b[33m⚠\x1b[0m Auth \x1b[1;31mDISABLED\x1b[0m and binding to {host} (not loopback).\n  \
229             Browser cross-origin/CSRF stays blocked (Sec-Fetch-Site/Origin/Host),\n  \
230             but ANY non-browser client that can reach {host}:{port} has full access.\n  \
231             Docker: publish only to the host loopback → -p 127.0.0.1:{port}:{port}\n  \
232             Add reachable hostnames via LEAN_CTX_DASHBOARD_ALLOWED_HOSTS=host:port,…\n  \
233             Browser URL:  http://<your-ip>:{port}{base_path}/"
234        );
235    }
236
237    let stats_path = lean_ctx::core::data_dir::lean_ctx_data_dir().map_or_else(
238        |_| "~/.lean-ctx/stats.json".to_string(),
239        |d| d.join("stats.json").display().to_string(),
240    );
241
242    if host == "0.0.0.0" {
243        println!("\n  LeanCTX Cockpit → http://0.0.0.0:{port} (all interfaces)");
244        println!("  Local access:  http://localhost:{port}");
245    } else {
246        println!("\n  LeanCTX Cockpit → http://{host}:{port}");
247    }
248    println!("  Stats file: {stats_path}");
249    println!("  Press Ctrl+C to stop");
250    println!(
251        "  \x1b[2mLocal Cockpit: context observations and evidence remain on this machine.\x1b[0m\n"
252    );
253
254    // The slow reads are computed once now, so the first visit is instant.
255    warm_display_snapshots(token.clone());
256
257    if is_local {
258        open_dashboard_url(
259            &launch_url(
260                port,
261                &base_path,
262                token.as_deref().map(String::as_str),
263                view.as_deref(),
264            ),
265            open,
266        );
267    }
268    if lean_ctx::shell::is_container() && is_local {
269        println!("  Tip (Docker): bind 0.0.0.0 + publish port:");
270        println!("    lean-ctx cockpit --host=0.0.0.0 --port={port}");
271        println!("    docker run ... -p {port}:{port} ...");
272        println!();
273    }
274
275    if lean_ctx::core::datadog_push::spawn_if_enabled() {
276        println!(
277            "  Datadog push: enabled (agentless, every LEAN_CTX_DATADOG_INTERVAL_SECS or 60s)"
278        );
279    }
280
281    // The Cockpit is started on first use for this dashboard's port, token
282    // and project, and stopped with the dashboard.
283    let project_root = routes::helpers::dashboard_project_binding()
284        .0
285        .map(std::path::PathBuf::from)
286        .unwrap_or_default();
287    let cockpit = cockpit::runtime_resolver(port, token.as_deref().cloned(), project_root);
288    loop {
289        tokio::select! {
290            accepted = listener.accept() => {
291                if let Ok((stream, _)) = accepted {
292                    let token_ref = token.clone();
293                    let base_ref = base_path.clone();
294                    let allowed_ref = allowed_hosts.clone();
295                    tokio::spawn(handle_request_with(
296                        stream,
297                        token_ref,
298                        base_ref,
299                        allowed_ref,
300                        cockpit.clone(),
301                    ));
302                }
303            }
304            _ = tokio::signal::ctrl_c() => {
305                let _ = tokio::task::spawn_blocking(cockpit::retire).await;
306                launch::remove_record_of(record.pid);
307                std::process::exit(130);
308            }
309            () = terminate_requested() => {
310                let _ = tokio::task::spawn_blocking(cockpit::retire).await;
311                launch::remove_record_of(record.pid);
312                std::process::exit(0);
313            }
314        }
315    }
316}
317
318/// `--port`/`LEAN_CTX_PORT` when given: a port the user chose, which a start
319/// never swaps silently for another one.
320fn requested_port_from_env() -> Option<u16> {
321    std::env::var("LEAN_CTX_PORT")
322        .ok()
323        .and_then(|p| p.trim().parse().ok())
324}
325
326/// Resolves when the process is asked to terminate (`lean-ctx cockpit stop`
327/// sends SIGTERM to the recorded PID). Never resolves where there is no
328/// such signal.
329async fn terminate_requested() {
330    #[cfg(unix)]
331    {
332        use tokio::signal::unix::{SignalKind, signal};
333        if let Ok(mut term) = signal(SignalKind::terminate()) {
334            term.recv().await;
335            return;
336        }
337    }
338    std::future::pending::<()>().await;
339}
340
341/// The browser URL that opens the Cockpit: the token travels in the query
342/// (the Cockpit stores it and removes it from the address bar), the view as
343/// the hash route the Cockpit navigates to.
344pub(crate) fn launch_url(
345    port: u16,
346    base_path: &str,
347    token: Option<&str>,
348    view: Option<&str>,
349) -> String {
350    let mut url = format!("http://localhost:{port}{base_path}/");
351    if let Some(token) = token.filter(|t| !t.is_empty()) {
352        url.push_str("?token=");
353        url.push_str(token);
354    }
355    if let Some(view) = view.filter(|v| !v.is_empty()) {
356        url.push('#');
357        url.push_str(view);
358    }
359    url
360}
361
362/// Compute the persisted display snapshots of the dashboard's own project
363/// in the background at server start.
364fn warm_display_snapshots(token: Option<Arc<String>>) {
365    std::thread::spawn(move || {
366        let partition = project_binding::partition_of(None);
367        let store = display_snapshots::DisplaySnapshots::global();
368        for route in display_snapshots::DisplaySnapshots::warmed_routes() {
369            let token = token.clone();
370            let compute: display_snapshots::Compute = Arc::new(move || {
371                routes::route_response(route, "", None, token.as_ref(), true, "GET", "")
372            });
373            store.warm(route, &partition, compute);
374        }
375    });
376}
377
378/// Name of the env var that pins the dashboard Bearer token (#377).
379const HTTP_TOKEN_ENV: &str = "LEAN_CTX_HTTP_TOKEN";
380/// Read-only token accepted **only** for `GET /metrics` (GL #401) so
381/// monitoring agents never hold the full dashboard credential.
382const SCRAPE_TOKEN_ENV: &str = "LEAN_CTX_SCRAPE_TOKEN";
383/// Toggles dashboard Bearer-token auth. `false`/`0`/`no`/`off` disable it.
384const DASHBOARD_AUTH_ENV: &str = "LEAN_CTX_DASHBOARD_AUTH";
385/// Extra `Host` header values accepted in no-auth mode (CSV, e.g.
386/// `box.local:3333,10.0.0.5:3333`). Extends the loopback/bound-host allowlist
387/// for Docker/reverse-proxy setups reached via a custom hostname.
388const ALLOWED_HOSTS_ENV: &str = "LEAN_CTX_DASHBOARD_ALLOWED_HOSTS";
389
390/// Parse a human boolean (`true/false/1/0/yes/no/on/off`, case-insensitive).
391fn parse_human_bool(s: &str) -> Option<bool> {
392    match s.trim().to_ascii_lowercase().as_str() {
393        "true" | "1" | "yes" | "on" => Some(true),
394        "false" | "0" | "no" | "off" => Some(false),
395        _ => None,
396    }
397}
398
399/// Resolve whether the dashboard requires Bearer-token auth. Precedence:
400/// `--no-auth`/`--auth=` flag > `LEAN_CTX_DASHBOARD_AUTH` env > `dashboard_auth`
401/// config > default `true`.
402fn resolve_auth_enabled(flag: Option<bool>) -> bool {
403    if let Some(v) = flag {
404        return v;
405    }
406    if let Ok(raw) = std::env::var(DASHBOARD_AUTH_ENV)
407        && let Some(v) = parse_human_bool(&raw)
408    {
409        return v;
410    }
411    lean_ctx::core::config::Config::load().dashboard_auth
412}
413
414/// Build the `Host` header allowlist for no-auth mode (anti-DNS-rebinding).
415/// Always includes the loopback aliases for `port` (localhost is the intended
416/// audience), the actual bound `host:port`, and any `LEAN_CTX_DASHBOARD_ALLOWED_HOSTS`
417/// entries. Bare-host forms (no port) are added too so non-browser clients that
418/// omit the port aren't rejected. `0.0.0.0` is never added — browsers don't send
419/// `Host: 0.0.0.0`; operators expose reachable names via the env allowlist.
420fn build_allowed_hosts(host: &str, port: u16) -> Vec<String> {
421    let mut allowed: Vec<String> = Vec::new();
422    let mut push = |h: String| {
423        if !h.is_empty() && !allowed.iter().any(|e| e.eq_ignore_ascii_case(&h)) {
424            allowed.push(h);
425        }
426    };
427    for base in ["127.0.0.1", "localhost", "[::1]", "::1"] {
428        push(base.to_string());
429        push(format!("{base}:{port}"));
430    }
431    if host != "0.0.0.0" && host != "::" {
432        push(host.to_string());
433        push(format!("{host}:{port}"));
434    }
435    if let Ok(raw) = std::env::var(ALLOWED_HOSTS_ENV) {
436        for entry in raw.split(',') {
437            push(entry.trim().to_string());
438        }
439    }
440    allowed
441}
442
443/// Is the request `Host` header in the allowlist (case-insensitive)?
444fn host_allowed(host: &str, allowed: &[String]) -> bool {
445    allowed.iter().any(|a| a.eq_ignore_ascii_case(host))
446}
447
448/// True when the `Host` header's hostname is a loopback literal
449/// (`localhost`, `127.0.0.0/8`, or `::1`), **regardless of port**.
450///
451/// A loopback `Host` is never a DNS-rebinding vector: the browser only sends one
452/// when the user navigated to a loopback URL directly (an attacker can't make
453/// their own hostname resolve to — and report a `Host` of — `127.0.0.1`). So in
454/// no-auth mode we accept loopback on any port, not just the bound one. This is
455/// what makes a port-remapped Docker publish work out of the box — e.g. the
456/// container binds `0.0.0.0:3333`, Docker publishes it as `-p 60000:3333`, and
457/// the host browser reaches `http://127.0.0.1:60000`, so the `Host` header is
458/// `127.0.0.1:60000` (the *published* port), which the bind-port allowlist
459/// (`127.0.0.1:3333`) would otherwise reject. Cross-origin/CSRF stays blocked by
460/// the `Sec-Fetch-Site`/`Origin` checks in `no_auth_request_ok`.
461fn host_is_loopback(host: &str) -> bool {
462    // Extract the hostname, dropping any `:port`. IPv6 literals are bracketed
463    // (`[::1]` / `[::1]:port`); a bare IPv6 (`::1`) can't carry a port.
464    let hostname = if let Some(rest) = host.strip_prefix('[') {
465        match rest.split_once(']') {
466            Some((inner, _)) => inner,
467            None => return false,
468        }
469    } else if host.matches(':').count() == 1 {
470        host.rsplit_once(':').map_or(host, |(h, _)| h)
471    } else {
472        // No colon (bare host[:no-port]) or multiple colons (unbracketed IPv6).
473        host
474    };
475    if hostname.eq_ignore_ascii_case("localhost") {
476        return true;
477    }
478    if let Ok(v4) = hostname.parse::<std::net::Ipv4Addr>() {
479        return v4.is_loopback();
480    }
481    if let Ok(v6) = hostname.parse::<std::net::Ipv6Addr>() {
482        return v6.is_loopback();
483    }
484    false
485}
486
487/// Token-free request gate for no-auth dashboards. Applied to the same sensitive
488/// endpoints the Bearer token guards (`/api/*`, `/metrics`). Blocks browser
489/// cross-origin/CSRF and DNS-rebinding without a credential:
490///  * `Sec-Fetch-Site`, when sent, must be `same-origin` or `none` (the header is
491///    set by the browser and cannot be forged by page JS).
492///  * `Host` must be in `allowed_hosts` (missing `Host` is rejected).
493///  * `Origin`, when sent and not `null`, must be same-origin as `Host`.
494///
495/// Non-browser clients (curl, Prometheus) omit `Sec-Fetch-Site`/`Origin` and pass
496/// those checks — they only need to target an allowlisted `Host`.
497fn no_auth_request_ok(header_section: &str, allowed_hosts: &[String]) -> bool {
498    if let Some(sfs) = header_line_value(header_section, "Sec-Fetch-Site") {
499        let sfs = sfs.trim();
500        if !sfs.is_empty()
501            && !sfs.eq_ignore_ascii_case("same-origin")
502            && !sfs.eq_ignore_ascii_case("none")
503        {
504            return false;
505        }
506    }
507    let Some(host) = header_line_value(header_section, "Host") else {
508        return false;
509    };
510    // Accept the explicit allowlist (loopback aliases for the bound port, the
511    // bound host, and any LEAN_CTX_DASHBOARD_ALLOWED_HOSTS entries) OR any
512    // loopback host on any port. The latter covers port-remapped Docker
513    // publishes (e.g. `-p 60000:3333` reached via `127.0.0.1:60000`) without a
514    // manual allowlist entry — loopback hosts are not a rebinding vector.
515    if !host_allowed(host, allowed_hosts) && !host_is_loopback(host) {
516        return false;
517    }
518    if let Some(origin) = header_line_value(header_section, "Origin")
519        && !origin.is_empty()
520        && !origin.eq_ignore_ascii_case("null")
521        && !origin_matches_dashboard_host(origin, host)
522    {
523        return false;
524    }
525    true
526}
527
528/// Resolve the dashboard Bearer token.
529///
530/// Honors `LEAN_CTX_HTTP_TOKEN` (#377): when set to a non-empty value it is used
531/// verbatim so reverse-proxy / container deployments keep a stable token across
532/// restarts and redeploys (nginx can inject a fixed `Authorization: Bearer …`).
533/// When unset or empty, a fresh random token is generated (no behavior change).
534///
535/// Resolve a *requested* fixed token with precedence `--auth-token` flag >
536/// `LEAN_CTX_HTTP_TOKEN` (#377). The flag wins so it survives container/service
537/// environments that strip or fail to inherit the env var. Returns the trimmed,
538/// non-empty token and a human label of its source; `None` means "no fixed token
539/// requested → caller generates a random one".
540fn resolve_requested_token(flag: Option<&str>) -> (Option<String>, &'static str) {
541    if let Some(t) = flag.map(str::trim).filter(|s| !s.is_empty()) {
542        return (Some(t.to_string()), "--auth-token");
543    }
544    if let Ok(raw) = std::env::var(HTTP_TOKEN_ENV) {
545        let trimmed = raw.trim();
546        if !trimmed.is_empty() {
547            return (Some(trimmed.to_string()), HTTP_TOKEN_ENV);
548        }
549    }
550    (None, "")
551}
552
553fn generate_token() -> String {
554    let mut bytes = [0u8; 32];
555    if getrandom::fill(&mut bytes).is_err() {
556        tracing::warn!("CSPRNG unavailable — falling back to time-based token");
557        let ts = std::time::SystemTime::now()
558            .duration_since(std::time::UNIX_EPOCH)
559            .unwrap_or_default()
560            .as_nanos();
561        for (i, b) in bytes.iter_mut().enumerate() {
562            *b = ((ts >> (i % 16 * 8)) & 0xFF) as u8;
563        }
564    }
565    format!("lctx_{}", hex_lower(&bytes))
566}
567
568fn save_token(token: &str) {
569    if let Ok(dir) = lean_ctx::core::paths::state_dir() {
570        let _ = std::fs::create_dir_all(&dir);
571        let path = dir.join("dashboard.token");
572        #[cfg(unix)]
573        {
574            use std::io::Write;
575            use std::os::unix::fs::OpenOptionsExt;
576            let Ok(mut f) = std::fs::OpenOptions::new()
577                .write(true)
578                .create(true)
579                .truncate(true)
580                .mode(0o600)
581                .open(&path)
582            else {
583                return;
584            };
585            let _ = f.write_all(token.as_bytes());
586        }
587        #[cfg(not(unix))]
588        {
589            let _ = std::fs::write(&path, token);
590        }
591    }
592}
593
594pub(crate) fn load_saved_token() -> Option<String> {
595    let dir = lean_ctx::core::paths::state_dir().ok()?;
596    let path = dir.join("dashboard.token");
597    std::fs::read_to_string(path)
598        .ok()
599        .map(|s| s.trim().to_string())
600}
601
602/// Adds `nonce="..."` to all inline `<script>` tags (those without a `src=` attribute).
603/// External scripts (`<script src="...">`) are left untouched.
604pub fn add_nonce_to_inline_scripts(html: &str, nonce: &str) -> String {
605    let mut result = String::with_capacity(html.len() + 128);
606    let mut remaining = html;
607    while let Some(pos) = remaining.find("<script") {
608        result.push_str(&remaining[..pos]);
609        let tag_start = &remaining[pos..];
610        let tag_end = tag_start.find('>').unwrap_or(tag_start.len());
611        let tag = &tag_start[..=tag_end];
612        if tag.contains("src=") || tag.contains("nonce=") {
613            result.push_str(tag);
614        } else {
615            result.push_str(&tag.replacen("<script", &format!("<script nonce=\"{nonce}\""), 1));
616        }
617        remaining = &tag_start[tag_end + 1..];
618    }
619    result.push_str(remaining);
620    result
621}
622
623fn hex_lower(bytes: &[u8]) -> String {
624    const HEX: &[u8; 16] = b"0123456789abcdef";
625    let mut out = String::with_capacity(bytes.len() * 2);
626    for &b in bytes {
627        out.push(HEX[(b >> 4) as usize] as char);
628        out.push(HEX[(b & 0x0f) as usize] as char);
629    }
630    out
631}
632
633/// How `lean-ctx dashboard` reveals the URL after the server is up (#424).
634#[derive(Clone, Copy, PartialEq, Eq, Debug)]
635pub(crate) enum DashboardOpen {
636    /// Launch the system default browser (historical default).
637    Browser,
638    /// Don't auto-launch anything — just print the URL. For users who run the
639    /// dashboard inside an editor / reverse proxy and don't want a new window.
640    None,
641    /// Suppress the external browser and print the steps to open the URL in
642    /// VS Code's built-in browser. VS Code exposes no stable CLI flag to open
643    /// its Simple/Integrated Browser, so we guide rather than fake it.
644    Vscode,
645}
646
647/// Resolve the open mode from (in precedence order) the `--open=` flag, the
648/// `LEAN_CTX_DASHBOARD_OPEN` env var, else the `browser` default.
649pub(crate) fn resolve_open_mode(flag: Option<&str>) -> DashboardOpen {
650    let raw = flag
651        .map(str::to_string)
652        .or_else(|| std::env::var("LEAN_CTX_DASHBOARD_OPEN").ok())
653        .unwrap_or_default();
654    match raw.trim().to_ascii_lowercase().as_str() {
655        "none" | "off" | "false" | "no" => DashboardOpen::None,
656        "vscode" | "code" | "editor" => DashboardOpen::Vscode,
657        _ => DashboardOpen::Browser,
658    }
659}
660
661/// Reveal `url` to the user according to `mode`.
662pub(crate) fn open_dashboard_url(url: &str, mode: DashboardOpen) {
663    match mode {
664        DashboardOpen::Browser => open_browser(url),
665        DashboardOpen::None => {}
666        DashboardOpen::Vscode => {
667            // Prefer the extension's native webview tab (#466 item 3): with the
668            // lean-ctx VS Code extension installed, one command opens the
669            // dashboard as a real editor tab — no URL copy/paste. Keep the
670            // Simple Browser path as the no-extension fallback.
671            println!(
672                "  \x1b[2mNative tab: run ⇧⌘P → \"lean-ctx: Open Cockpit\" (needs the lean-ctx VS Code extension)\x1b[0m"
673            );
674            println!(
675                "  \x1b[2mNo extension? ⇧⌘P → \"Simple Browser: Show\" → paste the URL above\x1b[0m"
676            );
677        }
678    }
679}
680
681fn open_browser(url: &str) {
682    #[cfg(target_os = "macos")]
683    {
684        let _ = std::process::Command::new("open").arg(url).spawn();
685    }
686
687    #[cfg(target_os = "linux")]
688    {
689        let _ = std::process::Command::new("xdg-open")
690            .arg(url)
691            .stderr(std::process::Stdio::null())
692            .spawn();
693    }
694
695    #[cfg(target_os = "windows")]
696    {
697        let _ = std::process::Command::new("cmd")
698            .args(["/C", "start", url])
699            .spawn();
700    }
701}
702
703/// Probes `http://{host}:{port}/api/version` (auth-aware) and returns true only
704/// when it answers `200` with the lean-ctx dashboard's own version JSON. Single
705/// source of truth for "is *our* dashboard already live on this port": used both
706/// when opening the browser (avoids spawning a second instance) and by `doctor`'s
707/// port check, so port 3333 held by our own dashboard reads as healthy instead of
708/// a false conflict (#644). The body check is what tells our dashboard apart from
709/// an unrelated service that merely answers 200 on the same port.
710pub(crate) fn dashboard_responding(host: &str, port: u16) -> bool {
711    // Field markers mirror `version_check::version_info_json`; see
712    // `launch::classify_response`. `localhost` and IPv6 hosts now probe the
713    // address they name instead of falling back to 127.0.0.1.
714    matches!(
715        launch::probe(host, port, load_saved_token().as_deref()),
716        launch::Health::Healthy { .. }
717    )
718}
719
720const MAX_HTTP_MESSAGE: usize = 2 * 1024 * 1024;
721
722fn header_line_value<'a>(header_section: &'a str, name: &str) -> Option<&'a str> {
723    for line in header_section.lines() {
724        let Some((k, v)) = line.split_once(':') else {
725            continue;
726        };
727        if k.trim().eq_ignore_ascii_case(name) {
728            return Some(v.trim());
729        }
730    }
731    None
732}
733
734/// Loopback dashboards often use `localhost` vs `127.0.0.1` interchangeably in `Origin`.
735fn host_loopback_aliases(host: &str) -> Vec<String> {
736    let mut v = vec![host.to_string()];
737    if let Some(port) = host.strip_prefix("127.0.0.1:") {
738        v.push(format!("localhost:{port}"));
739    }
740    if let Some(port) = host.strip_prefix("localhost:") {
741        v.push(format!("127.0.0.1:{port}"));
742    }
743    if let Some(port) = host.strip_prefix("[::1]:") {
744        v.push(format!("127.0.0.1:{port}"));
745        v.push(format!("localhost:{port}"));
746    }
747    v
748}
749
750fn origin_matches_dashboard_host(origin: &str, host: &str) -> bool {
751    let origin = origin.trim_end_matches('/');
752    for h in host_loopback_aliases(host) {
753        if origin.eq_ignore_ascii_case(&format!("http://{h}"))
754            || origin.eq_ignore_ascii_case(&format!("https://{h}"))
755        {
756            return true;
757        }
758    }
759    false
760}
761
762/// Defense-in-depth for browser POSTs: reject cross-site `Origin` on mutating `/api/*` calls.
763/// Non-browser clients (no `Origin`) remain allowed when Bearer auth succeeds.
764fn csrf_origin_ok(header_section: &str, method: &str, path: &str) -> bool {
765    let uc = method.to_ascii_uppercase();
766    if !matches!(uc.as_str(), "POST" | "PUT" | "PATCH" | "DELETE") {
767        return true;
768    }
769    if !path.starts_with("/api/") {
770        return true;
771    }
772    let Some(origin) = header_line_value(header_section, "Origin") else {
773        return true;
774    };
775    if origin.is_empty() || origin.eq_ignore_ascii_case("null") {
776        return true;
777    }
778    let Some(host) = header_line_value(header_section, "Host") else {
779        return false;
780    };
781    origin_matches_dashboard_host(origin, host)
782}
783
784fn find_headers_end(buf: &[u8]) -> Option<usize> {
785    buf.windows(4).position(|w| w == b"\r\n\r\n")
786}
787
788fn parse_content_length_header(header_section: &[u8]) -> Option<usize> {
789    let text = String::from_utf8_lossy(header_section);
790    for line in text.lines() {
791        let Some((k, v)) = line.split_once(':') else {
792            continue;
793        };
794        if k.trim().eq_ignore_ascii_case("content-length") {
795            return v.trim().parse::<usize>().ok();
796        }
797    }
798    Some(0)
799}
800
801async fn read_http_message(stream: &mut tokio::net::TcpStream) -> Option<Vec<u8>> {
802    let mut buf = Vec::new();
803    let mut tmp = [0u8; 8192];
804    loop {
805        if let Some(end) = find_headers_end(&buf) {
806            let cl = parse_content_length_header(&buf[..end])?;
807            let total = end + 4 + cl;
808            if total > MAX_HTTP_MESSAGE {
809                return None;
810            }
811            if buf.len() >= total {
812                buf.truncate(total);
813                return Some(buf);
814            }
815        } else if buf.len() > 65_536 {
816            return None;
817        }
818
819        let n = stream.read(&mut tmp).await.ok()?;
820        if n == 0 {
821            return None;
822        }
823        buf.extend_from_slice(&tmp[..n]);
824        if buf.len() > MAX_HTTP_MESSAGE {
825            return None;
826        }
827    }
828}
829
830#[cfg(test)]
831async fn handle_request(
832    stream: tokio::net::TcpStream,
833    token: Option<Arc<String>>,
834    base_path: Arc<String>,
835    allowed_hosts: Arc<Vec<String>>,
836) {
837    handle_request_with(
838        stream,
839        token,
840        base_path,
841        allowed_hosts,
842        Arc::new(|| Err(cockpit::CockpitUnavailable::NotInstalled)),
843    )
844    .await;
845}
846
847/// Write a complete response with a JSON error body.
848async fn write_json_error(stream: &mut tokio::net::TcpStream, status: &str, body: &str) {
849    let response = format!(
850        "HTTP/1.1 {status}\r\n\
851         Content-Type: application/json\r\n\
852         Content-Length: {}\r\n\
853         Cache-Control: no-store\r\n\
854         Connection: close\r\n\
855         \r\n\
856         {body}",
857        body.len()
858    );
859    let _ = stream.write_all(response.as_bytes()).await;
860}
861
862async fn handle_request_with(
863    mut stream: tokio::net::TcpStream,
864    token: Option<Arc<String>>,
865    base_path: Arc<String>,
866    allowed_hosts: Arc<Vec<String>>,
867    cockpit: cockpit::CockpitResolver,
868) {
869    let is_loopback = stream.peer_addr().is_ok_and(|a| a.ip().is_loopback());
870
871    let Some(buf) = read_http_message(&mut stream).await else {
872        return;
873    };
874    let Some(header_end) = find_headers_end(&buf) else {
875        return;
876    };
877    let header_text = String::from_utf8_lossy(&buf[..header_end]).to_string();
878    let body_start = header_end + 4;
879    let Some(content_len) = parse_content_length_header(&buf[..header_end]) else {
880        return;
881    };
882    if buf.len() < body_start + content_len {
883        return;
884    }
885    let body_str = std::str::from_utf8(&buf[body_start..body_start + content_len])
886        .unwrap_or("")
887        .to_string();
888
889    let first = header_text.lines().next().unwrap_or("");
890    let mut parts = first.split_whitespace();
891    let method = parts.next().unwrap_or("GET").to_string();
892    let raw_path = parts.next().unwrap_or("/").to_string();
893
894    let (path, query_token) = if let Some(idx) = raw_path.find('?') {
895        let p = &raw_path[..idx];
896        let qs = &raw_path[idx + 1..];
897        let tok = qs
898            .split('&')
899            .find_map(|pair| pair.strip_prefix("token="))
900            .map(std::string::ToString::to_string);
901        (p.to_string(), tok)
902    } else {
903        (raw_path.clone(), None)
904    };
905
906    let query_str = raw_path
907        .find('?')
908        .map_or(String::new(), |i| raw_path[i + 1..].to_string());
909
910    // Strip the reverse-proxy subpath prefix (if any) so all downstream matching
911    // (fonts, auth, routing) works on root-relative paths whether or not the
912    // proxy already stripped it (#355).
913    let path = base_path::strip(&path, base_path.as_str()).to_string();
914
915    let is_api = path.starts_with("/api/");
916    let requires_auth = is_api || path == "/metrics";
917
918    if let Some(ref expected) = token {
919        let mut has_header_auth = check_auth(&header_text, expected);
920
921        // Read-only scrape token (GL #401): lets a Prometheus/Datadog agent
922        // scrape `/metrics` without holding the full dashboard token. Valid
923        // for the metrics endpoint only — every other API stays gated on the
924        // dashboard token.
925        if !has_header_auth
926            && path == "/metrics"
927            && let Ok(scrape) = std::env::var(SCRAPE_TOKEN_ENV)
928        {
929            let scrape = scrape.trim();
930            if !scrape.is_empty() && check_auth(&header_text, scrape) {
931                has_header_auth = true;
932            }
933        }
934
935        if requires_auth && !has_header_auth {
936            let body = r#"{"error":"unauthorized"}"#;
937            let response = format!(
938                "HTTP/1.1 401 Unauthorized\r\n\
939                 Content-Type: application/json\r\n\
940                 Content-Length: {}\r\n\
941                 WWW-Authenticate: Bearer\r\n\
942                 Connection: close\r\n\
943                 \r\n\
944                 {body}",
945                body.len()
946            );
947            let _ = stream.write_all(response.as_bytes()).await;
948            return;
949        }
950
951        if !csrf_origin_ok(&header_text, method.as_str(), path.as_str()) {
952            let body = r#"{"error":"forbidden"}"#;
953            let response = format!(
954                "HTTP/1.1 403 Forbidden\r\n\
955                 Content-Type: application/json\r\n\
956                 Content-Length: {}\r\n\
957                 Connection: close\r\n\
958                 \r\n\
959                 {body}",
960                body.len()
961            );
962            let _ = stream.write_all(response.as_bytes()).await;
963            return;
964        }
965    } else if requires_auth && !no_auth_request_ok(&header_text, &allowed_hosts) {
966        // No-auth mode: the Bearer token is gone, so cross-origin/CSRF and
967        // DNS-rebinding are blocked by request-header validation instead.
968        let body = r#"{"error":"forbidden"}"#;
969        let response = format!(
970            "HTTP/1.1 403 Forbidden\r\n\
971             Content-Type: application/json\r\n\
972             Content-Length: {}\r\n\
973             Connection: close\r\n\
974             \r\n\
975             {body}",
976            body.len()
977        );
978        let _ = stream.write_all(response.as_bytes()).await;
979        return;
980    }
981
982    // The Cockpit answers `/`, its static assets and `/api/gateway/*`; the
983    // engine every other `/api/*` route and `/metrics`. A request that came
984    // from the Cockpit itself is never sent back to it.
985    if cockpit::serves(&path) && header_line_value(&header_text, cockpit::COCKPIT_HEADER).is_none()
986    {
987        let resolve = cockpit.clone();
988        let target = tokio::task::spawn_blocking(move || resolve())
989            .await
990            .unwrap_or(Err(cockpit::CockpitUnavailable::StartFailed));
991        let is_read = method.eq_ignore_ascii_case("GET") || method.eq_ignore_ascii_case("HEAD");
992        match target {
993            Ok(target) if is_api || is_read => {
994                let forwarded = if query_str.is_empty() {
995                    path.clone()
996                } else {
997                    format!("{path}?{query_str}")
998                };
999                let body = &buf[body_start..body_start + content_len];
1000                match cockpit::forward(&target, &method, &forwarded, &header_text, body).await {
1001                    Some(response) => {
1002                        let _ = stream.write_all(&response).await;
1003                    }
1004                    None => {
1005                        write_json_error(
1006                            &mut stream,
1007                            "502 Bad Gateway",
1008                            r#"{"error":"cockpit unavailable"}"#,
1009                        )
1010                        .await;
1011                    }
1012                }
1013                return;
1014            }
1015            Ok(_) => {
1016                write_json_error(
1017                    &mut stream,
1018                    "405 Method Not Allowed",
1019                    r#"{"error":"method not allowed"}"#,
1020                )
1021                .await;
1022                return;
1023            }
1024            // Without a Cockpit the engine keeps answering `/api/gateway/*`.
1025            Err(_) if is_api => {}
1026            Err(reason) => {
1027                let (status, content_type, body) = match path.as_str() {
1028                    // A source build is complete as it is: it has no Cockpit.
1029                    "/" | "/index.html" | "/cockpit" | "/cockpit/" => (
1030                        if reason == cockpit::CockpitUnavailable::SourceBuild {
1031                            "200 OK"
1032                        } else {
1033                            "503 Service Unavailable"
1034                        },
1035                        "text/html; charset=utf-8",
1036                        cockpit::unavailable_page(reason),
1037                    ),
1038                    "/favicon.ico" => ("204 No Content", "text/plain", String::new()),
1039                    _ => ("404 Not Found", "text/plain", "Not Found".to_string()),
1040                };
1041                let response = format!(
1042                    "HTTP/1.1 {status}\r\n\
1043                     Content-Type: {content_type}\r\n\
1044                     Content-Length: {}\r\n\
1045                     Cache-Control: no-store\r\n\
1046                     X-Content-Type-Options: nosniff\r\n\
1047                     X-Frame-Options: DENY\r\n\
1048                     Referrer-Policy: no-referrer\r\n\
1049                     Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'\r\n\
1050                     Connection: close\r\n\
1051                     \r\n\
1052                     {body}",
1053                    body.len()
1054                );
1055                let _ = stream.write_all(response.as_bytes()).await;
1056                return;
1057            }
1058        }
1059    }
1060
1061    // `X-LeanCTX-Project`: a read for a named project. A path that names no
1062    // project this dashboard may show is refused without saying why.
1063    let route = project_binding::canonical_route(&path).to_string();
1064    let project = match header_line_value(&header_text, cockpit::PROJECT_HEADER)
1065        .map(str::trim)
1066        .filter(|p| !p.is_empty())
1067    {
1068        None => None,
1069        Some(requested) => {
1070            let requested = requested.to_string();
1071            let authorised = tokio::task::spawn_blocking(move || {
1072                project_binding::authorise(&requested, &project_binding::project_pool())
1073            })
1074            .await
1075            .ok()
1076            .flatten();
1077            if authorised.is_none() {
1078                write_json_error(&mut stream, "403 Forbidden", r#"{"error":"forbidden"}"#).await;
1079                return;
1080            }
1081            authorised
1082        }
1083    };
1084    // A named project binds the routes that answer for it; device-wide routes
1085    // answer the same for every project; any other route refuses it rather
1086    // than answering for the dashboard's own project.
1087    let project = match project {
1088        None => None,
1089        Some(project) => match project_binding::project_scope(&route, &method) {
1090            project_binding::ProjectScope::Project => Some(project),
1091            project_binding::ProjectScope::Global => None,
1092            project_binding::ProjectScope::Refused => {
1093                write_json_error(
1094                    &mut stream,
1095                    "400 Bad Request",
1096                    r#"{"error":"this route does not answer for a named project"}"#,
1097                )
1098                .await;
1099                return;
1100            }
1101        },
1102    };
1103    // Display snapshots answer plain reads only; a query string selects a
1104    // different answer than the snapshot holds.
1105    let snapshot_read = method.eq_ignore_ascii_case("GET")
1106        && display_snapshots::is_display_route(&route)
1107        && query_str
1108            .split('&')
1109            .all(|pair| pair.is_empty() || pair.starts_with("token="));
1110
1111    // Route handlers are synchronous and a few (graph/index builds) do seconds
1112    // of disk work. Running them inline on an async worker thread lets one slow
1113    // endpoint starve the small worker pool, so a trivial GET like
1114    // `/api/settings` can wait minutes behind it (#431, Windows few-core). Run
1115    // them on the blocking pool instead: the async workers stay free to serve
1116    // light endpoints promptly. `spawn_blocking` also captures panics (returns
1117    // a `JoinError`), so the previous `catch_unwind` is no longer needed.
1118    let route_started = std::time::Instant::now();
1119    let route_label = route.clone();
1120    let compute = tokio::task::spawn_blocking(move || {
1121        let run: display_snapshots::Compute = {
1122            let project = project.clone();
1123            let route = route.clone();
1124            Arc::new(move || {
1125                project_binding::in_request_project(project.as_deref(), || {
1126                    routes::route_response(
1127                        &route,
1128                        &query_str,
1129                        query_token.as_ref(),
1130                        token.as_ref(),
1131                        is_loopback,
1132                        &method,
1133                        &body_str,
1134                    )
1135                })
1136            })
1137        };
1138        if snapshot_read {
1139            let partition = project_binding::partition_of(project.as_deref());
1140            display_snapshots::DisplaySnapshots::global().serve(&route, &partition, &run)
1141        } else {
1142            (run(), None)
1143        }
1144    })
1145    .await;
1146    let ((status, content_type, mut body), observation) = match compute {
1147        Ok(v) => v,
1148        // The blocking task panicked or was cancelled — surface a 500 rather
1149        // than dropping the connection.
1150        Err(_) => (
1151            (
1152                "500 Internal Server Error",
1153                "application/json",
1154                r#"{"error":"dashboard route panicked"}"#.to_string(),
1155            ),
1156            None,
1157        ),
1158    };
1159    // Observability: a slow light endpoint is exactly the #431 symptom, so make
1160    // any handler that crosses 1s visible in the logs for future diagnosis.
1161    let route_elapsed = route_started.elapsed();
1162    if route_elapsed >= std::time::Duration::from_secs(3) {
1163        tracing::warn!(
1164            target: "lean_ctx::dashboard",
1165            "slow dashboard route {route_label} took {} ms",
1166            route_elapsed.as_millis()
1167        );
1168    }
1169
1170    // Under a reverse-proxy subpath, rewrite root-absolute asset/API URLs in
1171    // any HTML/CSS/JS the engine serves so the browser requests them under
1172    // the prefix (#355).
1173    if !base_path.is_empty()
1174        && (content_type.contains("text/html")
1175            || content_type.contains("text/css")
1176            || content_type.contains("javascript"))
1177    {
1178        body = base_path::rewrite_asset_urls(&body, base_path.as_str());
1179    }
1180
1181    let cache_header = if content_type.starts_with("application/json") {
1182        "Cache-Control: no-cache, no-store, must-revalidate\r\nPragma: no-cache\r\n"
1183    } else if content_type.starts_with("application/javascript")
1184        || content_type.starts_with("text/css")
1185    {
1186        "Cache-Control: no-cache, must-revalidate\r\n"
1187    } else {
1188        ""
1189    };
1190    // Display data says when it was observed and whether it is a snapshot.
1191    let snapshot_headers = observation
1192        .as_ref()
1193        .map(display_snapshots::Observation::headers)
1194        .unwrap_or_default();
1195
1196    let nonce = {
1197        let mut nb = [0u8; 16];
1198        if getrandom::fill(&mut nb).is_err() {
1199            nb.iter_mut().enumerate().for_each(|(i, b)| {
1200                *b = (std::time::SystemTime::now()
1201                    .duration_since(std::time::UNIX_EPOCH)
1202                    .unwrap_or_default()
1203                    .subsec_nanos()
1204                    .wrapping_add(i as u32)) as u8;
1205            });
1206        }
1207        hex_lower(&nb)
1208    };
1209    if content_type.contains("text/html") {
1210        body = add_nonce_to_inline_scripts(&body, &nonce);
1211    }
1212    let security_headers = format!(
1213        "X-Content-Type-Options: nosniff\r\n\
1214         X-Frame-Options: DENY\r\n\
1215         Referrer-Policy: no-referrer\r\n\
1216         Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{nonce}'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:; connect-src 'self'\r\n"
1217    );
1218
1219    let response = format!(
1220        "HTTP/1.1 {status}\r\n\
1221         Content-Type: {content_type}\r\n\
1222         Content-Length: {}\r\n\
1223         {cache_header}\
1224         {snapshot_headers}\
1225         {security_headers}\
1226         Connection: close\r\n\
1227         \r\n\
1228         {body}",
1229        body.len()
1230    );
1231
1232    let _ = stream.write_all(response.as_bytes()).await;
1233}
1234
1235fn check_auth(request: &str, expected_token: &str) -> bool {
1236    for line in request.lines() {
1237        let lower = line.to_lowercase();
1238        if lower.starts_with("authorization:") {
1239            let value = line["authorization:".len()..].trim();
1240            if let Some(token) = value
1241                .strip_prefix("Bearer ")
1242                .or_else(|| value.strip_prefix("bearer "))
1243            {
1244                return constant_time_eq(token.trim().as_bytes(), expected_token.as_bytes());
1245            }
1246        }
1247    }
1248    false
1249}
1250
1251fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
1252    if a.len() != b.len() {
1253        return false;
1254    }
1255    bool::from(a.ct_eq(b))
1256}
1257
1258#[cfg(test)]
1259mod tests;