Skip to main content

slabs_http/
lib.rs

1//! HTTP router assembly, shared application context, background job dispatch, rate limiting, and built-in endpoints for Slabs.
2//!
3//! # What this crate owns
4//!
5//! - Types: [`AppCtx`], [`ClientIp`], [`SlabDef`], [`JobDef`], [`JobHandlerFn`], [`ScheduleDef`], [`JobRegistry`], and [`RateLimiter`].
6//! - Helpers: [`client_ip`] for proxy-aware IP extraction, and [`build_router`], which combines discovered slabs, built-in endpoints, and the Tower middleware stack into an [`axum::Router`].
7//! - Built-in routes mounted automatically by [`build_router`]:
8//!   - `GET /health` and `GET /_slabs/health`: pings the database with `SELECT 1` and returns `{"status": "ok", "app": "<app_name>"}`.
9//!   - `GET /health/live`: liveness probe returning `200 OK` JSON `{"status": "ok"}`.
10//!   - `GET /health/ready`: readiness probe returning `503 Service Unavailable` when draining or when `SELECT 1` on the read pool fails, otherwise `200 OK`.
11//!   - `GET /_slabs/metrics`: Prometheus text (or JSON when `Accept: application/json`) metrics covering HTTP counts, per-route latency histograms (`p50`/`p95`/`p99`), open incident count, job queue stats, and active realtime topics. In staging/production, returns `404` unless `metrics_token` is set, and requires `Authorization: Bearer <token>` in constant time.
12//!   - `GET /_slabs/incidents`, `GET /_slabs/incidents/ui`, `GET /_slabs/incidents/{id}`, `GET /_slabs/incidents/{id}/attachments/{blob_id}`, `POST /_slabs/incidents/{id}/claim`, `POST /_slabs/incidents/{id}/link`, `POST /_slabs/incidents/{id}/ignore`, and `POST /_slabs/incidents/{id}/resolve`: operator dashboard, attachment download, and agent-oriented runtime incident endpoints guarded by dev/test mode, constant-time `SLABS_METRICS_TOKEN`, or an authenticated admin session.
13//!   - `POST /_slabs/client-errors`: rate-limited (20 req/60s per IP, 4 KiB cap) browser/HTMX error beacon recording `client_error` incidents with query strings stripped.
14//!   - `POST /_slabs/bug-reports`: feature-gated (`SLABS_BUG_REPORTER`), rate-limited (10 req/300s) multipart user bug reporter storing optional screenshots and attachments in `ctx.storage` and recording `user_bug_report` incidents.
15//!   - Dev/test only (`env.is_dev_or_test()`): `GET /_slabs/manifest`, `GET /_slabs/openapi.json`, and `GET /_slabs/mail`.
16//!   - `GET /_slabs/vendor/{*path}`: serves embedded `basecoat.min.css` (with `@view-transition { navigation: auto; }`), `basecoat.min.js`, `htmx.min.js`, `htmx-ext-sse.js`, `idiomorph-ext.min.js`, `alpine.min.js`, `sw-register.js`, `slabs-telemetry.js`, and `slabs-bug-report.js` with `ETag` and `Cache-Control: public, max-age=86400`.
17//!   - `GET /assets/{hash}/{*path}`: serves content-hashed static files from `ctx.assets` with `Cache-Control: public, max-age=31536000, immutable` and a sandbox CSP on SVG/HTML/XHTML assets.
18//!
19//! # Agent invariants
20//!
21//! - Use Axum 0.8 `{param}` and `{*wildcard}` path syntax in [`SlabDef`] constructors. Do not use `:param` or `*wildcard`.
22//! - Multiple slabs may register the same path with different HTTP verbs (for example `GET /api/rooms` and `POST /api/rooms`). [`build_router`] groups slabs by path and merges each [`axum::routing::MethodRouter`] automatically.
23//! - Call `ctx.rate_limit.check(key, max_requests, window_secs)?` explicitly in auth or sensitive slabs. `RateLimiter` is bounded in memory (50,000 entries max) and returns HTTP 429 (`SlabError::TooManyRequests`) with a `Retry-After` header.
24//! - Pass a [`tokio::sync::watch::Receiver<bool>`] to [`JobRegistry::spawn_workers_with_shutdown`] and [`JobRegistry::spawn_schedules_with_shutdown`] so workers and schedules stop cleanly during shutdown.
25//! - [`JobRegistry::new`] always registers the built-in `slabs.deliver_webhook` handler unless an application job overrides that name.
26//!
27//! # Example
28//!
29//! ```rust,no_run
30//! use axum::{extract::{Path, State}, Json};
31//! use serde_json::{json, Value};
32//! use slabs_core::SlabResult;
33//! use slabs_http::{build_router, AppCtx, SlabDef};
34//!
35//! pub fn slab() -> SlabDef {
36//!     SlabDef::post("/api/rooms/{room_id}/messages", handle)
37//!         .name("messages.create")
38//!         .summary("Post a message to a room")
39//! }
40//!
41//! async fn handle(
42//!     State(ctx): State<AppCtx>,
43//!     Path(room_id): Path<String>,
44//! ) -> SlabResult<Json<Value>> {
45//!     ctx.rate_limit.check(&format!("room_msg:{room_id}"), 30, 60)?;
46//!     Ok(Json(json!({ "room_id": room_id })))
47//! }
48//!
49//! fn assemble(ctx: AppCtx) -> axum::Router {
50//!     build_router(ctx, vec![slab()], &[])
51//! }
52//! ```
53
54use axum::{
55    body::Bytes,
56    extract::{
57        ConnectInfo, DefaultBodyLimit, FromRequestParts, MatchedPath, Multipart, Path, Query,
58        Request, State,
59    },
60    handler::Handler,
61    http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri},
62    middleware::{self, Next},
63    response::{IntoResponse, Response},
64    routing::{delete, get, patch, post, put, MethodRouter},
65    Json, Router,
66};
67use axum_extra::extract::CookieJar;
68use chrono::{SecondsFormat, Utc};
69use futures_util::{future::BoxFuture, FutureExt as _};
70use hmac::{Hmac, Mac as _};
71use serde::Deserialize;
72use serde_json::{json, Value};
73use sha2::{Digest, Sha256};
74use slabs_assets::Assets;
75use slabs_auth::Auth;
76use slabs_cache::Cache;
77use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
78use slabs_db::{AuditLog, Db, IncidentInput, IncidentOutcome, IncidentRecord, Incidents};
79use slabs_jobs::{JobRecord, Jobs};
80use slabs_mail::{MailTransport, Mailer};
81use slabs_realtime::Realtime;
82use slabs_storage::{S3Config, Storage, StorageBackend};
83use slabs_webhooks::Webhooks;
84use std::collections::{btree_map::Entry, BTreeMap, HashMap, HashSet};
85use std::fmt::{self, Write as _};
86use std::future::Future;
87use std::net::{IpAddr, SocketAddr};
88use std::panic::AssertUnwindSafe;
89use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
90use std::sync::{Arc, Mutex, OnceLock};
91use std::time::{Duration, Instant};
92use tokio::sync::watch;
93use tokio::task::JoinHandle;
94use tower_http::{
95    compression::CompressionLayer,
96    cors::{AllowOrigin, CorsLayer},
97    limit::RequestBodyLimitLayer,
98    request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
99    set_header::SetResponseHeaderLayer,
100    trace::TraceLayer,
101};
102
103type HmacSha256 = Hmac<Sha256>;
104
105const MAX_RATE_LIMIT_ENTRIES: usize = 50_000;
106const RATE_LIMIT_PRUNE_INTERVAL: Duration = Duration::from_secs(5);
107const MAX_CLIENT_ERROR_BYTES: usize = 4 * 1024;
108const MIN_BUG_DESCRIPTION_CHARS: usize = 3;
109const MAX_BUG_DESCRIPTION_CHARS: usize = 4_000;
110const MAX_BUG_SOURCE_FILE_CHARS: usize = 200;
111const MAX_BUG_METADATA_BYTES: usize = 16 * 1024;
112const MAX_BUG_SCREENSHOT_BYTES: usize = 5 * 1024 * 1024;
113const MAX_BUG_ATTACHMENT_BYTES: usize = 5 * 1024 * 1024;
114const MAX_BUG_ATTACHMENTS: usize = 3;
115const INCIDENT_PROTOCOL_VERSION: &str = "slabs.incident.v1";
116const MAX_TRACKED_ROUTES: usize = 2048;
117const LATENCY_BUCKETS_MS: [u64; 8] = [10, 25, 50, 100, 250, 500, 1000, 2500];
118const BASECOAT_CSS: &str = concat!(
119    "@view-transition { navigation: auto; }\n",
120    include_str!("../assets/vendor/basecoat.min.css")
121);
122const SLABS_TELEMETRY_JS: &str = r#"(function () {
123  if (typeof window === "undefined" || window.__slabsTelemetryInstalled) return;
124  window.__slabsTelemetryInstalled = true;
125  function report(kind, message, detail) {
126    try {
127      var body = JSON.stringify({
128        kind: kind,
129        message: String(message || "client error").slice(0, 512),
130        path: window.location ? window.location.pathname : "/",
131        detail: detail ? String(detail).slice(0, 1024) : null
132      });
133      if (navigator.sendBeacon) {
134        navigator.sendBeacon("/_slabs/client-errors", new Blob([body], { type: "application/json" }));
135      }
136    } catch (_) {}
137  }
138  window.addEventListener("error", function (e) {
139    var loc = e.filename ? e.filename + ":" + e.lineno + ":" + e.colno : null;
140    report("onerror", e.message || "Script error", loc);
141  });
142  window.addEventListener("unhandledrejection", function (e) {
143    var r = e.reason;
144    report("unhandledrejection", (r && r.message) || String(r || "Unhandled promise rejection"), r && r.stack);
145  });
146  ["htmx:targetError", "htmx:swapError"].forEach(function (ev) {
147    document.addEventListener(ev, function (e) {
148      var d = e.detail || {};
149      report(ev, d.error || ev, d.target ? String(d.target) : null);
150    });
151  });
152})();
153"#;
154
155/// Generates time-sortable prefixed ULID `X-Request-Id` headers (`req_01j...`).
156#[derive(Clone, Default)]
157struct MakeUlidRequestId;
158
159impl MakeRequestId for MakeUlidRequestId {
160    fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
161        let id = slabs_core::id::new("req");
162        HeaderValue::from_str(&id).ok().map(RequestId::new)
163    }
164}
165
166#[derive(Debug)]
167struct RateLimiterState {
168    buckets: HashMap<String, (u64, Instant)>,
169    last_prune: Instant,
170}
171
172impl Default for RateLimiterState {
173    fn default() -> Self {
174        Self {
175            buckets: HashMap::new(),
176            last_prune: Instant::now(),
177        }
178    }
179}
180
181/// Explicit in-memory fixed-window rate limiter for auth and sensitive slabs.
182///
183/// Bounded to at most 50,000 tracked keys with throttled expiration pruning (at most once every
184/// 5 seconds) and lock-poison recovery.
185#[derive(Debug, Clone, Default)]
186pub struct RateLimiter {
187    state: Arc<Mutex<RateLimiterState>>,
188}
189
190impl RateLimiter {
191    /// Create a new empty in-memory rate limiter.
192    #[must_use]
193    pub fn new() -> Self {
194        Self::default()
195    }
196
197    /// Increment the counter for `key` and return the remaining quota for the current window.
198    ///
199    /// Returns HTTP 429 (`SlabError::TooManyRequests`) with a `Retry-After` duration when `key`
200    /// reaches `max_requests` within `window_secs`, or when the map reaches its 50,000-key cap.
201    pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
202        let now = Instant::now();
203        let window = Duration::from_secs(window_secs.max(1));
204        let mut guard = self
205            .state
206            .lock()
207            .unwrap_or_else(std::sync::PoisonError::into_inner);
208
209        let can_prune =
210            now.saturating_duration_since(guard.last_prune) >= RATE_LIMIT_PRUNE_INTERVAL;
211
212        if !guard.buckets.contains_key(key) && guard.buckets.len() >= MAX_RATE_LIMIT_ENTRIES {
213            if can_prune {
214                guard.buckets.retain(|_, (_, expires_at)| *expires_at > now);
215                guard.last_prune = now;
216            }
217            if guard.buckets.len() >= MAX_RATE_LIMIT_ENTRIES {
218                return Err(SlabError::too_many_requests(
219                    RATE_LIMIT_PRUNE_INTERVAL.as_secs().max(1),
220                    "rate limit exceeded, please try again shortly",
221                ));
222            }
223        } else if guard.buckets.len() > 10_000 && can_prune {
224            guard.buckets.retain(|_, (_, expires_at)| *expires_at > now);
225            guard.last_prune = now;
226        }
227
228        let entry = guard
229            .buckets
230            .entry(key.to_string())
231            .or_insert((0, now + window));
232
233        if entry.1 <= now {
234            entry.0 = 0;
235            entry.1 = now + window;
236        }
237
238        if entry.0 >= max_requests {
239            let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
240            return Err(SlabError::too_many_requests(
241                retry_after,
242                "rate limit exceeded, please try again shortly",
243            ));
244        }
245
246        entry.0 += 1;
247        Ok(max_requests - entry.0)
248    }
249
250    /// Enforce both a per-IP rate limit and a per-account rate limit in a single call.
251    ///
252    /// Checks `ip_key` against `ip_limit` first (so an already-blocked IP cannot burn a victim's
253    /// account quota), then checks `account_key` against `account_limit`, both over `window_secs`.
254    pub fn check_pair(
255        &self,
256        ip_key: &str,
257        ip_limit: u32,
258        account_key: &str,
259        account_limit: u32,
260        window_secs: u64,
261    ) -> SlabResult<()> {
262        self.check(ip_key, u64::from(ip_limit), window_secs)?;
263        self.check(account_key, u64::from(account_limit), window_secs)?;
264        Ok(())
265    }
266}
267
268/// Axum request-parts extractor resolving the client's IP address via [`client_ip`].
269///
270/// Honors proxy headers only when `state.config.trust_proxy` is `true`, otherwise reads the
271/// socket peer address from [`ConnectInfo`]. Falls back gracefully to `"127.0.0.1"` in unit
272/// tests where `ConnectInfo` is not attached.
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct ClientIp(pub String);
275
276impl FromRequestParts<AppCtx> for ClientIp {
277    type Rejection = std::convert::Infallible;
278
279    fn from_request_parts(
280        parts: &mut axum::http::request::Parts,
281        state: &AppCtx,
282    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
283        let peer = parts
284            .extensions
285            .get::<ConnectInfo<SocketAddr>>()
286            .map(|c| c.0);
287        let ip = client_ip(&parts.headers, peer, state.config.trust_proxy);
288        std::future::ready(if ip == "unknown" {
289            Ok(Self("127.0.0.1".to_string()))
290        } else {
291            Ok(Self(ip))
292        })
293    }
294}
295
296/// Resolve the client's IP address for logging and rate-limit keys.
297///
298/// When `trust_proxy` is `true`, inspects `CF-Connecting-IP`, `Fly-Client-IP`, and the rightmost
299/// valid IP address in `X-Forwarded-For` before falling back to `peer`. When `trust_proxy` is
300/// `false`, proxy headers are ignored and only `peer` is used. Returns `"unknown"` when no valid
301/// IP can be determined.
302#[must_use]
303pub fn client_ip(headers: &HeaderMap, peer: Option<SocketAddr>, trust_proxy: bool) -> String {
304    if trust_proxy {
305        for header_name in ["cf-connecting-ip", "fly-client-ip"] {
306            if let Some(ip) = headers
307                .get(header_name)
308                .and_then(|v| v.to_str().ok())
309                .and_then(|s| s.trim().parse::<IpAddr>().ok())
310            {
311                return ip.to_string();
312            }
313        }
314        if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
315            for part in xff.rsplit(',') {
316                if let Ok(ip) = part.trim().parse::<IpAddr>() {
317                    return ip.to_string();
318                }
319            }
320        }
321    }
322
323    peer.map_or_else(|| "unknown".to_string(), |addr| addr.ip().to_string())
324}
325
326#[derive(Debug, Clone)]
327struct RouteHistogram {
328    source_file: String,
329    requests: u64,
330    errors_5xx: u64,
331    slow_requests: u64,
332    latency_ms_total: u64,
333    max_latency_ms: u64,
334    buckets: [u64; 9],
335}
336
337impl RouteHistogram {
338    fn new(source_file: String) -> Self {
339        Self {
340            source_file,
341            requests: 0,
342            errors_5xx: 0,
343            slow_requests: 0,
344            latency_ms_total: 0,
345            max_latency_ms: 0,
346            buckets: [0; 9],
347        }
348    }
349
350    fn observe(&mut self, elapsed_ms: u64, is_5xx: bool, is_slow: bool) {
351        self.requests = self.requests.saturating_add(1);
352        if is_5xx {
353            self.errors_5xx = self.errors_5xx.saturating_add(1);
354        }
355        if is_slow {
356            self.slow_requests = self.slow_requests.saturating_add(1);
357        }
358        self.latency_ms_total = self.latency_ms_total.saturating_add(elapsed_ms);
359        if elapsed_ms > self.max_latency_ms {
360            self.max_latency_ms = elapsed_ms;
361        }
362        let bucket_idx = LATENCY_BUCKETS_MS
363            .iter()
364            .position(|&bound| elapsed_ms <= bound)
365            .unwrap_or(LATENCY_BUCKETS_MS.len());
366        self.buckets[bucket_idx] = self.buckets[bucket_idx].saturating_add(1);
367    }
368
369    #[allow(
370        clippy::cast_possible_truncation,
371        clippy::cast_sign_loss,
372        clippy::cast_precision_loss
373    )]
374    fn percentile_ms(&self, quantile: f64) -> u64 {
375        if self.requests == 0 {
376            return 0;
377        }
378        let target = ((self.requests as f64) * quantile).ceil().max(1.0) as u64;
379        let mut cumulative = 0u64;
380        for (idx, &count) in self.buckets.iter().enumerate() {
381            cumulative = cumulative.saturating_add(count);
382            if cumulative >= target {
383                return LATENCY_BUCKETS_MS
384                    .get(idx)
385                    .map_or(self.max_latency_ms, |&bound| bound.min(self.max_latency_ms));
386            }
387        }
388        self.max_latency_ms
389    }
390
391    fn p50_ms(&self) -> u64 {
392        self.percentile_ms(0.50)
393    }
394
395    fn p95_ms(&self) -> u64 {
396        self.percentile_ms(0.95)
397    }
398
399    fn p99_ms(&self) -> u64 {
400        self.percentile_ms(0.99)
401    }
402
403    #[allow(clippy::cast_precision_loss)]
404    fn avg_latency_ms(&self) -> f64 {
405        if self.requests > 0 {
406            self.latency_ms_total as f64 / self.requests as f64
407        } else {
408            0.0
409        }
410    }
411}
412
413#[derive(Debug, Clone)]
414struct RouteMetricSnapshot {
415    method: String,
416    route: String,
417    source_file: String,
418    requests: u64,
419    errors_5xx: u64,
420    slow_requests: u64,
421    avg_latency_ms: f64,
422    p50_ms: u64,
423    p95_ms: u64,
424    p99_ms: u64,
425    max_latency_ms: u64,
426}
427
428#[derive(Debug, Default)]
429struct HttpMetrics {
430    requests: AtomicU64,
431    errors_5xx: AtomicU64,
432    latency_ms: AtomicU64,
433    route_sources: Mutex<HashMap<(String, String), String>>,
434    routes: Mutex<HashMap<(String, String), RouteHistogram>>,
435}
436
437impl HttpMetrics {
438    fn register_route_source(&self, method: &str, path: &str, source_file: String) {
439        let mut guard = self
440            .route_sources
441            .lock()
442            .unwrap_or_else(std::sync::PoisonError::into_inner);
443        guard.insert((method.to_ascii_uppercase(), path.to_owned()), source_file);
444    }
445
446    fn source_file(&self, method: &str, route: &str) -> String {
447        let guard = self
448            .route_sources
449            .lock()
450            .unwrap_or_else(std::sync::PoisonError::into_inner);
451        guard
452            .get(&(method.to_ascii_uppercase(), route.to_owned()))
453            .cloned()
454            .unwrap_or_else(|| format!("route:{route}"))
455    }
456
457    fn record_request(
458        &self,
459        method: &str,
460        route: &str,
461        source_file: &str,
462        elapsed_ms: u64,
463        is_5xx: bool,
464        is_slow: bool,
465    ) {
466        self.requests.fetch_add(1, Ordering::Relaxed);
467        self.latency_ms.fetch_add(elapsed_ms, Ordering::Relaxed);
468        if is_5xx {
469            self.errors_5xx.fetch_add(1, Ordering::Relaxed);
470        }
471
472        let key = (method.to_ascii_uppercase(), route.to_owned());
473        let mut guard = self
474            .routes
475            .lock()
476            .unwrap_or_else(std::sync::PoisonError::into_inner);
477        if let Some(hist) = guard.get_mut(&key) {
478            hist.observe(elapsed_ms, is_5xx, is_slow);
479        } else if guard.len() < MAX_TRACKED_ROUTES {
480            let mut hist = RouteHistogram::new(source_file.to_owned());
481            hist.observe(elapsed_ms, is_5xx, is_slow);
482            guard.insert(key, hist);
483        }
484    }
485
486    fn route_snapshots(&self) -> Vec<RouteMetricSnapshot> {
487        let guard = self
488            .routes
489            .lock()
490            .unwrap_or_else(std::sync::PoisonError::into_inner);
491        let mut snapshots: Vec<RouteMetricSnapshot> = guard
492            .iter()
493            .map(|((method, route), hist)| RouteMetricSnapshot {
494                method: method.clone(),
495                route: route.clone(),
496                source_file: hist.source_file.clone(),
497                requests: hist.requests,
498                errors_5xx: hist.errors_5xx,
499                slow_requests: hist.slow_requests,
500                avg_latency_ms: hist.avg_latency_ms(),
501                p50_ms: hist.p50_ms(),
502                p95_ms: hist.p95_ms(),
503                p99_ms: hist.p99_ms(),
504                max_latency_ms: hist.max_latency_ms,
505            })
506            .collect();
507        snapshots.sort_by(|a, b| {
508            b.p95_ms
509                .cmp(&a.p95_ms)
510                .then_with(|| b.max_latency_ms.cmp(&a.max_latency_ms))
511                .then_with(|| a.route.cmp(&b.route))
512                .then_with(|| a.method.cmp(&b.method))
513        });
514        snapshots
515    }
516}
517
518fn derive_slab_source_file(slab: &SlabDef) -> String {
519    let name = slab.name.trim();
520    if name.contains("::") && !name.contains(' ') && !name.contains('/') {
521        format!("slabs/{}.rs", name.replace("::", "/"))
522    } else if name.contains('.') && !name.contains(' ') && !name.contains('/') {
523        format!("slabs/{}.rs", name.replace('.', "/"))
524    } else {
525        format!("route:{}", slab.path)
526    }
527}
528
529/// Shared runtime context passed to every HTTP slab handler and background job.
530///
531/// Every field is an explicit subsystem handle backed by `SQLite` or in-process state, with no ORM
532/// or hidden middleware state.
533#[derive(Debug, Clone)]
534pub struct AppCtx {
535    /// Runtime application configuration loaded from environment variables or defaults.
536    pub config: AppConfig,
537    /// Shared database connection pool.
538    pub db: Db,
539    /// Authentication, session, magic-link, and access-token helper.
540    pub auth: Auth,
541    /// Durable SQLite-backed background job queue.
542    pub jobs: Jobs,
543    /// Outbound email delivery and development outbox mailer.
544    pub mail: Mailer,
545    /// Local or S3-compatible blob storage handle.
546    pub storage: Storage,
547    /// SQLite-backed key/value cache.
548    pub cache: Cache,
549    /// In-process topic broadcast and presence hub for SSE and `WebSocket` updates.
550    pub realtime: Realtime,
551    /// Outbound signed webhook subscription and delivery manager.
552    pub webhooks: Webhooks,
553    /// Content-hashed static asset registry.
554    pub assets: Assets,
555    /// In-memory fixed-window rate limiter.
556    pub rate_limit: RateLimiter,
557    /// Transactional SQLite-backed audit log.
558    pub audit: AuditLog,
559    /// Deduplicated SQLite-backed runtime incident tracker.
560    pub incidents: Incidents,
561    draining: Arc<AtomicBool>,
562    metrics: Arc<HttpMetrics>,
563}
564
565impl AppCtx {
566    /// Initialize database connections and all framework subsystems from `config`.
567    pub async fn connect(config: AppConfig) -> SlabResult<Self> {
568        let db = Db::connect(&config.database_url).await?;
569        let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
570        let jobs = Jobs::new(db.clone());
571        let mail = Mailer::with_transport(
572            db.clone(),
573            format!("noreply@{}.local", config.app_name),
574            MailTransport::from_env(),
575        );
576        let storage_backend = match S3Config::from_env() {
577            Some(s3) => StorageBackend::S3(s3),
578            None => StorageBackend::Local {
579                root_dir: config.storage_dir.clone(),
580            },
581        };
582        let storage = Storage::with_backend(db.clone(), storage_backend)
583            .with_max_blob_bytes(config.max_blob_bytes);
584        let cache = Cache::new(db.clone());
585        let realtime = Realtime::new();
586        let webhooks = Webhooks::new(db.clone(), jobs.clone());
587        let assets = Assets::from_dir(&config.assets_dir);
588        let rate_limit = RateLimiter::new();
589        let audit = AuditLog::new(db.clone());
590        let incidents = Incidents::new(db.clone());
591
592        Ok(Self {
593            config,
594            db,
595            auth,
596            jobs,
597            mail,
598            storage,
599            cache,
600            realtime,
601            webhooks,
602            assets,
603            rate_limit,
604            audit,
605            incidents,
606            draining: Arc::new(AtomicBool::new(false)),
607            metrics: Arc::new(HttpMetrics::default()),
608        })
609    }
610
611    /// Mark this server instance as draining so `GET /health/ready` immediately returns HTTP `503`.
612    pub fn set_draining(&self) {
613        self.draining.store(true, Ordering::SeqCst);
614    }
615
616    /// Return `true` when this server instance has entered graceful shutdown draining.
617    #[must_use]
618    pub fn is_draining(&self) -> bool {
619        self.draining.load(Ordering::SeqCst)
620    }
621}
622
623/// Self-contained HTTP Transaction Script definition returned by `pub fn slab() -> SlabDef`.
624///
625/// Route paths use Axum 0.8 `{param}` and `{*wildcard}` syntax.
626#[derive(Debug)]
627pub struct SlabDef {
628    /// HTTP method handled by this slab (e.g. `"GET"`, `"POST"`).
629    pub method: String,
630    /// Route path pattern registered on the Axum router.
631    pub path: String,
632    /// Logical slab name (commonly `<feature>.<action>`).
633    pub name: String,
634    /// Feature grouping label for manifest inspection.
635    pub feature: String,
636    /// Short human-readable description of the endpoint.
637    pub summary: String,
638    /// Optional JSON Schema describing the expected request body for `OpenAPI` export.
639    pub input_schema: Option<Value>,
640    /// Optional JSON Schema describing the response body for `OpenAPI` export.
641    pub output_schema: Option<Value>,
642    /// When `true`, exempts this slab's `(method, path)` from browser Fetch Metadata / Origin CSRF checks.
643    ///
644    /// Only enable on server-to-server inbound webhook receivers that verify their own HMAC signature.
645    pub skip_csrf: bool,
646    /// Axum method router wrapping the slab's handler.
647    pub router: MethodRouter<AppCtx>,
648}
649
650impl SlabDef {
651    /// Define a `GET` slab at `path`.
652    pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
653    where
654        H: Handler<T, AppCtx>,
655        T: 'static,
656    {
657        Self::new("GET", path, get(handler))
658    }
659
660    /// Define a `POST` slab at `path`.
661    pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
662    where
663        H: Handler<T, AppCtx>,
664        T: 'static,
665    {
666        Self::new("POST", path, post(handler))
667    }
668
669    /// Define a `PUT` slab at `path`.
670    pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
671    where
672        H: Handler<T, AppCtx>,
673        T: 'static,
674    {
675        Self::new("PUT", path, put(handler))
676    }
677
678    /// Define a `PATCH` slab at `path`.
679    pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
680    where
681        H: Handler<T, AppCtx>,
682        T: 'static,
683    {
684        Self::new("PATCH", path, patch(handler))
685    }
686
687    /// Define a `DELETE` slab at `path`.
688    pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
689    where
690        H: Handler<T, AppCtx>,
691        T: 'static,
692    {
693        Self::new("DELETE", path, delete(handler))
694    }
695
696    fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
697        let path = path.into();
698        Self {
699            method: method.to_string(),
700            name: format!("{method} {path}"),
701            feature: "default".to_string(),
702            summary: String::new(),
703            input_schema: None,
704            output_schema: None,
705            skip_csrf: false,
706            path,
707            router,
708        }
709    }
710
711    /// Set the slab's logical name, automatically deriving `feature` from a `<feature>.<action>` prefix.
712    #[must_use]
713    pub fn name(mut self, name: impl Into<String>) -> Self {
714        let n = name.into();
715        if let Some((feat, _)) = n.split_once('.') {
716            self.feature = feat.to_string();
717        }
718        self.name = n;
719        self
720    }
721
722    /// Explicitly set the slab's feature group name.
723    #[must_use]
724    pub fn feature(mut self, feature: impl Into<String>) -> Self {
725        self.feature = feature.into();
726        self
727    }
728
729    /// Set a short human-readable summary for the route manifest.
730    #[must_use]
731    pub fn summary(mut self, summary: impl Into<String>) -> Self {
732        self.summary = summary.into();
733        self
734    }
735
736    /// Attach a JSON Schema describing the expected request body for `/_slabs/openapi.json`.
737    #[must_use]
738    pub fn input_schema(mut self, schema: Value) -> Self {
739        self.input_schema = Some(schema);
740        self
741    }
742
743    /// Attach a JSON Schema describing the response body for `/_slabs/openapi.json`.
744    #[must_use]
745    pub fn output_schema(mut self, schema: Value) -> Self {
746        self.output_schema = Some(schema);
747        self
748    }
749
750    /// Opt this route out of browser CSRF checks (Fetch Metadata and `Origin` verification).
751    ///
752    /// Use only on inbound server-to-server webhook receivers that validate an HMAC signature.
753    #[must_use]
754    pub fn skip_csrf(mut self) -> Self {
755        self.skip_csrf = true;
756        self
757    }
758
759    /// Extract serializable route metadata for the application manifest.
760    pub fn meta(&self) -> RouteMeta {
761        RouteMeta {
762            name: self.name.clone(),
763            method: self.method.clone(),
764            path: self.path.clone(),
765            summary: self.summary.clone(),
766            feature: self.feature.clone(),
767            input_schema: self.input_schema.clone(),
768            output_schema: self.output_schema.clone(),
769        }
770    }
771}
772
773/// Type-erased async handler function stored in a [`JobDef`].
774pub type JobHandlerFn =
775    Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;
776
777/// Self-contained Background Job Transaction Script definition returned by `pub fn job() -> JobDef`.
778#[derive(Clone)]
779pub struct JobDef {
780    /// Unique job identifier used when enqueueing and dispatching.
781    pub name: String,
782    /// Queue name this job belongs to (defaults to `"default"`).
783    pub queue: String,
784    /// Maximum execution attempts before marking the job dead.
785    pub max_attempts: i64,
786    /// Short human-readable summary of the job.
787    pub summary: String,
788    /// Async handler invoked with [`AppCtx`] and the JSON payload.
789    pub handler: JobHandlerFn,
790}
791
792impl fmt::Debug for JobDef {
793    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794        f.debug_struct("JobDef")
795            .field("name", &self.name)
796            .field("queue", &self.queue)
797            .field("max_attempts", &self.max_attempts)
798            .field("summary", &self.summary)
799            .field("handler", &"<fn>")
800            .finish()
801    }
802}
803
804impl JobDef {
805    /// Create a new [`JobDef`] with the given `name` and async `handler`.
806    #[must_use]
807    pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
808    where
809        F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
810        Fut: Future<Output = SlabResult<()>> + Send + 'static,
811    {
812        Self {
813            name: name.into(),
814            queue: "default".to_string(),
815            max_attempts: 5,
816            summary: String::new(),
817            handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
818        }
819    }
820
821    /// Override the queue name for this job.
822    #[must_use]
823    pub fn queue(mut self, queue: impl Into<String>) -> Self {
824        self.queue = queue.into();
825        self
826    }
827
828    /// Override the maximum number of retry attempts for this job.
829    #[must_use]
830    pub fn max_attempts(mut self, attempts: i64) -> Self {
831        self.max_attempts = attempts;
832        self
833    }
834
835    /// Set a short human-readable summary for the job manifest.
836    #[must_use]
837    pub fn summary(mut self, summary: impl Into<String>) -> Self {
838        self.summary = summary.into();
839        self
840    }
841
842    /// Extract serializable job metadata for the application manifest.
843    pub fn meta(&self) -> JobMeta {
844        JobMeta {
845            name: self.name.clone(),
846            queue: self.queue.clone(),
847            max_attempts: self.max_attempts,
848            summary: self.summary.clone(),
849        }
850    }
851}
852
853/// Recurring maintenance schedule that enqueues a registered job on a fixed interval.
854#[derive(Debug, Clone)]
855pub struct ScheduleDef {
856    /// Registered job name to enqueue on each tick.
857    pub job_name: String,
858    /// Interval between scheduled enqueues.
859    pub every: Duration,
860    /// JSON payload enqueued on each scheduled run.
861    pub payload: Value,
862}
863
864impl ScheduleDef {
865    /// Create a recurring schedule that enqueues `job_name` with `payload` on every `every` interval.
866    #[must_use]
867    pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
868        Self {
869            job_name: job_name.into(),
870            every,
871            payload,
872        }
873    }
874}
875
876/// Dispatches `SQLite`-queued jobs to discovered [`JobDef`] handlers.
877#[derive(Debug, Clone)]
878pub struct JobRegistry {
879    handlers: Arc<HashMap<String, JobDef>>,
880}
881
882impl JobRegistry {
883    /// Build a registry from discovered `jobs`, including the built-in `slabs.deliver_webhook` handler.
884    #[must_use]
885    pub fn new(jobs: Vec<JobDef>) -> Self {
886        let mut map = HashMap::new();
887        // Built-in dev-safe webhook delivery job (records delivery as 200 in outbox unless overridden)
888        map.insert(
889            "slabs.deliver_webhook".to_string(),
890            JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
891                .queue("webhooks")
892                .summary("Built-in webhook delivery handler"),
893        );
894        for job in jobs {
895            map.insert(job.name.clone(), job);
896        }
897        Self {
898            handlers: Arc::new(map),
899        }
900    }
901
902    /// Execute a registered job directly by name (ideal for testing scheduled/maintenance jobs).
903    pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
904        let def = self
905            .handlers
906            .get(job_name)
907            .ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
908        (def.handler)(ctx.clone(), payload).await
909    }
910
911    /// Dispatch a claimed [`JobRecord`] to its registered handler.
912    ///
913    /// If the stored JSON payload cannot be parsed (a poison pill), immediately dead-letters the
914    /// job via [`Jobs::mark_dead`] before returning an error so it cannot stall the queue.
915    pub async fn dispatch(&self, ctx: &AppCtx, job: &JobRecord) -> SlabResult<()> {
916        let Some(def) = self.handlers.get(&job.job_name) else {
917            return Err(SlabError::not_found(format!(
918                "no job handler registered for `{}`",
919                job.job_name
920            )));
921        };
922
923        let payload: Value = match serde_json::from_str(&job.payload_json) {
924            Ok(v) => v,
925            Err(e) => {
926                let msg = format!("invalid job payload: {e}");
927                let _ = ctx.jobs.mark_dead(&job.id, &msg).await;
928                return Err(SlabError::bad_request(msg));
929            }
930        };
931
932        (def.handler)(ctx.clone(), payload).await
933    }
934
935    /// Claim and execute the next ready job from the queue, returning `Ok(true)` if a job was processed.
936    pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
937        let Some(record) = ctx.jobs.claim_next().await? else {
938            return Ok(false);
939        };
940
941        let Some(def) = self.handlers.get(&record.job_name) else {
942            let msg = format!("no job handler registered for `{}`", record.job_name);
943            ctx.jobs.mark_failed(&record, &msg).await?;
944            return Ok(true);
945        };
946
947        let payload: Value = match serde_json::from_str(&record.payload_json) {
948            Ok(v) => v,
949            Err(e) => {
950                let msg = format!("invalid job payload: {e}");
951                let _ = ctx.jobs.mark_dead(&record.id, &msg).await;
952                return Err(SlabError::bad_request(msg));
953            }
954        };
955
956        match (def.handler)(ctx.clone(), payload).await {
957            Ok(()) => {
958                ctx.jobs.mark_done(&record.id).await?;
959            }
960            Err(err) => {
961                tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
962                ctx.jobs.mark_failed(&record, &err.to_string()).await?;
963            }
964        }
965
966        Ok(true)
967    }
968
969    /// Repeatedly run ready jobs until the queue is empty, returning the number of jobs processed.
970    pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
971        let mut processed = 0;
972        while self.run_next(ctx).await? {
973            processed += 1;
974        }
975        Ok(processed)
976    }
977
978    /// Spawn background job worker tasks without an external shutdown signal.
979    pub fn spawn_workers(&self, ctx: &AppCtx) {
980        let (_tx, rx) = watch::channel(false);
981        let _ = self.spawn_workers_with_shutdown(ctx, &rx);
982    }
983
984    /// Spawn background job worker tasks that stop cleanly when `shutdown` is signaled.
985    ///
986    /// Delegates execution to [`Jobs::spawn_workers_with_telemetry`] for lease reclamation,
987    /// timeouts, panic isolation, dead-letter incident capture, and slow-job tracking,
988    /// returning the spawned [`JoinHandle`]s for graceful drain.
989    pub fn spawn_workers_with_shutdown(
990        &self,
991        ctx: &AppCtx,
992        shutdown: &watch::Receiver<bool>,
993    ) -> Vec<JoinHandle<()>> {
994        let concurrency = ctx.config.job_concurrency.max(1);
995        let poll_interval = Duration::from_millis(ctx.config.job_poll_interval_ms.max(50));
996        let registry = self.clone();
997        let worker_ctx = ctx.clone();
998
999        ctx.jobs.spawn_workers_with_telemetry(
1000            concurrency,
1001            poll_interval,
1002            shutdown,
1003            move |job| {
1004                let registry = registry.clone();
1005                let worker_ctx = worker_ctx.clone();
1006                async move { registry.dispatch(&worker_ctx, &job).await }
1007            },
1008            Some(ctx.incidents.clone()),
1009            ctx.config.slow_job_ms,
1010            ctx.config.git_sha.clone(),
1011        )
1012    }
1013
1014    /// Spawn recurring schedule tasks without an external shutdown signal.
1015    pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
1016        let (_tx, rx) = watch::channel(false);
1017        let _ = self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
1018    }
1019
1020    /// Spawn recurring schedule tasks that stop cleanly when `shutdown` is signaled, returning
1021    /// their [`JoinHandle`]s.
1022    pub fn spawn_schedules_with_shutdown(
1023        &self,
1024        ctx: &AppCtx,
1025        schedules: Vec<ScheduleDef>,
1026        shutdown: &watch::Receiver<bool>,
1027    ) -> Vec<JoinHandle<()>> {
1028        let mut handles = Vec::with_capacity(schedules.len());
1029        for schedule in schedules {
1030            let sched_ctx = ctx.clone();
1031            let mut rx = shutdown.clone();
1032            handles.push(tokio::spawn(async move {
1033                let mut ticker = tokio::time::interval(schedule.every);
1034                ticker.tick().await;
1035                loop {
1036                    tokio::select! {
1037                        _ = ticker.tick() => {
1038                            if let Err(err) = sched_ctx
1039                                .jobs
1040                                .enqueue(&schedule.job_name, schedule.payload.clone())
1041                                .await
1042                            {
1043                                tracing::error!(
1044                                    job = %schedule.job_name,
1045                                    error = %err,
1046                                    "failed to enqueue scheduled job"
1047                                );
1048                            }
1049                        }
1050                        _ = rx.changed() => {
1051                            break;
1052                        }
1053                    }
1054                }
1055            }));
1056        }
1057        handles
1058    }
1059}
1060
1061async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
1062    let delivery_id = payload
1063        .get("delivery_id")
1064        .and_then(|v| v.as_str())
1065        .ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
1066    if ctx.config.webhooks_live {
1067        ctx.webhooks
1068            .deliver_http(delivery_id, ctx.config.webhooks_allow_local)
1069            .await?;
1070    } else {
1071        // Dev/test safe mode: marks signed delivery recorded in outbox without external HTTP calls.
1072        ctx.webhooks.mark_delivered(delivery_id, 200).await?;
1073    }
1074    Ok(())
1075}
1076
1077/// Assemble the full [`axum::Router`] from discovered slabs, built-in endpoints, and middleware.
1078///
1079/// Slabs registered on the same path with different HTTP methods are merged into one
1080/// [`MethodRouter`]. Mounts health probes (`/health`, `/health/live`, `/health/ready`,
1081/// `/_slabs/health`), `/_slabs/metrics`, `/_slabs/vendor/*`, `/assets/{hash}/{*path}`, and
1082/// dev-only endpoints (`/_slabs/manifest`, `/_slabs/openapi.json`, `/_slabs/mail`) when
1083/// `ctx.config.env.is_dev_or_test()`, then applies the hardened Tower middleware stack.
1084pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
1085    let manifest = Arc::new(AppManifest {
1086        app_name: ctx.config.app_name.clone(),
1087        routes: slabs.iter().map(SlabDef::meta).collect(),
1088        jobs: jobs.iter().map(JobDef::meta).collect(),
1089    });
1090
1091    let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
1092    let mut skip_csrf_routes: HashSet<(String, String)> = HashSet::new();
1093    skip_csrf_routes.insert(("POST".to_owned(), "/_slabs/client-errors".to_owned()));
1094    for slab in slabs {
1095        if slab.skip_csrf {
1096            skip_csrf_routes.insert((slab.method.to_ascii_uppercase(), slab.path.clone()));
1097        }
1098        let source_file = derive_slab_source_file(&slab);
1099        ctx.metrics
1100            .register_route_source(&slab.method, &slab.path, source_file);
1101        match grouped.entry(slab.path) {
1102            Entry::Occupied(mut existing) => {
1103                let taken = std::mem::take(existing.get_mut());
1104                *existing.get_mut() = taken.merge(slab.router);
1105            }
1106            Entry::Vacant(slot) => {
1107                slot.insert(slab.router);
1108            }
1109        }
1110    }
1111
1112    let has_custom_health = grouped.contains_key("/health");
1113    let has_custom_health_live = grouped.contains_key("/health/live");
1114    let has_custom_health_ready = grouped.contains_key("/health/ready");
1115
1116    let mut router: Router<AppCtx> = Router::new();
1117    for (path, method_router) in grouped {
1118        router = router.route(&path, method_router);
1119    }
1120
1121    if !has_custom_health {
1122        router = router.route("/health", get(health_handler));
1123    }
1124    if !has_custom_health_live {
1125        router = router.route("/health/live", get(health_live_handler));
1126    }
1127    if !has_custom_health_ready {
1128        router = router.route("/health/ready", get(health_ready_handler));
1129    }
1130
1131    router = router
1132        .route("/_slabs/health", get(health_handler))
1133        .route("/_slabs/metrics", get(metrics_handler))
1134        .route("/_slabs/incidents", get(list_incidents_handler))
1135        .route("/_slabs/incidents/ui", get(incidents_ui_handler))
1136        .route("/_slabs/incidents/{id}", get(get_incident_handler))
1137        .route("/_slabs/incidents/{id}/claim", post(claim_incident_handler))
1138        .route("/_slabs/incidents/{id}/link", post(link_incident_handler))
1139        .route(
1140            "/_slabs/incidents/{id}/ignore",
1141            post(ignore_incident_handler),
1142        )
1143        .route(
1144            "/_slabs/incidents/{id}/resolve",
1145            post(resolve_incident_handler),
1146        )
1147        .route(
1148            "/_slabs/incidents/{id}/attachments/{blob_id}",
1149            get(incident_attachment_handler),
1150        )
1151        .route("/_slabs/client-errors", post(client_errors_handler))
1152        .route(
1153            "/_slabs/bug-reports",
1154            post(bug_reports_handler).layer(DefaultBodyLimit::disable()),
1155        )
1156        .route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
1157        .route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
1158        .route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
1159        .route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
1160        .route(
1161            "/_slabs/vendor/idiomorph-ext.min.js",
1162            get(vendor_idiomorph_js),
1163        )
1164        .route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
1165        .route("/_slabs/vendor/sw-register.js", get(vendor_sw_register_js))
1166        .route(
1167            "/_slabs/vendor/slabs-telemetry.js",
1168            get(vendor_slabs_telemetry_js),
1169        )
1170        .route(
1171            "/_slabs/vendor/slabs-bug-report.js",
1172            get(vendor_slabs_bug_report_js),
1173        )
1174        .route("/assets/{hash}/{*path}", get(serve_asset_handler));
1175
1176    if ctx.config.env.is_dev_or_test() {
1177        let openapi_manifest = manifest.clone();
1178        router = router
1179            .route(
1180                "/_slabs/manifest",
1181                get(move || {
1182                    let m = manifest.clone();
1183                    async move { Json((*m).clone()) }
1184                }),
1185            )
1186            .route(
1187                "/_slabs/openapi.json",
1188                get(move || {
1189                    let m = openapi_manifest.clone();
1190                    async move { Json(m.to_openapi_3_1()) }
1191                }),
1192            )
1193            .route("/_slabs/mail", get(dev_mail_outbox_handler));
1194    }
1195
1196    let max_body_bytes = ctx.config.max_body_bytes;
1197    let cookie_secure = ctx.config.cookie_secure;
1198    let cors_origins: Vec<HeaderValue> = ctx
1199        .config
1200        .cors_origins
1201        .iter()
1202        .filter_map(|o| {
1203            let trimmed = o.trim();
1204            if trimmed.is_empty() {
1205                None
1206            } else {
1207                HeaderValue::from_str(trimmed).ok()
1208            }
1209        })
1210        .collect();
1211
1212    let x_request_id = HeaderName::from_static("x-request-id");
1213    let state_ctx = ctx.clone();
1214    let csrf_state = CsrfState {
1215        ctx: state_ctx.clone(),
1216        skip_routes: Arc::new(skip_csrf_routes),
1217    };
1218
1219    let mut app = router
1220        .route_layer(middleware::from_fn_with_state(
1221            state_ctx,
1222            metrics_middleware,
1223        ))
1224        .route_layer(middleware::from_fn_with_state(csrf_state, csrf_middleware))
1225        .with_state(ctx)
1226        .layer(CompressionLayer::new())
1227        .layer(RequestBodyLimitLayer::new(max_body_bytes))
1228        .layer(SetResponseHeaderLayer::if_not_present(
1229            header::X_CONTENT_TYPE_OPTIONS,
1230            HeaderValue::from_static("nosniff"),
1231        ))
1232        .layer(SetResponseHeaderLayer::if_not_present(
1233            header::X_FRAME_OPTIONS,
1234            HeaderValue::from_static("SAMEORIGIN"),
1235        ))
1236        .layer(SetResponseHeaderLayer::if_not_present(
1237            header::REFERRER_POLICY,
1238            HeaderValue::from_static("strict-origin-when-cross-origin"),
1239        ))
1240        .layer(SetResponseHeaderLayer::if_not_present(
1241            HeaderName::from_static("permissions-policy"),
1242            HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
1243        ));
1244
1245    if cookie_secure {
1246        app = app.layer(SetResponseHeaderLayer::if_not_present(
1247            header::STRICT_TRANSPORT_SECURITY,
1248            HeaderValue::from_static("max-age=31536000; includeSubDomains"),
1249        ));
1250    }
1251
1252    if !cors_origins.is_empty() {
1253        let cors = CorsLayer::new()
1254            .allow_origin(AllowOrigin::list(cors_origins))
1255            .allow_methods([
1256                Method::GET,
1257                Method::POST,
1258                Method::PUT,
1259                Method::PATCH,
1260                Method::DELETE,
1261                Method::OPTIONS,
1262            ])
1263            .allow_headers([
1264                header::AUTHORIZATION,
1265                header::CONTENT_TYPE,
1266                header::ACCEPT,
1267                HeaderName::from_static("hx-request"),
1268                HeaderName::from_static("hx-target"),
1269                HeaderName::from_static("hx-current-url"),
1270                HeaderName::from_static("x-csrf-token"),
1271                HeaderName::from_static("x-request-id"),
1272            ])
1273            .allow_credentials(true);
1274        app = app.layer(cors);
1275    }
1276
1277    app.layer(PropagateRequestIdLayer::new(x_request_id.clone()))
1278        .layer(TraceLayer::new_for_http())
1279        .layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
1280        .layer(middleware::from_fn(sanitize_request_id_middleware))
1281}
1282
1283async fn sanitize_request_id_middleware(mut request: Request, next: Next) -> Response {
1284    let x_request_id = HeaderName::from_static("x-request-id");
1285    let invalid = request.headers().get(&x_request_id).is_some_and(|val| {
1286        val.to_str().map_or(true, |s| {
1287            s.is_empty()
1288                || s.len() > 64
1289                || !s
1290                    .bytes()
1291                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
1292        })
1293    });
1294    if invalid {
1295        request.headers_mut().remove(&x_request_id);
1296    }
1297    next.run(request).await
1298}
1299
1300fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
1301    if let Some(s) = payload.downcast_ref::<&str>() {
1302        (*s).to_owned()
1303    } else if let Some(s) = payload.downcast_ref::<String>() {
1304        s.clone()
1305    } else {
1306        "handler panicked".to_owned()
1307    }
1308}
1309
1310fn incident_webhook_client() -> &'static reqwest::Client {
1311    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
1312    CLIENT.get_or_init(|| {
1313        reqwest::Client::builder()
1314            .timeout(Duration::from_secs(5))
1315            .redirect(reqwest::redirect::Policy::none())
1316            .build()
1317            .expect("failed to build incident webhook HTTP client")
1318    })
1319}
1320
1321fn sign_incident_webhook(secret: &str, body: &[u8]) -> String {
1322    let mut mac =
1323        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts keys of any size");
1324    mac.update(body);
1325    format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
1326}
1327
1328fn spawn_incident_webhook(ctx: &AppCtx, event: &'static str, record: &IncidentRecord) {
1329    let Some(raw_url) = ctx.config.incident_webhook_url.as_deref() else {
1330        return;
1331    };
1332    let validated_url =
1333        match Webhooks::validate_url_with_policy(raw_url, ctx.config.webhooks_allow_local) {
1334            Ok(url) => url,
1335            Err(err) => {
1336                tracing::warn!(
1337                    error = %err,
1338                    "skipped incident webhook notification because URL failed SSRF validation"
1339                );
1340                return;
1341            }
1342        };
1343
1344    let payload = json!({
1345        "protocol": INCIDENT_PROTOCOL_VERSION,
1346        "event": event,
1347        "sent_at": Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true),
1348        "app": ctx.config.app_name,
1349        "env": ctx.config.env.as_str(),
1350        "incident": record,
1351    });
1352    let Ok(body_bytes) = serde_json::to_vec(&payload) else {
1353        tracing::warn!("failed to serialize incident webhook payload");
1354        return;
1355    };
1356    let signature = ctx
1357        .config
1358        .incident_webhook_secret
1359        .as_deref()
1360        .map(|secret| sign_incident_webhook(secret, &body_bytes));
1361
1362    tokio::spawn(async move {
1363        let client = incident_webhook_client();
1364        let mut req = client
1365            .post(&validated_url)
1366            .header(header::CONTENT_TYPE, "application/json")
1367            .header("x-slabs-event", event)
1368            .header("x-slabs-protocol", INCIDENT_PROTOCOL_VERSION)
1369            .body(body_bytes);
1370        if let Some(sig) = signature {
1371            req = req.header("x-slabs-signature", sig);
1372        }
1373        if let Err(err) = req.send().await {
1374            tracing::warn!(error = %err, event, "incident webhook notification failed");
1375        }
1376    });
1377}
1378
1379async fn record_and_notify_incident(ctx: &AppCtx, input: IncidentInput) -> Option<IncidentRecord> {
1380    let (record, outcome) = match ctx.incidents.record_with_outcome(input).await {
1381        Ok(res) => res,
1382        Err(err) => {
1383            tracing::error!(error = %err, "failed to persist runtime incident");
1384            return None;
1385        }
1386    };
1387
1388    match outcome {
1389        IncidentOutcome::Opened => spawn_incident_webhook(ctx, "incident.opened", &record),
1390        IncidentOutcome::Reopened => spawn_incident_webhook(ctx, "incident.reopened", &record),
1391        IncidentOutcome::Incremented => {}
1392    }
1393
1394    Some(record)
1395}
1396
1397async fn metrics_middleware(State(ctx): State<AppCtx>, request: Request, next: Next) -> Response {
1398    let method = request.method().as_str().to_owned();
1399    let raw_path = request.uri().path().to_owned();
1400    let route_pattern = request
1401        .extensions()
1402        .get::<MatchedPath>()
1403        .map_or_else(|| raw_path.clone(), |m| m.as_str().to_owned());
1404    let request_id = request
1405        .headers()
1406        .get("x-request-id")
1407        .and_then(|v| v.to_str().ok())
1408        .unwrap_or("")
1409        .to_owned();
1410    let is_ws_upgrade = request
1411        .headers()
1412        .get(header::UPGRADE)
1413        .and_then(|v| v.to_str().ok())
1414        .is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
1415    let source_file = ctx.metrics.source_file(&method, &route_pattern);
1416    let started = Instant::now();
1417
1418    match AssertUnwindSafe(next.run(request)).catch_unwind().await {
1419        Ok(response) => {
1420            let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
1421            let status = response.status();
1422            let is_5xx = status.is_server_error();
1423            let is_sse = response
1424                .headers()
1425                .get(header::CONTENT_TYPE)
1426                .and_then(|v| v.to_str().ok())
1427                .is_some_and(|v| v.to_ascii_lowercase().starts_with("text/event-stream"));
1428            let is_stream = is_ws_upgrade || status == StatusCode::SWITCHING_PROTOCOLS || is_sse;
1429            let is_internal_route = raw_path.starts_with("/_slabs/");
1430            let is_slow =
1431                !is_internal_route && !is_stream && elapsed_ms >= ctx.config.slow_request_ms;
1432
1433            ctx.metrics.record_request(
1434                &method,
1435                &route_pattern,
1436                &source_file,
1437                elapsed_ms,
1438                is_5xx,
1439                is_slow,
1440            );
1441
1442            if is_5xx {
1443                let input = IncidentInput {
1444                    kind: "http_5xx".into(),
1445                    source_file: source_file.clone(),
1446                    route_pattern: Some(route_pattern.clone()),
1447                    status_code: Some(i64::from(status.as_u16())),
1448                    error_message: format!(
1449                        "HTTP {} on {} {}",
1450                        status.as_u16(),
1451                        method,
1452                        route_pattern
1453                    ),
1454                    detail: Some(format!(
1455                        "{method} {route_pattern} returned {} in {elapsed_ms}ms",
1456                        status.as_u16()
1457                    )),
1458                    context_json: json!({
1459                        "method": method,
1460                        "request_id": request_id,
1461                        "latency_ms": elapsed_ms,
1462                        "status": status.as_u16(),
1463                        "env": ctx.config.env.as_str(),
1464                        "git_sha": ctx.config.git_sha,
1465                    }),
1466                    git_sha: ctx.config.git_sha.clone(),
1467                    custom_fingerprint: None,
1468                };
1469                let _ = record_and_notify_incident(&ctx, input).await;
1470            }
1471
1472            if is_slow {
1473                let input = IncidentInput {
1474                    kind: "slow_request".into(),
1475                    source_file,
1476                    route_pattern: Some(route_pattern.clone()),
1477                    status_code: Some(i64::from(status.as_u16())),
1478                    error_message: format!(
1479                        "slow request on {} {} exceeded {}ms threshold",
1480                        method, route_pattern, ctx.config.slow_request_ms
1481                    ),
1482                    detail: Some(format!(
1483                        "{method} {route_pattern} took {elapsed_ms}ms (threshold {}ms, status {})",
1484                        ctx.config.slow_request_ms,
1485                        status.as_u16()
1486                    )),
1487                    context_json: json!({
1488                        "method": method,
1489                        "request_id": request_id,
1490                        "latency_ms": elapsed_ms,
1491                        "threshold_ms": ctx.config.slow_request_ms,
1492                        "status": status.as_u16(),
1493                        "env": ctx.config.env.as_str(),
1494                        "git_sha": ctx.config.git_sha,
1495                    }),
1496                    git_sha: ctx.config.git_sha.clone(),
1497                    custom_fingerprint: None,
1498                };
1499                let _ = record_and_notify_incident(&ctx, input).await;
1500            }
1501
1502            response
1503        }
1504        Err(panic_payload) => {
1505            let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
1506            let panic_msg = panic_payload_message(panic_payload.as_ref());
1507            let is_slow =
1508                !raw_path.starts_with("/_slabs/") && elapsed_ms >= ctx.config.slow_request_ms;
1509
1510            tracing::error!(
1511                method = %method,
1512                route = %route_pattern,
1513                source_file = %source_file,
1514                request_id = %request_id,
1515                panic = %panic_msg,
1516                "HTTP handler panicked"
1517            );
1518
1519            ctx.metrics.record_request(
1520                &method,
1521                &route_pattern,
1522                &source_file,
1523                elapsed_ms,
1524                true,
1525                is_slow,
1526            );
1527
1528            let input = IncidentInput {
1529                kind: "panic".into(),
1530                source_file,
1531                route_pattern: Some(route_pattern.clone()),
1532                status_code: Some(500),
1533                error_message: panic_msg.clone(),
1534                detail: Some(format!(
1535                    "HTTP {method} {route_pattern} panicked: {panic_msg}"
1536                )),
1537                context_json: json!({
1538                    "method": method,
1539                    "request_id": request_id,
1540                    "latency_ms": elapsed_ms,
1541                    "env": ctx.config.env.as_str(),
1542                    "git_sha": ctx.config.git_sha,
1543                }),
1544                git_sha: ctx.config.git_sha.clone(),
1545                custom_fingerprint: None,
1546            };
1547            let _ = record_and_notify_incident(&ctx, input).await;
1548
1549            (
1550                StatusCode::INTERNAL_SERVER_ERROR,
1551                Json(json!({ "error": "internal server error" })),
1552            )
1553                .into_response()
1554        }
1555    }
1556}
1557
1558#[derive(Clone)]
1559struct CsrfState {
1560    ctx: AppCtx,
1561    skip_routes: Arc<HashSet<(String, String)>>,
1562}
1563
1564async fn csrf_middleware(State(state): State<CsrfState>, request: Request, next: Next) -> Response {
1565    if !state.ctx.config.csrf_enforce {
1566        return next.run(request).await;
1567    }
1568
1569    if !matches!(
1570        *request.method(),
1571        Method::POST | Method::PUT | Method::PATCH | Method::DELETE
1572    ) {
1573        return next.run(request).await;
1574    }
1575
1576    let headers = request.headers();
1577    if !headers.contains_key(header::COOKIE) {
1578        return next.run(request).await;
1579    }
1580
1581    if headers
1582        .get(header::AUTHORIZATION)
1583        .and_then(|v| v.to_str().ok())
1584        .is_some_and(|v| v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer "))
1585    {
1586        return next.run(request).await;
1587    }
1588
1589    let method = request.method().as_str().to_ascii_uppercase();
1590    let matched_path = request
1591        .extensions()
1592        .get::<MatchedPath>()
1593        .map_or_else(|| request.uri().path(), MatchedPath::as_str);
1594    if matched_path == "/_slabs/client-errors"
1595        || state
1596            .skip_routes
1597            .contains(&(method, matched_path.to_owned()))
1598    {
1599        return next.run(request).await;
1600    }
1601
1602    if headers
1603        .get("sec-fetch-site")
1604        .and_then(|v| v.to_str().ok())
1605        .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
1606    {
1607        return SlabError::forbidden("cross-site request blocked by fetch metadata policy")
1608            .into_response();
1609    }
1610
1611    if let Some(origin_val) = headers.get(header::ORIGIN) {
1612        let Ok(origin_raw) = origin_val.to_str().map(str::trim) else {
1613            return SlabError::forbidden("invalid Origin header").into_response();
1614        };
1615        if !is_allowed_origin(origin_raw, headers, &state.ctx.config.cors_origins) {
1616            return SlabError::forbidden("cross-origin request blocked").into_response();
1617        }
1618    }
1619
1620    next.run(request).await
1621}
1622
1623fn is_allowed_origin(origin_raw: &str, headers: &HeaderMap, cors_origins: &[String]) -> bool {
1624    if origin_raw.is_empty() || origin_raw.eq_ignore_ascii_case("null") {
1625        return false;
1626    }
1627    if cors_origins
1628        .iter()
1629        .any(|allowed| allowed.trim().eq_ignore_ascii_case(origin_raw))
1630    {
1631        return true;
1632    }
1633
1634    let Ok(origin_uri) = origin_raw.parse::<Uri>() else {
1635        return false;
1636    };
1637    let Some(scheme) = origin_uri.scheme_str() else {
1638        return false;
1639    };
1640    if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
1641        return false;
1642    }
1643    let Some(authority) = origin_uri.authority() else {
1644        return false;
1645    };
1646    if authority.as_str().contains('@') {
1647        return false;
1648    }
1649
1650    let Some(host_raw) = headers
1651        .get(header::HOST)
1652        .and_then(|v| v.to_str().ok())
1653        .map(str::trim)
1654        .filter(|v| !v.is_empty())
1655    else {
1656        return false;
1657    };
1658
1659    authorities_match(scheme, authority.as_str(), host_raw)
1660}
1661
1662fn authorities_match(scheme: &str, origin_authority: &str, host_header: &str) -> bool {
1663    if origin_authority.eq_ignore_ascii_case(host_header) {
1664        return true;
1665    }
1666    let default_port = if scheme.eq_ignore_ascii_case("https") {
1667        ":443"
1668    } else {
1669        ":80"
1670    };
1671    let norm_origin = origin_authority
1672        .strip_suffix(default_port)
1673        .unwrap_or(origin_authority);
1674    let norm_host = host_header
1675        .strip_suffix(default_port)
1676        .unwrap_or(host_header);
1677    norm_origin.eq_ignore_ascii_case(norm_host)
1678}
1679
1680fn constant_time_eq_sha256(a: &[u8], b: &[u8]) -> bool {
1681    let ha = Sha256::digest(a);
1682    let hb = Sha256::digest(b);
1683    let mut diff = 0u8;
1684    for (x, y) in ha.iter().zip(hb.iter()) {
1685        diff |= x ^ y;
1686    }
1687    diff == 0
1688}
1689
1690async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
1691    ctx.db.ping().await?;
1692    Ok(Json(json!({
1693        "status": "ok",
1694        "app": ctx.config.app_name,
1695    })))
1696}
1697
1698async fn health_live_handler() -> Json<Value> {
1699    Json(json!({ "status": "ok" }))
1700}
1701
1702async fn health_ready_handler(State(ctx): State<AppCtx>) -> Response {
1703    if ctx.is_draining() {
1704        return (
1705            StatusCode::SERVICE_UNAVAILABLE,
1706            Json(json!({ "status": "draining" })),
1707        )
1708            .into_response();
1709    }
1710    match ctx.db.ping().await {
1711        Ok(()) => (StatusCode::OK, Json(json!({ "status": "ok" }))).into_response(),
1712        Err(err) => {
1713            tracing::warn!(error = %err, "readiness probe database check failed");
1714            (
1715                StatusCode::SERVICE_UNAVAILABLE,
1716                Json(json!({ "status": "unavailable" })),
1717            )
1718                .into_response()
1719        }
1720    }
1721}
1722
1723fn check_observability_auth(ctx: &AppCtx, headers: &HeaderMap) -> Option<Response> {
1724    if let Some(expected) = &ctx.config.metrics_token {
1725        let provided = headers
1726            .get(header::AUTHORIZATION)
1727            .and_then(|v| v.to_str().ok())
1728            .and_then(|v| v.strip_prefix("Bearer "));
1729        match provided {
1730            Some(token) if constant_time_eq_sha256(token.as_bytes(), expected.as_bytes()) => None,
1731            _ => Some(StatusCode::UNAUTHORIZED.into_response()),
1732        }
1733    } else if ctx.config.env.is_prod_like() {
1734        Some(StatusCode::NOT_FOUND.into_response())
1735    } else {
1736        None
1737    }
1738}
1739
1740fn escape_prom_label(raw: &str) -> String {
1741    let mut out = String::with_capacity(raw.len());
1742    for ch in raw.chars() {
1743        match ch {
1744            '\\' => out.push_str("\\\\"),
1745            '"' => out.push_str("\\\""),
1746            '\n' => out.push_str("\\n"),
1747            other => out.push(other),
1748        }
1749    }
1750    out
1751}
1752
1753async fn metrics_handler(State(ctx): State<AppCtx>, headers: HeaderMap) -> Response {
1754    if let Some(resp) = check_observability_auth(&ctx, &headers) {
1755        return resp;
1756    }
1757
1758    let requests_total = ctx.metrics.requests.load(Ordering::Relaxed);
1759    let errors_5xx_total = ctx.metrics.errors_5xx.load(Ordering::Relaxed);
1760    let latency_ms_total = ctx.metrics.latency_ms.load(Ordering::Relaxed);
1761    #[allow(clippy::cast_precision_loss)]
1762    let avg_latency_ms = if requests_total > 0 {
1763        latency_ms_total as f64 / requests_total as f64
1764    } else {
1765        0.0
1766    };
1767    let job_stats = ctx.jobs.stats().await.unwrap_or_default();
1768    let realtime_topics = ctx.realtime.active_topic_count();
1769    let open_incidents = ctx.incidents.count_open().await.unwrap_or(0);
1770    let route_snapshots = ctx.metrics.route_snapshots();
1771
1772    let wants_json = headers
1773        .get(header::ACCEPT)
1774        .and_then(|v| v.to_str().ok())
1775        .is_some_and(|v| v.contains("application/json"));
1776
1777    if wants_json {
1778        let routes_json: Vec<Value> = route_snapshots
1779            .iter()
1780            .map(|r| {
1781                json!({
1782                    "method": r.method,
1783                    "route": r.route,
1784                    "source_file": r.source_file,
1785                    "requests": r.requests,
1786                    "errors_5xx": r.errors_5xx,
1787                    "slow_requests": r.slow_requests,
1788                    "avg_latency_ms": r.avg_latency_ms,
1789                    "p50_ms": r.p50_ms,
1790                    "p95_ms": r.p95_ms,
1791                    "p99_ms": r.p99_ms,
1792                    "max_latency_ms": r.max_latency_ms,
1793                })
1794            })
1795            .collect();
1796        return (
1797            StatusCode::OK,
1798            Json(json!({
1799                "http": {
1800                    "requests_total": requests_total,
1801                    "errors_5xx_total": errors_5xx_total,
1802                    "latency_ms_total": latency_ms_total,
1803                    "avg_latency_ms": avg_latency_ms,
1804                },
1805                "routes": routes_json,
1806                "open_incidents": open_incidents,
1807                "jobs": {
1808                    "pending": job_stats.pending,
1809                    "running": job_stats.running,
1810                    "dead": job_stats.dead,
1811                    "completed": job_stats.completed,
1812                },
1813                "realtime": {
1814                    "active_topics": realtime_topics,
1815                },
1816            })),
1817        )
1818            .into_response();
1819    }
1820
1821    let mut body = String::with_capacity(1024);
1822    let _ = writeln!(
1823        body,
1824        "# HELP slabs_http_requests_total Total HTTP requests handled."
1825    );
1826    let _ = writeln!(body, "# TYPE slabs_http_requests_total counter");
1827    let _ = writeln!(body, "slabs_http_requests_total {requests_total}");
1828    let _ = writeln!(
1829        body,
1830        "# HELP slabs_http_errors_5xx_total Total HTTP 5xx responses."
1831    );
1832    let _ = writeln!(body, "# TYPE slabs_http_errors_5xx_total counter");
1833    let _ = writeln!(body, "slabs_http_errors_5xx_total {errors_5xx_total}");
1834    let _ = writeln!(
1835        body,
1836        "# HELP slabs_http_latency_ms_total Cumulative HTTP latency in milliseconds."
1837    );
1838    let _ = writeln!(body, "# TYPE slabs_http_latency_ms_total counter");
1839    let _ = writeln!(body, "slabs_http_latency_ms_total {latency_ms_total}");
1840    let _ = writeln!(
1841        body,
1842        "# HELP slabs_http_latency_avg_ms Average HTTP latency in milliseconds."
1843    );
1844    let _ = writeln!(body, "# TYPE slabs_http_latency_avg_ms gauge");
1845    let _ = writeln!(body, "slabs_http_latency_avg_ms {avg_latency_ms:.3}");
1846    let _ = writeln!(body, "# HELP slabs_jobs_pending Pending background jobs.");
1847    let _ = writeln!(body, "# TYPE slabs_jobs_pending gauge");
1848    let _ = writeln!(body, "slabs_jobs_pending {}", job_stats.pending);
1849    let _ = writeln!(body, "# HELP slabs_jobs_running Running background jobs.");
1850    let _ = writeln!(body, "# TYPE slabs_jobs_running gauge");
1851    let _ = writeln!(body, "slabs_jobs_running {}", job_stats.running);
1852    let _ = writeln!(
1853        body,
1854        "# HELP slabs_jobs_dead Dead-lettered background jobs."
1855    );
1856    let _ = writeln!(body, "# TYPE slabs_jobs_dead gauge");
1857    let _ = writeln!(body, "slabs_jobs_dead {}", job_stats.dead);
1858    let _ = writeln!(
1859        body,
1860        "# HELP slabs_jobs_completed Completed background jobs."
1861    );
1862    let _ = writeln!(body, "# TYPE slabs_jobs_completed counter");
1863    let _ = writeln!(body, "slabs_jobs_completed {}", job_stats.completed);
1864    let _ = writeln!(
1865        body,
1866        "# HELP slabs_realtime_active_topics Active realtime pub/sub topics."
1867    );
1868    let _ = writeln!(body, "# TYPE slabs_realtime_active_topics gauge");
1869    let _ = writeln!(body, "slabs_realtime_active_topics {realtime_topics}");
1870    let _ = writeln!(body, "# HELP slabs_incidents_open Open runtime incidents.");
1871    let _ = writeln!(body, "# TYPE slabs_incidents_open gauge");
1872    let _ = writeln!(body, "slabs_incidents_open {open_incidents}");
1873
1874    if !route_snapshots.is_empty() {
1875        let _ = writeln!(
1876            body,
1877            "# HELP slabs_route_requests_total Total HTTP requests per route."
1878        );
1879        let _ = writeln!(body, "# TYPE slabs_route_requests_total counter");
1880        for r in &route_snapshots {
1881            let _ = writeln!(
1882                body,
1883                "slabs_route_requests_total{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
1884                escape_prom_label(&r.method),
1885                escape_prom_label(&r.route),
1886                escape_prom_label(&r.source_file),
1887                r.requests
1888            );
1889        }
1890        let _ = writeln!(
1891            body,
1892            "# HELP slabs_route_slow_total Slow HTTP requests per route."
1893        );
1894        let _ = writeln!(body, "# TYPE slabs_route_slow_total counter");
1895        for r in &route_snapshots {
1896            let _ = writeln!(
1897                body,
1898                "slabs_route_slow_total{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
1899                escape_prom_label(&r.method),
1900                escape_prom_label(&r.route),
1901                escape_prom_label(&r.source_file),
1902                r.slow_requests
1903            );
1904        }
1905        let _ = writeln!(
1906            body,
1907            "# HELP slabs_route_p95_ms Estimated p95 latency in milliseconds per route."
1908        );
1909        let _ = writeln!(body, "# TYPE slabs_route_p95_ms gauge");
1910        for r in &route_snapshots {
1911            let _ = writeln!(
1912                body,
1913                "slabs_route_p95_ms{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
1914                escape_prom_label(&r.method),
1915                escape_prom_label(&r.route),
1916                escape_prom_label(&r.source_file),
1917                r.p95_ms
1918            );
1919        }
1920    }
1921
1922    (
1923        StatusCode::OK,
1924        [(
1925            header::CONTENT_TYPE,
1926            HeaderValue::from_static("text/plain; version=0.0.4; charset=utf-8"),
1927        )],
1928        body,
1929    )
1930        .into_response()
1931}
1932
1933#[derive(Debug, Deserialize)]
1934struct ListIncidentsQuery {
1935    status: Option<String>,
1936    limit: Option<i64>,
1937}
1938
1939#[derive(Debug, Deserialize)]
1940struct ResolveIncidentBody {
1941    resolved_in_sha: Option<String>,
1942}
1943
1944#[derive(Debug, Deserialize)]
1945struct ClaimIncidentBody {
1946    assignee: String,
1947}
1948
1949#[derive(Debug, Deserialize)]
1950struct LinkIncidentBody {
1951    external_issue_key: String,
1952    external_issue_url: String,
1953}
1954
1955#[derive(Debug, Clone, Deserialize)]
1956struct RecentOccurrenceEntry {
1957    #[serde(default)]
1958    seen_at: Option<String>,
1959    #[serde(default)]
1960    git_sha: Option<String>,
1961    #[serde(default)]
1962    request_id: Option<String>,
1963    #[serde(default)]
1964    latency_ms: Option<u64>,
1965}
1966
1967#[derive(Debug, Deserialize)]
1968struct ClientErrorPayload {
1969    #[serde(default)]
1970    kind: Option<String>,
1971    message: String,
1972    #[serde(default)]
1973    path: Option<String>,
1974    #[serde(default)]
1975    detail: Option<String>,
1976}
1977
1978fn repro_hint_for(inc: &IncidentRecord) -> String {
1979    if inc.source_file.starts_with("slabs/") || inc.source_file.starts_with("jobs/") {
1980        let test_filter = inc.source_file.trim_end_matches(".rs").replace('/', "::");
1981        format!(
1982            "Inspect `{}` and verify with `slabs check` (or `cargo test {}`)",
1983            inc.source_file, test_filter
1984        )
1985    } else {
1986        format!(
1987            "Inspect `{}` ({}) and verify with `slabs check`",
1988            inc.source_file,
1989            inc.route_pattern.as_deref().unwrap_or("unknown route")
1990        )
1991    }
1992}
1993
1994fn enrich_incident_json(inc: &IncidentRecord) -> Value {
1995    let mut value = serde_json::to_value(inc).unwrap_or_else(|_| json!({}));
1996    if let Some(obj) = value.as_object_mut() {
1997        obj.insert("repro_hint".into(), Value::String(repro_hint_for(inc)));
1998    }
1999    value
2000}
2001
2002async fn authorize_diagnostics(
2003    ctx: &AppCtx,
2004    headers: &HeaderMap,
2005    jar: &CookieJar,
2006) -> Option<Response> {
2007    if ctx.config.env.is_dev_or_test() {
2008        return None;
2009    }
2010
2011    if let Some(expected) = &ctx.config.metrics_token {
2012        let provided = headers
2013            .get(header::AUTHORIZATION)
2014            .and_then(|v| v.to_str().ok())
2015            .and_then(|v| v.strip_prefix("Bearer "));
2016        if let Some(token) = provided {
2017            if constant_time_eq_sha256(token.as_bytes(), expected.as_bytes()) {
2018                return None;
2019            }
2020        }
2021    }
2022
2023    let session = ctx.auth.optional_session(jar).await.ok().flatten();
2024    if let Some(ref s) = session {
2025        if s.role == "admin" {
2026            return None;
2027        }
2028    }
2029
2030    if ctx.config.metrics_token.is_some() {
2031        Some(StatusCode::UNAUTHORIZED.into_response())
2032    } else if session.is_some() {
2033        Some(StatusCode::FORBIDDEN.into_response())
2034    } else {
2035        Some(StatusCode::NOT_FOUND.into_response())
2036    }
2037}
2038
2039#[derive(Debug, Clone, Deserialize)]
2040struct IncidentAttachmentRef {
2041    blob_id: String,
2042    filename: String,
2043    content_type: String,
2044    #[serde(default)]
2045    byte_size: Option<i64>,
2046    #[serde(default)]
2047    is_screenshot: bool,
2048}
2049
2050fn parse_incident_attachments(context_json: &str) -> Vec<IncidentAttachmentRef> {
2051    serde_json::from_str::<Value>(context_json)
2052        .ok()
2053        .and_then(|v| v.get("attachments").cloned())
2054        .and_then(|arr| serde_json::from_value::<Vec<IncidentAttachmentRef>>(arr).ok())
2055        .unwrap_or_default()
2056}
2057
2058fn is_passive_image_content_type(content_type: &str) -> bool {
2059    let essence = content_type
2060        .split(';')
2061        .next()
2062        .unwrap_or("")
2063        .trim()
2064        .to_ascii_lowercase();
2065    matches!(
2066        essence.as_str(),
2067        "image/png" | "image/jpeg" | "image/webp" | "image/gif"
2068    )
2069}
2070
2071fn parse_recent_occurrences(raw_json: &str) -> Vec<RecentOccurrenceEntry> {
2072    serde_json::from_str::<Vec<RecentOccurrenceEntry>>(raw_json).unwrap_or_default()
2073}
2074
2075fn is_safe_http_url(raw: &str) -> bool {
2076    let trimmed = raw.trim();
2077    (trimmed.starts_with("https://") || trimmed.starts_with("http://"))
2078        && trimmed.len() > "http://".len()
2079        && !trimmed.chars().any(|c| c.is_whitespace() || c.is_control())
2080}
2081
2082fn decode_form_component(raw: &str) -> String {
2083    let bytes = raw.as_bytes();
2084    let mut out = Vec::with_capacity(bytes.len());
2085    let mut i = 0;
2086    while i < bytes.len() {
2087        match bytes[i] {
2088            b'+' => {
2089                out.push(b' ');
2090                i += 1;
2091            }
2092            b'%' if i + 2 < bytes.len() => {
2093                let hex_pair = &raw[i + 1..i + 3];
2094                if let Ok(byte) = u8::from_str_radix(hex_pair, 16) {
2095                    out.push(byte);
2096                    i += 3;
2097                } else {
2098                    out.push(b'%');
2099                    i += 1;
2100                }
2101            }
2102            other => {
2103                out.push(other);
2104                i += 1;
2105            }
2106        }
2107    }
2108    String::from_utf8_lossy(&out).into_owned()
2109}
2110
2111fn accepts_html(headers: &HeaderMap) -> bool {
2112    !slabs_html::htmx::wants_json(headers)
2113        && headers
2114            .get(header::ACCEPT)
2115            .and_then(|v| v.to_str().ok())
2116            .is_some_and(|v| v.contains("text/html"))
2117}
2118
2119fn redirect_to_incidents_ui() -> Response {
2120    let mut resp_headers = HeaderMap::new();
2121    resp_headers.insert(
2122        header::LOCATION,
2123        HeaderValue::from_static("/_slabs/incidents/ui"),
2124    );
2125    (StatusCode::SEE_OTHER, resp_headers).into_response()
2126}
2127
2128fn parse_claim_assignee(headers: &HeaderMap, body: &Bytes) -> SlabResult<String> {
2129    if body.iter().all(u8::is_ascii_whitespace) {
2130        return Err(SlabError::validation("assignee", "cannot be empty"));
2131    }
2132    let is_form = headers
2133        .get(header::CONTENT_TYPE)
2134        .and_then(|v| v.to_str().ok())
2135        .is_some_and(|v| {
2136            v.to_ascii_lowercase()
2137                .starts_with("application/x-www-form-urlencoded")
2138        });
2139    if is_form {
2140        let raw = std::str::from_utf8(body)
2141            .map_err(|_| SlabError::bad_request("invalid UTF-8 form body"))?;
2142        for pair in raw.split('&') {
2143            if let Some((k, v)) = pair.split_once('=') {
2144                if k == "assignee" {
2145                    let decoded = decode_form_component(v);
2146                    let trimmed = decoded.trim();
2147                    if !trimmed.is_empty() {
2148                        return Ok(trimmed.chars().take(128).collect());
2149                    }
2150                }
2151            }
2152        }
2153        return Err(SlabError::validation("assignee", "cannot be empty"));
2154    }
2155
2156    match serde_json::from_slice::<ClaimIncidentBody>(body) {
2157        Ok(parsed) => {
2158            let trimmed = parsed.assignee.trim();
2159            if trimmed.is_empty() {
2160                Err(SlabError::validation("assignee", "cannot be empty"))
2161            } else {
2162                Ok(trimmed.chars().take(128).collect())
2163            }
2164        }
2165        Err(err) => Err(SlabError::bad_request(format!("invalid JSON body: {err}"))),
2166    }
2167}
2168
2169fn parse_resolve_sha(headers: &HeaderMap, body: &Bytes) -> SlabResult<Option<String>> {
2170    if body.iter().all(u8::is_ascii_whitespace) {
2171        return Ok(None);
2172    }
2173    let is_form = headers
2174        .get(header::CONTENT_TYPE)
2175        .and_then(|v| v.to_str().ok())
2176        .is_some_and(|v| {
2177            v.to_ascii_lowercase()
2178                .starts_with("application/x-www-form-urlencoded")
2179        });
2180    if is_form {
2181        let raw = std::str::from_utf8(body)
2182            .map_err(|_| SlabError::bad_request("invalid UTF-8 form body"))?;
2183        for pair in raw.split('&') {
2184            if let Some((k, v)) = pair.split_once('=') {
2185                if k == "resolved_in_sha" {
2186                    let trimmed = v.trim();
2187                    if !trimmed.is_empty() {
2188                        return Ok(Some(trimmed.chars().take(128).collect()));
2189                    }
2190                }
2191            }
2192        }
2193        return Ok(None);
2194    }
2195
2196    match serde_json::from_slice::<ResolveIncidentBody>(body) {
2197        Ok(parsed) => Ok(parsed
2198            .resolved_in_sha
2199            .map(|s| s.trim().to_owned())
2200            .filter(|s| !s.is_empty())),
2201        Err(err) => Err(SlabError::bad_request(format!("invalid JSON body: {err}"))),
2202    }
2203}
2204
2205async fn list_incidents_handler(
2206    State(ctx): State<AppCtx>,
2207    headers: HeaderMap,
2208    jar: CookieJar,
2209    Query(query): Query<ListIncidentsQuery>,
2210) -> Response {
2211    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2212        return resp;
2213    }
2214
2215    let status = query.status.as_deref().unwrap_or("open");
2216    let limit = query.limit.unwrap_or(50);
2217    match ctx.incidents.list(Some(status), limit).await {
2218        Ok(rows) => {
2219            let enriched: Vec<Value> = rows.iter().map(enrich_incident_json).collect();
2220            (StatusCode::OK, Json(json!({ "incidents": enriched }))).into_response()
2221        }
2222        Err(err) => err.into_response(),
2223    }
2224}
2225
2226async fn get_incident_handler(
2227    State(ctx): State<AppCtx>,
2228    headers: HeaderMap,
2229    jar: CookieJar,
2230    Path(id): Path<String>,
2231) -> Response {
2232    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2233        return resp;
2234    }
2235
2236    match ctx.incidents.get(&id).await {
2237        Ok(Some(inc)) => (StatusCode::OK, Json(enrich_incident_json(&inc))).into_response(),
2238        Ok(None) => SlabError::not_found("incident not found").into_response(),
2239        Err(err) => err.into_response(),
2240    }
2241}
2242
2243async fn claim_incident_handler(
2244    State(ctx): State<AppCtx>,
2245    headers: HeaderMap,
2246    jar: CookieJar,
2247    Path(id): Path<String>,
2248    body: Bytes,
2249) -> Response {
2250    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2251        return resp;
2252    }
2253
2254    let assignee = match parse_claim_assignee(&headers, &body) {
2255        Ok(val) => val,
2256        Err(err) => return err.into_response(),
2257    };
2258
2259    match ctx.incidents.claim(&id, &assignee).await {
2260        Ok(true) => {
2261            if let Ok(Some(record)) = ctx.incidents.get(&id).await {
2262                spawn_incident_webhook(&ctx, "incident.assigned", &record);
2263            }
2264            if accepts_html(&headers) {
2265                return redirect_to_incidents_ui();
2266            }
2267            (
2268                StatusCode::OK,
2269                Json(json!({
2270                    "id": id,
2271                    "status": "in_progress",
2272                    "assignee": assignee,
2273                })),
2274            )
2275                .into_response()
2276        }
2277        Ok(false) => match ctx.incidents.get(&id).await {
2278            Ok(Some(_)) => {
2279                SlabError::conflict("incident is already claimed or not open").into_response()
2280            }
2281            Ok(None) => SlabError::not_found("incident not found").into_response(),
2282            Err(err) => err.into_response(),
2283        },
2284        Err(err) => err.into_response(),
2285    }
2286}
2287
2288async fn link_incident_handler(
2289    State(ctx): State<AppCtx>,
2290    headers: HeaderMap,
2291    jar: CookieJar,
2292    Path(id): Path<String>,
2293    body: Bytes,
2294) -> Response {
2295    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2296        return resp;
2297    }
2298
2299    let payload: LinkIncidentBody = match serde_json::from_slice(&body) {
2300        Ok(parsed) => parsed,
2301        Err(err) => {
2302            return SlabError::bad_request(format!("invalid JSON body: {err}")).into_response();
2303        }
2304    };
2305
2306    match ctx
2307        .incidents
2308        .link_external(
2309            &id,
2310            &payload.external_issue_key,
2311            &payload.external_issue_url,
2312        )
2313        .await
2314    {
2315        Ok(true) => (
2316            StatusCode::OK,
2317            Json(json!({
2318                "id": id,
2319                "external_issue_key": payload.external_issue_key.trim(),
2320                "external_issue_url": payload.external_issue_url.trim(),
2321            })),
2322        )
2323            .into_response(),
2324        Ok(false) => SlabError::not_found("incident not found").into_response(),
2325        Err(err) => err.into_response(),
2326    }
2327}
2328
2329async fn ignore_incident_handler(
2330    State(ctx): State<AppCtx>,
2331    headers: HeaderMap,
2332    jar: CookieJar,
2333    Path(id): Path<String>,
2334) -> Response {
2335    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2336        return resp;
2337    }
2338
2339    match ctx.incidents.ignore(&id).await {
2340        Ok(true) => {
2341            if accepts_html(&headers) {
2342                return redirect_to_incidents_ui();
2343            }
2344            (
2345                StatusCode::OK,
2346                Json(json!({
2347                    "id": id,
2348                    "status": "ignored",
2349                })),
2350            )
2351                .into_response()
2352        }
2353        Ok(false) => SlabError::not_found("incident not found").into_response(),
2354        Err(err) => err.into_response(),
2355    }
2356}
2357
2358async fn resolve_incident_handler(
2359    State(ctx): State<AppCtx>,
2360    headers: HeaderMap,
2361    jar: CookieJar,
2362    Path(id): Path<String>,
2363    body: Bytes,
2364) -> Response {
2365    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2366        return resp;
2367    }
2368
2369    let resolved_in_sha = match parse_resolve_sha(&headers, &body) {
2370        Ok(sha) => sha,
2371        Err(err) => return err.into_response(),
2372    };
2373
2374    match ctx.incidents.resolve(&id, resolved_in_sha.as_deref()).await {
2375        Ok(true) => {
2376            if let Ok(Some(record)) = ctx.incidents.get(&id).await {
2377                spawn_incident_webhook(&ctx, "incident.resolved", &record);
2378            }
2379            if accepts_html(&headers) {
2380                return redirect_to_incidents_ui();
2381            }
2382            (
2383                StatusCode::OK,
2384                Json(json!({
2385                    "id": id,
2386                    "status": "resolved",
2387                    "resolved_in_sha": resolved_in_sha,
2388                })),
2389            )
2390                .into_response()
2391        }
2392        Ok(false) => SlabError::not_found("incident not found").into_response(),
2393        Err(err) => err.into_response(),
2394    }
2395}
2396
2397async fn incidents_ui_handler(
2398    State(ctx): State<AppCtx>,
2399    headers: HeaderMap,
2400    jar: CookieJar,
2401    Query(query): Query<ListIncidentsQuery>,
2402) -> Response {
2403    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2404        return resp;
2405    }
2406
2407    let active_status = match query.status.as_deref().map(str::trim) {
2408        Some("in_progress") => "in_progress",
2409        Some("resolved") => "resolved",
2410        Some("ignored") => "ignored",
2411        Some("all") => "all",
2412        _ => "open",
2413    };
2414    let limit = query.limit.unwrap_or(100);
2415    let incidents = match ctx.incidents.list(Some(active_status), limit).await {
2416        Ok(rows) => rows,
2417        Err(err) => return err.into_response(),
2418    };
2419    let open_count = ctx.incidents.count_open().await.unwrap_or(0);
2420
2421    let body = slabs_html::html! {
2422        main class="mx-auto max-w-5xl p-6 grid gap-6" {
2423            header class="flex flex-wrap items-center justify-between gap-4 border-b pb-4" {
2424                div {
2425                    h1 class="text-2xl font-bold" { "Incidents — " (ctx.config.app_name) }
2426                    p class="text-sm text-muted-foreground" {
2427                        "Environment: " (ctx.config.env.as_str()) " · Open incidents: " (open_count)
2428                    }
2429                }
2430                nav aria-label="Incident status filter" class="flex flex-wrap items-center gap-2" {
2431                    a
2432                        href="/_slabs/incidents/ui?status=open"
2433                        class=(if active_status == "open" { "btn" } else { "btn-outline" })
2434                    {
2435                        "Open (" (open_count) ")"
2436                    }
2437                    a
2438                        href="/_slabs/incidents/ui?status=in_progress"
2439                        class=(if active_status == "in_progress" { "btn" } else { "btn-outline" })
2440                    {
2441                        "In Progress"
2442                    }
2443                    a
2444                        href="/_slabs/incidents/ui?status=resolved"
2445                        class=(if active_status == "resolved" { "btn" } else { "btn-outline" })
2446                    {
2447                        "Resolved"
2448                    }
2449                    a
2450                        href="/_slabs/incidents/ui?status=ignored"
2451                        class=(if active_status == "ignored" { "btn" } else { "btn-outline" })
2452                    {
2453                        "Ignored"
2454                    }
2455                    a
2456                        href="/_slabs/incidents/ui?status=all"
2457                        class=(if active_status == "all" { "btn" } else { "btn-outline" })
2458                    {
2459                        "All"
2460                    }
2461                }
2462            }
2463
2464            @if incidents.is_empty() {
2465                section class="card p-8 text-center text-muted-foreground" {
2466                    p { "No " (active_status) " incidents recorded." }
2467                }
2468            } @else {
2469                div class="grid gap-4" {
2470                    @for inc in &incidents {
2471                        @let attachments = parse_incident_attachments(&inc.context_json);
2472                        @let recent_occurrences = parse_recent_occurrences(&inc.recent_occurrences_json);
2473                        @let hint = repro_hint_for(inc);
2474                        @let pretty_ctx = serde_json::from_str::<Value>(&inc.context_json)
2475                            .ok()
2476                            .and_then(|v| serde_json::to_string_pretty(&v).ok())
2477                            .unwrap_or_else(|| inc.context_json.clone());
2478                        article class="card p-5 grid gap-3" data-incident-id=(inc.id) data-incident-kind=(inc.kind) {
2479                            div class="flex flex-wrap items-start justify-between gap-3" {
2480                                div class="flex flex-wrap items-center gap-2" {
2481                                    span class="badge" { (inc.kind) }
2482                                    span class="badge-outline" { (inc.status) }
2483                                    span class="badge-secondary" { "×" (inc.occurrences) }
2484                                    @if let Some(code) = inc.status_code {
2485                                        span class="badge-outline" { "HTTP " (code) }
2486                                    }
2487                                    @if let Some(ref assignee) = inc.assignee {
2488                                        span class="badge-secondary" { "Assignee: " (assignee) }
2489                                    }
2490                                    @if let (Some(ref ext_key), Some(ref ext_url)) = (&inc.external_issue_key, &inc.external_issue_url) {
2491                                        @if is_safe_http_url(ext_url) {
2492                                            a
2493                                                href=(ext_url)
2494                                                target="_blank"
2495                                                rel="noopener noreferrer"
2496                                                class="badge-outline underline"
2497                                            {
2498                                                (ext_key)
2499                                            }
2500                                        }
2501                                    }
2502                                    code class="text-xs text-muted-foreground" { (inc.id) }
2503                                }
2504                                div class="flex flex-wrap items-center gap-2" {
2505                                    @if inc.status == "open" {
2506                                        form
2507                                            method="post"
2508                                            action=(format!("/_slabs/incidents/{}/claim", inc.id))
2509                                            class="flex items-center gap-1"
2510                                        {
2511                                            input
2512                                                type="text"
2513                                                name="assignee"
2514                                                placeholder="Assignee"
2515                                                required
2516                                                class="input w-32 text-xs"
2517                                            ;
2518                                            button type="submit" class="btn-outline" { "Claim" }
2519                                        }
2520                                    }
2521                                    @if inc.status == "open" || inc.status == "in_progress" {
2522                                        form method="post" action=(format!("/_slabs/incidents/{}/ignore", inc.id)) {
2523                                            button type="submit" class="btn-outline" { "Ignore" }
2524                                        }
2525                                        form method="post" action=(format!("/_slabs/incidents/{}/resolve", inc.id)) {
2526                                            button type="submit" class="btn-outline" { "Resolve" }
2527                                        }
2528                                    }
2529                                }
2530                            }
2531
2532                            div class="grid gap-1" {
2533                                h2 class="text-base font-semibold break-words" { (inc.error_message) }
2534                                p class="text-sm text-muted-foreground" {
2535                                    "Source: " code { (inc.source_file) }
2536                                    @if let Some(ref route) = inc.route_pattern {
2537                                        " · Route: " code { (route) }
2538                                    }
2539                                    @if let Some(ref sha) = inc.git_sha {
2540                                        " · Git: " code { (sha) }
2541                                    }
2542                                }
2543                                p class="text-xs text-muted-foreground" {
2544                                    "First seen: " (inc.first_seen_at) " · Last seen: " (inc.last_seen_at)
2545                                    @if let Some(ref rsha) = inc.resolved_in_sha {
2546                                        " · Resolved in: " code { (rsha) }
2547                                    }
2548                                }
2549                            }
2550
2551                            @if let Some(ref detail) = inc.detail {
2552                                @if detail != &inc.error_message {
2553                                    pre class="rounded bg-muted p-3 text-xs overflow-x-auto whitespace-pre-wrap" { (detail) }
2554                                }
2555                            }
2556
2557                            @if !recent_occurrences.is_empty() {
2558                                section class="grid gap-1.5 border-t pt-3" {
2559                                    h3 class="text-xs font-medium text-muted-foreground" {
2560                                        "Recent occurrences (" (recent_occurrences.len()) ")"
2561                                    }
2562                                    ul class="grid gap-1 text-xs font-mono text-muted-foreground" {
2563                                        @for occ in recent_occurrences.iter().rev() {
2564                                            li {
2565                                                @if let Some(ref ts) = occ.seen_at {
2566                                                    (ts)
2567                                                }
2568                                                @if let Some(ref sha) = occ.git_sha {
2569                                                    " · sha=" code { (sha) }
2570                                                }
2571                                                @if let Some(ref req_id) = occ.request_id {
2572                                                    " · req=" code { (req_id) }
2573                                                }
2574                                                @if let Some(ms) = occ.latency_ms {
2575                                                    " · " (ms) "ms"
2576                                                }
2577                                            }
2578                                        }
2579                                    }
2580                                }
2581                            }
2582
2583                            @if !attachments.is_empty() {
2584                                section class="grid gap-3 border-t pt-3" {
2585                                    h3 class="text-sm font-medium" { "Attachments (" (attachments.len()) ")" }
2586                                    div class="flex flex-wrap gap-4" {
2587                                        @for att in &attachments {
2588                                            @let href = format!("/_slabs/incidents/{}/attachments/{}", inc.id, att.blob_id);
2589                                            div class="grid gap-1.5" {
2590                                                @if att.is_screenshot || is_passive_image_content_type(&att.content_type) {
2591                                                    a href=(href) target="_blank" rel="noopener noreferrer" {
2592                                                        img
2593                                                            src=(href)
2594                                                            alt=(att.filename)
2595                                                            loading="lazy"
2596                                                            class="max-h-64 max-w-md rounded border object-contain"
2597                                                        ;
2598                                                    }
2599                                                }
2600                                                a
2601                                                    href=(href)
2602                                                    class="text-sm underline"
2603                                                {
2604                                                    (att.filename) " (" (att.content_type) ")"
2605                                                    @if let Some(sz) = att.byte_size {
2606                                                        " · " (sz) " B"
2607                                                    }
2608                                                }
2609                                            }
2610                                        }
2611                                    }
2612                                }
2613                            }
2614
2615                            details class="text-xs" {
2616                                summary class="cursor-pointer text-muted-foreground" { "Diagnostic context & repro hint" }
2617                                p class="mt-2 font-mono" { (hint) }
2618                                pre class="mt-2 rounded bg-muted p-3 overflow-x-auto" { (pretty_ctx) }
2619                            }
2620                        }
2621                    }
2622                }
2623            }
2624        }
2625    };
2626
2627    slabs_html::document("Slabs Incidents", &[], &[], body).into_response()
2628}
2629
2630async fn incident_attachment_handler(
2631    State(ctx): State<AppCtx>,
2632    headers: HeaderMap,
2633    jar: CookieJar,
2634    Path((id, blob_id)): Path<(String, String)>,
2635) -> Response {
2636    if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
2637        return resp;
2638    }
2639
2640    let incident = match ctx.incidents.get(&id).await {
2641        Ok(Some(inc)) => inc,
2642        Ok(None) => return SlabError::not_found("incident not found").into_response(),
2643        Err(err) => return err.into_response(),
2644    };
2645
2646    let attachments = parse_incident_attachments(&incident.context_json);
2647    if !attachments.iter().any(|att| att.blob_id == blob_id) {
2648        return SlabError::not_found("attachment not found for incident").into_response();
2649    }
2650
2651    match ctx.storage.get_scoped(&blob_id, Some("bug_report")).await {
2652        Ok(Some((meta, bytes))) => meta.into_safe_response(bytes, true),
2653        Ok(None) => SlabError::not_found("attachment not found for incident").into_response(),
2654        Err(err) => err.into_response(),
2655    }
2656}
2657
2658fn sanitize_client_path(raw: Option<&str>) -> Option<String> {
2659    let trimmed = raw?.trim();
2660    if trimmed.is_empty() {
2661        return None;
2662    }
2663    let path_only = if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
2664        trimmed
2665            .parse::<Uri>()
2666            .ok()
2667            .map_or_else(|| "/".to_owned(), |u| u.path().to_owned())
2668    } else {
2669        trimmed.split(['?', '#']).next().unwrap_or("/").to_owned()
2670    };
2671    let clean = path_only.trim();
2672    if clean.is_empty() {
2673        None
2674    } else {
2675        Some(clean.chars().take(256).collect())
2676    }
2677}
2678
2679async fn client_errors_handler(
2680    State(ctx): State<AppCtx>,
2681    headers: HeaderMap,
2682    extensions: http::Extensions,
2683    body: Bytes,
2684) -> Response {
2685    let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|c| c.0);
2686    let ip = client_ip(&headers, peer, ctx.config.trust_proxy);
2687    if let Err(err) = ctx
2688        .rate_limit
2689        .check(&format!("slabs_client_errors:{ip}"), 20, 60)
2690    {
2691        return err.into_response();
2692    }
2693
2694    if body.len() > MAX_CLIENT_ERROR_BYTES {
2695        return (
2696            StatusCode::PAYLOAD_TOO_LARGE,
2697            Json(json!({
2698                "error": "payload_too_large",
2699                "message": "client error payload exceeds 4096 bytes",
2700            })),
2701        )
2702            .into_response();
2703    }
2704
2705    let payload: ClientErrorPayload = match serde_json::from_slice(&body) {
2706        Ok(parsed) => parsed,
2707        Err(err) => {
2708            return SlabError::bad_request(format!("invalid client error JSON: {err}"))
2709                .into_response();
2710        }
2711    };
2712
2713    let message = payload.message.trim();
2714    if message.is_empty() {
2715        return SlabError::validation("message", "cannot be empty").into_response();
2716    }
2717
2718    let route_pattern = sanitize_client_path(payload.path.as_deref());
2719    let client_kind = payload
2720        .kind
2721        .as_deref()
2722        .map(str::trim)
2723        .filter(|s| !s.is_empty())
2724        .unwrap_or("error")
2725        .chars()
2726        .take(64)
2727        .collect::<String>();
2728
2729    let input = IncidentInput {
2730        kind: "client_error".into(),
2731        source_file: "browser".into(),
2732        route_pattern,
2733        status_code: None,
2734        error_message: message.to_owned(),
2735        detail: payload.detail,
2736        context_json: json!({
2737            "client_kind": client_kind,
2738            "env": ctx.config.env.as_str(),
2739            "git_sha": ctx.config.git_sha,
2740        }),
2741        git_sha: ctx.config.git_sha.clone(),
2742        custom_fingerprint: None,
2743    };
2744
2745    match record_and_notify_incident(&ctx, input).await {
2746        Some(record) => (
2747            StatusCode::ACCEPTED,
2748            Json(json!({
2749                "id": record.id,
2750                "status": record.status,
2751            })),
2752        )
2753            .into_response(),
2754        None => SlabError::internal("failed to record client error").into_response(),
2755    }
2756}
2757
2758struct PendingBugFile {
2759    filename: String,
2760    content_type: Option<String>,
2761    bytes: Bytes,
2762    is_screenshot: bool,
2763}
2764
2765fn sanitize_source_file(raw: &str) -> String {
2766    let cleaned: String = raw
2767        .trim()
2768        .chars()
2769        .filter(|&c| !c.is_ascii_control() && c != '\\')
2770        .take(MAX_BUG_SOURCE_FILE_CHARS)
2771        .collect();
2772    let trimmed = cleaned.trim();
2773    if trimmed.is_empty() || trimmed.contains("..") {
2774        "browser".to_owned()
2775    } else {
2776        trimmed.to_owned()
2777    }
2778}
2779
2780fn resolve_screenshot_content_type(
2781    content_type: Option<&str>,
2782    filename: &str,
2783) -> SlabResult<&'static str> {
2784    let ct = content_type
2785        .and_then(|v| v.split(';').next())
2786        .map(|s| s.trim().to_ascii_lowercase())
2787        .filter(|s| !s.is_empty());
2788    match ct.as_deref() {
2789        Some("image/png") => return Ok("image/png"),
2790        Some("image/jpeg" | "image/jpg") => return Ok("image/jpeg"),
2791        Some("image/webp") => return Ok("image/webp"),
2792        Some(_) => {
2793            return Err(SlabError::bad_request(
2794                "screenshot must be image/png, image/jpeg, or image/webp",
2795            ));
2796        }
2797        None => {}
2798    }
2799
2800    let ext = std::path::Path::new(filename)
2801        .extension()
2802        .and_then(|e| e.to_str());
2803    if ext.is_some_and(|e| e.eq_ignore_ascii_case("png")) {
2804        Ok("image/png")
2805    } else if ext.is_some_and(|e| e.eq_ignore_ascii_case("jpg") || e.eq_ignore_ascii_case("jpeg")) {
2806        Ok("image/jpeg")
2807    } else if ext.is_some_and(|e| e.eq_ignore_ascii_case("webp")) {
2808        Ok("image/webp")
2809    } else {
2810        Err(SlabError::bad_request(
2811            "screenshot must be image/png, image/jpeg, or image/webp",
2812        ))
2813    }
2814}
2815
2816async fn read_multipart_bytes(
2817    field: &mut axum::extract::multipart::Field<'_>,
2818    max_bytes: usize,
2819    label: &str,
2820) -> SlabResult<Bytes> {
2821    let mut buf = Vec::new();
2822    while let Some(chunk) = field.chunk().await.map_err(|e| {
2823        SlabError::bad_request(format!("failed to read multipart field `{label}`: {e}"))
2824    })? {
2825        if buf.len().saturating_add(chunk.len()) > max_bytes {
2826            return Err(SlabError::bad_request(format!(
2827                "{label} exceeds maximum allowed {max_bytes} bytes"
2828            )));
2829        }
2830        buf.extend_from_slice(&chunk);
2831    }
2832    Ok(Bytes::from(buf))
2833}
2834
2835fn redact_bug_metadata(value: Value) -> (Value, Option<String>) {
2836    let Value::Object(mut map) = value else {
2837        return (json!({}), None);
2838    };
2839    for sensitive in [
2840        "cookies",
2841        "cookie",
2842        "authorization",
2843        "token",
2844        "secret",
2845        "href",
2846        "query",
2847    ] {
2848        map.remove(sensitive);
2849    }
2850    let route_pattern = map
2851        .get("url_path")
2852        .and_then(Value::as_str)
2853        .and_then(|raw| sanitize_client_path(Some(raw)));
2854    if let Some(ref clean_path) = route_pattern {
2855        map.insert("url_path".into(), Value::String(clean_path.clone()));
2856    } else {
2857        map.remove("url_path");
2858    }
2859    if let Some(Value::Array(errors)) = map.get_mut("recent_errors") {
2860        if errors.len() > 10 {
2861            let drain_count = errors.len() - 10;
2862            errors.drain(..drain_count);
2863        }
2864    }
2865    (Value::Object(map), route_pattern)
2866}
2867
2868async fn bug_reports_handler(
2869    State(ctx): State<AppCtx>,
2870    headers: HeaderMap,
2871    jar: CookieJar,
2872    extensions: http::Extensions,
2873    mut multipart: Multipart,
2874) -> Response {
2875    if !ctx.config.bug_reporter_enabled {
2876        return SlabError::not_found("bug reporter is disabled").into_response();
2877    }
2878
2879    let session = match ctx.auth.optional_session(&jar).await {
2880        Ok(s) => s,
2881        Err(err) => return err.into_response(),
2882    };
2883    if session.is_none() && !ctx.config.bug_reporter_allow_anonymous {
2884        return SlabError::unauthorized("authentication required to submit bug reports")
2885            .into_response();
2886    }
2887
2888    let rate_key = if let Some(ref s) = session {
2889        format!("slabs_bug_reports:user:{}", s.user_id)
2890    } else {
2891        let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|c| c.0);
2892        let ip = client_ip(&headers, peer, ctx.config.trust_proxy);
2893        format!("slabs_bug_reports:ip:{ip}")
2894    };
2895    if let Err(err) = ctx.rate_limit.check(&rate_key, 10, 300) {
2896        return err.into_response();
2897    }
2898
2899    let max_screenshot_bytes = MAX_BUG_SCREENSHOT_BYTES.min(ctx.config.max_blob_bytes);
2900    let max_attachment_bytes = MAX_BUG_ATTACHMENT_BYTES.min(ctx.config.max_blob_bytes);
2901
2902    let mut description: Option<String> = None;
2903    let mut source_file: Option<String> = None;
2904    let mut metadata: Value = json!({});
2905    let mut route_pattern: Option<String> = None;
2906    let mut pending_screenshot: Option<PendingBugFile> = None;
2907    let mut pending_attachments: Vec<PendingBugFile> = Vec::new();
2908
2909    loop {
2910        let next_field = match multipart.next_field().await {
2911            Ok(Some(field)) => field,
2912            Ok(None) => break,
2913            Err(err) => {
2914                return SlabError::bad_request(format!("invalid multipart payload: {err}"))
2915                    .into_response();
2916            }
2917        };
2918        let mut field = next_field;
2919        let field_name = field.name().unwrap_or("").to_owned();
2920
2921        match field_name.as_str() {
2922            "description" => {
2923                let bytes = match read_multipart_bytes(&mut field, 32 * 1024, "description").await {
2924                    Ok(b) => b,
2925                    Err(err) => return err.into_response(),
2926                };
2927                let Ok(text) = String::from_utf8(bytes.to_vec()) else {
2928                    return SlabError::bad_request("description must be valid UTF-8")
2929                        .into_response();
2930                };
2931                description = Some(text);
2932            }
2933            "source_file" => {
2934                let bytes = match read_multipart_bytes(&mut field, 1024, "source_file").await {
2935                    Ok(b) => b,
2936                    Err(err) => return err.into_response(),
2937                };
2938                if let Ok(text) = String::from_utf8(bytes.to_vec()) {
2939                    source_file = Some(sanitize_source_file(&text));
2940                }
2941            }
2942            "metadata_json" => {
2943                let bytes =
2944                    match read_multipart_bytes(&mut field, MAX_BUG_METADATA_BYTES, "metadata_json")
2945                        .await
2946                    {
2947                        Ok(b) => b,
2948                        Err(err) => return err.into_response(),
2949                    };
2950                if !bytes.iter().all(u8::is_ascii_whitespace) {
2951                    let parsed: Value = match serde_json::from_slice(&bytes) {
2952                        Ok(v) => v,
2953                        Err(err) => {
2954                            return SlabError::bad_request(format!("invalid metadata_json: {err}"))
2955                                .into_response();
2956                        }
2957                    };
2958                    let (redacted, path) = redact_bug_metadata(parsed);
2959                    metadata = redacted;
2960                    route_pattern = path;
2961                }
2962            }
2963            "screenshot" => {
2964                let filename = field
2965                    .file_name()
2966                    .filter(|s| !s.trim().is_empty())
2967                    .unwrap_or("screenshot.png")
2968                    .to_owned();
2969                let content_type = field.content_type().map(ToOwned::to_owned);
2970                let bytes = match read_multipart_bytes(
2971                    &mut field,
2972                    max_screenshot_bytes,
2973                    "screenshot",
2974                )
2975                .await
2976                {
2977                    Ok(b) => b,
2978                    Err(err) => return err.into_response(),
2979                };
2980                if bytes.is_empty() {
2981                    continue;
2982                }
2983                let validated_ct =
2984                    match resolve_screenshot_content_type(content_type.as_deref(), &filename) {
2985                        Ok(ct) => ct,
2986                        Err(err) => return err.into_response(),
2987                    };
2988                pending_screenshot = Some(PendingBugFile {
2989                    filename,
2990                    content_type: Some(validated_ct.to_owned()),
2991                    bytes,
2992                    is_screenshot: true,
2993                });
2994            }
2995            "attachments" => {
2996                let filename = field
2997                    .file_name()
2998                    .filter(|s| !s.trim().is_empty())
2999                    .unwrap_or("attachment.bin")
3000                    .to_owned();
3001                let content_type = field.content_type().map(ToOwned::to_owned);
3002                let bytes =
3003                    match read_multipart_bytes(&mut field, max_attachment_bytes, "attachments")
3004                        .await
3005                    {
3006                        Ok(b) => b,
3007                        Err(err) => return err.into_response(),
3008                    };
3009                if bytes.is_empty() {
3010                    continue;
3011                }
3012                if pending_attachments.len() >= MAX_BUG_ATTACHMENTS {
3013                    return SlabError::bad_request("at most 3 attachments are allowed")
3014                        .into_response();
3015                }
3016                pending_attachments.push(PendingBugFile {
3017                    filename,
3018                    content_type,
3019                    bytes,
3020                    is_screenshot: false,
3021                });
3022            }
3023            _ => {}
3024        }
3025    }
3026
3027    let trimmed_desc = description.as_deref().map_or("", str::trim);
3028    let desc_chars = trimmed_desc.chars().count();
3029    if desc_chars < MIN_BUG_DESCRIPTION_CHARS {
3030        return SlabError::validation(
3031            "description",
3032            format!("must be at least {MIN_BUG_DESCRIPTION_CHARS} characters"),
3033        )
3034        .into_response();
3035    }
3036    if desc_chars > MAX_BUG_DESCRIPTION_CHARS {
3037        return SlabError::validation(
3038            "description",
3039            format!("must be at most {MAX_BUG_DESCRIPTION_CHARS} characters"),
3040        )
3041        .into_response();
3042    }
3043
3044    let mut stored_attachments: Vec<Value> = Vec::new();
3045    let files_to_store = pending_screenshot.into_iter().chain(pending_attachments);
3046    for file in files_to_store {
3047        let meta = match ctx
3048            .storage
3049            .put_scoped(
3050                "bug_report",
3051                &file.filename,
3052                file.content_type.as_deref(),
3053                &file.bytes,
3054            )
3055            .await
3056        {
3057            Ok(m) => m,
3058            Err(err) => return err.into_response(),
3059        };
3060        stored_attachments.push(json!({
3061            "blob_id": meta.id,
3062            "filename": meta.filename,
3063            "content_type": meta.content_type,
3064            "byte_size": meta.byte_size,
3065            "is_screenshot": file.is_screenshot,
3066        }));
3067    }
3068
3069    let input = IncidentInput {
3070        kind: "user_bug_report".into(),
3071        source_file: source_file.unwrap_or_else(|| "browser".to_owned()),
3072        route_pattern,
3073        status_code: None,
3074        error_message: trimmed_desc.to_owned(),
3075        detail: Some(trimmed_desc.to_owned()),
3076        context_json: json!({
3077            "reporter_user_id": session.as_ref().map(|s| s.user_id.as_str()),
3078            "reporter_role": session.as_ref().map(|s| s.role.as_str()),
3079            "attachments": stored_attachments,
3080            "client": metadata,
3081            "env": ctx.config.env.as_str(),
3082            "git_sha": ctx.config.git_sha,
3083        }),
3084        git_sha: ctx.config.git_sha.clone(),
3085        custom_fingerprint: Some(slabs_core::id::new("bug")),
3086    };
3087
3088    match record_and_notify_incident(&ctx, input).await {
3089        Some(record) => (
3090            StatusCode::CREATED,
3091            Json(json!({
3092                "id": record.id,
3093                "status": "open",
3094                "attachments": stored_attachments,
3095            })),
3096        )
3097            .into_response(),
3098        None => SlabError::internal("failed to record bug report").into_response(),
3099    }
3100}
3101
3102async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
3103    let sent = ctx.mail.list_sent(50).await?;
3104    Ok(Json(json!({ "emails": sent })))
3105}
3106
3107fn compute_etag(body: &str) -> HeaderValue {
3108    let digest = Sha256::digest(body.as_bytes());
3109    let tag = format!("\"{}\"", &hex::encode(digest)[..16]);
3110    HeaderValue::from_str(&tag).unwrap_or_else(|_| HeaderValue::from_static("\"0\""))
3111}
3112
3113fn vendor_response(
3114    req_headers: &HeaderMap,
3115    content_type: &'static str,
3116    body: &'static str,
3117    etag_cell: &'static OnceLock<HeaderValue>,
3118) -> Response {
3119    let etag = etag_cell.get_or_init(|| compute_etag(body)).clone();
3120    if req_headers
3121        .get(header::IF_NONE_MATCH)
3122        .and_then(|v| v.to_str().ok())
3123        .is_some_and(|v| v.trim() == etag.to_str().unwrap_or_default())
3124    {
3125        return (
3126            StatusCode::NOT_MODIFIED,
3127            [
3128                (
3129                    header::CACHE_CONTROL,
3130                    HeaderValue::from_static("public, max-age=86400"),
3131                ),
3132                (header::ETAG, etag),
3133            ],
3134        )
3135            .into_response();
3136    }
3137
3138    (
3139        StatusCode::OK,
3140        [
3141            (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
3142            (
3143                header::CACHE_CONTROL,
3144                HeaderValue::from_static("public, max-age=86400"),
3145            ),
3146            (header::ETAG, etag),
3147        ],
3148        body,
3149    )
3150        .into_response()
3151}
3152
3153async fn vendor_basecoat_css(headers: HeaderMap) -> Response {
3154    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3155    vendor_response(&headers, "text/css; charset=utf-8", BASECOAT_CSS, &ETAG)
3156}
3157
3158async fn vendor_basecoat_js(headers: HeaderMap) -> Response {
3159    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3160    vendor_response(
3161        &headers,
3162        "text/javascript; charset=utf-8",
3163        include_str!("../assets/vendor/basecoat.min.js"),
3164        &ETAG,
3165    )
3166}
3167
3168async fn vendor_htmx_js(headers: HeaderMap) -> Response {
3169    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3170    vendor_response(
3171        &headers,
3172        "text/javascript; charset=utf-8",
3173        include_str!("../assets/vendor/htmx.min.js"),
3174        &ETAG,
3175    )
3176}
3177
3178async fn vendor_htmx_sse_js(headers: HeaderMap) -> Response {
3179    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3180    vendor_response(
3181        &headers,
3182        "text/javascript; charset=utf-8",
3183        include_str!("../assets/vendor/htmx-ext-sse.js"),
3184        &ETAG,
3185    )
3186}
3187
3188async fn vendor_idiomorph_js(headers: HeaderMap) -> Response {
3189    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3190    vendor_response(
3191        &headers,
3192        "text/javascript; charset=utf-8",
3193        include_str!("../assets/vendor/idiomorph-ext.min.js"),
3194        &ETAG,
3195    )
3196}
3197
3198async fn vendor_alpine_js(headers: HeaderMap) -> Response {
3199    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3200    vendor_response(
3201        &headers,
3202        "text/javascript; charset=utf-8",
3203        include_str!("../assets/vendor/alpine.min.js"),
3204        &ETAG,
3205    )
3206}
3207
3208async fn vendor_sw_register_js(headers: HeaderMap) -> Response {
3209    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3210    vendor_response(
3211        &headers,
3212        "text/javascript; charset=utf-8",
3213        slabs_html::SW_REGISTER_JS,
3214        &ETAG,
3215    )
3216}
3217
3218async fn vendor_slabs_telemetry_js(headers: HeaderMap) -> Response {
3219    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3220    vendor_response(
3221        &headers,
3222        "text/javascript; charset=utf-8",
3223        SLABS_TELEMETRY_JS,
3224        &ETAG,
3225    )
3226}
3227
3228async fn vendor_slabs_bug_report_js(headers: HeaderMap) -> Response {
3229    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
3230    vendor_response(
3231        &headers,
3232        "text/javascript; charset=utf-8",
3233        slabs_html::BUG_REPORT_JS,
3234        &ETAG,
3235    )
3236}
3237
3238fn is_active_document_content_type(content_type: &str) -> bool {
3239    let mime = content_type
3240        .split(';')
3241        .next()
3242        .unwrap_or("")
3243        .trim()
3244        .to_ascii_lowercase();
3245    matches!(
3246        mime.as_str(),
3247        "image/svg+xml" | "text/html" | "application/xhtml+xml"
3248    )
3249}
3250
3251async fn serve_asset_handler(
3252    State(ctx): State<AppCtx>,
3253    Path((hash, path)): Path<(String, String)>,
3254) -> SlabResult<Response> {
3255    let Some(entry) = ctx.assets.get(&hash, &path) else {
3256        return Err(SlabError::not_found("asset not found"));
3257    };
3258    let ct = HeaderValue::from_str(&entry.content_type)
3259        .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
3260    let mut headers = HeaderMap::new();
3261    headers.insert(header::CONTENT_TYPE, ct);
3262    headers.insert(
3263        header::CACHE_CONTROL,
3264        HeaderValue::from_static("public, max-age=31536000, immutable"),
3265    );
3266    if is_active_document_content_type(&entry.content_type) {
3267        headers.insert(
3268            header::CONTENT_SECURITY_POLICY,
3269            HeaderValue::from_static("default-src 'none'; style-src 'unsafe-inline'; sandbox"),
3270        );
3271    }
3272    Ok((StatusCode::OK, headers, entry.bytes.clone()).into_response())
3273}
3274
3275#[cfg(test)]
3276mod tests {
3277    use super::*;
3278    use axum::body::Body;
3279    use http_body_util::BodyExt;
3280    use slabs_core::AppEnv;
3281    use std::path::PathBuf;
3282    use tower::ServiceExt;
3283
3284    async fn test_ctx(mut config: AppConfig) -> AppCtx {
3285        config.database_url = "sqlite::memory:".into();
3286        let ctx = AppCtx::connect(config).await.unwrap();
3287        ctx.db.init_system_tables().await.unwrap();
3288        ctx
3289    }
3290
3291    async fn send(router: &Router, req: http::Request<Body>) -> (StatusCode, HeaderMap, String) {
3292        let resp = router.clone().oneshot(req).await.unwrap();
3293        let status = resp.status();
3294        let headers = resp.headers().clone();
3295        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
3296        (status, headers, String::from_utf8_lossy(&bytes).to_string())
3297    }
3298
3299    #[tokio::test]
3300    async fn dev_routes_are_disabled_in_production_and_enabled_in_test() {
3301        let mut prod_cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_prod"));
3302        prod_cfg.env = AppEnv::Production;
3303        let prod_ctx = test_ctx(prod_cfg).await;
3304        let prod_router = build_router(prod_ctx, vec![], &[]);
3305
3306        for path in [
3307            "/_slabs/mail",
3308            "/_slabs/manifest",
3309            "/_slabs/openapi.json",
3310            "/_slabs/metrics",
3311        ] {
3312            let req = http::Request::builder()
3313                .uri(path)
3314                .body(Body::empty())
3315                .unwrap();
3316            let (status, _, _) = send(&prod_router, req).await;
3317            assert_eq!(status, StatusCode::NOT_FOUND, "{path} must be 404 in prod");
3318        }
3319
3320        let dev_cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_dev"));
3321        let dev_ctx = test_ctx(dev_cfg).await;
3322        let dev_router = build_router(dev_ctx, vec![], &[]);
3323
3324        for path in [
3325            "/_slabs/mail",
3326            "/_slabs/manifest",
3327            "/_slabs/openapi.json",
3328            "/_slabs/metrics",
3329        ] {
3330            let req = http::Request::builder()
3331                .uri(path)
3332                .body(Body::empty())
3333                .unwrap();
3334            let (status, _, _) = send(&dev_router, req).await;
3335            assert_eq!(status, StatusCode::OK, "{path} must be 200 in test");
3336        }
3337    }
3338
3339    #[tokio::test]
3340    async fn health_probes_and_draining_behavior() {
3341        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_health"));
3342        let ctx = test_ctx(cfg).await;
3343        let router = build_router(ctx.clone(), vec![], &[]);
3344
3345        let (status, _, _) = send(
3346            &router,
3347            http::Request::builder()
3348                .uri("/health")
3349                .body(Body::empty())
3350                .unwrap(),
3351        )
3352        .await;
3353        assert_eq!(status, StatusCode::OK);
3354
3355        let (status, _, _) = send(
3356            &router,
3357            http::Request::builder()
3358                .uri("/health/live")
3359                .body(Body::empty())
3360                .unwrap(),
3361        )
3362        .await;
3363        assert_eq!(status, StatusCode::OK);
3364
3365        let (status, _, _) = send(
3366            &router,
3367            http::Request::builder()
3368                .uri("/health/ready")
3369                .body(Body::empty())
3370                .unwrap(),
3371        )
3372        .await;
3373        assert_eq!(status, StatusCode::OK);
3374
3375        ctx.set_draining();
3376        let (status, _, _) = send(
3377            &router,
3378            http::Request::builder()
3379                .uri("/health/ready")
3380                .body(Body::empty())
3381                .unwrap(),
3382        )
3383        .await;
3384        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
3385    }
3386
3387    #[tokio::test]
3388    async fn metrics_token_enforces_bearer_auth_and_supports_json_and_prometheus() {
3389        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_metrics"));
3390        cfg.env = AppEnv::Production;
3391        cfg.metrics_token = Some("super-secret-metrics-token".into());
3392        let ctx = test_ctx(cfg).await;
3393        let router = build_router(ctx, vec![], &[]);
3394
3395        // Missing token -> 401
3396        let (status, _, _) = send(
3397            &router,
3398            http::Request::builder()
3399                .uri("/_slabs/metrics")
3400                .body(Body::empty())
3401                .unwrap(),
3402        )
3403        .await;
3404        assert_eq!(status, StatusCode::UNAUTHORIZED);
3405
3406        // Wrong token -> 401
3407        let (status, _, _) = send(
3408            &router,
3409            http::Request::builder()
3410                .uri("/_slabs/metrics")
3411                .header(header::AUTHORIZATION, "Bearer wrong-token")
3412                .body(Body::empty())
3413                .unwrap(),
3414        )
3415        .await;
3416        assert_eq!(status, StatusCode::UNAUTHORIZED);
3417
3418        // Valid token -> Prometheus text
3419        let (status, _, body) = send(
3420            &router,
3421            http::Request::builder()
3422                .uri("/_slabs/metrics")
3423                .header(header::AUTHORIZATION, "Bearer super-secret-metrics-token")
3424                .body(Body::empty())
3425                .unwrap(),
3426        )
3427        .await;
3428        assert_eq!(status, StatusCode::OK);
3429        assert!(body.contains("slabs_http_requests_total"));
3430        assert!(body.contains("slabs_jobs_pending"));
3431        assert!(body.contains("slabs_realtime_active_topics"));
3432
3433        // Valid token + Accept: application/json -> JSON
3434        let (status, _, body) = send(
3435            &router,
3436            http::Request::builder()
3437                .uri("/_slabs/metrics")
3438                .header(header::AUTHORIZATION, "Bearer super-secret-metrics-token")
3439                .header(header::ACCEPT, "application/json")
3440                .body(Body::empty())
3441                .unwrap(),
3442        )
3443        .await;
3444        assert_eq!(status, StatusCode::OK);
3445        let parsed: Value = serde_json::from_str(&body).unwrap();
3446        assert!(parsed["http"]["requests_total"].as_u64().unwrap() >= 3);
3447    }
3448
3449    #[tokio::test]
3450    async fn csrf_middleware_blocks_cross_site_cookie_mutations_and_exempts_bearer_and_skip_csrf() {
3451        async fn ok_handler() -> &'static str {
3452            "ok"
3453        }
3454
3455        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_csrf"));
3456        let ctx = test_ctx(cfg).await;
3457        let router = build_router(
3458            ctx,
3459            vec![
3460                SlabDef::post("/api/items", ok_handler),
3461                // Webhook management endpoint without .skip_csrf() MUST remain CSRF-protected.
3462                SlabDef::post("/api/webhooks", ok_handler),
3463                // Inbound webhook receiver explicitly opts out via .skip_csrf().
3464                SlabDef::post("/webhooks/{provider}", ok_handler).skip_csrf(),
3465            ],
3466            &[],
3467        );
3468
3469        // Cross-site Fetch Metadata with Cookie -> 403
3470        let (status, _, _) = send(
3471            &router,
3472            http::Request::builder()
3473                .method(Method::POST)
3474                .uri("/api/items")
3475                .header(header::COOKIE, "slabs_session=abc")
3476                .header("sec-fetch-site", "cross-site")
3477                .body(Body::empty())
3478                .unwrap(),
3479        )
3480        .await;
3481        assert_eq!(status, StatusCode::FORBIDDEN);
3482
3483        // Webhook management route without skip_csrf() -> 403 on cross-site cookie POST
3484        let (status, _, _) = send(
3485            &router,
3486            http::Request::builder()
3487                .method(Method::POST)
3488                .uri("/api/webhooks")
3489                .header(header::COOKIE, "slabs_session=abc")
3490                .header("sec-fetch-site", "cross-site")
3491                .body(Body::empty())
3492                .unwrap(),
3493        )
3494        .await;
3495        assert_eq!(status, StatusCode::FORBIDDEN);
3496
3497        // Cross-origin Origin header with Cookie -> 403
3498        let (status, _, _) = send(
3499            &router,
3500            http::Request::builder()
3501                .method(Method::POST)
3502                .uri("/api/items")
3503                .header(header::COOKIE, "slabs_session=abc")
3504                .header(header::HOST, "app.example.com")
3505                .header(header::ORIGIN, "https://evil.test")
3506                .body(Body::empty())
3507                .unwrap(),
3508        )
3509        .await;
3510        assert_eq!(status, StatusCode::FORBIDDEN);
3511
3512        // Same-origin Origin header with Cookie -> 200
3513        let (status, _, _) = send(
3514            &router,
3515            http::Request::builder()
3516                .method(Method::POST)
3517                .uri("/api/items")
3518                .header(header::COOKIE, "slabs_session=abc")
3519                .header(header::HOST, "app.example.com")
3520                .header(header::ORIGIN, "https://app.example.com")
3521                .header("sec-fetch-site", "same-origin")
3522                .body(Body::empty())
3523                .unwrap(),
3524        )
3525        .await;
3526        assert_eq!(status, StatusCode::OK);
3527
3528        // Bearer auth exempt -> 200
3529        let (status, _, _) = send(
3530            &router,
3531            http::Request::builder()
3532                .method(Method::POST)
3533                .uri("/api/items")
3534                .header(header::COOKIE, "slabs_session=abc")
3535                .header(header::AUTHORIZATION, "Bearer slb_123")
3536                .header("sec-fetch-site", "cross-site")
3537                .body(Body::empty())
3538                .unwrap(),
3539        )
3540        .await;
3541        assert_eq!(status, StatusCode::OK);
3542
3543        // Explicit .skip_csrf() parameterized webhook receiver exempt -> 200
3544        let (status, _, _) = send(
3545            &router,
3546            http::Request::builder()
3547                .method(Method::POST)
3548                .uri("/webhooks/stripe")
3549                .header(header::COOKIE, "slabs_session=abc")
3550                .header("sec-fetch-site", "cross-site")
3551                .body(Body::empty())
3552                .unwrap(),
3553        )
3554        .await;
3555        assert_eq!(status, StatusCode::OK);
3556
3557        // Built-in /_slabs/client-errors beacon remains exempt -> 202
3558        let (status, _, _) = send(
3559            &router,
3560            http::Request::builder()
3561                .method(Method::POST)
3562                .uri("/_slabs/client-errors")
3563                .header(header::COOKIE, "slabs_session=abc")
3564                .header("sec-fetch-site", "cross-site")
3565                .header(header::CONTENT_TYPE, "application/json")
3566                .body(Body::from(r#"{"message":"beacon error","path":"/app"}"#))
3567                .unwrap(),
3568        )
3569        .await;
3570        assert_eq!(status, StatusCode::ACCEPTED);
3571    }
3572
3573    #[tokio::test]
3574    async fn security_headers_cors_request_id_and_vendor_assets() {
3575        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_headers"));
3576        cfg.cookie_secure = true;
3577        let ctx = test_ctx(cfg).await;
3578        let router = build_router(ctx, vec![], &[]);
3579
3580        // Invalid X-Request-Id is replaced with a fresh req_ ULID
3581        let (status, headers, body) = send(
3582            &router,
3583            http::Request::builder()
3584                .uri("/_slabs/vendor/sw-register.js")
3585                .header("x-request-id", "bad id with spaces!")
3586                .body(Body::empty())
3587                .unwrap(),
3588        )
3589        .await;
3590        assert_eq!(status, StatusCode::OK);
3591        assert!(body.contains("navigator.serviceWorker.register(\"/sw.js\")"));
3592        assert!(headers.contains_key(header::ETAG));
3593        assert_eq!(
3594            headers
3595                .get(header::REFERRER_POLICY)
3596                .and_then(|v| v.to_str().ok()),
3597            Some("strict-origin-when-cross-origin")
3598        );
3599        assert_eq!(
3600            headers
3601                .get("permissions-policy")
3602                .and_then(|v| v.to_str().ok()),
3603            Some("camera=(), microphone=(), geolocation=()")
3604        );
3605        assert_eq!(
3606            headers
3607                .get(header::STRICT_TRANSPORT_SECURITY)
3608                .and_then(|v| v.to_str().ok()),
3609            Some("max-age=31536000; includeSubDomains")
3610        );
3611        // No permissive wildcard CORS when cors_origins is empty
3612        assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
3613        let req_id = headers
3614            .get("x-request-id")
3615            .and_then(|v| v.to_str().ok())
3616            .unwrap();
3617        assert!(req_id.starts_with("req_"));
3618
3619        // basecoat.min.css includes @view-transition rule and ETag
3620        let (status, headers, css) = send(
3621            &router,
3622            http::Request::builder()
3623                .uri("/_slabs/vendor/basecoat.min.css")
3624                .body(Body::empty())
3625                .unwrap(),
3626        )
3627        .await;
3628        assert_eq!(status, StatusCode::OK);
3629        assert!(css.starts_with("@view-transition { navigation: auto; }"));
3630        assert!(headers.contains_key(header::ETAG));
3631    }
3632
3633    #[tokio::test]
3634    async fn asset_handler_sandboxes_svg_and_html_with_csp() {
3635        let dir = std::env::temp_dir().join(format!("slabs_http_svg_{}", slabs_core::id::new("d")));
3636        std::fs::create_dir_all(&dir).unwrap();
3637        std::fs::write(dir.join("icon.svg"), "<svg></svg>").unwrap();
3638
3639        let mut cfg = AppConfig::for_test("demo", dir.clone());
3640        cfg.assets_dir = dir.clone();
3641        let ctx = test_ctx(cfg).await;
3642        let url = ctx.assets.url("icon.svg");
3643        let router = build_router(ctx, vec![], &[]);
3644
3645        let (status, headers, _) = send(
3646            &router,
3647            http::Request::builder()
3648                .uri(&url)
3649                .body(Body::empty())
3650                .unwrap(),
3651        )
3652        .await;
3653        assert_eq!(status, StatusCode::OK);
3654        assert_eq!(
3655            headers
3656                .get(header::CONTENT_SECURITY_POLICY)
3657                .and_then(|v| v.to_str().ok()),
3658            Some("default-src 'none'; style-src 'unsafe-inline'; sandbox")
3659        );
3660
3661        let _ = std::fs::remove_dir_all(&dir);
3662    }
3663
3664    #[test]
3665    fn client_ip_respects_trust_proxy_and_rightmost_xff() {
3666        let peer: SocketAddr = "10.0.0.5:12345".parse().unwrap();
3667        let mut headers = HeaderMap::new();
3668        headers.insert(
3669            "x-forwarded-for",
3670            HeaderValue::from_static("1.2.3.4, 203.0.113.9"),
3671        );
3672
3673        assert_eq!(client_ip(&headers, Some(peer), false), "10.0.0.5");
3674        assert_eq!(client_ip(&headers, Some(peer), true), "203.0.113.9");
3675
3676        headers.insert("cf-connecting-ip", HeaderValue::from_static("198.51.100.7"));
3677        assert_eq!(client_ip(&headers, Some(peer), true), "198.51.100.7");
3678    }
3679
3680    #[tokio::test]
3681    async fn client_ip_extractor_falls_back_in_tests_and_respects_trust_proxy() {
3682        async fn echo_ip(ClientIp(ip): ClientIp) -> String {
3683            ip
3684        }
3685
3686        // Without trust_proxy and without ConnectInfo -> falls back to 127.0.0.1
3687        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_client_ip"));
3688        let ctx = test_ctx(cfg).await;
3689        let router = build_router(ctx, vec![SlabDef::get("/ip", echo_ip)], &[]);
3690
3691        let (status, _, body) = send(
3692            &router,
3693            http::Request::builder()
3694                .uri("/ip")
3695                .header("cf-connecting-ip", "198.51.100.7")
3696                .body(Body::empty())
3697                .unwrap(),
3698        )
3699        .await;
3700        assert_eq!(status, StatusCode::OK);
3701        assert_eq!(body, "127.0.0.1");
3702
3703        // With ConnectInfo and trust_proxy = false -> uses socket peer address
3704        let mut req_with_peer = http::Request::builder()
3705            .uri("/ip")
3706            .header("x-forwarded-for", "203.0.113.9")
3707            .body(Body::empty())
3708            .unwrap();
3709        req_with_peer
3710            .extensions_mut()
3711            .insert(ConnectInfo::<SocketAddr>("10.0.0.5:4321".parse().unwrap()));
3712        let (status, _, body) = send(&router, req_with_peer).await;
3713        assert_eq!(status, StatusCode::OK);
3714        assert_eq!(body, "10.0.0.5");
3715
3716        // With trust_proxy = true -> honors CF-Connecting-IP / X-Forwarded-For
3717        let mut proxy_cfg =
3718            AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_client_ip_proxy"));
3719        proxy_cfg.trust_proxy = true;
3720        let proxy_ctx = test_ctx(proxy_cfg).await;
3721        let proxy_router = build_router(proxy_ctx, vec![SlabDef::get("/ip", echo_ip)], &[]);
3722
3723        let (status, _, body) = send(
3724            &proxy_router,
3725            http::Request::builder()
3726                .uri("/ip")
3727                .header("x-forwarded-for", "1.2.3.4, 203.0.113.9")
3728                .body(Body::empty())
3729                .unwrap(),
3730        )
3731        .await;
3732        assert_eq!(status, StatusCode::OK);
3733        assert_eq!(body, "203.0.113.9");
3734    }
3735
3736    #[test]
3737    fn rate_limiter_check_pair_enforces_both_ip_and_account_limits() {
3738        let rl = RateLimiter::new();
3739
3740        // Exhaust IP limit (2) across different accounts; third attempt fails on IP.
3741        rl.check_pair("ip:1.1.1.1", 2, "acct:a@example.com", 5, 60)
3742            .unwrap();
3743        rl.check_pair("ip:1.1.1.1", 2, "acct:b@example.com", 5, 60)
3744            .unwrap();
3745        let ip_err = rl
3746            .check_pair("ip:1.1.1.1", 2, "acct:c@example.com", 5, 60)
3747            .unwrap_err();
3748        assert_eq!(ip_err.status_code(), StatusCode::TOO_MANY_REQUESTS);
3749
3750        // Exhaust account limit (2) across different IPs; third attempt fails on account.
3751        rl.check_pair("ip:2.2.2.2", 5, "acct:victim@example.com", 2, 60)
3752            .unwrap();
3753        rl.check_pair("ip:3.3.3.3", 5, "acct:victim@example.com", 2, 60)
3754            .unwrap();
3755        let acct_err = rl
3756            .check_pair("ip:4.4.4.4", 5, "acct:victim@example.com", 2, 60)
3757            .unwrap_err();
3758        assert_eq!(acct_err.status_code(), StatusCode::TOO_MANY_REQUESTS);
3759
3760        // Blocked IP did not burn acct:c@example.com quota.
3761        rl.check_pair("ip:5.5.5.5", 5, "acct:c@example.com", 1, 60)
3762            .unwrap();
3763    }
3764
3765    #[tokio::test]
3766    async fn job_registry_dispatch_dead_letters_poison_pill_json() {
3767        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_poison"));
3768        let ctx = test_ctx(cfg).await;
3769        let job_id = ctx
3770            .jobs
3771            .enqueue("demo.job", json!({ "ok": true }))
3772            .await
3773            .unwrap();
3774        // Corrupt payload_json directly in SQLite to simulate a poison pill
3775        let mut tx = ctx.db.begin().await.unwrap();
3776        sqlx::query("UPDATE slabs_jobs SET payload_json = '{not-json' WHERE id = ?")
3777            .bind(&job_id)
3778            .execute(&mut *tx)
3779            .await
3780            .unwrap();
3781        tx.commit().await.unwrap();
3782
3783        let registry = JobRegistry::new(vec![JobDef::new("demo.job", |_ctx, _v| async { Ok(()) })]);
3784        let claimed = ctx.jobs.claim_next().await.unwrap().unwrap();
3785        assert!(registry.dispatch(&ctx, &claimed).await.is_err());
3786
3787        let stats = ctx.jobs.stats().await.unwrap();
3788        assert_eq!(stats.dead, 1);
3789        assert_eq!(stats.running, 0);
3790    }
3791
3792    #[tokio::test]
3793    async fn middleware_captures_panics_5xx_slow_requests_and_route_histograms() {
3794        async fn panic_handler() -> &'static str {
3795            panic!("boom in room handler")
3796        }
3797
3798        async fn err_5xx_handler() -> SlabResult<&'static str> {
3799            Err(SlabError::internal("db connection lost"))
3800        }
3801
3802        async fn slow_handler() -> &'static str {
3803            tokio::time::sleep(Duration::from_millis(25)).await;
3804            "slow ok"
3805        }
3806
3807        async fn fast_handler() -> &'static str {
3808            "fast ok"
3809        }
3810
3811        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_incidents"));
3812        cfg.slow_request_ms = 15;
3813        cfg.git_sha = Some("sha_abc123".into());
3814        let ctx = test_ctx(cfg).await;
3815
3816        let router = build_router(
3817            ctx.clone(),
3818            vec![
3819                SlabDef::get("/api/rooms/{room_id}/boom", panic_handler).name("rooms::boom"),
3820                SlabDef::get("/api/rooms/{room_id}/fail", err_5xx_handler).name("rooms::fail"),
3821                SlabDef::get("/api/rooms/{room_id}/slow", slow_handler).name("rooms::slow"),
3822                SlabDef::get("/api/rooms/{room_id}/fast", fast_handler).name("rooms::fast"),
3823            ],
3824            &[],
3825        );
3826
3827        // 1. Panic is caught and returns clean 500 JSON
3828        let (status, _, body) = send(
3829            &router,
3830            http::Request::builder()
3831                .uri("/api/rooms/room_42/boom")
3832                .body(Body::empty())
3833                .unwrap(),
3834        )
3835        .await;
3836        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
3837        let panic_body: Value = serde_json::from_str(&body).unwrap();
3838        assert_eq!(panic_body["error"], "internal server error");
3839
3840        // 2. 5xx error is recorded
3841        let (status, _, _) = send(
3842            &router,
3843            http::Request::builder()
3844                .uri("/api/rooms/room_42/fail")
3845                .body(Body::empty())
3846                .unwrap(),
3847        )
3848        .await;
3849        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
3850
3851        // 3. Slow request is recorded
3852        let (status, _, _) = send(
3853            &router,
3854            http::Request::builder()
3855                .uri("/api/rooms/room_42/slow")
3856                .body(Body::empty())
3857                .unwrap(),
3858        )
3859        .await;
3860        assert_eq!(status, StatusCode::OK);
3861
3862        // 4. Fast request does not create an incident
3863        let (status, _, _) = send(
3864            &router,
3865            http::Request::builder()
3866                .uri("/api/rooms/room_42/fast")
3867                .body(Body::empty())
3868                .unwrap(),
3869        )
3870        .await;
3871        assert_eq!(status, StatusCode::OK);
3872
3873        // Inspect via GET /_slabs/incidents
3874        let (status, _, body) = send(
3875            &router,
3876            http::Request::builder()
3877                .uri("/_slabs/incidents?status=open&limit=20")
3878                .body(Body::empty())
3879                .unwrap(),
3880        )
3881        .await;
3882        assert_eq!(status, StatusCode::OK);
3883        let parsed: Value = serde_json::from_str(&body).unwrap();
3884        let incidents = parsed["incidents"].as_array().unwrap();
3885        assert_eq!(incidents.len(), 3, "got incidents: {incidents:?}");
3886
3887        let panic_inc = incidents.iter().find(|i| i["kind"] == "panic").unwrap();
3888        assert_eq!(panic_inc["source_file"], "slabs/rooms/boom.rs");
3889        assert_eq!(panic_inc["route_pattern"], "/api/rooms/{room_id}/boom");
3890        assert_eq!(panic_inc["status_code"], 500);
3891        assert_eq!(panic_inc["git_sha"], "sha_abc123");
3892        assert!(panic_inc["repro_hint"]
3893            .as_str()
3894            .unwrap()
3895            .contains("slabs/rooms/boom.rs"));
3896
3897        let http_5xx_inc = incidents.iter().find(|i| i["kind"] == "http_5xx").unwrap();
3898        assert_eq!(http_5xx_inc["source_file"], "slabs/rooms/fail.rs");
3899        assert_eq!(http_5xx_inc["route_pattern"], "/api/rooms/{room_id}/fail");
3900
3901        let slow_inc = incidents
3902            .iter()
3903            .find(|i| i["kind"] == "slow_request")
3904            .unwrap();
3905        assert_eq!(slow_inc["source_file"], "slabs/rooms/slow.rs");
3906        assert_eq!(slow_inc["route_pattern"], "/api/rooms/{room_id}/slow");
3907
3908        // Fetch single incident by ID and resolve it
3909        let panic_id = panic_inc["id"].as_str().unwrap();
3910        let (status, _, body) = send(
3911            &router,
3912            http::Request::builder()
3913                .uri(format!("/_slabs/incidents/{panic_id}"))
3914                .body(Body::empty())
3915                .unwrap(),
3916        )
3917        .await;
3918        assert_eq!(status, StatusCode::OK);
3919        let single: Value = serde_json::from_str(&body).unwrap();
3920        assert_eq!(single["id"], panic_id);
3921        assert!(single["repro_hint"].as_str().is_some());
3922
3923        let (status, _, _) = send(
3924            &router,
3925            http::Request::builder()
3926                .method(Method::POST)
3927                .uri(format!("/_slabs/incidents/{panic_id}/resolve"))
3928                .header(header::CONTENT_TYPE, "application/json")
3929                .body(Body::from(r#"{"resolved_in_sha":"sha_fix_999"}"#))
3930                .unwrap(),
3931        )
3932        .await;
3933        assert_eq!(status, StatusCode::OK);
3934
3935        // Metrics JSON returns routes sorted by p95_ms DESC and open_incidents = 2
3936        let (status, _, body) = send(
3937            &router,
3938            http::Request::builder()
3939                .uri("/_slabs/metrics")
3940                .header(header::ACCEPT, "application/json")
3941                .body(Body::empty())
3942                .unwrap(),
3943        )
3944        .await;
3945        assert_eq!(status, StatusCode::OK);
3946        let metrics_json: Value = serde_json::from_str(&body).unwrap();
3947        assert_eq!(metrics_json["open_incidents"], 2);
3948        let route_metrics = metrics_json["routes"].as_array().unwrap();
3949        let slow_route = route_metrics
3950            .iter()
3951            .find(|r| r["route"] == "/api/rooms/{room_id}/slow")
3952            .unwrap();
3953        assert_eq!(slow_route["source_file"], "slabs/rooms/slow.rs");
3954        assert_eq!(slow_route["slow_requests"], 1);
3955        assert!(slow_route["p95_ms"].as_u64().unwrap() >= 15);
3956        assert!(slow_route["max_latency_ms"].as_u64().unwrap() >= 15);
3957
3958        // Metrics Prometheus text exposes per-route and incident gauges
3959        let (status, _, prom) = send(
3960            &router,
3961            http::Request::builder()
3962                .uri("/_slabs/metrics")
3963                .body(Body::empty())
3964                .unwrap(),
3965        )
3966        .await;
3967        assert_eq!(status, StatusCode::OK);
3968        assert!(prom.contains("slabs_incidents_open 2"));
3969        assert!(prom.contains("slabs_route_requests_total"));
3970        assert!(prom.contains("slabs_route_slow_total"));
3971        assert!(prom.contains("slabs_route_p95_ms"));
3972    }
3973
3974    #[tokio::test]
3975    async fn incidents_api_enforces_observability_auth_gate() {
3976        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_inc_auth"));
3977        cfg.env = AppEnv::Production;
3978        let ctx_no_tok = test_ctx(cfg.clone()).await;
3979        let router_no_tok = build_router(ctx_no_tok, vec![], &[]);
3980
3981        for path in ["/_slabs/incidents", "/_slabs/incidents/inc_1"] {
3982            let (status, _, _) = send(
3983                &router_no_tok,
3984                http::Request::builder()
3985                    .uri(path)
3986                    .body(Body::empty())
3987                    .unwrap(),
3988            )
3989            .await;
3990            assert_eq!(status, StatusCode::NOT_FOUND);
3991        }
3992
3993        cfg.metrics_token = Some("incident-secret-token".into());
3994        let ctx_tok = test_ctx(cfg).await;
3995        let router_tok = build_router(ctx_tok, vec![], &[]);
3996
3997        let (status, _, _) = send(
3998            &router_tok,
3999            http::Request::builder()
4000                .uri("/_slabs/incidents")
4001                .body(Body::empty())
4002                .unwrap(),
4003        )
4004        .await;
4005        assert_eq!(status, StatusCode::UNAUTHORIZED);
4006
4007        let (status, _, _) = send(
4008            &router_tok,
4009            http::Request::builder()
4010                .uri("/_slabs/incidents")
4011                .header(header::AUTHORIZATION, "Bearer incident-secret-token")
4012                .body(Body::empty())
4013                .unwrap(),
4014        )
4015        .await;
4016        assert_eq!(status, StatusCode::OK);
4017    }
4018
4019    #[tokio::test]
4020    async fn client_error_beacon_strips_query_enforces_cap_and_rate_limit_and_serves_vendor_js() {
4021        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_beacon"));
4022        let ctx = test_ctx(cfg).await;
4023        let router = build_router(ctx.clone(), vec![], &[]);
4024
4025        // Vendor telemetry script is served with ETag
4026        let (status, headers, js) = send(
4027            &router,
4028            http::Request::builder()
4029                .uri("/_slabs/vendor/slabs-telemetry.js")
4030                .body(Body::empty())
4031                .unwrap(),
4032        )
4033        .await;
4034        assert_eq!(status, StatusCode::OK);
4035        assert!(headers.contains_key(header::ETAG));
4036        assert!(js.contains("sendBeacon"));
4037        assert!(js.contains("/_slabs/client-errors"));
4038        assert!(js.contains("htmx:targetError"));
4039        assert!(js.contains("htmx:swapError"));
4040
4041        // Valid beacon strips query string PII
4042        let (status, _, body) = send(
4043            &router,
4044            http::Request::builder()
4045                .method(Method::POST)
4046                .uri("/_slabs/client-errors")
4047                .header(header::CONTENT_TYPE, "application/json")
4048                .body(Body::from(
4049                    r#"{"kind":"htmx:swapError","message":"Swap failed","path":"/rooms/123?token=secret_pii&email=a@b.com","detail":"target missing"}"#,
4050                ))
4051                .unwrap(),
4052        )
4053        .await;
4054        assert_eq!(status, StatusCode::ACCEPTED);
4055        let parsed: Value = serde_json::from_str(&body).unwrap();
4056        let inc_id = parsed["id"].as_str().unwrap();
4057
4058        let stored = ctx.incidents.get(inc_id).await.unwrap().unwrap();
4059        assert_eq!(stored.kind, "client_error");
4060        assert_eq!(stored.source_file, "browser");
4061        assert_eq!(stored.route_pattern.as_deref(), Some("/rooms/123"));
4062        assert!(!stored.context_json.contains("secret_pii"));
4063
4064        // Payload > 4 KiB is rejected
4065        let big_payload = format!(
4066            r#"{{"message":"{}"}}"#,
4067            "x".repeat(MAX_CLIENT_ERROR_BYTES + 10)
4068        );
4069        let (status, _, _) = send(
4070            &router,
4071            http::Request::builder()
4072                .method(Method::POST)
4073                .uri("/_slabs/client-errors")
4074                .body(Body::from(big_payload))
4075                .unwrap(),
4076        )
4077        .await;
4078        assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
4079
4080        // Rate limit kicks in after 20 requests within 60s (we already made 2 requests above)
4081        for _ in 0..18 {
4082            let (status, _, _) = send(
4083                &router,
4084                http::Request::builder()
4085                    .method(Method::POST)
4086                    .uri("/_slabs/client-errors")
4087                    .body(Body::from(
4088                        r#"{"message":"repeated error","path":"/rooms/1"}"#,
4089                    ))
4090                    .unwrap(),
4091            )
4092            .await;
4093            assert_eq!(status, StatusCode::ACCEPTED);
4094        }
4095        let (status, _, _) = send(
4096            &router,
4097            http::Request::builder()
4098                .method(Method::POST)
4099                .uri("/_slabs/client-errors")
4100                .body(Body::from(r#"{"message":"over limit","path":"/rooms/1"}"#))
4101                .unwrap(),
4102        )
4103        .await;
4104        assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
4105    }
4106
4107    type MultipartPart<'a> = (&'a str, Option<(&'a str, &'a str)>, &'a [u8]);
4108    type ReceivedWebhook = (String, Option<String>, Bytes);
4109
4110    fn build_multipart_body(boundary: &str, parts: &[MultipartPart<'_>]) -> Vec<u8> {
4111        let mut out = Vec::new();
4112        for (name, file_meta, data) in parts {
4113            out.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
4114            if let Some((filename, ct)) = file_meta {
4115                out.extend_from_slice(
4116                    format!(
4117                        "Content-Disposition: form-data; name=\"{name}\"; filename=\"{filename}\"\r\n\
4118                         Content-Type: {ct}\r\n\r\n"
4119                    )
4120                    .as_bytes(),
4121                );
4122            } else {
4123                out.extend_from_slice(
4124                    format!("Content-Disposition: form-data; name=\"{name}\"\r\n\r\n").as_bytes(),
4125                );
4126            }
4127            out.extend_from_slice(data);
4128            out.extend_from_slice(b"\r\n");
4129        }
4130        out.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
4131        out
4132    }
4133
4134    #[tokio::test]
4135    async fn bug_reports_endpoint_gates_auth_stores_attachments_and_serves_dashboard_safely() {
4136        let storage_dir = std::env::temp_dir().join(format!(
4137            "slabs_http_bug_reports_{}",
4138            slabs_core::id::new("d")
4139        ));
4140        let boundary = "----SlabsBugTestBoundary";
4141
4142        // 1. Disabled by default in test -> 404
4143        let disabled_cfg = AppConfig::for_test("demo", storage_dir.clone());
4144        assert!(!disabled_cfg.bug_reporter_enabled);
4145        let disabled_ctx = test_ctx(disabled_cfg).await;
4146        let disabled_router = build_router(disabled_ctx, vec![], &[]);
4147        let body_bytes = build_multipart_body(
4148            boundary,
4149            &[("description", None, b"Button broken on room page")],
4150        );
4151        let (status, _, _) = send(
4152            &disabled_router,
4153            http::Request::builder()
4154                .method(Method::POST)
4155                .uri("/_slabs/bug-reports")
4156                .header(
4157                    header::CONTENT_TYPE,
4158                    format!("multipart/form-data; boundary={boundary}"),
4159                )
4160                .body(Body::from(body_bytes.clone()))
4161                .unwrap(),
4162        )
4163        .await;
4164        assert_eq!(status, StatusCode::NOT_FOUND);
4165
4166        // 2. Enabled, anonymous disallowed -> 401 without session
4167        let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
4168        cfg.bug_reporter_enabled = true;
4169        cfg.bug_reporter_allow_anonymous = false;
4170        let ctx = test_ctx(cfg).await;
4171        let router = build_router(ctx.clone(), vec![], &[]);
4172
4173        // Vendor bug report JS is served with ETag
4174        let (status, headers, js) = send(
4175            &router,
4176            http::Request::builder()
4177                .uri("/_slabs/vendor/slabs-bug-report.js")
4178                .body(Body::empty())
4179                .unwrap(),
4180        )
4181        .await;
4182        assert_eq!(status, StatusCode::OK);
4183        assert!(headers.contains_key(header::ETAG));
4184        assert!(js.contains("/_slabs/bug-reports"));
4185
4186        let (status, _, _) = send(
4187            &router,
4188            http::Request::builder()
4189                .method(Method::POST)
4190                .uri("/_slabs/bug-reports")
4191                .header(
4192                    header::CONTENT_TYPE,
4193                    format!("multipart/form-data; boundary={boundary}"),
4194                )
4195                .body(Body::from(body_bytes))
4196                .unwrap(),
4197        )
4198        .await;
4199        assert_eq!(status, StatusCode::UNAUTHORIZED);
4200
4201        // 3. Authenticated user submits bug report with PNG screenshot + HTML attachment + metadata
4202        let (_session, cookie) = ctx
4203            .auth
4204            .create_session("usr_reporter_1", "member", 7)
4205            .await
4206            .unwrap();
4207        let session_cookie = format!("{}={}", cookie.name(), cookie.value());
4208
4209        let png_bytes: &[u8] = b"\x89PNG\r\n\x1a\nfake-png-payload";
4210        let html_bytes: &[u8] = b"<html><script>alert(1)</script></html>";
4211        let meta_json = br#"{"url_path":"/rooms/123?secret=dontstore","viewport":"1440x900","recent_errors":[]}"#;
4212
4213        let full_body = build_multipart_body(
4214            boundary,
4215            &[
4216                ("description", None, b"Submit button freezes after click"),
4217                ("source_file", None, b"slabs/rooms/show.rs"),
4218                ("metadata_json", None, meta_json),
4219                (
4220                    "screenshot",
4221                    Some(("screenshot.png", "image/png")),
4222                    png_bytes,
4223                ),
4224                ("attachments", Some(("repro.html", "text/html")), html_bytes),
4225            ],
4226        );
4227
4228        let (status, _, resp_body) = send(
4229            &router,
4230            http::Request::builder()
4231                .method(Method::POST)
4232                .uri("/_slabs/bug-reports")
4233                .header(header::COOKIE, &session_cookie)
4234                .header(
4235                    header::CONTENT_TYPE,
4236                    format!("multipart/form-data; boundary={boundary}"),
4237                )
4238                .body(Body::from(full_body.clone()))
4239                .unwrap(),
4240        )
4241        .await;
4242        assert_eq!(status, StatusCode::CREATED, "body: {resp_body}");
4243        let created: Value = serde_json::from_str(&resp_body).unwrap();
4244        let inc_id = created["id"].as_str().unwrap().to_owned();
4245        assert_eq!(created["status"], "open");
4246        let attachments = created["attachments"].as_array().unwrap();
4247        assert_eq!(attachments.len(), 2);
4248
4249        let screenshot_blob_id = attachments[0]["blob_id"].as_str().unwrap().to_owned();
4250        let html_blob_id = attachments[1]["blob_id"].as_str().unwrap().to_owned();
4251        assert_eq!(attachments[0]["is_screenshot"], true);
4252        assert_eq!(attachments[1]["is_screenshot"], false);
4253
4254        // Bug-report blobs are stored under the "bug_report" scope so unscoped app handlers cannot read them
4255        assert!(ctx
4256            .storage
4257            .get_scoped(&screenshot_blob_id, None)
4258            .await
4259            .unwrap()
4260            .is_none());
4261        assert!(ctx
4262            .storage
4263            .get_scoped(&html_blob_id, None)
4264            .await
4265            .unwrap()
4266            .is_none());
4267
4268        // Stored in slabs_incidents with server-derived reporter_user_id and stripped query string
4269        let stored = ctx.incidents.get(&inc_id).await.unwrap().unwrap();
4270        assert_eq!(stored.kind, "user_bug_report");
4271        assert_eq!(stored.source_file, "slabs/rooms/show.rs");
4272        assert_eq!(stored.route_pattern.as_deref(), Some("/rooms/123"));
4273        assert!(!stored.context_json.contains("dontstore"));
4274        assert!(stored.context_json.contains("usr_reporter_1"));
4275
4276        // Second submission creates a distinct bug report rather than deduplicating
4277        let (status, _, second_body) = send(
4278            &router,
4279            http::Request::builder()
4280                .method(Method::POST)
4281                .uri("/_slabs/bug-reports")
4282                .header(header::COOKIE, &session_cookie)
4283                .header(
4284                    header::CONTENT_TYPE,
4285                    format!("multipart/form-data; boundary={boundary}"),
4286                )
4287                .body(Body::from(full_body))
4288                .unwrap(),
4289        )
4290        .await;
4291        assert_eq!(status, StatusCode::CREATED);
4292        let second_created: Value = serde_json::from_str(&second_body).unwrap();
4293        assert_ne!(second_created["id"], inc_id);
4294
4295        // 4. Incidents UI renders open bug report, screenshot preview, attachment link, and Resolve button
4296        let (status, _, ui_html) = send(
4297            &router,
4298            http::Request::builder()
4299                .uri("/_slabs/incidents/ui")
4300                .body(Body::empty())
4301                .unwrap(),
4302        )
4303        .await;
4304        assert_eq!(status, StatusCode::OK);
4305        assert!(ui_html.contains("Submit button freezes after click"));
4306        assert!(ui_html.contains("slabs/rooms/show.rs"));
4307        assert!(ui_html.contains(&format!(
4308            "/_slabs/incidents/{inc_id}/attachments/{screenshot_blob_id}"
4309        )));
4310        assert!(ui_html.contains(&format!("/_slabs/incidents/{inc_id}/resolve")));
4311        assert!(!ui_html.contains("<script>"));
4312        assert!(!ui_html.contains("<style"));
4313
4314        // 5. Attachment endpoint serves PNG inline with sandbox CSP, forces HTML as attachment, and blocks IDOR
4315        let (status, headers, raw_png) = send(
4316            &router,
4317            http::Request::builder()
4318                .uri(format!(
4319                    "/_slabs/incidents/{inc_id}/attachments/{screenshot_blob_id}"
4320                ))
4321                .body(Body::empty())
4322                .unwrap(),
4323        )
4324        .await;
4325        assert_eq!(status, StatusCode::OK);
4326        assert_eq!(
4327            headers
4328                .get(header::CONTENT_TYPE)
4329                .and_then(|v| v.to_str().ok()),
4330            Some("image/png")
4331        );
4332        assert!(headers
4333            .get(header::CONTENT_DISPOSITION)
4334            .and_then(|v| v.to_str().ok())
4335            .unwrap()
4336            .starts_with("inline;"));
4337        assert_eq!(
4338            headers
4339                .get(header::CONTENT_SECURITY_POLICY)
4340                .and_then(|v| v.to_str().ok()),
4341            Some("default-src 'none'; sandbox")
4342        );
4343        assert!(raw_png.contains("fake-png-payload"));
4344
4345        let (status, headers, _) = send(
4346            &router,
4347            http::Request::builder()
4348                .uri(format!(
4349                    "/_slabs/incidents/{inc_id}/attachments/{html_blob_id}"
4350                ))
4351                .body(Body::empty())
4352                .unwrap(),
4353        )
4354        .await;
4355        assert_eq!(status, StatusCode::OK);
4356        assert!(headers
4357            .get(header::CONTENT_DISPOSITION)
4358            .and_then(|v| v.to_str().ok())
4359            .unwrap()
4360            .starts_with("attachment;"));
4361        assert_eq!(
4362            headers
4363                .get(header::CONTENT_SECURITY_POLICY)
4364                .and_then(|v| v.to_str().ok()),
4365            Some("default-src 'none'; sandbox")
4366        );
4367
4368        // Unrelated blob stored directly in ctx.storage cannot be fetched via incident attachment URL (IDOR blocked)
4369        let unrelated = ctx
4370            .storage
4371            .put(
4372                "secret.txt",
4373                Some("text/plain"),
4374                Bytes::from_static(b"top-secret"),
4375            )
4376            .await
4377            .unwrap();
4378        let (status, _, _) = send(
4379            &router,
4380            http::Request::builder()
4381                .uri(format!(
4382                    "/_slabs/incidents/{inc_id}/attachments/{}",
4383                    unrelated.id
4384                ))
4385                .body(Body::empty())
4386                .unwrap(),
4387        )
4388        .await;
4389        assert_eq!(status, StatusCode::NOT_FOUND);
4390
4391        // 6. HTML form resolve redirects cleanly back to /_slabs/incidents/ui
4392        let (status, headers, _) = send(
4393            &router,
4394            http::Request::builder()
4395                .method(Method::POST)
4396                .uri(format!("/_slabs/incidents/{inc_id}/resolve"))
4397                .header(header::ACCEPT, "text/html,application/xhtml+xml")
4398                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4399                .body(Body::empty())
4400                .unwrap(),
4401        )
4402        .await;
4403        assert_eq!(status, StatusCode::SEE_OTHER);
4404        assert_eq!(
4405            headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),
4406            Some("/_slabs/incidents/ui")
4407        );
4408
4409        let _ = std::fs::remove_dir_all(&storage_dir);
4410    }
4411
4412    #[tokio::test]
4413    async fn incidents_ui_enforces_prod_auth_and_allows_admin_session() {
4414        let storage_dir =
4415            std::env::temp_dir().join(format!("slabs_http_ui_auth_{}", slabs_core::id::new("d")));
4416        let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
4417        cfg.env = AppEnv::Production;
4418        let ctx = test_ctx(cfg).await;
4419        let router = build_router(ctx.clone(), vec![], &[]);
4420
4421        // Unauthenticated prod request -> 404 (no metrics_token, no session)
4422        let (status, _, _) = send(
4423            &router,
4424            http::Request::builder()
4425                .uri("/_slabs/incidents/ui")
4426                .body(Body::empty())
4427                .unwrap(),
4428        )
4429        .await;
4430        assert_eq!(status, StatusCode::NOT_FOUND);
4431
4432        // Regular member session -> 403 Forbidden
4433        let (_, member_c) = ctx
4434            .auth
4435            .create_session("usr_member", "member", 7)
4436            .await
4437            .unwrap();
4438        let member_cookie = format!("{}={}", member_c.name(), member_c.value());
4439        let (status, _, _) = send(
4440            &router,
4441            http::Request::builder()
4442                .uri("/_slabs/incidents/ui")
4443                .header(header::COOKIE, &member_cookie)
4444                .body(Body::empty())
4445                .unwrap(),
4446        )
4447        .await;
4448        assert_eq!(status, StatusCode::FORBIDDEN);
4449
4450        // Admin session -> 200 OK
4451        let (_, admin_c) = ctx
4452            .auth
4453            .create_session("usr_admin", "admin", 7)
4454            .await
4455            .unwrap();
4456        let admin_cookie = format!("{}={}", admin_c.name(), admin_c.value());
4457        let (status, _, html) = send(
4458            &router,
4459            http::Request::builder()
4460                .uri("/_slabs/incidents/ui")
4461                .header(header::COOKIE, &admin_cookie)
4462                .body(Body::empty())
4463                .unwrap(),
4464        )
4465        .await;
4466        assert_eq!(status, StatusCode::OK);
4467        assert!(html.contains("Incidents — demo"));
4468
4469        let _ = std::fs::remove_dir_all(&storage_dir);
4470    }
4471
4472    #[tokio::test]
4473    async fn signed_incident_protocol_webhooks_fire_on_opened_resolved_and_reopened() {
4474        let received: Arc<Mutex<Vec<ReceivedWebhook>>> = Arc::new(Mutex::new(Vec::new()));
4475        let recv_clone = received.clone();
4476
4477        let hook_app = Router::new().route(
4478            "/hook",
4479            post(move |headers: HeaderMap, body: Bytes| {
4480                let store = recv_clone.clone();
4481                async move {
4482                    let event = headers
4483                        .get("x-slabs-event")
4484                        .and_then(|v| v.to_str().ok())
4485                        .unwrap_or("")
4486                        .to_owned();
4487                    let sig = headers
4488                        .get("x-slabs-signature")
4489                        .and_then(|v| v.to_str().ok())
4490                        .map(ToOwned::to_owned);
4491                    store.lock().unwrap().push((event, sig, body));
4492                    StatusCode::OK
4493                }
4494            }),
4495        );
4496        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4497        let addr = listener.local_addr().unwrap();
4498        tokio::spawn(async move { axum::serve(listener, hook_app).await.unwrap() });
4499
4500        let secret = "whsec_incident_signing_secret";
4501        let storage_dir =
4502            std::env::temp_dir().join(format!("slabs_http_webhooks_{}", slabs_core::id::new("d")));
4503        let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
4504        cfg.webhooks_allow_local = true;
4505        cfg.incident_webhook_url = Some(format!("http://{addr}/hook"));
4506        cfg.incident_webhook_secret = Some(secret.into());
4507        let ctx = test_ctx(cfg).await;
4508        let router = build_router(ctx.clone(), vec![], &[]);
4509
4510        let input = IncidentInput {
4511            kind: "http_5xx".into(),
4512            source_file: "slabs/orders/create.rs".into(),
4513            route_pattern: Some("/api/orders".into()),
4514            status_code: Some(500),
4515            error_message: "payment timeout".into(),
4516            detail: None,
4517            context_json: json!({ "request_id": "req_1" }),
4518            git_sha: Some("sha_v1".into()),
4519            custom_fingerprint: None,
4520        };
4521
4522        // 1. Opened -> fires incident.opened
4523        let rec = record_and_notify_incident(&ctx, input.clone())
4524            .await
4525            .unwrap();
4526        // 2. Duplicate while open -> Incremented, must NOT fire another webhook
4527        let _ = record_and_notify_incident(&ctx, input.clone())
4528            .await
4529            .unwrap();
4530
4531        // 3. Resolve via HTTP -> fires incident.resolved
4532        let (status, _, _) = send(
4533            &router,
4534            http::Request::builder()
4535                .method(Method::POST)
4536                .uri(format!("/_slabs/incidents/{}/resolve", rec.id))
4537                .header(header::CONTENT_TYPE, "application/json")
4538                .body(Body::from(r#"{"resolved_in_sha":"sha_v2"}"#))
4539                .unwrap(),
4540        )
4541        .await;
4542        assert_eq!(status, StatusCode::OK);
4543
4544        // 4. Recurrence after resolve -> fires incident.reopened
4545        let _ = record_and_notify_incident(&ctx, input).await.unwrap();
4546
4547        // Wait briefly for spawned webhook tasks to complete
4548        for _ in 0..40 {
4549            if received.lock().unwrap().len() >= 3 {
4550                break;
4551            }
4552            tokio::time::sleep(Duration::from_millis(25)).await;
4553        }
4554
4555        let events = received.lock().unwrap().clone();
4556        assert_eq!(
4557            events.len(),
4558            3,
4559            "expected 3 webhook deliveries, got {events:?}"
4560        );
4561
4562        let event_names: Vec<&str> = events.iter().map(|(e, _, _)| e.as_str()).collect();
4563        assert!(event_names.contains(&"incident.opened"));
4564        assert!(event_names.contains(&"incident.resolved"));
4565        assert!(event_names.contains(&"incident.reopened"));
4566
4567        for (event_hdr, sig_hdr, raw_body) in &events {
4568            let expected_sig = sign_incident_webhook(secret, raw_body);
4569            assert_eq!(sig_hdr.as_deref(), Some(expected_sig.as_str()));
4570            let payload: Value = serde_json::from_slice(raw_body).unwrap();
4571            assert_eq!(payload["protocol"], "slabs.incident.v1");
4572            assert_eq!(payload["event"], event_hdr.as_str());
4573            assert!(payload["sent_at"].as_str().is_some());
4574            assert_eq!(payload["incident"]["id"], rec.id);
4575        }
4576
4577        let _ = std::fs::remove_dir_all(&storage_dir);
4578    }
4579
4580    #[tokio::test]
4581    async fn incident_claim_link_ignore_endpoints_webhooks_and_ui() {
4582        let received: Arc<Mutex<Vec<ReceivedWebhook>>> = Arc::new(Mutex::new(Vec::new()));
4583        let recv_clone = received.clone();
4584
4585        let hook_app = Router::new().route(
4586            "/hook",
4587            post(move |headers: HeaderMap, body: Bytes| {
4588                let store = recv_clone.clone();
4589                async move {
4590                    let event = headers
4591                        .get("x-slabs-event")
4592                        .and_then(|v| v.to_str().ok())
4593                        .unwrap_or("")
4594                        .to_owned();
4595                    let sig = headers
4596                        .get("x-slabs-signature")
4597                        .and_then(|v| v.to_str().ok())
4598                        .map(ToOwned::to_owned);
4599                    store.lock().unwrap().push((event, sig, body));
4600                    StatusCode::OK
4601                }
4602            }),
4603        );
4604        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
4605        let addr = listener.local_addr().unwrap();
4606        tokio::spawn(async move { axum::serve(listener, hook_app).await.unwrap() });
4607
4608        let secret = "whsec_claim_link_ignore_secret";
4609        let storage_dir = std::env::temp_dir().join(format!(
4610            "slabs_http_inc_lifecycle_{}",
4611            slabs_core::id::new("d")
4612        ));
4613        let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
4614        cfg.webhooks_allow_local = true;
4615        cfg.incident_webhook_url = Some(format!("http://{addr}/hook"));
4616        cfg.incident_webhook_secret = Some(secret.into());
4617        let ctx = test_ctx(cfg).await;
4618        let router = build_router(ctx.clone(), vec![], &[]);
4619
4620        // Record an incident across two SHAs so recent_occurrences_json has history
4621        let mut input = IncidentInput {
4622            kind: "http_5xx".into(),
4623            source_file: "slabs/orders/pay.rs".into(),
4624            route_pattern: Some("/api/orders/pay".into()),
4625            status_code: Some(500),
4626            error_message: "card declined upstream".into(),
4627            detail: Some("provider 502".into()),
4628            context_json: json!({ "request_id": "req_a", "latency_ms": 420 }),
4629            git_sha: Some("sha_1111".into()),
4630            custom_fingerprint: None,
4631        };
4632        let rec = record_and_notify_incident(&ctx, input.clone())
4633            .await
4634            .unwrap();
4635        input.git_sha = Some("sha_2222".into());
4636        input.context_json = json!({ "request_id": "req_b", "latency_ms": 610 });
4637        let _ = record_and_notify_incident(&ctx, input.clone())
4638            .await
4639            .unwrap();
4640
4641        // 1. Claim via JSON succeeds and second claim returns 409 Conflict
4642        let (status, _, body) = send(
4643            &router,
4644            http::Request::builder()
4645                .method(Method::POST)
4646                .uri(format!("/_slabs/incidents/{}/claim", rec.id))
4647                .header(header::CONTENT_TYPE, "application/json")
4648                .body(Body::from(r#"{"assignee":"agent-claude"}"#))
4649                .unwrap(),
4650        )
4651        .await;
4652        assert_eq!(status, StatusCode::OK, "body: {body}");
4653        let claimed_json: Value = serde_json::from_str(&body).unwrap();
4654        assert_eq!(claimed_json["status"], "in_progress");
4655        assert_eq!(claimed_json["assignee"], "agent-claude");
4656
4657        let (status, _, _) = send(
4658            &router,
4659            http::Request::builder()
4660                .method(Method::POST)
4661                .uri(format!("/_slabs/incidents/{}/claim", rec.id))
4662                .header(header::CONTENT_TYPE, "application/json")
4663                .body(Body::from(r#"{"assignee":"agent-codex"}"#))
4664                .unwrap(),
4665        )
4666        .await;
4667        assert_eq!(status, StatusCode::CONFLICT);
4668
4669        // 2. Link external tracker validates URL and persists key/url
4670        let (status, _, _) = send(
4671            &router,
4672            http::Request::builder()
4673                .method(Method::POST)
4674                .uri(format!("/_slabs/incidents/{}/link", rec.id))
4675                .header(header::CONTENT_TYPE, "application/json")
4676                .body(Body::from(
4677                    r#"{"external_issue_key":"ENG-99","external_issue_url":"javascript:alert(1)"}"#,
4678                ))
4679                .unwrap(),
4680        )
4681        .await;
4682        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
4683
4684        let (status, _, body) = send(
4685            &router,
4686            http::Request::builder()
4687                .method(Method::POST)
4688                .uri(format!("/_slabs/incidents/{}/link", rec.id))
4689                .header(header::CONTENT_TYPE, "application/json")
4690                .body(Body::from(
4691                    r#"{"external_issue_key":"ENG-99","external_issue_url":"https://linear.app/team/issue/ENG-99"}"#,
4692                ))
4693                .unwrap(),
4694        )
4695        .await;
4696        assert_eq!(status, StatusCode::OK, "body: {body}");
4697
4698        // 3. UI in_progress tab renders assignee badge, external issue link, SHA history, and Ignore/Resolve forms
4699        let (status, _, ui_html) = send(
4700            &router,
4701            http::Request::builder()
4702                .uri("/_slabs/incidents/ui?status=in_progress")
4703                .body(Body::empty())
4704                .unwrap(),
4705        )
4706        .await;
4707        assert_eq!(status, StatusCode::OK);
4708        assert!(ui_html.contains("status=in_progress"));
4709        assert!(ui_html.contains("status=ignored"));
4710        assert!(ui_html.contains("Assignee: agent-claude"));
4711        assert!(ui_html.contains("https://linear.app/team/issue/ENG-99"));
4712        assert!(ui_html.contains("ENG-99"));
4713        assert!(ui_html.contains("sha_1111"));
4714        assert!(ui_html.contains("sha_2222"));
4715        assert!(ui_html.contains(&format!("/_slabs/incidents/{}/ignore", rec.id)));
4716        assert!(ui_html.contains(&format!("/_slabs/incidents/{}/resolve", rec.id)));
4717        assert!(!ui_html.contains("<script>"));
4718        assert!(!ui_html.contains("<style"));
4719
4720        // 4. Ignore via HTML form redirects back to /_slabs/incidents/ui
4721        let (status, headers, _) = send(
4722            &router,
4723            http::Request::builder()
4724                .method(Method::POST)
4725                .uri(format!("/_slabs/incidents/{}/ignore", rec.id))
4726                .header(header::ACCEPT, "text/html")
4727                .body(Body::empty())
4728                .unwrap(),
4729        )
4730        .await;
4731        assert_eq!(status, StatusCode::SEE_OTHER);
4732        assert_eq!(
4733            headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),
4734            Some("/_slabs/incidents/ui")
4735        );
4736
4737        // Recurrence while ignored must NOT fire a webhook and stays in ignored tab
4738        let _ = record_and_notify_incident(&ctx, input).await.unwrap();
4739        let (status, _, ignored_html) = send(
4740            &router,
4741            http::Request::builder()
4742                .uri("/_slabs/incidents/ui?status=ignored")
4743                .body(Body::empty())
4744                .unwrap(),
4745        )
4746        .await;
4747        assert_eq!(status, StatusCode::OK);
4748        assert!(ignored_html.contains(&rec.id));
4749
4750        // 5. Claim via HTML form on a fresh open incident redirects to /_slabs/incidents/ui
4751        let open_input = IncidentInput {
4752            kind: "panic".into(),
4753            source_file: "slabs/orders/refund.rs".into(),
4754            route_pattern: Some("/api/orders/refund".into()),
4755            status_code: Some(500),
4756            error_message: "index out of bounds".into(),
4757            detail: None,
4758            context_json: json!({}),
4759            git_sha: Some("sha_3333".into()),
4760            custom_fingerprint: None,
4761        };
4762        let open_rec = record_and_notify_incident(&ctx, open_input).await.unwrap();
4763        let (status, _, open_ui) = send(
4764            &router,
4765            http::Request::builder()
4766                .uri("/_slabs/incidents/ui?status=open")
4767                .body(Body::empty())
4768                .unwrap(),
4769        )
4770        .await;
4771        assert_eq!(status, StatusCode::OK);
4772        assert!(open_ui.contains(&format!("/_slabs/incidents/{}/claim", open_rec.id)));
4773
4774        let (status, headers, _) = send(
4775            &router,
4776            http::Request::builder()
4777                .method(Method::POST)
4778                .uri(format!("/_slabs/incidents/{}/claim", open_rec.id))
4779                .header(header::ACCEPT, "text/html")
4780                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4781                .body(Body::from("assignee=alice+bot"))
4782                .unwrap(),
4783        )
4784        .await;
4785        assert_eq!(status, StatusCode::SEE_OTHER);
4786        assert_eq!(
4787            headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),
4788            Some("/_slabs/incidents/ui")
4789        );
4790        let form_claimed = ctx.incidents.get(&open_rec.id).await.unwrap().unwrap();
4791        assert_eq!(form_claimed.assignee.as_deref(), Some("alice bot"));
4792
4793        // Verify signed incident.assigned webhook fired
4794        for _ in 0..40 {
4795            if received.lock().unwrap().len() >= 4 {
4796                break;
4797            }
4798            tokio::time::sleep(Duration::from_millis(25)).await;
4799        }
4800        let events = received.lock().unwrap().clone();
4801        let assigned_events: Vec<&ReceivedWebhook> = events
4802            .iter()
4803            .filter(|(ev, _, _)| ev == "incident.assigned")
4804            .collect();
4805        assert_eq!(
4806            assigned_events.len(),
4807            2,
4808            "expected 2 incident.assigned webhooks, got {events:?}"
4809        );
4810        for (_, sig_hdr, raw_body) in assigned_events {
4811            let expected_sig = sign_incident_webhook(secret, raw_body);
4812            assert_eq!(sig_hdr.as_deref(), Some(expected_sig.as_str()));
4813            let payload: Value = serde_json::from_slice(raw_body).unwrap();
4814            assert_eq!(payload["event"], "incident.assigned");
4815            assert_eq!(payload["incident"]["status"], "in_progress");
4816        }
4817
4818        let _ = std::fs::remove_dir_all(&storage_dir);
4819    }
4820}