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