Skip to main content

slabs_core/
lib.rs

1//! Core types for the Slabs web framework.
2//!
3//! This crate owns prefixed ULID generation, the unified HTTP error type,
4//! environment configuration, and JSON route/job manifests.
5//!
6//! # Owned types
7//!
8//! - [`id::new`]: generates lowercase, time-sortable prefixed ULIDs such as `msg_01j...`.
9//! - [`SlabError`] and [`SlabResult`]: explicit error enum returned by every transaction script and background job.
10//! - [`Validate`]: multi-field procedural validation builder returning [`SlabError::ValidationErrors`].
11//! - [`AppEnv`] and [`AppConfig`]: deployment environment and runtime configuration loaded from `DATABASE_URL` and `SLABS_*` environment variables, plus [`AppConfig::for_test`] for isolated tests and [`AppConfig::validate`] for fail-closed staging/production startup checks.
12//! - [`AppManifest`], [`RouteMeta`], and [`JobMeta`]: JSON metadata returned by `/_slabs/manifest` and `slabs manifest`, plus `OpenAPI` 3.1.0 export via [`AppManifest::to_openapi_3_1`].
13//!
14//! # HTTP status mapping
15//!
16//! [`SlabError`] implements [`axum::response::IntoResponse`] and returns a JSON body with `error` and `message` fields:
17//!
18//! | Variant | HTTP status | JSON `error` field | Notes |
19//! | --- | --- | --- | --- |
20//! | [`SlabError::BadRequest`] | `400` | `"bad_request"` | Includes the error message. |
21//! | [`SlabError::Unauthorized`] | `401` | `"unauthorized"` | Missing or invalid credentials. |
22//! | [`SlabError::Forbidden`] | `403` | `"forbidden"` | Authenticated caller lacks permission. |
23//! | [`SlabError::NotFound`] | `404` | `"not_found"` | Resource does not exist. |
24//! | [`SlabError::Database`] (`RowNotFound`) | `404` | `"not_found"` | Message is fixed to `"record not found"`. |
25//! | [`SlabError::Conflict`] | `409` | `"conflict"` | Unique key or state conflict. |
26//! | [`SlabError::Validation`] | `422` | `"validation_error"` | Also includes a `field` string. |
27//! | [`SlabError::ValidationErrors`] | `422` | `"validation_error"` | Includes a `fields` map of field names to error message lists. |
28//! | [`SlabError::TooManyRequests`] | `429` | `"too_many_requests"` | Sets `Retry-After` header and `retry_after_secs`. |
29//! | [`SlabError::Database`] (other) | `500` | `"database_error"` | Logs via `tracing::error!` and hides raw SQL details. |
30//! | [`SlabError::Internal`] | `500` | `"internal_error"` | Logs via `tracing::error!` and returns `"internal server error"`. |
31//!
32//! # Environment variables
33//!
34//! [`AppConfig::from_env`] reads these variables and falls back to local development defaults derived from `app_name`:
35//!
36//! - `SLABS_ENV`: deployment environment (`development`, `test`, `staging`, `production`). Defaults to `development`.
37//! - `SLABS_BIND`: bind address. Defaults to `"127.0.0.1:3000"`.
38//! - `DATABASE_URL`: database connection string. Defaults to `"sqlite://{app_name}.db?mode=rwc"`.
39//! - `SLABS_SECRET_KEY`: signing key for cookies, tokens, and HMAC digests. Generates an ephemeral 32-byte key in dev/test; required (>= 32 bytes) in staging/production.
40//! - `SLABS_STORAGE_DIR`: local blob directory. Defaults to `"./storage/{app_name}"`.
41//! - `SLABS_ASSETS_DIR`: static assets directory. Defaults to `"./assets"` when present, otherwise `"./examples/{app_name}/assets"`.
42//! - `SLABS_JOB_POLL_MS`: background worker poll interval in milliseconds. Defaults to `500`.
43//! - `SLABS_JOB_CONCURRENCY`: maximum concurrent background jobs. Defaults to `4`.
44//! - `SLABS_COOKIE_SECURE`: enables the `Secure` cookie attribute when `"1"` or `"true"`. Defaults to `true` in staging/production and `false` in dev/test.
45//! - `SLABS_WEBHOOKS_LIVE`: enables live outbound webhook HTTP requests when `"1"` or `"true"`. Defaults to `false`.
46//! - `SLABS_WEBHOOKS_ALLOW_LOCAL`: permits webhooks to target loopback addresses when `"1"` or `"true"`. Defaults to `false`.
47//! - `SLABS_CORS_ORIGINS`: comma-separated list of allowed CORS origins. Defaults to empty.
48//! - `SLABS_TRUST_PROXY`: trusts reverse-proxy forwarding headers when `"1"` or `"true"`. Defaults to `false`.
49//! - `SLABS_METRICS_TOKEN`: optional bearer token guarding `/_slabs/metrics`.
50//! - `SLABS_MAX_BODY_BYTES`: maximum HTTP request body size in bytes. Defaults to `4 MiB`.
51//! - `SLABS_MAX_BLOB_BYTES`: maximum blob upload size in bytes. Defaults to `10 MiB`.
52//! - `SLABS_CSRF_ENFORCE`: enforces CSRF origin checks on cookie-authenticated mutations. Defaults to `true`.
53//! - `SLABS_SLOW_REQUEST_MS`: HTTP latency threshold in milliseconds for recording `slow_request` incidents. Defaults to `500`.
54//! - `SLABS_SLOW_JOB_MS`: background job latency threshold in milliseconds for recording `slow_job` incidents. Defaults to `5000`.
55//! - `SLABS_GIT_SHA`: optional deployment commit SHA attached to recorded runtime incidents.
56//! - `SLABS_INCIDENT_WEBHOOK_URL`: optional outbound webhook URL notified when a new or re-opened runtime incident is recorded or resolved.
57//! - `SLABS_INCIDENT_WEBHOOK_SECRET`: optional HMAC-SHA256 signing secret for Incident Protocol v1 webhooks (`X-Slabs-Signature: sha256=<hex>`).
58//! - `SLABS_BUG_REPORTER`: enables the built-in user bug reporter endpoint (`POST /_slabs/bug-reports`) and widget helper when `"1"` or `"true"`. Defaults to `true` in `Development` and `Staging`, and `false` in `Production` and `Test`.
59//! - `SLABS_BUG_REPORTER_ANONYMOUS`: allows unauthenticated callers to submit bug reports when `"1"` or `"true"`. Defaults to `false`.
60//!
61//! # Invariants
62//!
63//! - [`id::new`] produces lowercase ULIDs prefixed with `<prefix>_` so `SQLite` B-tree primary keys stay append-friendly.
64//! - Returning `?` on a [`sqlx::Error::RowNotFound`] produces HTTP 404 without manual mapping.
65//! - Unexpected database and internal errors never leak internal messages or SQL strings in the HTTP response body.
66//! - [`AppConfig::for_test`] pins `database_url` to `"sqlite::memory:"`, `bind_addr` to `"127.0.0.1:0"`, and disables live webhooks.
67//!
68//! # Usage
69//!
70//! ```rust
71//! use slabs_core::{id, AppConfig, SlabError, SlabResult};
72//!
73//! fn validate_title(title: &str) -> SlabResult<String> {
74//!     if title.trim().is_empty() {
75//!         return Err(SlabError::validation("title", "cannot be blank"));
76//!     }
77//!     Ok(id::new("room"))
78//! }
79//!
80//! let config = AppConfig::from_env("campfire");
81//! assert_eq!(config.app_name, "campfire");
82//! assert!(validate_title("Lobby").unwrap().starts_with("room_"));
83//! assert_eq!(validate_title("  ").unwrap_err().status_code().as_u16(), 422);
84//! ```
85
86use axum::{
87    http::StatusCode,
88    response::{IntoResponse, Response},
89    Json,
90};
91use serde::{Deserialize, Serialize};
92use serde_json::json;
93use std::collections::BTreeMap;
94use std::fmt;
95use std::path::PathBuf;
96use thiserror::Error;
97
98/// Prefix-tagged, time-sortable ULID generator (for example `msg_01j...` or `usr_01j...`).
99///
100/// Time-sorted IDs keep `SQLite` B-tree indexes compact and append-friendly.
101pub mod id {
102    use ulid::Ulid;
103
104    /// Generates a lowercase prefixed ULID string in the form `<prefix>_<ulid>`.
105    ///
106    /// The ULID suffix is 26 Crockford Base32 characters encoded in lowercase.
107    #[must_use]
108    pub fn new(prefix: &str) -> String {
109        format!("{prefix}_{}", Ulid::new().to_string().to_lowercase())
110    }
111}
112
113/// Unified HTTP error type returned by every transaction script and background job.
114///
115/// Implements [`IntoResponse`] with JSON error bodies and explicit HTTP status codes.
116#[derive(Debug, Error)]
117#[non_exhaustive]
118pub enum SlabError {
119    /// Input validation failure targeting a specific field (HTTP 422, `error: "validation_error"`).
120    #[error("validation failed on `{field}`: {message}")]
121    Validation {
122        /// Name of the field that failed validation.
123        field: String,
124        /// Human-readable description of the validation failure.
125        message: String,
126    },
127
128    /// Multi-field input validation failure (HTTP 422, `error: "validation_error"`).
129    #[error("validation failed on {} field(s)", .0.len())]
130    ValidationErrors(BTreeMap<String, Vec<String>>),
131
132    /// Malformed or invalid client request (HTTP 400, `error: "bad_request"`).
133    #[error("bad request: {0}")]
134    BadRequest(String),
135
136    /// Missing or invalid authentication credentials (HTTP 401, `error: "unauthorized"`).
137    #[error("unauthorized: {0}")]
138    Unauthorized(String),
139
140    /// Authenticated caller lacks permission for the requested action (HTTP 403, `error: "forbidden"`).
141    #[error("forbidden: {0}")]
142    Forbidden(String),
143
144    /// Requested resource does not exist (HTTP 404, `error: "not_found"`).
145    #[error("not found: {0}")]
146    NotFound(String),
147
148    /// Resource state conflict, such as a duplicate unique key (HTTP 409, `error: "conflict"`).
149    #[error("conflict: {0}")]
150    Conflict(String),
151
152    /// Rate limit exceeded (HTTP 429, `error: "too_many_requests"`).
153    ///
154    /// Sets the `Retry-After` response header to `retry_after_secs`.
155    #[error("too many requests: {message} (retry after {retry_after_secs}s)")]
156    TooManyRequests {
157        /// Seconds the client should wait before retrying.
158        retry_after_secs: u64,
159        /// Human-readable rate-limit explanation.
160        message: String,
161    },
162
163    /// Underlying `sqlx` database error.
164    ///
165    /// Maps [`sqlx::Error::RowNotFound`] to HTTP 404 (`"record not found"`).
166    /// Maps all other database errors to HTTP 500 and logs the raw error with `tracing::error!`.
167    #[error("database error: {0}")]
168    Database(#[from] sqlx::Error),
169
170    /// Unexpected server-side failure (HTTP 500, `error: "internal_error"`).
171    ///
172    /// Logs the message with `tracing::error!` and returns `"internal server error"` to clients.
173    #[error("internal error: {0}")]
174    Internal(String),
175}
176
177impl SlabError {
178    /// Creates a [`SlabError::Validation`] error (HTTP 422) for `field` with `message`.
179    #[must_use]
180    pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
181        Self::Validation {
182            field: field.into(),
183            message: message.into(),
184        }
185    }
186
187    /// Creates a [`SlabError::BadRequest`] error (HTTP 400).
188    #[must_use]
189    pub fn bad_request(msg: impl Into<String>) -> Self {
190        Self::BadRequest(msg.into())
191    }
192
193    /// Creates a [`SlabError::Unauthorized`] error (HTTP 401).
194    #[must_use]
195    pub fn unauthorized(msg: impl Into<String>) -> Self {
196        Self::Unauthorized(msg.into())
197    }
198
199    /// Creates a [`SlabError::Forbidden`] error (HTTP 403).
200    #[must_use]
201    pub fn forbidden(msg: impl Into<String>) -> Self {
202        Self::Forbidden(msg.into())
203    }
204
205    /// Creates a [`SlabError::NotFound`] error (HTTP 404).
206    #[must_use]
207    pub fn not_found(msg: impl Into<String>) -> Self {
208        Self::NotFound(msg.into())
209    }
210
211    /// Creates a [`SlabError::Conflict`] error (HTTP 409).
212    #[must_use]
213    pub fn conflict(msg: impl Into<String>) -> Self {
214        Self::Conflict(msg.into())
215    }
216
217    /// Creates a [`SlabError::TooManyRequests`] error (HTTP 429) with a `Retry-After` value in seconds.
218    #[must_use]
219    pub fn too_many_requests(retry_after_secs: u64, msg: impl Into<String>) -> Self {
220        Self::TooManyRequests {
221            retry_after_secs,
222            message: msg.into(),
223        }
224    }
225
226    /// Creates a [`SlabError::Internal`] error (HTTP 500).
227    #[must_use]
228    pub fn internal(msg: impl Into<String>) -> Self {
229        Self::Internal(msg.into())
230    }
231
232    /// Returns the HTTP [`StatusCode`] mapped to this error variant.
233    #[must_use]
234    pub fn status_code(&self) -> StatusCode {
235        match self {
236            Self::Validation { .. } | Self::ValidationErrors(_) => StatusCode::UNPROCESSABLE_ENTITY,
237            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
238            Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
239            Self::Forbidden(_) => StatusCode::FORBIDDEN,
240            Self::NotFound(_) | Self::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND,
241            Self::Conflict(_) => StatusCode::CONFLICT,
242            Self::TooManyRequests { .. } => StatusCode::TOO_MANY_REQUESTS,
243            Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
244        }
245    }
246}
247
248impl IntoResponse for SlabError {
249    fn into_response(self) -> Response {
250        let status = self.status_code();
251        if let Self::TooManyRequests {
252            retry_after_secs,
253            message,
254        } = self
255        {
256            let mut resp = (
257                status,
258                Json(json!({
259                    "error": "too_many_requests",
260                    "retry_after_secs": retry_after_secs,
261                    "message": message,
262                })),
263            )
264                .into_response();
265            if let Ok(val) = http::HeaderValue::from_str(&retry_after_secs.to_string()) {
266                resp.headers_mut().insert(http::header::RETRY_AFTER, val);
267            }
268            return resp;
269        }
270        let body = match &self {
271            Self::Validation { field, message } => json!({
272                "error": "validation_error",
273                "field": field,
274                "message": message,
275            }),
276            Self::ValidationErrors(fields) => json!({
277                "error": "validation_error",
278                "fields": fields,
279            }),
280            Self::Database(sqlx::Error::RowNotFound) => json!({
281                "error": "not_found",
282                "message": "record not found",
283            }),
284            Self::Database(err) => {
285                tracing::error!(error = %err, "database error in slab");
286                json!({
287                    "error": "database_error",
288                    "message": "internal database error",
289                })
290            }
291            Self::Internal(msg) => {
292                tracing::error!(error = %msg, "internal error in slab");
293                json!({
294                    "error": "internal_error",
295                    "message": "internal server error",
296                })
297            }
298            other => json!({
299                "error": status.canonical_reason().unwrap_or("error").to_lowercase().replace(' ', "_"),
300                "message": other.to_string(),
301            }),
302        };
303
304        (status, Json(body)).into_response()
305    }
306}
307
308/// Result alias using [`SlabError`] as the error type.
309pub type SlabResult<T> = Result<T, SlabError>;
310
311/// Multi-field procedural validation builder for transaction scripts.
312///
313/// Accumulates field errors in deterministic key order and returns
314/// [`SlabError::ValidationErrors`] (HTTP 422) from [`Validate::finish`].
315#[derive(Debug, Clone, Default)]
316pub struct Validate {
317    errors: BTreeMap<String, Vec<String>>,
318}
319
320impl Validate {
321    /// Creates an empty [`Validate`] builder with no recorded errors.
322    #[must_use]
323    pub fn new() -> Self {
324        Self::default()
325    }
326
327    /// Requires `value` to be non-empty after trimming whitespace.
328    ///
329    /// Records `"is required"` under `field` when empty.
330    pub fn required(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
331        if value.trim().is_empty() {
332            self.push(field, "is required");
333        }
334        self
335    }
336
337    /// Requires the trimmed `value` to have at least `min` Unicode scalar characters.
338    pub fn min_len(&mut self, field: impl Into<String>, value: &str, min: usize) -> &mut Self {
339        if value.trim().chars().count() < min {
340            self.push(field, format!("must be at least {min} characters"));
341        }
342        self
343    }
344
345    /// Requires the trimmed `value` to have at most `max` Unicode scalar characters.
346    pub fn max_len(&mut self, field: impl Into<String>, value: &str, max: usize) -> &mut Self {
347        if value.trim().chars().count() > max {
348            self.push(field, format!("must be at most {max} characters"));
349        }
350        self
351    }
352
353    /// Requires the trimmed `value` to look like an email address.
354    ///
355    /// Rejects ASCII control characters, whitespace, values longer than 254 bytes, and
356    /// requires a non-empty local part before `@` and a domain containing `.` after `@`.
357    pub fn email(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
358        let trimmed = value.trim();
359        let valid = !trimmed.is_empty()
360            && trimmed.len() <= 254
361            && !has_ascii_control(value)
362            && !trimmed.chars().any(char::is_whitespace)
363            && trimmed.split_once('@').is_some_and(|(local, domain)| {
364                !local.is_empty()
365                    && !domain.is_empty()
366                    && !domain.contains('@')
367                    && domain.contains('.')
368                    && !domain.starts_with('.')
369                    && !domain.ends_with('.')
370            });
371        if !valid {
372            self.push(field, "must be a valid email address");
373        }
374        self
375    }
376
377    /// Requires the trimmed `value` to parse as an `http://` or `https://` URL with a host.
378    ///
379    /// Rejects ASCII control characters, whitespace, and values longer than 2048 bytes.
380    pub fn url(&mut self, field: impl Into<String>, value: &str) -> &mut Self {
381        let trimmed = value.trim();
382        let valid = !trimmed.is_empty()
383            && trimmed.len() <= 2048
384            && !has_ascii_control(value)
385            && !trimmed.chars().any(char::is_whitespace)
386            && url::Url::parse(trimmed).is_ok_and(|parsed| {
387                matches!(parsed.scheme(), "http" | "https") && parsed.host().is_some()
388            });
389        if !valid {
390            self.push(field, "must start with http:// or https://");
391        }
392        self
393    }
394
395    /// Requires `value` to match one of the entries in `allowed`.
396    pub fn one_of(&mut self, field: impl Into<String>, value: &str, allowed: &[&str]) -> &mut Self {
397        if !allowed.contains(&value) {
398            self.push(field, format!("must be one of: {}", allowed.join(", ")));
399        }
400        self
401    }
402
403    /// Records `message` under `field` when `condition` is `false`.
404    pub fn check(
405        &mut self,
406        field: impl Into<String>,
407        condition: bool,
408        message: impl Into<String>,
409    ) -> &mut Self {
410        if !condition {
411            self.push(field, message);
412        }
413        self
414    }
415
416    /// Unconditionally appends `message` to the error list for `field`.
417    pub fn push(&mut self, field: impl Into<String>, message: impl Into<String>) -> &mut Self {
418        self.errors
419            .entry(field.into())
420            .or_default()
421            .push(message.into());
422        self
423    }
424
425    /// Returns `true` when no validation errors have been recorded.
426    #[must_use]
427    pub fn is_empty(&self) -> bool {
428        self.errors.is_empty()
429    }
430
431    /// Returns the map of field names to accumulated validation messages.
432    #[must_use]
433    pub fn errors(&self) -> &BTreeMap<String, Vec<String>> {
434        &self.errors
435    }
436
437    /// Finalizes validation, returning `Ok(())` when empty or [`SlabError::ValidationErrors`].
438    pub fn finish(self) -> SlabResult<()> {
439        if self.errors.is_empty() {
440            Ok(())
441        } else {
442            Err(SlabError::ValidationErrors(self.errors))
443        }
444    }
445}
446
447fn has_ascii_control(s: &str) -> bool {
448    s.bytes().any(|b| b < 0x20 || b == 0x7f)
449}
450
451fn parse_bool_env(key: &str) -> Option<bool> {
452    let raw = std::env::var(key).ok()?;
453    let trimmed = raw.trim();
454    if trimmed == "1" || trimmed.eq_ignore_ascii_case("true") {
455        Some(true)
456    } else if trimmed == "0" || trimmed.eq_ignore_ascii_case("false") {
457        Some(false)
458    } else {
459        None
460    }
461}
462
463fn redact_database_url(raw: &str) -> String {
464    if let Ok(mut parsed) = url::Url::parse(raw) {
465        if parsed.password().is_some() {
466            const SENTINEL: &str = "__SLABS_REDACTED_PW__";
467            if parsed.set_password(Some(SENTINEL)).is_ok() {
468                return parsed.as_str().replace(SENTINEL, "[REDACTED]");
469            }
470        }
471        return raw.to_owned();
472    }
473    if let Some(scheme_end) = raw.find("://") {
474        let rest = &raw[scheme_end + 3..];
475        let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
476        let authority = &rest[..authority_end];
477        if let Some(at_pos) = authority.rfind('@') {
478            let userinfo = &authority[..at_pos];
479            if let Some(colon_pos) = userinfo.find(':') {
480                let prefix_end = scheme_end + 3 + colon_pos + 1;
481                let suffix_start = scheme_end + 3 + at_pos;
482                return format!("{}[REDACTED]{}", &raw[..prefix_end], &raw[suffix_start..]);
483            }
484        }
485    }
486    raw.to_owned()
487}
488
489/// Deployment environment controlling security defaults and fail-closed startup checks.
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
491pub enum AppEnv {
492    /// Local development environment (`"dev"` / `"development"`).
493    Development,
494    /// Automated test environment (`"test"`).
495    Test,
496    /// Staging or review environment (`"staging"` / `"review"`).
497    Staging,
498    /// Production environment (`"prod"` / `"production"`).
499    Production,
500}
501
502impl AppEnv {
503    /// Parses a deployment environment string (case-insensitive, trimmed).
504    ///
505    /// Maps `"dev"` / `"development"` to [`AppEnv::Development`], `"test"` to [`AppEnv::Test`],
506    /// `"staging"` / `"review"` to [`AppEnv::Staging`], and `"prod"` / `"production"` to
507    /// [`AppEnv::Production`]. Unrecognized values default to [`AppEnv::Development`].
508    #[must_use]
509    pub fn parse_env(value: &str) -> Self {
510        match value.trim().to_ascii_lowercase().as_str() {
511            "test" => Self::Test,
512            "staging" | "review" => Self::Staging,
513            "prod" | "production" => Self::Production,
514            _ => Self::Development,
515        }
516    }
517
518    /// Reads the deployment environment from `SLABS_ENV`, defaulting to [`AppEnv::Development`].
519    #[must_use]
520    pub fn from_env() -> Self {
521        std::env::var("SLABS_ENV").map_or(Self::Development, |v| Self::parse_env(&v))
522    }
523
524    /// Returns `true` for [`AppEnv::Staging`] and [`AppEnv::Production`].
525    #[must_use]
526    pub fn is_prod_like(self) -> bool {
527        matches!(self, Self::Staging | Self::Production)
528    }
529
530    /// Returns `true` for [`AppEnv::Development`] and [`AppEnv::Test`].
531    #[must_use]
532    pub fn is_dev_or_test(self) -> bool {
533        matches!(self, Self::Development | Self::Test)
534    }
535
536    /// Returns the canonical lowercase string name of this environment.
537    #[must_use]
538    pub fn as_str(self) -> &'static str {
539        match self {
540            Self::Development => "development",
541            Self::Test => "test",
542            Self::Staging => "staging",
543            Self::Production => "production",
544        }
545    }
546}
547
548/// Runtime configuration loaded from `SLABS_*` and `DATABASE_URL` environment variables.
549#[derive(Clone, Serialize, Deserialize)]
550#[allow(clippy::struct_excessive_bools)]
551pub struct AppConfig {
552    /// Deployment environment (`SLABS_ENV`, default [`AppEnv::Development`]).
553    pub env: AppEnv,
554    /// Application name used for default database filenames, storage directories, and manifests.
555    pub app_name: String,
556    /// Socket address to bind the HTTP server to (`SLABS_BIND`, default `"127.0.0.1:3000"`).
557    pub bind_addr: String,
558    /// Connection string for the primary database (`DATABASE_URL`, default `"sqlite://{app_name}.db?mode=rwc"`).
559    pub database_url: String,
560    /// Secret key for signing cookies, tokens, and HMAC digests (`SLABS_SECRET_KEY`).
561    #[serde(default, skip_serializing)]
562    pub secret_key: String,
563    /// Directory where uploaded blobs and local storage files are written (`SLABS_STORAGE_DIR`).
564    pub storage_dir: PathBuf,
565    /// Directory containing static assets such as CSS and JS files (`SLABS_ASSETS_DIR`).
566    pub assets_dir: PathBuf,
567    /// Polling interval in milliseconds for the background job worker (`SLABS_JOB_POLL_MS`, default `500`).
568    pub job_poll_interval_ms: u64,
569    /// Maximum number of background jobs executed concurrently (`SLABS_JOB_CONCURRENCY`, default `4`).
570    pub job_concurrency: usize,
571    /// Sets the `Secure` attribute on session cookies when `true` (`SLABS_COOKIE_SECURE`, default `env.is_prod_like()`).
572    pub cookie_secure: bool,
573    /// Enables live HTTP delivery for outbound webhooks when `true` (`SLABS_WEBHOOKS_LIVE`, default `false`).
574    pub webhooks_live: bool,
575    /// Allows outbound webhooks to target loopback addresses when `true` (`SLABS_WEBHOOKS_ALLOW_LOCAL`, default `false`).
576    pub webhooks_allow_local: bool,
577    /// Allowed CORS origins loaded from comma-separated `SLABS_CORS_ORIGINS`.
578    pub cors_origins: Vec<String>,
579    /// Whether to trust reverse-proxy forwarding headers (`SLABS_TRUST_PROXY`, default `false`).
580    pub trust_proxy: bool,
581    /// Optional bearer token protecting the metrics endpoint (`SLABS_METRICS_TOKEN`).
582    #[serde(default, skip_serializing)]
583    pub metrics_token: Option<String>,
584    /// Maximum HTTP request body size in bytes (`SLABS_MAX_BODY_BYTES`, default `4 MiB`).
585    pub max_body_bytes: usize,
586    /// Maximum blob upload size in bytes (`SLABS_MAX_BLOB_BYTES`, default `10 MiB`).
587    pub max_blob_bytes: usize,
588    /// Enforces CSRF checks on cookie-authenticated mutations (`SLABS_CSRF_ENFORCE`, default `true`).
589    pub csrf_enforce: bool,
590    /// HTTP request latency threshold in milliseconds for slow-request incident capture (`SLABS_SLOW_REQUEST_MS`, default `500`).
591    pub slow_request_ms: u64,
592    /// Background job execution latency threshold in milliseconds for slow-job incident capture (`SLABS_SLOW_JOB_MS`, default `5_000`).
593    pub slow_job_ms: u64,
594    /// Optional Git commit SHA of the running build attached to runtime incidents (`SLABS_GIT_SHA`).
595    pub git_sha: Option<String>,
596    /// Optional webhook URL notified when a runtime incident is opened, re-opened, or resolved (`SLABS_INCIDENT_WEBHOOK_URL`).
597    #[serde(default, skip_serializing)]
598    pub incident_webhook_url: Option<String>,
599    /// Optional HMAC-SHA256 signing secret for Incident Protocol v1 webhooks (`SLABS_INCIDENT_WEBHOOK_SECRET`).
600    #[serde(default, skip_serializing)]
601    pub incident_webhook_secret: Option<String>,
602    /// Enables the built-in user bug reporter endpoint and widget (`SLABS_BUG_REPORTER`, defaults to `true` in development/staging and `false` in production/test).
603    pub bug_reporter_enabled: bool,
604    /// Allows unauthenticated users to submit bug reports (`SLABS_BUG_REPORTER_ANONYMOUS`, default `false`).
605    pub bug_reporter_allow_anonymous: bool,
606}
607
608impl fmt::Debug for AppConfig {
609    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
610        let redacted_db_url = redact_database_url(&self.database_url);
611        let redacted_metrics_token = self.metrics_token.as_ref().map(|_| "[REDACTED]");
612        let redacted_incident_webhook_url =
613            self.incident_webhook_url.as_ref().map(|_| "[CONFIGURED]");
614        let redacted_incident_webhook_secret =
615            self.incident_webhook_secret.as_ref().map(|_| "[REDACTED]");
616        f.debug_struct("AppConfig")
617            .field("env", &self.env)
618            .field("app_name", &self.app_name)
619            .field("bind_addr", &self.bind_addr)
620            .field("database_url", &redacted_db_url)
621            .field("secret_key", &"[REDACTED]")
622            .field("storage_dir", &self.storage_dir)
623            .field("assets_dir", &self.assets_dir)
624            .field("job_poll_interval_ms", &self.job_poll_interval_ms)
625            .field("job_concurrency", &self.job_concurrency)
626            .field("cookie_secure", &self.cookie_secure)
627            .field("webhooks_live", &self.webhooks_live)
628            .field("webhooks_allow_local", &self.webhooks_allow_local)
629            .field("cors_origins", &self.cors_origins)
630            .field("trust_proxy", &self.trust_proxy)
631            .field("metrics_token", &redacted_metrics_token)
632            .field("max_body_bytes", &self.max_body_bytes)
633            .field("max_blob_bytes", &self.max_blob_bytes)
634            .field("csrf_enforce", &self.csrf_enforce)
635            .field("slow_request_ms", &self.slow_request_ms)
636            .field("slow_job_ms", &self.slow_job_ms)
637            .field("git_sha", &self.git_sha)
638            .field("incident_webhook_url", &redacted_incident_webhook_url)
639            .field("incident_webhook_secret", &redacted_incident_webhook_secret)
640            .field("bug_reporter_enabled", &self.bug_reporter_enabled)
641            .field(
642                "bug_reporter_allow_anonymous",
643                &self.bug_reporter_allow_anonymous,
644            )
645            .finish()
646    }
647}
648
649impl AppConfig {
650    /// Legacy development fallback secret rejected by [`AppConfig::validate`] in staging and production.
651    pub const DEV_SECRET_FALLBACK_SENTINEL: &str =
652        "dev-only-change-me-in-production-slabs-secret-key";
653
654    /// Loads configuration from `SLABS_*` and `DATABASE_URL` environment variables.
655    ///
656    /// Falls back to local development defaults derived from `app_name` when variables are unset.
657    /// When `SLABS_SECRET_KEY` is unset in development or test, generates a random ephemeral
658    /// 32-byte hex key and logs a warning; in staging or production it leaves `secret_key` empty
659    /// so [`AppConfig::validate`] fails closed.
660    #[must_use]
661    pub fn from_env(app_name: impl Into<String>) -> Self {
662        let app_name = app_name.into();
663        let env = AppEnv::from_env();
664        let secret_key = match std::env::var("SLABS_SECRET_KEY") {
665            Ok(val) if !val.trim().is_empty() => val,
666            _ if env.is_dev_or_test() => {
667                use rand_core::RngCore as _;
668                let mut bytes = [0u8; 32];
669                rand_core::OsRng.fill_bytes(&mut bytes);
670                tracing::warn!(
671                    env = env.as_str(),
672                    "SLABS_SECRET_KEY is not set; generated an ephemeral random secret key for this process"
673                );
674                hex::encode(bytes)
675            }
676            _ => String::new(),
677        };
678
679        let cors_origins = std::env::var("SLABS_CORS_ORIGINS").map_or_else(
680            |_| Vec::new(),
681            |raw| {
682                raw.split(',')
683                    .map(str::trim)
684                    .filter(|s| !s.is_empty())
685                    .map(ToOwned::to_owned)
686                    .collect()
687            },
688        );
689
690        let metrics_token = std::env::var("SLABS_METRICS_TOKEN")
691            .ok()
692            .map(|s| s.trim().to_owned())
693            .filter(|s| !s.is_empty());
694
695        let git_sha = std::env::var("SLABS_GIT_SHA")
696            .ok()
697            .map(|s| s.trim().to_owned())
698            .filter(|s| !s.is_empty());
699
700        let incident_webhook_url = std::env::var("SLABS_INCIDENT_WEBHOOK_URL")
701            .ok()
702            .map(|s| s.trim().to_owned())
703            .filter(|s| !s.is_empty());
704
705        let incident_webhook_secret = std::env::var("SLABS_INCIDENT_WEBHOOK_SECRET")
706            .ok()
707            .map(|s| s.trim().to_owned())
708            .filter(|s| !s.is_empty());
709
710        Self {
711            env,
712            app_name: app_name.clone(),
713            bind_addr: std::env::var("SLABS_BIND").unwrap_or_else(|_| "127.0.0.1:3000".into()),
714            database_url: std::env::var("DATABASE_URL")
715                .unwrap_or_else(|_| format!("sqlite://{app_name}.db?mode=rwc")),
716            secret_key,
717            storage_dir: std::env::var("SLABS_STORAGE_DIR").map_or_else(
718                |_| PathBuf::from(format!("./storage/{app_name}")),
719                PathBuf::from,
720            ),
721            assets_dir: std::env::var("SLABS_ASSETS_DIR").map_or_else(
722                |_| {
723                    let local = PathBuf::from("./assets");
724                    if local.is_dir() {
725                        local
726                    } else {
727                        PathBuf::from(format!("./examples/{app_name}/assets"))
728                    }
729                },
730                PathBuf::from,
731            ),
732            job_poll_interval_ms: std::env::var("SLABS_JOB_POLL_MS")
733                .ok()
734                .and_then(|v| v.parse().ok())
735                .unwrap_or(500),
736            job_concurrency: std::env::var("SLABS_JOB_CONCURRENCY")
737                .ok()
738                .and_then(|v| v.parse().ok())
739                .unwrap_or(4),
740            cookie_secure: parse_bool_env("SLABS_COOKIE_SECURE")
741                .unwrap_or_else(|| env.is_prod_like()),
742            webhooks_live: parse_bool_env("SLABS_WEBHOOKS_LIVE").unwrap_or(false),
743            webhooks_allow_local: parse_bool_env("SLABS_WEBHOOKS_ALLOW_LOCAL").unwrap_or(false),
744            cors_origins,
745            trust_proxy: parse_bool_env("SLABS_TRUST_PROXY").unwrap_or(false),
746            metrics_token,
747            max_body_bytes: std::env::var("SLABS_MAX_BODY_BYTES")
748                .ok()
749                .and_then(|v| v.parse().ok())
750                .unwrap_or(4 * 1024 * 1024),
751            max_blob_bytes: std::env::var("SLABS_MAX_BLOB_BYTES")
752                .ok()
753                .and_then(|v| v.parse().ok())
754                .unwrap_or(10 * 1024 * 1024),
755            csrf_enforce: parse_bool_env("SLABS_CSRF_ENFORCE").unwrap_or(true),
756            slow_request_ms: std::env::var("SLABS_SLOW_REQUEST_MS")
757                .ok()
758                .and_then(|v| v.parse().ok())
759                .unwrap_or(500),
760            slow_job_ms: std::env::var("SLABS_SLOW_JOB_MS")
761                .ok()
762                .and_then(|v| v.parse().ok())
763                .unwrap_or(5_000),
764            git_sha,
765            incident_webhook_url,
766            incident_webhook_secret,
767            bug_reporter_enabled: parse_bool_env("SLABS_BUG_REPORTER")
768                .unwrap_or(matches!(env, AppEnv::Development | AppEnv::Staging)),
769            bug_reporter_allow_anonymous: parse_bool_env("SLABS_BUG_REPORTER_ANONYMOUS")
770                .unwrap_or(false),
771        }
772    }
773
774    /// Builds an isolated configuration for parallel tests.
775    ///
776    /// Uses `env = AppEnv::Test`, `database_url = "sqlite::memory:"`, `bind_addr = "127.0.0.1:0"`,
777    /// a 50ms job poll interval, and disables `cookie_secure`, `webhooks_live`, and `webhooks_allow_local`.
778    #[must_use]
779    pub fn for_test(app_name: impl Into<String>, storage_dir: PathBuf) -> Self {
780        let app_name = app_name.into();
781        let assets_dir = if PathBuf::from("./assets").is_dir() {
782            PathBuf::from("./assets")
783        } else {
784            PathBuf::from(format!("./examples/{app_name}/assets"))
785        };
786        Self {
787            env: AppEnv::Test,
788            app_name,
789            bind_addr: "127.0.0.1:0".into(),
790            database_url: "sqlite::memory:".into(),
791            secret_key: "test-only-slabs-secret-key-at-least-32-bytes-long!".into(),
792            storage_dir,
793            assets_dir,
794            job_poll_interval_ms: 50,
795            job_concurrency: 2,
796            cookie_secure: false,
797            webhooks_live: false,
798            webhooks_allow_local: false,
799            cors_origins: Vec::new(),
800            trust_proxy: false,
801            metrics_token: None,
802            max_body_bytes: 4 * 1024 * 1024,
803            max_blob_bytes: 10 * 1024 * 1024,
804            csrf_enforce: true,
805            slow_request_ms: 500,
806            slow_job_ms: 5_000,
807            git_sha: None,
808            incident_webhook_url: None,
809            incident_webhook_secret: None,
810            bug_reporter_enabled: false,
811            bug_reporter_allow_anonymous: false,
812        }
813    }
814
815    /// Validates configuration invariants, failing closed in staging and production environments.
816    ///
817    /// Rejects missing, short (`< 32` bytes), or sentinel `SLABS_SECRET_KEY` values when
818    /// `self.env.is_prod_like()` is `true`.
819    pub fn validate(&self) -> SlabResult<()> {
820        if self.env.is_prod_like() {
821            let trimmed = self.secret_key.trim();
822            if trimmed.len() < 32 || trimmed == Self::DEV_SECRET_FALLBACK_SENTINEL {
823                return Err(SlabError::internal(format!(
824                    "invalid SLABS_SECRET_KEY for {} environment: set SLABS_SECRET_KEY to a unique secret of at least 32 bytes",
825                    self.env.as_str()
826                )));
827            }
828        }
829        Ok(())
830    }
831}
832
833/// Machine-readable HTTP route metadata emitted by `/_slabs/manifest` and `slabs manifest`.
834///
835/// Agents read this list to inspect every registered endpoint in a single call.
836#[derive(Debug, Clone, Serialize, Deserialize)]
837pub struct RouteMeta {
838    /// Unique identifier for the slab route (for example `rooms::create_room`).
839    pub name: String,
840    /// HTTP verb accepted by the route (for example `GET` or `POST`).
841    pub method: String,
842    /// URL path pattern registered with the router (for example `/api/rooms/{room_id}`).
843    pub path: String,
844    /// Short description of what the slab does.
845    pub summary: String,
846    /// Feature group owning this slab, derived from `slabs/<feature>/`.
847    pub feature: String,
848    /// Optional JSON Schema describing the expected request body.
849    #[serde(default, skip_serializing_if = "Option::is_none")]
850    pub input_schema: Option<serde_json::Value>,
851    /// Optional JSON Schema describing the JSON response body.
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    pub output_schema: Option<serde_json::Value>,
854}
855
856/// Machine-readable metadata describing a registered background job.
857#[derive(Debug, Clone, Serialize, Deserialize)]
858pub struct JobMeta {
859    /// Unique job identifier used when enqueueing work.
860    pub name: String,
861    /// Queue name this job is routed to.
862    pub queue: String,
863    /// Maximum number of execution attempts before the worker marks the job failed.
864    pub max_attempts: i64,
865    /// Short description of what the job performs.
866    pub summary: String,
867}
868
869/// Complete JSON manifest of an application's discovered HTTP routes and background jobs.
870#[derive(Debug, Clone, Serialize, Deserialize)]
871pub struct AppManifest {
872    /// Name of the application producing this manifest.
873    pub app_name: String,
874    /// All HTTP slab routes registered in the application.
875    pub routes: Vec<RouteMeta>,
876    /// All background jobs registered in the application.
877    pub jobs: Vec<JobMeta>,
878}
879
880impl AppManifest {
881    /// Exports this application manifest as an `OpenAPI` `3.1.0` JSON document.
882    ///
883    /// Extracts `{param}` and `{*wildcard}` path segments into `OpenAPI` path parameters,
884    /// attaches `requestBody` (`application/json`) when `input_schema` is present, and
885    /// attaches `responses["200"]` (`application/json`) when `output_schema` is present.
886    #[must_use]
887    pub fn to_openapi_3_1(&self) -> serde_json::Value {
888        let mut paths = serde_json::Map::new();
889
890        for route in &self.routes {
891            let mut parameters = Vec::new();
892            let mut normalized_segments = Vec::new();
893
894            for segment in route.path.split('/') {
895                if let Some(inner) = segment.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
896                    let param_name = inner.strip_prefix('*').unwrap_or(inner);
897                    if !param_name.is_empty() {
898                        parameters.push(json!({
899                            "name": param_name,
900                            "in": "path",
901                            "required": true,
902                            "schema": { "type": "string" },
903                        }));
904                        normalized_segments.push(format!("{{{param_name}}}"));
905                        continue;
906                    }
907                }
908                normalized_segments.push(segment.to_string());
909            }
910
911            let openapi_path = normalized_segments.join("/");
912            let method_key = route.method.to_ascii_lowercase();
913
914            let mut operation = serde_json::Map::new();
915            operation.insert("operationId".into(), json!(route.name));
916            operation.insert("summary".into(), json!(route.summary));
917            if !route.feature.is_empty() {
918                operation.insert("tags".into(), json!([route.feature]));
919            }
920            if !parameters.is_empty() {
921                operation.insert("parameters".into(), serde_json::Value::Array(parameters));
922            }
923            if let Some(input_schema) = &route.input_schema {
924                operation.insert(
925                    "requestBody".into(),
926                    json!({
927                        "required": true,
928                        "content": {
929                            "application/json": {
930                                "schema": input_schema,
931                            }
932                        }
933                    }),
934                );
935            }
936
937            let ok_response = if let Some(output_schema) = &route.output_schema {
938                json!({
939                    "description": "Success",
940                    "content": {
941                        "application/json": {
942                            "schema": output_schema,
943                        }
944                    }
945                })
946            } else {
947                json!({
948                    "description": "Success",
949                })
950            };
951            operation.insert("responses".into(), json!({ "200": ok_response }));
952
953            let path_item = paths
954                .entry(openapi_path)
955                .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
956            if let Some(path_obj) = path_item.as_object_mut() {
957                path_obj.insert(method_key, serde_json::Value::Object(operation));
958            }
959        }
960
961        json!({
962            "openapi": "3.1.0",
963            "info": {
964                "title": self.app_name,
965                "version": "0.1.0",
966            },
967            "paths": serde_json::Value::Object(paths),
968        })
969    }
970}
971
972/// URL slug generation helpers.
973pub mod slug {
974    /// Convert arbitrary text into a lowercase, hyphen-separated URL slug.
975    ///
976    /// Keeps ASCII alphanumeric characters, collapses separator runs into a single `-`,
977    /// trims leading and trailing hyphens, and returns `"-"` if no alphanumeric characters remain.
978    #[must_use]
979    pub fn slugify(input: &str) -> String {
980        let mut out = String::with_capacity(input.len());
981        let mut prev_hyphen = true;
982        for ch in input.chars() {
983            if ch.is_ascii_alphanumeric() {
984                out.push(ch.to_ascii_lowercase());
985                prev_hyphen = false;
986            } else if !prev_hyphen {
987                out.push('-');
988                prev_hyphen = true;
989            }
990        }
991        while out.ends_with('-') {
992            out.pop();
993        }
994        if out.is_empty() {
995            "-".to_string()
996        } else {
997            out
998        }
999    }
1000}
1001
1002/// Fractional list positioning helpers for O(1) single-row reordering.
1003pub mod position {
1004    /// Compute a fractional `f64` sort score between two optional neighbor positions.
1005    ///
1006    /// - `(None, None)` returns `1.0` (first item in an empty list).
1007    /// - `(Some(prev), None)` returns `prev + 1.0` (append after `prev`).
1008    /// - `(None, Some(next))` returns `next / 2.0` (prepend before `next`, or `next - 1.0` when `next <= 0.0`).
1009    /// - `(Some(prev), Some(next))` returns `(prev + next) / 2.0` (insert between `prev` and `next`).
1010    #[must_use]
1011    pub fn between(prev: Option<f64>, next: Option<f64>) -> f64 {
1012        match (prev, next) {
1013            (None, None) => 1.0,
1014            (Some(p), None) => p + 1.0,
1015            (None, Some(n)) => {
1016                if n > 0.0 {
1017                    n / 2.0
1018                } else {
1019                    n - 1.0
1020                }
1021            }
1022            (Some(p), Some(n)) => f64::midpoint(p, n),
1023        }
1024    }
1025}
1026
1027/// Compute a lowercase SHA-256 hex digest over length-prefixed string parts.
1028///
1029/// Each part is hashed with its 64-bit little-endian byte length prefix followed by its UTF-8
1030/// bytes, preventing delimiter-collision attacks even when parts contain NUL bytes.
1031/// Use this for content fingerprints, optimistic concurrency checks (`If-Match`), and cache keys.
1032#[must_use]
1033pub fn fingerprint(parts: &[&str]) -> String {
1034    use sha2::{Digest, Sha256};
1035
1036    let mut hasher = Sha256::new();
1037    for part in parts {
1038        hasher.update((part.len() as u64).to_le_bytes());
1039        hasher.update(part.as_bytes());
1040    }
1041    hex::encode(hasher.finalize())
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046    use super::*;
1047
1048    #[test]
1049    fn slugify_normalizes_titles_and_fallbacks() {
1050        assert_eq!(slug::slugify("Hello, World! 2026"), "hello-world-2026");
1051        assert_eq!(
1052            slug::slugify("  Rust & SQLite --- WAL  "),
1053            "rust-sqlite-wal"
1054        );
1055        assert_eq!(slug::slugify("!!!"), "-");
1056    }
1057
1058    #[test]
1059    fn position_between_orders_items() {
1060        assert!((position::between(None, None) - 1.0).abs() < f64::EPSILON);
1061        assert!((position::between(Some(2.0), None) - 3.0).abs() < f64::EPSILON);
1062        assert!((position::between(None, Some(1.0)) - 0.5).abs() < f64::EPSILON);
1063        assert!((position::between(Some(1.0), Some(2.0)) - 1.5).abs() < f64::EPSILON);
1064    }
1065
1066    #[test]
1067    fn fingerprint_distinguishes_part_boundaries_and_embedded_nuls() {
1068        assert_ne!(fingerprint(&["ab", "c"]), fingerprint(&["a", "bc"]));
1069        assert_ne!(fingerprint(&["a\0b", "c"]), fingerprint(&["a", "b\0c"]));
1070        assert_ne!(fingerprint(&["a", ""]), fingerprint(&["a"]));
1071        assert_eq!(fingerprint(&["a", "b"]).len(), 64);
1072    }
1073
1074    #[test]
1075    fn app_env_parses_and_classifies_modes() {
1076        assert_eq!(AppEnv::parse_env("dev"), AppEnv::Development);
1077        assert_eq!(AppEnv::parse_env("Development"), AppEnv::Development);
1078        assert_eq!(AppEnv::parse_env("test"), AppEnv::Test);
1079        assert_eq!(AppEnv::parse_env("staging"), AppEnv::Staging);
1080        assert_eq!(AppEnv::parse_env("REVIEW"), AppEnv::Staging);
1081        assert_eq!(AppEnv::parse_env("prod"), AppEnv::Production);
1082        assert_eq!(AppEnv::parse_env("  Production "), AppEnv::Production);
1083        assert_eq!(AppEnv::parse_env("unknown"), AppEnv::Development);
1084
1085        assert!(AppEnv::Development.is_dev_or_test());
1086        assert!(!AppEnv::Development.is_prod_like());
1087        assert_eq!(AppEnv::Development.as_str(), "development");
1088
1089        assert!(AppEnv::Test.is_dev_or_test());
1090        assert!(!AppEnv::Test.is_prod_like());
1091        assert_eq!(AppEnv::Test.as_str(), "test");
1092
1093        assert!(AppEnv::Staging.is_prod_like());
1094        assert!(!AppEnv::Staging.is_dev_or_test());
1095        assert_eq!(AppEnv::Staging.as_str(), "staging");
1096
1097        assert!(AppEnv::Production.is_prod_like());
1098        assert!(!AppEnv::Production.is_dev_or_test());
1099        assert_eq!(AppEnv::Production.as_str(), "production");
1100    }
1101
1102    #[test]
1103    fn app_config_validate_fails_closed_in_prod_like_envs() {
1104        let mut cfg = AppConfig::for_test("demo", PathBuf::from("./tmp"));
1105        assert!(cfg.validate().is_ok());
1106
1107        // Short or empty secret allowed in dev/test
1108        cfg.env = AppEnv::Development;
1109        cfg.secret_key = String::new();
1110        assert!(cfg.validate().is_ok());
1111
1112        // Staging/Production reject empty, short, and sentinel secrets
1113        for prod_env in [AppEnv::Staging, AppEnv::Production] {
1114            cfg.env = prod_env;
1115            cfg.secret_key = String::new();
1116            assert!(cfg.validate().is_err());
1117
1118            cfg.secret_key = "too-short-secret-key".into();
1119            assert!(cfg.validate().is_err());
1120
1121            cfg.secret_key = AppConfig::DEV_SECRET_FALLBACK_SENTINEL.into();
1122            assert!(cfg.validate().is_err());
1123
1124            cfg.secret_key = "a".repeat(32);
1125            assert!(cfg.validate().is_ok());
1126        }
1127    }
1128
1129    #[test]
1130    fn app_config_debug_and_serde_redact_secrets_and_db_passwords() {
1131        let mut config = AppConfig::for_test("demo", PathBuf::from("./tmp"));
1132        assert_eq!(config.slow_request_ms, 500);
1133        assert_eq!(config.slow_job_ms, 5_000);
1134        assert!(config.git_sha.is_none());
1135        assert!(config.incident_webhook_url.is_none());
1136        assert!(config.incident_webhook_secret.is_none());
1137        assert!(!config.bug_reporter_enabled);
1138        assert!(!config.bug_reporter_allow_anonymous);
1139
1140        config.secret_key = "super-secret-signing-key-value-32-bytes!".into();
1141        config.metrics_token = Some("metrics-bearer-secret".into());
1142        config.database_url = "postgres://app_user:db_super_secret@db.internal:5432/slabs".into();
1143        config.incident_webhook_url =
1144            Some("https://hooks.example.com/incidents?token=topsecret123".into());
1145        config.incident_webhook_secret = Some("whsec_super_secret_hmac_key".into());
1146
1147        let rendered = format!("{config:?}");
1148        assert!(!rendered.contains("super-secret-signing-key-value-32-bytes!"));
1149        assert!(!rendered.contains("metrics-bearer-secret"));
1150        assert!(!rendered.contains("db_super_secret"));
1151        assert!(!rendered.contains("topsecret123"));
1152        assert!(!rendered.contains("whsec_super_secret_hmac_key"));
1153        assert!(rendered.contains("postgres://app_user:[REDACTED]@db.internal:5432/slabs"));
1154        assert!(rendered.contains("metrics_token: Some(\"[REDACTED]\")"));
1155        assert!(rendered.contains("incident_webhook_url: Some(\"[CONFIGURED]\")"));
1156        assert!(rendered.contains("incident_webhook_secret: Some(\"[REDACTED]\")"));
1157        assert!(rendered.contains("secret_key: \"[REDACTED]\""));
1158
1159        let serialized = serde_json::to_value(&config).unwrap();
1160        assert!(serialized.get("secret_key").is_none());
1161        assert!(serialized.get("metrics_token").is_none());
1162        assert!(serialized.get("incident_webhook_url").is_none());
1163        assert!(serialized.get("incident_webhook_secret").is_none());
1164    }
1165
1166    #[test]
1167    fn validate_rejects_control_chars_oversized_inputs_and_invalid_urls() {
1168        let mut v = Validate::new();
1169        let long_email = format!("{}@example.com", "a".repeat(250));
1170        let long_url = format!("https://example.com/{}", "a".repeat(2040));
1171
1172        v.email("email_crlf", "alice@example.com\r\nBcc: evil@example.com")
1173            .email("email_nul", "alice\0@example.com")
1174            .email("email_del", "alice\x7f@example.com")
1175            .email("email_long", &long_email)
1176            .url("url_ctrl", "https://example.com/\x07path")
1177            .url("url_crlf", "https://example.com/\r\n")
1178            .url("url_no_host", "https://:8080/path")
1179            .url("url_query_only", "https://?query=1")
1180            .url("url_javascript", "javascript:alert(1)")
1181            .url("url_long", &long_url)
1182            .url("url_valid", "https://example.com:8443/path?a=1#frag");
1183
1184        assert!(v.errors().contains_key("email_crlf"));
1185        assert!(v.errors().contains_key("email_nul"));
1186        assert!(v.errors().contains_key("email_del"));
1187        assert!(v.errors().contains_key("email_long"));
1188        assert!(v.errors().contains_key("url_ctrl"));
1189        assert!(v.errors().contains_key("url_crlf"));
1190        assert!(v.errors().contains_key("url_no_host"));
1191        assert!(v.errors().contains_key("url_query_only"));
1192        assert!(v.errors().contains_key("url_javascript"));
1193        assert!(v.errors().contains_key("url_long"));
1194        assert!(!v.errors().contains_key("url_valid"));
1195    }
1196
1197    #[test]
1198    fn validate_builder_succeeds_for_valid_inputs() {
1199        let mut v = Validate::new();
1200        v.required("name", "  Alice  ")
1201            .min_len("name", "  Alice  ", 3)
1202            .max_len("name", "  Alice  ", 10)
1203            .email("email", " alice@example.com ")
1204            .url("website", "https://example.com/docs")
1205            .one_of("role", "admin", &["member", "admin"])
1206            .check("age", true, "must be adult");
1207
1208        assert!(v.is_empty());
1209        assert!(v.errors().is_empty());
1210        assert!(v.finish().is_ok());
1211    }
1212
1213    #[test]
1214    fn validate_builder_collects_all_field_errors_and_maps_to_422() {
1215        let mut v = Validate::new();
1216        v.required("title", "   ")
1217            .min_len("title", "hi", 3)
1218            .max_len("bio", "123456", 5)
1219            .email("email", "not-an-email")
1220            .url("website", "ftp://example.com")
1221            .one_of("role", "owner", &["member", "admin"])
1222            .check("terms", false, "must accept terms")
1223            .push("custom", "extra problem");
1224
1225        assert!(!v.is_empty());
1226        assert_eq!(v.errors()["title"].len(), 2);
1227        assert_eq!(v.errors()["title"][0], "is required");
1228        assert!(v.errors().contains_key("bio"));
1229        assert!(v.errors().contains_key("email"));
1230        assert!(v.errors().contains_key("website"));
1231        assert!(v.errors().contains_key("role"));
1232        assert_eq!(v.errors()["terms"], vec!["must accept terms"]);
1233        assert_eq!(v.errors()["custom"], vec!["extra problem"]);
1234
1235        let err = v.finish().unwrap_err();
1236        assert_eq!(err.status_code(), StatusCode::UNPROCESSABLE_ENTITY);
1237
1238        let response = err.into_response();
1239        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
1240    }
1241
1242    #[test]
1243    fn validate_checks_unicode_char_lengths_and_email_url_edge_cases() {
1244        let mut v = Validate::new();
1245        // 5 chars ("café!"), even though UTF-8 byte length is 6
1246        v.min_len("label", "café!", 5)
1247            .max_len("label", "café!", 5)
1248            .email("bad_at", "@example.com")
1249            .email("bad_dot", "alice@localhost")
1250            .email("bad_trail", "alice@example.")
1251            .url("bare_scheme", "https://")
1252            .url("http_ok", "http://localhost:3000");
1253
1254        assert!(!v.errors().contains_key("label"));
1255        assert!(v.errors().contains_key("bad_at"));
1256        assert!(v.errors().contains_key("bad_dot"));
1257        assert!(v.errors().contains_key("bad_trail"));
1258        assert!(v.errors().contains_key("bare_scheme"));
1259        assert!(!v.errors().contains_key("http_ok"));
1260    }
1261
1262    #[test]
1263    fn app_manifest_to_openapi_3_1_builds_paths_params_and_schemas() {
1264        let manifest = AppManifest {
1265            app_name: "campfire".into(),
1266            routes: vec![
1267                RouteMeta {
1268                    name: "rooms::list_rooms".into(),
1269                    method: "GET".into(),
1270                    path: "/api/rooms".into(),
1271                    summary: "List all rooms".into(),
1272                    feature: "rooms".into(),
1273                    input_schema: None,
1274                    output_schema: Some(json!({
1275                        "type": "array",
1276                        "items": { "type": "object" }
1277                    })),
1278                },
1279                RouteMeta {
1280                    name: "rooms::create_room".into(),
1281                    method: "POST".into(),
1282                    path: "/api/rooms".into(),
1283                    summary: "Create a room".into(),
1284                    feature: "rooms".into(),
1285                    input_schema: Some(json!({
1286                        "type": "object",
1287                        "required": ["name"],
1288                        "properties": { "name": { "type": "string" } }
1289                    })),
1290                    output_schema: Some(json!({
1291                        "type": "object",
1292                        "properties": { "id": { "type": "string" } }
1293                    })),
1294                },
1295                RouteMeta {
1296                    name: "messages::get_message".into(),
1297                    method: "GET".into(),
1298                    path: "/api/rooms/{room_id}/messages/{msg_id}".into(),
1299                    summary: "Get one message".into(),
1300                    feature: "messages".into(),
1301                    input_schema: None,
1302                    output_schema: None,
1303                },
1304                RouteMeta {
1305                    name: "files::serve_asset".into(),
1306                    method: "GET".into(),
1307                    path: "/assets/{*filepath}".into(),
1308                    summary: "Serve a static asset".into(),
1309                    feature: "files".into(),
1310                    input_schema: None,
1311                    output_schema: None,
1312                },
1313            ],
1314            jobs: vec![],
1315        };
1316
1317        let doc = manifest.to_openapi_3_1();
1318        assert_eq!(doc["openapi"], "3.1.0");
1319        assert_eq!(doc["info"]["title"], "campfire");
1320        assert_eq!(doc["info"]["version"], "0.1.0");
1321
1322        // Same path with GET and POST should merge into one Path Item object
1323        assert_eq!(
1324            doc["paths"]["/api/rooms"]["get"]["operationId"],
1325            "rooms::list_rooms"
1326        );
1327        assert!(doc["paths"]["/api/rooms"]["get"]["requestBody"].is_null());
1328        assert_eq!(
1329            doc["paths"]["/api/rooms"]["get"]["responses"]["200"]["content"]["application/json"]
1330                ["schema"]["type"],
1331            "array"
1332        );
1333
1334        assert_eq!(
1335            doc["paths"]["/api/rooms"]["post"]["operationId"],
1336            "rooms::create_room"
1337        );
1338        assert_eq!(
1339            doc["paths"]["/api/rooms"]["post"]["requestBody"]["content"]["application/json"]
1340                ["schema"]["required"][0],
1341            "name"
1342        );
1343        assert_eq!(
1344            doc["paths"]["/api/rooms"]["post"]["responses"]["200"]["content"]["application/json"]
1345                ["schema"]["properties"]["id"]["type"],
1346            "string"
1347        );
1348
1349        // Multi-parameter path extraction
1350        let params = doc["paths"]["/api/rooms/{room_id}/messages/{msg_id}"]["get"]["parameters"]
1351            .as_array()
1352            .unwrap();
1353        assert_eq!(params.len(), 2);
1354        assert_eq!(params[0]["name"], "room_id");
1355        assert_eq!(params[0]["in"], "path");
1356        assert_eq!(params[0]["required"], true);
1357        assert_eq!(params[0]["schema"]["type"], "string");
1358        assert_eq!(params[1]["name"], "msg_id");
1359
1360        // Wildcard parameter extraction
1361        let wildcard_params = doc["paths"]["/assets/{filepath}"]["get"]["parameters"]
1362            .as_array()
1363            .unwrap();
1364        assert_eq!(wildcard_params.len(), 1);
1365        assert_eq!(wildcard_params[0]["name"], "filepath");
1366        assert_eq!(wildcard_params[0]["in"], "path");
1367        assert_eq!(wildcard_params[0]["required"], true);
1368    }
1369
1370    #[test]
1371    fn route_meta_omits_none_schemas_when_serialized() {
1372        let meta = RouteMeta {
1373            name: "health::check".into(),
1374            method: "GET".into(),
1375            path: "/health".into(),
1376            summary: "Health check".into(),
1377            feature: "health".into(),
1378            input_schema: None,
1379            output_schema: None,
1380        };
1381        let value = serde_json::to_value(&meta).unwrap();
1382        assert!(value.get("input_schema").is_none());
1383        assert!(value.get("output_schema").is_none());
1384
1385        let parsed: RouteMeta = serde_json::from_value(value).unwrap();
1386        assert!(parsed.input_schema.is_none());
1387        assert!(parsed.output_schema.is_none());
1388    }
1389}