use axum::{
body::Bytes,
extract::{ConnectInfo, FromRequestParts, MatchedPath, 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 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 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")
);
#[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;
record_poison_pill_job_incident(ctx, job, &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;
record_poison_pill_job_incident(ctx, &record, &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(),
ctx.config.incident_stale_days,
)
}
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();
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/{id}", get(get_incident_handler))
.route(
"/_slabs/incidents/{id}/attachments/{blob_id}",
get(incident_attachment_handler),
)
.route(
"/_slabs/incidents/{id}/resolve",
post(resolve_incident_handler),
)
.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("/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 record_poison_pill_job_incident(ctx: &AppCtx, job: &JobRecord, msg: &str) {
let input = IncidentInput {
kind: "job_dead".into(),
source_file: format!("jobs/{}.rs", job.job_name),
route_pattern: Some(job.job_name.clone()),
status_code: None,
error_message: msg.to_owned(),
detail: Some(format!(
"job {} ({}) dead-lettered due to invalid JSON payload: {msg}",
job.id, job.job_name
)),
context_json: json!({
"job_id": job.id,
"job_type": job.job_name,
"attempts": job.attempts,
"max_attempts": job.max_attempts,
"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;
}
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 {
tracing::error!(
slab_file = %source_file,
method = %method,
route = %route_pattern,
status = status.as_u16(),
latency_ms = elapsed_ms,
request_id = %request_id,
git_sha = ctx.config.git_sha.as_deref().unwrap_or(""),
"HTTP 5xx response"
);
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 {
tracing::warn!(
slab_file = %source_file,
method = %method,
route = %route_pattern,
status = status.as_u16(),
latency_ms = elapsed_ms,
request_id = %request_id,
git_sha = ctx.config.git_sha.as_deref().unwrap_or(""),
"slow HTTP request"
);
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!(
slab_file = %source_file,
method = %method,
route = %route_pattern,
status = StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
latency_ms = elapsed_ms,
request_id = %request_id,
git_sha = ctx.config.git_sha.as_deref().unwrap_or(""),
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 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 is_metrics_authorized(ctx: &AppCtx, headers: &HeaderMap) -> Result<(), StatusCode> {
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()) => Ok(()),
_ => Err(StatusCode::UNAUTHORIZED),
}
} else if ctx.config.env.is_prod_like() {
Err(StatusCode::NOT_FOUND)
} else {
Ok(())
}
}
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 Err(status) = is_metrics_authorized(&ctx, &headers) {
return status.into_response();
}
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, Clone, Deserialize)]
struct IncidentAttachmentRef {
blob_id: String,
}
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 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 repro_test_for(inc: &IncidentRecord) -> String {
let fn_suffix: String = inc
.id
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
let fn_name = if fn_suffix.is_empty() {
"repro_incident".to_owned()
} else {
format!("repro_{fn_suffix}")
};
if matches!(inc.kind.as_str(), "job_dead" | "slow_job") || inc.source_file.starts_with("jobs/")
{
let job_name = inc.route_pattern.as_deref().unwrap_or("job_name");
return format!(
"// Paste into `#[cfg(test)] mod tests` in `{}`\n\
#[tokio::test]\n\
async fn {fn_name}() {{\n\
let app = crate::test_app().await;\n\
app.run_job_now({job_name:?}, serde_json::json!({{}})).await;\n\
}}",
inc.source_file
);
}
let route = inc.route_pattern.as_deref().unwrap_or("/");
let method = serde_json::from_str::<Value>(&inc.context_json)
.ok()
.and_then(|v| {
v.get("method")
.and_then(Value::as_str)
.map(str::to_ascii_uppercase)
})
.unwrap_or_else(|| "GET".to_owned());
let request_lines = match method.as_str() {
"GET" => format!(" let resp = app.get({route:?}).await;"),
"POST" => {
format!(" let resp = app.post_json({route:?}, &serde_json::json!({{}})).await;")
}
other => format!(
" let req = axum::http::Request::builder()\n\
.method({other:?})\n\
.uri({route:?})\n\
.body(axum::body::Body::empty())\n\
.unwrap();\n\
let resp = app.request(req).await;"
),
};
format!(
"// Paste into `#[cfg(test)] mod tests` in `{}`\n\
#[tokio::test]\n\
async fn {fn_name}() {{\n\
let app = crate::test_app().await;\n\
{request_lines}\n\
assert!(resp.status.is_success(), \"unexpected status: {{}}\", resp.status);\n\
}}",
inc.source_file
)
}
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
}
fn enrich_incident_detail_json(inc: &IncidentRecord) -> Value {
let mut value = enrich_incident_json(inc);
if let Some(obj) = value.as_object_mut() {
obj.insert("repro_test".into(), Value::String(repro_test_for(inc)));
}
value
}
fn parse_resolve_sha(body: &Bytes) -> SlabResult<Option<String>> {
if body.iter().all(u8::is_ascii_whitespace) {
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,
Query(query): Query<ListIncidentsQuery>,
) -> Response {
if let Err(status) = is_metrics_authorized(&ctx, &headers) {
return status.into_response();
}
let status = query.status.as_deref().unwrap_or("active");
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,
Path(id): Path<String>,
) -> Response {
if let Err(status) = is_metrics_authorized(&ctx, &headers) {
return status.into_response();
}
match ctx.incidents.get(&id).await {
Ok(Some(inc)) => (StatusCode::OK, Json(enrich_incident_detail_json(&inc))).into_response(),
Ok(None) => SlabError::not_found("incident not found").into_response(),
Err(err) => err.into_response(),
}
}
async fn resolve_incident_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
Path(id): Path<String>,
body: Bytes,
) -> Response {
if let Err(status) = is_metrics_authorized(&ctx, &headers) {
return status.into_response();
}
let resolved_in_sha = match parse_resolve_sha(&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);
}
(
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 incident_attachment_handler(
State(ctx): State<AppCtx>,
headers: HeaderMap,
Path((id, blob_id)): Path<(String, String)>,
) -> Response {
if let Err(status) = is_metrics_authorized(&ctx, &headers) {
return status.into_response();
}
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(),
}
}
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,
)
}
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);
}
#[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_and_records_incident() {
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_poison_pill_secret";
let mut cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_poison"));
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 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);
let incidents = ctx.incidents.list(Some("active"), 10).await.unwrap();
assert_eq!(incidents.len(), 1);
assert_eq!(incidents[0].kind, "job_dead");
assert_eq!(incidents[0].source_file, "jobs/demo.job.rs");
assert_eq!(incidents[0].route_pattern.as_deref(), Some("demo.job"));
for _ in 0..40 {
if !received.lock().unwrap().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
let events = received.lock().unwrap().clone();
assert_eq!(events.len(), 1);
assert_eq!(events[0].0, "incident.opened");
let expected_sig = sign_incident_webhook(secret, &events[0].2);
assert_eq!(events[0].1.as_deref(), Some(expected_sig.as_str()));
}
#[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 repro_test = single["repro_test"].as_str().expect("repro_test string");
assert!(repro_test.contains("#[tokio::test]"));
assert!(repro_test.contains("crate::test_app().await"));
assert!(repro_test.contains("/api/rooms/{room_id}/boom"));
assert!(repro_test.contains("slabs/rooms/boom.rs"));
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"));
}
type ReceivedWebhook = (String, Option<String>, Bytes);
#[tokio::test]
async fn incidents_api_enforces_observability_auth_gate_without_cookie_bypass() {
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.clone(), vec![], &[]);
let (_, admin_c) = ctx_no_tok
.auth
.create_session("usr_admin", "admin", 7)
.await
.unwrap();
let admin_cookie = format!("{}={}", admin_c.name(), admin_c.value());
for path in [
"/_slabs/incidents",
"/_slabs/incidents/inc_1",
"/_slabs/incidents/inc_1/attachments/blob_1",
] {
let (status, _, _) = send(
&router_no_tok,
http::Request::builder()
.uri(path)
.header(header::COOKIE, &admin_cookie)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"{path} must be 404 in prod without token"
);
}
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 removed_v04_endpoints_and_vendor_scripts_return_not_found() {
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_removed"));
let ctx = test_ctx(cfg).await;
let router = build_router(ctx, vec![], &[]);
for (method, path) in [
(Method::GET, "/_slabs/incidents/ui"),
(Method::POST, "/_slabs/incidents/inc_1/claim"),
(Method::POST, "/_slabs/incidents/inc_1/link"),
(Method::POST, "/_slabs/incidents/inc_1/ignore"),
(Method::POST, "/_slabs/bug-reports"),
(Method::POST, "/_slabs/client-errors"),
(Method::GET, "/_slabs/vendor/slabs-telemetry.js"),
(Method::GET, "/_slabs/vendor/slabs-bug-report.js"),
] {
let (status, _, _) = send(
&router,
http::Request::builder()
.method(method.clone())
.uri(path)
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"{method} {path} should be removed in v0.4.0"
);
}
}
#[tokio::test]
async fn incident_inbox_supports_open_resolved_reopened_lifecycle_and_repro_test() {
let cfg = AppConfig::for_test("demo", PathBuf::from("/tmp/slabs_http_lifecycle"));
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let input = IncidentInput {
kind: "http_5xx".into(),
source_file: "slabs/orders/pay.rs".into(),
route_pattern: Some("/api/orders/{order_id}/pay".into()),
status_code: Some(500),
error_message: "card declined upstream".into(),
detail: Some("provider 502".into()),
context_json: json!({ "method": "POST", "request_id": "req_a" }),
git_sha: Some("sha_1111".into()),
custom_fingerprint: None,
};
let rec = record_and_notify_incident(&ctx, input.clone())
.await
.unwrap();
assert_eq!(rec.status, "open");
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let active: Value = serde_json::from_str(&body).unwrap();
assert_eq!(active["incidents"].as_array().unwrap().len(), 1);
assert_eq!(active["incidents"][0]["status"], "open");
let (status, _, body) = send(
&router,
http::Request::builder()
.uri(format!("/_slabs/incidents/{}", rec.id))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let detail: Value = serde_json::from_str(&body).unwrap();
let repro_test = detail["repro_test"].as_str().unwrap();
assert!(repro_test.contains("#[tokio::test]"));
assert!(repro_test.contains("crate::test_app().await"));
assert!(repro_test.contains("post_json"));
assert!(repro_test.contains("/api/orders/{order_id}/pay"));
assert!(repro_test.contains("slabs/orders/pay.rs"));
let (status, _, body) = 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_fix_1"}"#))
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let resolved: Value = serde_json::from_str(&body).unwrap();
assert_eq!(resolved["status"], "resolved");
assert_eq!(resolved["resolved_in_sha"], "sha_fix_1");
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap()["incidents"],
json!([])
);
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents?status=resolved")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap()["incidents"]
.as_array()
.unwrap()
.len(),
1
);
let reopened_rec = record_and_notify_incident(&ctx, input).await.unwrap();
assert_eq!(reopened_rec.status, "reopened");
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
let active_after: Value = serde_json::from_str(&body).unwrap();
assert_eq!(active_after["incidents"].as_array().unwrap().len(), 1);
assert_eq!(active_after["incidents"][0]["status"], "reopened");
let (status, _, body) = send(
&router,
http::Request::builder()
.uri("/_slabs/incidents?status=reopened")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap()["incidents"]
.as_array()
.unwrap()
.len(),
1
);
}
#[tokio::test]
async fn incident_attachment_download_serves_scoped_blobs_and_blocks_idor() {
let storage_dir = std::env::temp_dir().join(format!(
"slabs_http_inc_attach_{}",
slabs_core::id::new("d")
));
let cfg = AppConfig::for_test("demo", storage_dir.clone());
let ctx = test_ctx(cfg).await;
let router = build_router(ctx.clone(), vec![], &[]);
let png_meta = ctx
.storage
.put_scoped(
"bug_report",
"screenshot.png",
Some("image/png"),
b"\x89PNG\r\n\x1a\nfake-png-payload",
)
.await
.unwrap();
let html_meta = ctx
.storage
.put_scoped(
"bug_report",
"repro.html",
Some("text/html"),
b"<html><script>alert(1)</script></html>",
)
.await
.unwrap();
let unrelated = ctx
.storage
.put(
"secret.txt",
Some("text/plain"),
Bytes::from_static(b"top-secret"),
)
.await
.unwrap();
let (inc, _) = ctx
.incidents
.record(IncidentInput {
kind: "user_bug_report".into(),
source_file: "slabs/rooms/show.rs".into(),
route_pattern: Some("/rooms/123".into()),
status_code: None,
error_message: "Button freezes".into(),
detail: None,
context_json: json!({
"attachments": [
{ "blob_id": png_meta.id, "filename": "screenshot.png" },
{ "blob_id": html_meta.id, "filename": "repro.html" },
]
}),
git_sha: None,
custom_fingerprint: Some(slabs_core::id::new("bug")),
})
.await
.unwrap();
let (status, headers, raw_png) = send(
&router,
http::Request::builder()
.uri(format!(
"/_slabs/incidents/{}/attachments/{}",
inc.id, png_meta.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/{}/attachments/{}",
inc.id, html_meta.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 (status, _, _) = send(
&router,
http::Request::builder()
.uri(format!(
"/_slabs/incidents/{}/attachments/{}",
inc.id, unrelated.id
))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::NOT_FOUND);
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 reopened = record_and_notify_incident(&ctx, input).await.unwrap();
assert_eq!(reopened.status, "reopened");
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);
}
}