use axum::{
body::Bytes,
extract::{
ConnectInfo, DefaultBodyLimit, FromRequestParts, MatchedPath, Multipart, Path, Query,
Request, State,
},
handler::Handler,
http::{header, HeaderMap, HeaderName, HeaderValue, Method, StatusCode, Uri},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::{delete, get, patch, post, put, MethodRouter},
Json, Router,
};
use axum_extra::extract::CookieJar;
use chrono::{SecondsFormat, Utc};
use futures_util::{future::BoxFuture, FutureExt as _};
use hmac::{Hmac, Mac as _};
use serde::Deserialize;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use slabs_assets::Assets;
use slabs_auth::Auth;
use slabs_cache::Cache;
use slabs_core::{AppConfig, AppManifest, JobMeta, RouteMeta, SlabError, SlabResult};
use slabs_db::{AuditLog, Db, IncidentInput, IncidentOutcome, IncidentRecord, Incidents};
use slabs_jobs::{JobRecord, Jobs};
use slabs_mail::{MailTransport, Mailer};
use slabs_realtime::Realtime;
use slabs_storage::{S3Config, Storage, StorageBackend};
use slabs_webhooks::Webhooks;
use std::collections::{btree_map::Entry, BTreeMap, HashMap, HashSet};
use std::fmt::{self, Write as _};
use std::future::Future;
use std::net::{IpAddr, SocketAddr};
use std::panic::AssertUnwindSafe;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio::sync::watch;
use tokio::task::JoinHandle;
use tower_http::{
compression::CompressionLayer,
cors::{AllowOrigin, CorsLayer},
limit::RequestBodyLimitLayer,
request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},
set_header::SetResponseHeaderLayer,
trace::TraceLayer,
};
type HmacSha256 = Hmac<Sha256>;
const MAX_RATE_LIMIT_ENTRIES: usize = 50_000;
const RATE_LIMIT_PRUNE_INTERVAL: Duration = Duration::from_secs(5);
const MAX_CLIENT_ERROR_BYTES: usize = 4 * 1024;
const MIN_BUG_DESCRIPTION_CHARS: usize = 3;
const MAX_BUG_DESCRIPTION_CHARS: usize = 4_000;
const MAX_BUG_SOURCE_FILE_CHARS: usize = 200;
const MAX_BUG_METADATA_BYTES: usize = 16 * 1024;
const MAX_BUG_SCREENSHOT_BYTES: usize = 5 * 1024 * 1024;
const MAX_BUG_ATTACHMENT_BYTES: usize = 5 * 1024 * 1024;
const MAX_BUG_ATTACHMENTS: usize = 3;
const INCIDENT_PROTOCOL_VERSION: &str = "slabs.incident.v1";
const MAX_TRACKED_ROUTES: usize = 2048;
const LATENCY_BUCKETS_MS: [u64; 8] = [10, 25, 50, 100, 250, 500, 1000, 2500];
const BASECOAT_CSS: &str = concat!(
"@view-transition { navigation: auto; }\n",
include_str!("../assets/vendor/basecoat.min.css")
);
const SLABS_TELEMETRY_JS: &str = r#"(function () {
if (typeof window === "undefined" || window.__slabsTelemetryInstalled) return;
window.__slabsTelemetryInstalled = true;
function report(kind, message, detail) {
try {
var body = JSON.stringify({
kind: kind,
message: String(message || "client error").slice(0, 512),
path: window.location ? window.location.pathname : "/",
detail: detail ? String(detail).slice(0, 1024) : null
});
if (navigator.sendBeacon) {
navigator.sendBeacon("/_slabs/client-errors", new Blob([body], { type: "application/json" }));
}
} catch (_) {}
}
window.addEventListener("error", function (e) {
var loc = e.filename ? e.filename + ":" + e.lineno + ":" + e.colno : null;
report("onerror", e.message || "Script error", loc);
});
window.addEventListener("unhandledrejection", function (e) {
var r = e.reason;
report("unhandledrejection", (r && r.message) || String(r || "Unhandled promise rejection"), r && r.stack);
});
["htmx:targetError", "htmx:swapError"].forEach(function (ev) {
document.addEventListener(ev, function (e) {
var d = e.detail || {};
report(ev, d.error || ev, d.target ? String(d.target) : null);
});
});
})();
"#;
#[derive(Clone, Default)]
struct MakeUlidRequestId;
impl MakeRequestId for MakeUlidRequestId {
fn make_request_id<B>(&mut self, _request: &http::Request<B>) -> Option<RequestId> {
let id = slabs_core::id::new("req");
HeaderValue::from_str(&id).ok().map(RequestId::new)
}
}
#[derive(Debug)]
struct RateLimiterState {
buckets: HashMap<String, (u64, Instant)>,
last_prune: Instant,
}
impl Default for RateLimiterState {
fn default() -> Self {
Self {
buckets: HashMap::new(),
last_prune: Instant::now(),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct RateLimiter {
state: Arc<Mutex<RateLimiterState>>,
}
impl RateLimiter {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn check(&self, key: &str, max_requests: u64, window_secs: u64) -> SlabResult<u64> {
let now = Instant::now();
let window = Duration::from_secs(window_secs.max(1));
let mut guard = self
.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let can_prune =
now.saturating_duration_since(guard.last_prune) >= RATE_LIMIT_PRUNE_INTERVAL;
if !guard.buckets.contains_key(key) && guard.buckets.len() >= MAX_RATE_LIMIT_ENTRIES {
if can_prune {
guard.buckets.retain(|_, (_, expires_at)| *expires_at > now);
guard.last_prune = now;
}
if guard.buckets.len() >= MAX_RATE_LIMIT_ENTRIES {
return Err(SlabError::too_many_requests(
RATE_LIMIT_PRUNE_INTERVAL.as_secs().max(1),
"rate limit exceeded, please try again shortly",
));
}
} else if guard.buckets.len() > 10_000 && can_prune {
guard.buckets.retain(|_, (_, expires_at)| *expires_at > now);
guard.last_prune = now;
}
let entry = guard
.buckets
.entry(key.to_string())
.or_insert((0, now + window));
if entry.1 <= now {
entry.0 = 0;
entry.1 = now + window;
}
if entry.0 >= max_requests {
let retry_after = entry.1.saturating_duration_since(now).as_secs().max(1);
return Err(SlabError::too_many_requests(
retry_after,
"rate limit exceeded, please try again shortly",
));
}
entry.0 += 1;
Ok(max_requests - entry.0)
}
pub fn check_pair(
&self,
ip_key: &str,
ip_limit: u32,
account_key: &str,
account_limit: u32,
window_secs: u64,
) -> SlabResult<()> {
self.check(ip_key, u64::from(ip_limit), window_secs)?;
self.check(account_key, u64::from(account_limit), window_secs)?;
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientIp(pub String);
impl FromRequestParts<AppCtx> for ClientIp {
type Rejection = std::convert::Infallible;
fn from_request_parts(
parts: &mut axum::http::request::Parts,
state: &AppCtx,
) -> impl Future<Output = Result<Self, Self::Rejection>> + Send {
let peer = parts
.extensions
.get::<ConnectInfo<SocketAddr>>()
.map(|c| c.0);
let ip = client_ip(&parts.headers, peer, state.config.trust_proxy);
std::future::ready(if ip == "unknown" {
Ok(Self("127.0.0.1".to_string()))
} else {
Ok(Self(ip))
})
}
}
#[must_use]
pub fn client_ip(headers: &HeaderMap, peer: Option<SocketAddr>, trust_proxy: bool) -> String {
if trust_proxy {
for header_name in ["cf-connecting-ip", "fly-client-ip"] {
if let Some(ip) = headers
.get(header_name)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<IpAddr>().ok())
{
return ip.to_string();
}
}
if let Some(xff) = headers.get("x-forwarded-for").and_then(|v| v.to_str().ok()) {
for part in xff.rsplit(',') {
if let Ok(ip) = part.trim().parse::<IpAddr>() {
return ip.to_string();
}
}
}
}
peer.map_or_else(|| "unknown".to_string(), |addr| addr.ip().to_string())
}
#[derive(Debug, Clone)]
struct RouteHistogram {
source_file: String,
requests: u64,
errors_5xx: u64,
slow_requests: u64,
latency_ms_total: u64,
max_latency_ms: u64,
buckets: [u64; 9],
}
impl RouteHistogram {
fn new(source_file: String) -> Self {
Self {
source_file,
requests: 0,
errors_5xx: 0,
slow_requests: 0,
latency_ms_total: 0,
max_latency_ms: 0,
buckets: [0; 9],
}
}
fn observe(&mut self, elapsed_ms: u64, is_5xx: bool, is_slow: bool) {
self.requests = self.requests.saturating_add(1);
if is_5xx {
self.errors_5xx = self.errors_5xx.saturating_add(1);
}
if is_slow {
self.slow_requests = self.slow_requests.saturating_add(1);
}
self.latency_ms_total = self.latency_ms_total.saturating_add(elapsed_ms);
if elapsed_ms > self.max_latency_ms {
self.max_latency_ms = elapsed_ms;
}
let bucket_idx = LATENCY_BUCKETS_MS
.iter()
.position(|&bound| elapsed_ms <= bound)
.unwrap_or(LATENCY_BUCKETS_MS.len());
self.buckets[bucket_idx] = self.buckets[bucket_idx].saturating_add(1);
}
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss
)]
fn percentile_ms(&self, quantile: f64) -> u64 {
if self.requests == 0 {
return 0;
}
let target = ((self.requests as f64) * quantile).ceil().max(1.0) as u64;
let mut cumulative = 0u64;
for (idx, &count) in self.buckets.iter().enumerate() {
cumulative = cumulative.saturating_add(count);
if cumulative >= target {
return LATENCY_BUCKETS_MS
.get(idx)
.map_or(self.max_latency_ms, |&bound| bound.min(self.max_latency_ms));
}
}
self.max_latency_ms
}
fn p50_ms(&self) -> u64 {
self.percentile_ms(0.50)
}
fn p95_ms(&self) -> u64 {
self.percentile_ms(0.95)
}
fn p99_ms(&self) -> u64 {
self.percentile_ms(0.99)
}
#[allow(clippy::cast_precision_loss)]
fn avg_latency_ms(&self) -> f64 {
if self.requests > 0 {
self.latency_ms_total as f64 / self.requests as f64
} else {
0.0
}
}
}
#[derive(Debug, Clone)]
struct RouteMetricSnapshot {
method: String,
route: String,
source_file: String,
requests: u64,
errors_5xx: u64,
slow_requests: u64,
avg_latency_ms: f64,
p50_ms: u64,
p95_ms: u64,
p99_ms: u64,
max_latency_ms: u64,
}
#[derive(Debug, Default)]
struct HttpMetrics {
requests: AtomicU64,
errors_5xx: AtomicU64,
latency_ms: AtomicU64,
route_sources: Mutex<HashMap<(String, String), String>>,
routes: Mutex<HashMap<(String, String), RouteHistogram>>,
}
impl HttpMetrics {
fn register_route_source(&self, method: &str, path: &str, source_file: String) {
let mut guard = self
.route_sources
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard.insert((method.to_ascii_uppercase(), path.to_owned()), source_file);
}
fn source_file(&self, method: &str, route: &str) -> String {
let guard = self
.route_sources
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard
.get(&(method.to_ascii_uppercase(), route.to_owned()))
.cloned()
.unwrap_or_else(|| format!("route:{route}"))
}
fn record_request(
&self,
method: &str,
route: &str,
source_file: &str,
elapsed_ms: u64,
is_5xx: bool,
is_slow: bool,
) {
self.requests.fetch_add(1, Ordering::Relaxed);
self.latency_ms.fetch_add(elapsed_ms, Ordering::Relaxed);
if is_5xx {
self.errors_5xx.fetch_add(1, Ordering::Relaxed);
}
let key = (method.to_ascii_uppercase(), route.to_owned());
let mut guard = self
.routes
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(hist) = guard.get_mut(&key) {
hist.observe(elapsed_ms, is_5xx, is_slow);
} else if guard.len() < MAX_TRACKED_ROUTES {
let mut hist = RouteHistogram::new(source_file.to_owned());
hist.observe(elapsed_ms, is_5xx, is_slow);
guard.insert(key, hist);
}
}
fn route_snapshots(&self) -> Vec<RouteMetricSnapshot> {
let guard = self
.routes
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut snapshots: Vec<RouteMetricSnapshot> = guard
.iter()
.map(|((method, route), hist)| RouteMetricSnapshot {
method: method.clone(),
route: route.clone(),
source_file: hist.source_file.clone(),
requests: hist.requests,
errors_5xx: hist.errors_5xx,
slow_requests: hist.slow_requests,
avg_latency_ms: hist.avg_latency_ms(),
p50_ms: hist.p50_ms(),
p95_ms: hist.p95_ms(),
p99_ms: hist.p99_ms(),
max_latency_ms: hist.max_latency_ms,
})
.collect();
snapshots.sort_by(|a, b| {
b.p95_ms
.cmp(&a.p95_ms)
.then_with(|| b.max_latency_ms.cmp(&a.max_latency_ms))
.then_with(|| a.route.cmp(&b.route))
.then_with(|| a.method.cmp(&b.method))
});
snapshots
}
}
fn derive_slab_source_file(slab: &SlabDef) -> String {
let name = slab.name.trim();
if name.contains("::") && !name.contains(' ') && !name.contains('/') {
format!("slabs/{}.rs", name.replace("::", "/"))
} else if name.contains('.') && !name.contains(' ') && !name.contains('/') {
format!("slabs/{}.rs", name.replace('.', "/"))
} else {
format!("route:{}", slab.path)
}
}
#[derive(Debug, Clone)]
pub struct AppCtx {
pub config: AppConfig,
pub db: Db,
pub auth: Auth,
pub jobs: Jobs,
pub mail: Mailer,
pub storage: Storage,
pub cache: Cache,
pub realtime: Realtime,
pub webhooks: Webhooks,
pub assets: Assets,
pub rate_limit: RateLimiter,
pub audit: AuditLog,
pub incidents: Incidents,
draining: Arc<AtomicBool>,
metrics: Arc<HttpMetrics>,
}
impl AppCtx {
pub async fn connect(config: AppConfig) -> SlabResult<Self> {
let db = Db::connect(&config.database_url).await?;
let auth = Auth::new(db.clone(), config.secret_key.clone(), config.cookie_secure);
let jobs = Jobs::new(db.clone());
let mail = Mailer::with_transport(
db.clone(),
format!("noreply@{}.local", config.app_name),
MailTransport::from_env(),
);
let storage_backend = match S3Config::from_env() {
Some(s3) => StorageBackend::S3(s3),
None => StorageBackend::Local {
root_dir: config.storage_dir.clone(),
},
};
let storage = Storage::with_backend(db.clone(), storage_backend)
.with_max_blob_bytes(config.max_blob_bytes);
let cache = Cache::new(db.clone());
let realtime = Realtime::new();
let webhooks = Webhooks::new(db.clone(), jobs.clone());
let assets = Assets::from_dir(&config.assets_dir);
let rate_limit = RateLimiter::new();
let audit = AuditLog::new(db.clone());
let incidents = Incidents::new(db.clone());
Ok(Self {
config,
db,
auth,
jobs,
mail,
storage,
cache,
realtime,
webhooks,
assets,
rate_limit,
audit,
incidents,
draining: Arc::new(AtomicBool::new(false)),
metrics: Arc::new(HttpMetrics::default()),
})
}
pub fn set_draining(&self) {
self.draining.store(true, Ordering::SeqCst);
}
#[must_use]
pub fn is_draining(&self) -> bool {
self.draining.load(Ordering::SeqCst)
}
}
#[derive(Debug)]
pub struct SlabDef {
pub method: String,
pub path: String,
pub name: String,
pub feature: String,
pub summary: String,
pub input_schema: Option<Value>,
pub output_schema: Option<Value>,
pub skip_csrf: bool,
pub router: MethodRouter<AppCtx>,
}
impl SlabDef {
pub fn get<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("GET", path, get(handler))
}
pub fn post<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("POST", path, post(handler))
}
pub fn put<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("PUT", path, put(handler))
}
pub fn patch<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("PATCH", path, patch(handler))
}
pub fn delete<H, T>(path: impl Into<String>, handler: H) -> Self
where
H: Handler<T, AppCtx>,
T: 'static,
{
Self::new("DELETE", path, delete(handler))
}
fn new(method: &str, path: impl Into<String>, router: MethodRouter<AppCtx>) -> Self {
let path = path.into();
Self {
method: method.to_string(),
name: format!("{method} {path}"),
feature: "default".to_string(),
summary: String::new(),
input_schema: None,
output_schema: None,
skip_csrf: false,
path,
router,
}
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
let n = name.into();
if let Some((feat, _)) = n.split_once('.') {
self.feature = feat.to_string();
}
self.name = n;
self
}
#[must_use]
pub fn feature(mut self, feature: impl Into<String>) -> Self {
self.feature = feature.into();
self
}
#[must_use]
pub fn summary(mut self, summary: impl Into<String>) -> Self {
self.summary = summary.into();
self
}
#[must_use]
pub fn input_schema(mut self, schema: Value) -> Self {
self.input_schema = Some(schema);
self
}
#[must_use]
pub fn output_schema(mut self, schema: Value) -> Self {
self.output_schema = Some(schema);
self
}
#[must_use]
pub fn skip_csrf(mut self) -> Self {
self.skip_csrf = true;
self
}
pub fn meta(&self) -> RouteMeta {
RouteMeta {
name: self.name.clone(),
method: self.method.clone(),
path: self.path.clone(),
summary: self.summary.clone(),
feature: self.feature.clone(),
input_schema: self.input_schema.clone(),
output_schema: self.output_schema.clone(),
}
}
}
pub type JobHandlerFn =
Arc<dyn Fn(AppCtx, Value) -> BoxFuture<'static, SlabResult<()>> + Send + Sync>;
#[derive(Clone)]
pub struct JobDef {
pub name: String,
pub queue: String,
pub max_attempts: i64,
pub summary: String,
pub handler: JobHandlerFn,
}
impl fmt::Debug for JobDef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("JobDef")
.field("name", &self.name)
.field("queue", &self.queue)
.field("max_attempts", &self.max_attempts)
.field("summary", &self.summary)
.field("handler", &"<fn>")
.finish()
}
}
impl JobDef {
#[must_use]
pub fn new<F, Fut>(name: impl Into<String>, handler: F) -> Self
where
F: Fn(AppCtx, Value) -> Fut + Send + Sync + 'static,
Fut: Future<Output = SlabResult<()>> + Send + 'static,
{
Self {
name: name.into(),
queue: "default".to_string(),
max_attempts: 5,
summary: String::new(),
handler: Arc::new(move |ctx, payload| Box::pin(handler(ctx, payload))),
}
}
#[must_use]
pub fn queue(mut self, queue: impl Into<String>) -> Self {
self.queue = queue.into();
self
}
#[must_use]
pub fn max_attempts(mut self, attempts: i64) -> Self {
self.max_attempts = attempts;
self
}
#[must_use]
pub fn summary(mut self, summary: impl Into<String>) -> Self {
self.summary = summary.into();
self
}
pub fn meta(&self) -> JobMeta {
JobMeta {
name: self.name.clone(),
queue: self.queue.clone(),
max_attempts: self.max_attempts,
summary: self.summary.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct ScheduleDef {
pub job_name: String,
pub every: Duration,
pub payload: Value,
}
impl ScheduleDef {
#[must_use]
pub fn every(every: Duration, job_name: impl Into<String>, payload: Value) -> Self {
Self {
job_name: job_name.into(),
every,
payload,
}
}
}
#[derive(Debug, Clone)]
pub struct JobRegistry {
handlers: Arc<HashMap<String, JobDef>>,
}
impl JobRegistry {
#[must_use]
pub fn new(jobs: Vec<JobDef>) -> Self {
let mut map = HashMap::new();
map.insert(
"slabs.deliver_webhook".to_string(),
JobDef::new("slabs.deliver_webhook", default_deliver_webhook)
.queue("webhooks")
.summary("Built-in webhook delivery handler"),
);
for job in jobs {
map.insert(job.name.clone(), job);
}
Self {
handlers: Arc::new(map),
}
}
pub async fn run_now(&self, ctx: &AppCtx, job_name: &str, payload: Value) -> SlabResult<()> {
let def = self
.handlers
.get(job_name)
.ok_or_else(|| SlabError::not_found(format!("no job handler `{job_name}`")))?;
(def.handler)(ctx.clone(), payload).await
}
pub async fn dispatch(&self, ctx: &AppCtx, job: &JobRecord) -> SlabResult<()> {
let Some(def) = self.handlers.get(&job.job_name) else {
return Err(SlabError::not_found(format!(
"no job handler registered for `{}`",
job.job_name
)));
};
let payload: Value = match serde_json::from_str(&job.payload_json) {
Ok(v) => v,
Err(e) => {
let msg = format!("invalid job payload: {e}");
let _ = ctx.jobs.mark_dead(&job.id, &msg).await;
return Err(SlabError::bad_request(msg));
}
};
(def.handler)(ctx.clone(), payload).await
}
pub async fn run_next(&self, ctx: &AppCtx) -> SlabResult<bool> {
let Some(record) = ctx.jobs.claim_next().await? else {
return Ok(false);
};
let Some(def) = self.handlers.get(&record.job_name) else {
let msg = format!("no job handler registered for `{}`", record.job_name);
ctx.jobs.mark_failed(&record, &msg).await?;
return Ok(true);
};
let payload: Value = match serde_json::from_str(&record.payload_json) {
Ok(v) => v,
Err(e) => {
let msg = format!("invalid job payload: {e}");
let _ = ctx.jobs.mark_dead(&record.id, &msg).await;
return Err(SlabError::bad_request(msg));
}
};
match (def.handler)(ctx.clone(), payload).await {
Ok(()) => {
ctx.jobs.mark_done(&record.id).await?;
}
Err(err) => {
tracing::warn!(job_id = %record.id, job_name = %record.job_name, error = %err, "job execution failed");
ctx.jobs.mark_failed(&record, &err.to_string()).await?;
}
}
Ok(true)
}
pub async fn drain_ready(&self, ctx: &AppCtx) -> SlabResult<usize> {
let mut processed = 0;
while self.run_next(ctx).await? {
processed += 1;
}
Ok(processed)
}
pub fn spawn_workers(&self, ctx: &AppCtx) {
let (_tx, rx) = watch::channel(false);
let _ = self.spawn_workers_with_shutdown(ctx, &rx);
}
pub fn spawn_workers_with_shutdown(
&self,
ctx: &AppCtx,
shutdown: &watch::Receiver<bool>,
) -> Vec<JoinHandle<()>> {
let concurrency = ctx.config.job_concurrency.max(1);
let poll_interval = Duration::from_millis(ctx.config.job_poll_interval_ms.max(50));
let registry = self.clone();
let worker_ctx = ctx.clone();
ctx.jobs.spawn_workers_with_telemetry(
concurrency,
poll_interval,
shutdown,
move |job| {
let registry = registry.clone();
let worker_ctx = worker_ctx.clone();
async move { registry.dispatch(&worker_ctx, &job).await }
},
Some(ctx.incidents.clone()),
ctx.config.slow_job_ms,
ctx.config.git_sha.clone(),
)
}
pub fn spawn_schedules(&self, ctx: &AppCtx, schedules: Vec<ScheduleDef>) {
let (_tx, rx) = watch::channel(false);
let _ = self.spawn_schedules_with_shutdown(ctx, schedules, &rx);
}
pub fn spawn_schedules_with_shutdown(
&self,
ctx: &AppCtx,
schedules: Vec<ScheduleDef>,
shutdown: &watch::Receiver<bool>,
) -> Vec<JoinHandle<()>> {
let mut handles = Vec::with_capacity(schedules.len());
for schedule in schedules {
let sched_ctx = ctx.clone();
let mut rx = shutdown.clone();
handles.push(tokio::spawn(async move {
let mut ticker = tokio::time::interval(schedule.every);
ticker.tick().await;
loop {
tokio::select! {
_ = ticker.tick() => {
if let Err(err) = sched_ctx
.jobs
.enqueue(&schedule.job_name, schedule.payload.clone())
.await
{
tracing::error!(
job = %schedule.job_name,
error = %err,
"failed to enqueue scheduled job"
);
}
}
_ = rx.changed() => {
break;
}
}
}
}));
}
handles
}
}
async fn default_deliver_webhook(ctx: AppCtx, payload: Value) -> SlabResult<()> {
let delivery_id = payload
.get("delivery_id")
.and_then(|v| v.as_str())
.ok_or_else(|| SlabError::bad_request("missing delivery_id"))?;
if ctx.config.webhooks_live {
ctx.webhooks
.deliver_http(delivery_id, ctx.config.webhooks_allow_local)
.await?;
} else {
ctx.webhooks.mark_delivered(delivery_id, 200).await?;
}
Ok(())
}
pub fn build_router(ctx: AppCtx, slabs: Vec<SlabDef>, jobs: &[JobDef]) -> Router {
let manifest = Arc::new(AppManifest {
app_name: ctx.config.app_name.clone(),
routes: slabs.iter().map(SlabDef::meta).collect(),
jobs: jobs.iter().map(JobDef::meta).collect(),
});
let mut grouped: BTreeMap<String, MethodRouter<AppCtx>> = BTreeMap::new();
let mut skip_csrf_routes: HashSet<(String, String)> = HashSet::new();
skip_csrf_routes.insert(("POST".to_owned(), "/_slabs/client-errors".to_owned()));
for slab in slabs {
if slab.skip_csrf {
skip_csrf_routes.insert((slab.method.to_ascii_uppercase(), slab.path.clone()));
}
let source_file = derive_slab_source_file(&slab);
ctx.metrics
.register_route_source(&slab.method, &slab.path, source_file);
match grouped.entry(slab.path) {
Entry::Occupied(mut existing) => {
let taken = std::mem::take(existing.get_mut());
*existing.get_mut() = taken.merge(slab.router);
}
Entry::Vacant(slot) => {
slot.insert(slab.router);
}
}
}
let has_custom_health = grouped.contains_key("/health");
let has_custom_health_live = grouped.contains_key("/health/live");
let has_custom_health_ready = grouped.contains_key("/health/ready");
let mut router: Router<AppCtx> = Router::new();
for (path, method_router) in grouped {
router = router.route(&path, method_router);
}
if !has_custom_health {
router = router.route("/health", get(health_handler));
}
if !has_custom_health_live {
router = router.route("/health/live", get(health_live_handler));
}
if !has_custom_health_ready {
router = router.route("/health/ready", get(health_ready_handler));
}
router = router
.route("/_slabs/health", get(health_handler))
.route("/_slabs/metrics", get(metrics_handler))
.route("/_slabs/incidents", get(list_incidents_handler))
.route("/_slabs/incidents/ui", get(incidents_ui_handler))
.route("/_slabs/incidents/{id}", get(get_incident_handler))
.route("/_slabs/incidents/{id}/claim", post(claim_incident_handler))
.route("/_slabs/incidents/{id}/link", post(link_incident_handler))
.route(
"/_slabs/incidents/{id}/ignore",
post(ignore_incident_handler),
)
.route(
"/_slabs/incidents/{id}/resolve",
post(resolve_incident_handler),
)
.route(
"/_slabs/incidents/{id}/attachments/{blob_id}",
get(incident_attachment_handler),
)
.route("/_slabs/client-errors", post(client_errors_handler))
.route(
"/_slabs/bug-reports",
post(bug_reports_handler).layer(DefaultBodyLimit::disable()),
)
.route("/_slabs/vendor/basecoat.min.css", get(vendor_basecoat_css))
.route("/_slabs/vendor/basecoat.min.js", get(vendor_basecoat_js))
.route("/_slabs/vendor/htmx.min.js", get(vendor_htmx_js))
.route("/_slabs/vendor/htmx-ext-sse.js", get(vendor_htmx_sse_js))
.route(
"/_slabs/vendor/idiomorph-ext.min.js",
get(vendor_idiomorph_js),
)
.route("/_slabs/vendor/alpine.min.js", get(vendor_alpine_js))
.route("/_slabs/vendor/sw-register.js", get(vendor_sw_register_js))
.route(
"/_slabs/vendor/slabs-telemetry.js",
get(vendor_slabs_telemetry_js),
)
.route(
"/_slabs/vendor/slabs-bug-report.js",
get(vendor_slabs_bug_report_js),
)
.route("/assets/{hash}/{*path}", get(serve_asset_handler));
if ctx.config.env.is_dev_or_test() {
let openapi_manifest = manifest.clone();
router = router
.route(
"/_slabs/manifest",
get(move || {
let m = manifest.clone();
async move { Json((*m).clone()) }
}),
)
.route(
"/_slabs/openapi.json",
get(move || {
let m = openapi_manifest.clone();
async move { Json(m.to_openapi_3_1()) }
}),
)
.route("/_slabs/mail", get(dev_mail_outbox_handler));
}
let max_body_bytes = ctx.config.max_body_bytes;
let cookie_secure = ctx.config.cookie_secure;
let cors_origins: Vec<HeaderValue> = ctx
.config
.cors_origins
.iter()
.filter_map(|o| {
let trimmed = o.trim();
if trimmed.is_empty() {
None
} else {
HeaderValue::from_str(trimmed).ok()
}
})
.collect();
let x_request_id = HeaderName::from_static("x-request-id");
let state_ctx = ctx.clone();
let csrf_state = CsrfState {
ctx: state_ctx.clone(),
skip_routes: Arc::new(skip_csrf_routes),
};
let mut app = router
.route_layer(middleware::from_fn_with_state(
state_ctx,
metrics_middleware,
))
.route_layer(middleware::from_fn_with_state(csrf_state, csrf_middleware))
.with_state(ctx)
.layer(CompressionLayer::new())
.layer(RequestBodyLimitLayer::new(max_body_bytes))
.layer(SetResponseHeaderLayer::if_not_present(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
))
.layer(SetResponseHeaderLayer::if_not_present(
header::X_FRAME_OPTIONS,
HeaderValue::from_static("SAMEORIGIN"),
))
.layer(SetResponseHeaderLayer::if_not_present(
header::REFERRER_POLICY,
HeaderValue::from_static("strict-origin-when-cross-origin"),
))
.layer(SetResponseHeaderLayer::if_not_present(
HeaderName::from_static("permissions-policy"),
HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
));
if cookie_secure {
app = app.layer(SetResponseHeaderLayer::if_not_present(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
));
}
if !cors_origins.is_empty() {
let cors = CorsLayer::new()
.allow_origin(AllowOrigin::list(cors_origins))
.allow_methods([
Method::GET,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
Method::OPTIONS,
])
.allow_headers([
header::AUTHORIZATION,
header::CONTENT_TYPE,
header::ACCEPT,
HeaderName::from_static("hx-request"),
HeaderName::from_static("hx-target"),
HeaderName::from_static("hx-current-url"),
HeaderName::from_static("x-csrf-token"),
HeaderName::from_static("x-request-id"),
])
.allow_credentials(true);
app = app.layer(cors);
}
app.layer(PropagateRequestIdLayer::new(x_request_id.clone()))
.layer(TraceLayer::new_for_http())
.layer(SetRequestIdLayer::new(x_request_id, MakeUlidRequestId))
.layer(middleware::from_fn(sanitize_request_id_middleware))
}
async fn sanitize_request_id_middleware(mut request: Request, next: Next) -> Response {
let x_request_id = HeaderName::from_static("x-request-id");
let invalid = request.headers().get(&x_request_id).is_some_and(|val| {
val.to_str().map_or(true, |s| {
s.is_empty()
|| s.len() > 64
|| !s
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
})
});
if invalid {
request.headers_mut().remove(&x_request_id);
}
next.run(request).await
}
fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(s) = payload.downcast_ref::<&str>() {
(*s).to_owned()
} else if let Some(s) = payload.downcast_ref::<String>() {
s.clone()
} else {
"handler panicked".to_owned()
}
}
fn incident_webhook_client() -> &'static reqwest::Client {
static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
CLIENT.get_or_init(|| {
reqwest::Client::builder()
.timeout(Duration::from_secs(5))
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("failed to build incident webhook HTTP client")
})
}
fn sign_incident_webhook(secret: &str, body: &[u8]) -> String {
let mut mac =
HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts keys of any size");
mac.update(body);
format!("sha256={}", hex::encode(mac.finalize().into_bytes()))
}
fn spawn_incident_webhook(ctx: &AppCtx, event: &'static str, record: &IncidentRecord) {
let Some(raw_url) = ctx.config.incident_webhook_url.as_deref() else {
return;
};
let validated_url =
match Webhooks::validate_url_with_policy(raw_url, ctx.config.webhooks_allow_local) {
Ok(url) => url,
Err(err) => {
tracing::warn!(
error = %err,
"skipped incident webhook notification because URL failed SSRF validation"
);
return;
}
};
let payload = json!({
"protocol": INCIDENT_PROTOCOL_VERSION,
"event": event,
"sent_at": Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true),
"app": ctx.config.app_name,
"env": ctx.config.env.as_str(),
"incident": record,
});
let Ok(body_bytes) = serde_json::to_vec(&payload) else {
tracing::warn!("failed to serialize incident webhook payload");
return;
};
let signature = ctx
.config
.incident_webhook_secret
.as_deref()
.map(|secret| sign_incident_webhook(secret, &body_bytes));
tokio::spawn(async move {
let client = incident_webhook_client();
let mut req = client
.post(&validated_url)
.header(header::CONTENT_TYPE, "application/json")
.header("x-slabs-event", event)
.header("x-slabs-protocol", INCIDENT_PROTOCOL_VERSION)
.body(body_bytes);
if let Some(sig) = signature {
req = req.header("x-slabs-signature", sig);
}
if let Err(err) = req.send().await {
tracing::warn!(error = %err, event, "incident webhook notification failed");
}
});
}
async fn record_and_notify_incident(ctx: &AppCtx, input: IncidentInput) -> Option<IncidentRecord> {
let (record, outcome) = match ctx.incidents.record_with_outcome(input).await {
Ok(res) => res,
Err(err) => {
tracing::error!(error = %err, "failed to persist runtime incident");
return None;
}
};
match outcome {
IncidentOutcome::Opened => spawn_incident_webhook(ctx, "incident.opened", &record),
IncidentOutcome::Reopened => spawn_incident_webhook(ctx, "incident.reopened", &record),
IncidentOutcome::Incremented => {}
}
Some(record)
}
async fn metrics_middleware(State(ctx): State<AppCtx>, request: Request, next: Next) -> Response {
let method = request.method().as_str().to_owned();
let raw_path = request.uri().path().to_owned();
let route_pattern = request
.extensions()
.get::<MatchedPath>()
.map_or_else(|| raw_path.clone(), |m| m.as_str().to_owned());
let request_id = request
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_owned();
let is_ws_upgrade = request
.headers()
.get(header::UPGRADE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.eq_ignore_ascii_case("websocket"));
let source_file = ctx.metrics.source_file(&method, &route_pattern);
let started = Instant::now();
match AssertUnwindSafe(next.run(request)).catch_unwind().await {
Ok(response) => {
let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let status = response.status();
let is_5xx = status.is_server_error();
let is_sse = response
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.to_ascii_lowercase().starts_with("text/event-stream"));
let is_stream = is_ws_upgrade || status == StatusCode::SWITCHING_PROTOCOLS || is_sse;
let is_internal_route = raw_path.starts_with("/_slabs/");
let is_slow =
!is_internal_route && !is_stream && elapsed_ms >= ctx.config.slow_request_ms;
ctx.metrics.record_request(
&method,
&route_pattern,
&source_file,
elapsed_ms,
is_5xx,
is_slow,
);
if is_5xx {
let input = IncidentInput {
kind: "http_5xx".into(),
source_file: source_file.clone(),
route_pattern: Some(route_pattern.clone()),
status_code: Some(i64::from(status.as_u16())),
error_message: format!(
"HTTP {} on {} {}",
status.as_u16(),
method,
route_pattern
),
detail: Some(format!(
"{method} {route_pattern} returned {} in {elapsed_ms}ms",
status.as_u16()
)),
context_json: json!({
"method": method,
"request_id": request_id,
"latency_ms": elapsed_ms,
"status": status.as_u16(),
"env": ctx.config.env.as_str(),
"git_sha": ctx.config.git_sha,
}),
git_sha: ctx.config.git_sha.clone(),
custom_fingerprint: None,
};
let _ = record_and_notify_incident(&ctx, input).await;
}
if is_slow {
let input = IncidentInput {
kind: "slow_request".into(),
source_file,
route_pattern: Some(route_pattern.clone()),
status_code: Some(i64::from(status.as_u16())),
error_message: format!(
"slow request on {} {} exceeded {}ms threshold",
method, route_pattern, ctx.config.slow_request_ms
),
detail: Some(format!(
"{method} {route_pattern} took {elapsed_ms}ms (threshold {}ms, status {})",
ctx.config.slow_request_ms,
status.as_u16()
)),
context_json: json!({
"method": method,
"request_id": request_id,
"latency_ms": elapsed_ms,
"threshold_ms": ctx.config.slow_request_ms,
"status": status.as_u16(),
"env": ctx.config.env.as_str(),
"git_sha": ctx.config.git_sha,
}),
git_sha: ctx.config.git_sha.clone(),
custom_fingerprint: None,
};
let _ = record_and_notify_incident(&ctx, input).await;
}
response
}
Err(panic_payload) => {
let elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let panic_msg = panic_payload_message(panic_payload.as_ref());
let is_slow =
!raw_path.starts_with("/_slabs/") && elapsed_ms >= ctx.config.slow_request_ms;
tracing::error!(
method = %method,
route = %route_pattern,
source_file = %source_file,
request_id = %request_id,
panic = %panic_msg,
"HTTP handler panicked"
);
ctx.metrics.record_request(
&method,
&route_pattern,
&source_file,
elapsed_ms,
true,
is_slow,
);
let input = IncidentInput {
kind: "panic".into(),
source_file,
route_pattern: Some(route_pattern.clone()),
status_code: Some(500),
error_message: panic_msg.clone(),
detail: Some(format!(
"HTTP {method} {route_pattern} panicked: {panic_msg}"
)),
context_json: json!({
"method": method,
"request_id": request_id,
"latency_ms": elapsed_ms,
"env": ctx.config.env.as_str(),
"git_sha": ctx.config.git_sha,
}),
git_sha: ctx.config.git_sha.clone(),
custom_fingerprint: None,
};
let _ = record_and_notify_incident(&ctx, input).await;
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "error": "internal server error" })),
)
.into_response()
}
}
}
#[derive(Clone)]
struct CsrfState {
ctx: AppCtx,
skip_routes: Arc<HashSet<(String, String)>>,
}
async fn csrf_middleware(State(state): State<CsrfState>, request: Request, next: Next) -> Response {
if !state.ctx.config.csrf_enforce {
return next.run(request).await;
}
if !matches!(
*request.method(),
Method::POST | Method::PUT | Method::PATCH | Method::DELETE
) {
return next.run(request).await;
}
let headers = request.headers();
if !headers.contains_key(header::COOKIE) {
return next.run(request).await;
}
if headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.len() > 7 && v[..7].eq_ignore_ascii_case("bearer "))
{
return next.run(request).await;
}
let method = request.method().as_str().to_ascii_uppercase();
let matched_path = request
.extensions()
.get::<MatchedPath>()
.map_or_else(|| request.uri().path(), MatchedPath::as_str);
if matched_path == "/_slabs/client-errors"
|| state
.skip_routes
.contains(&(method, matched_path.to_owned()))
{
return next.run(request).await;
}
if headers
.get("sec-fetch-site")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
{
return SlabError::forbidden("cross-site request blocked by fetch metadata policy")
.into_response();
}
if let Some(origin_val) = headers.get(header::ORIGIN) {
let Ok(origin_raw) = origin_val.to_str().map(str::trim) else {
return SlabError::forbidden("invalid Origin header").into_response();
};
if !is_allowed_origin(origin_raw, headers, &state.ctx.config.cors_origins) {
return SlabError::forbidden("cross-origin request blocked").into_response();
}
}
next.run(request).await
}
fn is_allowed_origin(origin_raw: &str, headers: &HeaderMap, cors_origins: &[String]) -> bool {
if origin_raw.is_empty() || origin_raw.eq_ignore_ascii_case("null") {
return false;
}
if cors_origins
.iter()
.any(|allowed| allowed.trim().eq_ignore_ascii_case(origin_raw))
{
return true;
}
let Ok(origin_uri) = origin_raw.parse::<Uri>() else {
return false;
};
let Some(scheme) = origin_uri.scheme_str() else {
return false;
};
if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
return false;
}
let Some(authority) = origin_uri.authority() else {
return false;
};
if authority.as_str().contains('@') {
return false;
}
let Some(host_raw) = headers
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.map(str::trim)
.filter(|v| !v.is_empty())
else {
return false;
};
authorities_match(scheme, authority.as_str(), host_raw)
}
fn authorities_match(scheme: &str, origin_authority: &str, host_header: &str) -> bool {
if origin_authority.eq_ignore_ascii_case(host_header) {
return true;
}
let default_port = if scheme.eq_ignore_ascii_case("https") {
":443"
} else {
":80"
};
let norm_origin = origin_authority
.strip_suffix(default_port)
.unwrap_or(origin_authority);
let norm_host = host_header
.strip_suffix(default_port)
.unwrap_or(host_header);
norm_origin.eq_ignore_ascii_case(norm_host)
}
fn constant_time_eq_sha256(a: &[u8], b: &[u8]) -> bool {
let ha = Sha256::digest(a);
let hb = Sha256::digest(b);
let mut diff = 0u8;
for (x, y) in ha.iter().zip(hb.iter()) {
diff |= x ^ y;
}
diff == 0
}
async fn health_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
ctx.db.ping().await?;
Ok(Json(json!({
"status": "ok",
"app": ctx.config.app_name,
})))
}
async fn health_live_handler() -> Json<Value> {
Json(json!({ "status": "ok" }))
}
async fn health_ready_handler(State(ctx): State<AppCtx>) -> Response {
if ctx.is_draining() {
return (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "status": "draining" })),
)
.into_response();
}
match ctx.db.ping().await {
Ok(()) => (StatusCode::OK, Json(json!({ "status": "ok" }))).into_response(),
Err(err) => {
tracing::warn!(error = %err, "readiness probe database check failed");
(
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "status": "unavailable" })),
)
.into_response()
}
}
}
fn check_observability_auth(ctx: &AppCtx, headers: &HeaderMap) -> Option<Response> {
if let Some(expected) = &ctx.config.metrics_token {
let provided = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "));
match provided {
Some(token) if constant_time_eq_sha256(token.as_bytes(), expected.as_bytes()) => None,
_ => Some(StatusCode::UNAUTHORIZED.into_response()),
}
} else if ctx.config.env.is_prod_like() {
Some(StatusCode::NOT_FOUND.into_response())
} else {
None
}
}
fn escape_prom_label(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
other => out.push(other),
}
}
out
}
async fn metrics_handler(State(ctx): State<AppCtx>, headers: HeaderMap) -> Response {
if let Some(resp) = check_observability_auth(&ctx, &headers) {
return resp;
}
let requests_total = ctx.metrics.requests.load(Ordering::Relaxed);
let errors_5xx_total = ctx.metrics.errors_5xx.load(Ordering::Relaxed);
let latency_ms_total = ctx.metrics.latency_ms.load(Ordering::Relaxed);
#[allow(clippy::cast_precision_loss)]
let avg_latency_ms = if requests_total > 0 {
latency_ms_total as f64 / requests_total as f64
} else {
0.0
};
let job_stats = ctx.jobs.stats().await.unwrap_or_default();
let realtime_topics = ctx.realtime.active_topic_count();
let open_incidents = ctx.incidents.count_open().await.unwrap_or(0);
let route_snapshots = ctx.metrics.route_snapshots();
let wants_json = headers
.get(header::ACCEPT)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("application/json"));
if wants_json {
let routes_json: Vec<Value> = route_snapshots
.iter()
.map(|r| {
json!({
"method": r.method,
"route": r.route,
"source_file": r.source_file,
"requests": r.requests,
"errors_5xx": r.errors_5xx,
"slow_requests": r.slow_requests,
"avg_latency_ms": r.avg_latency_ms,
"p50_ms": r.p50_ms,
"p95_ms": r.p95_ms,
"p99_ms": r.p99_ms,
"max_latency_ms": r.max_latency_ms,
})
})
.collect();
return (
StatusCode::OK,
Json(json!({
"http": {
"requests_total": requests_total,
"errors_5xx_total": errors_5xx_total,
"latency_ms_total": latency_ms_total,
"avg_latency_ms": avg_latency_ms,
},
"routes": routes_json,
"open_incidents": open_incidents,
"jobs": {
"pending": job_stats.pending,
"running": job_stats.running,
"dead": job_stats.dead,
"completed": job_stats.completed,
},
"realtime": {
"active_topics": realtime_topics,
},
})),
)
.into_response();
}
let mut body = String::with_capacity(1024);
let _ = writeln!(
body,
"# HELP slabs_http_requests_total Total HTTP requests handled."
);
let _ = writeln!(body, "# TYPE slabs_http_requests_total counter");
let _ = writeln!(body, "slabs_http_requests_total {requests_total}");
let _ = writeln!(
body,
"# HELP slabs_http_errors_5xx_total Total HTTP 5xx responses."
);
let _ = writeln!(body, "# TYPE slabs_http_errors_5xx_total counter");
let _ = writeln!(body, "slabs_http_errors_5xx_total {errors_5xx_total}");
let _ = writeln!(
body,
"# HELP slabs_http_latency_ms_total Cumulative HTTP latency in milliseconds."
);
let _ = writeln!(body, "# TYPE slabs_http_latency_ms_total counter");
let _ = writeln!(body, "slabs_http_latency_ms_total {latency_ms_total}");
let _ = writeln!(
body,
"# HELP slabs_http_latency_avg_ms Average HTTP latency in milliseconds."
);
let _ = writeln!(body, "# TYPE slabs_http_latency_avg_ms gauge");
let _ = writeln!(body, "slabs_http_latency_avg_ms {avg_latency_ms:.3}");
let _ = writeln!(body, "# HELP slabs_jobs_pending Pending background jobs.");
let _ = writeln!(body, "# TYPE slabs_jobs_pending gauge");
let _ = writeln!(body, "slabs_jobs_pending {}", job_stats.pending);
let _ = writeln!(body, "# HELP slabs_jobs_running Running background jobs.");
let _ = writeln!(body, "# TYPE slabs_jobs_running gauge");
let _ = writeln!(body, "slabs_jobs_running {}", job_stats.running);
let _ = writeln!(
body,
"# HELP slabs_jobs_dead Dead-lettered background jobs."
);
let _ = writeln!(body, "# TYPE slabs_jobs_dead gauge");
let _ = writeln!(body, "slabs_jobs_dead {}", job_stats.dead);
let _ = writeln!(
body,
"# HELP slabs_jobs_completed Completed background jobs."
);
let _ = writeln!(body, "# TYPE slabs_jobs_completed counter");
let _ = writeln!(body, "slabs_jobs_completed {}", job_stats.completed);
let _ = writeln!(
body,
"# HELP slabs_realtime_active_topics Active realtime pub/sub topics."
);
let _ = writeln!(body, "# TYPE slabs_realtime_active_topics gauge");
let _ = writeln!(body, "slabs_realtime_active_topics {realtime_topics}");
let _ = writeln!(body, "# HELP slabs_incidents_open Open runtime incidents.");
let _ = writeln!(body, "# TYPE slabs_incidents_open gauge");
let _ = writeln!(body, "slabs_incidents_open {open_incidents}");
if !route_snapshots.is_empty() {
let _ = writeln!(
body,
"# HELP slabs_route_requests_total Total HTTP requests per route."
);
let _ = writeln!(body, "# TYPE slabs_route_requests_total counter");
for r in &route_snapshots {
let _ = writeln!(
body,
"slabs_route_requests_total{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
escape_prom_label(&r.method),
escape_prom_label(&r.route),
escape_prom_label(&r.source_file),
r.requests
);
}
let _ = writeln!(
body,
"# HELP slabs_route_slow_total Slow HTTP requests per route."
);
let _ = writeln!(body, "# TYPE slabs_route_slow_total counter");
for r in &route_snapshots {
let _ = writeln!(
body,
"slabs_route_slow_total{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
escape_prom_label(&r.method),
escape_prom_label(&r.route),
escape_prom_label(&r.source_file),
r.slow_requests
);
}
let _ = writeln!(
body,
"# HELP slabs_route_p95_ms Estimated p95 latency in milliseconds per route."
);
let _ = writeln!(body, "# TYPE slabs_route_p95_ms gauge");
for r in &route_snapshots {
let _ = writeln!(
body,
"slabs_route_p95_ms{{method=\"{}\",route=\"{}\",source_file=\"{}\"}} {}",
escape_prom_label(&r.method),
escape_prom_label(&r.route),
escape_prom_label(&r.source_file),
r.p95_ms
);
}
}
(
StatusCode::OK,
[(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; version=0.0.4; charset=utf-8"),
)],
body,
)
.into_response()
}
#[derive(Debug, Deserialize)]
struct ListIncidentsQuery {
status: Option<String>,
limit: Option<i64>,
}
#[derive(Debug, Deserialize)]
struct ResolveIncidentBody {
resolved_in_sha: Option<String>,
}
#[derive(Debug, Deserialize)]
struct ClaimIncidentBody {
assignee: String,
}
#[derive(Debug, Deserialize)]
struct LinkIncidentBody {
external_issue_key: String,
external_issue_url: String,
}
#[derive(Debug, Clone, Deserialize)]
struct RecentOccurrenceEntry {
#[serde(default)]
seen_at: Option<String>,
#[serde(default)]
git_sha: Option<String>,
#[serde(default)]
request_id: Option<String>,
#[serde(default)]
latency_ms: Option<u64>,
}
#[derive(Debug, Deserialize)]
struct ClientErrorPayload {
#[serde(default)]
kind: Option<String>,
message: String,
#[serde(default)]
path: Option<String>,
#[serde(default)]
detail: Option<String>,
}
fn repro_hint_for(inc: &IncidentRecord) -> String {
if inc.source_file.starts_with("slabs/") || inc.source_file.starts_with("jobs/") {
let test_filter = inc.source_file.trim_end_matches(".rs").replace('/', "::");
format!(
"Inspect `{}` and verify with `slabs check` (or `cargo test {}`)",
inc.source_file, test_filter
)
} else {
format!(
"Inspect `{}` ({}) and verify with `slabs check`",
inc.source_file,
inc.route_pattern.as_deref().unwrap_or("unknown route")
)
}
}
fn enrich_incident_json(inc: &IncidentRecord) -> Value {
let mut value = serde_json::to_value(inc).unwrap_or_else(|_| json!({}));
if let Some(obj) = value.as_object_mut() {
obj.insert("repro_hint".into(), Value::String(repro_hint_for(inc)));
}
value
}
async fn authorize_diagnostics(
ctx: &AppCtx,
headers: &HeaderMap,
jar: &CookieJar,
) -> Option<Response> {
if ctx.config.env.is_dev_or_test() {
return None;
}
if let Some(expected) = &ctx.config.metrics_token {
let provided = headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "));
if let Some(token) = provided {
if constant_time_eq_sha256(token.as_bytes(), expected.as_bytes()) {
return None;
}
}
}
let session = ctx.auth.optional_session(jar).await.ok().flatten();
if let Some(ref s) = session {
if s.role == "admin" {
return None;
}
}
if ctx.config.metrics_token.is_some() {
Some(StatusCode::UNAUTHORIZED.into_response())
} else if session.is_some() {
Some(StatusCode::FORBIDDEN.into_response())
} else {
Some(StatusCode::NOT_FOUND.into_response())
}
}
#[derive(Debug, Clone, Deserialize)]
struct IncidentAttachmentRef {
blob_id: String,
filename: String,
content_type: String,
#[serde(default)]
byte_size: Option<i64>,
#[serde(default)]
is_screenshot: bool,
}
fn parse_incident_attachments(context_json: &str) -> Vec<IncidentAttachmentRef> {
serde_json::from_str::<Value>(context_json)
.ok()
.and_then(|v| v.get("attachments").cloned())
.and_then(|arr| serde_json::from_value::<Vec<IncidentAttachmentRef>>(arr).ok())
.unwrap_or_default()
}
fn is_passive_image_content_type(content_type: &str) -> bool {
let essence = content_type
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
matches!(
essence.as_str(),
"image/png" | "image/jpeg" | "image/webp" | "image/gif"
)
}
fn parse_recent_occurrences(raw_json: &str) -> Vec<RecentOccurrenceEntry> {
serde_json::from_str::<Vec<RecentOccurrenceEntry>>(raw_json).unwrap_or_default()
}
fn is_safe_http_url(raw: &str) -> bool {
let trimmed = raw.trim();
(trimmed.starts_with("https://") || trimmed.starts_with("http://"))
&& trimmed.len() > "http://".len()
&& !trimmed.chars().any(|c| c.is_whitespace() || c.is_control())
}
fn decode_form_component(raw: &str) -> String {
let bytes = raw.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'+' => {
out.push(b' ');
i += 1;
}
b'%' if i + 2 < bytes.len() => {
let hex_pair = &raw[i + 1..i + 3];
if let Ok(byte) = u8::from_str_radix(hex_pair, 16) {
out.push(byte);
i += 3;
} else {
out.push(b'%');
i += 1;
}
}
other => {
out.push(other);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
fn accepts_html(headers: &HeaderMap) -> bool {
!slabs_html::htmx::wants_json(headers)
&& headers
.get(header::ACCEPT)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("text/html"))
}
fn redirect_to_incidents_ui() -> Response {
let mut resp_headers = HeaderMap::new();
resp_headers.insert(
header::LOCATION,
HeaderValue::from_static("/_slabs/incidents/ui"),
);
(StatusCode::SEE_OTHER, resp_headers).into_response()
}
fn parse_claim_assignee(headers: &HeaderMap, body: &Bytes) -> SlabResult<String> {
if body.iter().all(u8::is_ascii_whitespace) {
return Err(SlabError::validation("assignee", "cannot be empty"));
}
let is_form = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| {
v.to_ascii_lowercase()
.starts_with("application/x-www-form-urlencoded")
});
if is_form {
let raw = std::str::from_utf8(body)
.map_err(|_| SlabError::bad_request("invalid UTF-8 form body"))?;
for pair in raw.split('&') {
if let Some((k, v)) = pair.split_once('=') {
if k == "assignee" {
let decoded = decode_form_component(v);
let trimmed = decoded.trim();
if !trimmed.is_empty() {
return Ok(trimmed.chars().take(128).collect());
}
}
}
}
return Err(SlabError::validation("assignee", "cannot be empty"));
}
match serde_json::from_slice::<ClaimIncidentBody>(body) {
Ok(parsed) => {
let trimmed = parsed.assignee.trim();
if trimmed.is_empty() {
Err(SlabError::validation("assignee", "cannot be empty"))
} else {
Ok(trimmed.chars().take(128).collect())
}
}
Err(err) => Err(SlabError::bad_request(format!("invalid JSON body: {err}"))),
}
}
fn parse_resolve_sha(headers: &HeaderMap, body: &Bytes) -> SlabResult<Option<String>> {
if body.iter().all(u8::is_ascii_whitespace) {
return Ok(None);
}
let is_form = headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| {
v.to_ascii_lowercase()
.starts_with("application/x-www-form-urlencoded")
});
if is_form {
let raw = std::str::from_utf8(body)
.map_err(|_| SlabError::bad_request("invalid UTF-8 form body"))?;
for pair in raw.split('&') {
if let Some((k, v)) = pair.split_once('=') {
if k == "resolved_in_sha" {
let trimmed = v.trim();
if !trimmed.is_empty() {
return Ok(Some(trimmed.chars().take(128).collect()));
}
}
}
}
return Ok(None);
}
match serde_json::from_slice::<ResolveIncidentBody>(body) {
Ok(parsed) => Ok(parsed
.resolved_in_sha
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())),
Err(err) => Err(SlabError::bad_request(format!("invalid JSON body: {err}"))),
}
}
async fn list_incidents_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Query(query): Query<ListIncidentsQuery>,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
let status = query.status.as_deref().unwrap_or("open");
let limit = query.limit.unwrap_or(50);
match ctx.incidents.list(Some(status), limit).await {
Ok(rows) => {
let enriched: Vec<Value> = rows.iter().map(enrich_incident_json).collect();
(StatusCode::OK, Json(json!({ "incidents": enriched }))).into_response()
}
Err(err) => err.into_response(),
}
}
async fn get_incident_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Path(id): Path<String>,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
match ctx.incidents.get(&id).await {
Ok(Some(inc)) => (StatusCode::OK, Json(enrich_incident_json(&inc))).into_response(),
Ok(None) => SlabError::not_found("incident not found").into_response(),
Err(err) => err.into_response(),
}
}
async fn claim_incident_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Path(id): Path<String>,
body: Bytes,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
let assignee = match parse_claim_assignee(&headers, &body) {
Ok(val) => val,
Err(err) => return err.into_response(),
};
match ctx.incidents.claim(&id, &assignee).await {
Ok(true) => {
if let Ok(Some(record)) = ctx.incidents.get(&id).await {
spawn_incident_webhook(&ctx, "incident.assigned", &record);
}
if accepts_html(&headers) {
return redirect_to_incidents_ui();
}
(
StatusCode::OK,
Json(json!({
"id": id,
"status": "in_progress",
"assignee": assignee,
})),
)
.into_response()
}
Ok(false) => match ctx.incidents.get(&id).await {
Ok(Some(_)) => {
SlabError::conflict("incident is already claimed or not open").into_response()
}
Ok(None) => SlabError::not_found("incident not found").into_response(),
Err(err) => err.into_response(),
},
Err(err) => err.into_response(),
}
}
async fn link_incident_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Path(id): Path<String>,
body: Bytes,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
let payload: LinkIncidentBody = match serde_json::from_slice(&body) {
Ok(parsed) => parsed,
Err(err) => {
return SlabError::bad_request(format!("invalid JSON body: {err}")).into_response();
}
};
match ctx
.incidents
.link_external(
&id,
&payload.external_issue_key,
&payload.external_issue_url,
)
.await
{
Ok(true) => (
StatusCode::OK,
Json(json!({
"id": id,
"external_issue_key": payload.external_issue_key.trim(),
"external_issue_url": payload.external_issue_url.trim(),
})),
)
.into_response(),
Ok(false) => SlabError::not_found("incident not found").into_response(),
Err(err) => err.into_response(),
}
}
async fn ignore_incident_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Path(id): Path<String>,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
match ctx.incidents.ignore(&id).await {
Ok(true) => {
if accepts_html(&headers) {
return redirect_to_incidents_ui();
}
(
StatusCode::OK,
Json(json!({
"id": id,
"status": "ignored",
})),
)
.into_response()
}
Ok(false) => SlabError::not_found("incident not found").into_response(),
Err(err) => err.into_response(),
}
}
async fn resolve_incident_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Path(id): Path<String>,
body: Bytes,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
let resolved_in_sha = match parse_resolve_sha(&headers, &body) {
Ok(sha) => sha,
Err(err) => return err.into_response(),
};
match ctx.incidents.resolve(&id, resolved_in_sha.as_deref()).await {
Ok(true) => {
if let Ok(Some(record)) = ctx.incidents.get(&id).await {
spawn_incident_webhook(&ctx, "incident.resolved", &record);
}
if accepts_html(&headers) {
return redirect_to_incidents_ui();
}
(
StatusCode::OK,
Json(json!({
"id": id,
"status": "resolved",
"resolved_in_sha": resolved_in_sha,
})),
)
.into_response()
}
Ok(false) => SlabError::not_found("incident not found").into_response(),
Err(err) => err.into_response(),
}
}
async fn incidents_ui_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Query(query): Query<ListIncidentsQuery>,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
let active_status = match query.status.as_deref().map(str::trim) {
Some("in_progress") => "in_progress",
Some("resolved") => "resolved",
Some("ignored") => "ignored",
Some("all") => "all",
_ => "open",
};
let limit = query.limit.unwrap_or(100);
let incidents = match ctx.incidents.list(Some(active_status), limit).await {
Ok(rows) => rows,
Err(err) => return err.into_response(),
};
let open_count = ctx.incidents.count_open().await.unwrap_or(0);
let body = slabs_html::html! {
main class="mx-auto max-w-5xl p-6 grid gap-6" {
header class="flex flex-wrap items-center justify-between gap-4 border-b pb-4" {
div {
h1 class="text-2xl font-bold" { "Incidents — " (ctx.config.app_name) }
p class="text-sm text-muted-foreground" {
"Environment: " (ctx.config.env.as_str()) " · Open incidents: " (open_count)
}
}
nav aria-label="Incident status filter" class="flex flex-wrap items-center gap-2" {
a
href="/_slabs/incidents/ui?status=open"
class=(if active_status == "open" { "btn" } else { "btn-outline" })
{
"Open (" (open_count) ")"
}
a
href="/_slabs/incidents/ui?status=in_progress"
class=(if active_status == "in_progress" { "btn" } else { "btn-outline" })
{
"In Progress"
}
a
href="/_slabs/incidents/ui?status=resolved"
class=(if active_status == "resolved" { "btn" } else { "btn-outline" })
{
"Resolved"
}
a
href="/_slabs/incidents/ui?status=ignored"
class=(if active_status == "ignored" { "btn" } else { "btn-outline" })
{
"Ignored"
}
a
href="/_slabs/incidents/ui?status=all"
class=(if active_status == "all" { "btn" } else { "btn-outline" })
{
"All"
}
}
}
@if incidents.is_empty() {
section class="card p-8 text-center text-muted-foreground" {
p { "No " (active_status) " incidents recorded." }
}
} @else {
div class="grid gap-4" {
@for inc in &incidents {
@let attachments = parse_incident_attachments(&inc.context_json);
@let recent_occurrences = parse_recent_occurrences(&inc.recent_occurrences_json);
@let hint = repro_hint_for(inc);
@let pretty_ctx = serde_json::from_str::<Value>(&inc.context_json)
.ok()
.and_then(|v| serde_json::to_string_pretty(&v).ok())
.unwrap_or_else(|| inc.context_json.clone());
article class="card p-5 grid gap-3" data-incident-id=(inc.id) data-incident-kind=(inc.kind) {
div class="flex flex-wrap items-start justify-between gap-3" {
div class="flex flex-wrap items-center gap-2" {
span class="badge" { (inc.kind) }
span class="badge-outline" { (inc.status) }
span class="badge-secondary" { "×" (inc.occurrences) }
@if let Some(code) = inc.status_code {
span class="badge-outline" { "HTTP " (code) }
}
@if let Some(ref assignee) = inc.assignee {
span class="badge-secondary" { "Assignee: " (assignee) }
}
@if let (Some(ref ext_key), Some(ref ext_url)) = (&inc.external_issue_key, &inc.external_issue_url) {
@if is_safe_http_url(ext_url) {
a
href=(ext_url)
target="_blank"
rel="noopener noreferrer"
class="badge-outline underline"
{
(ext_key)
}
}
}
code class="text-xs text-muted-foreground" { (inc.id) }
}
div class="flex flex-wrap items-center gap-2" {
@if inc.status == "open" {
form
method="post"
action=(format!("/_slabs/incidents/{}/claim", inc.id))
class="flex items-center gap-1"
{
input
type="text"
name="assignee"
placeholder="Assignee"
required
class="input w-32 text-xs"
;
button type="submit" class="btn-outline" { "Claim" }
}
}
@if inc.status == "open" || inc.status == "in_progress" {
form method="post" action=(format!("/_slabs/incidents/{}/ignore", inc.id)) {
button type="submit" class="btn-outline" { "Ignore" }
}
form method="post" action=(format!("/_slabs/incidents/{}/resolve", inc.id)) {
button type="submit" class="btn-outline" { "Resolve" }
}
}
}
}
div class="grid gap-1" {
h2 class="text-base font-semibold break-words" { (inc.error_message) }
p class="text-sm text-muted-foreground" {
"Source: " code { (inc.source_file) }
@if let Some(ref route) = inc.route_pattern {
" · Route: " code { (route) }
}
@if let Some(ref sha) = inc.git_sha {
" · Git: " code { (sha) }
}
}
p class="text-xs text-muted-foreground" {
"First seen: " (inc.first_seen_at) " · Last seen: " (inc.last_seen_at)
@if let Some(ref rsha) = inc.resolved_in_sha {
" · Resolved in: " code { (rsha) }
}
}
}
@if let Some(ref detail) = inc.detail {
@if detail != &inc.error_message {
pre class="rounded bg-muted p-3 text-xs overflow-x-auto whitespace-pre-wrap" { (detail) }
}
}
@if !recent_occurrences.is_empty() {
section class="grid gap-1.5 border-t pt-3" {
h3 class="text-xs font-medium text-muted-foreground" {
"Recent occurrences (" (recent_occurrences.len()) ")"
}
ul class="grid gap-1 text-xs font-mono text-muted-foreground" {
@for occ in recent_occurrences.iter().rev() {
li {
@if let Some(ref ts) = occ.seen_at {
(ts)
}
@if let Some(ref sha) = occ.git_sha {
" · sha=" code { (sha) }
}
@if let Some(ref req_id) = occ.request_id {
" · req=" code { (req_id) }
}
@if let Some(ms) = occ.latency_ms {
" · " (ms) "ms"
}
}
}
}
}
}
@if !attachments.is_empty() {
section class="grid gap-3 border-t pt-3" {
h3 class="text-sm font-medium" { "Attachments (" (attachments.len()) ")" }
div class="flex flex-wrap gap-4" {
@for att in &attachments {
@let href = format!("/_slabs/incidents/{}/attachments/{}", inc.id, att.blob_id);
div class="grid gap-1.5" {
@if att.is_screenshot || is_passive_image_content_type(&att.content_type) {
a href=(href) target="_blank" rel="noopener noreferrer" {
img
src=(href)
alt=(att.filename)
loading="lazy"
class="max-h-64 max-w-md rounded border object-contain"
;
}
}
a
href=(href)
class="text-sm underline"
{
(att.filename) " (" (att.content_type) ")"
@if let Some(sz) = att.byte_size {
" · " (sz) " B"
}
}
}
}
}
}
}
details class="text-xs" {
summary class="cursor-pointer text-muted-foreground" { "Diagnostic context & repro hint" }
p class="mt-2 font-mono" { (hint) }
pre class="mt-2 rounded bg-muted p-3 overflow-x-auto" { (pretty_ctx) }
}
}
}
}
}
}
};
slabs_html::document("Slabs Incidents", &[], &[], body).into_response()
}
async fn incident_attachment_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
Path((id, blob_id)): Path<(String, String)>,
) -> Response {
if let Some(resp) = authorize_diagnostics(&ctx, &headers, &jar).await {
return resp;
}
let incident = match ctx.incidents.get(&id).await {
Ok(Some(inc)) => inc,
Ok(None) => return SlabError::not_found("incident not found").into_response(),
Err(err) => return err.into_response(),
};
let attachments = parse_incident_attachments(&incident.context_json);
if !attachments.iter().any(|att| att.blob_id == blob_id) {
return SlabError::not_found("attachment not found for incident").into_response();
}
match ctx.storage.get_scoped(&blob_id, Some("bug_report")).await {
Ok(Some((meta, bytes))) => meta.into_safe_response(bytes, true),
Ok(None) => SlabError::not_found("attachment not found for incident").into_response(),
Err(err) => err.into_response(),
}
}
fn sanitize_client_path(raw: Option<&str>) -> Option<String> {
let trimmed = raw?.trim();
if trimmed.is_empty() {
return None;
}
let path_only = if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
trimmed
.parse::<Uri>()
.ok()
.map_or_else(|| "/".to_owned(), |u| u.path().to_owned())
} else {
trimmed.split(['?', '#']).next().unwrap_or("/").to_owned()
};
let clean = path_only.trim();
if clean.is_empty() {
None
} else {
Some(clean.chars().take(256).collect())
}
}
async fn client_errors_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
extensions: http::Extensions,
body: Bytes,
) -> Response {
let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|c| c.0);
let ip = client_ip(&headers, peer, ctx.config.trust_proxy);
if let Err(err) = ctx
.rate_limit
.check(&format!("slabs_client_errors:{ip}"), 20, 60)
{
return err.into_response();
}
if body.len() > MAX_CLIENT_ERROR_BYTES {
return (
StatusCode::PAYLOAD_TOO_LARGE,
Json(json!({
"error": "payload_too_large",
"message": "client error payload exceeds 4096 bytes",
})),
)
.into_response();
}
let payload: ClientErrorPayload = match serde_json::from_slice(&body) {
Ok(parsed) => parsed,
Err(err) => {
return SlabError::bad_request(format!("invalid client error JSON: {err}"))
.into_response();
}
};
let message = payload.message.trim();
if message.is_empty() {
return SlabError::validation("message", "cannot be empty").into_response();
}
let route_pattern = sanitize_client_path(payload.path.as_deref());
let client_kind = payload
.kind
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("error")
.chars()
.take(64)
.collect::<String>();
let input = IncidentInput {
kind: "client_error".into(),
source_file: "browser".into(),
route_pattern,
status_code: None,
error_message: message.to_owned(),
detail: payload.detail,
context_json: json!({
"client_kind": client_kind,
"env": ctx.config.env.as_str(),
"git_sha": ctx.config.git_sha,
}),
git_sha: ctx.config.git_sha.clone(),
custom_fingerprint: None,
};
match record_and_notify_incident(&ctx, input).await {
Some(record) => (
StatusCode::ACCEPTED,
Json(json!({
"id": record.id,
"status": record.status,
})),
)
.into_response(),
None => SlabError::internal("failed to record client error").into_response(),
}
}
struct PendingBugFile {
filename: String,
content_type: Option<String>,
bytes: Bytes,
is_screenshot: bool,
}
fn sanitize_source_file(raw: &str) -> String {
let cleaned: String = raw
.trim()
.chars()
.filter(|&c| !c.is_ascii_control() && c != '\\')
.take(MAX_BUG_SOURCE_FILE_CHARS)
.collect();
let trimmed = cleaned.trim();
if trimmed.is_empty() || trimmed.contains("..") {
"browser".to_owned()
} else {
trimmed.to_owned()
}
}
fn resolve_screenshot_content_type(
content_type: Option<&str>,
filename: &str,
) -> SlabResult<&'static str> {
let ct = content_type
.and_then(|v| v.split(';').next())
.map(|s| s.trim().to_ascii_lowercase())
.filter(|s| !s.is_empty());
match ct.as_deref() {
Some("image/png") => return Ok("image/png"),
Some("image/jpeg" | "image/jpg") => return Ok("image/jpeg"),
Some("image/webp") => return Ok("image/webp"),
Some(_) => {
return Err(SlabError::bad_request(
"screenshot must be image/png, image/jpeg, or image/webp",
));
}
None => {}
}
let ext = std::path::Path::new(filename)
.extension()
.and_then(|e| e.to_str());
if ext.is_some_and(|e| e.eq_ignore_ascii_case("png")) {
Ok("image/png")
} else if ext.is_some_and(|e| e.eq_ignore_ascii_case("jpg") || e.eq_ignore_ascii_case("jpeg")) {
Ok("image/jpeg")
} else if ext.is_some_and(|e| e.eq_ignore_ascii_case("webp")) {
Ok("image/webp")
} else {
Err(SlabError::bad_request(
"screenshot must be image/png, image/jpeg, or image/webp",
))
}
}
async fn read_multipart_bytes(
field: &mut axum::extract::multipart::Field<'_>,
max_bytes: usize,
label: &str,
) -> SlabResult<Bytes> {
let mut buf = Vec::new();
while let Some(chunk) = field.chunk().await.map_err(|e| {
SlabError::bad_request(format!("failed to read multipart field `{label}`: {e}"))
})? {
if buf.len().saturating_add(chunk.len()) > max_bytes {
return Err(SlabError::bad_request(format!(
"{label} exceeds maximum allowed {max_bytes} bytes"
)));
}
buf.extend_from_slice(&chunk);
}
Ok(Bytes::from(buf))
}
fn redact_bug_metadata(value: Value) -> (Value, Option<String>) {
let Value::Object(mut map) = value else {
return (json!({}), None);
};
for sensitive in [
"cookies",
"cookie",
"authorization",
"token",
"secret",
"href",
"query",
] {
map.remove(sensitive);
}
let route_pattern = map
.get("url_path")
.and_then(Value::as_str)
.and_then(|raw| sanitize_client_path(Some(raw)));
if let Some(ref clean_path) = route_pattern {
map.insert("url_path".into(), Value::String(clean_path.clone()));
} else {
map.remove("url_path");
}
if let Some(Value::Array(errors)) = map.get_mut("recent_errors") {
if errors.len() > 10 {
let drain_count = errors.len() - 10;
errors.drain(..drain_count);
}
}
(Value::Object(map), route_pattern)
}
async fn bug_reports_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
jar: CookieJar,
extensions: http::Extensions,
mut multipart: Multipart,
) -> Response {
if !ctx.config.bug_reporter_enabled {
return SlabError::not_found("bug reporter is disabled").into_response();
}
let session = match ctx.auth.optional_session(&jar).await {
Ok(s) => s,
Err(err) => return err.into_response(),
};
if session.is_none() && !ctx.config.bug_reporter_allow_anonymous {
return SlabError::unauthorized("authentication required to submit bug reports")
.into_response();
}
let rate_key = if let Some(ref s) = session {
format!("slabs_bug_reports:user:{}", s.user_id)
} else {
let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|c| c.0);
let ip = client_ip(&headers, peer, ctx.config.trust_proxy);
format!("slabs_bug_reports:ip:{ip}")
};
if let Err(err) = ctx.rate_limit.check(&rate_key, 10, 300) {
return err.into_response();
}
let max_screenshot_bytes = MAX_BUG_SCREENSHOT_BYTES.min(ctx.config.max_blob_bytes);
let max_attachment_bytes = MAX_BUG_ATTACHMENT_BYTES.min(ctx.config.max_blob_bytes);
let mut description: Option<String> = None;
let mut source_file: Option<String> = None;
let mut metadata: Value = json!({});
let mut route_pattern: Option<String> = None;
let mut pending_screenshot: Option<PendingBugFile> = None;
let mut pending_attachments: Vec<PendingBugFile> = Vec::new();
loop {
let next_field = match multipart.next_field().await {
Ok(Some(field)) => field,
Ok(None) => break,
Err(err) => {
return SlabError::bad_request(format!("invalid multipart payload: {err}"))
.into_response();
}
};
let mut field = next_field;
let field_name = field.name().unwrap_or("").to_owned();
match field_name.as_str() {
"description" => {
let bytes = match read_multipart_bytes(&mut field, 32 * 1024, "description").await {
Ok(b) => b,
Err(err) => return err.into_response(),
};
let Ok(text) = String::from_utf8(bytes.to_vec()) else {
return SlabError::bad_request("description must be valid UTF-8")
.into_response();
};
description = Some(text);
}
"source_file" => {
let bytes = match read_multipart_bytes(&mut field, 1024, "source_file").await {
Ok(b) => b,
Err(err) => return err.into_response(),
};
if let Ok(text) = String::from_utf8(bytes.to_vec()) {
source_file = Some(sanitize_source_file(&text));
}
}
"metadata_json" => {
let bytes =
match read_multipart_bytes(&mut field, MAX_BUG_METADATA_BYTES, "metadata_json")
.await
{
Ok(b) => b,
Err(err) => return err.into_response(),
};
if !bytes.iter().all(u8::is_ascii_whitespace) {
let parsed: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(err) => {
return SlabError::bad_request(format!("invalid metadata_json: {err}"))
.into_response();
}
};
let (redacted, path) = redact_bug_metadata(parsed);
metadata = redacted;
route_pattern = path;
}
}
"screenshot" => {
let filename = field
.file_name()
.filter(|s| !s.trim().is_empty())
.unwrap_or("screenshot.png")
.to_owned();
let content_type = field.content_type().map(ToOwned::to_owned);
let bytes = match read_multipart_bytes(
&mut field,
max_screenshot_bytes,
"screenshot",
)
.await
{
Ok(b) => b,
Err(err) => return err.into_response(),
};
if bytes.is_empty() {
continue;
}
let validated_ct =
match resolve_screenshot_content_type(content_type.as_deref(), &filename) {
Ok(ct) => ct,
Err(err) => return err.into_response(),
};
pending_screenshot = Some(PendingBugFile {
filename,
content_type: Some(validated_ct.to_owned()),
bytes,
is_screenshot: true,
});
}
"attachments" => {
let filename = field
.file_name()
.filter(|s| !s.trim().is_empty())
.unwrap_or("attachment.bin")
.to_owned();
let content_type = field.content_type().map(ToOwned::to_owned);
let bytes =
match read_multipart_bytes(&mut field, max_attachment_bytes, "attachments")
.await
{
Ok(b) => b,
Err(err) => return err.into_response(),
};
if bytes.is_empty() {
continue;
}
if pending_attachments.len() >= MAX_BUG_ATTACHMENTS {
return SlabError::bad_request("at most 3 attachments are allowed")
.into_response();
}
pending_attachments.push(PendingBugFile {
filename,
content_type,
bytes,
is_screenshot: false,
});
}
_ => {}
}
}
let trimmed_desc = description.as_deref().map_or("", str::trim);
let desc_chars = trimmed_desc.chars().count();
if desc_chars < MIN_BUG_DESCRIPTION_CHARS {
return SlabError::validation(
"description",
format!("must be at least {MIN_BUG_DESCRIPTION_CHARS} characters"),
)
.into_response();
}
if desc_chars > MAX_BUG_DESCRIPTION_CHARS {
return SlabError::validation(
"description",
format!("must be at most {MAX_BUG_DESCRIPTION_CHARS} characters"),
)
.into_response();
}
let mut stored_attachments: Vec<Value> = Vec::new();
let files_to_store = pending_screenshot.into_iter().chain(pending_attachments);
for file in files_to_store {
let meta = match ctx
.storage
.put_scoped(
"bug_report",
&file.filename,
file.content_type.as_deref(),
&file.bytes,
)
.await
{
Ok(m) => m,
Err(err) => return err.into_response(),
};
stored_attachments.push(json!({
"blob_id": meta.id,
"filename": meta.filename,
"content_type": meta.content_type,
"byte_size": meta.byte_size,
"is_screenshot": file.is_screenshot,
}));
}
let input = IncidentInput {
kind: "user_bug_report".into(),
source_file: source_file.unwrap_or_else(|| "browser".to_owned()),
route_pattern,
status_code: None,
error_message: trimmed_desc.to_owned(),
detail: Some(trimmed_desc.to_owned()),
context_json: json!({
"reporter_user_id": session.as_ref().map(|s| s.user_id.as_str()),
"reporter_role": session.as_ref().map(|s| s.role.as_str()),
"attachments": stored_attachments,
"client": metadata,
"env": ctx.config.env.as_str(),
"git_sha": ctx.config.git_sha,
}),
git_sha: ctx.config.git_sha.clone(),
custom_fingerprint: Some(slabs_core::id::new("bug")),
};
match record_and_notify_incident(&ctx, input).await {
Some(record) => (
StatusCode::CREATED,
Json(json!({
"id": record.id,
"status": "open",
"attachments": stored_attachments,
})),
)
.into_response(),
None => SlabError::internal("failed to record bug report").into_response(),
}
}
async fn dev_mail_outbox_handler(State(ctx): State<AppCtx>) -> SlabResult<Json<Value>> {
let sent = ctx.mail.list_sent(50).await?;
Ok(Json(json!({ "emails": sent })))
}
fn compute_etag(body: &str) -> HeaderValue {
let digest = Sha256::digest(body.as_bytes());
let tag = format!("\"{}\"", &hex::encode(digest)[..16]);
HeaderValue::from_str(&tag).unwrap_or_else(|_| HeaderValue::from_static("\"0\""))
}
fn vendor_response(
req_headers: &HeaderMap,
content_type: &'static str,
body: &'static str,
etag_cell: &'static OnceLock<HeaderValue>,
) -> Response {
let etag = etag_cell.get_or_init(|| compute_etag(body)).clone();
if req_headers
.get(header::IF_NONE_MATCH)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.trim() == etag.to_str().unwrap_or_default())
{
return (
StatusCode::NOT_MODIFIED,
[
(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=86400"),
),
(header::ETAG, etag),
],
)
.into_response();
}
(
StatusCode::OK,
[
(header::CONTENT_TYPE, HeaderValue::from_static(content_type)),
(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=86400"),
),
(header::ETAG, etag),
],
body,
)
.into_response()
}
async fn vendor_basecoat_css(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(&headers, "text/css; charset=utf-8", BASECOAT_CSS, &ETAG)
}
async fn vendor_basecoat_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/basecoat.min.js"),
&ETAG,
)
}
async fn vendor_htmx_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/htmx.min.js"),
&ETAG,
)
}
async fn vendor_htmx_sse_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/htmx-ext-sse.js"),
&ETAG,
)
}
async fn vendor_idiomorph_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/idiomorph-ext.min.js"),
&ETAG,
)
}
async fn vendor_alpine_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
include_str!("../assets/vendor/alpine.min.js"),
&ETAG,
)
}
async fn vendor_sw_register_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
slabs_html::SW_REGISTER_JS,
&ETAG,
)
}
async fn vendor_slabs_telemetry_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
SLABS_TELEMETRY_JS,
&ETAG,
)
}
async fn vendor_slabs_bug_report_js(headers: HeaderMap) -> Response {
static ETAG: OnceLock<HeaderValue> = OnceLock::new();
vendor_response(
&headers,
"text/javascript; charset=utf-8",
slabs_html::BUG_REPORT_JS,
&ETAG,
)
}
fn is_active_document_content_type(content_type: &str) -> bool {
let mime = content_type
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
matches!(
mime.as_str(),
"image/svg+xml" | "text/html" | "application/xhtml+xml"
)
}
async fn serve_asset_handler(
State(ctx): State<AppCtx>,
Path((hash, path)): Path<(String, String)>,
) -> SlabResult<Response> {
let Some(entry) = ctx.assets.get(&hash, &path) else {
return Err(SlabError::not_found("asset not found"));
};
let ct = HeaderValue::from_str(&entry.content_type)
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
let mut headers = HeaderMap::new();
headers.insert(header::CONTENT_TYPE, ct);
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
if is_active_document_content_type(&entry.content_type) {
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; style-src 'unsafe-inline'; sandbox"),
);
}
Ok((StatusCode::OK, headers, entry.bytes.clone()).into_response())
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use http_body_util::BodyExt;
use slabs_core::AppEnv;
use std::path::PathBuf;
use tower::ServiceExt;
async fn test_ctx(mut config: AppConfig) -> AppCtx {
config.database_url = "sqlite::memory:".into();
let ctx = AppCtx::connect(config).await.unwrap();
ctx.db.init_system_tables().await.unwrap();
ctx
}
async fn send(router: &Router, req: http::Request<Body>) -> (StatusCode, HeaderMap, String) {
let resp = router.clone().oneshot(req).await.unwrap();
let status = resp.status();
let headers = resp.headers().clone();
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
(status, headers, String::from_utf8_lossy(&bytes).to_string())
}
#[tokio::test]
async fn dev_routes_are_disabled_in_production_and_enabled_in_test() {
let mut prod_cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_prod"));
prod_cfg.env = AppEnv::Production;
let prod_ctx = test_ctx(prod_cfg).await;
let prod_router = build_router(prod_ctx, vec![], &[]);
for path in [
"/_slabs/mail",
"/_slabs/manifest",
"/_slabs/openapi.json",
"/_slabs/metrics",
] {
let req = http::Request::builder()
.uri(path)
.body(Body::empty())
.unwrap();
let (status, _, _) = send(&prod_router, req).await;
assert_eq!(status, StatusCode::NOT_FOUND, "{path} must be 404 in prod");
}
let dev_cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_dev"));
let dev_ctx = test_ctx(dev_cfg).await;
let dev_router = build_router(dev_ctx, vec![], &[]);
for path in [
"/_slabs/mail",
"/_slabs/manifest",
"/_slabs/openapi.json",
"/_slabs/metrics",
] {
let req = http::Request::builder()
.uri(path)
.body(Body::empty())
.unwrap();
let (status, _, _) = send(&dev_router, req).await;
assert_eq!(status, StatusCode::OK, "{path} must be 200 in test");
}
}
#[tokio::test]
async fn health_probes_and_draining_behavior() {
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_health"));
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/health/live")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
ctx.set_draining();
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn metrics_token_enforces_bearer_auth_and_supports_json_and_prometheus() {
let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_metrics"));
cfg.env = AppEnv::Production;
cfg.metrics_token = Some("super-secret-metrics-token".into());
let ctx = test_ctx(cfg).await;
let router = build_router(ctx, vec![], &[]);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/_slabs/metrics")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/_slabs/metrics")
.header(header::AUTHORIZATION, "Bearer wrong-token")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/metrics")
.header(header::AUTHORIZATION, "Bearer super-secret-metrics-token")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(body.contains("slabs_http_requests_total"));
assert!(body.contains("slabs_jobs_pending"));
assert!(body.contains("slabs_realtime_active_topics"));
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/metrics")
.header(header::AUTHORIZATION, "Bearer super-secret-metrics-token")
.header(header::ACCEPT, "application/json")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let parsed: Value = serde_json::from_str(&body).unwrap();
assert!(parsed["http"]["requests_total"].as_u64().unwrap() >= 3);
}
#[tokio::test]
async fn csrf_middleware_blocks_cross_site_cookie_mutations_and_exempts_bearer_and_skip_csrf() {
async fn ok_handler() -> &'static str {
"ok"
}
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_csrf"));
let ctx = test_ctx(cfg).await;
let router = build_router(
ctx,
vec![
SlabDef::post("/api/items", ok_handler),
SlabDef::post("/api/webhooks", ok_handler),
SlabDef::post("/webhooks/{provider}", ok_handler).skip_csrf(),
],
&[],
);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/api/items")
.header(header::COOKIE, "slabs_session=abc")
.header("sec-fetch-site", "cross-site")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/api/webhooks")
.header(header::COOKIE, "slabs_session=abc")
.header("sec-fetch-site", "cross-site")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/api/items")
.header(header::COOKIE, "slabs_session=abc")
.header(header::HOST, "app.example.com")
.header(header::ORIGIN, "https://evil.test")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/api/items")
.header(header::COOKIE, "slabs_session=abc")
.header(header::HOST, "app.example.com")
.header(header::ORIGIN, "https://app.example.com")
.header("sec-fetch-site", "same-origin")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/api/items")
.header(header::COOKIE, "slabs_session=abc")
.header(header::AUTHORIZATION, "Bearer slb_123")
.header("sec-fetch-site", "cross-site")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/webhooks/stripe")
.header(header::COOKIE, "slabs_session=abc")
.header("sec-fetch-site", "cross-site")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/client-errors")
.header(header::COOKIE, "slabs_session=abc")
.header("sec-fetch-site", "cross-site")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"message":"beacon error","path":"/app"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::ACCEPTED);
}
#[tokio::test]
async fn security_headers_cors_request_id_and_vendor_assets() {
let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_headers"));
cfg.cookie_secure = true;
let ctx = test_ctx(cfg).await;
let router = build_router(ctx, vec![], &[]);
let (status, headers, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/vendor/sw-register.js")
.header("x-request-id", "bad id with spaces!")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(body.contains("navigator.serviceWorker.register(\"/sw.js\")"));
assert!(headers.contains_key(header::ETAG));
assert_eq!(
headers
.get(header::REFERRER_POLICY)
.and_then(|v| v.to_str().ok()),
Some("strict-origin-when-cross-origin")
);
assert_eq!(
headers
.get("permissions-policy")
.and_then(|v| v.to_str().ok()),
Some("camera=(), microphone=(), geolocation=()")
);
assert_eq!(
headers
.get(header::STRICT_TRANSPORT_SECURITY)
.and_then(|v| v.to_str().ok()),
Some("max-age=31536000; includeSubDomains")
);
assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
let req_id = headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.unwrap();
assert!(req_id.starts_with("req_"));
let (status, headers, css) = send(
&router,
http::Request::builder()
.uri("/_slabs/vendor/basecoat.min.css")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(css.starts_with("@view-transition { navigation: auto; }"));
assert!(headers.contains_key(header::ETAG));
}
#[tokio::test]
async fn asset_handler_sandboxes_svg_and_html_with_csp() {
let dir = std::env::temp_dir().join(format!("slabs_http_svg_{}", slabs_core::id::new("d")));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("icon.svg"), "<svg></svg>").unwrap();
let mut cfg = AppConfig::for_test("demo", dir.clone());
cfg.assets_dir = dir.clone();
let ctx = test_ctx(cfg).await;
let url = ctx.assets.url("icon.svg");
let router = build_router(ctx, vec![], &[]);
let (status, headers, _) = send(
&router,
http::Request::builder()
.uri(&url)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
headers
.get(header::CONTENT_SECURITY_POLICY)
.and_then(|v| v.to_str().ok()),
Some("default-src 'none'; style-src 'unsafe-inline'; sandbox")
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn client_ip_respects_trust_proxy_and_rightmost_xff() {
let peer: SocketAddr = "10.0.0.5:12345".parse().unwrap();
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
HeaderValue::from_static("1.2.3.4, 203.0.113.9"),
);
assert_eq!(client_ip(&headers, Some(peer), false), "10.0.0.5");
assert_eq!(client_ip(&headers, Some(peer), true), "203.0.113.9");
headers.insert("cf-connecting-ip", HeaderValue::from_static("198.51.100.7"));
assert_eq!(client_ip(&headers, Some(peer), true), "198.51.100.7");
}
#[tokio::test]
async fn client_ip_extractor_falls_back_in_tests_and_respects_trust_proxy() {
async fn echo_ip(ClientIp(ip): ClientIp) -> String {
ip
}
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_client_ip"));
let ctx = test_ctx(cfg).await;
let router = build_router(ctx, vec![SlabDef::get("/ip", echo_ip)], &[]);
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/ip")
.header("cf-connecting-ip", "198.51.100.7")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "127.0.0.1");
let mut req_with_peer = http::Request::builder()
.uri("/ip")
.header("x-forwarded-for", "203.0.113.9")
.body(Body::empty())
.unwrap();
req_with_peer
.extensions_mut()
.insert(ConnectInfo::<SocketAddr>("10.0.0.5:4321".parse().unwrap()));
let (status, _, body) = send(&router, req_with_peer).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "10.0.0.5");
let mut proxy_cfg =
AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_client_ip_proxy"));
proxy_cfg.trust_proxy = true;
let proxy_ctx = test_ctx(proxy_cfg).await;
let proxy_router = build_router(proxy_ctx, vec![SlabDef::get("/ip", echo_ip)], &[]);
let (status, _, body) = send(
&proxy_router,
http::Request::builder()
.uri("/ip")
.header("x-forwarded-for", "1.2.3.4, 203.0.113.9")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, "203.0.113.9");
}
#[test]
fn rate_limiter_check_pair_enforces_both_ip_and_account_limits() {
let rl = RateLimiter::new();
rl.check_pair("ip:1.1.1.1", 2, "acct:a@example.com", 5, 60)
.unwrap();
rl.check_pair("ip:1.1.1.1", 2, "acct:b@example.com", 5, 60)
.unwrap();
let ip_err = rl
.check_pair("ip:1.1.1.1", 2, "acct:c@example.com", 5, 60)
.unwrap_err();
assert_eq!(ip_err.status_code(), StatusCode::TOO_MANY_REQUESTS);
rl.check_pair("ip:2.2.2.2", 5, "acct:victim@example.com", 2, 60)
.unwrap();
rl.check_pair("ip:3.3.3.3", 5, "acct:victim@example.com", 2, 60)
.unwrap();
let acct_err = rl
.check_pair("ip:4.4.4.4", 5, "acct:victim@example.com", 2, 60)
.unwrap_err();
assert_eq!(acct_err.status_code(), StatusCode::TOO_MANY_REQUESTS);
rl.check_pair("ip:5.5.5.5", 5, "acct:c@example.com", 1, 60)
.unwrap();
}
#[tokio::test]
async fn job_registry_dispatch_dead_letters_poison_pill_json() {
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_poison"));
let ctx = test_ctx(cfg).await;
let job_id = ctx
.jobs
.enqueue("demo.job", json!({ "ok": true }))
.await
.unwrap();
let mut tx = ctx.db.begin().await.unwrap();
sqlx::query("UPDATE slabs_jobs SET payload_json = '{not-json' WHERE id = ?")
.bind(&job_id)
.execute(&mut *tx)
.await
.unwrap();
tx.commit().await.unwrap();
let registry = JobRegistry::new(vec![JobDef::new("demo.job", |_ctx, _v| async { Ok(()) })]);
let claimed = ctx.jobs.claim_next().await.unwrap().unwrap();
assert!(registry.dispatch(&ctx, &claimed).await.is_err());
let stats = ctx.jobs.stats().await.unwrap();
assert_eq!(stats.dead, 1);
assert_eq!(stats.running, 0);
}
#[tokio::test]
async fn middleware_captures_panics_5xx_slow_requests_and_route_histograms() {
async fn panic_handler() -> &'static str {
panic!("boom in room handler")
}
async fn err_5xx_handler() -> SlabResult<&'static str> {
Err(SlabError::internal("db connection lost"))
}
async fn slow_handler() -> &'static str {
tokio::time::sleep(Duration::from_millis(25)).await;
"slow ok"
}
async fn fast_handler() -> &'static str {
"fast ok"
}
let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_incidents"));
cfg.slow_request_ms = 15;
cfg.git_sha = Some("sha_abc123".into());
let ctx = test_ctx(cfg).await;
let router = build_router(
ctx.clone(),
vec![
SlabDef::get("/api/rooms/{room_id}/boom", panic_handler).name("rooms::boom"),
SlabDef::get("/api/rooms/{room_id}/fail", err_5xx_handler).name("rooms::fail"),
SlabDef::get("/api/rooms/{room_id}/slow", slow_handler).name("rooms::slow"),
SlabDef::get("/api/rooms/{room_id}/fast", fast_handler).name("rooms::fast"),
],
&[],
);
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/api/rooms/room_42/boom")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
let panic_body: Value = serde_json::from_str(&body).unwrap();
assert_eq!(panic_body["error"], "internal server error");
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/api/rooms/room_42/fail")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/api/rooms/room_42/slow")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/api/rooms/room_42/fast")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents?status=open&limit=20")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let parsed: Value = serde_json::from_str(&body).unwrap();
let incidents = parsed["incidents"].as_array().unwrap();
assert_eq!(incidents.len(), 3, "got incidents: {incidents:?}");
let panic_inc = incidents.iter().find(|i| i["kind"] == "panic").unwrap();
assert_eq!(panic_inc["source_file"], "slabs/rooms/boom.rs");
assert_eq!(panic_inc["route_pattern"], "/api/rooms/{room_id}/boom");
assert_eq!(panic_inc["status_code"], 500);
assert_eq!(panic_inc["git_sha"], "sha_abc123");
assert!(panic_inc["repro_hint"]
.as_str()
.unwrap()
.contains("slabs/rooms/boom.rs"));
let http_5xx_inc = incidents.iter().find(|i| i["kind"] == "http_5xx").unwrap();
assert_eq!(http_5xx_inc["source_file"], "slabs/rooms/fail.rs");
assert_eq!(http_5xx_inc["route_pattern"], "/api/rooms/{room_id}/fail");
let slow_inc = incidents
.iter()
.find(|i| i["kind"] == "slow_request")
.unwrap();
assert_eq!(slow_inc["source_file"], "slabs/rooms/slow.rs");
assert_eq!(slow_inc["route_pattern"], "/api/rooms/{room_id}/slow");
let panic_id = panic_inc["id"].as_str().unwrap();
let (status, _, body) = send(
&router,
http::Request::builder()
.uri(format!("/_slabs/incidents/{panic_id}"))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let single: Value = serde_json::from_str(&body).unwrap();
assert_eq!(single["id"], panic_id);
assert!(single["repro_hint"].as_str().is_some());
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{panic_id}/resolve"))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"resolved_in_sha":"sha_fix_999"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/metrics")
.header(header::ACCEPT, "application/json")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let metrics_json: Value = serde_json::from_str(&body).unwrap();
assert_eq!(metrics_json["open_incidents"], 2);
let route_metrics = metrics_json["routes"].as_array().unwrap();
let slow_route = route_metrics
.iter()
.find(|r| r["route"] == "/api/rooms/{room_id}/slow")
.unwrap();
assert_eq!(slow_route["source_file"], "slabs/rooms/slow.rs");
assert_eq!(slow_route["slow_requests"], 1);
assert!(slow_route["p95_ms"].as_u64().unwrap() >= 15);
assert!(slow_route["max_latency_ms"].as_u64().unwrap() >= 15);
let (status, _, prom) = send(
&router,
http::Request::builder()
.uri("/_slabs/metrics")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(prom.contains("slabs_incidents_open 2"));
assert!(prom.contains("slabs_route_requests_total"));
assert!(prom.contains("slabs_route_slow_total"));
assert!(prom.contains("slabs_route_p95_ms"));
}
#[tokio::test]
async fn incidents_api_enforces_observability_auth_gate() {
let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_inc_auth"));
cfg.env = AppEnv::Production;
let ctx_no_tok = test_ctx(cfg.clone()).await;
let router_no_tok = build_router(ctx_no_tok, vec![], &[]);
for path in ["/_slabs/incidents", "/_slabs/incidents/inc_1"] {
let (status, _, _) = send(
&router_no_tok,
http::Request::builder()
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
}
cfg.metrics_token = Some("incident-secret-token".into());
let ctx_tok = test_ctx(cfg).await;
let router_tok = build_router(ctx_tok, vec![], &[]);
let (status, _, _) = send(
&router_tok,
http::Request::builder()
.uri("/_slabs/incidents")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (status, _, _) = send(
&router_tok,
http::Request::builder()
.uri("/_slabs/incidents")
.header(header::AUTHORIZATION, "Bearer incident-secret-token")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
}
#[tokio::test]
async fn client_error_beacon_strips_query_enforces_cap_and_rate_limit_and_serves_vendor_js() {
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_beacon"));
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let (status, headers, js) = send(
&router,
http::Request::builder()
.uri("/_slabs/vendor/slabs-telemetry.js")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(headers.contains_key(header::ETAG));
assert!(js.contains("sendBeacon"));
assert!(js.contains("/_slabs/client-errors"));
assert!(js.contains("htmx:targetError"));
assert!(js.contains("htmx:swapError"));
let (status, _, body) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/client-errors")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
r#"{"kind":"htmx:swapError","message":"Swap failed","path":"/rooms/123?token=secret_pii&email=a@b.com","detail":"target missing"}"#,
))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::ACCEPTED);
let parsed: Value = serde_json::from_str(&body).unwrap();
let inc_id = parsed["id"].as_str().unwrap();
let stored = ctx.incidents.get(inc_id).await.unwrap().unwrap();
assert_eq!(stored.kind, "client_error");
assert_eq!(stored.source_file, "browser");
assert_eq!(stored.route_pattern.as_deref(), Some("/rooms/123"));
assert!(!stored.context_json.contains("secret_pii"));
let big_payload = format!(
r#"{{"message":"{}"}}"#,
"x".repeat(MAX_CLIENT_ERROR_BYTES + 10)
);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/client-errors")
.body(Body::from(big_payload))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
for _ in 0..18 {
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/client-errors")
.body(Body::from(
r#"{"message":"repeated error","path":"/rooms/1"}"#,
))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::ACCEPTED);
}
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/client-errors")
.body(Body::from(r#"{"message":"over limit","path":"/rooms/1"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
}
type MultipartPart<'a> = (&'a str, Option<(&'a str, &'a str)>, &'a [u8]);
type ReceivedWebhook = (String, Option<String>, Bytes);
fn build_multipart_body(boundary: &str, parts: &[MultipartPart<'_>]) -> Vec<u8> {
let mut out = Vec::new();
for (name, file_meta, data) in parts {
out.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
if let Some((filename, ct)) = file_meta {
out.extend_from_slice(
format!(
"Content-Disposition: form-data; name=\"{name}\"; filename=\"{filename}\"\r\n\
Content-Type: {ct}\r\n\r\n"
)
.as_bytes(),
);
} else {
out.extend_from_slice(
format!("Content-Disposition: form-data; name=\"{name}\"\r\n\r\n").as_bytes(),
);
}
out.extend_from_slice(data);
out.extend_from_slice(b"\r\n");
}
out.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
out
}
#[tokio::test]
async fn bug_reports_endpoint_gates_auth_stores_attachments_and_serves_dashboard_safely() {
let storage_dir = std::env::temp_dir().join(format!(
"slabs_http_bug_reports_{}",
slabs_core::id::new("d")
));
let boundary = "----SlabsBugTestBoundary";
let disabled_cfg = AppConfig::for_test("demo", storage_dir.clone());
assert!(!disabled_cfg.bug_reporter_enabled);
let disabled_ctx = test_ctx(disabled_cfg).await;
let disabled_router = build_router(disabled_ctx, vec![], &[]);
let body_bytes = build_multipart_body(
boundary,
&[("description", None, b"Button broken on room page")],
);
let (status, _, _) = send(
&disabled_router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/bug-reports")
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
)
.body(Body::from(body_bytes.clone()))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
cfg.bug_reporter_enabled = true;
cfg.bug_reporter_allow_anonymous = false;
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let (status, headers, js) = send(
&router,
http::Request::builder()
.uri("/_slabs/vendor/slabs-bug-report.js")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(headers.contains_key(header::ETAG));
assert!(js.contains("/_slabs/bug-reports"));
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/bug-reports")
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
)
.body(Body::from(body_bytes))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
let (_session, cookie) = ctx
.auth
.create_session("usr_reporter_1", "member", 7)
.await
.unwrap();
let session_cookie = format!("{}={}", cookie.name(), cookie.value());
let png_bytes: &[u8] = b"\x89PNG\r\n\x1a\nfake-png-payload";
let html_bytes: &[u8] = b"<html><script>alert(1)</script></html>";
let meta_json = br#"{"url_path":"/rooms/123?secret=dontstore","viewport":"1440x900","recent_errors":[]}"#;
let full_body = build_multipart_body(
boundary,
&[
("description", None, b"Submit button freezes after click"),
("source_file", None, b"slabs/rooms/show.rs"),
("metadata_json", None, meta_json),
(
"screenshot",
Some(("screenshot.png", "image/png")),
png_bytes,
),
("attachments", Some(("repro.html", "text/html")), html_bytes),
],
);
let (status, _, resp_body) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/bug-reports")
.header(header::COOKIE, &session_cookie)
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
)
.body(Body::from(full_body.clone()))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::CREATED, "body: {resp_body}");
let created: Value = serde_json::from_str(&resp_body).unwrap();
let inc_id = created["id"].as_str().unwrap().to_owned();
assert_eq!(created["status"], "open");
let attachments = created["attachments"].as_array().unwrap();
assert_eq!(attachments.len(), 2);
let screenshot_blob_id = attachments[0]["blob_id"].as_str().unwrap().to_owned();
let html_blob_id = attachments[1]["blob_id"].as_str().unwrap().to_owned();
assert_eq!(attachments[0]["is_screenshot"], true);
assert_eq!(attachments[1]["is_screenshot"], false);
assert!(ctx
.storage
.get_scoped(&screenshot_blob_id, None)
.await
.unwrap()
.is_none());
assert!(ctx
.storage
.get_scoped(&html_blob_id, None)
.await
.unwrap()
.is_none());
let stored = ctx.incidents.get(&inc_id).await.unwrap().unwrap();
assert_eq!(stored.kind, "user_bug_report");
assert_eq!(stored.source_file, "slabs/rooms/show.rs");
assert_eq!(stored.route_pattern.as_deref(), Some("/rooms/123"));
assert!(!stored.context_json.contains("dontstore"));
assert!(stored.context_json.contains("usr_reporter_1"));
let (status, _, second_body) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri("/_slabs/bug-reports")
.header(header::COOKIE, &session_cookie)
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={boundary}"),
)
.body(Body::from(full_body))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::CREATED);
let second_created: Value = serde_json::from_str(&second_body).unwrap();
assert_ne!(second_created["id"], inc_id);
let (status, _, ui_html) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(ui_html.contains("Submit button freezes after click"));
assert!(ui_html.contains("slabs/rooms/show.rs"));
assert!(ui_html.contains(&format!(
"/_slabs/incidents/{inc_id}/attachments/{screenshot_blob_id}"
)));
assert!(ui_html.contains(&format!("/_slabs/incidents/{inc_id}/resolve")));
assert!(!ui_html.contains("<script>"));
assert!(!ui_html.contains("<style"));
let (status, headers, raw_png) = send(
&router,
http::Request::builder()
.uri(format!(
"/_slabs/incidents/{inc_id}/attachments/{screenshot_blob_id}"
))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
headers
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok()),
Some("image/png")
);
assert!(headers
.get(header::CONTENT_DISPOSITION)
.and_then(|v| v.to_str().ok())
.unwrap()
.starts_with("inline;"));
assert_eq!(
headers
.get(header::CONTENT_SECURITY_POLICY)
.and_then(|v| v.to_str().ok()),
Some("default-src 'none'; sandbox")
);
assert!(raw_png.contains("fake-png-payload"));
let (status, headers, _) = send(
&router,
http::Request::builder()
.uri(format!(
"/_slabs/incidents/{inc_id}/attachments/{html_blob_id}"
))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(headers
.get(header::CONTENT_DISPOSITION)
.and_then(|v| v.to_str().ok())
.unwrap()
.starts_with("attachment;"));
assert_eq!(
headers
.get(header::CONTENT_SECURITY_POLICY)
.and_then(|v| v.to_str().ok()),
Some("default-src 'none'; sandbox")
);
let unrelated = ctx
.storage
.put(
"secret.txt",
Some("text/plain"),
Bytes::from_static(b"top-secret"),
)
.await
.unwrap();
let (status, _, _) = send(
&router,
http::Request::builder()
.uri(format!(
"/_slabs/incidents/{inc_id}/attachments/{}",
unrelated.id
))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
let (status, headers, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{inc_id}/resolve"))
.header(header::ACCEPT, "text/html,application/xhtml+xml")
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::SEE_OTHER);
assert_eq!(
headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),
Some("/_slabs/incidents/ui")
);
let _ = std::fs::remove_dir_all(&storage_dir);
}
#[tokio::test]
async fn incidents_ui_enforces_prod_auth_and_allows_admin_session() {
let storage_dir =
std::env::temp_dir().join(format!("slabs_http_ui_auth_{}", slabs_core::id::new("d")));
let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
cfg.env = AppEnv::Production;
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
let (_, member_c) = ctx
.auth
.create_session("usr_member", "member", 7)
.await
.unwrap();
let member_cookie = format!("{}={}", member_c.name(), member_c.value());
let (status, _, _) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui")
.header(header::COOKIE, &member_cookie)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::FORBIDDEN);
let (_, admin_c) = ctx
.auth
.create_session("usr_admin", "admin", 7)
.await
.unwrap();
let admin_cookie = format!("{}={}", admin_c.name(), admin_c.value());
let (status, _, html) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui")
.header(header::COOKIE, &admin_cookie)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(html.contains("Incidents — demo"));
let _ = std::fs::remove_dir_all(&storage_dir);
}
#[tokio::test]
async fn signed_incident_protocol_webhooks_fire_on_opened_resolved_and_reopened() {
let received: Arc<Mutex<Vec<ReceivedWebhook>>> = Arc::new(Mutex::new(Vec::new()));
let recv_clone = received.clone();
let hook_app = Router::new().route(
"/hook",
post(move |headers: HeaderMap, body: Bytes| {
let store = recv_clone.clone();
async move {
let event = headers
.get("x-slabs-event")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_owned();
let sig = headers
.get("x-slabs-signature")
.and_then(|v| v.to_str().ok())
.map(ToOwned::to_owned);
store.lock().unwrap().push((event, sig, body));
StatusCode::OK
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, hook_app).await.unwrap() });
let secret = "whsec_incident_signing_secret";
let storage_dir =
std::env::temp_dir().join(format!("slabs_http_webhooks_{}", slabs_core::id::new("d")));
let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
cfg.webhooks_allow_local = true;
cfg.incident_webhook_url = Some(format!("http://{addr}/hook"));
cfg.incident_webhook_secret = Some(secret.into());
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let input = IncidentInput {
kind: "http_5xx".into(),
source_file: "slabs/orders/create.rs".into(),
route_pattern: Some("/api/orders".into()),
status_code: Some(500),
error_message: "payment timeout".into(),
detail: None,
context_json: json!({ "request_id": "req_1" }),
git_sha: Some("sha_v1".into()),
custom_fingerprint: None,
};
let rec = record_and_notify_incident(&ctx, input.clone())
.await
.unwrap();
let _ = record_and_notify_incident(&ctx, input.clone())
.await
.unwrap();
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/resolve", rec.id))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"resolved_in_sha":"sha_v2"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let _ = record_and_notify_incident(&ctx, input).await.unwrap();
for _ in 0..40 {
if received.lock().unwrap().len() >= 3 {
break;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
let events = received.lock().unwrap().clone();
assert_eq!(
events.len(),
3,
"expected 3 webhook deliveries, got {events:?}"
);
let event_names: Vec<&str> = events.iter().map(|(e, _, _)| e.as_str()).collect();
assert!(event_names.contains(&"incident.opened"));
assert!(event_names.contains(&"incident.resolved"));
assert!(event_names.contains(&"incident.reopened"));
for (event_hdr, sig_hdr, raw_body) in &events {
let expected_sig = sign_incident_webhook(secret, raw_body);
assert_eq!(sig_hdr.as_deref(), Some(expected_sig.as_str()));
let payload: Value = serde_json::from_slice(raw_body).unwrap();
assert_eq!(payload["protocol"], "slabs.incident.v1");
assert_eq!(payload["event"], event_hdr.as_str());
assert!(payload["sent_at"].as_str().is_some());
assert_eq!(payload["incident"]["id"], rec.id);
}
let _ = std::fs::remove_dir_all(&storage_dir);
}
#[tokio::test]
async fn incident_claim_link_ignore_endpoints_webhooks_and_ui() {
let received: Arc<Mutex<Vec<ReceivedWebhook>>> = Arc::new(Mutex::new(Vec::new()));
let recv_clone = received.clone();
let hook_app = Router::new().route(
"/hook",
post(move |headers: HeaderMap, body: Bytes| {
let store = recv_clone.clone();
async move {
let event = headers
.get("x-slabs-event")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_owned();
let sig = headers
.get("x-slabs-signature")
.and_then(|v| v.to_str().ok())
.map(ToOwned::to_owned);
store.lock().unwrap().push((event, sig, body));
StatusCode::OK
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, hook_app).await.unwrap() });
let secret = "whsec_claim_link_ignore_secret";
let storage_dir = std::env::temp_dir().join(format!(
"slabs_http_inc_lifecycle_{}",
slabs_core::id::new("d")
));
let mut cfg = AppConfig::for_test("demo", storage_dir.clone());
cfg.webhooks_allow_local = true;
cfg.incident_webhook_url = Some(format!("http://{addr}/hook"));
cfg.incident_webhook_secret = Some(secret.into());
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let mut input = IncidentInput {
kind: "http_5xx".into(),
source_file: "slabs/orders/pay.rs".into(),
route_pattern: Some("/api/orders/pay".into()),
status_code: Some(500),
error_message: "card declined upstream".into(),
detail: Some("provider 502".into()),
context_json: json!({ "request_id": "req_a", "latency_ms": 420 }),
git_sha: Some("sha_1111".into()),
custom_fingerprint: None,
};
let rec = record_and_notify_incident(&ctx, input.clone())
.await
.unwrap();
input.git_sha = Some("sha_2222".into());
input.context_json = json!({ "request_id": "req_b", "latency_ms": 610 });
let _ = record_and_notify_incident(&ctx, input.clone())
.await
.unwrap();
let (status, _, body) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/claim", rec.id))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"assignee":"agent-claude"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {body}");
let claimed_json: Value = serde_json::from_str(&body).unwrap();
assert_eq!(claimed_json["status"], "in_progress");
assert_eq!(claimed_json["assignee"], "agent-claude");
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/claim", rec.id))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(r#"{"assignee":"agent-codex"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::CONFLICT);
let (status, _, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/link", rec.id))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
r#"{"external_issue_key":"ENG-99","external_issue_url":"javascript:alert(1)"}"#,
))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
let (status, _, body) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/link", rec.id))
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(
r#"{"external_issue_key":"ENG-99","external_issue_url":"https://linear.app/team/issue/ENG-99"}"#,
))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK, "body: {body}");
let (status, _, ui_html) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui?status=in_progress")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(ui_html.contains("status=in_progress"));
assert!(ui_html.contains("status=ignored"));
assert!(ui_html.contains("Assignee: agent-claude"));
assert!(ui_html.contains("https://linear.app/team/issue/ENG-99"));
assert!(ui_html.contains("ENG-99"));
assert!(ui_html.contains("sha_1111"));
assert!(ui_html.contains("sha_2222"));
assert!(ui_html.contains(&format!("/_slabs/incidents/{}/ignore", rec.id)));
assert!(ui_html.contains(&format!("/_slabs/incidents/{}/resolve", rec.id)));
assert!(!ui_html.contains("<script>"));
assert!(!ui_html.contains("<style"));
let (status, headers, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/ignore", rec.id))
.header(header::ACCEPT, "text/html")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::SEE_OTHER);
assert_eq!(
headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),
Some("/_slabs/incidents/ui")
);
let _ = record_and_notify_incident(&ctx, input).await.unwrap();
let (status, _, ignored_html) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui?status=ignored")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(ignored_html.contains(&rec.id));
let open_input = IncidentInput {
kind: "panic".into(),
source_file: "slabs/orders/refund.rs".into(),
route_pattern: Some("/api/orders/refund".into()),
status_code: Some(500),
error_message: "index out of bounds".into(),
detail: None,
context_json: json!({}),
git_sha: Some("sha_3333".into()),
custom_fingerprint: None,
};
let open_rec = record_and_notify_incident(&ctx, open_input).await.unwrap();
let (status, _, open_ui) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents/ui?status=open")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert!(open_ui.contains(&format!("/_slabs/incidents/{}/claim", open_rec.id)));
let (status, headers, _) = send(
&router,
http::Request::builder()
.method(Method::POST)
.uri(format!("/_slabs/incidents/{}/claim", open_rec.id))
.header(header::ACCEPT, "text/html")
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(Body::from("assignee=alice+bot"))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::SEE_OTHER);
assert_eq!(
headers.get(header::LOCATION).and_then(|v| v.to_str().ok()),
Some("/_slabs/incidents/ui")
);
let form_claimed = ctx.incidents.get(&open_rec.id).await.unwrap().unwrap();
assert_eq!(form_claimed.assignee.as_deref(), Some("alice bot"));
for _ in 0..40 {
if received.lock().unwrap().len() >= 4 {
break;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
let events = received.lock().unwrap().clone();
let assigned_events: Vec<&ReceivedWebhook> = events
.iter()
.filter(|(ev, _, _)| ev == "incident.assigned")
.collect();
assert_eq!(
assigned_events.len(),
2,
"expected 2 incident.assigned webhooks, got {events:?}"
);
for (_, sig_hdr, raw_body) in assigned_events {
let expected_sig = sign_incident_webhook(secret, raw_body);
assert_eq!(sig_hdr.as_deref(), Some(expected_sig.as_str()));
let payload: Value = serde_json::from_slice(raw_body).unwrap();
assert_eq!(payload["event"], "incident.assigned");
assert_eq!(payload["incident"]["status"], "in_progress");
}
let _ = std::fs::remove_dir_all(&storage_dir);
}
}