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/{id}`, `GET /_slabs/incidents/{id}/attachments/{blob_id}`, and `POST /_slabs/incidents/{id}/resolve`: agent-oriented runtime incident inbox guarded by dev/test mode or constant-time `SLABS_METRICS_TOKEN` (`Authorization: Bearer <token>`).
13//!   - Dev/test only (`env.is_dev_or_test()`): `GET /_slabs/manifest`, `GET /_slabs/openapi.json`, and `GET /_slabs/mail`.
14//!   - `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`, and `sw-register.js` with `ETag` and `Cache-Control: public, max-age=86400`.
15//!   - `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.
16//!
17//! # Agent invariants
18//!
19//! - Use Axum 0.8 `{param}` and `{*wildcard}` path syntax in [`SlabDef`] constructors. Do not use `:param` or `*wildcard`.
20//! - 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.
21//! - 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.
22//! - 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.
23//! - [`JobRegistry::new`] always registers the built-in `slabs.deliver_webhook` handler unless an application job overrides that name.
24//!
25//! # Example
26//!
27//! ```rust,no_run
28//! use axum::{extract::{Path, State}, Json};
29//! use serde_json::{json, Value};
30//! use slabs_core::SlabResult;
31//! use slabs_http::{build_router, AppCtx, SlabDef};
32//!
33//! pub fn slab() -> SlabDef {
34//!     SlabDef::post("/api/rooms/{room_id}/messages", handle)
35//!         .name("messages.create")
36//!         .summary("Post a message to a room")
37//! }
38//!
39//! async fn handle(
40//!     State(ctx): State<AppCtx>,
41//!     Path(room_id): Path<String>,
42//! ) -> SlabResult<Json<Value>> {
43//!     ctx.rate_limit.check(&format!("room_msg:{room_id}"), 30, 60)?;
44//!     Ok(Json(json!({ "room_id": room_id })))
45//! }
46//!
47//! fn assemble(ctx: AppCtx) -> axum::Router {
48//!     build_router(ctx, vec![slab()], &[])
49//! }
50//! ```
51
52use axum::{
53    body::Bytes,
54    extract::{ConnectInfo, FromRequestParts, MatchedPath, Path, Query, Request, State},
55    handler::Handler,
56    http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri},
57    middleware::{self, Next},
58    response::{IntoResponse, Response},
59    routing::{delete, get, patch, post, put, MethodRouter},
60    Json, Router,
61};
62use chrono::{SecondsFormat, Utc};
63use futures_util::{future::BoxFuture, FutureExt as _};
64use hmac::{Hmac, Mac as _};
65use serde::Deserialize;
66use serde_json::{json, Value};
67use sha2::{Digest, Sha256};
68use slabs_assets::Assets;
69use slabs_auth::Auth;
70use slabs_cache::Cache;
71use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
72use slabs_db::{AuditLog, Db, IncidentInput, IncidentOutcome, IncidentRecord, Incidents};
73use slabs_jobs::{JobRecord, Jobs};
74use slabs_mail::{MailTransport, Mailer};
75use slabs_realtime::Realtime;
76use slabs_storage::{S3Config, Storage, StorageBackend};
77use slabs_webhooks::Webhooks;
78use std::collections::{btree_map::Entry, BTreeMap, HashMap, HashSet};
79use std::fmt::{self, Write as _};
80use std::future::Future;
81use std::net::{IpAddr, SocketAddr};
82use std::panic::AssertUnwindSafe;
83use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
84use std::sync::{Arc, Mutex, OnceLock};
85use std::time::{Duration, Instant};
86use tokio::sync::watch;
87use tokio::task::JoinHandle;
88use tower_http::{
89    compression::CompressionLayer,
90    cors::{AllowOrigin, CorsLayer},
91    limit::RequestBodyLimitLayer,
92    request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
93    set_header::SetResponseHeaderLayer,
94    trace::TraceLayer,
95};
96
97type HmacSha256 = Hmac<Sha256>;
98
99const MAX_RATE_LIMIT_ENTRIES: usize = 50_000;
100const RATE_LIMIT_PRUNE_INTERVAL: Duration = Duration::from_secs(5);
101const INCIDENT_PROTOCOL_VERSION: &str = "slabs.incident.v1";
102const MAX_TRACKED_ROUTES: usize = 2048;
103const LATENCY_BUCKETS_MS: [u64; 8] = [10, 25, 50, 100, 250, 500, 1000, 2500];
104const BASECOAT_CSS: &str = concat!(
105    "@view-transition { navigation: auto; }\n",
106    include_str!("../assets/vendor/basecoat.min.css")
107);
108
109/// Generates time-sortable prefixed ULID `X-Request-Id` headers (`req_01j...`).
110#[derive(Clone, Default)]
111struct MakeUlidRequestId;
112
113impl MakeRequestId for MakeUlidRequestId {
114    fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
115        let id = slabs_core::id::new("req");
116        HeaderValue::from_str(&id).ok().map(RequestId::new)
117    }
118}
119
120#[derive(Debug)]
121struct RateLimiterState {
122    buckets: HashMap<String, (u64, Instant)>,
123    last_prune: Instant,
124}
125
126impl Default for RateLimiterState {
127    fn default() -> Self {
128        Self {
129            buckets: HashMap::new(),
130            last_prune: Instant::now(),
131        }
132    }
133}
134
135/// Explicit in-memory fixed-window rate limiter for auth and sensitive slabs.
136///
137/// Bounded to at most 50,000 tracked keys with throttled expiration pruning (at most once every
138/// 5 seconds) and lock-poison recovery.
139#[derive(Debug, Clone, Default)]
140pub struct RateLimiter {
141    state: Arc<Mutex<RateLimiterState>>,
142}
143
144impl RateLimiter {
145    /// Create a new empty in-memory rate limiter.
146    #[must_use]
147    pub fn new() -> Self {
148        Self::default()
149    }
150
151    /// Increment the counter for `key` and return the remaining quota for the current window.
152    ///
153    /// Returns HTTP 429 (`SlabError::TooManyRequests`) with a `Retry-After` duration when `key`
154    /// reaches `max_requests` within `window_secs`, or when the map reaches its 50,000-key cap.
155    pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
156        let now = Instant::now();
157        let window = Duration::from_secs(window_secs.max(1));
158        let mut guard = self
159            .state
160            .lock()
161            .unwrap_or_else(std::sync::PoisonError::into_inner);
162
163        let can_prune =
164            now.saturating_duration_since(guard.last_prune) >= RATE_LIMIT_PRUNE_INTERVAL;
165
166        if !guard.buckets.contains_key(key) && guard.buckets.len() >= MAX_RATE_LIMIT_ENTRIES {
167            if can_prune {
168                guard.buckets.retain(|_, (_, expires_at)| *expires_at > now);
169                guard.last_prune = now;
170            }
171            if guard.buckets.len() >= MAX_RATE_LIMIT_ENTRIES {
172                return Err(SlabError::too_many_requests(
173                    RATE_LIMIT_PRUNE_INTERVAL.as_secs().max(1),
174                    "rate limit exceeded, please try again shortly",
175                ));
176            }
177        } else if guard.buckets.len() > 10_000 && can_prune {
178            guard.buckets.retain(|_, (_, expires_at)| *expires_at > now);
179            guard.last_prune = now;
180        }
181
182        let entry = guard
183            .buckets
184            .entry(key.to_string())
185            .or_insert((0, now + window));
186
187        if entry.1 <= now {
188            entry.0 = 0;
189            entry.1 = now + window;
190        }
191
192        if entry.0 >= max_requests {
193            let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
194            return Err(SlabError::too_many_requests(
195                retry_after,
196                "rate limit exceeded, please try again shortly",
197            ));
198        }
199
200        entry.0 += 1;
201        Ok(max_requests - entry.0)
202    }
203
204    /// Enforce both a per-IP rate limit and a per-account rate limit in a single call.
205    ///
206    /// Checks `ip_key` against `ip_limit` first (so an already-blocked IP cannot burn a victim's
207    /// account quota), then checks `account_key` against `account_limit`, both over `window_secs`.
208    pub fn check_pair(
209        &self,
210        ip_key: &str,
211        ip_limit: u32,
212        account_key: &str,
213        account_limit: u32,
214        window_secs: u64,
215    ) -> SlabResult<()> {
216        self.check(ip_key, u64::from(ip_limit), window_secs)?;
217        self.check(account_key, u64::from(account_limit), window_secs)?;
218        Ok(())
219    }
220}
221
222/// Axum request-parts extractor resolving the client's IP address via [`client_ip`].
223///
224/// Honors proxy headers only when `state.config.trust_proxy` is `true`, otherwise reads the
225/// socket peer address from [`ConnectInfo`]. Falls back gracefully to `"127.0.0.1"` in unit
226/// tests where `ConnectInfo` is not attached.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct ClientIp(pub String);
229
230impl FromRequestParts<AppCtx> for ClientIp {
231    type Rejection = std::convert::Infallible;
232
233    fn from_request_parts(
234        parts: &mut axum::http::request::Parts,
235        state: &AppCtx,
236    ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
237        let peer = parts
238            .extensions
239            .get::<ConnectInfo<SocketAddr>>()
240            .map(|c| c.0);
241        let ip = client_ip(&parts.headers, peer, state.config.trust_proxy);
242        std::future::ready(if ip == "unknown" {
243            Ok(Self("127.0.0.1".to_string()))
244        } else {
245            Ok(Self(ip))
246        })
247    }
248}
249
250/// Resolve the client's IP address for logging and rate-limit keys.
251///
252/// When `trust_proxy` is `true`, inspects `CF-Connecting-IP`, `Fly-Client-IP`, and the rightmost
253/// valid IP address in `X-Forwarded-For` before falling back to `peer`. When `trust_proxy` is
254/// `false`, proxy headers are ignored and only `peer` is used. Returns `"unknown"` when no valid
255/// IP can be determined.
256#[must_use]
257pub fn client_ip(headers: &HeaderMap, peer: Option<SocketAddr>, trust_proxy: bool) -> String {
258    if trust_proxy {
259        for header_name in ["cf-connecting-ip", "fly-client-ip"] {
260            if let Some(ip) = headers
261                .get(header_name)
262                .and_then(|v| v.to_str().ok())
263                .and_then(|s| s.trim().parse::<IpAddr>().ok())
264            {
265                return ip.to_string();
266            }
267        }
268        if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
269            for part in xff.rsplit(',') {
270                if let Ok(ip) = part.trim().parse::<IpAddr>() {
271                    return ip.to_string();
272                }
273            }
274        }
275    }
276
277    peer.map_or_else(|| "unknown".to_string(), |addr| addr.ip().to_string())
278}
279
280#[derive(Debug, Clone)]
281struct RouteHistogram {
282    source_file: String,
283    requests: u64,
284    errors_5xx: u64,
285    slow_requests: u64,
286    latency_ms_total: u64,
287    max_latency_ms: u64,
288    buckets: [u64; 9],
289}
290
291impl RouteHistogram {
292    fn new(source_file: String) -> Self {
293        Self {
294            source_file,
295            requests: 0,
296            errors_5xx: 0,
297            slow_requests: 0,
298            latency_ms_total: 0,
299            max_latency_ms: 0,
300            buckets: [0; 9],
301        }
302    }
303
304    fn observe(&mut self, elapsed_ms: u64, is_5xx: bool, is_slow: bool) {
305        self.requests = self.requests.saturating_add(1);
306        if is_5xx {
307            self.errors_5xx = self.errors_5xx.saturating_add(1);
308        }
309        if is_slow {
310            self.slow_requests = self.slow_requests.saturating_add(1);
311        }
312        self.latency_ms_total = self.latency_ms_total.saturating_add(elapsed_ms);
313        if elapsed_ms > self.max_latency_ms {
314            self.max_latency_ms = elapsed_ms;
315        }
316        let bucket_idx = LATENCY_BUCKETS_MS
317            .iter()
318            .position(|&bound| elapsed_ms <= bound)
319            .unwrap_or(LATENCY_BUCKETS_MS.len());
320        self.buckets[bucket_idx] = self.buckets[bucket_idx].saturating_add(1);
321    }
322
323    #[allow(
324        clippy::cast_possible_truncation,
325        clippy::cast_sign_loss,
326        clippy::cast_precision_loss
327    )]
328    fn percentile_ms(&self, quantile: f64) -> u64 {
329        if self.requests == 0 {
330            return 0;
331        }
332        let target = ((self.requests as f64) * quantile).ceil().max(1.0) as u64;
333        let mut cumulative = 0u64;
334        for (idx, &count) in self.buckets.iter().enumerate() {
335            cumulative = cumulative.saturating_add(count);
336            if cumulative >= target {
337                return LATENCY_BUCKETS_MS
338                    .get(idx)
339                    .map_or(self.max_latency_ms, |&bound| bound.min(self.max_latency_ms));
340            }
341        }
342        self.max_latency_ms
343    }
344
345    fn p50_ms(&self) -> u64 {
346        self.percentile_ms(0.50)
347    }
348
349    fn p95_ms(&self) -> u64 {
350        self.percentile_ms(0.95)
351    }
352
353    fn p99_ms(&self) -> u64 {
354        self.percentile_ms(0.99)
355    }
356
357    #[allow(clippy::cast_precision_loss)]
358    fn avg_latency_ms(&self) -> f64 {
359        if self.requests > 0 {
360            self.latency_ms_total as f64 / self.requests as f64
361        } else {
362            0.0
363        }
364    }
365}
366
367#[derive(Debug, Clone)]
368struct RouteMetricSnapshot {
369    method: String,
370    route: String,
371    source_file: String,
372    requests: u64,
373    errors_5xx: u64,
374    slow_requests: u64,
375    avg_latency_ms: f64,
376    p50_ms: u64,
377    p95_ms: u64,
378    p99_ms: u64,
379    max_latency_ms: u64,
380}
381
382#[derive(Debug, Default)]
383struct HttpMetrics {
384    requests: AtomicU64,
385    errors_5xx: AtomicU64,
386    latency_ms: AtomicU64,
387    route_sources: Mutex<HashMap<(String, String), String>>,
388    routes: Mutex<HashMap<(String, String), RouteHistogram>>,
389}
390
391impl HttpMetrics {
392    fn register_route_source(&self, method: &str, path: &str, source_file: String) {
393        let mut guard = self
394            .route_sources
395            .lock()
396            .unwrap_or_else(std::sync::PoisonError::into_inner);
397        guard.insert((method.to_ascii_uppercase(), path.to_owned()), source_file);
398    }
399
400    fn source_file(&self, method: &str, route: &str) -> String {
401        let guard = self
402            .route_sources
403            .lock()
404            .unwrap_or_else(std::sync::PoisonError::into_inner);
405        guard
406            .get(&(method.to_ascii_uppercase(), route.to_owned()))
407            .cloned()
408            .unwrap_or_else(|| format!("route:{route}"))
409    }
410
411    fn record_request(
412        &self,
413        method: &str,
414        route: &str,
415        source_file: &str,
416        elapsed_ms: u64,
417        is_5xx: bool,
418        is_slow: bool,
419    ) {
420        self.requests.fetch_add(1, Ordering::Relaxed);
421        self.latency_ms.fetch_add(elapsed_ms, Ordering::Relaxed);
422        if is_5xx {
423            self.errors_5xx.fetch_add(1, Ordering::Relaxed);
424        }
425
426        let key = (method.to_ascii_uppercase(), route.to_owned());
427        let mut guard = self
428            .routes
429            .lock()
430            .unwrap_or_else(std::sync::PoisonError::into_inner);
431        if let Some(hist) = guard.get_mut(&key) {
432            hist.observe(elapsed_ms, is_5xx, is_slow);
433        } else if guard.len() < MAX_TRACKED_ROUTES {
434            let mut hist = RouteHistogram::new(source_file.to_owned());
435            hist.observe(elapsed_ms, is_5xx, is_slow);
436            guard.insert(key, hist);
437        }
438    }
439
440    fn route_snapshots(&self) -> Vec<RouteMetricSnapshot> {
441        let guard = self
442            .routes
443            .lock()
444            .unwrap_or_else(std::sync::PoisonError::into_inner);
445        let mut snapshots: Vec<RouteMetricSnapshot> = guard
446            .iter()
447            .map(|((method, route), hist)| RouteMetricSnapshot {
448                method: method.clone(),
449                route: route.clone(),
450                source_file: hist.source_file.clone(),
451                requests: hist.requests,
452                errors_5xx: hist.errors_5xx,
453                slow_requests: hist.slow_requests,
454                avg_latency_ms: hist.avg_latency_ms(),
455                p50_ms: hist.p50_ms(),
456                p95_ms: hist.p95_ms(),
457                p99_ms: hist.p99_ms(),
458                max_latency_ms: hist.max_latency_ms,
459            })
460            .collect();
461        snapshots.sort_by(|a, b| {
462            b.p95_ms
463                .cmp(&a.p95_ms)
464                .then_with(|| b.max_latency_ms.cmp(&a.max_latency_ms))
465                .then_with(|| a.route.cmp(&b.route))
466                .then_with(|| a.method.cmp(&b.method))
467        });
468        snapshots
469    }
470}
471
472fn derive_slab_source_file(slab: &SlabDef) -> String {
473    let name = slab.name.trim();
474    if name.contains("::") && !name.contains(' ') && !name.contains('/') {
475        format!("slabs/{}.rs", name.replace("::", "/"))
476    } else if name.contains('.') && !name.contains(' ') && !name.contains('/') {
477        format!("slabs/{}.rs", name.replace('.', "/"))
478    } else {
479        format!("route:{}", slab.path)
480    }
481}
482
483/// Shared runtime context passed to every HTTP slab handler and background job.
484///
485/// Every field is an explicit subsystem handle backed by `SQLite` or in-process state, with no ORM
486/// or hidden middleware state.
487#[derive(Debug, Clone)]
488pub struct AppCtx {
489    /// Runtime application configuration loaded from environment variables or defaults.
490    pub config: AppConfig,
491    /// Shared database connection pool.
492    pub db: Db,
493    /// Authentication, session, magic-link, and access-token helper.
494    pub auth: Auth,
495    /// Durable SQLite-backed background job queue.
496    pub jobs: Jobs,
497    /// Outbound email delivery and development outbox mailer.
498    pub mail: Mailer,
499    /// Local or S3-compatible blob storage handle.
500    pub storage: Storage,
501    /// SQLite-backed key/value cache.
502    pub cache: Cache,
503    /// In-process topic broadcast and presence hub for SSE and `WebSocket` updates.
504    pub realtime: Realtime,
505    /// Outbound signed webhook subscription and delivery manager.
506    pub webhooks: Webhooks,
507    /// Content-hashed static asset registry.
508    pub assets: Assets,
509    /// In-memory fixed-window rate limiter.
510    pub rate_limit: RateLimiter,
511    /// Transactional SQLite-backed audit log.
512    pub audit: AuditLog,
513    /// Deduplicated SQLite-backed runtime incident tracker.
514    pub incidents: Incidents,
515    draining: Arc<AtomicBool>,
516    metrics: Arc<HttpMetrics>,
517}
518
519impl AppCtx {
520    /// Initialize database connections and all framework subsystems from `config`.
521    pub async fn connect(config: AppConfig) -> SlabResult<Self> {
522        let db = Db::connect(&config.database_url).await?;
523        let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
524        let jobs = Jobs::new(db.clone());
525        let mail = Mailer::with_transport(
526            db.clone(),
527            format!("noreply@{}.local", config.app_name),
528            MailTransport::from_env(),
529        );
530        let storage_backend = match S3Config::from_env() {
531            Some(s3) => StorageBackend::S3(s3),
532            None => StorageBackend::Local {
533                root_dir: config.storage_dir.clone(),
534            },
535        };
536        let storage = Storage::with_backend(db.clone(), storage_backend)
537            .with_max_blob_bytes(config.max_blob_bytes);
538        let cache = Cache::new(db.clone());
539        let realtime = Realtime::new();
540        let webhooks = Webhooks::new(db.clone(), jobs.clone());
541        let assets = Assets::from_dir(&config.assets_dir);
542        let rate_limit = RateLimiter::new();
543        let audit = AuditLog::new(db.clone());
544        let incidents = Incidents::new(db.clone());
545
546        Ok(Self {
547            config,
548            db,
549            auth,
550            jobs,
551            mail,
552            storage,
553            cache,
554            realtime,
555            webhooks,
556            assets,
557            rate_limit,
558            audit,
559            incidents,
560            draining: Arc::new(AtomicBool::new(false)),
561            metrics: Arc::new(HttpMetrics::default()),
562        })
563    }
564
565    /// Mark this server instance as draining so `GET /health/ready` immediately returns HTTP `503`.
566    pub fn set_draining(&self) {
567        self.draining.store(true, Ordering::SeqCst);
568    }
569
570    /// Return `true` when this server instance has entered graceful shutdown draining.
571    #[must_use]
572    pub fn is_draining(&self) -> bool {
573        self.draining.load(Ordering::SeqCst)
574    }
575}
576
577/// Self-contained HTTP Transaction Script definition returned by `pub fn slab() -> SlabDef`.
578///
579/// Route paths use Axum 0.8 `{param}` and `{*wildcard}` syntax.
580#[derive(Debug)]
581pub struct SlabDef {
582    /// HTTP method handled by this slab (e.g. `"GET"`, `"POST"`).
583    pub method: String,
584    /// Route path pattern registered on the Axum router.
585    pub path: String,
586    /// Logical slab name (commonly `<feature>.<action>`).
587    pub name: String,
588    /// Feature grouping label for manifest inspection.
589    pub feature: String,
590    /// Short human-readable description of the endpoint.
591    pub summary: String,
592    /// Optional JSON Schema describing the expected request body for `OpenAPI` export.
593    pub input_schema: Option<Value>,
594    /// Optional JSON Schema describing the response body for `OpenAPI` export.
595    pub output_schema: Option<Value>,
596    /// When `true`, exempts this slab's `(method, path)` from browser Fetch Metadata / Origin CSRF checks.
597    ///
598    /// Only enable on server-to-server inbound webhook receivers that verify their own HMAC signature.
599    pub skip_csrf: bool,
600    /// Axum method router wrapping the slab's handler.
601    pub router: MethodRouter<AppCtx>,
602}
603
604impl SlabDef {
605    /// Define a `GET` slab at `path`.
606    pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
607    where
608        H: Handler<T, AppCtx>,
609        T: 'static,
610    {
611        Self::new("GET", path, get(handler))
612    }
613
614    /// Define a `POST` slab at `path`.
615    pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
616    where
617        H: Handler<T, AppCtx>,
618        T: 'static,
619    {
620        Self::new("POST", path, post(handler))
621    }
622
623    /// Define a `PUT` slab at `path`.
624    pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
625    where
626        H: Handler<T, AppCtx>,
627        T: 'static,
628    {
629        Self::new("PUT", path, put(handler))
630    }
631
632    /// Define a `PATCH` slab at `path`.
633    pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
634    where
635        H: Handler<T, AppCtx>,
636        T: 'static,
637    {
638        Self::new("PATCH", path, patch(handler))
639    }
640
641    /// Define a `DELETE` slab at `path`.
642    pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
643    where
644        H: Handler<T, AppCtx>,
645        T: 'static,
646    {
647        Self::new("DELETE", path, delete(handler))
648    }
649
650    fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
651        let path = path.into();
652        Self {
653            method: method.to_string(),
654            name: format!("{method} {path}"),
655            feature: "default".to_string(),
656            summary: String::new(),
657            input_schema: None,
658            output_schema: None,
659            skip_csrf: false,
660            path,
661            router,
662        }
663    }
664
665    /// Set the slab's logical name, automatically deriving `feature` from a `<feature>.<action>` prefix.
666    #[must_use]
667    pub fn name(mut self, name: impl Into<String>) -> Self {
668        let n = name.into();
669        if let Some((feat, _)) = n.split_once('.') {
670            self.feature = feat.to_string();
671        }
672        self.name = n;
673        self
674    }
675
676    /// Explicitly set the slab's feature group name.
677    #[must_use]
678    pub fn feature(mut self, feature: impl Into<String>) -> Self {
679        self.feature = feature.into();
680        self
681    }
682
683    /// Set a short human-readable summary for the route manifest.
684    #[must_use]
685    pub fn summary(mut self, summary: impl Into<String>) -> Self {
686        self.summary = summary.into();
687        self
688    }
689
690    /// Attach a JSON Schema describing the expected request body for `/_slabs/openapi.json`.
691    #[must_use]
692    pub fn input_schema(mut self, schema: Value) -> Self {
693        self.input_schema = Some(schema);
694        self
695    }
696
697    /// Attach a JSON Schema describing the response body for `/_slabs/openapi.json`.
698    #[must_use]
699    pub fn output_schema(mut self, schema: Value) -> Self {
700        self.output_schema = Some(schema);
701        self
702    }
703
704    /// Opt this route out of browser CSRF checks (Fetch Metadata and `Origin` verification).
705    ///
706    /// Use only on inbound server-to-server webhook receivers that validate an HMAC signature.
707    #[must_use]
708    pub fn skip_csrf(mut self) -> Self {
709        self.skip_csrf = true;
710        self
711    }
712
713    /// Extract serializable route metadata for the application manifest.
714    pub fn meta(&self) -> RouteMeta {
715        RouteMeta {
716            name: self.name.clone(),
717            method: self.method.clone(),
718            path: self.path.clone(),
719            summary: self.summary.clone(),
720            feature: self.feature.clone(),
721            input_schema: self.input_schema.clone(),
722            output_schema: self.output_schema.clone(),
723        }
724    }
725}
726
727/// Type-erased async handler function stored in a [`JobDef`].
728pub type JobHandlerFn =
729    Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;
730
731/// Self-contained Background Job Transaction Script definition returned by `pub fn job() -> JobDef`.
732#[derive(Clone)]
733pub struct JobDef {
734    /// Unique job identifier used when enqueueing and dispatching.
735    pub name: String,
736    /// Queue name this job belongs to (defaults to `"default"`).
737    pub queue: String,
738    /// Maximum execution attempts before marking the job dead.
739    pub max_attempts: i64,
740    /// Short human-readable summary of the job.
741    pub summary: String,
742    /// Async handler invoked with [`AppCtx`] and the JSON payload.
743    pub handler: JobHandlerFn,
744}
745
746impl fmt::Debug for JobDef {
747    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748        f.debug_struct("JobDef")
749            .field("name", &self.name)
750            .field("queue", &self.queue)
751            .field("max_attempts", &self.max_attempts)
752            .field("summary", &self.summary)
753            .field("handler", &"<fn>")
754            .finish()
755    }
756}
757
758impl JobDef {
759    /// Create a new [`JobDef`] with the given `name` and async `handler`.
760    #[must_use]
761    pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
762    where
763        F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
764        Fut: Future<Output = SlabResult<()>> + Send + 'static,
765    {
766        Self {
767            name: name.into(),
768            queue: "default".to_string(),
769            max_attempts: 5,
770            summary: String::new(),
771            handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
772        }
773    }
774
775    /// Override the queue name for this job.
776    #[must_use]
777    pub fn queue(mut self, queue: impl Into<String>) -> Self {
778        self.queue = queue.into();
779        self
780    }
781
782    /// Override the maximum number of retry attempts for this job.
783    #[must_use]
784    pub fn max_attempts(mut self, attempts: i64) -> Self {
785        self.max_attempts = attempts;
786        self
787    }
788
789    /// Set a short human-readable summary for the job manifest.
790    #[must_use]
791    pub fn summary(mut self, summary: impl Into<String>) -> Self {
792        self.summary = summary.into();
793        self
794    }
795
796    /// Extract serializable job metadata for the application manifest.
797    pub fn meta(&self) -> JobMeta {
798        JobMeta {
799            name: self.name.clone(),
800            queue: self.queue.clone(),
801            max_attempts: self.max_attempts,
802            summary: self.summary.clone(),
803        }
804    }
805}
806
807/// Recurring maintenance schedule that enqueues a registered job on a fixed interval.
808#[derive(Debug, Clone)]
809pub struct ScheduleDef {
810    /// Registered job name to enqueue on each tick.
811    pub job_name: String,
812    /// Interval between scheduled enqueues.
813    pub every: Duration,
814    /// JSON payload enqueued on each scheduled run.
815    pub payload: Value,
816}
817
818impl ScheduleDef {
819    /// Create a recurring schedule that enqueues `job_name` with `payload` on every `every` interval.
820    #[must_use]
821    pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
822        Self {
823            job_name: job_name.into(),
824            every,
825            payload,
826        }
827    }
828}
829
830/// Dispatches `SQLite`-queued jobs to discovered [`JobDef`] handlers.
831#[derive(Debug, Clone)]
832pub struct JobRegistry {
833    handlers: Arc<HashMap<String, JobDef>>,
834}
835
836impl JobRegistry {
837    /// Build a registry from discovered `jobs`, including the built-in `slabs.deliver_webhook` handler.
838    #[must_use]
839    pub fn new(jobs: Vec<JobDef>) -> Self {
840        let mut map = HashMap::new();
841        // Built-in dev-safe webhook delivery job (records delivery as 200 in outbox unless overridden)
842        map.insert(
843            "slabs.deliver_webhook".to_string(),
844            JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
845                .queue("webhooks")
846                .summary("Built-in webhook delivery handler"),
847        );
848        for job in jobs {
849            map.insert(job.name.clone(), job);
850        }
851        Self {
852            handlers: Arc::new(map),
853        }
854    }
855
856    /// Execute a registered job directly by name (ideal for testing scheduled/maintenance jobs).
857    pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
858        let def = self
859            .handlers
860            .get(job_name)
861            .ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
862        (def.handler)(ctx.clone(), payload).await
863    }
864
865    /// Dispatch a claimed [`JobRecord`] to its registered handler.
866    ///
867    /// If the stored JSON payload cannot be parsed (a poison pill), immediately dead-letters the
868    /// job via [`Jobs::mark_dead`], records a `job_dead` incident (firing the incident webhook on
869    /// `Opened` or `Reopened`), and returns an error so it cannot stall the queue.
870    pub async fn dispatch(&self, ctx: &AppCtx, job: &JobRecord) -> SlabResult<()> {
871        let Some(def) = self.handlers.get(&job.job_name) else {
872            return Err(SlabError::not_found(format!(
873                "no job handler registered for `{}`",
874                job.job_name
875            )));
876        };
877
878        let payload: Value = match serde_json::from_str(&job.payload_json) {
879            Ok(v) => v,
880            Err(e) => {
881                let msg = format!("invalid job payload: {e}");
882                let _ = ctx.jobs.mark_dead(&job.id, &msg).await;
883                record_poison_pill_job_incident(ctx, job, &msg).await;
884                return Err(SlabError::bad_request(msg));
885            }
886        };
887
888        (def.handler)(ctx.clone(), payload).await
889    }
890
891    /// Claim and execute the next ready job from the queue, returning `Ok(true)` if a job was processed.
892    pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
893        let Some(record) = ctx.jobs.claim_next().await? else {
894            return Ok(false);
895        };
896
897        let Some(def) = self.handlers.get(&record.job_name) else {
898            let msg = format!("no job handler registered for `{}`", record.job_name);
899            ctx.jobs.mark_failed(&record, &msg).await?;
900            return Ok(true);
901        };
902
903        let payload: Value = match serde_json::from_str(&record.payload_json) {
904            Ok(v) => v,
905            Err(e) => {
906                let msg = format!("invalid job payload: {e}");
907                let _ = ctx.jobs.mark_dead(&record.id, &msg).await;
908                record_poison_pill_job_incident(ctx, &record, &msg).await;
909                return Err(SlabError::bad_request(msg));
910            }
911        };
912
913        match (def.handler)(ctx.clone(), payload).await {
914            Ok(()) => {
915                ctx.jobs.mark_done(&record.id).await?;
916            }
917            Err(err) => {
918                tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
919                ctx.jobs.mark_failed(&record, &err.to_string()).await?;
920            }
921        }
922
923        Ok(true)
924    }
925
926    /// Repeatedly run ready jobs until the queue is empty, returning the number of jobs processed.
927    pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
928        let mut processed = 0;
929        while self.run_next(ctx).await? {
930            processed += 1;
931        }
932        Ok(processed)
933    }
934
935    /// Spawn background job worker tasks without an external shutdown signal.
936    pub fn spawn_workers(&self, ctx: &AppCtx) {
937        let (_tx, rx) = watch::channel(false);
938        let _ = self.spawn_workers_with_shutdown(ctx, &rx);
939    }
940
941    /// Spawn background job worker tasks that stop cleanly when `shutdown` is signaled.
942    ///
943    /// Delegates execution to [`Jobs::spawn_workers_with_telemetry`] for lease reclamation,
944    /// timeouts, panic isolation, dead-letter incident capture, and slow-job tracking,
945    /// returning the spawned [`JoinHandle`]s for graceful drain.
946    pub fn spawn_workers_with_shutdown(
947        &self,
948        ctx: &AppCtx,
949        shutdown: &watch::Receiver<bool>,
950    ) -> Vec<JoinHandle<()>> {
951        let concurrency = ctx.config.job_concurrency.max(1);
952        let poll_interval = Duration::from_millis(ctx.config.job_poll_interval_ms.max(50));
953        let registry = self.clone();
954        let worker_ctx = ctx.clone();
955
956        ctx.jobs.spawn_workers_with_telemetry(
957            concurrency,
958            poll_interval,
959            shutdown,
960            move |job| {
961                let registry = registry.clone();
962                let worker_ctx = worker_ctx.clone();
963                async move { registry.dispatch(&worker_ctx, &job).await }
964            },
965            Some(ctx.incidents.clone()),
966            ctx.config.slow_job_ms,
967            ctx.config.git_sha.clone(),
968            ctx.config.incident_stale_days,
969        )
970    }
971
972    /// Spawn recurring schedule tasks without an external shutdown signal.
973    pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
974        let (_tx, rx) = watch::channel(false);
975        let _ = self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
976    }
977
978    /// Spawn recurring schedule tasks that stop cleanly when `shutdown` is signaled, returning
979    /// their [`JoinHandle`]s.
980    pub fn spawn_schedules_with_shutdown(
981        &self,
982        ctx: &AppCtx,
983        schedules: Vec<ScheduleDef>,
984        shutdown: &watch::Receiver<bool>,
985    ) -> Vec<JoinHandle<()>> {
986        let mut handles = Vec::with_capacity(schedules.len());
987        for schedule in schedules {
988            let sched_ctx = ctx.clone();
989            let mut rx = shutdown.clone();
990            handles.push(tokio::spawn(async move {
991                let mut ticker = tokio::time::interval(schedule.every);
992                ticker.tick().await;
993                loop {
994                    tokio::select! {
995                        _ = ticker.tick() => {
996                            if let Err(err) = sched_ctx
997                                .jobs
998                                .enqueue(&schedule.job_name, schedule.payload.clone())
999                                .await
1000                            {
1001                                tracing::error!(
1002                                    job = %schedule.job_name,
1003                                    error = %err,
1004                                    "failed to enqueue scheduled job"
1005                                );
1006                            }
1007                        }
1008                        _ = rx.changed() => {
1009                            break;
1010                        }
1011                    }
1012                }
1013            }));
1014        }
1015        handles
1016    }
1017}
1018
1019async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
1020    let delivery_id = payload
1021        .get("delivery_id")
1022        .and_then(|v| v.as_str())
1023        .ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
1024    if ctx.config.webhooks_live {
1025        ctx.webhooks
1026            .deliver_http(delivery_id, ctx.config.webhooks_allow_local)
1027            .await?;
1028    } else {
1029        // Dev/test safe mode: marks signed delivery recorded in outbox without external HTTP calls.
1030        ctx.webhooks.mark_delivered(delivery_id, 200).await?;
1031    }
1032    Ok(())
1033}
1034
1035/// Assemble the full [`axum::Router`] from discovered slabs, built-in endpoints, and middleware.
1036///
1037/// Slabs registered on the same path with different HTTP methods are merged into one
1038/// [`MethodRouter`]. Mounts health probes (`/health`, `/health/live`, `/health/ready`,
1039/// `/_slabs/health`), `/_slabs/metrics`, `/_slabs/vendor/*`, `/assets/{hash}/{*path}`, and
1040/// dev-only endpoints (`/_slabs/manifest`, `/_slabs/openapi.json`, `/_slabs/mail`) when
1041/// `ctx.config.env.is_dev_or_test()`, then applies the hardened Tower middleware stack.
1042pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
1043    let manifest = Arc::new(AppManifest {
1044        app_name: ctx.config.app_name.clone(),
1045        routes: slabs.iter().map(SlabDef::meta).collect(),
1046        jobs: jobs.iter().map(JobDef::meta).collect(),
1047    });
1048
1049    let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
1050    let mut skip_csrf_routes: HashSet<(String, String)> = HashSet::new();
1051    for slab in slabs {
1052        if slab.skip_csrf {
1053            skip_csrf_routes.insert((slab.method.to_ascii_uppercase(), slab.path.clone()));
1054        }
1055        let source_file = derive_slab_source_file(&slab);
1056        ctx.metrics
1057            .register_route_source(&slab.method, &slab.path, source_file);
1058        match grouped.entry(slab.path) {
1059            Entry::Occupied(mut existing) => {
1060                let taken = std::mem::take(existing.get_mut());
1061                *existing.get_mut() = taken.merge(slab.router);
1062            }
1063            Entry::Vacant(slot) => {
1064                slot.insert(slab.router);
1065            }
1066        }
1067    }
1068
1069    let has_custom_health = grouped.contains_key("/health");
1070    let has_custom_health_live = grouped.contains_key("/health/live");
1071    let has_custom_health_ready = grouped.contains_key("/health/ready");
1072
1073    let mut router: Router<AppCtx> = Router::new();
1074    for (path, method_router) in grouped {
1075        router = router.route(&path, method_router);
1076    }
1077
1078    if !has_custom_health {
1079        router = router.route("/health", get(health_handler));
1080    }
1081    if !has_custom_health_live {
1082        router = router.route("/health/live", get(health_live_handler));
1083    }
1084    if !has_custom_health_ready {
1085        router = router.route("/health/ready", get(health_ready_handler));
1086    }
1087
1088    router = router
1089        .route("/_slabs/health", get(health_handler))
1090        .route("/_slabs/metrics", get(metrics_handler))
1091        .route("/_slabs/incidents", get(list_incidents_handler))
1092        .route("/_slabs/incidents/{id}", get(get_incident_handler))
1093        .route(
1094            "/_slabs/incidents/{id}/attachments/{blob_id}",
1095            get(incident_attachment_handler),
1096        )
1097        .route(
1098            "/_slabs/incidents/{id}/resolve",
1099            post(resolve_incident_handler),
1100        )
1101        .route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
1102        .route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
1103        .route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
1104        .route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
1105        .route(
1106            "/_slabs/vendor/idiomorph-ext.min.js",
1107            get(vendor_idiomorph_js),
1108        )
1109        .route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
1110        .route("/_slabs/vendor/sw-register.js", get(vendor_sw_register_js))
1111        .route("/assets/{hash}/{*path}", get(serve_asset_handler));
1112
1113    if ctx.config.env.is_dev_or_test() {
1114        let openapi_manifest = manifest.clone();
1115        router = router
1116            .route(
1117                "/_slabs/manifest",
1118                get(move || {
1119                    let m = manifest.clone();
1120                    async move { Json((*m).clone()) }
1121                }),
1122            )
1123            .route(
1124                "/_slabs/openapi.json",
1125                get(move || {
1126                    let m = openapi_manifest.clone();
1127                    async move { Json(m.to_openapi_3_1()) }
1128                }),
1129            )
1130            .route("/_slabs/mail", get(dev_mail_outbox_handler));
1131    }
1132
1133    let max_body_bytes = ctx.config.max_body_bytes;
1134    let cookie_secure = ctx.config.cookie_secure;
1135    let cors_origins: Vec<HeaderValue> = ctx
1136        .config
1137        .cors_origins
1138        .iter()
1139        .filter_map(|o| {
1140            let trimmed = o.trim();
1141            if trimmed.is_empty() {
1142                None
1143            } else {
1144                HeaderValue::from_str(trimmed).ok()
1145            }
1146        })
1147        .collect();
1148
1149    let x_request_id = HeaderName::from_static("x-request-id");
1150    let state_ctx = ctx.clone();
1151    let csrf_state = CsrfState {
1152        ctx: state_ctx.clone(),
1153        skip_routes: Arc::new(skip_csrf_routes),
1154    };
1155
1156    let mut app = router
1157        .route_layer(middleware::from_fn_with_state(
1158            state_ctx,
1159            metrics_middleware,
1160        ))
1161        .route_layer(middleware::from_fn_with_state(csrf_state, csrf_middleware))
1162        .with_state(ctx)
1163        .layer(CompressionLayer::new())
1164        .layer(RequestBodyLimitLayer::new(max_body_bytes))
1165        .layer(SetResponseHeaderLayer::if_not_present(
1166            header::X_CONTENT_TYPE_OPTIONS,
1167            HeaderValue::from_static("nosniff"),
1168        ))
1169        .layer(SetResponseHeaderLayer::if_not_present(
1170            header::X_FRAME_OPTIONS,
1171            HeaderValue::from_static("SAMEORIGIN"),
1172        ))
1173        .layer(SetResponseHeaderLayer::if_not_present(
1174            header::REFERRER_POLICY,
1175            HeaderValue::from_static("strict-origin-when-cross-origin"),
1176        ))
1177        .layer(SetResponseHeaderLayer::if_not_present(
1178            HeaderName::from_static("permissions-policy"),
1179            HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
1180        ));
1181
1182    if cookie_secure {
1183        app = app.layer(SetResponseHeaderLayer::if_not_present(
1184            header::STRICT_TRANSPORT_SECURITY,
1185            HeaderValue::from_static("max-age=31536000; includeSubDomains"),
1186        ));
1187    }
1188
1189    if !cors_origins.is_empty() {
1190        let cors = CorsLayer::new()
1191            .allow_origin(AllowOrigin::list(cors_origins))
1192            .allow_methods([
1193                Method::GET,
1194                Method::POST,
1195                Method::PUT,
1196                Method::PATCH,
1197                Method::DELETE,
1198                Method::OPTIONS,
1199            ])
1200            .allow_headers([
1201                header::AUTHORIZATION,
1202                header::CONTENT_TYPE,
1203                header::ACCEPT,
1204                HeaderName::from_static("hx-request"),
1205                HeaderName::from_static("hx-target"),
1206                HeaderName::from_static("hx-current-url"),
1207                HeaderName::from_static("x-csrf-token"),
1208                HeaderName::from_static("x-request-id"),
1209            ])
1210            .allow_credentials(true);
1211        app = app.layer(cors);
1212    }
1213
1214    app.layer(PropagateRequestIdLayer::new(x_request_id.clone()))
1215        .layer(TraceLayer::new_for_http())
1216        .layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
1217        .layer(middleware::from_fn(sanitize_request_id_middleware))
1218}
1219
1220async fn sanitize_request_id_middleware(mut request: Request, next: Next) -> Response {
1221    let x_request_id = HeaderName::from_static("x-request-id");
1222    let invalid = request.headers().get(&x_request_id).is_some_and(|val| {
1223        val.to_str().map_or(true, |s| {
1224            s.is_empty()
1225                || s.len() > 64
1226                || !s
1227                    .bytes()
1228                    .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
1229        })
1230    });
1231    if invalid {
1232        request.headers_mut().remove(&x_request_id);
1233    }
1234    next.run(request).await
1235}
1236
1237fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
1238    if let Some(s) = payload.downcast_ref::<&str>() {
1239        (*s).to_owned()
1240    } else if let Some(s) = payload.downcast_ref::<String>() {
1241        s.clone()
1242    } else {
1243        "handler panicked".to_owned()
1244    }
1245}
1246
1247fn incident_webhook_client() -> &'static reqwest::Client {
1248    static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
1249    CLIENT.get_or_init(|| {
1250        reqwest::Client::builder()
1251            .timeout(Duration::from_secs(5))
1252            .redirect(reqwest::redirect::Policy::none())
1253            .build()
1254            .expect("failed to build incident webhook HTTP client")
1255    })
1256}
1257
1258fn sign_incident_webhook(secret: &str, body: &[u8]) -> String {
1259    let mut mac =
1260        HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts keys of any size");
1261    mac.update(body);
1262    format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
1263}
1264
1265fn spawn_incident_webhook(ctx: &AppCtx, event: &'static str, record: &IncidentRecord) {
1266    let Some(raw_url) = ctx.config.incident_webhook_url.as_deref() else {
1267        return;
1268    };
1269    let validated_url =
1270        match Webhooks::validate_url_with_policy(raw_url, ctx.config.webhooks_allow_local) {
1271            Ok(url) => url,
1272            Err(err) => {
1273                tracing::warn!(
1274                    error = %err,
1275                    "skipped incident webhook notification because URL failed SSRF validation"
1276                );
1277                return;
1278            }
1279        };
1280
1281    let payload = json!({
1282        "protocol": INCIDENT_PROTOCOL_VERSION,
1283        "event": event,
1284        "sent_at": Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true),
1285        "app": ctx.config.app_name,
1286        "env": ctx.config.env.as_str(),
1287        "incident": record,
1288    });
1289    let Ok(body_bytes) = serde_json::to_vec(&payload) else {
1290        tracing::warn!("failed to serialize incident webhook payload");
1291        return;
1292    };
1293    let signature = ctx
1294        .config
1295        .incident_webhook_secret
1296        .as_deref()
1297        .map(|secret| sign_incident_webhook(secret, &body_bytes));
1298
1299    tokio::spawn(async move {
1300        let client = incident_webhook_client();
1301        let mut req = client
1302            .post(&validated_url)
1303            .header(header::CONTENT_TYPE, "application/json")
1304            .header("x-slabs-event", event)
1305            .header("x-slabs-protocol", INCIDENT_PROTOCOL_VERSION)
1306            .body(body_bytes);
1307        if let Some(sig) = signature {
1308            req = req.header("x-slabs-signature", sig);
1309        }
1310        if let Err(err) = req.send().await {
1311            tracing::warn!(error = %err, event, "incident webhook notification failed");
1312        }
1313    });
1314}
1315
1316async fn record_and_notify_incident(ctx: &AppCtx, input: IncidentInput) -> Option<IncidentRecord> {
1317    let (record, outcome) = match ctx.incidents.record_with_outcome(input).await {
1318        Ok(res) => res,
1319        Err(err) => {
1320            tracing::error!(error = %err, "failed to persist runtime incident");
1321            return None;
1322        }
1323    };
1324
1325    match outcome {
1326        IncidentOutcome::Opened => spawn_incident_webhook(ctx, "incident.opened", &record),
1327        IncidentOutcome::Reopened => spawn_incident_webhook(ctx, "incident.reopened", &record),
1328        IncidentOutcome::Incremented => {}
1329    }
1330
1331    Some(record)
1332}
1333
1334async fn record_poison_pill_job_incident(ctx: &AppCtx, job: &JobRecord, msg: &str) {
1335    let input = IncidentInput {
1336        kind: "job_dead".into(),
1337        source_file: format!("jobs/{}.rs", job.job_name),
1338        route_pattern: Some(job.job_name.clone()),
1339        status_code: None,
1340        error_message: msg.to_owned(),
1341        detail: Some(format!(
1342            "job {} ({}) dead-lettered due to invalid JSON payload: {msg}",
1343            job.id, job.job_name
1344        )),
1345        context_json: json!({
1346            "job_id": job.id,
1347            "job_type": job.job_name,
1348            "attempts": job.attempts,
1349            "max_attempts": job.max_attempts,
1350            "env": ctx.config.env.as_str(),
1351            "git_sha": ctx.config.git_sha,
1352        }),
1353        git_sha: ctx.config.git_sha.clone(),
1354        custom_fingerprint: None,
1355    };
1356    let _ = record_and_notify_incident(ctx, input).await;
1357}
1358
1359async fn metrics_middleware(State(ctx): State<AppCtx>, request: Request, next: Next) -> Response {
1360    let method = request.method().as_str().to_owned();
1361    let raw_path = request.uri().path().to_owned();
1362    let route_pattern = request
1363        .extensions()
1364        .get::<MatchedPath>()
1365        .map_or_else(|| raw_path.clone(), |m| m.as_str().to_owned());
1366    let request_id = request
1367        .headers()
1368        .get("x-request-id")
1369        .and_then(|v| v.to_str().ok())
1370        .unwrap_or("")
1371        .to_owned();
1372    let is_ws_upgrade = request
1373        .headers()
1374        .get(header::UPGRADE)
1375        .and_then(|v| v.to_str().ok())
1376        .is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
1377    let source_file = ctx.metrics.source_file(&method, &route_pattern);
1378    let started = Instant::now();
1379
1380    match AssertUnwindSafe(next.run(request)).catch_unwind().await {
1381        Ok(response) => {
1382            let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
1383            let status = response.status();
1384            let is_5xx = status.is_server_error();
1385            let is_sse = response
1386                .headers()
1387                .get(header::CONTENT_TYPE)
1388                .and_then(|v| v.to_str().ok())
1389                .is_some_and(|v| v.to_ascii_lowercase().starts_with("text/event-stream"));
1390            let is_stream = is_ws_upgrade || status == StatusCode::SWITCHING_PROTOCOLS || is_sse;
1391            let is_internal_route = raw_path.starts_with("/_slabs/");
1392            let is_slow =
1393                !is_internal_route && !is_stream && elapsed_ms >= ctx.config.slow_request_ms;
1394
1395            ctx.metrics.record_request(
1396                &method,
1397                &route_pattern,
1398                &source_file,
1399                elapsed_ms,
1400                is_5xx,
1401                is_slow,
1402            );
1403
1404            if is_5xx {
1405                tracing::error!(
1406                    slab_file = %source_file,
1407                    method = %method,
1408                    route = %route_pattern,
1409                    status = status.as_u16(),
1410                    latency_ms = elapsed_ms,
1411                    request_id = %request_id,
1412                    git_sha = ctx.config.git_sha.as_deref().unwrap_or(""),
1413                    "HTTP 5xx response"
1414                );
1415                let input = IncidentInput {
1416                    kind: "http_5xx".into(),
1417                    source_file: source_file.clone(),
1418                    route_pattern: Some(route_pattern.clone()),
1419                    status_code: Some(i64::from(status.as_u16())),
1420                    error_message: format!(
1421                        "HTTP {} on {} {}",
1422                        status.as_u16(),
1423                        method,
1424                        route_pattern
1425                    ),
1426                    detail: Some(format!(
1427                        "{method} {route_pattern} returned {} in {elapsed_ms}ms",
1428                        status.as_u16()
1429                    )),
1430                    context_json: json!({
1431                        "method": method,
1432                        "request_id": request_id,
1433                        "latency_ms": elapsed_ms,
1434                        "status": status.as_u16(),
1435                        "env": ctx.config.env.as_str(),
1436                        "git_sha": ctx.config.git_sha,
1437                    }),
1438                    git_sha: ctx.config.git_sha.clone(),
1439                    custom_fingerprint: None,
1440                };
1441                let _ = record_and_notify_incident(&ctx, input).await;
1442            }
1443
1444            if is_slow {
1445                tracing::warn!(
1446                    slab_file = %source_file,
1447                    method = %method,
1448                    route = %route_pattern,
1449                    status = status.as_u16(),
1450                    latency_ms = elapsed_ms,
1451                    request_id = %request_id,
1452                    git_sha = ctx.config.git_sha.as_deref().unwrap_or(""),
1453                    "slow HTTP request"
1454                );
1455                let input = IncidentInput {
1456                    kind: "slow_request".into(),
1457                    source_file,
1458                    route_pattern: Some(route_pattern.clone()),
1459                    status_code: Some(i64::from(status.as_u16())),
1460                    error_message: format!(
1461                        "slow request on {} {} exceeded {}ms threshold",
1462                        method, route_pattern, ctx.config.slow_request_ms
1463                    ),
1464                    detail: Some(format!(
1465                        "{method} {route_pattern} took {elapsed_ms}ms (threshold {}ms, status {})",
1466                        ctx.config.slow_request_ms,
1467                        status.as_u16()
1468                    )),
1469                    context_json: json!({
1470                        "method": method,
1471                        "request_id": request_id,
1472                        "latency_ms": elapsed_ms,
1473                        "threshold_ms": ctx.config.slow_request_ms,
1474                        "status": status.as_u16(),
1475                        "env": ctx.config.env.as_str(),
1476                        "git_sha": ctx.config.git_sha,
1477                    }),
1478                    git_sha: ctx.config.git_sha.clone(),
1479                    custom_fingerprint: None,
1480                };
1481                let _ = record_and_notify_incident(&ctx, input).await;
1482            }
1483
1484            response
1485        }
1486        Err(panic_payload) => {
1487            let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
1488            let panic_msg = panic_payload_message(panic_payload.as_ref());
1489            let is_slow =
1490                !raw_path.starts_with("/_slabs/") && elapsed_ms >= ctx.config.slow_request_ms;
1491
1492            tracing::error!(
1493                slab_file = %source_file,
1494                method = %method,
1495                route = %route_pattern,
1496                status = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
1497                latency_ms = elapsed_ms,
1498                request_id = %request_id,
1499                git_sha = ctx.config.git_sha.as_deref().unwrap_or(""),
1500                panic = %panic_msg,
1501                "HTTP handler panicked"
1502            );
1503
1504            ctx.metrics.record_request(
1505                &method,
1506                &route_pattern,
1507                &source_file,
1508                elapsed_ms,
1509                true,
1510                is_slow,
1511            );
1512
1513            let input = IncidentInput {
1514                kind: "panic".into(),
1515                source_file,
1516                route_pattern: Some(route_pattern.clone()),
1517                status_code: Some(500),
1518                error_message: panic_msg.clone(),
1519                detail: Some(format!(
1520                    "HTTP {method} {route_pattern} panicked: {panic_msg}"
1521                )),
1522                context_json: json!({
1523                    "method": method,
1524                    "request_id": request_id,
1525                    "latency_ms": elapsed_ms,
1526                    "env": ctx.config.env.as_str(),
1527                    "git_sha": ctx.config.git_sha,
1528                }),
1529                git_sha: ctx.config.git_sha.clone(),
1530                custom_fingerprint: None,
1531            };
1532            let _ = record_and_notify_incident(&ctx, input).await;
1533
1534            (
1535                StatusCode::INTERNAL_SERVER_ERROR,
1536                Json(json!({ "error": "internal server error" })),
1537            )
1538                .into_response()
1539        }
1540    }
1541}
1542
1543#[derive(Clone)]
1544struct CsrfState {
1545    ctx: AppCtx,
1546    skip_routes: Arc<HashSet<(String, String)>>,
1547}
1548
1549async fn csrf_middleware(State(state): State<CsrfState>, request: Request, next: Next) -> Response {
1550    if !state.ctx.config.csrf_enforce {
1551        return next.run(request).await;
1552    }
1553
1554    if !matches!(
1555        *request.method(),
1556        Method::POST | Method::PUT | Method::PATCH | Method::DELETE
1557    ) {
1558        return next.run(request).await;
1559    }
1560
1561    let headers = request.headers();
1562    if !headers.contains_key(header::COOKIE) {
1563        return next.run(request).await;
1564    }
1565
1566    if headers
1567        .get(header::AUTHORIZATION)
1568        .and_then(|v| v.to_str().ok())
1569        .is_some_and(|v| v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer "))
1570    {
1571        return next.run(request).await;
1572    }
1573
1574    let method = request.method().as_str().to_ascii_uppercase();
1575    let matched_path = request
1576        .extensions()
1577        .get::<MatchedPath>()
1578        .map_or_else(|| request.uri().path(), MatchedPath::as_str);
1579    if state
1580        .skip_routes
1581        .contains(&(method, matched_path.to_owned()))
1582    {
1583        return next.run(request).await;
1584    }
1585
1586    if headers
1587        .get("sec-fetch-site")
1588        .and_then(|v| v.to_str().ok())
1589        .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
1590    {
1591        return SlabError::forbidden("cross-site request blocked by fetch metadata policy")
1592            .into_response();
1593    }
1594
1595    if let Some(origin_val) = headers.get(header::ORIGIN) {
1596        let Ok(origin_raw) = origin_val.to_str().map(str::trim) else {
1597            return SlabError::forbidden("invalid Origin header").into_response();
1598        };
1599        if !is_allowed_origin(origin_raw, headers, &state.ctx.config.cors_origins) {
1600            return SlabError::forbidden("cross-origin request blocked").into_response();
1601        }
1602    }
1603
1604    next.run(request).await
1605}
1606
1607fn is_allowed_origin(origin_raw: &str, headers: &HeaderMap, cors_origins: &[String]) -> bool {
1608    if origin_raw.is_empty() || origin_raw.eq_ignore_ascii_case("null") {
1609        return false;
1610    }
1611    if cors_origins
1612        .iter()
1613        .any(|allowed| allowed.trim().eq_ignore_ascii_case(origin_raw))
1614    {
1615        return true;
1616    }
1617
1618    let Ok(origin_uri) = origin_raw.parse::<Uri>() else {
1619        return false;
1620    };
1621    let Some(scheme) = origin_uri.scheme_str() else {
1622        return false;
1623    };
1624    if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
1625        return false;
1626    }
1627    let Some(authority) = origin_uri.authority() else {
1628        return false;
1629    };
1630    if authority.as_str().contains('@') {
1631        return false;
1632    }
1633
1634    let Some(host_raw) = headers
1635        .get(header::HOST)
1636        .and_then(|v| v.to_str().ok())
1637        .map(str::trim)
1638        .filter(|v| !v.is_empty())
1639    else {
1640        return false;
1641    };
1642
1643    authorities_match(scheme, authority.as_str(), host_raw)
1644}
1645
1646fn authorities_match(scheme: &str, origin_authority: &str, host_header: &str) -> bool {
1647    if origin_authority.eq_ignore_ascii_case(host_header) {
1648        return true;
1649    }
1650    let default_port = if scheme.eq_ignore_ascii_case("https") {
1651        ":443"
1652    } else {
1653        ":80"
1654    };
1655    let norm_origin = origin_authority
1656        .strip_suffix(default_port)
1657        .unwrap_or(origin_authority);
1658    let norm_host = host_header
1659        .strip_suffix(default_port)
1660        .unwrap_or(host_header);
1661    norm_origin.eq_ignore_ascii_case(norm_host)
1662}
1663
1664fn constant_time_eq_sha256(a: &[u8], b: &[u8]) -> bool {
1665    let ha = Sha256::digest(a);
1666    let hb = Sha256::digest(b);
1667    let mut diff = 0u8;
1668    for (x, y) in ha.iter().zip(hb.iter()) {
1669        diff |= x ^ y;
1670    }
1671    diff == 0
1672}
1673
1674async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
1675    ctx.db.ping().await?;
1676    Ok(Json(json!({
1677        "status": "ok",
1678        "app": ctx.config.app_name,
1679    })))
1680}
1681
1682async fn health_live_handler() -> Json<Value> {
1683    Json(json!({ "status": "ok" }))
1684}
1685
1686async fn health_ready_handler(State(ctx): State<AppCtx>) -> Response {
1687    if ctx.is_draining() {
1688        return (
1689            StatusCode::SERVICE_UNAVAILABLE,
1690            Json(json!({ "status": "draining" })),
1691        )
1692            .into_response();
1693    }
1694    match ctx.db.ping().await {
1695        Ok(()) => (StatusCode::OK, Json(json!({ "status": "ok" }))).into_response(),
1696        Err(err) => {
1697            tracing::warn!(error = %err, "readiness probe database check failed");
1698            (
1699                StatusCode::SERVICE_UNAVAILABLE,
1700                Json(json!({ "status": "unavailable" })),
1701            )
1702                .into_response()
1703        }
1704    }
1705}
1706
1707fn is_metrics_authorized(ctx: &AppCtx, headers: &HeaderMap) -> Result<(), StatusCode> {
1708    if let Some(expected) = &ctx.config.metrics_token {
1709        let provided = headers
1710            .get(header::AUTHORIZATION)
1711            .and_then(|v| v.to_str().ok())
1712            .and_then(|v| v.strip_prefix("Bearer "));
1713        match provided {
1714            Some(token) if constant_time_eq_sha256(token.as_bytes(), expected.as_bytes()) => Ok(()),
1715            _ => Err(StatusCode::UNAUTHORIZED),
1716        }
1717    } else if ctx.config.env.is_prod_like() {
1718        Err(StatusCode::NOT_FOUND)
1719    } else {
1720        Ok(())
1721    }
1722}
1723
1724fn escape_prom_label(raw: &str) -> String {
1725    let mut out = String::with_capacity(raw.len());
1726    for ch in raw.chars() {
1727        match ch {
1728            '\\' => out.push_str("\\\\"),
1729            '"' => out.push_str("\\\""),
1730            '\n' => out.push_str("\\n"),
1731            other => out.push(other),
1732        }
1733    }
1734    out
1735}
1736
1737async fn metrics_handler(State(ctx): State<AppCtx>, headers: HeaderMap) -> Response {
1738    if let Err(status) = is_metrics_authorized(&ctx, &headers) {
1739        return status.into_response();
1740    }
1741
1742    let requests_total = ctx.metrics.requests.load(Ordering::Relaxed);
1743    let errors_5xx_total = ctx.metrics.errors_5xx.load(Ordering::Relaxed);
1744    let latency_ms_total = ctx.metrics.latency_ms.load(Ordering::Relaxed);
1745    #[allow(clippy::cast_precision_loss)]
1746    let avg_latency_ms = if requests_total > 0 {
1747        latency_ms_total as f64 / requests_total as f64
1748    } else {
1749        0.0
1750    };
1751    let job_stats = ctx.jobs.stats().await.unwrap_or_default();
1752    let realtime_topics = ctx.realtime.active_topic_count();
1753    let open_incidents = ctx.incidents.count_open().await.unwrap_or(0);
1754    let route_snapshots = ctx.metrics.route_snapshots();
1755
1756    let wants_json = headers
1757        .get(header::ACCEPT)
1758        .and_then(|v| v.to_str().ok())
1759        .is_some_and(|v| v.contains("application/json"));
1760
1761    if wants_json {
1762        let routes_json: Vec<Value> = route_snapshots
1763            .iter()
1764            .map(|r| {
1765                json!({
1766                    "method": r.method,
1767                    "route": r.route,
1768                    "source_file": r.source_file,
1769                    "requests": r.requests,
1770                    "errors_5xx": r.errors_5xx,
1771                    "slow_requests": r.slow_requests,
1772                    "avg_latency_ms": r.avg_latency_ms,
1773                    "p50_ms": r.p50_ms,
1774                    "p95_ms": r.p95_ms,
1775                    "p99_ms": r.p99_ms,
1776                    "max_latency_ms": r.max_latency_ms,
1777                })
1778            })
1779            .collect();
1780        return (
1781            StatusCode::OK,
1782            Json(json!({
1783                "http": {
1784                    "requests_total": requests_total,
1785                    "errors_5xx_total": errors_5xx_total,
1786                    "latency_ms_total": latency_ms_total,
1787                    "avg_latency_ms": avg_latency_ms,
1788                },
1789                "routes": routes_json,
1790                "open_incidents": open_incidents,
1791                "jobs": {
1792                    "pending": job_stats.pending,
1793                    "running": job_stats.running,
1794                    "dead": job_stats.dead,
1795                    "completed": job_stats.completed,
1796                },
1797                "realtime": {
1798                    "active_topics": realtime_topics,
1799                },
1800            })),
1801        )
1802            .into_response();
1803    }
1804
1805    let mut body = String::with_capacity(1024);
1806    let _ = writeln!(
1807        body,
1808        "# HELP slabs_http_requests_total Total HTTP requests handled."
1809    );
1810    let _ = writeln!(body, "# TYPE slabs_http_requests_total counter");
1811    let _ = writeln!(body, "slabs_http_requests_total {requests_total}");
1812    let _ = writeln!(
1813        body,
1814        "# HELP slabs_http_errors_5xx_total Total HTTP 5xx responses."
1815    );
1816    let _ = writeln!(body, "# TYPE slabs_http_errors_5xx_total counter");
1817    let _ = writeln!(body, "slabs_http_errors_5xx_total {errors_5xx_total}");
1818    let _ = writeln!(
1819        body,
1820        "# HELP slabs_http_latency_ms_total Cumulative HTTP latency in milliseconds."
1821    );
1822    let _ = writeln!(body, "# TYPE slabs_http_latency_ms_total counter");
1823    let _ = writeln!(body, "slabs_http_latency_ms_total {latency_ms_total}");
1824    let _ = writeln!(
1825        body,
1826        "# HELP slabs_http_latency_avg_ms Average HTTP latency in milliseconds."
1827    );
1828    let _ = writeln!(body, "# TYPE slabs_http_latency_avg_ms gauge");
1829    let _ = writeln!(body, "slabs_http_latency_avg_ms {avg_latency_ms:.3}");
1830    let _ = writeln!(body, "# HELP slabs_jobs_pending Pending background jobs.");
1831    let _ = writeln!(body, "# TYPE slabs_jobs_pending gauge");
1832    let _ = writeln!(body, "slabs_jobs_pending {}", job_stats.pending);
1833    let _ = writeln!(body, "# HELP slabs_jobs_running Running background jobs.");
1834    let _ = writeln!(body, "# TYPE slabs_jobs_running gauge");
1835    let _ = writeln!(body, "slabs_jobs_running {}", job_stats.running);
1836    let _ = writeln!(
1837        body,
1838        "# HELP slabs_jobs_dead Dead-lettered background jobs."
1839    );
1840    let _ = writeln!(body, "# TYPE slabs_jobs_dead gauge");
1841    let _ = writeln!(body, "slabs_jobs_dead {}", job_stats.dead);
1842    let _ = writeln!(
1843        body,
1844        "# HELP slabs_jobs_completed Completed background jobs."
1845    );
1846    let _ = writeln!(body, "# TYPE slabs_jobs_completed counter");
1847    let _ = writeln!(body, "slabs_jobs_completed {}", job_stats.completed);
1848    let _ = writeln!(
1849        body,
1850        "# HELP slabs_realtime_active_topics Active realtime pub/sub topics."
1851    );
1852    let _ = writeln!(body, "# TYPE slabs_realtime_active_topics gauge");
1853    let _ = writeln!(body, "slabs_realtime_active_topics {realtime_topics}");
1854    let _ = writeln!(body, "# HELP slabs_incidents_open Open runtime incidents.");
1855    let _ = writeln!(body, "# TYPE slabs_incidents_open gauge");
1856    let _ = writeln!(body, "slabs_incidents_open {open_incidents}");
1857
1858    if !route_snapshots.is_empty() {
1859        let _ = writeln!(
1860            body,
1861            "# HELP slabs_route_requests_total Total HTTP requests per route."
1862        );
1863        let _ = writeln!(body, "# TYPE slabs_route_requests_total counter");
1864        for r in &route_snapshots {
1865            let _ = writeln!(
1866                body,
1867                "slabs_route_requests_total{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
1868                escape_prom_label(&r.method),
1869                escape_prom_label(&r.route),
1870                escape_prom_label(&r.source_file),
1871                r.requests
1872            );
1873        }
1874        let _ = writeln!(
1875            body,
1876            "# HELP slabs_route_slow_total Slow HTTP requests per route."
1877        );
1878        let _ = writeln!(body, "# TYPE slabs_route_slow_total counter");
1879        for r in &route_snapshots {
1880            let _ = writeln!(
1881                body,
1882                "slabs_route_slow_total{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
1883                escape_prom_label(&r.method),
1884                escape_prom_label(&r.route),
1885                escape_prom_label(&r.source_file),
1886                r.slow_requests
1887            );
1888        }
1889        let _ = writeln!(
1890            body,
1891            "# HELP slabs_route_p95_ms Estimated p95 latency in milliseconds per route."
1892        );
1893        let _ = writeln!(body, "# TYPE slabs_route_p95_ms gauge");
1894        for r in &route_snapshots {
1895            let _ = writeln!(
1896                body,
1897                "slabs_route_p95_ms{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
1898                escape_prom_label(&r.method),
1899                escape_prom_label(&r.route),
1900                escape_prom_label(&r.source_file),
1901                r.p95_ms
1902            );
1903        }
1904    }
1905
1906    (
1907        StatusCode::OK,
1908        [(
1909            header::CONTENT_TYPE,
1910            HeaderValue::from_static("text/plain; version=0.0.4; charset=utf-8"),
1911        )],
1912        body,
1913    )
1914        .into_response()
1915}
1916
1917#[derive(Debug, Deserialize)]
1918struct ListIncidentsQuery {
1919    status: Option<String>,
1920    limit: Option<i64>,
1921}
1922
1923#[derive(Debug, Deserialize)]
1924struct ResolveIncidentBody {
1925    resolved_in_sha: Option<String>,
1926}
1927
1928#[derive(Debug, Clone, Deserialize)]
1929struct IncidentAttachmentRef {
1930    blob_id: String,
1931}
1932
1933fn parse_incident_attachments(context_json: &str) -> Vec<IncidentAttachmentRef> {
1934    serde_json::from_str::<Value>(context_json)
1935        .ok()
1936        .and_then(|v| v.get("attachments").cloned())
1937        .and_then(|arr| serde_json::from_value::<Vec<IncidentAttachmentRef>>(arr).ok())
1938        .unwrap_or_default()
1939}
1940
1941fn repro_hint_for(inc: &IncidentRecord) -> String {
1942    if inc.source_file.starts_with("slabs/") || inc.source_file.starts_with("jobs/") {
1943        let test_filter = inc.source_file.trim_end_matches(".rs").replace('/', "::");
1944        format!(
1945            "Inspect `{}` and verify with `slabs check` (or `cargo test {}`)",
1946            inc.source_file, test_filter
1947        )
1948    } else {
1949        format!(
1950            "Inspect `{}` ({}) and verify with `slabs check`",
1951            inc.source_file,
1952            inc.route_pattern.as_deref().unwrap_or("unknown route")
1953        )
1954    }
1955}
1956
1957fn repro_test_for(inc: &IncidentRecord) -> String {
1958    let fn_suffix: String = inc
1959        .id
1960        .chars()
1961        .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
1962        .collect();
1963    let fn_name = if fn_suffix.is_empty() {
1964        "repro_incident".to_owned()
1965    } else {
1966        format!("repro_{fn_suffix}")
1967    };
1968
1969    if matches!(inc.kind.as_str(), "job_dead" | "slow_job") || inc.source_file.starts_with("jobs/")
1970    {
1971        let job_name = inc.route_pattern.as_deref().unwrap_or("job_name");
1972        return format!(
1973            "// Paste into `#[cfg(test)] mod tests` in `{}`\n\
1974             #[tokio::test]\n\
1975             async fn {fn_name}() {{\n\
1976                 let app = crate::test_app().await;\n\
1977                 app.run_job_now({job_name:?}, serde_json::json!({{}})).await;\n\
1978             }}",
1979            inc.source_file
1980        );
1981    }
1982
1983    let route = inc.route_pattern.as_deref().unwrap_or("/");
1984    let method = serde_json::from_str::<Value>(&inc.context_json)
1985        .ok()
1986        .and_then(|v| {
1987            v.get("method")
1988                .and_then(Value::as_str)
1989                .map(str::to_ascii_uppercase)
1990        })
1991        .unwrap_or_else(|| "GET".to_owned());
1992
1993    let request_lines = match method.as_str() {
1994        "GET" => format!("    let resp = app.get({route:?}).await;"),
1995        "POST" => {
1996            format!("    let resp = app.post_json({route:?}, &serde_json::json!({{}})).await;")
1997        }
1998        other => format!(
1999            "    let req = axum::http::Request::builder()\n\
2000                 .method({other:?})\n\
2001                 .uri({route:?})\n\
2002                 .body(axum::body::Body::empty())\n\
2003                 .unwrap();\n\
2004             let resp = app.request(req).await;"
2005        ),
2006    };
2007
2008    format!(
2009        "// Paste into `#[cfg(test)] mod tests` in `{}`\n\
2010         #[tokio::test]\n\
2011         async fn {fn_name}() {{\n\
2012             let app = crate::test_app().await;\n\
2013         {request_lines}\n\
2014             assert!(resp.status.is_success(), \"unexpected status: {{}}\", resp.status);\n\
2015         }}",
2016        inc.source_file
2017    )
2018}
2019
2020fn enrich_incident_json(inc: &IncidentRecord) -> Value {
2021    let mut value = serde_json::to_value(inc).unwrap_or_else(|_| json!({}));
2022    if let Some(obj) = value.as_object_mut() {
2023        obj.insert("repro_hint".into(), Value::String(repro_hint_for(inc)));
2024    }
2025    value
2026}
2027
2028fn enrich_incident_detail_json(inc: &IncidentRecord) -> Value {
2029    let mut value = enrich_incident_json(inc);
2030    if let Some(obj) = value.as_object_mut() {
2031        obj.insert("repro_test".into(), Value::String(repro_test_for(inc)));
2032    }
2033    value
2034}
2035
2036fn parse_resolve_sha(body: &Bytes) -> SlabResult<Option<String>> {
2037    if body.iter().all(u8::is_ascii_whitespace) {
2038        return Ok(None);
2039    }
2040    match serde_json::from_slice::<ResolveIncidentBody>(body) {
2041        Ok(parsed) => Ok(parsed
2042            .resolved_in_sha
2043            .map(|s| s.trim().to_owned())
2044            .filter(|s| !s.is_empty())),
2045        Err(err) => Err(SlabError::bad_request(format!("invalid JSON body: {err}"))),
2046    }
2047}
2048
2049async fn list_incidents_handler(
2050    State(ctx): State<AppCtx>,
2051    headers: HeaderMap,
2052    Query(query): Query<ListIncidentsQuery>,
2053) -> Response {
2054    if let Err(status) = is_metrics_authorized(&ctx, &headers) {
2055        return status.into_response();
2056    }
2057
2058    let status = query.status.as_deref().unwrap_or("active");
2059    let limit = query.limit.unwrap_or(50);
2060    match ctx.incidents.list(Some(status), limit).await {
2061        Ok(rows) => {
2062            let enriched: Vec<Value> = rows.iter().map(enrich_incident_json).collect();
2063            (StatusCode::OK, Json(json!({ "incidents": enriched }))).into_response()
2064        }
2065        Err(err) => err.into_response(),
2066    }
2067}
2068
2069async fn get_incident_handler(
2070    State(ctx): State<AppCtx>,
2071    headers: HeaderMap,
2072    Path(id): Path<String>,
2073) -> Response {
2074    if let Err(status) = is_metrics_authorized(&ctx, &headers) {
2075        return status.into_response();
2076    }
2077
2078    match ctx.incidents.get(&id).await {
2079        Ok(Some(inc)) => (StatusCode::OK, Json(enrich_incident_detail_json(&inc))).into_response(),
2080        Ok(None) => SlabError::not_found("incident not found").into_response(),
2081        Err(err) => err.into_response(),
2082    }
2083}
2084
2085async fn resolve_incident_handler(
2086    State(ctx): State<AppCtx>,
2087    headers: HeaderMap,
2088    Path(id): Path<String>,
2089    body: Bytes,
2090) -> Response {
2091    if let Err(status) = is_metrics_authorized(&ctx, &headers) {
2092        return status.into_response();
2093    }
2094
2095    let resolved_in_sha = match parse_resolve_sha(&body) {
2096        Ok(sha) => sha,
2097        Err(err) => return err.into_response(),
2098    };
2099
2100    match ctx.incidents.resolve(&id, resolved_in_sha.as_deref()).await {
2101        Ok(true) => {
2102            if let Ok(Some(record)) = ctx.incidents.get(&id).await {
2103                spawn_incident_webhook(&ctx, "incident.resolved", &record);
2104            }
2105            (
2106                StatusCode::OK,
2107                Json(json!({
2108                    "id": id,
2109                    "status": "resolved",
2110                    "resolved_in_sha": resolved_in_sha,
2111                })),
2112            )
2113                .into_response()
2114        }
2115        Ok(false) => SlabError::not_found("incident not found").into_response(),
2116        Err(err) => err.into_response(),
2117    }
2118}
2119
2120async fn incident_attachment_handler(
2121    State(ctx): State<AppCtx>,
2122    headers: HeaderMap,
2123    Path((id, blob_id)): Path<(String, String)>,
2124) -> Response {
2125    if let Err(status) = is_metrics_authorized(&ctx, &headers) {
2126        return status.into_response();
2127    }
2128
2129    let incident = match ctx.incidents.get(&id).await {
2130        Ok(Some(inc)) => inc,
2131        Ok(None) => return SlabError::not_found("incident not found").into_response(),
2132        Err(err) => return err.into_response(),
2133    };
2134
2135    let attachments = parse_incident_attachments(&incident.context_json);
2136    if !attachments.iter().any(|att| att.blob_id == blob_id) {
2137        return SlabError::not_found("attachment not found for incident").into_response();
2138    }
2139
2140    match ctx.storage.get_scoped(&blob_id, Some("bug_report")).await {
2141        Ok(Some((meta, bytes))) => meta.into_safe_response(bytes, true),
2142        Ok(None) => SlabError::not_found("attachment not found for incident").into_response(),
2143        Err(err) => err.into_response(),
2144    }
2145}
2146
2147async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
2148    let sent = ctx.mail.list_sent(50).await?;
2149    Ok(Json(json!({ "emails": sent })))
2150}
2151
2152fn compute_etag(body: &str) -> HeaderValue {
2153    let digest = Sha256::digest(body.as_bytes());
2154    let tag = format!("\"{}\"", &hex::encode(digest)[..16]);
2155    HeaderValue::from_str(&tag).unwrap_or_else(|_| HeaderValue::from_static("\"0\""))
2156}
2157
2158fn vendor_response(
2159    req_headers: &HeaderMap,
2160    content_type: &'static str,
2161    body: &'static str,
2162    etag_cell: &'static OnceLock<HeaderValue>,
2163) -> Response {
2164    let etag = etag_cell.get_or_init(|| compute_etag(body)).clone();
2165    if req_headers
2166        .get(header::IF_NONE_MATCH)
2167        .and_then(|v| v.to_str().ok())
2168        .is_some_and(|v| v.trim() == etag.to_str().unwrap_or_default())
2169    {
2170        return (
2171            StatusCode::NOT_MODIFIED,
2172            [
2173                (
2174                    header::CACHE_CONTROL,
2175                    HeaderValue::from_static("public, max-age=86400"),
2176                ),
2177                (header::ETAG, etag),
2178            ],
2179        )
2180            .into_response();
2181    }
2182
2183    (
2184        StatusCode::OK,
2185        [
2186            (header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
2187            (
2188                header::CACHE_CONTROL,
2189                HeaderValue::from_static("public, max-age=86400"),
2190            ),
2191            (header::ETAG, etag),
2192        ],
2193        body,
2194    )
2195        .into_response()
2196}
2197
2198async fn vendor_basecoat_css(headers: HeaderMap) -> Response {
2199    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2200    vendor_response(&headers, "text/css; charset=utf-8", BASECOAT_CSS, &ETAG)
2201}
2202
2203async fn vendor_basecoat_js(headers: HeaderMap) -> Response {
2204    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2205    vendor_response(
2206        &headers,
2207        "text/javascript; charset=utf-8",
2208        include_str!("../assets/vendor/basecoat.min.js"),
2209        &ETAG,
2210    )
2211}
2212
2213async fn vendor_htmx_js(headers: HeaderMap) -> Response {
2214    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2215    vendor_response(
2216        &headers,
2217        "text/javascript; charset=utf-8",
2218        include_str!("../assets/vendor/htmx.min.js"),
2219        &ETAG,
2220    )
2221}
2222
2223async fn vendor_htmx_sse_js(headers: HeaderMap) -> Response {
2224    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2225    vendor_response(
2226        &headers,
2227        "text/javascript; charset=utf-8",
2228        include_str!("../assets/vendor/htmx-ext-sse.js"),
2229        &ETAG,
2230    )
2231}
2232
2233async fn vendor_idiomorph_js(headers: HeaderMap) -> Response {
2234    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2235    vendor_response(
2236        &headers,
2237        "text/javascript; charset=utf-8",
2238        include_str!("../assets/vendor/idiomorph-ext.min.js"),
2239        &ETAG,
2240    )
2241}
2242
2243async fn vendor_alpine_js(headers: HeaderMap) -> Response {
2244    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2245    vendor_response(
2246        &headers,
2247        "text/javascript; charset=utf-8",
2248        include_str!("../assets/vendor/alpine.min.js"),
2249        &ETAG,
2250    )
2251}
2252
2253async fn vendor_sw_register_js(headers: HeaderMap) -> Response {
2254    static ETAG: OnceLock<HeaderValue> = OnceLock::new();
2255    vendor_response(
2256        &headers,
2257        "text/javascript; charset=utf-8",
2258        slabs_html::SW_REGISTER_JS,
2259        &ETAG,
2260    )
2261}
2262
2263fn is_active_document_content_type(content_type: &str) -> bool {
2264    let mime = content_type
2265        .split(';')
2266        .next()
2267        .unwrap_or("")
2268        .trim()
2269        .to_ascii_lowercase();
2270    matches!(
2271        mime.as_str(),
2272        "image/svg+xml" | "text/html" | "application/xhtml+xml"
2273    )
2274}
2275
2276async fn serve_asset_handler(
2277    State(ctx): State<AppCtx>,
2278    Path((hash, path)): Path<(String, String)>,
2279) -> SlabResult<Response> {
2280    let Some(entry) = ctx.assets.get(&hash, &path) else {
2281        return Err(SlabError::not_found("asset not found"));
2282    };
2283    let ct = HeaderValue::from_str(&entry.content_type)
2284        .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
2285    let mut headers = HeaderMap::new();
2286    headers.insert(header::CONTENT_TYPE, ct);
2287    headers.insert(
2288        header::CACHE_CONTROL,
2289        HeaderValue::from_static("public, max-age=31536000, immutable"),
2290    );
2291    if is_active_document_content_type(&entry.content_type) {
2292        headers.insert(
2293            header::CONTENT_SECURITY_POLICY,
2294            HeaderValue::from_static("default-src 'none'; style-src 'unsafe-inline'; sandbox"),
2295        );
2296    }
2297    Ok((StatusCode::OK, headers, entry.bytes.clone()).into_response())
2298}
2299
2300#[cfg(test)]
2301mod tests {
2302    use super::*;
2303    use axum::body::Body;
2304    use http_body_util::BodyExt;
2305    use slabs_core::AppEnv;
2306    use std::path::PathBuf;
2307    use tower::ServiceExt;
2308
2309    async fn test_ctx(mut config: AppConfig) -> AppCtx {
2310        config.database_url = "sqlite::memory:".into();
2311        let ctx = AppCtx::connect(config).await.unwrap();
2312        ctx.db.init_system_tables().await.unwrap();
2313        ctx
2314    }
2315
2316    async fn send(router: &Router, req: http::Request<Body>) -> (StatusCode, HeaderMap, String) {
2317        let resp = router.clone().oneshot(req).await.unwrap();
2318        let status = resp.status();
2319        let headers = resp.headers().clone();
2320        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
2321        (status, headers, String::from_utf8_lossy(&bytes).to_string())
2322    }
2323
2324    #[tokio::test]
2325    async fn dev_routes_are_disabled_in_production_and_enabled_in_test() {
2326        let mut prod_cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_prod"));
2327        prod_cfg.env = AppEnv::Production;
2328        let prod_ctx = test_ctx(prod_cfg).await;
2329        let prod_router = build_router(prod_ctx, vec![], &[]);
2330
2331        for path in [
2332            "/_slabs/mail",
2333            "/_slabs/manifest",
2334            "/_slabs/openapi.json",
2335            "/_slabs/metrics",
2336        ] {
2337            let req = http::Request::builder()
2338                .uri(path)
2339                .body(Body::empty())
2340                .unwrap();
2341            let (status, _, _) = send(&prod_router, req).await;
2342            assert_eq!(status, StatusCode::NOT_FOUND, "{path} must be 404 in prod");
2343        }
2344
2345        let dev_cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_dev"));
2346        let dev_ctx = test_ctx(dev_cfg).await;
2347        let dev_router = build_router(dev_ctx, vec![], &[]);
2348
2349        for path in [
2350            "/_slabs/mail",
2351            "/_slabs/manifest",
2352            "/_slabs/openapi.json",
2353            "/_slabs/metrics",
2354        ] {
2355            let req = http::Request::builder()
2356                .uri(path)
2357                .body(Body::empty())
2358                .unwrap();
2359            let (status, _, _) = send(&dev_router, req).await;
2360            assert_eq!(status, StatusCode::OK, "{path} must be 200 in test");
2361        }
2362    }
2363
2364    #[tokio::test]
2365    async fn health_probes_and_draining_behavior() {
2366        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_health"));
2367        let ctx = test_ctx(cfg).await;
2368        let router = build_router(ctx.clone(), vec![], &[]);
2369
2370        let (status, _, _) = send(
2371            &router,
2372            http::Request::builder()
2373                .uri("/health")
2374                .body(Body::empty())
2375                .unwrap(),
2376        )
2377        .await;
2378        assert_eq!(status, StatusCode::OK);
2379
2380        let (status, _, _) = send(
2381            &router,
2382            http::Request::builder()
2383                .uri("/health/live")
2384                .body(Body::empty())
2385                .unwrap(),
2386        )
2387        .await;
2388        assert_eq!(status, StatusCode::OK);
2389
2390        let (status, _, _) = send(
2391            &router,
2392            http::Request::builder()
2393                .uri("/health/ready")
2394                .body(Body::empty())
2395                .unwrap(),
2396        )
2397        .await;
2398        assert_eq!(status, StatusCode::OK);
2399
2400        ctx.set_draining();
2401        let (status, _, _) = send(
2402            &router,
2403            http::Request::builder()
2404                .uri("/health/ready")
2405                .body(Body::empty())
2406                .unwrap(),
2407        )
2408        .await;
2409        assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
2410    }
2411
2412    #[tokio::test]
2413    async fn metrics_token_enforces_bearer_auth_and_supports_json_and_prometheus() {
2414        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_metrics"));
2415        cfg.env = AppEnv::Production;
2416        cfg.metrics_token = Some("super-secret-metrics-token".into());
2417        let ctx = test_ctx(cfg).await;
2418        let router = build_router(ctx, vec![], &[]);
2419
2420        // Missing token -> 401
2421        let (status, _, _) = send(
2422            &router,
2423            http::Request::builder()
2424                .uri("/_slabs/metrics")
2425                .body(Body::empty())
2426                .unwrap(),
2427        )
2428        .await;
2429        assert_eq!(status, StatusCode::UNAUTHORIZED);
2430
2431        // Wrong token -> 401
2432        let (status, _, _) = send(
2433            &router,
2434            http::Request::builder()
2435                .uri("/_slabs/metrics")
2436                .header(header::AUTHORIZATION, "Bearer wrong-token")
2437                .body(Body::empty())
2438                .unwrap(),
2439        )
2440        .await;
2441        assert_eq!(status, StatusCode::UNAUTHORIZED);
2442
2443        // Valid token -> Prometheus text
2444        let (status, _, body) = send(
2445            &router,
2446            http::Request::builder()
2447                .uri("/_slabs/metrics")
2448                .header(header::AUTHORIZATION, "Bearer super-secret-metrics-token")
2449                .body(Body::empty())
2450                .unwrap(),
2451        )
2452        .await;
2453        assert_eq!(status, StatusCode::OK);
2454        assert!(body.contains("slabs_http_requests_total"));
2455        assert!(body.contains("slabs_jobs_pending"));
2456        assert!(body.contains("slabs_realtime_active_topics"));
2457
2458        // Valid token + Accept: application/json -> JSON
2459        let (status, _, body) = send(
2460            &router,
2461            http::Request::builder()
2462                .uri("/_slabs/metrics")
2463                .header(header::AUTHORIZATION, "Bearer super-secret-metrics-token")
2464                .header(header::ACCEPT, "application/json")
2465                .body(Body::empty())
2466                .unwrap(),
2467        )
2468        .await;
2469        assert_eq!(status, StatusCode::OK);
2470        let parsed: Value = serde_json::from_str(&body).unwrap();
2471        assert!(parsed["http"]["requests_total"].as_u64().unwrap() >= 3);
2472    }
2473
2474    #[tokio::test]
2475    async fn csrf_middleware_blocks_cross_site_cookie_mutations_and_exempts_bearer_and_skip_csrf() {
2476        async fn ok_handler() -> &'static str {
2477            "ok"
2478        }
2479
2480        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_csrf"));
2481        let ctx = test_ctx(cfg).await;
2482        let router = build_router(
2483            ctx,
2484            vec![
2485                SlabDef::post("/api/items", ok_handler),
2486                // Webhook management endpoint without .skip_csrf() MUST remain CSRF-protected.
2487                SlabDef::post("/api/webhooks", ok_handler),
2488                // Inbound webhook receiver explicitly opts out via .skip_csrf().
2489                SlabDef::post("/webhooks/{provider}", ok_handler).skip_csrf(),
2490            ],
2491            &[],
2492        );
2493
2494        // Cross-site Fetch Metadata with Cookie -> 403
2495        let (status, _, _) = send(
2496            &router,
2497            http::Request::builder()
2498                .method(Method::POST)
2499                .uri("/api/items")
2500                .header(header::COOKIE, "slabs_session=abc")
2501                .header("sec-fetch-site", "cross-site")
2502                .body(Body::empty())
2503                .unwrap(),
2504        )
2505        .await;
2506        assert_eq!(status, StatusCode::FORBIDDEN);
2507
2508        // Webhook management route without skip_csrf() -> 403 on cross-site cookie POST
2509        let (status, _, _) = send(
2510            &router,
2511            http::Request::builder()
2512                .method(Method::POST)
2513                .uri("/api/webhooks")
2514                .header(header::COOKIE, "slabs_session=abc")
2515                .header("sec-fetch-site", "cross-site")
2516                .body(Body::empty())
2517                .unwrap(),
2518        )
2519        .await;
2520        assert_eq!(status, StatusCode::FORBIDDEN);
2521
2522        // Cross-origin Origin header with Cookie -> 403
2523        let (status, _, _) = send(
2524            &router,
2525            http::Request::builder()
2526                .method(Method::POST)
2527                .uri("/api/items")
2528                .header(header::COOKIE, "slabs_session=abc")
2529                .header(header::HOST, "app.example.com")
2530                .header(header::ORIGIN, "https://evil.test")
2531                .body(Body::empty())
2532                .unwrap(),
2533        )
2534        .await;
2535        assert_eq!(status, StatusCode::FORBIDDEN);
2536
2537        // Same-origin Origin header with Cookie -> 200
2538        let (status, _, _) = send(
2539            &router,
2540            http::Request::builder()
2541                .method(Method::POST)
2542                .uri("/api/items")
2543                .header(header::COOKIE, "slabs_session=abc")
2544                .header(header::HOST, "app.example.com")
2545                .header(header::ORIGIN, "https://app.example.com")
2546                .header("sec-fetch-site", "same-origin")
2547                .body(Body::empty())
2548                .unwrap(),
2549        )
2550        .await;
2551        assert_eq!(status, StatusCode::OK);
2552
2553        // Bearer auth exempt -> 200
2554        let (status, _, _) = send(
2555            &router,
2556            http::Request::builder()
2557                .method(Method::POST)
2558                .uri("/api/items")
2559                .header(header::COOKIE, "slabs_session=abc")
2560                .header(header::AUTHORIZATION, "Bearer slb_123")
2561                .header("sec-fetch-site", "cross-site")
2562                .body(Body::empty())
2563                .unwrap(),
2564        )
2565        .await;
2566        assert_eq!(status, StatusCode::OK);
2567
2568        // Explicit .skip_csrf() parameterized webhook receiver exempt -> 200
2569        let (status, _, _) = send(
2570            &router,
2571            http::Request::builder()
2572                .method(Method::POST)
2573                .uri("/webhooks/stripe")
2574                .header(header::COOKIE, "slabs_session=abc")
2575                .header("sec-fetch-site", "cross-site")
2576                .body(Body::empty())
2577                .unwrap(),
2578        )
2579        .await;
2580        assert_eq!(status, StatusCode::OK);
2581    }
2582
2583    #[tokio::test]
2584    async fn security_headers_cors_request_id_and_vendor_assets() {
2585        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_headers"));
2586        cfg.cookie_secure = true;
2587        let ctx = test_ctx(cfg).await;
2588        let router = build_router(ctx, vec![], &[]);
2589
2590        // Invalid X-Request-Id is replaced with a fresh req_ ULID
2591        let (status, headers, body) = send(
2592            &router,
2593            http::Request::builder()
2594                .uri("/_slabs/vendor/sw-register.js")
2595                .header("x-request-id", "bad id with spaces!")
2596                .body(Body::empty())
2597                .unwrap(),
2598        )
2599        .await;
2600        assert_eq!(status, StatusCode::OK);
2601        assert!(body.contains("navigator.serviceWorker.register(\"/sw.js\")"));
2602        assert!(headers.contains_key(header::ETAG));
2603        assert_eq!(
2604            headers
2605                .get(header::REFERRER_POLICY)
2606                .and_then(|v| v.to_str().ok()),
2607            Some("strict-origin-when-cross-origin")
2608        );
2609        assert_eq!(
2610            headers
2611                .get("permissions-policy")
2612                .and_then(|v| v.to_str().ok()),
2613            Some("camera=(), microphone=(), geolocation=()")
2614        );
2615        assert_eq!(
2616            headers
2617                .get(header::STRICT_TRANSPORT_SECURITY)
2618                .and_then(|v| v.to_str().ok()),
2619            Some("max-age=31536000; includeSubDomains")
2620        );
2621        // No permissive wildcard CORS when cors_origins is empty
2622        assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
2623        let req_id = headers
2624            .get("x-request-id")
2625            .and_then(|v| v.to_str().ok())
2626            .unwrap();
2627        assert!(req_id.starts_with("req_"));
2628
2629        // basecoat.min.css includes @view-transition rule and ETag
2630        let (status, headers, css) = send(
2631            &router,
2632            http::Request::builder()
2633                .uri("/_slabs/vendor/basecoat.min.css")
2634                .body(Body::empty())
2635                .unwrap(),
2636        )
2637        .await;
2638        assert_eq!(status, StatusCode::OK);
2639        assert!(css.starts_with("@view-transition { navigation: auto; }"));
2640        assert!(headers.contains_key(header::ETAG));
2641    }
2642
2643    #[tokio::test]
2644    async fn asset_handler_sandboxes_svg_and_html_with_csp() {
2645        let dir = std::env::temp_dir().join(format!("slabs_http_svg_{}", slabs_core::id::new("d")));
2646        std::fs::create_dir_all(&dir).unwrap();
2647        std::fs::write(dir.join("icon.svg"), "<svg></svg>").unwrap();
2648
2649        let mut cfg = AppConfig::for_test("demo", dir.clone());
2650        cfg.assets_dir = dir.clone();
2651        let ctx = test_ctx(cfg).await;
2652        let url = ctx.assets.url("icon.svg");
2653        let router = build_router(ctx, vec![], &[]);
2654
2655        let (status, headers, _) = send(
2656            &router,
2657            http::Request::builder()
2658                .uri(&url)
2659                .body(Body::empty())
2660                .unwrap(),
2661        )
2662        .await;
2663        assert_eq!(status, StatusCode::OK);
2664        assert_eq!(
2665            headers
2666                .get(header::CONTENT_SECURITY_POLICY)
2667                .and_then(|v| v.to_str().ok()),
2668            Some("default-src 'none'; style-src 'unsafe-inline'; sandbox")
2669        );
2670
2671        let _ = std::fs::remove_dir_all(&dir);
2672    }
2673
2674    #[test]
2675    fn client_ip_respects_trust_proxy_and_rightmost_xff() {
2676        let peer: SocketAddr = "10.0.0.5:12345".parse().unwrap();
2677        let mut headers = HeaderMap::new();
2678        headers.insert(
2679            "x-forwarded-for",
2680            HeaderValue::from_static("1.2.3.4, 203.0.113.9"),
2681        );
2682
2683        assert_eq!(client_ip(&headers, Some(peer), false), "10.0.0.5");
2684        assert_eq!(client_ip(&headers, Some(peer), true), "203.0.113.9");
2685
2686        headers.insert("cf-connecting-ip", HeaderValue::from_static("198.51.100.7"));
2687        assert_eq!(client_ip(&headers, Some(peer), true), "198.51.100.7");
2688    }
2689
2690    #[tokio::test]
2691    async fn client_ip_extractor_falls_back_in_tests_and_respects_trust_proxy() {
2692        async fn echo_ip(ClientIp(ip): ClientIp) -> String {
2693            ip
2694        }
2695
2696        // Without trust_proxy and without ConnectInfo -> falls back to 127.0.0.1
2697        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_client_ip"));
2698        let ctx = test_ctx(cfg).await;
2699        let router = build_router(ctx, vec![SlabDef::get("/ip", echo_ip)], &[]);
2700
2701        let (status, _, body) = send(
2702            &router,
2703            http::Request::builder()
2704                .uri("/ip")
2705                .header("cf-connecting-ip", "198.51.100.7")
2706                .body(Body::empty())
2707                .unwrap(),
2708        )
2709        .await;
2710        assert_eq!(status, StatusCode::OK);
2711        assert_eq!(body, "127.0.0.1");
2712
2713        // With ConnectInfo and trust_proxy = false -> uses socket peer address
2714        let mut req_with_peer = http::Request::builder()
2715            .uri("/ip")
2716            .header("x-forwarded-for", "203.0.113.9")
2717            .body(Body::empty())
2718            .unwrap();
2719        req_with_peer
2720            .extensions_mut()
2721            .insert(ConnectInfo::<SocketAddr>("10.0.0.5:4321".parse().unwrap()));
2722        let (status, _, body) = send(&router, req_with_peer).await;
2723        assert_eq!(status, StatusCode::OK);
2724        assert_eq!(body, "10.0.0.5");
2725
2726        // With trust_proxy = true -> honors CF-Connecting-IP / X-Forwarded-For
2727        let mut proxy_cfg =
2728            AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_client_ip_proxy"));
2729        proxy_cfg.trust_proxy = true;
2730        let proxy_ctx = test_ctx(proxy_cfg).await;
2731        let proxy_router = build_router(proxy_ctx, vec![SlabDef::get("/ip", echo_ip)], &[]);
2732
2733        let (status, _, body) = send(
2734            &proxy_router,
2735            http::Request::builder()
2736                .uri("/ip")
2737                .header("x-forwarded-for", "1.2.3.4, 203.0.113.9")
2738                .body(Body::empty())
2739                .unwrap(),
2740        )
2741        .await;
2742        assert_eq!(status, StatusCode::OK);
2743        assert_eq!(body, "203.0.113.9");
2744    }
2745
2746    #[test]
2747    fn rate_limiter_check_pair_enforces_both_ip_and_account_limits() {
2748        let rl = RateLimiter::new();
2749
2750        // Exhaust IP limit (2) across different accounts; third attempt fails on IP.
2751        rl.check_pair("ip:1.1.1.1", 2, "acct:a@example.com", 5, 60)
2752            .unwrap();
2753        rl.check_pair("ip:1.1.1.1", 2, "acct:b@example.com", 5, 60)
2754            .unwrap();
2755        let ip_err = rl
2756            .check_pair("ip:1.1.1.1", 2, "acct:c@example.com", 5, 60)
2757            .unwrap_err();
2758        assert_eq!(ip_err.status_code(), StatusCode::TOO_MANY_REQUESTS);
2759
2760        // Exhaust account limit (2) across different IPs; third attempt fails on account.
2761        rl.check_pair("ip:2.2.2.2", 5, "acct:victim@example.com", 2, 60)
2762            .unwrap();
2763        rl.check_pair("ip:3.3.3.3", 5, "acct:victim@example.com", 2, 60)
2764            .unwrap();
2765        let acct_err = rl
2766            .check_pair("ip:4.4.4.4", 5, "acct:victim@example.com", 2, 60)
2767            .unwrap_err();
2768        assert_eq!(acct_err.status_code(), StatusCode::TOO_MANY_REQUESTS);
2769
2770        // Blocked IP did not burn acct:c@example.com quota.
2771        rl.check_pair("ip:5.5.5.5", 5, "acct:c@example.com", 1, 60)
2772            .unwrap();
2773    }
2774
2775    #[tokio::test]
2776    async fn job_registry_dispatch_dead_letters_poison_pill_json_and_records_incident() {
2777        let received: Arc<Mutex<Vec<ReceivedWebhook>>> = Arc::new(Mutex::new(Vec::new()));
2778        let recv_clone = received.clone();
2779        let hook_app = Router::new().route(
2780            "/hook",
2781            post(move |headers: HeaderMap, body: Bytes| {
2782                let store = recv_clone.clone();
2783                async move {
2784                    let event = headers
2785                        .get("x-slabs-event")
2786                        .and_then(|v| v.to_str().ok())
2787                        .unwrap_or("")
2788                        .to_owned();
2789                    let sig = headers
2790                        .get("x-slabs-signature")
2791                        .and_then(|v| v.to_str().ok())
2792                        .map(ToOwned::to_owned);
2793                    store.lock().unwrap().push((event, sig, body));
2794                    StatusCode::OK
2795                }
2796            }),
2797        );
2798        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2799        let addr = listener.local_addr().unwrap();
2800        tokio::spawn(async move { axum::serve(listener, hook_app).await.unwrap() });
2801
2802        let secret = "whsec_poison_pill_secret";
2803        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_poison"));
2804        cfg.webhooks_allow_local = true;
2805        cfg.incident_webhook_url = Some(format!("http://{addr}/hook"));
2806        cfg.incident_webhook_secret = Some(secret.into());
2807        let ctx = test_ctx(cfg).await;
2808        let job_id = ctx
2809            .jobs
2810            .enqueue("demo.job", json!({ "ok": true }))
2811            .await
2812            .unwrap();
2813        // Corrupt payload_json directly in SQLite to simulate a poison pill
2814        let mut tx = ctx.db.begin().await.unwrap();
2815        sqlx::query("UPDATE slabs_jobs SET payload_json = '{not-json' WHERE id = ?")
2816            .bind(&job_id)
2817            .execute(&mut *tx)
2818            .await
2819            .unwrap();
2820        tx.commit().await.unwrap();
2821
2822        let registry = JobRegistry::new(vec![JobDef::new("demo.job", |_ctx, _v| async { Ok(()) })]);
2823        let claimed = ctx.jobs.claim_next().await.unwrap().unwrap();
2824        assert!(registry.dispatch(&ctx, &claimed).await.is_err());
2825
2826        let stats = ctx.jobs.stats().await.unwrap();
2827        assert_eq!(stats.dead, 1);
2828        assert_eq!(stats.running, 0);
2829
2830        let incidents = ctx.incidents.list(Some("active"), 10).await.unwrap();
2831        assert_eq!(incidents.len(), 1);
2832        assert_eq!(incidents[0].kind, "job_dead");
2833        assert_eq!(incidents[0].source_file, "jobs/demo.job.rs");
2834        assert_eq!(incidents[0].route_pattern.as_deref(), Some("demo.job"));
2835
2836        // Signed incident.opened webhook fires for the dead-lettered poison pill
2837        for _ in 0..40 {
2838            if !received.lock().unwrap().is_empty() {
2839                break;
2840            }
2841            tokio::time::sleep(Duration::from_millis(25)).await;
2842        }
2843        let events = received.lock().unwrap().clone();
2844        assert_eq!(events.len(), 1);
2845        assert_eq!(events[0].0, "incident.opened");
2846        let expected_sig = sign_incident_webhook(secret, &events[0].2);
2847        assert_eq!(events[0].1.as_deref(), Some(expected_sig.as_str()));
2848    }
2849
2850    #[tokio::test]
2851    async fn middleware_captures_panics_5xx_slow_requests_and_route_histograms() {
2852        async fn panic_handler() -> &'static str {
2853            panic!("boom in room handler")
2854        }
2855
2856        async fn err_5xx_handler() -> SlabResult<&'static str> {
2857            Err(SlabError::internal("db connection lost"))
2858        }
2859
2860        async fn slow_handler() -> &'static str {
2861            tokio::time::sleep(Duration::from_millis(25)).await;
2862            "slow ok"
2863        }
2864
2865        async fn fast_handler() -> &'static str {
2866            "fast ok"
2867        }
2868
2869        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_incidents"));
2870        cfg.slow_request_ms = 15;
2871        cfg.git_sha = Some("sha_abc123".into());
2872        let ctx = test_ctx(cfg).await;
2873
2874        let router = build_router(
2875            ctx.clone(),
2876            vec![
2877                SlabDef::get("/api/rooms/{room_id}/boom", panic_handler).name("rooms::boom"),
2878                SlabDef::get("/api/rooms/{room_id}/fail", err_5xx_handler).name("rooms::fail"),
2879                SlabDef::get("/api/rooms/{room_id}/slow", slow_handler).name("rooms::slow"),
2880                SlabDef::get("/api/rooms/{room_id}/fast", fast_handler).name("rooms::fast"),
2881            ],
2882            &[],
2883        );
2884
2885        // 1. Panic is caught and returns clean 500 JSON
2886        let (status, _, body) = send(
2887            &router,
2888            http::Request::builder()
2889                .uri("/api/rooms/room_42/boom")
2890                .body(Body::empty())
2891                .unwrap(),
2892        )
2893        .await;
2894        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
2895        let panic_body: Value = serde_json::from_str(&body).unwrap();
2896        assert_eq!(panic_body["error"], "internal server error");
2897
2898        // 2. 5xx error is recorded
2899        let (status, _, _) = send(
2900            &router,
2901            http::Request::builder()
2902                .uri("/api/rooms/room_42/fail")
2903                .body(Body::empty())
2904                .unwrap(),
2905        )
2906        .await;
2907        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
2908
2909        // 3. Slow request is recorded
2910        let (status, _, _) = send(
2911            &router,
2912            http::Request::builder()
2913                .uri("/api/rooms/room_42/slow")
2914                .body(Body::empty())
2915                .unwrap(),
2916        )
2917        .await;
2918        assert_eq!(status, StatusCode::OK);
2919
2920        // 4. Fast request does not create an incident
2921        let (status, _, _) = send(
2922            &router,
2923            http::Request::builder()
2924                .uri("/api/rooms/room_42/fast")
2925                .body(Body::empty())
2926                .unwrap(),
2927        )
2928        .await;
2929        assert_eq!(status, StatusCode::OK);
2930
2931        // Inspect via GET /_slabs/incidents
2932        let (status, _, body) = send(
2933            &router,
2934            http::Request::builder()
2935                .uri("/_slabs/incidents?status=open&limit=20")
2936                .body(Body::empty())
2937                .unwrap(),
2938        )
2939        .await;
2940        assert_eq!(status, StatusCode::OK);
2941        let parsed: Value = serde_json::from_str(&body).unwrap();
2942        let incidents = parsed["incidents"].as_array().unwrap();
2943        assert_eq!(incidents.len(), 3, "got incidents: {incidents:?}");
2944
2945        let panic_inc = incidents.iter().find(|i| i["kind"] == "panic").unwrap();
2946        assert_eq!(panic_inc["source_file"], "slabs/rooms/boom.rs");
2947        assert_eq!(panic_inc["route_pattern"], "/api/rooms/{room_id}/boom");
2948        assert_eq!(panic_inc["status_code"], 500);
2949        assert_eq!(panic_inc["git_sha"], "sha_abc123");
2950        assert!(panic_inc["repro_hint"]
2951            .as_str()
2952            .unwrap()
2953            .contains("slabs/rooms/boom.rs"));
2954
2955        let http_5xx_inc = incidents.iter().find(|i| i["kind"] == "http_5xx").unwrap();
2956        assert_eq!(http_5xx_inc["source_file"], "slabs/rooms/fail.rs");
2957        assert_eq!(http_5xx_inc["route_pattern"], "/api/rooms/{room_id}/fail");
2958
2959        let slow_inc = incidents
2960            .iter()
2961            .find(|i| i["kind"] == "slow_request")
2962            .unwrap();
2963        assert_eq!(slow_inc["source_file"], "slabs/rooms/slow.rs");
2964        assert_eq!(slow_inc["route_pattern"], "/api/rooms/{room_id}/slow");
2965
2966        // Fetch single incident by ID and check repro_hint + repro_test, then resolve it
2967        let panic_id = panic_inc["id"].as_str().unwrap();
2968        let (status, _, body) = send(
2969            &router,
2970            http::Request::builder()
2971                .uri(format!("/_slabs/incidents/{panic_id}"))
2972                .body(Body::empty())
2973                .unwrap(),
2974        )
2975        .await;
2976        assert_eq!(status, StatusCode::OK);
2977        let single: Value = serde_json::from_str(&body).unwrap();
2978        assert_eq!(single["id"], panic_id);
2979        assert!(single["repro_hint"].as_str().is_some());
2980        let repro_test = single["repro_test"].as_str().expect("repro_test string");
2981        assert!(repro_test.contains("#[tokio::test]"));
2982        assert!(repro_test.contains("crate::test_app().await"));
2983        assert!(repro_test.contains("/api/rooms/{room_id}/boom"));
2984        assert!(repro_test.contains("slabs/rooms/boom.rs"));
2985
2986        let (status, _, _) = send(
2987            &router,
2988            http::Request::builder()
2989                .method(Method::POST)
2990                .uri(format!("/_slabs/incidents/{panic_id}/resolve"))
2991                .header(header::CONTENT_TYPE, "application/json")
2992                .body(Body::from(r#"{"resolved_in_sha":"sha_fix_999"}"#))
2993                .unwrap(),
2994        )
2995        .await;
2996        assert_eq!(status, StatusCode::OK);
2997
2998        // Metrics JSON returns routes sorted by p95_ms DESC and open_incidents = 2
2999        let (status, _, body) = send(
3000            &router,
3001            http::Request::builder()
3002                .uri("/_slabs/metrics")
3003                .header(header::ACCEPT, "application/json")
3004                .body(Body::empty())
3005                .unwrap(),
3006        )
3007        .await;
3008        assert_eq!(status, StatusCode::OK);
3009        let metrics_json: Value = serde_json::from_str(&body).unwrap();
3010        assert_eq!(metrics_json["open_incidents"], 2);
3011        let route_metrics = metrics_json["routes"].as_array().unwrap();
3012        let slow_route = route_metrics
3013            .iter()
3014            .find(|r| r["route"] == "/api/rooms/{room_id}/slow")
3015            .unwrap();
3016        assert_eq!(slow_route["source_file"], "slabs/rooms/slow.rs");
3017        assert_eq!(slow_route["slow_requests"], 1);
3018        assert!(slow_route["p95_ms"].as_u64().unwrap() >= 15);
3019        assert!(slow_route["max_latency_ms"].as_u64().unwrap() >= 15);
3020
3021        // Metrics Prometheus text exposes per-route and incident gauges
3022        let (status, _, prom) = send(
3023            &router,
3024            http::Request::builder()
3025                .uri("/_slabs/metrics")
3026                .body(Body::empty())
3027                .unwrap(),
3028        )
3029        .await;
3030        assert_eq!(status, StatusCode::OK);
3031        assert!(prom.contains("slabs_incidents_open 2"));
3032        assert!(prom.contains("slabs_route_requests_total"));
3033        assert!(prom.contains("slabs_route_slow_total"));
3034        assert!(prom.contains("slabs_route_p95_ms"));
3035    }
3036
3037    type ReceivedWebhook = (String, Option<String>, Bytes);
3038
3039    #[tokio::test]
3040    async fn incidents_api_enforces_observability_auth_gate_without_cookie_bypass() {
3041        let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_inc_auth"));
3042        cfg.env = AppEnv::Production;
3043        let ctx_no_tok = test_ctx(cfg.clone()).await;
3044        let router_no_tok = build_router(ctx_no_tok.clone(), vec![], &[]);
3045
3046        // Even an admin session cookie does NOT bypass Bearer token auth in production
3047        let (_, admin_c) = ctx_no_tok
3048            .auth
3049            .create_session("usr_admin", "admin", 7)
3050            .await
3051            .unwrap();
3052        let admin_cookie = format!("{}={}", admin_c.name(), admin_c.value());
3053
3054        for path in [
3055            "/_slabs/incidents",
3056            "/_slabs/incidents/inc_1",
3057            "/_slabs/incidents/inc_1/attachments/blob_1",
3058        ] {
3059            let (status, _, _) = send(
3060                &router_no_tok,
3061                http::Request::builder()
3062                    .uri(path)
3063                    .header(header::COOKIE, &admin_cookie)
3064                    .body(Body::empty())
3065                    .unwrap(),
3066            )
3067            .await;
3068            assert_eq!(
3069                status,
3070                StatusCode::NOT_FOUND,
3071                "{path} must be 404 in prod without token"
3072            );
3073        }
3074
3075        cfg.metrics_token = Some("incident-secret-token".into());
3076        let ctx_tok = test_ctx(cfg).await;
3077        let router_tok = build_router(ctx_tok, vec![], &[]);
3078
3079        let (status, _, _) = send(
3080            &router_tok,
3081            http::Request::builder()
3082                .uri("/_slabs/incidents")
3083                .body(Body::empty())
3084                .unwrap(),
3085        )
3086        .await;
3087        assert_eq!(status, StatusCode::UNAUTHORIZED);
3088
3089        let (status, _, _) = send(
3090            &router_tok,
3091            http::Request::builder()
3092                .uri("/_slabs/incidents")
3093                .header(header::AUTHORIZATION, "Bearer incident-secret-token")
3094                .body(Body::empty())
3095                .unwrap(),
3096        )
3097        .await;
3098        assert_eq!(status, StatusCode::OK);
3099    }
3100
3101    #[tokio::test]
3102    async fn removed_v04_endpoints_and_vendor_scripts_return_not_found() {
3103        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_removed"));
3104        let ctx = test_ctx(cfg).await;
3105        let router = build_router(ctx, vec![], &[]);
3106
3107        for (method, path) in [
3108            (Method::GET, "/_slabs/incidents/ui"),
3109            (Method::POST, "/_slabs/incidents/inc_1/claim"),
3110            (Method::POST, "/_slabs/incidents/inc_1/link"),
3111            (Method::POST, "/_slabs/incidents/inc_1/ignore"),
3112            (Method::POST, "/_slabs/bug-reports"),
3113            (Method::POST, "/_slabs/client-errors"),
3114            (Method::GET, "/_slabs/vendor/slabs-telemetry.js"),
3115            (Method::GET, "/_slabs/vendor/slabs-bug-report.js"),
3116        ] {
3117            let (status, _, _) = send(
3118                &router,
3119                http::Request::builder()
3120                    .method(method.clone())
3121                    .uri(path)
3122                    .body(Body::empty())
3123                    .unwrap(),
3124            )
3125            .await;
3126            assert_eq!(
3127                status,
3128                StatusCode::NOT_FOUND,
3129                "{method} {path} should be removed in v0.4.0"
3130            );
3131        }
3132    }
3133
3134    #[tokio::test]
3135    async fn incident_inbox_supports_open_resolved_reopened_lifecycle_and_repro_test() {
3136        let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_lifecycle"));
3137        let ctx = test_ctx(cfg).await;
3138        let router = build_router(ctx.clone(), vec![], &[]);
3139
3140        let input = IncidentInput {
3141            kind: "http_5xx".into(),
3142            source_file: "slabs/orders/pay.rs".into(),
3143            route_pattern: Some("/api/orders/{order_id}/pay".into()),
3144            status_code: Some(500),
3145            error_message: "card declined upstream".into(),
3146            detail: Some("provider 502".into()),
3147            context_json: json!({ "method": "POST", "request_id": "req_a" }),
3148            git_sha: Some("sha_1111".into()),
3149            custom_fingerprint: None,
3150        };
3151        let rec = record_and_notify_incident(&ctx, input.clone())
3152            .await
3153            .unwrap();
3154        assert_eq!(rec.status, "open");
3155
3156        // Default GET /_slabs/incidents lists active (open + reopened)
3157        let (status, _, body) = send(
3158            &router,
3159            http::Request::builder()
3160                .uri("/_slabs/incidents")
3161                .body(Body::empty())
3162                .unwrap(),
3163        )
3164        .await;
3165        assert_eq!(status, StatusCode::OK);
3166        let active: Value = serde_json::from_str(&body).unwrap();
3167        assert_eq!(active["incidents"].as_array().unwrap().len(), 1);
3168        assert_eq!(active["incidents"][0]["status"], "open");
3169
3170        // Detail endpoint includes ready-to-paste repro_test targeting method, route_pattern, and source_file
3171        let (status, _, body) = send(
3172            &router,
3173            http::Request::builder()
3174                .uri(format!("/_slabs/incidents/{}", rec.id))
3175                .body(Body::empty())
3176                .unwrap(),
3177        )
3178        .await;
3179        assert_eq!(status, StatusCode::OK);
3180        let detail: Value = serde_json::from_str(&body).unwrap();
3181        let repro_test = detail["repro_test"].as_str().unwrap();
3182        assert!(repro_test.contains("#[tokio::test]"));
3183        assert!(repro_test.contains("crate::test_app().await"));
3184        assert!(repro_test.contains("post_json"));
3185        assert!(repro_test.contains("/api/orders/{order_id}/pay"));
3186        assert!(repro_test.contains("slabs/orders/pay.rs"));
3187
3188        // Resolve via JSON
3189        let (status, _, body) = send(
3190            &router,
3191            http::Request::builder()
3192                .method(Method::POST)
3193                .uri(format!("/_slabs/incidents/{}/resolve", rec.id))
3194                .header(header::CONTENT_TYPE, "application/json")
3195                .body(Body::from(r#"{"resolved_in_sha":"sha_fix_1"}"#))
3196                .unwrap(),
3197        )
3198        .await;
3199        assert_eq!(status, StatusCode::OK);
3200        let resolved: Value = serde_json::from_str(&body).unwrap();
3201        assert_eq!(resolved["status"], "resolved");
3202        assert_eq!(resolved["resolved_in_sha"], "sha_fix_1");
3203
3204        // Active inbox is now empty; status=resolved contains it
3205        let (status, _, body) = send(
3206            &router,
3207            http::Request::builder()
3208                .uri("/_slabs/incidents")
3209                .body(Body::empty())
3210                .unwrap(),
3211        )
3212        .await;
3213        assert_eq!(status, StatusCode::OK);
3214        assert_eq!(
3215            serde_json::from_str::<Value>(&body).unwrap()["incidents"],
3216            json!([])
3217        );
3218
3219        let (status, _, body) = send(
3220            &router,
3221            http::Request::builder()
3222                .uri("/_slabs/incidents?status=resolved")
3223                .body(Body::empty())
3224                .unwrap(),
3225        )
3226        .await;
3227        assert_eq!(status, StatusCode::OK);
3228        assert_eq!(
3229            serde_json::from_str::<Value>(&body).unwrap()["incidents"]
3230                .as_array()
3231                .unwrap()
3232                .len(),
3233            1
3234        );
3235
3236        // Recurrence after resolve transitions status -> reopened and shows in active & reopened
3237        let reopened_rec = record_and_notify_incident(&ctx, input).await.unwrap();
3238        assert_eq!(reopened_rec.status, "reopened");
3239
3240        let (status, _, body) = send(
3241            &router,
3242            http::Request::builder()
3243                .uri("/_slabs/incidents")
3244                .body(Body::empty())
3245                .unwrap(),
3246        )
3247        .await;
3248        assert_eq!(status, StatusCode::OK);
3249        let active_after: Value = serde_json::from_str(&body).unwrap();
3250        assert_eq!(active_after["incidents"].as_array().unwrap().len(), 1);
3251        assert_eq!(active_after["incidents"][0]["status"], "reopened");
3252
3253        let (status, _, body) = send(
3254            &router,
3255            http::Request::builder()
3256                .uri("/_slabs/incidents?status=reopened")
3257                .body(Body::empty())
3258                .unwrap(),
3259        )
3260        .await;
3261        assert_eq!(status, StatusCode::OK);
3262        assert_eq!(
3263            serde_json::from_str::<Value>(&body).unwrap()["incidents"]
3264                .as_array()
3265                .unwrap()
3266                .len(),
3267            1
3268        );
3269    }
3270
3271    #[tokio::test]
3272    async fn incident_attachment_download_serves_scoped_blobs_and_blocks_idor() {
3273        let storage_dir = std::env::temp_dir().join(format!(
3274            "slabs_http_inc_attach_{}",
3275            slabs_core::id::new("d")
3276        ));
3277        let cfg = AppConfig::for_test("demo", storage_dir.clone());
3278        let ctx = test_ctx(cfg).await;
3279        let router = build_router(ctx.clone(), vec![], &[]);
3280
3281        let png_meta = ctx
3282            .storage
3283            .put_scoped(
3284                "bug_report",
3285                "screenshot.png",
3286                Some("image/png"),
3287                b"\x89PNG\r\n\x1a\nfake-png-payload",
3288            )
3289            .await
3290            .unwrap();
3291        let html_meta = ctx
3292            .storage
3293            .put_scoped(
3294                "bug_report",
3295                "repro.html",
3296                Some("text/html"),
3297                b"<html><script>alert(1)</script></html>",
3298            )
3299            .await
3300            .unwrap();
3301        let unrelated = ctx
3302            .storage
3303            .put(
3304                "secret.txt",
3305                Some("text/plain"),
3306                Bytes::from_static(b"top-secret"),
3307            )
3308            .await
3309            .unwrap();
3310
3311        let (inc, _) = ctx
3312            .incidents
3313            .record(IncidentInput {
3314                kind: "user_bug_report".into(),
3315                source_file: "slabs/rooms/show.rs".into(),
3316                route_pattern: Some("/rooms/123".into()),
3317                status_code: None,
3318                error_message: "Button freezes".into(),
3319                detail: None,
3320                context_json: json!({
3321                    "attachments": [
3322                        { "blob_id": png_meta.id, "filename": "screenshot.png" },
3323                        { "blob_id": html_meta.id, "filename": "repro.html" },
3324                    ]
3325                }),
3326                git_sha: None,
3327                custom_fingerprint: Some(slabs_core::id::new("bug")),
3328            })
3329            .await
3330            .unwrap();
3331
3332        // PNG served inline with sandbox CSP
3333        let (status, headers, raw_png) = send(
3334            &router,
3335            http::Request::builder()
3336                .uri(format!(
3337                    "/_slabs/incidents/{}/attachments/{}",
3338                    inc.id, png_meta.id
3339                ))
3340                .body(Body::empty())
3341                .unwrap(),
3342        )
3343        .await;
3344        assert_eq!(status, StatusCode::OK);
3345        assert_eq!(
3346            headers
3347                .get(header::CONTENT_TYPE)
3348                .and_then(|v| v.to_str().ok()),
3349            Some("image/png")
3350        );
3351        assert!(headers
3352            .get(header::CONTENT_DISPOSITION)
3353            .and_then(|v| v.to_str().ok())
3354            .unwrap()
3355            .starts_with("inline;"));
3356        assert_eq!(
3357            headers
3358                .get(header::CONTENT_SECURITY_POLICY)
3359                .and_then(|v| v.to_str().ok()),
3360            Some("default-src 'none'; sandbox")
3361        );
3362        assert!(raw_png.contains("fake-png-payload"));
3363
3364        // Active HTML forced to attachment disposition with sandbox CSP
3365        let (status, headers, _) = send(
3366            &router,
3367            http::Request::builder()
3368                .uri(format!(
3369                    "/_slabs/incidents/{}/attachments/{}",
3370                    inc.id, html_meta.id
3371                ))
3372                .body(Body::empty())
3373                .unwrap(),
3374        )
3375        .await;
3376        assert_eq!(status, StatusCode::OK);
3377        assert!(headers
3378            .get(header::CONTENT_DISPOSITION)
3379            .and_then(|v| v.to_str().ok())
3380            .unwrap()
3381            .starts_with("attachment;"));
3382        assert_eq!(
3383            headers
3384                .get(header::CONTENT_SECURITY_POLICY)
3385                .and_then(|v| v.to_str().ok()),
3386            Some("default-src 'none'; sandbox")
3387        );
3388
3389        // Unrelated blob cannot be downloaded via incident attachment URL (IDOR blocked)
3390        let (status, _, _) = send(
3391            &router,
3392            http::Request::builder()
3393                .uri(format!(
3394                    "/_slabs/incidents/{}/attachments/{}",
3395                    inc.id, unrelated.id
3396                ))
3397                .body(Body::empty())
3398                .unwrap(),
3399        )
3400        .await;
3401        assert_eq!(status, StatusCode::NOT_FOUND);
3402
3403        let _ = std::fs::remove_dir_all(&storage_dir);
3404    }
3405
3406    #[tokio::test]
3407    async fn signed_incident_protocol_webhooks_fire_on_opened_resolved_and_reopened() {
3408        let received: Arc<Mutex<Vec<ReceivedWebhook>>> = Arc::new(Mutex::new(Vec::new()));
3409        let recv_clone = received.clone();
3410
3411        let hook_app = Router::new().route(
3412            "/hook",
3413            post(move |headers: HeaderMap, body: Bytes| {
3414                let store = recv_clone.clone();
3415                async move {
3416                    let event = headers
3417                        .get("x-slabs-event")
3418                        .and_then(|v| v.to_str().ok())
3419                        .unwrap_or("")
3420                        .to_owned();
3421                    let sig = headers
3422                        .get("x-slabs-signature")
3423                        .and_then(|v| v.to_str().ok())
3424                        .map(ToOwned::to_owned);
3425                    store.lock().unwrap().push((event, sig, body));
3426                    StatusCode::OK
3427                }
3428            }),
3429        );
3430        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3431        let addr = listener.local_addr().unwrap();
3432        tokio::spawn(async move { axum::serve(listener, hook_app).await.unwrap() });
3433
3434        let secret = "whsec_incident_signing_secret";
3435        let storage_dir =
3436            std::env::temp_dir().join(format!("slabs_http_webhooks_{}", slabs_core::id::new("d")));
3437        let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
3438        cfg.webhooks_allow_local = true;
3439        cfg.incident_webhook_url = Some(format!("http://{addr}/hook"));
3440        cfg.incident_webhook_secret = Some(secret.into());
3441        let ctx = test_ctx(cfg).await;
3442        let router = build_router(ctx.clone(), vec![], &[]);
3443
3444        let input = IncidentInput {
3445            kind: "http_5xx".into(),
3446            source_file: "slabs/orders/create.rs".into(),
3447            route_pattern: Some("/api/orders".into()),
3448            status_code: Some(500),
3449            error_message: "payment timeout".into(),
3450            detail: None,
3451            context_json: json!({ "request_id": "req_1" }),
3452            git_sha: Some("sha_v1".into()),
3453            custom_fingerprint: None,
3454        };
3455
3456        // 1. Opened -> fires incident.opened
3457        let rec = record_and_notify_incident(&ctx, input.clone())
3458            .await
3459            .unwrap();
3460        // 2. Duplicate while open -> Incremented, must NOT fire another webhook
3461        let _ = record_and_notify_incident(&ctx, input.clone())
3462            .await
3463            .unwrap();
3464
3465        // 3. Resolve via HTTP -> fires incident.resolved
3466        let (status, _, _) = send(
3467            &router,
3468            http::Request::builder()
3469                .method(Method::POST)
3470                .uri(format!("/_slabs/incidents/{}/resolve", rec.id))
3471                .header(header::CONTENT_TYPE, "application/json")
3472                .body(Body::from(r#"{"resolved_in_sha":"sha_v2"}"#))
3473                .unwrap(),
3474        )
3475        .await;
3476        assert_eq!(status, StatusCode::OK);
3477
3478        // 4. Recurrence after resolve -> fires incident.reopened
3479        let reopened = record_and_notify_incident(&ctx, input).await.unwrap();
3480        assert_eq!(reopened.status, "reopened");
3481
3482        // Wait briefly for spawned webhook tasks to complete
3483        for _ in 0..40 {
3484            if received.lock().unwrap().len() >= 3 {
3485                break;
3486            }
3487            tokio::time::sleep(Duration::from_millis(25)).await;
3488        }
3489
3490        let events = received.lock().unwrap().clone();
3491        assert_eq!(
3492            events.len(),
3493            3,
3494            "expected 3 webhook deliveries, got {events:?}"
3495        );
3496
3497        let event_names: Vec<&str> = events.iter().map(|(e, _, _)| e.as_str()).collect();
3498        assert!(event_names.contains(&"incident.opened"));
3499        assert!(event_names.contains(&"incident.resolved"));
3500        assert!(event_names.contains(&"incident.reopened"));
3501
3502        for (event_hdr, sig_hdr, raw_body) in &events {
3503            let expected_sig = sign_incident_webhook(secret, raw_body);
3504            assert_eq!(sig_hdr.as_deref(), Some(expected_sig.as_str()));
3505            let payload: Value = serde_json::from_slice(raw_body).unwrap();
3506            assert_eq!(payload["protocol"], "slabs.incident.v1");
3507            assert_eq!(payload["event"], event_hdr.as_str());
3508            assert!(payload["sent_at"].as_str().is_some());
3509            assert_eq!(payload["incident"]["id"], rec.id);
3510        }
3511
3512        let _ = std::fs::remove_dir_all(&storage_dir);
3513    }
3514}