use clap::{Parser, Subcommand, ValueEnum};
use serde_json::{json, Value};
use slabs_db::{Db, DbEngine};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::process::Command;
#[derive(Parser, Debug)]
#[command(
name = "slabs",
about = "Batteries-included, agent-first Transaction Script web framework CLI"
)]
struct Cli {
#[arg(long, global = true, default_value = ".")]
app_dir: PathBuf,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
New {
#[command(subcommand)]
kind: NewKind,
},
Db {
#[command(subcommand)]
action: DbAction,
},
Fmt {
#[arg(long)]
check: bool,
},
Check {
#[arg(long)]
workspace: bool,
#[arg(long)]
no_docs: bool,
#[arg(long)]
changed: bool,
#[arg(long)]
base: Option<String>,
#[arg(long)]
slab: Option<String>,
#[arg(long)]
explain: bool,
#[arg(long)]
strict_explain: bool,
#[arg(short, long)]
verbose: bool,
},
Manifest {
#[arg(long)]
json: bool,
#[arg(long)]
write: Option<PathBuf>,
#[arg(long)]
diff: Option<String>,
},
Doctor,
Deploy {
#[command(subcommand)]
action: DeployAction,
},
List,
Css {
#[arg(long)]
watch: bool,
},
Dev {
#[arg(long, short)]
package: Option<String>,
#[arg(long)]
bind: Option<String>,
#[arg(long)]
ephemeral: bool,
},
Incidents {
#[command(subcommand)]
action: IncidentsAction,
},
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum HttpMethod {
Get,
Post,
Put,
Patch,
Delete,
}
impl HttpMethod {
const fn as_str(self) -> &'static str {
match self {
Self::Get => "get",
Self::Post => "post",
Self::Put => "put",
Self::Patch => "patch",
Self::Delete => "delete",
}
}
const fn axum_const(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST",
Self::Put => "PUT",
Self::Patch => "PATCH",
Self::Delete => "DELETE",
}
}
}
#[derive(Subcommand, Debug)]
enum NewKind {
App {
name: String,
#[arg(long)]
dir: Option<PathBuf>,
},
Slab {
feature: String,
name: String,
#[arg(long, value_enum, default_value_t = HttpMethod::Post)]
method: HttpMethod,
#[arg(long)]
path: Option<String>,
},
BugReport {
#[arg(long, default_value = "support")]
feature: String,
#[arg(long, default_value = "report_bug")]
name: String,
},
Job { name: String },
Migration {
name: String,
},
}
#[derive(Subcommand, Debug)]
enum DeployAction {
Init {
#[arg(long, value_enum)]
target: DeployTarget,
#[arg(long)]
app: Option<String>,
#[arg(long)]
force: bool,
},
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum DeployTarget {
Kamal,
Fly,
Vps,
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum IncidentStatusFilter {
Active,
Open,
Reopened,
Resolved,
All,
}
impl IncidentStatusFilter {
const fn as_str(self) -> &'static str {
match self {
Self::Active => "active",
Self::Open => "open",
Self::Reopened => "reopened",
Self::Resolved => "resolved",
Self::All => "all",
}
}
}
#[derive(Subcommand, Debug)]
enum IncidentsAction {
List {
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
#[arg(long, value_enum, default_value_t = IncidentStatusFilter::Active)]
status: IncidentStatusFilter,
#[arg(long, default_value_t = 50)]
limit: u32,
#[arg(long)]
json: bool,
},
Show {
id: String,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
#[arg(long)]
json: bool,
},
Resolve {
id: String,
#[arg(long)]
sha: Option<String>,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
},
Perf {
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand, Debug)]
enum DbAction {
Migrate {
#[arg(long, env = "DATABASE_URL")]
database_url: String,
#[arg(long)]
no_dump: bool,
},
DumpSchema {
#[arg(long)]
database_url: Option<String>,
},
Seed {
#[arg(long, env = "DATABASE_URL")]
database_url: String,
#[arg(long)]
file: Option<PathBuf>,
},
Prepare {
#[arg(long, env = "DATABASE_URL")]
database_url: Option<String>,
#[arg(long, short)]
package: Option<String>,
},
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match cli.command {
Commands::New { kind } => match kind {
NewKind::App { name, dir } => {
validate_app_name(&name)?;
let target_dir = dir.unwrap_or_else(|| PathBuf::from(&name));
scaffold_app(&name, &target_dir)?;
println!("Created Slabs app `{name}` in {}", target_dir.display());
}
NewKind::Slab {
feature,
name,
method,
path,
} => {
validate_rust_ident(&feature)?;
validate_rust_ident(&name)?;
let route_path = path.unwrap_or_else(|| format!("/api/{feature}/{name}"));
validate_route_path(&route_path)?;
let dir = cli.app_dir.join("slabs").join(&feature);
fs::create_dir_all(&dir)?;
let target = dir.join(format!("{name}.rs"));
if target.exists() {
return Err(format!("slab already exists: {}", target.display()).into());
}
let template = render_slab_template(&feature, &name, method, &route_path);
fs::write(&target, template)?;
println!("Created slab: {}", target.display());
}
NewKind::BugReport { feature, name } => {
validate_rust_ident(&feature)?;
validate_rust_ident(&name)?;
let dir = cli.app_dir.join("slabs").join(&feature);
fs::create_dir_all(&dir)?;
let target = dir.join(format!("{name}.rs"));
if target.exists() {
return Err(format!("slab already exists: {}", target.display()).into());
}
let template = render_bug_report_template(&feature, &name);
fs::write(&target, template)?;
println!("Created bug-report slab: {}", target.display());
}
NewKind::Job { name } => {
validate_rust_ident(&name)?;
let dir = cli.app_dir.join("jobs");
fs::create_dir_all(&dir)?;
let target = dir.join(format!("{name}.rs"));
if target.exists() {
return Err(format!("job already exists: {}", target.display()).into());
}
let template = render_job_template(&name);
fs::write(&target, template)?;
println!("Created job: {}", target.display());
}
NewKind::Migration { name } => {
let target = scaffold_migration(&cli.app_dir, &name)?;
println!("Created migration: {}", target.display());
}
},
Commands::Db { action } => match action {
DbAction::Migrate {
database_url,
no_dump,
} => {
let migrations_dir = cli.app_dir.join("migrations");
match DbEngine::detect(&database_url) {
DbEngine::Sqlite => {
let db = Db::connect(&database_url).await?;
db.migrate_dir(&migrations_dir).await?;
println!(
"SQLite migrations applied from {}",
migrations_dir.display()
);
if !no_dump && !is_deployed_slabs_env() {
let schema_sql = dump_schema_from_migrations(&cli.app_dir).await?;
let target = cli.app_dir.join("schema.sql");
fs::write(&target, schema_sql)?;
println!("Updated schema snapshot: {}", target.display());
}
}
DbEngine::Postgres => {
return Err(
"PostgreSQL adapter is not enabled in Slabs 0.6; configure a sqlite:// DATABASE_URL"
.into(),
);
}
}
}
DbAction::DumpSchema { database_url } => {
let schema_sql = if let Some(url) = database_url {
dump_schema_from_url(&url).await?
} else if dir_has_sql_files(&cli.app_dir.join("migrations")) {
dump_schema_from_migrations(&cli.app_dir).await?
} else {
let fallback_url = match std::env::var("DATABASE_URL") {
Ok(url) if !url.trim().is_empty() => url,
_ => {
let pkg = infer_package_name(&cli.app_dir)?;
format!("sqlite://{pkg}.db?mode=rwc")
}
};
dump_schema_from_url(&fallback_url).await?
};
let target = cli.app_dir.join("schema.sql");
fs::write(&target, schema_sql)?;
println!("Wrote schema snapshot to {}", target.display());
}
DbAction::Seed { database_url, file } => {
let seed_file = file.unwrap_or_else(|| cli.app_dir.join("seeds.sql"));
match DbEngine::detect(&database_url) {
DbEngine::Sqlite => {
let db = Db::connect(&database_url).await?;
db.execute_sql_file(&seed_file).await?;
println!("Applied SQLite seed script from {}", seed_file.display());
}
DbEngine::Postgres => {
return Err(
"PostgreSQL adapter is not enabled in Slabs 0.6; configure a sqlite:// DATABASE_URL"
.into(),
);
}
}
}
DbAction::Prepare {
database_url,
package,
} => {
let pkg = match package {
Some(p) => {
validate_app_name(&p)?;
p
}
None => infer_package_name(&cli.app_dir)?,
};
let (url, temp_file) = if let Some(u) = database_url {
(u, None)
} else {
let tmp = std::env::temp_dir().join(format!(
"slabs_prepare_{pkg}_{}.db",
slabs_core::id::new("tmp")
));
let u = format!("sqlite://{}", tmp.display());
let db = Db::connect(&u).await?;
db.migrate_dir(&cli.app_dir.join("migrations")).await?;
(u, Some(tmp))
};
let status = Command::new("cargo")
.args(["sqlx", "prepare", "--", "-p", &pkg, "--all-targets"])
.env("DATABASE_URL", &url)
.status()
.await;
if let Some(tmp) = temp_file {
let _ = fs::remove_file(&tmp);
let _ = fs::remove_file(format!("{}-wal", tmp.display()));
let _ = fs::remove_file(format!("{}-shm", tmp.display()));
}
match status {
Ok(s) if s.success() => {
println!("Prepared compile-time SQLx metadata (.sqlx/) for `{pkg}`");
}
_ => {
return Err(
"cargo sqlx prepare failed. Install sqlx-cli via: `cargo install sqlx-cli --no-default-features --features sqlite`"
.into(),
);
}
}
}
},
Commands::Fmt { check } => {
run_fmt(&cli.app_dir, check).await?;
}
Commands::Check {
workspace,
no_docs,
changed,
base,
slab,
explain,
strict_explain,
verbose,
} => {
if slab.is_some() && (changed || base.is_some()) {
return Err("cannot combine `--slab` with `--changed` or `--base`".into());
}
let target = if let Some(spec) = slab {
CheckTarget::Slab(spec)
} else if changed || base.is_some() {
CheckTarget::Changed { base }
} else {
CheckTarget::Full
};
let explain_mode = if strict_explain {
ExplainMode::Strict
} else if explain {
ExplainMode::Warn
} else {
ExplainMode::Off
};
let opts = CheckOptions {
workspace,
no_docs,
target,
explain: explain_mode,
verbose,
};
run_check(&cli.app_dir, &opts).await?;
}
Commands::Manifest { json, write, diff } => {
run_manifest(&cli.app_dir, json, write.as_deref(), diff.as_deref())?;
}
Commands::Doctor => {
run_doctor(&cli.app_dir).await?;
}
Commands::Deploy { action } => match action {
DeployAction::Init { target, app, force } => {
let app_name = match app {
Some(a) => {
validate_app_name(&a)?;
a
}
None => infer_package_name(&cli.app_dir)?,
};
let created = scaffold_deploy(&cli.app_dir, &app_name, target, force)?;
for path in created {
println!("Created deployment template: {}", path.display());
}
}
},
Commands::List => {
list_dir(&cli.app_dir)?;
}
Commands::Css { watch } => {
run_tailwind(&cli.app_dir, watch).await?;
}
Commands::Dev {
package,
bind,
ephemeral,
} => {
if ephemeral {
run_dev_ephemeral(&cli.app_dir, package, bind).await?;
} else {
run_dev(&cli.app_dir, package, bind).await?;
}
}
Commands::Incidents { action } => match action {
IncidentsAction::List {
url,
token,
status,
limit,
json,
} => {
run_incidents_list(&url, token.as_deref(), status, limit, json).await?;
}
IncidentsAction::Show {
id,
url,
token,
json,
} => {
run_incidents_show(&url, token.as_deref(), &id, json).await?;
}
IncidentsAction::Resolve {
id,
sha,
url,
token,
} => {
run_incidents_resolve(&url, token.as_deref(), &id, sha.as_deref()).await?;
}
IncidentsAction::Perf { url, token, json } => {
run_incidents_perf(&url, token.as_deref(), json).await?;
}
},
}
Ok(())
}
const RUST_KEYWORDS: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
"unsafe", "use", "where", "while", "abstract", "become", "box", "do", "final", "gen", "macro",
"override", "priv", "try", "typeof", "unsized", "virtual", "yield", "union",
];
fn validate_rust_ident(value: &str) -> Result<(), String> {
let mut chars = value.chars();
let Some(first) = chars.next() else {
return Err("identifier must not be empty".to_string());
};
if !first.is_ascii_lowercase() {
return Err(format!(
"invalid Rust identifier `{value}`: must match ^[a-z][a-z0-9_]*$"
));
}
if !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
return Err(format!(
"invalid Rust identifier `{value}`: must match ^[a-z][a-z0-9_]*$"
));
}
if RUST_KEYWORDS.contains(&value) {
return Err(format!(
"invalid Rust identifier `{value}`: reserved Rust keyword"
));
}
Ok(())
}
fn validate_app_name(value: &str) -> Result<(), String> {
if value.is_empty() || value.len() > 64 {
return Err(format!(
"invalid app name `{value}`: must be 1 to 64 characters matching ^[a-z][a-z0-9_-]*$"
));
}
let mut chars = value.chars();
let Some(first) = chars.next() else {
return Err("app name must not be empty".to_string());
};
if !first.is_ascii_lowercase()
|| !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
{
return Err(format!(
"invalid app name `{value}`: must match ^[a-z][a-z0-9_-]*$"
));
}
Ok(())
}
fn validate_route_path(value: &str) -> Result<(), String> {
if !value.starts_with('/') {
return Err(format!("invalid route path `{value}`: must start with `/`"));
}
if value.chars().any(|c| {
c.is_whitespace() || c == '"' || c == '\\' || c == '\r' || c == '\n' || c.is_control()
}) {
return Err(format!(
"invalid route path `{value}`: must not contain whitespace, quotes, backslashes, or control characters"
));
}
Ok(())
}
fn render_slab_template(feature: &str, name: &str, method: HttpMethod, route_path: &str) -> String {
let method_lower = method.as_str();
let axum_method = method.axum_const();
if method == HttpMethod::Get {
format!(
r#"use axum::{{extract::State, http::StatusCode, Json}};
use axum_extra::extract::CookieJar;
use serde::Serialize;
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("{route_path}", handle)
.name("{feature}.{name}")
.summary("TODO: describe {feature}.{name}")
}}
#[derive(Debug, Serialize)]
pub struct Output {{
pub ok: bool,
}}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
) -> SlabResult<(StatusCode, Json<Output>)> {{
let session = ctx.auth.require_session(&jar).await?;
// Enforce resource ownership or role checks against `session.user_id` before returning data.
tracing::debug!(user_id = %session.user_id, "handling {feature}.{name}");
let _reader = ctx.db.reader();
Ok((StatusCode::OK, Json(Output {{ ok: true }})))
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn requires_authentication() {{
let app = crate::test_app().await;
let res = app.get("{route_path}").await;
assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}}
}}
"#
)
} else {
format!(
r#"use axum::{{extract::State, http::StatusCode, Json}};
use axum_extra::extract::CookieJar;
use serde::{{Deserialize, Serialize}};
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::{method_lower}("{route_path}", handle)
.name("{feature}.{name}")
.summary("TODO: describe {feature}.{name}")
}}
#[derive(Debug, Deserialize)]
pub struct Input {{
// Define request fields here, owned locally by this slab.
}}
#[derive(Debug, Serialize)]
pub struct Output {{
pub ok: bool,
}}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
Json(_input): Json<Input>,
) -> SlabResult<(StatusCode, Json<Output>)> {{
let session = ctx.auth.require_session(&jar).await?;
// Enforce resource ownership or role checks against `session.user_id` before mutating state.
tracing::debug!(user_id = %session.user_id, "handling {feature}.{name}");
let mut tx = ctx.db.begin().await?;
// Write self-contained parameterized SQL here using `sqlx::query` / `sqlx::query_as`.
tx.commit().await?;
Ok((StatusCode::OK, Json(Output {{ ok: true }})))
}}
#[cfg(test)]
mod tests {{
use axum::{{
body::Body,
http::{{header, Method, Request, StatusCode}},
}};
#[tokio::test]
async fn requires_authentication() {{
let app = crate::test_app().await;
let req = Request::builder()
.method(Method::{axum_method})
.uri("{route_path}")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from("{{}}"))
.unwrap();
let res = app.request(req).await;
assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}}
}}
"#
)
}
}
fn render_job_template(name: &str) -> String {
format!(
r#"use serde::Deserialize;
use serde_json::Value;
use slabs::prelude::*;
pub fn job() -> JobDef {{
JobDef::new("{name}", run).summary("TODO: describe {name}")
}}
#[derive(Debug, Deserialize)]
struct Payload {{
// Define job payload fields here.
}}
async fn run(ctx: AppCtx, raw: Value) -> SlabResult<()> {{
let payload: Payload = serde_json::from_value(raw)
.map_err(|e| SlabError::bad_request(format!("invalid job payload: {{e}}")))?;
tracing::debug!(?payload, "running job {name}");
let mut tx = ctx.db.begin().await?;
// Execute idempotent SQL updates inside this transaction.
tx.commit().await?;
Ok(())
}}
"#
)
}
fn render_bug_report_template(feature: &str, name: &str) -> String {
let route_path = format!("/{feature}/{name}");
format!(
r#"use axum::{{
body::Bytes,
extract::{{Multipart, State}},
http::{{header, HeaderMap, StatusCode, Uri}},
response::{{IntoResponse, Response}},
Json,
}};
use axum_extra::extract::CookieJar;
use serde::Serialize;
use serde_json::json;
use slabs::prelude::*;
const MIN_DESCRIPTION_CHARS: usize = 3;
const MAX_DESCRIPTION_CHARS: usize = 4_000;
const MAX_TITLE_CHARS: usize = 200;
const MAX_ATTACHMENTS: usize = 3;
const MAX_ATTACHMENT_BYTES: usize = 10 * 1024 * 1024;
const MAX_TOTAL_ATTACHMENT_BYTES: usize = 20 * 1024 * 1024;
// Set `SLABS_MAX_BODY_BYTES=20971520` in your environment if you want to accept full 20 MiB uploads.
pub fn slab() -> SlabDef {{
SlabDef::post("{route_path}", handle)
.name("{feature}.{name}")
.summary("Submit a user bug report with optional attachments")
}}
#[derive(Debug, Serialize)]
pub struct Output {{
pub id: String,
pub status: String,
pub attachments: usize,
}}
#[derive(Debug, Serialize)]
struct StoredAttachment {{
blob_id: String,
filename: String,
content_type: String,
byte_size: i64,
}}
struct PendingAttachment {{
filename: String,
content_type: &'static str,
bytes: Bytes,
}}
/// Render a zero-JS Basecoat bug-report form posting multipart data to `{route_path}`.
pub fn bug_report_form(source_file: &str) -> Markup {{
maud! {{
form
method="post"
action="{route_path}"
enctype="multipart/form-data"
class="form grid gap-4"
{{
input type="hidden" name="source_file" value=(source_file);
div class="grid gap-1.5" {{
label for="bug-report-title" class="label" {{ "Summary (optional)" }}
input
id="bug-report-title"
name="title"
type="text"
maxlength="200"
placeholder="Short summary of what went wrong"
class="input";
}}
div class="grid gap-1.5" {{
label for="bug-report-description" class="label" {{ "What happened?" }}
textarea
id="bug-report-description"
name="description"
required
minlength="3"
maxlength="4000"
rows="5"
placeholder="Describe what you expected and what happened instead."
class="textarea" {{}}
}}
div class="grid gap-1.5" {{
label for="bug-report-attachments" class="label" {{
"Attachments (up to 3 files: PNG, JPEG, WebP, GIF, MP4, WebM, TXT, LOG)"
}}
input
id="bug-report-attachments"
name="attachments"
type="file"
multiple
accept="image/png,image/jpeg,image/webp,image/gif,video/mp4,video/webm,text/plain,.txt,.log"
class="input";
}}
button type="submit" class="btn" {{ "Submit bug report" }}
}}
}}
}}
fn resolve_attachment_content_type(
content_type: Option<&str>,
filename: &str,
) -> SlabResult<&'static str> {{
let essence = content_type
.and_then(|ct| ct.split(';').next())
.map(|ct| ct.trim().to_ascii_lowercase())
.filter(|ct| !ct.is_empty() && ct != "application/octet-stream");
if let Some(ct) = essence {{
return match ct.as_str() {{
"image/png" => Ok("image/png"),
"image/jpeg" | "image/jpg" => Ok("image/jpeg"),
"image/webp" => Ok("image/webp"),
"image/gif" => Ok("image/gif"),
"video/mp4" => Ok("video/mp4"),
"video/webm" => Ok("video/webm"),
"text/plain" => Ok("text/plain"),
_ => Err(SlabError::bad_request(
"unsupported attachment type; allowed: png, jpeg, webp, gif, mp4, webm, txt, log",
)),
}};
}}
let ext = std::path::Path::new(filename)
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase);
match ext.as_deref() {{
Some("png") => Ok("image/png"),
Some("jpg" | "jpeg") => Ok("image/jpeg"),
Some("webp") => Ok("image/webp"),
Some("gif") => Ok("image/gif"),
Some("mp4") => Ok("video/mp4"),
Some("webm") => Ok("video/webm"),
Some("txt" | "log") => Ok("text/plain"),
_ => Err(SlabError::bad_request(
"unsupported attachment type; allowed: png, jpeg, webp, gif, mp4, webm, txt, log",
)),
}}
}}
fn sanitize_referer_path(headers: &HeaderMap) -> Option<String> {{
let raw = headers.get(header::REFERER)?.to_str().ok()?.trim();
if raw.is_empty() {{
return None;
}}
let path_only = if raw.starts_with("http://") || raw.starts_with("https://") {{
raw.parse::<Uri>()
.ok()
.map_or_else(|| "/".to_string(), |uri| uri.path().to_string())
}} else {{
raw.split(['?', '#']).next().unwrap_or("/").to_string()
}};
let clean: String = path_only
.trim()
.chars()
.filter(|&c| !c.is_control())
.take(256)
.collect();
if clean.is_empty() {{
None
}} else {{
Some(clean)
}}
}}
fn sanitize_source_file(raw: Option<&str>) -> String {{
let Some(value) = raw else {{
return "browser".to_string();
}};
let clean: String = value
.trim()
.chars()
.filter(|&c| !c.is_ascii_control() && c != '\\')
.take(200)
.collect();
let trimmed = clean.trim();
if trimmed.is_empty() || trimmed.contains("..") {{
"browser".to_string()
}} else {{
trimmed.to_string()
}}
}}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
headers: HeaderMap,
ClientIp(ip): ClientIp,
mut multipart: Multipart,
) -> SlabResult<Response> {{
let session = ctx.auth.require_session(&jar).await?;
ctx.rate_limit.check_pair(
&format!("bug_report:ip:{{ip}}"),
10,
&format!("bug_report:user:{{}}", session.user_id),
10,
300,
)?;
let mut title: Option<String> = None;
let mut description = String::new();
let mut source_file: Option<String> = None;
let mut pending_attachments: Vec<PendingAttachment> = Vec::new();
let mut total_attachment_bytes: usize = 0;
while let Some(field) = multipart
.next_field()
.await
.map_err(|e| SlabError::bad_request(format!("invalid multipart payload: {{e}}")))?
{{
let field_name = field.name().unwrap_or("").to_string();
match field_name.as_str() {{
"title" => {{
let val = field
.text()
.await
.map_err(|e| SlabError::bad_request(format!("invalid title field: {{e}}")))?;
let trimmed = val.trim();
if !trimmed.is_empty() {{
title = Some(trimmed.to_string());
}}
}}
"description" => {{
let val = field.text().await.map_err(|e| {{
SlabError::bad_request(format!("invalid description field: {{e}}"))
}})?;
description = val.trim().to_string();
}}
"source_file" => {{
let val = field.text().await.map_err(|e| {{
SlabError::bad_request(format!("invalid source_file field: {{e}}"))
}})?;
let trimmed = val.trim();
if !trimmed.is_empty() {{
source_file = Some(trimmed.to_string());
}}
}}
"attachments" | "attachment" => {{
let raw_filename = field.file_name().unwrap_or("").to_string();
let raw_ct = field.content_type().map(ToOwned::to_owned);
let bytes = field.bytes().await.map_err(|e| {{
SlabError::bad_request(format!("failed to read attachment: {{e}}"))
}})?;
if bytes.is_empty() && raw_filename.is_empty() {{
continue;
}}
if pending_attachments.len() >= MAX_ATTACHMENTS {{
return Err(SlabError::bad_request("at most 3 attachments are allowed"));
}}
if bytes.len() > MAX_ATTACHMENT_BYTES {{
return Err(SlabError::bad_request(
"each attachment must be at most 10 MiB",
));
}}
total_attachment_bytes = total_attachment_bytes
.checked_add(bytes.len())
.ok_or_else(|| SlabError::bad_request("attachment size overflow"))?;
if total_attachment_bytes > MAX_TOTAL_ATTACHMENT_BYTES {{
return Err(SlabError::bad_request(
"total attachments size must be at most 20 MiB",
));
}}
let filename = if raw_filename.is_empty() {{
"attachment.bin".to_string()
}} else {{
raw_filename
}};
let content_type = resolve_attachment_content_type(raw_ct.as_deref(), &filename)?;
pending_attachments.push(PendingAttachment {{
filename,
content_type,
bytes,
}});
}}
_ => {{}}
}}
}}
let mut v = Validate::new();
v.required("description", &description)
.min_len("description", &description, MIN_DESCRIPTION_CHARS)
.max_len("description", &description, MAX_DESCRIPTION_CHARS);
if let Some(ref t) = title {{
v.max_len("title", t, MAX_TITLE_CHARS);
}}
v.finish()?;
let mut stored_attachments = Vec::with_capacity(pending_attachments.len());
for att in pending_attachments {{
let meta = ctx
.storage
.put_scoped(
"bug_report",
&att.filename,
Some(att.content_type),
&att.bytes,
)
.await?;
stored_attachments.push(StoredAttachment {{
blob_id: meta.id,
filename: meta.filename,
content_type: meta.content_type,
byte_size: meta.byte_size,
}});
}}
let referer_path = sanitize_referer_path(&headers);
let user_agent = headers
.get(header::USER_AGENT)
.and_then(|h| h.to_str().ok())
.map(|s| {{
s.trim()
.chars()
.filter(|&c| !c.is_control())
.take(256)
.collect::<String>()
}})
.filter(|s| !s.is_empty());
let resolved_source_file = sanitize_source_file(source_file.as_deref());
let summary = title
.clone()
.unwrap_or_else(|| description.chars().take(120).collect());
let (record, _) = ctx
.incidents
.record(IncidentInput {{
kind: "user_bug_report".to_string(),
source_file: resolved_source_file,
route_pattern: referer_path.clone(),
status_code: None,
error_message: summary,
detail: Some(description),
context_json: json!({{
"title": title,
"reporter_user_id": session.user_id,
"reporter_role": session.role,
"referer_path": referer_path,
"user_agent": user_agent,
"git_sha": ctx.config.git_sha,
"app_env": ctx.config.env.as_str(),
"attachments": stored_attachments,
}}),
git_sha: ctx.config.git_sha.clone(),
custom_fingerprint: None,
}})
.await?;
tracing::info!(
incident_id = %record.id,
user_id = %session.user_id,
attachments = stored_attachments.len(),
"recorded user bug report"
);
if htmx::wants_json(&headers) {{
return Ok((
StatusCode::CREATED,
Json(Output {{
id: record.id,
status: record.status,
attachments: stored_attachments.len(),
}}),
)
.into_response());
}}
let return_href = referer_path.as_deref().unwrap_or("/");
let confirmation = maud! {{
section class="mx-auto max-w-xl px-6 py-12 space-y-4" {{
h1 class="text-2xl font-semibold tracking-tight" {{ "Bug report submitted" }}
p class="text-muted-foreground" {{
"Reference ID: " code {{ (record.id) }}
}}
a href=(return_href) class="btn-outline" {{ "Back" }}
}}
}};
if htmx::is_htmx(&headers) {{
return Ok((StatusCode::CREATED, confirmation).into_response());
}}
Ok((
StatusCode::CREATED,
html::document(
"Bug report submitted",
&ctx.assets.stylesheet_urls(),
&ctx.assets.behavior_urls(),
confirmation,
),
)
.into_response())
}}
#[cfg(test)]
mod tests {{
use axum::{{
body::Body,
http::{{header, Method, Request, StatusCode}},
}};
use slabs::prelude::SESSION_COOKIE_NAME;
#[tokio::test]
async fn requires_authentication() {{
let app = crate::test_app().await;
let req = Request::builder()
.method(Method::POST)
.uri("{route_path}")
.header(header::CONTENT_TYPE, "multipart/form-data; boundary=BOUND")
.body(Body::from("--BOUND--\r\n"))
.unwrap();
let res = app.request(req).await;
assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}}
#[tokio::test]
async fn records_bug_report_with_attachment() {{
let app = crate::test_app().await;
let (_session, cookie) = app
.ctx
.auth
.create_session("usr_reporter", "member", 1)
.await
.unwrap();
let boundary = "SLABSBUGBOUNDARY";
let mut body = Vec::new();
body.extend_from_slice(
format!(
"--{{boundary}}\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nBroken button\r\n\
--{{boundary}}\r\nContent-Disposition: form-data; name=\"description\"\r\n\r\nClicking save does nothing on mobile.\r\n\
--{{boundary}}\r\nContent-Disposition: form-data; name=\"source_file\"\r\n\r\nslabs/pages/show_home.rs\r\n\
--{{boundary}}\r\nContent-Disposition: form-data; name=\"attachments\"; filename=\"shot.png\"\r\nContent-Type: image/png\r\n\r\n"
)
.as_bytes(),
);
body.extend_from_slice(b"\x89PNG\r\n\x1a\nfake-png-bytes");
body.extend_from_slice(format!("\r\n--{{boundary}}--\r\n").as_bytes());
let req = Request::builder()
.method(Method::POST)
.uri("{route_path}")
.header(
header::COOKIE,
format!("{{SESSION_COOKIE_NAME}}={{}}", cookie.value()),
)
.header(header::ACCEPT, "application/json")
.header(
header::CONTENT_TYPE,
format!("multipart/form-data; boundary={{boundary}}"),
)
.header(
header::REFERER,
"https://app.example.com/settings/profile?token=secret",
)
.header(header::USER_AGENT, "SlabsTest/1.0")
.body(Body::from(body))
.unwrap();
let res = app.request(req).await;
assert_eq!(res.status, StatusCode::CREATED);
let payload: serde_json::Value = serde_json::from_slice(&res.bytes).unwrap();
let incident_id = payload["id"].as_str().unwrap();
assert_eq!(payload["attachments"], 1);
let inc = app.ctx.incidents.get(incident_id).await.unwrap().unwrap();
assert_eq!(inc.kind, "user_bug_report");
assert_eq!(inc.source_file, "slabs/pages/show_home.rs");
assert_eq!(inc.route_pattern.as_deref(), Some("/settings/profile"));
let ctx_val: serde_json::Value = serde_json::from_str(&inc.context_json).unwrap();
assert_eq!(ctx_val["reporter_user_id"], "usr_reporter");
assert_eq!(ctx_val["referer_path"], "/settings/profile");
let blob_id = ctx_val["attachments"][0]["blob_id"].as_str().unwrap();
assert!(app
.ctx
.storage
.get_scoped(blob_id, Some("bug_report"))
.await
.unwrap()
.is_some());
assert!(app
.ctx
.storage
.get_scoped(blob_id, None)
.await
.unwrap()
.is_none());
}}
}}
"#
)
}
fn format_utc_timestamp_secs(epoch_secs: u64) -> String {
let days = epoch_secs / 86_400;
let secs_of_day = epoch_secs % 86_400;
let hour = secs_of_day / 3_600;
let minute = (secs_of_day % 3_600) / 60;
let second = secs_of_day % 60;
let z = days + 719_468;
let era = z / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = y + u64::from(month <= 2);
format!("{year:04}{month:02}{day:02}{hour:02}{minute:02}{second:02}")
}
fn slugify_migration_name(raw: &str) -> Result<String, String> {
let trimmed = raw.trim();
if trimmed.is_empty()
|| !trimmed
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | ' '))
{
return Err(format!(
"invalid migration name `{raw}`: use ASCII letters, digits, underscores, hyphens, or spaces"
));
}
let mut slug = String::new();
let mut prev_underscore = true;
for ch in trimmed.chars() {
if ch.is_ascii_alphanumeric() {
slug.push(ch.to_ascii_lowercase());
prev_underscore = false;
} else if !prev_underscore {
slug.push('_');
prev_underscore = true;
}
}
while slug.ends_with('_') {
slug.pop();
}
if slug.is_empty() {
return Err(format!(
"invalid migration name `{raw}`: must contain at least one letter or digit"
));
}
Ok(slug)
}
fn next_unique_migration_timestamp(
migrations_dir: &Path,
now_secs: u64,
) -> Result<String, std::io::Error> {
let mut existing_prefixes = BTreeSet::new();
if migrations_dir.is_dir() {
for entry in fs::read_dir(migrations_dir)? {
let entry = entry?;
if let Some(file_name) = entry.file_name().to_str() {
if file_name.len() >= 14
&& file_name.as_bytes()[..14].iter().all(u8::is_ascii_digit)
{
existing_prefixes.insert(file_name[..14].to_string());
}
}
}
}
let mut secs = now_secs;
loop {
let ts = format_utc_timestamp_secs(secs);
if !existing_prefixes.contains(&ts) {
return Ok(ts);
}
secs = secs.saturating_add(1);
}
}
fn scaffold_migration(app_dir: &Path, name: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
let slug = slugify_migration_name(name)?;
let migrations_dir = app_dir.join("migrations");
fs::create_dir_all(&migrations_dir)?;
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let timestamp = next_unique_migration_timestamp(&migrations_dir, now_secs)?;
let target = migrations_dir.join(format!("{timestamp}_{slug}.sql"));
let template = format!(
"-- Migration: {slug}\n-- Design for expand-and-contract rollbacks; after applying run `slabs db dump-schema`.\n\n"
);
fs::write(&target, template)?;
Ok(target)
}
fn scaffold_app(name: &str, dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
validate_app_name(name)?;
if dir.exists() && fs::read_dir(dir)?.next().is_some() {
return Err(format!("target directory is not empty: {}", dir.display()).into());
}
fs::create_dir_all(dir.join("src"))?;
fs::create_dir_all(dir.join("slabs/pages"))?;
fs::create_dir_all(dir.join("slabs/pwa"))?;
fs::create_dir_all(dir.join("jobs"))?;
fs::create_dir_all(dir.join("migrations"))?;
fs::create_dir_all(dir.join("assets/styles"))?;
fs::create_dir_all(dir.join(".github/workflows"))?;
fs::create_dir_all(dir.join(".claude/skills/add-slab"))?;
fs::create_dir_all(dir.join(".claude/skills/add-migration"))?;
fs::create_dir_all(dir.join(".claude/skills/review-slab"))?;
fs::create_dir_all(dir.join(".claude/skills/deploy-app"))?;
fs::create_dir_all(dir.join(".claude/skills/fix-incident"))?;
let cargo_toml = format!(
r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = {{ version = "0.8", features = ["ws", "multipart"] }}
axum-extra = {{ version = "0.10", features = ["cookie"] }}
maud = {{ version = "0.27", features = ["axum"] }}
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
slabs-framework = "0.5"
sqlx = {{ version = "0.8", default-features = false, features = ["runtime-tokio", "tls-rustls", "sqlite", "migrate", "chrono", "json", "macros"] }}
tokio = {{ version = "1", features = ["full"] }}
tracing = "0.1"
[build-dependencies]
slabs-build = "0.5"
[lints.rust]
unsafe_code = "forbid"
[lints.clippy]
dbg_macro = "warn"
todo = "warn"
unimplemented = "warn"
await_holding_lock = "deny"
await_holding_refcell_ref = "deny"
"#
);
let build_rs = "fn main() {\n slabs_build::discover();\n}\n";
let lib_rs = format!(
r#"use slabs::SlabsApp;
use sqlx::migrate::Migrator;
slabs::discover_slabs!();
pub static MIGRATOR: Migrator = sqlx::migrate!("./migrations");
pub async fn boot(config: slabs::AppConfig) -> slabs::SlabResult<SlabsApp> {{
let app = SlabsApp::boot(config, &MIGRATOR, collect_slabs(), collect_jobs()).await?;
Ok(app.with_schedules(collect_schedules()))
}}
#[cfg(test)]
pub async fn test_app() -> slabs::test::TestApp {{
slabs::test::TestApp::boot("{name}", &MIGRATOR, collect_slabs(), collect_jobs()).await
}}
"#
);
let pkg_ident = name.replace('-', "_");
let main_rs = format!(
r#"#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {{
slabs::init_tracing();
let config = slabs::AppConfig::from_env("{name}");
let app = {pkg_ident}::boot(config).await?;
app.serve().await?;
Ok(())
}}
"#
);
let show_home_rs = format!(
r#"use axum::extract::State;
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("/", handle)
.name("pages.show_home")
.summary("Render the {name} home page")
}}
async fn handle(State(ctx): State<AppCtx>) -> Markup {{
html::document(
"{name}",
&ctx.assets.stylesheet_urls(),
&ctx.assets.behavior_urls(),
maud! {{
main class="mx-auto max-w-2xl px-6 py-16 space-y-4" {{
h1 class="text-3xl font-bold tracking-tight" {{ "{name}" }}
p class="text-muted-foreground" {{
"Built with Slabs Transaction Scripts, raw SQL, Tailwind v4, Basecoat, HTMX, and Alpine."
}}
}}
}},
)
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn home_page_renders() {{
let app = crate::test_app().await;
let res = app.get("/").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("{name}"));
}}
}}
"#
);
let pwa_manifest_rs = format!(
r##"use axum::{{
extract::State,
http::{{header, HeaderValue, StatusCode}},
response::IntoResponse,
}};
use serde_json::json;
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("/manifest.webmanifest", handle)
.name("pwa.manifest")
.summary("Serve the Progressive Web App manifest")
}}
async fn handle(State(ctx): State<AppCtx>) -> impl IntoResponse {{
let icon_url = ctx.assets.url("icon.svg");
let body = json!({{
"name": "{name}",
"short_name": "{name}",
"start_url": "/",
"display": "standalone",
"background_color": "#1a1b26",
"theme_color": "#D34516",
"icons": [
{{
"src": icon_url,
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any maskable"
}}
]
}})
.to_string();
(
StatusCode::OK,
[(
header::CONTENT_TYPE,
HeaderValue::from_static("application/manifest+json; charset=utf-8"),
)],
body,
)
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn serves_pwa_manifest() {{
let app = crate::test_app().await;
let res = app.get("/manifest.webmanifest").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("\"display\":\"standalone\""));
}}
}}
"##
);
let pwa_service_worker_rs = format!(
r##"use axum::{{
http::{{header, HeaderName, HeaderValue, StatusCode}},
response::IntoResponse,
}};
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("/service-worker.js", handle)
.name("pwa.service_worker")
.summary("Serve the Progressive Web App service worker")
}}
const SW_JS: &str = r#"const CACHE_NAME = "{name}-v1";
self.addEventListener("install", () => {{
self.skipWaiting();
}});
self.addEventListener("activate", (event) => {{
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
)
);
self.clients.claim();
}});
self.addEventListener("fetch", (event) => {{
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith("/assets/")) {{
event.respondWith(
caches.open(CACHE_NAME).then((cache) =>
cache.match(req).then((cached) =>
cached ||
fetch(req).then((res) => {{
if (res.ok) cache.put(req, res.clone());
return res;
}})
)
)
);
return;
}}
if (url.pathname.startsWith("/_slabs/vendor/")) {{
event.respondWith(
caches.open(CACHE_NAME).then((cache) =>
cache.match(req).then((cached) => {{
const network = fetch(req).then((res) => {{
if (res.ok) cache.put(req, res.clone());
return res;
}});
return cached || network;
}})
)
);
return;
}}
if (req.mode === "navigate") {{
event.respondWith(
fetch(req).catch(() =>
new Response("<h1>Offline</h1><p>Reconnect to continue using {name}.</p>", {{
status: 503,
headers: {{ "Content-Type": "text/html; charset=utf-8" }},
}})
)
);
}}
}});
self.addEventListener("push", (event) => {{
let data = {{ title: "{name}", body: "New update", url: "/" }};
if (event.data) {{
try {{
const parsed = event.data.json();
if (parsed && typeof parsed === "object") {{
data = parsed;
}}
}} catch (_err) {{
data = {{ title: "{name}", body: event.data.text() || "New update", url: "/" }};
}}
}}
event.waitUntil(
self.registration.showNotification(data.title || "{name}", {{
body: data.body || "",
data: {{ url: data.url || "/" }},
}})
);
}});
self.addEventListener("notificationclick", (event) => {{
event.notification.close();
const rawTarget = (event.notification.data && event.notification.data.url) || "/";
let safeTarget = "/";
try {{
const resolved = new URL(rawTarget, self.location.origin);
if (resolved.origin === self.location.origin) {{
safeTarget = resolved.pathname + resolved.search + resolved.hash;
}}
}} catch (_err) {{
safeTarget = "/";
}}
event.waitUntil(clients.openWindow(safeTarget));
}});
"#;
async fn handle() -> impl IntoResponse {{
(
StatusCode::OK,
[
(
header::CONTENT_TYPE,
HeaderValue::from_static("application/javascript; charset=utf-8"),
),
(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
(
HeaderName::from_static("service-worker-allowed"),
HeaderValue::from_static("/"),
),
],
SW_JS,
)
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn serves_service_worker() {{
let app = crate::test_app().await;
let res = app.get("/service-worker.js").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("url.origin !== self.location.origin"));
}}
}}
"##
);
let icon_svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 112 112" fill="none">
<defs>
<mask id="slabs-mark-cuts">
<rect x="0" y="0" width="112" height="112" fill="white"/>
<rect x="40" y="0" width="6" height="112" fill="black"/>
<rect x="66" y="0" width="6" height="112" fill="black"/>
</mask>
<path id="slabs-mark-s" d="M26,10 L86,10 C94,10 98,14 98,22 L98,42 L76,42 L76,27 L37,27 L37,46 L84,56 C93,58 98,64 98,73 L98,90 C98,98 94,102 86,102 L26,102 C18,102 14,98 14,90 L14,69 L36,69 L36,85 L76,85 L76,68 L29,58 C20,56 14,50 14,41 L14,22 C14,14 18,10 26,10 Z"/>
</defs>
<g mask="url(#slabs-mark-cuts)">
<use href="#slabs-mark-s" x="-5" y="4" fill="#8C2A0B"/>
<use href="#slabs-mark-s" x="-2.5" y="2" fill="#A6330E"/>
<use href="#slabs-mark-s" x="0" y="0" fill="#D34516"/>
</g>
</svg>
"##;
let dockerfile = format!(
r#"FROM lukemathwalker/cargo-chef:latest-rust-1-slim AS chef
WORKDIR /app
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
ARG TARGETARCH
ARG LITESTREAM_VERSION=v0.3.13
ARG TAILWIND_VERSION=v4.1.4
RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config libssl-dev curl ca-certificates tar gzip \
&& rm -rf /var/lib/apt/lists/* \
&& ARCH="${{TARGETARCH:-amd64}}" \
&& curl -fsSL "https://github.com/benbjohnson/litestream/releases/download/${{LITESTREAM_VERSION}}/litestream-${{LITESTREAM_VERSION}}-linux-${{ARCH}}.tar.gz" \
| tar -xz -C /usr/local/bin litestream \
&& chmod +x /usr/local/bin/litestream \
&& case "${{ARCH}}" in \
amd64) TW_ARCH="x64" ;; \
arm64) TW_ARCH="arm64" ;; \
*) TW_ARCH="${{ARCH}}" ;; \
esac \
&& curl -fsSL "https://github.com/tailwindlabs/tailwindcss/releases/download/${{TAILWIND_VERSION}}/tailwindcss-linux-${{TW_ARCH}}" \
-o /usr/local/bin/tailwindcss \
&& chmod +x /usr/local/bin/tailwindcss
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN mkdir -p /app/assets/styles \
&& /usr/local/bin/tailwindcss -i /app/assets/input.css -o /app/assets/styles/app.css --minify
RUN cargo build --release --locked \
&& strip /app/target/release/{name}
FROM debian:bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd -r -g 10001 slabs \
&& useradd -r -u 10001 -g slabs -m slabs
COPY --from=builder /app/target/release/{name} /usr/local/bin/{name}
COPY --from=builder /usr/local/bin/litestream /usr/local/bin/litestream
COPY --from=builder /app/litestream.yml /etc/litestream.yml
COPY --from=builder /app/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
COPY --from=builder --chown=root:root /app/assets /app/assets
RUN chmod +x /usr/local/bin/docker-entrypoint.sh \
&& chmod -R a-w /app/assets \
&& mkdir -p /data /data/storage \
&& chown -R slabs:slabs /data
# Entrypoint fixes root-owned mounted volumes (Fly.io, Railway, Docker) on boot
# and immediately drops privileges to `slabs` (10001:10001) via `setpriv`.
ARG SLABS_GIT_SHA=""
ENV HOME=/home/slabs
ENV SLABS_ENV=production
ENV SLABS_COOKIE_SECURE=true
ENV SLABS_TRUST_PROXY=true
ENV PORT=3000
ENV DATABASE_URL=sqlite:///data/{name}.db?mode=rwc
ENV SLABS_STORAGE_DIR=/data/storage
ENV SLABS_ASSETS_DIR=/app/assets
ENV SLABS_LOG_FORMAT=json
ENV SLABS_GIT_SHA=${{SLABS_GIT_SHA}}
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 \
CMD curl -fsS "http://127.0.0.1:${{PORT:-3000}}/health/ready" || exit 1
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
"#
);
let entrypoint_sh = format!(
r#"#!/bin/sh
set -eu
DATA_DIR="/data"
STORAGE_DIR="${{SLABS_STORAGE_DIR:-/data/storage}}"
# Fresh persistent volumes on Fly.io, Railway, and Docker hosts mount as root:root.
# Fix ownership once at boot and immediately drop privileges to `slabs` (10001:10001).
if [ "$(id -u)" = "0" ]; then
mkdir -p "$DATA_DIR" "$STORAGE_DIR"
chown -R 10001:10001 "$DATA_DIR" "$STORAGE_DIR"
exec setpriv --reuid=10001 --regid=10001 --clear-groups "$0" "$@"
fi
mkdir -p "$DATA_DIR" "$STORAGE_DIR"
export SLABS_BIND="${{SLABS_BIND:-0.0.0.0:${{PORT:-3000}}}}"
if [ -n "${{LITESTREAM_BUCKET:-}}" ]; then
litestream restore -if-db-not-exists -if-replica-exists -config /etc/litestream.yml "/data/{name}.db"
exec litestream replicate -config /etc/litestream.yml -exec "/usr/local/bin/{name}"
fi
exec /usr/local/bin/{name}
"#
);
let gitignore =
"/target\n.env\n.env.*\n*.db\n*.db-wal\n*.db-shm\nstorage/\nassets/styles/app.css\n";
let dockerignore = ".git\ntarget\n.env\n.env.*\n*.db\n*.db-wal\n*.db-shm\nstorage/\n";
let litestream_yml = format!(
r"dbs:
- path: /data/{name}.db
replicas:
- type: s3
bucket: ${{LITESTREAM_BUCKET}}
path: {name}/db
endpoint: ${{LITESTREAM_ENDPOINT}}
region: ${{LITESTREAM_REGION:-auto}}
"
);
let seeds_sql = "-- Idempotent development seed data applied via `slabs db seed`.\nSELECT 1;\n";
let init_sql = "-- Add your domain tables here. Slabs manages sessions, jobs, mail, cache, blobs, webhooks, idempotency keys, and audit logs automatically.\n";
let input_css = "@import \"tailwindcss\";\n@source \"../slabs\";\n";
let ci_yml = r"name: CI
permissions:
contents: read
on:
push:
branches: [main]
pull_request:
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- uses: taiki-e/install-action@nextest
- name: Check formatting (crate + slabs/ + jobs/)
run: |
cargo fmt --all -- --check
find slabs jobs -name '*.rs' -print0 2>/dev/null | xargs -0 -r rustfmt --edition 2021 --check
- name: Clippy
run: cargo clippy --all-targets -- -D warnings
- name: Tests
run: cargo nextest run
";
let agents_md = format!(
r"# AGENTS.md: {name} (Slabs App)
- One use case is one self-contained slab in `slabs/<feature>/<action>.rs` (auto-discovered at compile time).
- Background jobs live in `jobs/<name>.rs`.
- Read `schema.sql` before writing raw parameterized SQL inside explicit transactions (`ctx.db.begin().await?`).
- Bundled agent skills live in `.claude/skills/` (`add-slab`, `add-migration`, `review-slab`, `deploy-app`, `fix-incident`).
- Run `slabs doctor`, `slabs fmt --check`, and `slabs check --no-docs` before finishing changes.
"
);
fs::write(dir.join("Cargo.toml"), cargo_toml)?;
fs::write(dir.join("build.rs"), build_rs)?;
fs::write(dir.join("src/lib.rs"), lib_rs)?;
fs::write(dir.join("src/main.rs"), main_rs)?;
fs::write(dir.join("slabs/pages/show_home.rs"), show_home_rs)?;
fs::write(dir.join("slabs/pwa/manifest.rs"), pwa_manifest_rs)?;
fs::write(
dir.join("slabs/pwa/service_worker.rs"),
pwa_service_worker_rs,
)?;
fs::write(dir.join("migrations/0001_init.sql"), init_sql)?;
fs::write(dir.join("schema.sql"), init_sql)?;
fs::write(dir.join("seeds.sql"), seeds_sql)?;
fs::write(dir.join("assets/input.css"), input_css)?;
fs::write(dir.join("assets/icon.svg"), icon_svg)?;
fs::write(dir.join("Dockerfile"), dockerfile)?;
let entrypoint_path = dir.join("docker-entrypoint.sh");
fs::write(&entrypoint_path, entrypoint_sh)?;
set_executable_if_unix(&entrypoint_path)?;
fs::write(dir.join(".gitignore"), gitignore)?;
fs::write(dir.join(".dockerignore"), dockerignore)?;
fs::write(dir.join("litestream.yml"), litestream_yml)?;
fs::write(dir.join(".github/workflows/ci.yml"), ci_yml)?;
fs::write(dir.join("AGENTS.md"), agents_md)?;
fs::write(dir.join("CLAUDE.md"), "@AGENTS.md\n")?;
fs::write(dir.join(".claude/skills/add-slab/SKILL.md"), SKILL_ADD_SLAB)?;
fs::write(
dir.join(".claude/skills/add-migration/SKILL.md"),
SKILL_ADD_MIGRATION,
)?;
fs::write(
dir.join(".claude/skills/review-slab/SKILL.md"),
SKILL_REVIEW_SLAB,
)?;
fs::write(
dir.join(".claude/skills/deploy-app/SKILL.md"),
SKILL_DEPLOY_APP,
)?;
fs::write(
dir.join(".claude/skills/fix-incident/SKILL.md"),
SKILL_FIX_INCIDENT,
)?;
Ok(())
}
#[cfg(unix)]
fn set_executable_if_unix(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(path, perms)?;
Ok(())
}
#[cfg(not(unix))]
fn set_executable_if_unix(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn scaffold_deploy(
app_dir: &Path,
app_name: &str,
target: DeployTarget,
force: bool,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
validate_app_name(app_name)?;
let mut created = Vec::new();
match target {
DeployTarget::Kamal => {
let path = app_dir.join("config/deploy.yml");
write_deploy_file(&path, &render_kamal_config(app_name), force)?;
created.push(path);
}
DeployTarget::Fly => {
let path = app_dir.join("fly.toml");
write_deploy_file(&path, &render_fly_config(app_name), force)?;
created.push(path);
}
DeployTarget::Vps => {
let caddy_path = app_dir.join("deploy/Caddyfile");
let service_path = app_dir.join(format!("deploy/{app_name}.service"));
write_deploy_file(&caddy_path, &render_vps_caddyfile(app_name), force)?;
write_deploy_file(&service_path, &render_vps_systemd_unit(app_name), force)?;
created.push(caddy_path);
created.push(service_path);
}
}
Ok(created)
}
fn write_deploy_file(
path: &Path,
content: &str,
force: bool,
) -> Result<(), Box<dyn std::error::Error>> {
if path.exists() && !force {
return Err(format!(
"deployment file already exists (pass `--force` to overwrite): {}",
path.display()
)
.into());
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, content)?;
Ok(())
}
fn render_kamal_config(app: &str) -> String {
format!(
r#"# Kamal 2 deployment configuration for `{app}` (SQLite).
#
# Rollbacks:
# Kamal tags images with the git SHA by default. Roll back in seconds with:
# kamal rollback <version>
#
# Zero-downtime single-writer SQLite rollout:
# Single-volume SQLite + Litestream runs one active writer at a time. Keep
# `boot.limit: 1` and `proxy.buffering` enabled so kamal-proxy holds incoming
# requests with zero dropped connections while the old container drains on
# SIGTERM (`drain_timeout: 20`), runs `PRAGMA wal_checkpoint(TRUNCATE)`, and
# the replacement container passes `/health/ready`.
service: {app}
image: your-registry/{app}
servers:
web:
- 192.0.2.10
proxy:
ssl: true
host: {app}.example.com
app_port: 3000
buffering:
requests: true
responses: true
healthcheck:
path: /health/ready
interval: 2
timeout: 3
drain_timeout: 20
boot:
limit: 1
wait: 5
volumes:
- /var/lib/{app}/data:/data
env:
clear:
SLABS_ENV: production
SLABS_COOKIE_SECURE: "true"
SLABS_TRUST_PROXY: "true"
SLABS_BIND: 0.0.0.0:3000
DATABASE_URL: sqlite:///data/{app}.db?mode=rwc
SLABS_STORAGE_DIR: /data/storage
SLABS_LOG_FORMAT: json
secret:
- SLABS_SECRET_KEY
- LITESTREAM_BUCKET
- LITESTREAM_ENDPOINT
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
"#
)
}
fn render_fly_config(app: &str) -> String {
let volume_source = format!("{}_data", app.replace('-', "_"));
format!(
r#"# Fly.io deployment configuration for `{app}` (SQLite).
#
# Set required secrets before deploying:
# fly secrets set SLABS_SECRET_KEY="$(openssl rand -hex 32)"
#
# On SIGTERM (`kill_timeout = "20s"`), Slabs drains in-flight requests and runs
# `PRAGMA wal_checkpoint(TRUNCATE)` before exiting so the replacement machine
# mounts `/data` cleanly.
#
# Roll back to a previous release with:
# fly releases rollback <version>
app = "{app}"
primary_region = "iad"
kill_signal = "SIGTERM"
kill_timeout = "20s"
[deploy]
# Single-volume SQLite allows only one active writer at a time.
strategy = "immediate"
[env]
SLABS_ENV = "production"
SLABS_COOKIE_SECURE = "true"
SLABS_TRUST_PROXY = "true"
SLABS_BIND = "0.0.0.0:3000"
DATABASE_URL = "sqlite:///data/{app}.db?mode=rwc"
SLABS_STORAGE_DIR = "/data/storage"
SLABS_LOG_FORMAT = "json"
[[mounts]]
source = "{volume_source}"
destination = "/data"
[http_service]
internal_port = 3000
force_https = true
auto_stop_machines = "off"
auto_start_machines = true
min_machines_running = 1
[[http_service.checks]]
grace_period = "10s"
interval = "15s"
method = "GET"
timeout = "3s"
path = "/health/ready"
"#
)
}
fn render_vps_caddyfile(app: &str) -> String {
format!(
r"# Caddy auto-HTTPS reverse proxy configuration for `{app}` (SQLite).
# Copy to `/etc/caddy/Caddyfile` and reload with `systemctl reload caddy`.
{app}.example.com {{
encode zstd gzip
reverse_proxy 127.0.0.1:3000 {{
health_uri /health/ready
health_interval 5s
health_timeout 3s
header_up X-Forwarded-Proto {{scheme}}
}}
}}
"
)
}
fn render_vps_systemd_unit(app: &str) -> String {
format!(
r"# Hardened systemd unit for `{app}` (SQLite).
# Copy to `/etc/systemd/system/{app}.service`, then run:
# systemctl daemon-reload && systemctl enable --now {app}
#
# On SIGTERM (`TimeoutStopSec=20s`), Slabs drains active requests and runs
# `PRAGMA wal_checkpoint(TRUNCATE)` on `/data/{app}.db` before exiting.
#
# Atomic deploy / fast rollback:
# ln -sfn /opt/{app}/releases/<git-sha> /opt/{app}/current
# systemctl restart {app}
[Unit]
Description={app} (Slabs web application - SQLite)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=slabs
Group=slabs
WorkingDirectory=/opt/{app}/current
EnvironmentFile=/etc/{app}/env
ExecStart=/opt/{app}/current/{app}
KillSignal=SIGTERM
TimeoutStopSec=20s
Restart=on-failure
RestartSec=2s
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/data
[Install]
WantedBy=multi-user.target
"
)
}
async fn run_fmt(app_dir: &Path, check: bool) -> Result<(), Box<dyn std::error::Error>> {
let manifest_path = app_dir.join("Cargo.toml");
let mut cargo_cmd = Command::new("cargo");
cargo_cmd.arg("fmt");
if manifest_path.exists() {
cargo_cmd.arg("--manifest-path").arg(&manifest_path);
}
if check {
cargo_cmd.args(["--", "--check"]);
}
let cargo_status = cargo_cmd.status().await?;
if !cargo_status.success() {
return Err(format!("cargo fmt failed with status {cargo_status}").into());
}
let discovered_files = collect_workspace_discovered_rs_files(app_dir)?;
if !discovered_files.is_empty() {
let mut rustfmt_cmd = Command::new("rustfmt");
rustfmt_cmd.args(["--edition", "2021"]);
if check {
rustfmt_cmd.arg("--check");
}
rustfmt_cmd.args(&discovered_files);
let rustfmt_status = rustfmt_cmd.status().await?;
if !rustfmt_status.success() {
return Err(
format!("rustfmt failed on slabs/jobs files with status {rustfmt_status}").into(),
);
}
}
if check {
println!(
"Formatting OK ({} discovered slab/job files checked)",
discovered_files.len()
);
} else {
println!(
"Formatted crate + {} discovered slab/job files",
discovered_files.len()
);
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExplainMode {
Off,
Warn,
Strict,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum CheckTarget {
Full,
Changed { base: Option<String> },
Slab(String),
}
#[derive(Debug, Clone)]
struct CheckOptions {
workspace: bool,
no_docs: bool,
target: CheckTarget,
explain: ExplainMode,
verbose: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SelectedSlab {
feature: String,
action: String,
file: PathBuf,
crate_dir: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ChangedSelection {
NoChanges,
OnlySlabs(Vec<SelectedSlab>),
SharedFilesChanged(Vec<PathBuf>),
}
fn parse_slab_selector(spec: &str) -> Result<(String, String), String> {
let trimmed = spec.trim().trim_end_matches(".rs");
let mut parts = trimmed.split('/');
let Some(feature) = parts.next() else {
return Err(format!(
"invalid `--slab` value `{spec}`: expected `<feature>/<action>`"
));
};
let Some(action) = parts.next() else {
return Err(format!(
"invalid `--slab` value `{spec}`: expected `<feature>/<action>`"
));
};
if parts.next().is_some() {
return Err(format!(
"invalid `--slab` value `{spec}`: expected `<feature>/<action>`"
));
}
validate_rust_ident(feature)?;
validate_rust_ident(action)?;
Ok((feature.to_string(), action.to_string()))
}
fn build_nextest_slab_filter(slabs: &[(String, String)]) -> String {
let mut unique: BTreeSet<(&str, &str)> = BTreeSet::new();
for (feature, action) in slabs {
unique.insert((feature.as_str(), action.as_str()));
}
unique
.into_iter()
.map(|(f, a)| format!("test(discovered_slabs::{f}::{a})"))
.collect::<Vec<_>>()
.join(" | ")
}
fn validate_git_ref(git_ref: &str) -> Result<(), String> {
let trimmed = git_ref.trim();
if trimmed.is_empty()
|| trimmed.starts_with('-')
|| trimmed.chars().any(|c| c.is_whitespace() || c.is_control())
{
return Err(format!("invalid git ref `{git_ref}`"));
}
Ok(())
}
fn extract_slab_from_path(path: &Path) -> Option<(String, String, PathBuf)> {
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
return None;
}
let stem = path.file_stem().and_then(|s| s.to_str())?;
if stem == "mod" || stem.starts_with('_') || validate_rust_ident(stem).is_err() {
return None;
}
let feature_dir = path.parent()?;
let feature = feature_dir.file_name().and_then(|s| s.to_str())?;
if feature.starts_with('_') || feature.starts_with('.') || validate_rust_ident(feature).is_err()
{
return None;
}
let slabs_dir = feature_dir.parent()?;
if slabs_dir.file_name().and_then(|s| s.to_str()) != Some("slabs") {
return None;
}
let crate_dir = slabs_dir.parent()?.to_path_buf();
Some((feature.to_string(), stem.to_string(), crate_dir))
}
fn locate_single_slab(
app_dir: &Path,
is_workspace: bool,
feature: &str,
action: &str,
) -> Result<SelectedSlab, Box<dyn std::error::Error>> {
let direct = app_dir
.join("slabs")
.join(feature)
.join(format!("{action}.rs"));
if direct.is_file() {
return Ok(SelectedSlab {
feature: feature.to_string(),
action: action.to_string(),
file: direct,
crate_dir: app_dir.to_path_buf(),
});
}
if is_workspace {
for member in discover_workspace_member_dirs(app_dir) {
let candidate = member
.join("slabs")
.join(feature)
.join(format!("{action}.rs"));
if candidate.is_file() {
return Ok(SelectedSlab {
feature: feature.to_string(),
action: action.to_string(),
file: candidate,
crate_dir: member,
});
}
}
}
Err(format!("slab not found: slabs/{feature}/{action}.rs").into())
}
fn parse_git_porcelain_paths(output: &str) -> Vec<PathBuf> {
let mut paths = Vec::new();
for line in output.lines() {
if line.len() < 4 {
continue;
}
let raw = &line[3..];
let target = raw.rsplit(" -> ").next().unwrap_or(raw).trim();
let unquoted = target
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.unwrap_or(target);
if !unquoted.is_empty() {
paths.push(PathBuf::from(unquoted));
}
}
paths
}
fn collect_git_changed_paths(
app_dir: &Path,
base: Option<&str>,
) -> Result<(PathBuf, Vec<PathBuf>), Box<dyn std::error::Error>> {
let top_out = std::process::Command::new("git")
.arg("-C")
.arg(app_dir)
.args(["rev-parse", "--show-toplevel"])
.output()?;
if !top_out.status.success() {
return Err("`slabs check --changed` requires a git repository".into());
}
let repo_root = PathBuf::from(String::from_utf8_lossy(&top_out.stdout).trim());
let status_out = std::process::Command::new("git")
.arg("-C")
.arg(app_dir)
.args(["status", "--porcelain"])
.output()?;
if !status_out.status.success() {
return Err("`git status --porcelain` failed".into());
}
let mut changed: BTreeSet<PathBuf> =
parse_git_porcelain_paths(&String::from_utf8_lossy(&status_out.stdout))
.into_iter()
.collect();
if let Some(git_ref) = base {
validate_git_ref(git_ref)?;
let diff_out = std::process::Command::new("git")
.arg("-C")
.arg(app_dir)
.args(["diff", "--name-only", git_ref])
.output()?;
if !diff_out.status.success() {
return Err(format!(
"`git diff --name-only {git_ref}` failed: {}",
String::from_utf8_lossy(&diff_out.stderr).trim()
)
.into());
}
for line in String::from_utf8_lossy(&diff_out.stdout).lines() {
let trimmed = line.trim();
if !trimmed.is_empty() {
changed.insert(PathBuf::from(trimmed));
}
}
}
Ok((repo_root, changed.into_iter().collect()))
}
fn classify_changed_paths(repo_root: &Path, rel_paths: &[PathBuf]) -> ChangedSelection {
if rel_paths.is_empty() {
return ChangedSelection::NoChanges;
}
let mut slabs = Vec::new();
let mut shared = Vec::new();
for rel in rel_paths {
let abs = repo_root.join(rel);
if abs.is_file() {
if let Some((feature, action, crate_dir)) = extract_slab_from_path(&abs) {
slabs.push(SelectedSlab {
feature,
action,
file: abs,
crate_dir,
});
continue;
}
}
shared.push(rel.clone());
}
if !shared.is_empty() {
ChangedSelection::SharedFilesChanged(shared)
} else if slabs.is_empty() {
ChangedSelection::NoChanges
} else {
slabs.sort_by(|a, b| a.file.cmp(&b.file));
slabs.dedup_by(|a, b| a.file == b.file);
ChangedSelection::OnlySlabs(slabs)
}
}
async fn has_cargo_nextest() -> bool {
Command::new("cargo")
.args(["nextest", "--version"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await
.is_ok_and(|s| s.success())
}
fn slab_source_has_colocated_test(content: &str) -> bool {
let code_lines = strip_rust_file_code_lines(content);
let has_cfg_test = code_lines.iter().any(|l| l.contains("#[cfg(test)]"));
if !has_cfg_test {
return false;
}
let test_lines = compute_cfg_test_lines(content);
code_lines
.iter()
.zip(test_lines.iter())
.any(|(code, &in_test)| {
in_test
&& (code.contains("#[test]")
|| code.contains("#[tokio::test]")
|| code.contains("#[tokio::test("))
})
}
fn find_untested_selected_slabs(slabs: &[SelectedSlab]) -> Result<Vec<PathBuf>, std::io::Error> {
let mut untested = Vec::new();
for slab in slabs {
let content = fs::read_to_string(&slab.file)?;
if !slab_source_has_colocated_test(&content) {
untested.push(slab.file.clone());
}
}
Ok(untested)
}
async fn run_selective_slabs_check(
app_dir: &Path,
is_workspace: bool,
slabs: &[SelectedSlab],
explain: ExplainMode,
verbose: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let manifest_path = app_dir.join("Cargo.toml");
let files: Vec<PathBuf> = slabs.iter().map(|s| s.file.clone()).collect();
let run_sql = has_sql_schema(app_dir, &files);
let total_steps = 3 + usize::from(run_sql) + usize::from(explain != ExplainMode::Off);
let mut step = 1usize;
println!(
"[{step}/{total_steps}] Checking formatting on {} slab file(s)...",
files.len()
);
let mut rustfmt_cmd = Command::new("rustfmt");
rustfmt_cmd
.args(["--edition", "2021", "--check"])
.args(&files);
run_checked_command(&mut rustfmt_cmd, "rustfmt --edition 2021 --check").await?;
step += 1;
println!(
"[{step}/{total_steps}] [security] Scanning {} slab file(s)...",
files.len()
);
let mut report = SecurityReport::default();
for slab in slabs {
let pkg_name = infer_package_name_raw(&slab.crate_dir.join("Cargo.toml"));
scan_rust_file(
&slab.file,
FileArea::Slabs,
pkg_name.as_deref(),
&mut report,
)?;
}
print_security_report(&report, verbose);
if report.error_count() > 0 {
return Err(format!(
"[security] static analyzer failed with {} error(s) and {} warning(s)",
report.error_count(),
report.warning_count()
)
.into());
}
step += 1;
if run_sql {
println!("[{step}/{total_steps}] [sql] Validating static SQL queries against schema...");
run_sql_schema_check(app_dir, &files).await?;
step += 1;
}
if explain != ExplainMode::Off {
println!("[{step}/{total_steps}] [explain] Checking SQLite query plans...");
run_explain_check(app_dir, &files, explain == ExplainMode::Strict).await?;
step += 1;
}
let untested = find_untested_selected_slabs(slabs)?;
if !untested.is_empty() {
let listed = untested
.iter()
.map(|p| format!(" - {}", p.display()))
.collect::<Vec<_>>()
.join("\n");
return Err(format!(
"selective check failed: {} targeted slab(s) lack a co-located test (`#[cfg(test)]` with at least one `#[test]` or `#[tokio::test]`):\n{listed}",
untested.len()
)
.into());
}
let pairs: Vec<(String, String)> = slabs
.iter()
.map(|s| (s.feature.clone(), s.action.clone()))
.collect();
let filter_expr = build_nextest_slab_filter(&pairs);
let mut pkg_names: BTreeSet<String> = BTreeSet::new();
for slab in slabs {
if let Some(pkg) = infer_package_name_raw(&slab.crate_dir.join("Cargo.toml")) {
pkg_names.insert(pkg);
}
}
if has_cargo_nextest().await {
println!("[{step}/{total_steps}] Running targeted nextest: `{filter_expr}`...");
let mut test_cmd = Command::new("cargo");
test_cmd.args(["nextest", "run", "--no-tests=fail"]);
if manifest_path.exists() {
test_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
if pkg_names.len() == 1 {
if let Some(pkg) = pkg_names.iter().next() {
test_cmd.args(["-p", pkg]);
}
} else {
test_cmd.arg("--workspace");
}
}
test_cmd.args(["-E", &filter_expr]);
run_checked_command(&mut test_cmd, "cargo nextest run").await?;
} else {
println!(
"[{step}/{total_steps}] Running targeted cargo test for {} slab(s)...",
pairs.len()
);
for (feature, action) in &pairs {
let mut test_cmd = Command::new("cargo");
test_cmd.arg("test");
if manifest_path.exists() {
test_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
if pkg_names.len() == 1 {
if let Some(pkg) = pkg_names.iter().next() {
test_cmd.args(["-p", pkg]);
}
} else {
test_cmd.arg("--workspace");
}
}
test_cmd.arg(format!("discovered_slabs::{feature}::{action}"));
run_checked_command(&mut test_cmd, "cargo test").await?;
}
}
println!(
"Selective verification passed ({} slab(s) checked).",
slabs.len()
);
Ok(())
}
async fn run_check(app_dir: &Path, opts: &CheckOptions) -> Result<(), Box<dyn std::error::Error>> {
let manifest_path = app_dir.join("Cargo.toml");
let is_workspace = opts.workspace || manifest_is_workspace(&manifest_path);
match &opts.target {
CheckTarget::Slab(spec) => {
let (feature, action) = parse_slab_selector(spec)?;
let selected = locate_single_slab(app_dir, is_workspace, &feature, &action)?;
return run_selective_slabs_check(
app_dir,
is_workspace,
&[selected],
opts.explain,
opts.verbose,
)
.await;
}
CheckTarget::Changed { base } => {
let (repo_root, rel_paths) = collect_git_changed_paths(app_dir, base.as_deref())?;
match classify_changed_paths(&repo_root, &rel_paths) {
ChangedSelection::NoChanges => {
println!("[check --changed] No modified files detected; nothing to verify.");
return Ok(());
}
ChangedSelection::OnlySlabs(slabs) => {
println!(
"[check --changed] Only {} slab file(s) changed; running selective verification.",
slabs.len()
);
return run_selective_slabs_check(
app_dir,
is_workspace,
&slabs,
opts.explain,
opts.verbose,
)
.await;
}
ChangedSelection::SharedFilesChanged(shared) => {
let preview: Vec<String> = shared
.iter()
.take(5)
.map(|p| p.display().to_string())
.collect();
let suffix = if shared.len() > 5 {
format!(" (+{} more)", shared.len() - 5)
} else {
String::new()
};
println!(
"[check --changed] Shared file(s) changed ({}{suffix}); running full check suite.",
preview.join(", ")
);
}
}
}
CheckTarget::Full => {}
}
let discovered_files = collect_workspace_discovered_rs_files(app_dir)?;
let run_sql = has_sql_schema(app_dir, &discovered_files);
let extra_sql = usize::from(run_sql);
let extra_explain = usize::from(opts.explain != ExplainMode::Off);
let total_steps = (if opts.no_docs { 4 } else { 6 }) + extra_sql + extra_explain;
let mut step = 1usize;
println!("[{step}/{total_steps}] Checking formatting...");
if is_workspace {
let mut fmt_cmd = Command::new("cargo");
fmt_cmd.args(["fmt", "--all"]);
if manifest_path.exists() {
fmt_cmd.arg("--manifest-path").arg(&manifest_path);
}
fmt_cmd.args(["--", "--check"]);
run_checked_command(&mut fmt_cmd, "cargo fmt --all -- --check").await?;
if !discovered_files.is_empty() {
let mut rustfmt_cmd = Command::new("rustfmt");
rustfmt_cmd
.args(["--edition", "2021", "--check"])
.args(&discovered_files);
run_checked_command(&mut rustfmt_cmd, "rustfmt on discovered slabs/jobs").await?;
}
} else {
run_fmt(app_dir, true).await?;
}
step += 1;
println!("[{step}/{total_steps}] [security] Running static security analyzer...");
let report = scan_security(app_dir, is_workspace)?;
print_security_report(&report, opts.verbose);
if report.error_count() > 0 {
return Err(format!(
"[security] static analyzer failed with {} error(s) and {} warning(s)",
report.error_count(),
report.warning_count()
)
.into());
}
step += 1;
if run_sql {
println!("[{step}/{total_steps}] [sql] Validating static SQL queries against schema...");
run_sql_schema_check(app_dir, &discovered_files).await?;
step += 1;
}
if opts.explain != ExplainMode::Off {
println!("[{step}/{total_steps}] [explain] Checking SQLite query plans...");
run_explain_check(
app_dir,
&discovered_files,
opts.explain == ExplainMode::Strict,
)
.await?;
step += 1;
}
println!("[{step}/{total_steps}] Running clippy...");
let mut clippy_cmd = Command::new("cargo");
clippy_cmd.arg("clippy");
if manifest_path.exists() {
clippy_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
clippy_cmd.arg("--workspace");
}
clippy_cmd.args(["--all-targets", "--", "-D", "warnings"]);
run_checked_command(&mut clippy_cmd, "cargo clippy").await?;
step += 1;
if !opts.no_docs {
println!("[{step}/{total_steps}] Building rustdoc...");
let mut doc_cmd = Command::new("cargo");
doc_cmd.arg("doc").env("RUSTDOCFLAGS", "-D warnings");
if manifest_path.exists() {
doc_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
doc_cmd.arg("--workspace");
}
doc_cmd.arg("--no-deps");
run_checked_command(&mut doc_cmd, "cargo doc").await?;
step += 1;
println!("[{step}/{total_steps}] Running doctests...");
let mut doctest_cmd = Command::new("cargo");
doctest_cmd.args(["test", "--doc"]);
if manifest_path.exists() {
doctest_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
doctest_cmd.arg("--workspace");
}
run_checked_command(&mut doctest_cmd, "cargo test --doc").await?;
step += 1;
}
if has_cargo_nextest().await {
println!("[{step}/{total_steps}] Running tests with cargo-nextest...");
let mut test_cmd = Command::new("cargo");
test_cmd.args(["nextest", "run"]);
if manifest_path.exists() {
test_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
test_cmd.arg("--workspace");
}
run_checked_command(&mut test_cmd, "cargo nextest run").await?;
} else {
println!("[{step}/{total_steps}] Running tests with cargo test...");
let mut test_cmd = Command::new("cargo");
test_cmd.arg("test");
if manifest_path.exists() {
test_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
test_cmd.arg("--workspace");
}
run_checked_command(&mut test_cmd, "cargo test").await?;
}
println!("All {total_steps} checks passed.");
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ExtractedSqlQuery {
line: usize,
sql: String,
allow_scan: bool,
allow_sql: bool,
chained_binds: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SqlSchemaFinding {
file: PathBuf,
line: usize,
error: String,
query_snippet: String,
}
#[derive(Debug, Default)]
struct SqlSchemaReport {
queries_checked: usize,
files_checked: usize,
findings: Vec<SqlSchemaFinding>,
schema_drift: Vec<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ExplainFinding {
file: PathBuf,
line: usize,
plan_detail: String,
query_snippet: String,
index_hint: String,
}
#[derive(Debug, Default)]
struct ExplainReport {
queries_checked: usize,
files_checked: usize,
findings: Vec<ExplainFinding>,
}
fn compute_cfg_test_lines(content: &str) -> Vec<bool> {
let code_lines = strip_rust_file_code_lines(content);
let mut in_test = Vec::with_capacity(code_lines.len());
let mut in_cfg_test = false;
let mut pending_cfg_test = false;
let mut test_brace_depth: i32 = 0;
for code in &code_lines {
if code.contains("#[cfg(test)]") && !in_cfg_test {
pending_cfg_test = true;
}
if pending_cfg_test {
let (opens, closes, saw_semi) = count_braces_and_semi(code);
if opens > 0 {
in_cfg_test = true;
pending_cfg_test = false;
test_brace_depth = opens - closes;
if test_brace_depth <= 0 {
in_cfg_test = false;
test_brace_depth = 0;
}
} else if saw_semi {
pending_cfg_test = false;
}
in_test.push(true);
continue;
}
if in_cfg_test {
in_test.push(true);
let (opens, closes, _) = count_braces_and_semi(code);
test_brace_depth += opens - closes;
if test_brace_depth <= 0 {
in_cfg_test = false;
test_brace_depth = 0;
}
} else {
in_test.push(false);
}
}
in_test
}
fn parse_rust_string_literal(chars: &[char], start: usize) -> Option<(String, usize)> {
if start >= chars.len() {
return None;
}
if chars[start] == 'r' {
let mut hashes = 0usize;
let mut j = start + 1;
while j < chars.len() && chars[j] == '#' {
hashes += 1;
j += 1;
}
if j < chars.len() && chars[j] == '"' {
let mut out = String::new();
let mut k = j + 1;
while k < chars.len() {
if chars[k] == '"' {
let mut matched = 0usize;
while matched < hashes
&& k + 1 + matched < chars.len()
&& chars[k + 1 + matched] == '#'
{
matched += 1;
}
if matched == hashes {
return Some((out, k + 1 + hashes));
}
}
out.push(chars[k]);
k += 1;
}
return None;
}
}
if chars[start] != '"' {
return None;
}
let mut out = String::new();
let mut i = start + 1;
while i < chars.len() {
let ch = chars[i];
if ch == '\\' {
i += 1;
if i >= chars.len() {
return None;
}
match chars[i] {
'n' => out.push('\n'),
'r' => out.push('\r'),
't' => out.push('\t'),
'\\' => out.push('\\'),
'"' => out.push('"'),
'\'' => out.push('\''),
'0' => out.push('\0'),
'\n' => {
while i + 1 < chars.len() && matches!(chars[i + 1], ' ' | '\t') {
i += 1;
}
}
'\r' => {
if i + 1 < chars.len() && chars[i + 1] == '\n' {
i += 1;
}
while i + 1 < chars.len() && matches!(chars[i + 1], ' ' | '\t') {
i += 1;
}
}
other => out.push(other),
}
i += 1;
continue;
}
if ch == '"' {
return Some((out, i + 1));
}
out.push(ch);
i += 1;
}
None
}
fn skip_rust_ws_and_comments(chars: &[char], mut i: usize) -> usize {
while i < chars.len() {
if chars[i].is_whitespace() {
i += 1;
} else if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
i += 2;
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
} else if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
let mut depth = 1usize;
i += 2;
while i < chars.len() && depth > 0 {
if chars[i] == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
depth += 1;
i += 2;
} else if chars[i] == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
depth -= 1;
i += 2;
} else {
i += 1;
}
}
} else {
break;
}
}
i
}
fn skip_turbofish(chars: &[char], start: usize) -> usize {
let i = skip_rust_ws_and_comments(chars, start);
if i + 2 >= chars.len() || chars[i] != ':' || chars[i + 1] != ':' || chars[i + 2] != '<' {
return start;
}
let mut j = i + 3;
let mut depth = 1usize;
while j < chars.len() && depth > 0 {
match chars[j] {
'<' => depth += 1,
'>' => depth -= 1,
_ => {}
}
j += 1;
}
j
}
fn skip_first_macro_arg_to_comma(chars: &[char], mut i: usize) -> Option<usize> {
let mut paren = 0usize;
let mut bracket = 0usize;
let mut brace = 0usize;
let mut angle = 0usize;
while i < chars.len() {
match chars[i] {
',' if paren == 0 && bracket == 0 && brace == 0 && angle == 0 => {
return Some(i + 1);
}
')' if paren == 0 => return None,
'(' => paren += 1,
')' => paren = paren.saturating_sub(1),
'[' => bracket += 1,
']' => bracket = bracket.saturating_sub(1),
'{' => brace += 1,
'}' => brace = brace.saturating_sub(1),
'<' => angle += 1,
'>' => angle = angle.saturating_sub(1),
_ => {}
}
i += 1;
}
None
}
fn chars_match_prefix(chars: &[char], pos: usize, pattern: &str) -> bool {
let pat_chars: Vec<char> = pattern.chars().collect();
if pos + pat_chars.len() > chars.len() {
return false;
}
chars[pos..pos + pat_chars.len()] == pat_chars[..]
}
fn line_has_marker(lines: &[&str], line_no_1based: usize, marker: &str) -> bool {
let idx = line_no_1based.saturating_sub(1);
let here = lines.get(idx).is_some_and(|l| l.contains(marker));
let prev = idx > 0 && lines.get(idx - 1).is_some_and(|l| l.contains(marker));
here || prev
}
fn line_has_allow_scan(lines: &[&str], line_no_1based: usize) -> bool {
line_has_marker(lines, line_no_1based, "// slabs:allow-scan:")
}
fn skip_balanced_parens(chars: &[char], open_idx: usize) -> Option<usize> {
if open_idx >= chars.len() || chars[open_idx] != '(' {
return None;
}
let mut i = open_idx + 1;
let mut depth = 1usize;
let mut block_comment_depth = 0usize;
let mut in_string = false;
let mut string_escaped = false;
let mut raw_string_hashes: Option<usize> = None;
while i < chars.len() && depth > 0 {
let ch = chars[i];
if block_comment_depth > 0 {
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth += 1;
i += 2;
} else if ch == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
block_comment_depth -= 1;
i += 2;
} else {
i += 1;
}
continue;
}
if let Some(hashes) = raw_string_hashes {
if ch == '"' {
let mut matched = 0usize;
while matched < hashes
&& i + 1 + matched < chars.len()
&& chars[i + 1 + matched] == '#'
{
matched += 1;
}
if matched == hashes {
raw_string_hashes = None;
i += 1 + hashes;
continue;
}
}
i += 1;
continue;
}
if in_string {
if string_escaped {
string_escaped = false;
} else if ch == '\\' {
string_escaped = true;
} else if ch == '"' {
in_string = false;
}
i += 1;
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth = 1;
i += 2;
continue;
}
if ch == '\'' {
if i + 2 < chars.len() && chars[i + 1] == '\\' {
if let Some(end) = chars[i + 2..].iter().position(|&c| c == '\'') {
if end <= 6 {
i += end + 3;
continue;
}
}
} else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\n' {
i += 3;
continue;
}
}
if ch == 'r'
&& (i == 0
|| (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_')
|| (chars[i - 1] == 'b'
&& (i == 1 || (!chars[i - 2].is_alphanumeric() && chars[i - 2] != '_'))))
{
let mut hashes = 0usize;
let mut j = i + 1;
while j < chars.len() && chars[j] == '#' {
hashes += 1;
j += 1;
}
if j < chars.len() && chars[j] == '"' {
raw_string_hashes = Some(hashes);
i = j + 1;
continue;
}
}
if ch == '"' {
in_string = true;
i += 1;
continue;
}
match ch {
'(' => depth += 1,
')' => depth -= 1,
_ => {}
}
i += 1;
}
if depth == 0 {
Some(i)
} else {
None
}
}
fn count_sql_placeholders(sql: &str) -> Option<usize> {
let chars: Vec<char> = sql.chars().collect();
let mut i = 0usize;
let mut positional_count = 0usize;
let mut max_numbered: Option<usize> = None;
while i < chars.len() {
let ch = chars[i];
if ch == '\'' {
i += 1;
while i < chars.len() {
if chars[i] == '\'' {
if i + 1 < chars.len() && chars[i + 1] == '\'' {
i += 2;
continue;
}
i += 1;
break;
}
i += 1;
}
continue;
}
if ch == '"' {
i += 1;
while i < chars.len() {
if chars[i] == '"' {
if i + 1 < chars.len() && chars[i + 1] == '"' {
i += 2;
continue;
}
i += 1;
break;
}
i += 1;
}
continue;
}
if ch == '`' {
i += 1;
while i < chars.len() {
if chars[i] == '`' {
if i + 1 < chars.len() && chars[i + 1] == '`' {
i += 2;
continue;
}
i += 1;
break;
}
i += 1;
}
continue;
}
if ch == '-' && i + 1 < chars.len() && chars[i + 1] == '-' {
i += 2;
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
i += 2;
while i < chars.len() {
if chars[i] == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
i += 2;
break;
}
i += 1;
}
continue;
}
if matches!(ch, ':' | '@' | '$') {
if ch == ':' && i + 1 < chars.len() && chars[i + 1] == ':' {
i += 2;
continue;
}
if i + 1 < chars.len()
&& (chars[i + 1].is_ascii_alphabetic()
|| chars[i + 1] == '_'
|| (ch == '$' && chars[i + 1].is_ascii_digit()))
{
return None;
}
i += 1;
continue;
}
if ch == '?' {
let mut j = i + 1;
while j < chars.len() && chars[j].is_ascii_digit() {
j += 1;
}
if j > i + 1 {
let digits: String = chars[i + 1..j].iter().collect();
let idx = digits.parse::<usize>().ok()?;
if idx == 0 {
return None;
}
max_numbered = Some(max_numbered.map_or(idx, |m| m.max(idx)));
i = j;
} else {
positional_count += 1;
i += 1;
}
continue;
}
i += 1;
}
match (max_numbered, positional_count) {
(Some(_), n) if n > 0 => None,
(Some(max_idx), 0) => Some(max_idx),
(None, count) => Some(count),
_ => None,
}
}
fn count_chained_binds(chars: &[char], query_call_end_idx: usize) -> Option<usize> {
let mut pos = query_call_end_idx;
let mut bind_count = 0usize;
loop {
pos = skip_rust_ws_and_comments(chars, pos);
if pos >= chars.len() || chars[pos] != '.' {
return None;
}
pos = skip_rust_ws_and_comments(chars, pos + 1);
let ident_start = pos;
while pos < chars.len() && (chars[pos].is_ascii_alphanumeric() || chars[pos] == '_') {
pos += 1;
}
if pos == ident_start {
return None;
}
let method: String = chars[ident_start..pos].iter().collect();
if matches!(
method.as_str(),
"if" | "match" | "for" | "while" | "bind_all" | "bind_with"
) {
return None;
}
pos = skip_turbofish(chars, pos);
pos = skip_rust_ws_and_comments(chars, pos);
if pos >= chars.len() || chars[pos] != '(' {
return None;
}
pos = skip_balanced_parens(chars, pos)?;
if method == "bind" {
bind_count += 1;
} else if matches!(
method.as_str(),
"fetch_one" | "fetch_optional" | "fetch_all" | "fetch" | "fetch_many" | "execute"
) {
return Some(bind_count);
}
}
}
fn line_has_allow_sql(lines: &[&str], line_no_1based: usize) -> bool {
line_has_marker(lines, line_no_1based, "// slabs:allow-sql:")
}
fn extract_sql_queries_from_source(
content: &str,
include_builders: bool,
) -> Vec<ExtractedSqlQuery> {
let lines: Vec<&str> = content.lines().collect();
let test_lines = compute_cfg_test_lines(content);
let chars: Vec<char> = content.chars().collect();
let mut out = Vec::new();
let mut i = 0usize;
let mut line_no = 1usize;
let mut block_comment_depth = 0usize;
let mut in_string = false;
let mut string_escaped = false;
let mut raw_string_hashes: Option<usize> = None;
while i < chars.len() {
let ch = chars[i];
if ch == '\n' {
line_no += 1;
i += 1;
continue;
}
if block_comment_depth > 0 {
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth += 1;
i += 2;
} else if ch == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
block_comment_depth -= 1;
i += 2;
} else {
i += 1;
}
continue;
}
if let Some(hashes) = raw_string_hashes {
if ch == '"' {
let mut matched = 0usize;
while matched < hashes
&& i + 1 + matched < chars.len()
&& chars[i + 1 + matched] == '#'
{
matched += 1;
}
if matched == hashes {
raw_string_hashes = None;
i += 1 + hashes;
continue;
}
}
i += 1;
continue;
}
if in_string {
if string_escaped {
string_escaped = false;
} else if ch == '\\' {
string_escaped = true;
} else if ch == '"' {
in_string = false;
}
i += 1;
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth = 1;
i += 2;
continue;
}
if ch == '\'' {
if i + 2 < chars.len() && chars[i + 1] == '\\' {
if let Some(end) = chars[i + 2..].iter().position(|&c| c == '\'') {
if end <= 6 {
i += end + 3;
continue;
}
}
} else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\n' {
i += 3;
continue;
}
}
if ch == 'r'
&& (i == 0
|| (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_')
|| (chars[i - 1] == 'b'
&& (i == 1 || (!chars[i - 2].is_alphanumeric() && chars[i - 2] != '_'))))
{
let mut hashes = 0usize;
let mut j = i + 1;
while j < chars.len() && chars[j] == '#' {
hashes += 1;
j += 1;
}
if j < chars.len() && chars[j] == '"' {
raw_string_hashes = Some(hashes);
i = j + 1;
continue;
}
}
if ch == '"' {
in_string = true;
i += 1;
continue;
}
let in_test = test_lines
.get(line_no.saturating_sub(1))
.copied()
.unwrap_or(false);
if !in_test {
let word_start = i == 0 || (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_');
if word_start {
let mut targets: Vec<(&str, bool)> = vec![
("sqlx::query_scalar!", false),
("sqlx::query_scalar", false),
("sqlx::query_as!", true),
("sqlx::query_as", false),
("sqlx::query!", false),
("sqlx::query", false),
];
if include_builders {
targets.push(("sqlx::raw_sql", false));
targets.push(("QueryBuilder::new", false));
}
let mut matched_target: Option<(&str, bool)> = None;
for (pat, skip_type_arg) in targets {
if chars_match_prefix(&chars, i, pat) {
let after_idx = i + pat.chars().count();
let next_ok = after_idx >= chars.len()
|| (!chars[after_idx].is_alphanumeric()
&& chars[after_idx] != '_'
&& chars[after_idx] != '!');
if next_ok {
matched_target = Some((pat, skip_type_arg));
break;
}
}
}
if let Some((pat, skip_type_arg)) = matched_target {
let call_line = line_no;
let mut pos = i + pat.chars().count();
if !pat.ends_with('!') {
pos = skip_turbofish(&chars, pos);
}
pos = skip_rust_ws_and_comments(&chars, pos);
if pos < chars.len() && chars[pos] == '(' {
pos = skip_rust_ws_and_comments(&chars, pos + 1);
if skip_type_arg {
if let Some(after_comma) = skip_first_macro_arg_to_comma(&chars, pos) {
pos = skip_rust_ws_and_comments(&chars, after_comma);
} else {
i += pat.chars().count();
continue;
}
}
if let Some((sql, end_pos)) = parse_rust_string_literal(&chars, pos) {
let literal_newlines =
chars[i..pos].iter().filter(|&&c| c == '\n').count();
let literal_line = call_line + literal_newlines;
let allow_scan = line_has_allow_scan(&lines, call_line)
|| line_has_allow_scan(&lines, literal_line);
let allow_sql = line_has_allow_sql(&lines, call_line)
|| line_has_allow_sql(&lines, literal_line);
let after_lit = skip_rust_ws_and_comments(&chars, end_pos);
let after_comma = if after_lit < chars.len() && chars[after_lit] == ','
{
skip_rust_ws_and_comments(&chars, after_lit + 1)
} else {
after_lit
};
let chained_binds = if !pat.ends_with('!')
&& pat.starts_with("sqlx::query")
&& after_comma < chars.len()
&& chars[after_comma] == ')'
{
count_chained_binds(&chars, after_comma + 1)
} else {
None
};
out.push(ExtractedSqlQuery {
line: call_line,
sql,
allow_scan,
allow_sql,
chained_binds,
});
line_no += chars[i..end_pos].iter().filter(|&&c| c == '\n').count();
i = end_pos;
continue;
}
}
}
}
}
i += 1;
}
out
}
fn starts_with_sql_keyword(trimmed: &str, keyword: &str) -> bool {
let kw_len = keyword.len();
trimmed.len() > kw_len
&& trimmed
.get(..kw_len)
.is_some_and(|p| p.eq_ignore_ascii_case(keyword))
&& trimmed
.as_bytes()
.get(kw_len)
.is_some_and(u8::is_ascii_whitespace)
}
fn strip_leading_sql_line_comments(mut sql: &str) -> &str {
loop {
sql = sql.trim_start();
if let Some(rest) = sql.strip_prefix("--") {
if let Some(newline_pos) = rest.find('\n') {
sql = &rest[newline_pos + 1..];
continue;
}
return "";
}
return sql;
}
}
fn normalize_validatable_dml_sql(sql: &str) -> Option<&str> {
const DML_KEYWORDS: &[&str] = &["SELECT", "WITH", "INSERT", "UPDATE", "DELETE", "REPLACE"];
let trimmed = sql.trim().trim_end_matches(';').trim();
if trimmed.is_empty() || trimmed.contains(';') {
return None;
}
let body = strip_leading_sql_line_comments(trimmed);
if DML_KEYWORDS
.iter()
.any(|kw| starts_with_sql_keyword(body, kw))
{
Some(trimmed)
} else {
None
}
}
fn is_explainable_read_sql(sql: &str) -> bool {
let trimmed = sql.trim();
if trimmed.is_empty() || trimmed.contains(';') {
return false;
}
let body = strip_leading_sql_line_comments(trimmed);
starts_with_sql_keyword(body, "SELECT") || starts_with_sql_keyword(body, "WITH")
}
fn is_full_table_scan(plan_detail: &str) -> bool {
plan_detail.contains("SCAN ")
&& !plan_detail.contains("USING INDEX")
&& !plan_detail.contains("USING COVERING INDEX")
&& !plan_detail.contains("USING INTEGER PRIMARY KEY")
&& !plan_detail.contains("CONSTANT")
&& !plan_detail.contains("SUBQUERY")
}
fn suggest_index_hint(plan_detail: &str, sql: &str) -> String {
let table = plan_detail
.split_once("SCAN ")
.and_then(|(_, rest)| rest.split_whitespace().next())
.map(|t| t.trim_matches(|c| c == '"' || c == '`' || c == ',' || c == ')'))
.filter(|t| !t.is_empty())
.unwrap_or("<table>");
let cols = extract_where_columns(sql);
if cols.is_empty() {
format!("CREATE INDEX idx_{table}_lookup ON {table}(<columns>);")
} else {
let joined_name = cols.join("_");
let joined_cols = cols.join(", ");
format!("CREATE INDEX idx_{table}_{joined_name} ON {table}({joined_cols});")
}
}
fn extract_where_columns(sql: &str) -> Vec<String> {
let upper = sql.to_ascii_uppercase();
let Some(where_pos) = find_sql_keyword(&upper, "WHERE") else {
return Vec::new();
};
let rest = &sql[where_pos + 5..];
let rest_upper = &upper[where_pos + 5..];
let mut end = rest.len();
for stop_kw in ["GROUP BY", "ORDER BY", "LIMIT", "HAVING", "UNION"] {
if let Some(pos) = find_sql_keyword(rest_upper, stop_kw) {
end = end.min(pos);
}
}
let clause = &rest[..end];
let tokens = tokenize_sql_words(clause);
let mut cols = Vec::new();
for idx in 0..tokens.len() {
let next = tokens.get(idx + 1).map(String::as_str);
if matches!(
next,
Some("=" | ">" | "<" | ">=" | "<=" | "!=" | "<>" | "IN" | "LIKE" | "IS" | "BETWEEN")
) {
let raw_col = tokens[idx]
.rsplit('.')
.next()
.unwrap_or(&tokens[idx])
.trim_matches(|c| c == '"' || c == '`');
let upper_col = raw_col.to_ascii_uppercase();
if is_valid_sql_identifier(raw_col)
&& !is_sql_keyword(&upper_col)
&& !cols.iter().any(|c: &String| c == raw_col)
{
cols.push(raw_col.to_string());
if cols.len() >= 3 {
break;
}
}
}
}
cols
}
fn find_sql_keyword(upper_sql: &str, kw: &str) -> Option<usize> {
let bytes = upper_sql.as_bytes();
let mut start = 0usize;
while let Some(rel) = upper_sql[start..].find(kw) {
let pos = start + rel;
let before_ok =
pos == 0 || !bytes[pos - 1].is_ascii_alphanumeric() && bytes[pos - 1] != b'_';
let after_pos = pos + kw.len();
let after_ok = after_pos >= bytes.len()
|| (!bytes[after_pos].is_ascii_alphanumeric() && bytes[after_pos] != b'_');
if before_ok && after_ok {
return Some(pos);
}
start = pos + kw.len();
}
None
}
fn tokenize_sql_words(sql: &str) -> Vec<String> {
let chars: Vec<char> = sql.chars().collect();
let mut tokens = Vec::new();
let mut i = 0usize;
while i < chars.len() {
let ch = chars[i];
if ch.is_whitespace() || matches!(ch, ',' | ';') {
i += 1;
continue;
}
if ch == '\'' {
i += 1;
while i < chars.len() {
if chars[i] == '\'' {
if i + 1 < chars.len() && chars[i + 1] == '\'' {
i += 2;
continue;
}
i += 1;
break;
}
i += 1;
}
tokens.push("?STR?".to_string());
continue;
}
if matches!(ch, '(' | ')') {
tokens.push(ch.to_string());
i += 1;
continue;
}
if matches!(ch, '=' | '<' | '>' | '!') {
let mut op = String::new();
op.push(ch);
if i + 1 < chars.len() && matches!(chars[i + 1], '=' | '>') {
op.push(chars[i + 1]);
i += 2;
} else {
i += 1;
}
tokens.push(op);
continue;
}
if ch.is_alphanumeric() || matches!(ch, '_' | '.' | '"' | '`') {
let mut word = String::new();
while i < chars.len()
&& (chars[i].is_alphanumeric() || matches!(chars[i], '_' | '.' | '"' | '`'))
{
word.push(chars[i]);
i += 1;
}
tokens.push(word);
continue;
}
i += 1;
}
tokens
}
fn is_valid_sql_identifier(s: &str) -> bool {
let mut chars = s.chars();
let Some(first) = chars.next() else {
return false;
};
(first.is_ascii_alphabetic() || first == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn is_sql_keyword(upper: &str) -> bool {
matches!(
upper,
"SELECT"
| "FROM"
| "WHERE"
| "JOIN"
| "INNER"
| "LEFT"
| "RIGHT"
| "OUTER"
| "CROSS"
| "NATURAL"
| "ON"
| "AS"
| "AND"
| "OR"
| "NOT"
| "IN"
| "IS"
| "NULL"
| "TRUE"
| "FALSE"
| "ORDER"
| "GROUP"
| "BY"
| "LIMIT"
| "OFFSET"
| "HAVING"
| "UNION"
| "ALL"
| "DISTINCT"
| "INSERT"
| "INTO"
| "VALUES"
| "UPDATE"
| "SET"
| "DELETE"
| "CREATE"
| "TABLE"
| "INDEX"
| "IGNORE"
| "REPLACE"
| "ABORT"
| "ROLLBACK"
| "FAIL"
| "CASE"
| "WHEN"
| "THEN"
| "ELSE"
| "END"
| "EXISTS"
| "WITH"
| "RECURSIVE"
| "BETWEEN"
| "LIKE"
| "RETURNING"
| "CONFLICT"
| "DO"
| "NOTHING"
| "COALESCE"
| "COUNT"
| "LOWER"
| "UPPER"
| "LENGTH"
| "MAX"
| "MIN"
| "SUM"
| "AVG"
)
}
fn dir_has_sql_files(dir: &Path) -> bool {
if !dir.is_dir() {
return false;
}
fs::read_dir(dir).is_ok_and(|entries| {
entries.flatten().any(|e| {
e.path().is_file() && e.path().extension().and_then(|s| s.to_str()) == Some("sql")
})
})
}
fn app_root_for_file(file: &Path, candidate_roots: &[PathBuf]) -> Option<PathBuf> {
let canonical_file = fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf());
let mut best: Option<(usize, PathBuf)> = None;
for root in candidate_roots {
let canonical_root = fs::canonicalize(root).unwrap_or_else(|_| root.clone());
if canonical_file.starts_with(&canonical_root) {
let depth = canonical_root.components().count();
if best.as_ref().is_none_or(|(d, _)| depth > *d) {
best = Some((depth, root.clone()));
}
}
}
if let Some((_, root)) = best {
return Some(root);
}
for ancestor in file.ancestors().skip(1) {
if dir_has_sql_files(&ancestor.join("migrations")) || ancestor.join("schema.sql").is_file()
{
return Some(ancestor.to_path_buf());
}
}
None
}
fn candidate_schema_roots(app_dir: &Path) -> Vec<PathBuf> {
let mut candidate_roots: Vec<PathBuf> = discover_workspace_member_dirs(app_dir);
if !candidate_roots.iter().any(|r| r == app_dir) {
candidate_roots.push(app_dir.to_path_buf());
}
candidate_roots.retain(|root| {
dir_has_sql_files(&root.join("migrations")) || root.join("schema.sql").is_file()
});
candidate_roots
}
fn group_files_by_schema_root(
app_dir: &Path,
files: &[PathBuf],
) -> BTreeMap<PathBuf, Vec<PathBuf>> {
let candidate_roots = candidate_schema_roots(app_dir);
let mut grouped: BTreeMap<PathBuf, Vec<PathBuf>> = BTreeMap::new();
for file in files {
if !file.is_file() {
continue;
}
if let Some(root) = app_root_for_file(file, &candidate_roots) {
grouped.entry(root).or_default().push(file.clone());
}
}
grouped
}
fn has_sql_schema(app_dir: &Path, files: &[PathBuf]) -> bool {
!candidate_schema_roots(app_dir).is_empty()
|| !group_files_by_schema_root(app_dir, files).is_empty()
}
fn is_deployed_slabs_env() -> bool {
std::env::var("SLABS_ENV").is_ok_and(|env| {
let lower = env.trim().to_ascii_lowercase();
lower == "staging" || lower == "production"
})
}
async fn dump_schema_from_migrations(app_dir: &Path) -> Result<String, Box<dyn std::error::Error>> {
let migrations_dir = app_dir.join("migrations");
let db = Db::connect("sqlite::memory:").await?;
db.migrate_dir(&migrations_dir).await?;
Ok(db.dump_schema_sql().await?)
}
async fn dump_schema_from_url(database_url: &str) -> Result<String, Box<dyn std::error::Error>> {
match DbEngine::detect(database_url) {
DbEngine::Sqlite => {
let db = Db::connect(database_url).await?;
Ok(db.dump_schema_sql().await?)
}
DbEngine::Postgres => Err(
"PostgreSQL adapter is not enabled in Slabs 0.6; configure a sqlite:// DATABASE_URL"
.into(),
),
}
}
async fn open_in_memory_schema_db(root: &Path) -> Result<Option<Db>, Box<dyn std::error::Error>> {
let migrations_dir = root.join("migrations");
let schema_path = root.join("schema.sql");
let db = Db::connect("sqlite::memory:").await?;
if dir_has_sql_files(&migrations_dir) {
db.migrate_dir(&migrations_dir).await?;
Ok(Some(db))
} else if schema_path.is_file() {
db.execute_sql_file(&schema_path).await?;
db.init_system_tables().await?;
Ok(Some(db))
} else {
Ok(None)
}
}
async fn evaluate_sql_schema_check(
app_dir: &Path,
files: &[PathBuf],
) -> Result<SqlSchemaReport, Box<dyn std::error::Error>> {
let mut report = SqlSchemaReport::default();
let mut grouped = group_files_by_schema_root(app_dir, files);
if grouped.is_empty() && files.is_empty() {
for root in candidate_schema_roots(app_dir) {
grouped.entry(root).or_default();
}
}
for (root, root_files) in grouped {
let Some(db) = open_in_memory_schema_db(&root).await? else {
continue;
};
let migrations_dir = root.join("migrations");
let schema_path = root.join("schema.sql");
if dir_has_sql_files(&migrations_dir) && schema_path.is_file() {
let expected = db.dump_schema_sql().await?;
let actual = fs::read_to_string(&schema_path)?;
if expected.replace("\r\n", "\n").trim() != actual.replace("\r\n", "\n").trim() {
report.schema_drift.push(schema_path);
}
}
for file in root_files {
let content = fs::read_to_string(&file)?;
report.files_checked += 1;
let queries = extract_sql_queries_from_source(&content, false);
for extracted in queries {
if extracted.allow_sql {
continue;
}
let Some(sql) = normalize_validatable_dml_sql(&extracted.sql) else {
continue;
};
report.queries_checked += 1;
if let Err(err) = db.validate_sql(sql).await {
report.findings.push(SqlSchemaFinding {
file: file.clone(),
line: extracted.line,
error: err.to_string(),
query_snippet: truncate_str(sql, 96),
});
}
if let (Some(expected), Some(actual)) =
(count_sql_placeholders(sql), extracted.chained_binds)
{
if expected != actual {
report.findings.push(SqlSchemaFinding {
file: file.clone(),
line: extracted.line,
error: format!(
"SQL query has {expected} placeholder(s) (`?`) but {actual} chained `.bind(...)` call(s)"
),
query_snippet: truncate_str(sql, 96),
});
}
}
}
}
}
Ok(report)
}
async fn run_sql_schema_check(
app_dir: &Path,
files: &[PathBuf],
) -> Result<(), Box<dyn std::error::Error>> {
let report = evaluate_sql_schema_check(app_dir, files).await?;
for finding in &report.findings {
println!(" [SQL ERR] {}:{}", finding.file.display(), finding.line);
println!(" error: {}", finding.error);
println!(" query: {}", finding.query_snippet);
println!(
" hint: fix the SQL query or schema migration (or add `// slabs:allow-sql: <reason>`)"
);
}
for drifted in &report.schema_drift {
println!(
" [SCHEMA] {}: out of date with migrations/ (run `slabs db dump-schema` to refresh)",
drifted.display()
);
}
let total_errors = report.findings.len() + report.schema_drift.len();
println!(
"[sql] Validated {} query(ies) across {} file(s): {} error(s)",
report.queries_checked, report.files_checked, total_errors
);
if total_errors > 0 {
return Err(
format!("[sql] offline schema validation failed with {total_errors} error(s)").into(),
);
}
Ok(())
}
async fn evaluate_explain_check(
app_dir: &Path,
files: &[PathBuf],
) -> Result<ExplainReport, Box<dyn std::error::Error>> {
let mut report = ExplainReport::default();
let grouped = group_files_by_schema_root(app_dir, files);
for (root, root_files) in grouped {
let Some(db) = open_in_memory_schema_db(&root).await? else {
continue;
};
for file in root_files {
let content = fs::read_to_string(&file)?;
report.files_checked += 1;
let queries = extract_sql_queries_from_source(&content, false);
for extracted in queries {
if !is_explainable_read_sql(&extracted.sql) {
continue;
}
if extracted.allow_scan {
continue;
}
report.queries_checked += 1;
match db.explain_query_plan(&extracted.sql).await {
Ok(plan_lines) => {
for detail in plan_lines {
if is_full_table_scan(&detail) {
let hint = suggest_index_hint(&detail, &extracted.sql);
report.findings.push(ExplainFinding {
file: file.clone(),
line: extracted.line,
plan_detail: detail,
query_snippet: truncate_str(extracted.sql.trim(), 96),
index_hint: hint,
});
}
}
}
Err(_err) => {
}
}
}
}
}
Ok(report)
}
async fn run_explain_check(
app_dir: &Path,
files: &[PathBuf],
strict: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let report = evaluate_explain_check(app_dir, files).await?;
for finding in &report.findings {
println!(" [SCAN] {}:{}", finding.file.display(), finding.line);
println!(" plan: {}", finding.plan_detail);
println!(" query: {}", finding.query_snippet);
println!(
" hint: {} (or add `// slabs:allow-scan: <reason>`)",
finding.index_hint
);
}
println!(
"[explain] Checked {} read query(ies) across {} file(s): {} full-table SCAN warning(s)",
report.queries_checked,
report.files_checked,
report.findings.len()
);
if strict && !report.findings.is_empty() {
return Err(format!(
"[explain] failed with {} unannotated full-table SCAN warning(s) (`--strict-explain`)",
report.findings.len()
)
.into());
}
Ok(())
}
async fn run_doctor(app_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
let mut passed = 0usize;
let mut warned = 0usize;
let mut failed = 0usize;
let mut record = |status: &str, label: &str, detail: &str| {
println!("[{status}] {label}: {detail}");
match status {
"PASS" => passed += 1,
"WARN" => warned += 1,
_ => failed += 1,
}
};
match command_first_line("rustc", &["--version"]).await {
Some(ver) => record("PASS", "rustc", &ver),
None => record("FAIL", "rustc", "not found in PATH"),
}
match command_first_line("cargo", &["nextest", "--version"]).await {
Some(ver) => record("PASS", "cargo-nextest", &ver),
None => record(
"WARN",
"cargo-nextest",
"not installed (optional; install via `cargo install cargo-nextest`)",
),
}
let sqlx_ver = match command_first_line("sqlx", &["--version"]).await {
Some(ver) => Some(ver),
None => command_first_line("cargo", &["sqlx", "--version"]).await,
};
match sqlx_ver {
Some(ver) => record("PASS", "sqlx-cli", &ver),
None => record(
"WARN",
"sqlx-cli",
"not installed (optional; needed only for `slabs db prepare`)",
),
}
let manifest_path = app_dir.join("Cargo.toml");
let is_workspace = manifest_is_workspace(&manifest_path);
if manifest_path.exists() {
let workspace_forbids = cargo_toml_forbids_unsafe(&manifest_path);
if workspace_forbids {
record(
"PASS",
"Cargo.toml unsafe_code",
"unsafe_code = \"forbid\" configured",
);
} else {
record(
"FAIL",
"Cargo.toml unsafe_code",
"missing `unsafe_code = \"forbid\"` in Cargo.toml",
);
}
} else {
record(
"FAIL",
"Cargo.toml",
&format!("not found at {}", manifest_path.display()),
);
}
let schema_path = app_dir.join("schema.sql");
if schema_path.is_file() {
let content = fs::read_to_string(&schema_path).unwrap_or_default();
if content.trim().is_empty() {
record("FAIL", "schema.sql", "file exists but is empty");
} else {
record(
"PASS",
"schema.sql",
&format!("present ({} bytes)", content.len()),
);
}
} else if is_workspace && !app_dir.join("slabs").is_dir() {
record(
"WARN",
"schema.sql",
"not present at workspace root (expected inside individual app directories)",
);
} else {
record("FAIL", "schema.sql", "missing; run `slabs db dump-schema`");
}
let dockerignore_path = app_dir.join(".dockerignore");
if dockerignore_path.is_file() {
record("PASS", ".dockerignore", "present");
} else {
record(
"WARN",
".dockerignore",
"missing; add `.dockerignore` excluding `.git`, `target`, `.env`, and `*.db`",
);
}
let dockerfile_path = app_dir.join("Dockerfile");
if dockerfile_path.is_file() {
let content = fs::read_to_string(&dockerfile_path).unwrap_or_default();
let entrypoint_content = fs::read_to_string(app_dir.join("docker-entrypoint.sh")).ok();
let missing = missing_dockerfile_hardening_tokens(&content, entrypoint_content.as_deref());
if missing.is_empty() {
record(
"PASS",
"dockerfile-hardening",
"Dockerfile sets SLABS_ENV=production, SLABS_COOKIE_SECURE=true, --locked, non-root execution, and /health/ready",
);
} else {
record(
"WARN",
"dockerfile-hardening",
&format!(
"Dockerfile is missing required hardening settings: {}",
missing.join(", ")
),
);
}
}
let slabs_env = std::env::var("SLABS_ENV").unwrap_or_else(|_| "development".to_string());
let env_lower = slabs_env.to_ascii_lowercase();
if env_lower == "staging" || env_lower == "production" {
let dev_sentinel = concat!("dev-only-change-me-", "in-production");
match std::env::var("SLABS_SECRET_KEY") {
Ok(key) if key.len() >= 32 && !key.contains(dev_sentinel) => record(
"PASS",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!("SLABS_ENV={slabs_env} with valid secret key (>= 32 bytes)"),
),
Ok(key) => record(
"FAIL",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!(
"SLABS_ENV={slabs_env} requires a non-default SLABS_SECRET_KEY of at least 32 bytes (got {} bytes)",
key.len()
),
),
Err(_) => record(
"FAIL",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!("SLABS_ENV={slabs_env} requires SLABS_SECRET_KEY (>= 32 random bytes)"),
),
}
} else {
record(
"PASS",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!(
"SLABS_ENV={slabs_env} (set SLABS_SECRET_KEY >= 32 bytes in staging/production)"
),
);
}
let report = scan_security(app_dir, is_workspace)?;
let errors = report.error_count();
let warnings = report.warning_count();
if errors > 0 {
record(
"FAIL",
"[security] static scan",
&format!(
"{errors} error(s), {warnings} warning(s) across {} file(s)",
report.files_scanned
),
);
print_security_report(&report, false);
} else if warnings > 0 {
record(
"WARN",
"[security] static scan",
&format!(
"0 errors, {warnings} warning(s) across {} file(s)",
report.files_scanned
),
);
print_security_report(&report, false);
} else {
record(
"PASS",
"[security] static scan",
&format!(
"0 errors, 0 warnings across {} file(s)",
report.files_scanned
),
);
}
println!("Doctor summary: {passed} passed, {warned} warnings, {failed} failed.");
if failed > 0 {
return Err(format!("slabs doctor found {failed} failing check(s)").into());
}
Ok(())
}
async fn command_first_line(program: &str, args: &[&str]) -> Option<String> {
let output = Command::new(program).args(args).output().await.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8_lossy(&output.stdout);
stdout
.lines()
.next()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SecurityFinding {
severity: Severity,
rule: &'static str,
file: PathBuf,
line: usize,
message: String,
}
#[derive(Debug, Default)]
struct SecurityReport {
findings: Vec<SecurityFinding>,
files_scanned: usize,
}
impl SecurityReport {
fn error_count(&self) -> usize {
self.findings
.iter()
.filter(|f| f.severity == Severity::Error)
.count()
}
fn warning_count(&self) -> usize {
self.findings
.iter()
.filter(|f| f.severity == Severity::Warning)
.count()
}
}
fn format_security_report(report: &SecurityReport, verbose: bool) -> String {
let mut out = String::new();
for finding in report
.findings
.iter()
.filter(|f| f.severity == Severity::Error)
{
let _ = writeln!(
out,
" [ERR ] ({}) {}:{}: {}",
finding.rule,
finding.file.display(),
finding.line,
finding.message
);
}
if verbose {
for finding in report
.findings
.iter()
.filter(|f| f.severity == Severity::Warning)
{
let _ = writeln!(
out,
" [WARN ] ({}) {}:{}: {}",
finding.rule,
finding.file.display(),
finding.line,
finding.message
);
}
} else {
let mut warnings_by_rule: BTreeMap<&'static str, Vec<&SecurityFinding>> = BTreeMap::new();
for finding in report
.findings
.iter()
.filter(|f| f.severity == Severity::Warning)
{
warnings_by_rule
.entry(finding.rule)
.or_default()
.push(finding);
}
for (rule, list) in warnings_by_rule {
if list.len() <= 3 {
for finding in list {
let _ = writeln!(
out,
" [WARN ] ({}) {}:{}: {}",
finding.rule,
finding.file.display(),
finding.line,
finding.message
);
}
} else {
let examples = list
.iter()
.take(3)
.map(|f| format!("{}:{}", f.file.display(), f.line))
.collect::<Vec<_>>()
.join(", ");
let _ = writeln!(
out,
" [WARN ] ({rule}) {} finding(s) (e.g. {examples}; pass --verbose to list all)",
list.len()
);
}
}
}
let _ = writeln!(
out,
"[security] Scanned {} file(s): {} error(s), {} warning(s).",
report.files_scanned,
report.error_count(),
report.warning_count()
);
out
}
fn print_security_report(report: &SecurityReport, verbose: bool) {
print!("{}", format_security_report(report, verbose));
}
fn scan_security(
root: &Path,
is_workspace: bool,
) -> Result<SecurityReport, Box<dyn std::error::Error>> {
let mut report = SecurityReport::default();
let root_manifest = root.join("Cargo.toml");
let workspace_forbids_unsafe =
root_manifest.is_file() && cargo_toml_forbids_unsafe(&root_manifest);
let crate_dirs = if is_workspace {
discover_workspace_member_dirs(root)
} else {
vec![root.to_path_buf()]
};
if is_workspace && root_manifest.is_file() {
scan_cargo_toml(&root_manifest, true, &mut report)?;
}
for crate_dir in crate_dirs {
let manifest = crate_dir.join("Cargo.toml");
let pkg_name = infer_package_name_raw(&manifest);
if manifest.is_file() {
scan_cargo_toml(&manifest, workspace_forbids_unsafe, &mut report)?;
}
let mut scan_targets: Vec<(PathBuf, FileArea)> = Vec::new();
for (subdir, area) in [
("slabs", FileArea::Slabs),
("jobs", FileArea::Jobs),
("src", FileArea::Src),
] {
let dir = crate_dir.join(subdir);
if dir.is_dir() {
let mut rs_files = Vec::new();
collect_rs_recursive(&dir, &mut rs_files)?;
rs_files.sort();
for path in rs_files {
scan_targets.push((path, area));
}
}
}
for (file, area) in scan_targets {
scan_rust_file(&file, area, pkg_name.as_deref(), &mut report)?;
}
}
Ok(report)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FileArea {
Slabs,
Jobs,
Src,
}
fn scan_cargo_toml(
path: &Path,
workspace_forbids_unsafe: bool,
report: &mut SecurityReport,
) -> Result<(), Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
report.files_scanned += 1;
let inherits_workspace_lints = cargo_toml_inherits_workspace_lints(&content);
let has_forbid = cargo_toml_content_forbids_unsafe(&content)
|| (inherits_workspace_lints && workspace_forbids_unsafe);
if !has_forbid {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "unsafe-code",
file: path.to_path_buf(),
line: 1,
message: "Cargo.toml must set `unsafe_code = \"forbid\"` (or inherit workspace lints that forbid unsafe code)".to_string(),
});
}
for (idx, line) in content.lines().enumerate() {
let trimmed = line.trim();
if trimmed.starts_with('#') {
continue;
}
if let Some(secret_kind) = detect_hardcoded_secret(line, false) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "hardcoded-secret",
file: path.to_path_buf(),
line: idx + 1,
message: format!("possible hardcoded secret ({secret_kind}) in Cargo.toml"),
});
}
}
Ok(())
}
fn scan_rust_file(
path: &Path,
area: FileArea,
pkg_name: Option<&str>,
report: &mut SecurityReport,
) -> Result<(), Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
report.files_scanned += 1;
let lines: Vec<&str> = content.lines().collect();
let code_lines = strip_rust_file_code_lines(&content);
let is_slabs_html_crate = pkg_name == Some("slabs-html");
let is_slabs_core_crate = pkg_name == Some("slabs-core");
let is_service_worker_file =
path.file_name().and_then(|s| s.to_str()) == Some("service_worker.rs");
let is_auth_or_web = area == FileArea::Slabs && is_auth_or_web_slab(path);
let mut in_cfg_test = false;
let mut pending_cfg_test = false;
let mut test_brace_depth: i32 = 0;
let mut has_cfg_test = false;
let mut ws_upgrade_line: Option<usize> = None;
let mut has_validate_ws_origin = false;
let mut has_storage_get = false;
let mut content_disposition_line: Option<usize> = None;
let mut has_into_safe_response = false;
let mut sw_fetch_line: Option<usize> = None;
let mut sw_has_origin_check = false;
for (idx, &raw_line) in lines.iter().enumerate() {
let line_no = idx + 1;
let trimmed = raw_line.trim();
let code = code_lines.get(idx).map_or("", String::as_str);
if code.contains("#[cfg(test)]") {
has_cfg_test = true;
if !in_cfg_test {
pending_cfg_test = true;
}
}
let code_no_comment = strip_line_comment(raw_line);
if pending_cfg_test {
let (opens, closes, saw_semi) = count_braces_and_semi(code);
if opens > 0 {
in_cfg_test = true;
pending_cfg_test = false;
test_brace_depth = opens - closes;
if test_brace_depth <= 0 {
in_cfg_test = false;
test_brace_depth = 0;
}
} else if saw_semi {
pending_cfg_test = false;
}
} else if in_cfg_test {
let (opens, closes, _) = count_braces_and_semi(code);
test_brace_depth += opens - closes;
if test_brace_depth <= 0 {
in_cfg_test = false;
test_brace_depth = 0;
}
}
if trimmed.starts_with("//") {
continue;
}
for sql_call in ["sqlx::query(", "sqlx::query_as(", "sqlx::raw_sql("] {
if let Some(pos) = code.find(sql_call) {
let arg_slice = extract_call_arg_slice(&code_lines, idx, pos + sql_call.len());
if has_sql_interpolation(&arg_slice) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "sql-injection",
file: path.to_path_buf(),
line: line_no,
message: format!(
"dynamic SQL construction (`format!(` or `+`) inside `{sql_call}...)`; use parameterized `.bind(...)` instead"
),
});
}
}
}
if !in_cfg_test && !is_slabs_html_crate && code.contains(concat!("Pre", "Escaped(")) {
let allow_marker = "// slabs:allow-raw-html:";
let has_allow_here = raw_line.contains(allow_marker);
let has_allow_prev = idx > 0 && lines[idx - 1].contains(allow_marker);
if !has_allow_here && !has_allow_prev {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "raw-html",
file: path.to_path_buf(),
line: line_no,
message: "unannotated `PreEscaped(` outside `#[cfg(test)]`; prefer `html::render_markdown` or add `// slabs:allow-raw-html: <reason>`".to_string(),
});
}
}
if contains_unsafe_pattern(code) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "unsafe-code",
file: path.to_path_buf(),
line: line_no,
message: "unsafe Rust code or `allow(unsafe_code)` is forbidden in Slabs projects"
.to_string(),
});
}
if let Some(secret_kind) = detect_hardcoded_secret(code_no_comment, is_slabs_core_crate) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "hardcoded-secret",
file: path.to_path_buf(),
line: line_no,
message: format!("possible hardcoded secret ({secret_kind})"),
});
}
if !in_cfg_test
&& matches!(area, FileArea::Slabs | FileArea::Jobs)
&& (code.contains(".unwrap()") || code.contains(".expect("))
{
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "panic-hazard",
file: path.to_path_buf(),
line: line_no,
message: "avoid `.unwrap()` / `.expect()` outside `#[cfg(test)]` in `slabs/` and `jobs/`; return a `SlabError` with `?`".to_string(),
});
}
if !in_cfg_test {
for hmac_call in [
"verify_incoming_hmac_sha256(",
"verify_signed_timestamped_webhook(",
] {
if let Some(pos) = code.find(hmac_call) {
let arg_slice = extract_call_arg_slice(&code_lines, idx, pos + hmac_call.len());
if arg_slice.contains("config.secret_key") {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "master-key-reuse",
file: path.to_path_buf(),
line: line_no,
message: "do not pass `config.secret_key` to webhook HMAC verification; use a dedicated webhook signing secret".to_string(),
});
}
}
}
if area == FileArea::Slabs {
if ws_upgrade_line.is_none() && code.contains("WebSocketUpgrade") {
ws_upgrade_line = Some(line_no);
}
if code.contains("validate_ws_origin") {
has_validate_ws_origin = true;
}
if code.contains(".storage.get") {
has_storage_get = true;
}
if content_disposition_line.is_none() && code.contains("CONTENT_DISPOSITION") {
content_disposition_line = Some(line_no);
}
if code.contains("into_safe_response") {
has_into_safe_response = true;
}
if code.contains("style=(format!") || code.contains("hx-vals=(format!") {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "template-attr-injection",
file: path.to_path_buf(),
line: line_no,
message: "avoid `style=(format!(...))` or `hx-vals=(format!(...))` in Maud templates; use fixed CSS classes or JSON serialization".to_string(),
});
}
}
if is_service_worker_file {
if sw_fetch_line.is_none()
&& (raw_line.contains("addEventListener(\"fetch\"")
|| raw_line.contains("addEventListener('fetch'"))
{
sw_fetch_line = Some(line_no);
}
if raw_line.contains("self.location.origin") {
sw_has_origin_check = true;
}
}
if is_auth_or_web {
if code.contains(".verify_password(") {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "password-timing-enum",
file: path.to_path_buf(),
line: line_no,
message: "prefer `verify_password_constant_time` over `.verify_password(` in auth handlers to prevent login timing enumeration".to_string(),
});
}
if code.contains(".create_session(") {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "session-fixation",
file: path.to_path_buf(),
line: line_no,
message: "prefer `rotate_session` or `rotate_session_in_tx` over `.create_session(` in auth handlers to prevent session fixation".to_string(),
});
}
}
}
}
if area == FileArea::Slabs && is_discovered_slab_file(path) && !has_cfg_test {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "missing-test",
file: path.to_path_buf(),
line: 1,
message: "slab file is missing a co-located `#[cfg(test)] mod tests` block".to_string(),
});
}
if area == FileArea::Slabs {
if let Some(line_no) = ws_upgrade_line {
if !has_validate_ws_origin {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "ws-missing-origin-check",
file: path.to_path_buf(),
line: line_no,
message:
"WebSocket slab uses `WebSocketUpgrade` without calling `validate_ws_origin`"
.to_string(),
});
}
}
}
if area == FileArea::Slabs && has_storage_get && !has_into_safe_response {
if let Some(line_no) = content_disposition_line {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "unsafe-blob-response",
file: path.to_path_buf(),
line: line_no,
message: "blob response sets `CONTENT_DISPOSITION` manually instead of using `BlobMeta::into_safe_response`".to_string(),
});
}
}
if is_service_worker_file {
if let Some(line_no) = sw_fetch_line {
if !sw_has_origin_check {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "service-worker-origin",
file: path.to_path_buf(),
line: line_no,
message: "service worker `fetch` listener must check `self.location.origin` before caching or intercepting requests".to_string(),
});
}
}
}
if area == FileArea::Slabs && !lines.iter().any(|l| l.contains("// slabs:allow-unscoped:")) {
let route_calls = extract_call_first_string_arg(
&content,
&[
"SlabDef::get",
"SlabDef::post",
"SlabDef::put",
"SlabDef::patch",
"SlabDef::delete",
],
);
let has_param_route = route_calls.iter().any(|(_, p)| route_has_path_param(p));
if has_param_route {
let non_test_code = non_test_code_string(&content);
let has_user_auth =
non_test_code.contains("require_session") || non_test_code.contains("require_auth");
let has_admin_auth = non_test_code.contains("require_admin");
if has_user_auth && !has_admin_auth {
let sql_queries = extract_sql_queries_from_source(&content, false);
if !sql_queries.is_empty() {
let (reads, writes) = extract_tables_from_sql_queries(&sql_queries);
let touches_domain_table = reads.iter().chain(writes.iter()).any(|table| {
!table.eq_ignore_ascii_case("users")
&& !table.to_ascii_lowercase().starts_with("slabs_")
});
let has_scoping_ident = sql_queries
.iter()
.any(|q| sql_mentions_scoping_ident(&q.sql));
if touches_domain_table && !has_scoping_ident {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "possible-idor",
file: path.to_path_buf(),
line: sql_queries[0].line,
message: "parameterized route queries a domain table without visible ownership/tenant scoping (for example `user_id`, `account_id`, `owner_id`, or `memberships`); verify access control or add `// slabs:allow-unscoped: <reason>`".to_string(),
});
}
}
}
}
}
Ok(())
}
fn route_has_path_param(route_path: &str) -> bool {
if let Some(open) = route_path.find('{') {
if let Some(close) = route_path[open + 1..].find('}') {
return close > 0;
}
}
false
}
fn sql_mentions_scoping_ident(sql: &str) -> bool {
const SCOPING_IDENTS: &[&str] = &[
"user_id",
"account_id",
"owner_id",
"creator_id",
"author_id",
"assignee_id",
"member_id",
"memberships",
"accesses",
"upload_owners",
];
tokenize_sql_words(sql).into_iter().any(|token| {
token.split('.').any(|segment| {
let clean = segment
.trim_matches(|c| c == '"' || c == '`')
.to_ascii_lowercase();
SCOPING_IDENTS.contains(&clean.as_str())
})
})
}
fn is_auth_or_web_slab(path: &Path) -> bool {
let mut saw_slabs = false;
for comp in path.components() {
if let std::path::Component::Normal(os) = comp {
if let Some(s) = os.to_str() {
if saw_slabs && (s == "auth" || s == "web") {
return true;
}
if s == "slabs" {
saw_slabs = true;
}
}
}
}
false
}
fn missing_dockerfile_hardening_tokens(
content: &str,
entrypoint_content: Option<&str>,
) -> Vec<&'static str> {
let active_lines: Vec<&str> = content
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.collect();
let active = active_lines.join("\n");
let mut missing: Vec<&'static str> = [
"SLABS_ENV=production",
"SLABS_COOKIE_SECURE=true",
"--locked",
"/health/ready",
]
.into_iter()
.filter(|token| !active.contains(token))
.collect();
let has_non_root_user = active_lines.iter().any(|line| {
let mut parts = line.split_whitespace();
let Some(cmd) = parts.next() else {
return false;
};
if !cmd.eq_ignore_ascii_case("USER") {
return false;
}
let Some(target) = parts.next() else {
return false;
};
let user = target.split(':').next().unwrap_or("");
!user.is_empty() && !user.eq_ignore_ascii_case("root") && user != "0"
});
let has_entrypoint_priv_drop = active.contains("docker-entrypoint.sh")
&& entrypoint_content.is_some_and(|script| {
script.lines().any(|line| {
let trimmed = line.trim();
!trimmed.starts_with('#')
&& (trimmed.contains("setpriv")
|| trimmed.contains("gosu")
|| trimmed.contains("su-exec"))
})
});
if !has_non_root_user && !has_entrypoint_priv_drop {
missing
.push("non-root USER (or setpriv/gosu/su-exec privilege drop in docker-entrypoint.sh)");
}
missing
}
fn is_discovered_slab_file(path: &Path) -> bool {
let Some(file_name) = path.file_name().and_then(|s| s.to_str()) else {
return false;
};
if file_name == "mod.rs" || file_name.starts_with('_') || file_name.starts_with('.') {
return false;
}
let Some(parent_name) = path
.parent()
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
else {
return false;
};
!parent_name.starts_with('_') && !parent_name.starts_with('.') && parent_name != "slabs"
}
fn cargo_toml_forbids_unsafe(manifest_path: &Path) -> bool {
fs::read_to_string(manifest_path).is_ok_and(|c| cargo_toml_content_forbids_unsafe(&c))
}
fn cargo_toml_content_forbids_unsafe(content: &str) -> bool {
let mut in_lints_rust = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if trimmed.starts_with('[') {
in_lints_rust = trimmed == "[lints.rust]" || trimmed == "[workspace.lints.rust]";
continue;
}
if in_lints_rust {
if let Some(rest) = trimmed.strip_prefix("unsafe_code") {
let rest = rest.trim_start();
if let Some(val) = rest.strip_prefix('=') {
let val = val.split('#').next().unwrap_or("").trim();
if val == "\"forbid\"" || val == "'forbid'" {
return true;
}
}
}
}
}
false
}
fn cargo_toml_inherits_workspace_lints(content: &str) -> bool {
let mut in_lints = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if trimmed.starts_with('[') {
in_lints = trimmed == "[lints]";
continue;
}
if in_lints {
if let Some(rest) = trimmed.strip_prefix("workspace") {
let rest = rest.trim_start();
if let Some(val) = rest.strip_prefix('=') {
let val = val.split('#').next().unwrap_or("").trim();
if val == "true" {
return true;
}
}
}
}
}
false
}
fn strip_line_comment(line: &str) -> &str {
let bytes = line.as_bytes();
let mut in_string = false;
let mut escaped = false;
let mut i = 0usize;
while i < bytes.len() {
let b = bytes[i];
if in_string {
if escaped {
escaped = false;
} else if b == b'\\' {
escaped = true;
} else if b == b'"' {
in_string = false;
}
} else if b == b'"' {
in_string = true;
} else if b == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
return &line[..i];
}
i += 1;
}
line
}
fn strip_rust_file_code_lines(content: &str) -> Vec<String> {
let chars: Vec<char> = content.chars().collect();
let mut lines = Vec::new();
let mut current = String::new();
let mut i = 0usize;
let mut block_comment_depth = 0usize;
let mut in_string = false;
let mut string_escaped = false;
let mut raw_string_hashes: Option<usize> = None;
while i < chars.len() {
let ch = chars[i];
if ch == '\n' {
lines.push(std::mem::take(&mut current));
i += 1;
continue;
}
if ch == '\r' {
i += 1;
continue;
}
if block_comment_depth > 0 {
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth += 1;
current.push_str(" ");
i += 2;
} else if ch == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
block_comment_depth -= 1;
current.push_str(" ");
i += 2;
} else {
current.push(' ');
i += 1;
}
continue;
}
if let Some(hashes) = raw_string_hashes {
if ch == '"' {
let mut matched = 0usize;
while matched < hashes
&& i + 1 + matched < chars.len()
&& chars[i + 1 + matched] == '#'
{
matched += 1;
}
if matched == hashes {
raw_string_hashes = None;
for _ in 0..=hashes {
current.push(' ');
}
i += 1 + hashes;
continue;
}
}
current.push(' ');
i += 1;
continue;
}
if in_string {
if string_escaped {
string_escaped = false;
} else if ch == '\\' {
string_escaped = true;
} else if ch == '"' {
in_string = false;
}
current.push(' ');
i += 1;
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth = 1;
current.push_str(" ");
i += 2;
continue;
}
if ch == '\'' {
if i + 2 < chars.len() && chars[i + 1] == '\\' {
if let Some(end) = chars[i + 2..].iter().position(|&c| c == '\'') {
if end <= 6 {
for _ in 0..(end + 3) {
current.push(' ');
}
i += end + 3;
continue;
}
}
} else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\n' {
current.push_str(" ");
i += 3;
continue;
}
}
if ch == 'r'
&& (i == 0
|| (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_')
|| (chars[i - 1] == 'b'
&& (i == 1 || (!chars[i - 2].is_alphanumeric() && chars[i - 2] != '_'))))
{
let mut hashes = 0usize;
let mut j = i + 1;
while j < chars.len() && chars[j] == '#' {
hashes += 1;
j += 1;
}
if j < chars.len() && chars[j] == '"' {
raw_string_hashes = Some(hashes);
for _ in i..=j {
current.push(' ');
}
i = j + 1;
continue;
}
}
if ch == '"' {
in_string = true;
current.push(' ');
i += 1;
continue;
}
current.push(ch);
i += 1;
}
if !current.is_empty() || content.ends_with('\n') || lines.is_empty() {
lines.push(current);
}
lines
}
fn count_braces_and_semi(code: &str) -> (i32, i32, bool) {
let mut opens = 0i32;
let mut closes = 0i32;
let mut saw_semi = false;
for ch in code.chars() {
match ch {
'{' => opens += 1,
'}' => closes += 1,
';' => saw_semi = true,
_ => {}
}
}
(opens, closes, saw_semi)
}
fn extract_call_arg_slice(code_lines: &[String], start_idx: usize, start_col: usize) -> String {
let mut collected = String::new();
let mut depth = 1i32;
let end_idx = (start_idx + 20).min(code_lines.len());
for (offset, code) in code_lines[start_idx..end_idx].iter().enumerate() {
let segment = if offset == 0 {
code.get(start_col..).unwrap_or("")
} else {
code.as_str()
};
for ch in segment.chars() {
match ch {
'(' => {
depth += 1;
collected.push(ch);
}
')' => {
depth -= 1;
if depth == 0 {
return collected;
}
collected.push(ch);
}
_ => collected.push(ch),
}
}
collected.push(' ');
}
collected
}
fn has_sql_interpolation(code_arg: &str) -> bool {
code_arg.contains("format!(") || code_arg.contains('+')
}
fn contains_unsafe_pattern(code: &str) -> bool {
let allow_inner = concat!("#![allow(", "unsafe_code)]");
let allow_outer = concat!("#[allow(", "unsafe_code)]");
if code.contains(allow_inner) || code.contains(allow_outer) {
return true;
}
let unsafe_kw = concat!("un", "safe");
let bytes = code.as_bytes();
let mut start = 0usize;
while let Some(rel) = code[start..].find(unsafe_kw) {
let pos = start + rel;
let before_ok =
pos == 0 || !(bytes[pos - 1].is_ascii_alphanumeric() || bytes[pos - 1] == b'_');
let after = &code[pos + unsafe_kw.len()..];
if before_ok {
let trimmed_after = after.trim_start();
if trimmed_after.starts_with('{')
|| trimmed_after.starts_with("fn ")
|| trimmed_after.starts_with("fn\t")
{
return true;
}
}
start = pos + unsafe_kw.len();
}
false
}
fn detect_hardcoded_secret(line: &str, skip_dev_sentinel: bool) -> Option<&'static str> {
let stripe_live = concat!("sk_", "live_");
let pem_begin = concat!("-----", "BEGIN ");
let dev_sentinel = concat!("dev-only-change-me-", "in-production");
if line.contains(stripe_live) {
return Some("Stripe live secret key");
}
if line.contains(pem_begin) {
return Some("PEM private key block");
}
if !skip_dev_sentinel && line.contains(dev_sentinel) {
return Some("hardcoded development fallback secret");
}
if contains_resend_api_key(line) {
return Some("Resend API key");
}
None
}
fn contains_resend_api_key(line: &str) -> bool {
let bytes = line.as_bytes();
let prefix = concat!("re", "_");
let mut start = 0usize;
while let Some(rel) = line[start..].find(prefix) {
let pos = start + rel;
let quote_preceded = pos > 0 && (bytes[pos - 1] == b'"' || bytes[pos - 1] == b'\'');
if quote_preceded {
let tail = &bytes[pos + prefix.len()..];
let token_len = tail
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || **b == b'_' || **b == b'-')
.count();
if token_len >= 16 {
return true;
}
}
start = pos + prefix.len();
}
false
}
async fn run_checked_command(
cmd: &mut Command,
label: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let status = cmd.status().await?;
if !status.success() {
return Err(format!("{label} failed with status {status}").into());
}
Ok(())
}
fn manifest_is_workspace(manifest_path: &Path) -> bool {
fs::read_to_string(manifest_path)
.is_ok_and(|content| content.lines().any(|line| line.trim() == "[workspace]"))
}
fn discover_workspace_member_dirs(root: &Path) -> Vec<PathBuf> {
let manifest_path = root.join("Cargo.toml");
if manifest_path.is_file() {
let output = std::process::Command::new("cargo")
.args([
"metadata",
"--no-deps",
"--format-version",
"1",
"--manifest-path",
])
.arg(&manifest_path)
.output();
if let Ok(out) = output {
if out.status.success() {
if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&out.stdout) {
if let Some(packages) = json.get("packages").and_then(|v| v.as_array()) {
let mut dirs: Vec<PathBuf> = packages
.iter()
.filter_map(|p| p.get("manifest_path").and_then(|m| m.as_str()))
.filter_map(|p| Path::new(p).parent().map(Path::to_path_buf))
.collect();
dirs.sort();
dirs.dedup();
if !dirs.is_empty() {
return dirs;
}
}
}
}
}
}
let mut dirs = vec![root.to_path_buf()];
if let Ok(entries) = fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
if name.starts_with('.') || name == "target" {
continue;
}
if path.join("Cargo.toml").exists() {
dirs.push(path);
}
}
}
dirs.sort();
dirs.dedup();
dirs
}
fn collect_workspace_discovered_rs_files(
root: &Path,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
let mut files = collect_discovered_rs_files(root)?;
for member_dir in discover_workspace_member_dirs(root) {
files.extend(collect_discovered_rs_files(&member_dir)?);
}
files.sort();
files.dedup();
Ok(files)
}
fn collect_discovered_rs_files(app_dir: &Path) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
let mut files = Vec::new();
for root in [app_dir.join("slabs"), app_dir.join("jobs")] {
if root.is_dir() {
collect_rs_recursive(&root, &mut files)?;
}
}
files.sort();
Ok(files)
}
fn collect_rs_recursive(
dir: &Path,
out: &mut Vec<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
for entry in fs::read_dir(dir)? {
let path = entry?.path();
if path.is_dir() {
collect_rs_recursive(&path, out)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
out.push(path);
}
}
Ok(())
}
async fn run_tailwind(app_dir: &Path, watch: bool) -> Result<(), Box<dyn std::error::Error>> {
let (input, output) = ensure_tailwind_paths(app_dir)?;
let mut cmd = Command::new("tailwindcss");
cmd.arg("-i").arg(&input).arg("-o").arg(&output);
if watch {
cmd.arg("--watch");
} else {
cmd.arg("--minify");
}
let status = cmd.status().await.map_err(|e| {
format!(
"failed to launch standalone `tailwindcss` binary ({e}). Install via `mise use github:tailwindlabs/tailwindcss`."
)
})?;
if !status.success() {
return Err(format!("tailwindcss exited with status {status}").into());
}
println!("Compiled Tailwind CSS -> {}", output.display());
Ok(())
}
async fn run_dev(
app_dir: &Path,
package: Option<String>,
bind: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
let pkg = match package {
Some(p) => {
validate_app_name(&p)?;
p
}
None => infer_package_name(app_dir)?,
};
let _ = run_tailwind(app_dir, false).await;
let (input, output) = ensure_tailwind_paths(app_dir)?;
let mut tw_child = Command::new("tailwindcss")
.arg("-i")
.arg(&input)
.arg("-o")
.arg(&output)
.arg("--watch")
.kill_on_drop(true)
.spawn()
.ok();
if tw_child.is_some() {
println!(
"[slabs dev] tailwind --watch running on {}",
input.display()
);
} else {
eprintln!("[slabs dev] warning: `tailwindcss` binary not found; skipping CSS watch");
}
let has_cargo_watch = Command::new("cargo")
.args(["watch", "--version"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await
.is_ok_and(|s| s.success());
let mut app_cmd = Command::new("cargo");
if has_cargo_watch {
println!("[slabs dev] starting `{pkg}` with `cargo watch` (auto-reloads on .rs edits)");
app_cmd.args([
"watch",
"-q",
"-w",
&app_dir.to_string_lossy(),
"-x",
&format!("run -p {pkg}"),
]);
} else {
println!(
"[slabs dev] starting `{pkg}` with `cargo run` (install `cargo-watch` for Rust auto-reload)"
);
app_cmd.args(["run", "-p", &pkg]);
}
if let Some(addr) = bind {
app_cmd.env("SLABS_BIND", addr);
}
let mut app_child = app_cmd.kill_on_drop(true).spawn()?;
tokio::select! {
status = app_child.wait() => {
if let Ok(s) = status {
println!("[slabs dev] app exited with {s}");
}
}
_ = tokio::signal::ctrl_c() => {
println!("\n[slabs dev] shutting down...");
}
}
let _ = app_child.kill().await;
if let Some(ref mut tw) = tw_child {
let _ = tw.kill().await;
}
Ok(())
}
#[derive(Debug, Clone)]
struct EphemeralSandbox {
root_dir: PathBuf,
db_path: PathBuf,
storage_dir: PathBuf,
seeded: bool,
}
#[derive(Debug)]
struct SandboxDirGuard(PathBuf);
impl Drop for SandboxDirGuard {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[cfg(unix)]
fn set_dir_private_if_unix(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(0o700);
fs::set_permissions(path, perms)?;
Ok(())
}
#[cfg(not(unix))]
fn set_dir_private_if_unix(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn new_ephemeral_sandbox_dir() -> PathBuf {
let generated = slabs_core::id::new("e");
let ulid_part = generated.strip_prefix("e_").unwrap_or(&generated);
#[cfg(unix)]
let base = PathBuf::from("/tmp");
#[cfg(not(unix))]
let base = std::env::temp_dir();
base.join(format!("slabs-ephemeral-{ulid_part}"))
}
fn ephemeral_secret_key() -> String {
let a = slabs_core::id::new("ephemeral");
let b = slabs_core::id::new("secret");
slabs_core::fingerprint(&[&a, &b])
}
fn pick_ephemeral_bind_addr(bind: Option<String>) -> Result<String, Box<dyn std::error::Error>> {
if let Some(addr) = bind {
return Ok(addr);
}
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
let port = listener.local_addr()?.port();
drop(listener);
Ok(format!("127.0.0.1:{port}"))
}
async fn prepare_ephemeral_sandbox(
app_dir: &Path,
sandbox_dir: &Path,
) -> Result<EphemeralSandbox, Box<dyn std::error::Error>> {
fs::create_dir_all(sandbox_dir)?;
set_dir_private_if_unix(sandbox_dir)?;
let storage_dir = sandbox_dir.join("storage");
fs::create_dir_all(&storage_dir)?;
let db_path = sandbox_dir.join("ephemeral.db");
let db_url = format!("sqlite://{}?mode=rwc", db_path.display());
let db = Db::connect(&db_url).await?;
let migrations_dir = app_dir.join("migrations");
if dir_has_sql_files(&migrations_dir) {
db.migrate_dir(&migrations_dir).await?;
} else {
db.init_system_tables().await?;
}
let seeds_path = app_dir.join("seeds.sql");
let seeded = if seeds_path.is_file() {
db.execute_sql_file(&seeds_path).await?;
true
} else {
false
};
db.checkpoint_and_close().await;
Ok(EphemeralSandbox {
root_dir: sandbox_dir.to_path_buf(),
db_path,
storage_dir,
seeded,
})
}
async fn run_dev_ephemeral(
app_dir: &Path,
package: Option<String>,
bind: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
let pkg = match package {
Some(p) => {
validate_app_name(&p)?;
p
}
None => infer_package_name(app_dir)?,
};
let sandbox_dir = new_ephemeral_sandbox_dir();
let _cleanup_guard = SandboxDirGuard(sandbox_dir.clone());
let sandbox = prepare_ephemeral_sandbox(app_dir, &sandbox_dir).await?;
let bind_addr = pick_ephemeral_bind_addr(bind)?;
let secret_key = ephemeral_secret_key();
let db_url = format!("sqlite://{}?mode=rwc", sandbox.db_path.display());
if app_dir.join("assets/input.css").is_file()
&& !app_dir.join("assets/styles/app.css").is_file()
{
let _ = run_tailwind(app_dir, false).await;
}
println!("SLABS_EPHEMERAL_URL=http://{bind_addr}");
println!("SLABS_EPHEMERAL_DB={}", sandbox.db_path.display());
println!("SLABS_EPHEMERAL_SEEDED={}", sandbox.seeded);
let manifest_path = app_dir.join("Cargo.toml");
let mut app_cmd = Command::new("cargo");
app_cmd.args(["run", "-p", &pkg]);
if manifest_path.is_file() {
app_cmd.arg("--manifest-path").arg(&manifest_path);
}
app_cmd
.env("SLABS_ENV", "development")
.env("SLABS_BIND", &bind_addr)
.env("DATABASE_URL", &db_url)
.env("SLABS_STORAGE_DIR", &sandbox.storage_dir)
.env("SLABS_SECRET_KEY", &secret_key)
.kill_on_drop(true);
let mut app_child = app_cmd.spawn()?;
tokio::select! {
status = app_child.wait() => {
if let Ok(s) = status {
println!("[slabs dev --ephemeral] app exited with {s}");
}
}
_ = tokio::signal::ctrl_c() => {
println!("\n[slabs dev --ephemeral] shutting down and cleaning up {}...", sandbox.root_dir.display());
}
}
let _ = app_child.kill().await;
let _ = app_child.wait().await;
Ok(())
}
fn ensure_tailwind_paths(app_dir: &Path) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
let input = app_dir.join("assets/input.css");
let output = app_dir.join("assets/styles/app.css");
if let Some(parent) = output.parent() {
fs::create_dir_all(parent)?;
}
if !input.exists() {
fs::create_dir_all(app_dir.join("assets"))?;
fs::write(&input, "@import \"tailwindcss\";\n@source \"../slabs\";\n")?;
}
Ok((input, output))
}
fn infer_package_name_raw(cargo_toml: &Path) -> Option<String> {
let content = fs::read_to_string(cargo_toml).ok()?;
let mut in_package = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if trimmed.starts_with('[') {
in_package = trimmed == "[package]";
continue;
}
if !in_package {
continue;
}
if let Some(rest) = trimmed.strip_prefix("name") {
let rest = rest.trim_start();
if let Some(val) = rest.strip_prefix('=') {
let raw_val = val.split('#').next().unwrap_or("").trim();
let quoted = raw_val
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.or_else(|| {
raw_val
.strip_prefix('\'')
.and_then(|s| s.strip_suffix('\''))
});
if let Some(name) = quoted {
if !name.is_empty() {
return Some(name.to_string());
}
}
}
}
}
None
}
fn infer_package_name(app_dir: &Path) -> Result<String, Box<dyn std::error::Error>> {
let cargo_toml = app_dir.join("Cargo.toml");
if !cargo_toml.exists() {
return Err(format!(
"could not read {}; pass `--package <name>`",
cargo_toml.display()
)
.into());
}
let name = infer_package_name_raw(&cargo_toml)
.ok_or("could not infer `[package] name` from Cargo.toml; pass `--package <name>`")?;
validate_app_name(&name)?;
Ok(name)
}
fn list_dir(app_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
println!("Slabs in {}:", app_dir.display());
let slabs_dir = app_dir.join("slabs");
if slabs_dir.is_dir() {
let mut features: Vec<_> = fs::read_dir(&slabs_dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.is_dir())
.collect();
features.sort();
for feat in features {
let Some(feat_name) = feat.file_name().map(|n| n.to_string_lossy()) else {
continue;
};
let mut files: Vec<_> = fs::read_dir(&feat)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().and_then(|s| s.to_str()) == Some("rs"))
.collect();
files.sort();
for file in files {
let Some(stem) = file.file_stem().map(|n| n.to_string_lossy()) else {
continue;
};
println!(" slab {feat_name}.{stem} ({})", file.display());
}
}
}
let jobs_dir = app_dir.join("jobs");
if jobs_dir.is_dir() {
let mut files: Vec<_> = fs::read_dir(&jobs_dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().and_then(|s| s.to_str()) == Some("rs"))
.collect();
files.sort();
for file in files {
let Some(stem) = file.file_stem().map(|n| n.to_string_lossy()) else {
continue;
};
println!(" job {stem} ({})", file.display());
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SlabContract {
file: String,
feature: String,
name: String,
method: String,
path: String,
auth: String,
skip_csrf: bool,
tables_read: Vec<String>,
tables_written: Vec<String>,
jobs_enqueued: Vec<String>,
has_tests: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct JobContract {
file: String,
name: String,
tables_read: Vec<String>,
tables_written: Vec<String>,
jobs_enqueued: Vec<String>,
has_tests: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct StaticManifest {
slabs: Vec<SlabContract>,
jobs: Vec<JobContract>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ChangedSlabEntry {
file: String,
changes: Vec<String>,
security_warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ChangedJobEntry {
file: String,
changes: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct ManifestDiff {
added_slabs: Vec<SlabContract>,
removed_slabs: Vec<SlabContract>,
changed_slabs: Vec<ChangedSlabEntry>,
added_jobs: Vec<JobContract>,
removed_jobs: Vec<JobContract>,
changed_jobs: Vec<ChangedJobEntry>,
}
impl ManifestDiff {
fn is_empty(&self) -> bool {
self.added_slabs.is_empty()
&& self.removed_slabs.is_empty()
&& self.changed_slabs.is_empty()
&& self.added_jobs.is_empty()
&& self.removed_jobs.is_empty()
&& self.changed_jobs.is_empty()
}
}
impl StaticManifest {
fn to_json(&self) -> Value {
let slabs_json: Vec<Value> = self
.slabs
.iter()
.map(|s| {
json!({
"file": s.file,
"feature": s.feature,
"name": s.name,
"method": s.method,
"path": s.path,
"auth": s.auth,
"skip_csrf": s.skip_csrf,
"tables_read": s.tables_read,
"tables_written": s.tables_written,
"jobs_enqueued": s.jobs_enqueued,
"has_tests": s.has_tests,
})
})
.collect();
let jobs_json: Vec<Value> = self
.jobs
.iter()
.map(|j| {
json!({
"file": j.file,
"name": j.name,
"tables_read": j.tables_read,
"tables_written": j.tables_written,
"jobs_enqueued": j.jobs_enqueued,
"has_tests": j.has_tests,
})
})
.collect();
json!({
"slabs": slabs_json,
"jobs": jobs_json,
})
}
fn from_json(value: &Value) -> Result<Self, String> {
let mut slabs = Vec::new();
if let Some(arr) = value.get("slabs").and_then(Value::as_array) {
for item in arr {
slabs.push(SlabContract {
file: json_req_str(item, "file")?,
feature: json_opt_str(item, "feature"),
name: json_opt_str(item, "name"),
method: json_opt_str(item, "method"),
path: json_opt_str(item, "path"),
auth: json_opt_str(item, "auth"),
skip_csrf: item
.get("skip_csrf")
.and_then(Value::as_bool)
.unwrap_or(false),
tables_read: json_str_vec(item, "tables_read"),
tables_written: json_str_vec(item, "tables_written"),
jobs_enqueued: json_str_vec(item, "jobs_enqueued"),
has_tests: item
.get("has_tests")
.and_then(Value::as_bool)
.unwrap_or(false),
});
}
}
slabs.sort_by(|a, b| a.file.cmp(&b.file));
let mut jobs = Vec::new();
if let Some(arr) = value.get("jobs").and_then(Value::as_array) {
for item in arr {
jobs.push(JobContract {
file: json_req_str(item, "file")?,
name: json_opt_str(item, "name"),
tables_read: json_str_vec(item, "tables_read"),
tables_written: json_str_vec(item, "tables_written"),
jobs_enqueued: json_str_vec(item, "jobs_enqueued"),
has_tests: item
.get("has_tests")
.and_then(Value::as_bool)
.unwrap_or(false),
});
}
}
jobs.sort_by(|a, b| a.file.cmp(&b.file));
Ok(Self { slabs, jobs })
}
}
fn json_req_str(obj: &Value, key: &str) -> Result<String, String> {
obj.get(key)
.and_then(Value::as_str)
.map(ToOwned::to_owned)
.ok_or_else(|| format!("manifest JSON entry missing string field `{key}`"))
}
fn json_opt_str(obj: &Value, key: &str) -> String {
obj.get(key)
.and_then(Value::as_str)
.unwrap_or("")
.to_string()
}
fn json_str_vec(obj: &Value, key: &str) -> Vec<String> {
let mut vals: Vec<String> = obj
.get(key)
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(Value::as_str)
.map(ToOwned::to_owned)
.collect()
})
.unwrap_or_default();
vals.sort();
vals.dedup();
vals
}
fn non_test_code_string(content: &str) -> String {
let code_lines = strip_rust_file_code_lines(content);
let test_lines = compute_cfg_test_lines(content);
let mut out = String::new();
for (idx, line) in code_lines.iter().enumerate() {
if !test_lines.get(idx).copied().unwrap_or(false) {
out.push_str(line);
out.push('\n');
}
}
out
}
fn extract_call_first_string_arg(content: &str, patterns: &[&str]) -> Vec<(String, String)> {
let test_lines = compute_cfg_test_lines(content);
let chars: Vec<char> = content.chars().collect();
let mut results = Vec::new();
let mut i = 0usize;
let mut line_no = 1usize;
let mut block_comment_depth = 0usize;
let mut in_string = false;
let mut string_escaped = false;
let mut raw_string_hashes: Option<usize> = None;
while i < chars.len() {
let ch = chars[i];
if ch == '\n' {
line_no += 1;
i += 1;
continue;
}
if block_comment_depth > 0 {
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth += 1;
i += 2;
} else if ch == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
block_comment_depth -= 1;
i += 2;
} else {
i += 1;
}
continue;
}
if let Some(hashes) = raw_string_hashes {
if ch == '"' {
let mut matched = 0usize;
while matched < hashes
&& i + 1 + matched < chars.len()
&& chars[i + 1 + matched] == '#'
{
matched += 1;
}
if matched == hashes {
raw_string_hashes = None;
i += 1 + hashes;
continue;
}
}
i += 1;
continue;
}
if in_string {
if string_escaped {
string_escaped = false;
} else if ch == '\\' {
string_escaped = true;
} else if ch == '"' {
in_string = false;
}
i += 1;
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth = 1;
i += 2;
continue;
}
if ch == '\'' {
if i + 2 < chars.len() && chars[i + 1] == '\\' {
if let Some(end) = chars[i + 2..].iter().position(|&c| c == '\'') {
if end <= 6 {
i += end + 3;
continue;
}
}
} else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\n' {
i += 3;
continue;
}
}
if ch == 'r'
&& (i == 0
|| (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_')
|| (chars[i - 1] == 'b'
&& (i == 1 || (!chars[i - 2].is_alphanumeric() && chars[i - 2] != '_'))))
{
let mut hashes = 0usize;
let mut j = i + 1;
while j < chars.len() && chars[j] == '#' {
hashes += 1;
j += 1;
}
if j < chars.len() && chars[j] == '"' {
raw_string_hashes = Some(hashes);
i = j + 1;
continue;
}
}
if ch == '"' {
in_string = true;
i += 1;
continue;
}
let in_test = test_lines
.get(line_no.saturating_sub(1))
.copied()
.unwrap_or(false);
if !in_test {
let word_start = i == 0 || (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_');
let mut advanced = false;
for &pat in patterns {
let starts_ok = pat.starts_with('.') || word_start;
if starts_ok && chars_match_prefix(&chars, i, pat) {
let pat_len = pat.chars().count();
let pos = skip_rust_ws_and_comments(&chars, i + pat_len);
if pos < chars.len() && chars[pos] == '(' {
let mut scan = skip_rust_ws_and_comments(&chars, pos + 1);
let mut depth = 1usize;
while scan < chars.len() && depth > 0 {
scan = skip_rust_ws_and_comments(&chars, scan);
if scan >= chars.len() {
break;
}
if let Some((lit, end_pos)) = parse_rust_string_literal(&chars, scan) {
results.push((pat.to_string(), lit));
line_no += chars[i..end_pos].iter().filter(|&&c| c == '\n').count();
i = end_pos;
advanced = true;
break;
}
match chars[scan] {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
_ => {}
}
scan += 1;
}
if !advanced {
line_no += chars[i..i + pat_len].iter().filter(|&&c| c == '\n').count();
i += pat_len;
advanced = true;
}
break;
}
}
}
if advanced {
continue;
}
}
i += 1;
}
results
}
fn detect_auth_guard(non_test_code: &str) -> &'static str {
if non_test_code.contains("require_admin(") {
"require_admin"
} else if non_test_code.contains("require_write_auth(") {
"require_write_auth"
} else if non_test_code.contains("require_session(") {
"require_session"
} else if non_test_code.contains("require_auth(") {
"require_auth"
} else if non_test_code.contains("optional_session(") {
"optional_session"
} else if non_test_code.contains("optional_auth(") {
"optional_auth"
} else {
"public"
}
}
fn auth_strength(auth: &str) -> u8 {
match auth {
"require_admin" => 4,
"require_write_auth" => 3,
"require_session" | "require_auth" => 2,
"optional_session" | "optional_auth" => 1,
_ => 0,
}
}
fn extract_tables_from_sql_queries(queries: &[ExtractedSqlQuery]) -> (Vec<String>, Vec<String>) {
let mut reads = BTreeSet::new();
let mut writes = BTreeSet::new();
for q in queries {
let tokens = tokenize_sql_words(&q.sql);
let upper: Vec<String> = tokens.iter().map(|t| t.to_ascii_uppercase()).collect();
let mut ctes = BTreeSet::new();
for idx in 0..upper.len() {
if upper[idx] == "AS" && idx > 0 && upper.get(idx + 1).map(String::as_str) == Some("(")
{
let prev = clean_sql_table_ident(&tokens[idx - 1]);
if let Some(cte_name) = prev {
let is_cte =
idx >= 2 && matches!(upper[idx - 2].as_str(), "WITH" | "RECURSIVE" | ")");
if is_cte {
ctes.insert(cte_name);
}
}
}
}
let mut i = 0usize;
while i < upper.len() {
match upper[i].as_str() {
"INSERT" => {
let mut j = i + 1;
if upper.get(j).map(String::as_str) == Some("OR") {
j += 2;
}
if upper.get(j).map(String::as_str) == Some("INTO") {
if let Some(table) =
tokens.get(j + 1).and_then(|t| clean_sql_table_ident(t))
{
if !ctes.contains(&table) {
writes.insert(table);
}
}
i = j + 2;
continue;
}
}
"UPDATE" => {
let mut j = i + 1;
if upper.get(j).map(String::as_str) == Some("OR") {
j += 2;
}
if let Some(table) = tokens.get(j).and_then(|t| clean_sql_table_ident(t)) {
if !ctes.contains(&table) {
writes.insert(table);
}
}
i = j + 1;
continue;
}
"DELETE" => {
if upper.get(i + 1).map(String::as_str) == Some("FROM") {
if let Some(table) =
tokens.get(i + 2).and_then(|t| clean_sql_table_ident(t))
{
if !ctes.contains(&table) {
writes.insert(table);
}
}
i += 3;
continue;
}
}
"FROM" | "JOIN" => {
if let Some(table) = tokens.get(i + 1).and_then(|t| clean_sql_table_ident(t)) {
if !ctes.contains(&table) {
reads.insert(table);
}
}
i += 2;
continue;
}
_ => {}
}
i += 1;
}
}
(reads.into_iter().collect(), writes.into_iter().collect())
}
fn clean_sql_table_ident(raw: &str) -> Option<String> {
let trimmed = raw
.trim()
.trim_matches(|c| c == '"' || c == '`' || c == '(' || c == ')');
let without_schema = trimmed.rsplit('.').next().unwrap_or(trimmed);
let clean = without_schema.trim_matches(|c| c == '"' || c == '`');
if !is_valid_sql_identifier(clean) {
return None;
}
let upper = clean.to_ascii_uppercase();
if is_sql_keyword(&upper)
|| clean.eq_ignore_ascii_case("sqlite_master")
|| clean.to_ascii_lowercase().starts_with("pragma_")
{
return None;
}
Some(clean.to_string())
}
fn parse_slab_contract(rel_file: &str, feature: &str, stem: &str, content: &str) -> SlabContract {
let code_lines = strip_rust_file_code_lines(content);
let has_tests = code_lines.iter().any(|l| l.contains("#[cfg(test)]"));
let non_test_code = non_test_code_string(content);
let route_calls = extract_call_first_string_arg(
content,
&[
"SlabDef::get",
"SlabDef::post",
"SlabDef::put",
"SlabDef::patch",
"SlabDef::delete",
],
);
let (method, path) = route_calls.into_iter().next().map_or_else(
|| ("UNKNOWN".to_string(), String::new()),
|(pat, route_path)| {
let verb = pat
.strip_prefix("SlabDef::")
.unwrap_or("unknown")
.to_ascii_uppercase();
(verb, route_path)
},
);
let name = extract_call_first_string_arg(content, &[".name"])
.into_iter()
.next()
.map_or_else(|| format!("{feature}.{stem}"), |(_, n)| n);
let auth = detect_auth_guard(&non_test_code).to_string();
let skip_csrf = non_test_code.contains(".skip_csrf(");
let sql_queries = extract_sql_queries_from_source(content, true);
let (tables_read, tables_written) = extract_tables_from_sql_queries(&sql_queries);
let mut jobs_set: BTreeSet<String> = extract_call_first_string_arg(
content,
&[
"enqueue_in_tx",
"enqueue_with_options_in_tx",
"enqueue_with_options",
".enqueue",
],
)
.into_iter()
.map(|(_, job_name)| job_name)
.filter(|j| !j.is_empty())
.collect();
let jobs_enqueued: Vec<String> = std::mem::take(&mut jobs_set).into_iter().collect();
SlabContract {
file: rel_file.replace('\\', "/"),
feature: feature.to_string(),
name,
method,
path,
auth,
skip_csrf,
tables_read,
tables_written,
jobs_enqueued,
has_tests,
}
}
fn parse_job_contract(rel_file: &str, stem: &str, content: &str) -> JobContract {
let code_lines = strip_rust_file_code_lines(content);
let has_tests = code_lines.iter().any(|l| l.contains("#[cfg(test)]"));
let name = extract_call_first_string_arg(content, &["JobDef::new"])
.into_iter()
.next()
.map_or_else(|| stem.to_string(), |(_, n)| n);
let sql_queries = extract_sql_queries_from_source(content, true);
let (tables_read, tables_written) = extract_tables_from_sql_queries(&sql_queries);
let jobs_set: BTreeSet<String> = extract_call_first_string_arg(
content,
&[
"enqueue_in_tx",
"enqueue_with_options_in_tx",
"enqueue_with_options",
".enqueue",
],
)
.into_iter()
.map(|(_, job_name)| job_name)
.filter(|j| !j.is_empty())
.collect();
JobContract {
file: rel_file.replace('\\', "/"),
name,
tables_read,
tables_written,
jobs_enqueued: jobs_set.into_iter().collect(),
has_tests,
}
}
fn is_discovered_job_file(path: &Path) -> bool {
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
return false;
}
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
return false;
};
if stem == "mod" || stem.starts_with('_') {
return false;
}
path.parent()
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
== Some("jobs")
}
fn build_manifest(app_dir: &Path) -> Result<StaticManifest, Box<dyn std::error::Error>> {
let mut manifest = StaticManifest::default();
let dirs = if app_dir.join("slabs").is_dir() || app_dir.join("jobs").is_dir() {
vec![app_dir.to_path_buf()]
} else if manifest_is_workspace(&app_dir.join("Cargo.toml")) {
discover_workspace_member_dirs(app_dir)
} else {
vec![app_dir.to_path_buf()]
};
let canonical_base = fs::canonicalize(app_dir).unwrap_or_else(|_| app_dir.to_path_buf());
for dir in dirs {
let slabs_root = dir.join("slabs");
if slabs_root.is_dir() {
let mut rs_files = Vec::new();
collect_rs_recursive(&slabs_root, &mut rs_files)?;
rs_files.sort();
for file in rs_files {
if !is_discovered_slab_file(&file) {
continue;
}
let Some((feature, stem, _)) = extract_slab_from_path(&file) else {
continue;
};
let canonical_file = fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
let rel = canonical_file
.strip_prefix(&canonical_base)
.unwrap_or(&file)
.to_string_lossy()
.replace('\\', "/");
let content = fs::read_to_string(&file)?;
manifest
.slabs
.push(parse_slab_contract(&rel, &feature, &stem, &content));
}
}
let jobs_root = dir.join("jobs");
if jobs_root.is_dir() {
let mut rs_files = Vec::new();
collect_rs_recursive(&jobs_root, &mut rs_files)?;
rs_files.sort();
for file in rs_files {
if !is_discovered_job_file(&file) {
continue;
}
let Some(stem) = file.file_stem().and_then(|s| s.to_str()) else {
continue;
};
let canonical_file = fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
let rel = canonical_file
.strip_prefix(&canonical_base)
.unwrap_or(&file)
.to_string_lossy()
.replace('\\', "/");
let content = fs::read_to_string(&file)?;
manifest.jobs.push(parse_job_contract(&rel, stem, &content));
}
}
}
manifest.slabs.sort_by(|a, b| a.file.cmp(&b.file));
manifest.jobs.sort_by(|a, b| a.file.cmp(&b.file));
Ok(manifest)
}
fn build_manifest_from_git_ref(
app_dir: &Path,
git_ref: &str,
) -> Result<StaticManifest, Box<dyn std::error::Error>> {
validate_git_ref(git_ref)?;
let prefix_out = std::process::Command::new("git")
.arg("-C")
.arg(app_dir)
.args(["rev-parse", "--show-prefix"])
.output()?;
if !prefix_out.status.success() {
return Err(format!(
"`slabs manifest --diff {git_ref}` failed: not a git repository and file does not exist"
)
.into());
}
let prefix = String::from_utf8_lossy(&prefix_out.stdout)
.trim()
.to_string();
let mut ls_cmd = std::process::Command::new("git");
ls_cmd
.arg("-C")
.arg(app_dir)
.args(["ls-tree", "-r", "--name-only", git_ref]);
if !prefix.is_empty() {
ls_cmd.arg("--").arg(&prefix);
}
let ls_out = ls_cmd.output()?;
if !ls_out.status.success() {
return Err(format!(
"`git ls-tree {git_ref}` failed: {}",
String::from_utf8_lossy(&ls_out.stderr).trim()
)
.into());
}
let mut manifest = StaticManifest::default();
for repo_path in String::from_utf8_lossy(&ls_out.stdout).lines() {
let trimmed = repo_path.trim();
if trimmed.is_empty()
|| !Path::new(trimmed)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
{
continue;
}
let rel_str = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);
let rel_path = Path::new(rel_str);
if is_discovered_slab_file(rel_path) {
if let Some((feature, stem, _)) = extract_slab_from_path(rel_path) {
let show_out = std::process::Command::new("git")
.arg("-C")
.arg(app_dir)
.args(["show", &format!("{git_ref}:{trimmed}")])
.output()?;
if show_out.status.success() {
let content = String::from_utf8_lossy(&show_out.stdout);
manifest
.slabs
.push(parse_slab_contract(rel_str, &feature, &stem, &content));
}
}
} else if is_discovered_job_file(rel_path) {
if let Some(stem) = rel_path.file_stem().and_then(|s| s.to_str()) {
let show_out = std::process::Command::new("git")
.arg("-C")
.arg(app_dir)
.args(["show", &format!("{git_ref}:{trimmed}")])
.output()?;
if show_out.status.success() {
let content = String::from_utf8_lossy(&show_out.stdout);
manifest
.jobs
.push(parse_job_contract(rel_str, stem, &content));
}
}
}
}
manifest.slabs.sort_by(|a, b| a.file.cmp(&b.file));
manifest.jobs.sort_by(|a, b| a.file.cmp(&b.file));
Ok(manifest)
}
fn diff_manifests(baseline: &StaticManifest, current: &StaticManifest) -> ManifestDiff {
let mut diff = ManifestDiff::default();
let base_slabs: BTreeMap<&str, &SlabContract> = baseline
.slabs
.iter()
.map(|s| (s.file.as_str(), s))
.collect();
let curr_slabs: BTreeMap<&str, &SlabContract> =
current.slabs.iter().map(|s| (s.file.as_str(), s)).collect();
for (file, curr) in &curr_slabs {
match base_slabs.get(file) {
None => diff.added_slabs.push((*curr).clone()),
Some(base) => {
let mut changes = Vec::new();
let mut security_warnings = Vec::new();
if base.method != curr.method {
changes.push(format!("method: {} -> {}", base.method, curr.method));
}
if base.path != curr.path {
changes.push(format!("path: {} -> {}", base.path, curr.path));
}
if base.auth != curr.auth {
if auth_strength(&curr.auth) < auth_strength(&base.auth) {
security_warnings.push(format!(
"[SECURITY] auth weakened: {} -> {}",
base.auth, curr.auth
));
} else {
changes.push(format!("auth: {} -> {}", base.auth, curr.auth));
}
}
if base.skip_csrf != curr.skip_csrf {
if !base.skip_csrf && curr.skip_csrf {
security_warnings
.push("[SECURITY] skip_csrf enabled: false -> true".to_string());
} else {
changes.push(format!(
"skip_csrf: {} -> {}",
base.skip_csrf, curr.skip_csrf
));
}
}
if base.tables_read != curr.tables_read {
changes.push(format!(
"tables_read: [{}] -> [{}]",
base.tables_read.join(", "),
curr.tables_read.join(", ")
));
}
if base.tables_written != curr.tables_written {
changes.push(format!(
"tables_written: [{}] -> [{}]",
base.tables_written.join(", "),
curr.tables_written.join(", ")
));
}
if base.jobs_enqueued != curr.jobs_enqueued {
changes.push(format!(
"jobs_enqueued: [{}] -> [{}]",
base.jobs_enqueued.join(", "),
curr.jobs_enqueued.join(", ")
));
}
if base.has_tests != curr.has_tests {
changes.push(format!(
"has_tests: {} -> {}",
base.has_tests, curr.has_tests
));
}
if !changes.is_empty() || !security_warnings.is_empty() {
diff.changed_slabs.push(ChangedSlabEntry {
file: (*file).to_string(),
changes,
security_warnings,
});
}
}
}
}
for (file, base) in &base_slabs {
if !curr_slabs.contains_key(file) {
diff.removed_slabs.push((*base).clone());
}
}
let base_jobs: BTreeMap<&str, &JobContract> =
baseline.jobs.iter().map(|j| (j.file.as_str(), j)).collect();
let curr_jobs: BTreeMap<&str, &JobContract> =
current.jobs.iter().map(|j| (j.file.as_str(), j)).collect();
for (file, curr) in &curr_jobs {
match base_jobs.get(file) {
None => diff.added_jobs.push((*curr).clone()),
Some(base) => {
let mut changes = Vec::new();
if base.name != curr.name {
changes.push(format!("name: {} -> {}", base.name, curr.name));
}
if base.tables_read != curr.tables_read {
changes.push(format!(
"tables_read: [{}] -> [{}]",
base.tables_read.join(", "),
curr.tables_read.join(", ")
));
}
if base.tables_written != curr.tables_written {
changes.push(format!(
"tables_written: [{}] -> [{}]",
base.tables_written.join(", "),
curr.tables_written.join(", ")
));
}
if base.jobs_enqueued != curr.jobs_enqueued {
changes.push(format!(
"jobs_enqueued: [{}] -> [{}]",
base.jobs_enqueued.join(", "),
curr.jobs_enqueued.join(", ")
));
}
if base.has_tests != curr.has_tests {
changes.push(format!(
"has_tests: {} -> {}",
base.has_tests, curr.has_tests
));
}
if !changes.is_empty() {
diff.changed_jobs.push(ChangedJobEntry {
file: (*file).to_string(),
changes,
});
}
}
}
}
for (file, base) in &base_jobs {
if !curr_jobs.contains_key(file) {
diff.removed_jobs.push((*base).clone());
}
}
diff
}
fn format_tables_rw(reads: &[String], writes: &[String]) -> String {
match (reads.is_empty(), writes.is_empty()) {
(true, true) => "-".to_string(),
(false, true) => format!("R: {}", reads.join(", ")),
(true, false) => format!("W: {}", writes.join(", ")),
(false, false) => format!("R: {} | W: {}", reads.join(", "), writes.join(", ")),
}
}
fn format_manifest_table(manifest: &StaticManifest) -> String {
let mut out = String::new();
if manifest.slabs.is_empty() {
out.push_str("No slabs discovered.\n");
} else {
let rows: Vec<Vec<String>> = manifest
.slabs
.iter()
.map(|s| {
let auth_col = if s.skip_csrf {
format!("{} (skip_csrf)", s.auth)
} else {
s.auth.clone()
};
let jobs_col = if s.jobs_enqueued.is_empty() {
"-".to_string()
} else {
s.jobs_enqueued.join(", ")
};
vec![
s.method.clone(),
s.path.clone(),
auth_col,
format_tables_rw(&s.tables_read, &s.tables_written),
jobs_col,
if s.has_tests { "yes" } else { "no" }.to_string(),
s.file.clone(),
]
})
.collect();
out.push_str(&render_table(
&[
"METHOD",
"PATH",
"AUTH",
"TABLES (R/W)",
"JOBS",
"TESTS",
"FILE",
],
&rows,
&[false, false, false, false, false, false, false],
));
}
if !manifest.jobs.is_empty() {
out.push('\n');
let job_rows: Vec<Vec<String>> = manifest
.jobs
.iter()
.map(|j| {
let enq = if j.jobs_enqueued.is_empty() {
"-".to_string()
} else {
j.jobs_enqueued.join(", ")
};
vec![
j.name.clone(),
format_tables_rw(&j.tables_read, &j.tables_written),
enq,
if j.has_tests { "yes" } else { "no" }.to_string(),
j.file.clone(),
]
})
.collect();
out.push_str(&render_table(
&["JOB", "TABLES (R/W)", "ENQUEUES", "TESTS", "FILE"],
&job_rows,
&[false, false, false, false, false],
));
}
out
}
fn format_manifest_diff(diff: &ManifestDiff) -> String {
if diff.is_empty() {
return "No manifest changes detected.\n".to_string();
}
let mut out = String::new();
for s in &diff.added_slabs {
let _ = writeln!(
out,
"+ ADDED {} {} [{}] ({})",
s.method, s.path, s.auth, s.file
);
}
for s in &diff.removed_slabs {
let _ = writeln!(
out,
"- REMOVED {} {} [{}] ({})",
s.method, s.path, s.auth, s.file
);
}
for c in &diff.changed_slabs {
let mut parts = c.security_warnings.clone();
parts.extend(c.changes.clone());
let _ = writeln!(out, "~ CHANGED {} {}", c.file, parts.join("; "));
}
for j in &diff.added_jobs {
let _ = writeln!(out, "+ ADDED job {} ({})", j.name, j.file);
}
for j in &diff.removed_jobs {
let _ = writeln!(out, "- REMOVED job {} ({})", j.name, j.file);
}
for c in &diff.changed_jobs {
let _ = writeln!(out, "~ CHANGED {} {}", c.file, c.changes.join("; "));
}
out
}
fn manifest_diff_to_json(diff: &ManifestDiff) -> Value {
let added_slabs: Vec<Value> = diff
.added_slabs
.iter()
.map(|s| json!({ "file": s.file, "method": s.method, "path": s.path, "auth": s.auth }))
.collect();
let removed_slabs: Vec<Value> = diff
.removed_slabs
.iter()
.map(|s| json!({ "file": s.file, "method": s.method, "path": s.path, "auth": s.auth }))
.collect();
let changed_slabs: Vec<Value> = diff
.changed_slabs
.iter()
.map(|c| {
json!({
"file": c.file,
"changes": c.changes,
"security_warnings": c.security_warnings,
})
})
.collect();
let added_jobs: Vec<Value> = diff
.added_jobs
.iter()
.map(|j| json!({ "file": j.file, "name": j.name }))
.collect();
let removed_jobs: Vec<Value> = diff
.removed_jobs
.iter()
.map(|j| json!({ "file": j.file, "name": j.name }))
.collect();
let changed_jobs: Vec<Value> = diff
.changed_jobs
.iter()
.map(|c| json!({ "file": c.file, "changes": c.changes }))
.collect();
json!({
"added_slabs": added_slabs,
"removed_slabs": removed_slabs,
"changed_slabs": changed_slabs,
"added_jobs": added_jobs,
"removed_jobs": removed_jobs,
"changed_jobs": changed_jobs,
})
}
fn run_manifest(
app_dir: &Path,
json_out: bool,
write_path: Option<&Path>,
diff_target: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
let current = build_manifest(app_dir)?;
if let Some(target_path) = write_path {
if let Some(parent) = target_path.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
let serialized = format!("{}\n", serde_json::to_string_pretty(¤t.to_json())?);
fs::write(target_path, serialized)?;
println!("Wrote manifest snapshot to {}", target_path.display());
if diff_target.is_none() && !json_out {
return Ok(());
}
}
if let Some(target) = diff_target {
let candidate_path = Path::new(target);
let baseline = if candidate_path.is_file() {
let raw = fs::read_to_string(candidate_path)?;
let parsed: Value = serde_json::from_str(&raw)?;
StaticManifest::from_json(&parsed)?
} else {
build_manifest_from_git_ref(app_dir, target)?
};
let diff = diff_manifests(&baseline, ¤t);
if json_out {
println!(
"{}",
serde_json::to_string_pretty(&manifest_diff_to_json(&diff))?
);
} else {
print!("{}", format_manifest_diff(&diff));
}
return Ok(());
}
if json_out {
println!("{}", serde_json::to_string_pretty(¤t.to_json())?);
} else {
print!("{}", format_manifest_table(¤t));
}
Ok(())
}
fn normalize_base_url(raw: &str) -> Result<String, String> {
let trimmed = raw.trim().trim_end_matches('/');
let rest = trimmed
.strip_prefix("http://")
.or_else(|| trimmed.strip_prefix("https://"))
.ok_or_else(|| {
format!("invalid base URL `{raw}`: must start with `http://` or `https://`")
})?;
if rest.is_empty() || rest.chars().any(char::is_whitespace) {
return Err(format!("invalid base URL `{raw}`"));
}
Ok(trimmed.to_string())
}
fn validate_incident_id(id: &str) -> Result<(), String> {
if id.is_empty() || id.len() > 128 {
return Err(format!(
"invalid incident ID `{id}`: must be 1 to 128 characters"
));
}
if !id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return Err(format!(
"invalid incident ID `{id}`: only ASCII letters, digits, `_`, and `-` are allowed"
));
}
Ok(())
}
fn build_http_client() -> Result<reqwest::Client, Box<dyn std::error::Error>> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.user_agent(concat!("slabs-cli/", env!("CARGO_PKG_VERSION")))
.build()?;
Ok(client)
}
fn apply_bearer_auth(req: reqwest::RequestBuilder, token: Option<&str>) -> reqwest::RequestBuilder {
match token.map(str::trim).filter(|t| !t.is_empty()) {
Some(t) => req.bearer_auth(t),
None => req,
}
}
async fn parse_json_response(
resp: reqwest::Response,
endpoint: &str,
) -> Result<Value, Box<dyn std::error::Error>> {
let status = resp.status();
let body = resp.text().await?;
if !status.is_success() {
let hint = if status == reqwest::StatusCode::UNAUTHORIZED
|| status == reqwest::StatusCode::NOT_FOUND
{
" (hint: pass `--token` or set `SLABS_METRICS_TOKEN` in staging/production)"
} else {
""
};
let snippet = truncate_str(body.trim(), 200);
if snippet.is_empty() {
return Err(format!("request to {endpoint} failed with HTTP {status}{hint}").into());
}
return Err(
format!("request to {endpoint} failed with HTTP {status}: {snippet}{hint}").into(),
);
}
if body.trim().is_empty() {
return Ok(json!({}));
}
let parsed: Value = serde_json::from_str(&body)
.map_err(|e| format!("invalid JSON response from {endpoint}: {e}"))?;
Ok(parsed)
}
async fn run_incidents_list(
base_url: &str,
token: Option<&str>,
status: IncidentStatusFilter,
limit: u32,
json_out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
let endpoint = format!(
"{base}/_slabs/incidents?status={}&limit={limit}",
status.as_str()
);
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let payload = parse_json_response(resp, &endpoint).await?;
if json_out {
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
print!("{}", format_incidents_list_table(&payload));
}
Ok(())
}
async fn run_incidents_show(
base_url: &str,
token: Option<&str>,
id: &str,
json_out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}");
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let payload = parse_json_response(resp, &endpoint).await?;
if json_out {
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
print!("{}", format_incident_detail(&payload));
}
Ok(())
}
async fn run_incidents_resolve(
base_url: &str,
token: Option<&str>,
id: &str,
sha: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/resolve");
let client = build_http_client()?;
let body = json!({ "resolved_in_sha": sha });
let req = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json")
.json(&body),
token,
);
let resp = req.send().await?;
let _payload = parse_json_response(resp, &endpoint).await?;
if let Some(commit) = sha {
println!("Resolved incident `{id}` (resolved_in_sha: {commit})");
} else {
println!("Resolved incident `{id}`");
}
Ok(())
}
async fn run_incidents_perf(
base_url: &str,
token: Option<&str>,
json_out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
let endpoint = format!("{base}/_slabs/metrics");
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let payload = parse_json_response(resp, &endpoint).await?;
if json_out {
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
print!("{}", format_perf_table(&payload));
}
Ok(())
}
fn value_str<'a>(obj: &'a Value, keys: &[&str]) -> Option<&'a str> {
for key in keys {
if let Some(s) = obj.get(*key).and_then(Value::as_str) {
if !s.is_empty() {
return Some(s);
}
}
}
None
}
fn value_u64(obj: &Value, keys: &[&str]) -> u64 {
for key in keys {
if let Some(v) = obj.get(*key) {
if let Some(n) = v.as_u64() {
return n;
}
if let Some(n) = v.as_i64().and_then(|i| u64::try_from(i).ok()) {
return n;
}
}
}
0
}
fn value_f64(obj: &Value, keys: &[&str]) -> f64 {
for key in keys {
if let Some(v) = obj.get(*key) {
if let Some(n) = v.as_f64() {
return n;
}
}
}
0.0
}
fn truncate_str(input: &str, max_chars: usize) -> String {
let clean: String = input
.chars()
.map(|c| {
if c == '\n' || c == '\r' || c == '\t' {
' '
} else {
c
}
})
.collect();
let count = clean.chars().count();
if count <= max_chars {
return clean;
}
if max_chars <= 3 {
return clean.chars().take(max_chars).collect();
}
let mut out: String = clean.chars().take(max_chars - 3).collect();
out.push_str("...");
out
}
fn render_table(headers: &[&str], rows: &[Vec<String>], right_align: &[bool]) -> String {
let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
for row in rows {
for (idx, cell) in row.iter().enumerate() {
if let Some(w) = widths.get_mut(idx) {
*w = (*w).max(cell.chars().count());
}
}
}
let mut out = String::new();
for (idx, header) in headers.iter().enumerate() {
if idx > 0 {
out.push_str(" ");
}
let width = widths[idx];
let is_last = idx + 1 == headers.len();
if right_align.get(idx).copied().unwrap_or(false) {
let _ = write!(out, "{header:>width$}");
} else if is_last {
out.push_str(header);
} else {
let _ = write!(out, "{header:<width$}");
}
}
out.push('\n');
for row in rows {
for (idx, cell) in row.iter().enumerate() {
if idx > 0 {
out.push_str(" ");
}
let width = widths[idx];
let is_last = idx + 1 == headers.len();
if right_align.get(idx).copied().unwrap_or(false) {
let _ = write!(out, "{cell:>width$}");
} else if is_last {
out.push_str(cell);
} else {
let _ = write!(out, "{cell:<width$}");
}
}
out.push('\n');
}
out
}
fn format_incidents_list_table(payload: &Value) -> String {
let items = payload
.get("incidents")
.and_then(Value::as_array)
.or_else(|| payload.as_array());
let Some(list) = items else {
return "No incidents found.\n".to_string();
};
if list.is_empty() {
return "No incidents found.\n".to_string();
}
let rows: Vec<Vec<String>> = list
.iter()
.map(|item| {
let id = value_str(item, &["id"]).unwrap_or("-").to_string();
let kind = value_str(item, &["kind"]).unwrap_or("-").to_string();
let occ = value_u64(item, &["occurrences", "count"]).to_string();
let source_file = value_str(item, &["source_file", "slab_name"])
.unwrap_or("-")
.to_string();
let route = value_str(item, &["route_pattern", "route"])
.unwrap_or("-")
.to_string();
let err_msg = truncate_str(
value_str(item, &["error_message", "message"]).unwrap_or("-"),
64,
);
vec![id, kind, occ, source_file, route, err_msg]
})
.collect();
render_table(
&[
"ID",
"KIND",
"OCCURRENCES",
"SOURCE_FILE",
"ROUTE",
"ERROR_MESSAGE",
],
&rows,
&[false, false, true, false, false, false],
)
}
fn format_incident_detail(payload: &Value) -> String {
let item = payload
.get("incident")
.filter(|v| v.is_object())
.unwrap_or(payload);
let mut out = String::new();
let _ = writeln!(
out,
"ID: {}",
value_str(item, &["id"]).unwrap_or("-")
);
if let Some(status) = value_str(item, &["status"]) {
let _ = writeln!(out, "Status: {status}");
}
let _ = writeln!(
out,
"Kind: {}",
value_str(item, &["kind"]).unwrap_or("-")
);
let _ = writeln!(
out,
"Occurrences: {}",
value_u64(item, &["occurrences", "count"])
);
if let Some(fp) = value_str(item, &["fingerprint"]) {
let _ = writeln!(out, "Fingerprint: {fp}");
}
let _ = writeln!(
out,
"Source File: {}",
value_str(item, &["source_file", "slab_name"]).unwrap_or("-")
);
let _ = writeln!(
out,
"Route Pattern: {}",
value_str(item, &["route_pattern", "route"]).unwrap_or("-")
);
if let Some(code) = item.get("status_code").and_then(Value::as_i64) {
let _ = writeln!(out, "Status Code: {code}");
}
let _ = writeln!(
out,
"Git SHA: {}",
value_str(item, &["git_sha"]).unwrap_or("-")
);
if let Some(first) = value_str(item, &["first_seen_at"]) {
let _ = writeln!(out, "First Seen: {first}");
}
if let Some(last) = value_str(item, &["last_seen_at"]) {
let _ = writeln!(out, "Last Seen: {last}");
}
if let Some(resolved_sha) = value_str(item, &["resolved_in_sha"]) {
let _ = writeln!(out, "Resolved SHA: {resolved_sha}");
}
let _ = writeln!(
out,
"Error Message: {}",
value_str(item, &["error_message", "message"]).unwrap_or("-")
);
let context_val = item.get("context_json").or_else(|| item.get("context"));
if let Some(ctx) = context_val.filter(|v| !v.is_null()) {
let formatted_ctx = match ctx {
Value::String(s) => serde_json::from_str::<Value>(s)
.ok()
.and_then(|v| serde_json::to_string_pretty(&v).ok())
.unwrap_or_else(|| s.clone()),
other => serde_json::to_string_pretty(other).unwrap_or_else(|_| other.to_string()),
};
if !formatted_ctx.trim().is_empty() {
let _ = writeln!(out, "\nContext:\n{formatted_ctx}");
}
}
if let Some(detail) = value_str(item, &["detail"]) {
let _ = writeln!(out, "\nDetail:\n{detail}");
}
let repro = value_str(item, &["repro_hint"]).or_else(|| value_str(payload, &["repro_hint"]));
if let Some(hint) = repro {
let _ = writeln!(out, "\nRepro Hint:\n{hint}");
}
let repro_test =
value_str(item, &["repro_test"]).or_else(|| value_str(payload, &["repro_test"]));
if let Some(skeleton) = repro_test {
let _ = writeln!(out, "\nRepro Test (paste into source_file):\n{skeleton}");
}
out
}
fn format_ms(ms: f64) -> String {
if (ms - ms.round()).abs() < 0.05 {
format!("{:.0}ms", ms.round())
} else {
format!("{ms:.1}ms")
}
}
fn format_perf_table(payload: &Value) -> String {
let mut out = String::new();
let routes = payload
.get("routes")
.and_then(Value::as_array)
.or_else(|| payload.pointer("/http/routes").and_then(Value::as_array))
.or_else(|| payload.get("per_route").and_then(Value::as_array));
if let Some(route_list) = routes.filter(|r| !r.is_empty()) {
let mut entries: Vec<(&Value, f64, f64, u64)> = route_list
.iter()
.map(|r| {
let p95 = value_f64(r, &["p95_ms", "p95"]);
let max = value_f64(r, &["max_ms", "max"]);
let reqs = value_u64(r, &["requests", "requests_total", "count"]);
(r, p95, max, reqs)
})
.collect();
entries.sort_by(|a, b| {
b.1.total_cmp(&a.1)
.then_with(|| b.2.total_cmp(&a.2))
.then_with(|| b.3.cmp(&a.3))
});
let rows: Vec<Vec<String>> = entries
.into_iter()
.map(|(item, p95, max, reqs)| {
let source_file = value_str(item, &["source_file", "slab", "name"])
.unwrap_or("-")
.to_string();
let method = value_str(item, &["method"]).unwrap_or("");
let route = value_str(item, &["route_pattern", "route", "path"]).unwrap_or("-");
let method_route = if method.is_empty() {
route.to_string()
} else {
format!("{method} {route}")
};
let p50 = value_f64(item, &["p50_ms", "p50"]);
let p99 = value_f64(item, &["p99_ms", "p99"]);
let slow = value_u64(item, &["slow_count", "slow_requests", "slow"]);
let err_5xx = value_u64(item, &["errors_5xx", "status_5xx", "5xx"]);
vec![
source_file,
method_route,
format_ms(p50),
format_ms(p95),
format_ms(p99),
format_ms(max),
slow.to_string(),
err_5xx.to_string(),
reqs.to_string(),
]
})
.collect();
out.push_str(&render_table(
&[
"SOURCE_FILE",
"METHOD ROUTE",
"P50",
"P95",
"P99",
"MAX",
"SLOW",
"5XX",
"REQS",
],
&rows,
&[false, false, true, true, true, true, true, true, true],
));
} else {
out.push_str("No per-route latency metrics recorded yet.\n");
}
out.push('\n');
if let Some(http) = payload.get("http").filter(|v| v.is_object()) {
let reqs = value_u64(http, &["requests_total"]);
let err_5xx = value_u64(http, &["errors_5xx_total"]);
let avg = value_f64(http, &["avg_latency_ms"]);
let _ = writeln!(
out,
"HTTP: requests={reqs} errors_5xx={err_5xx} avg_latency={}",
format_ms(avg)
);
}
if let Some(jobs) = payload.get("jobs").filter(|v| v.is_object()) {
let pending = value_u64(jobs, &["pending"]);
let running = value_u64(jobs, &["running"]);
let dead = value_u64(jobs, &["dead"]);
let completed = value_u64(jobs, &["completed"]);
let _ = writeln!(
out,
"Jobs: pending={pending} running={running} dead={dead} completed={completed}"
);
}
let open_incidents = payload
.get("incidents")
.filter(|v| v.is_object())
.map(|inc| value_u64(inc, &["active", "open", "open_count", "count"]))
.or_else(|| payload.get("open_incidents").and_then(Value::as_u64))
.unwrap_or(0);
let _ = writeln!(out, "Incidents: open={open_incidents}");
if let Some(realtime) = payload.get("realtime").filter(|v| v.is_object()) {
let topics = value_u64(realtime, &["active_topics"]);
let _ = writeln!(out, "Realtime: active_topics={topics}");
}
out
}
const SKILL_ADD_SLAB: &str = r#"---
name: add-slab
description: End-to-end procedure for creating a new self-contained HTTP Transaction Script in a Slabs application. Use when adding any new endpoint, page, or HTMX fragment handler.
---
# Add a slab
Follow every step in order. Do not create `models/`, `controllers/`, `repositories/`, `services/`, or a central `routes.rs`, and do not edit `src/lib.rs` to wire up the route.
## 1. Inspect the schema
Read `schema.sql` in the application directory before writing any SQL. Confirm exact table names, column types, foreign keys, and indexes.
## 2. Create the slab file
Place the file at `slabs/<feature>/<action>.rs` (for example `slabs/cards/create_card.rs`), or generate a starter with:
```bash
slabs new slab <feature> <action> --method <get|post|put|patch|delete> --path <route>
```
Use Axum 0.8 path syntax: `{id}` for parameters and `{*path}` for wildcards. Never use `:id` or `*path`. Keep `<feature>` and `<action>` lowercase snake_case Rust identifiers.
## 3. Implement the Transaction Script
Structure the file from top to bottom:
1. `pub fn slab() -> SlabDef` with `.name("<feature>.<action>")` and `.summary("...")`.
2. Local `Input` and `Output` structs: duplicate small read queries and DTOs freely across slabs instead of creating shared `models/` or `services/` abstractions, but **never** duplicate security invariants or multi-step write state machines across sibling API and HTML slabs (handle content negotiation in one slab or extract feature-local `slabs/<feature>/_helpers.rs`).
3. `async fn handle(...)`:
- Put authentication and rate-limit guards on line 1 (`ctx.auth.require_session(&jar).await?`, `require_admin`, `require_auth`, `require_write_auth`, and `ctx.rate_limit.check(&key, limit, window_secs)?` on auth or expensive routes).
- Verify resource ownership or role permissions against `session.user_id` before reading private data or mutating rows.
- Validate and trim inputs, returning `SlabError::validation(field, message)`, `SlabError::ValidationErrors`, or `SlabError::bad_request(message)`.
- Never use `.unwrap()` or `.expect()` in request handler code; propagate errors with `?`.
- For read-only `SELECT` queries, execute against `ctx.db.reader()`.
- For any multi-step write or write with side effects, open `let mut tx = ctx.db.begin().await?;` (`BEGIN IMMEDIATE` on the single writer pool).
- Use parameterized `sqlx::query` / `sqlx::query_as` only. Escape FTS5 search terms with `slabs::db::fts5_query`.
- Enqueue background jobs inside the transaction with `ctx.jobs.enqueue_in_tx(&mut tx, ...)` and queue webhooks with `ctx.webhooks.dispatch_in_tx(&mut tx, ...)`.
- For shared form edits where stale saves could overwrite concurrent changes, use the opt-in **Optimistic Offline Lock** pattern: add `version INTEGER NOT NULL DEFAULT 1` to the table, run `UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?`, and return `SlabError::conflict("record was modified by another user")` (`409 Conflict`) when `res.rows_affected() == 0`. Skip this pattern for append-only rows, hot counters, or CRDT collaborative documents.
- Commit with `tx.commit().await?;`.
- For HTML responses, render with `maud!`, `html::document(...)`, and `html::render_markdown(&untrusted_md)`. Avoid raw HTML; if a static snippet requires it, document why with `// slabs:allow-raw-html: <reason>`.
## 4. Add a co-located test
Add `#[cfg(test)] mod tests` at the bottom of the same slab file using `crate::test_app().await`.
## 5. Verify before finishing
```bash
slabs css
slabs fmt --check || slabs fmt
# Fast single-slab verification while iterating:
slabs check --slab <feature>/<action> --explain
# Full verification before opening a PR:
slabs check --no-docs --explain
```
"#;
const SKILL_ADD_MIGRATION: &str = r"---
name: add-migration
description: Procedure for adding or updating SQLite database schema migrations in a Slabs application and keeping schema.sql and offline SQLx metadata in sync.
---
# Add a database migration
Follow every step in order so `migrations/`, `schema.sql`, and any `.sqlx/` cache stay consistent and rollbacks remain safe.
## 1. Check existing migrations
List `migrations/` and read `schema.sql`. Do not modify an already-applied migration file; generate a new UTC-timestamped file with `slabs new migration <description>`.
## 2. Design for expand-and-contract rollbacks
- **Expand first:** add nullable columns, defaults, new tables, and new indexes so the previous container image continues to work if you roll back.
- **Contract later:** drop obsolete columns or tables in a follow-up migration after the new binary is stable.
## 3. Write the migration SQL
Run `slabs new migration <description>` to create `migrations/<YYYYMMDDHHMMSS>_<description>.sql` (UTC timestamps prevent collisions between parallel agents). Avoid colliding with the 12 framework system tables (`slabs_sessions`, `slabs_magic_links`, `slabs_access_tokens`, `slabs_jobs`, `slabs_mail_outbox`, `slabs_blobs`, `slabs_cache`, `slabs_webhooks`, `slabs_webhook_deliveries`, `slabs_idempotency_keys`, `slabs_audit_log`, `slabs_incidents`).
## 4. Apply migrations and refresh `schema.sql`
`slabs db migrate` refreshes `schema.sql` automatically from `migrations/` in local development (pass `--no-dump` or set `SLABS_ENV=staging|production` to skip). You can also regenerate `schema.sql` deterministically offline from `migrations/` without a live database:
```bash
slabs db migrate --database-url sqlite://dev.db?mode=rwc
# Or regenerate schema.sql deterministically offline from migrations/:
slabs db dump-schema
```
## 5. Refresh compile-time SQLx cache (if used)
```bash
slabs db prepare
```
## 6. Run the full verification suite
```bash
slabs check --no-docs
```
";
const SKILL_REVIEW_SLAB: &str = r#"---
name: review-slab
description: Audit a Slabs application or pull request for common agent and Rust pitfalls specific to the Slabs architecture. Use before merging or handing off a feature.
---
# Review a slab
Inspect every added or modified file in `slabs/` and `jobs/` against this checklist. Report concrete `file:line` references for every defect found.
## Architecture and discovery
- No `models/`, `controllers/`, `repositories/`, `services/`, or central `routes.rs` directories were added.
- `src/lib.rs` was not edited to register routes or jobs, and `test_app()` is gated behind `#[cfg(test)]`.
- Helper files inside `slabs/` or `jobs/` start with `_`.
- Duplicate small read queries and DTOs freely across slabs, but **never** duplicate security invariants or multi-step write state machines across sibling API and HTML slabs (handle content negotiation in one slab or extract feature-local `slabs/<feature>/_helpers.rs`).
- Every route path uses Axum 0.8 `{param}` and `{*wildcard}` syntax.
## Database and transactions
- Read-only `SELECT` queries use `ctx.db.reader()`.
- Multi-step writes and domain writes paired with jobs or webhooks use `let mut tx = ctx.db.begin().await?;`.
- All SQL uses parameterized binds (`.bind(...)`), with zero dynamic string interpolation.
- FTS5 search queries sanitize user input through `slabs::db::fts5_query`.
- Shared form updates use an opt-in Optimistic Offline Lock (`version INTEGER NOT NULL DEFAULT 1`, `WHERE id = ? AND version = ?`, returning `SlabError::conflict(...)` on `rows_affected() == 0`) or `fingerprint` check when stale writes could overwrite data.
- `schema.sql` matches the latest SQL in `migrations/`.
## Security and HTML
- Protected endpoints call `ctx.auth.require_session`, `require_admin`, `require_auth`, or `require_write_auth` on line 1 of `handle`, and verify resource ownership against `session.user_id`.
- Auth, magic-link, and expensive endpoints call `ctx.rate_limit.check(...)`.
- User-authored Markdown uses `html::render_markdown(&text)` rather than raw HTML.
- No hardcoded secrets exist anywhere in source or config files.
- `Cargo.toml` enforces `unsafe_code = "forbid"`.
## Reliability, formatting, and tests
- No `.unwrap()` or `.expect()` calls appear outside `#[cfg(test)]` in `slabs/` or `jobs/`.
- Every new slab includes a co-located `#[cfg(test)] mod tests` block using `crate::test_app().await`.
- Run `slabs manifest --diff HEAD` (or `--diff origin/main`) to inspect route, auth, table, and job diffs and catch `[SECURITY]` auth downgrades.
- Run `slabs doctor`, `slabs fmt --check`, and `slabs check --no-docs --strict-explain`.
"#;
const SKILL_DEPLOY_APP: &str = r#"---
name: deploy-app
description: Production deployment, zero-downtime rollout, and fast rollback procedure for a Slabs application on Kamal 2, Fly.io, or a bare Linux VPS with Caddy and systemd.
---
# Deploy a Slabs application
## 1. Pre-flight verification
```bash
slabs doctor
slabs check --no-docs
slabs css
```
Confirm `SLABS_ENV=production`, `SLABS_SECRET_KEY` (>= 32 random bytes), `SLABS_COOKIE_SECURE=true`, `SLABS_TRUST_PROXY=true`, and optional `SLABS_CORS_ORIGINS` are configured.
## 2. Expand-and-contract migrations and backup
Ensure new migrations keep the previous container image functional during a rollback, and back up SQLite (`sqlite3 /data/<app>.db "VACUUM INTO '/data/backup-pre-deploy.db'"` or verify `litestream snapshots`) before migrating.
## 3. Immutable SHA tags and deploy target
Generate config once via `slabs deploy init --target kamal|fly|vps` and tag images with the git SHA, never `:latest`.
- Single-volume SQLite + Litestream runs one writer at a time (Kamal 2 `boot.limit: 1` + `proxy.buffering` on `/health/ready` + 20s `SIGTERM` drain, or Fly.io `strategy = "immediate"`). On `SIGTERM`, Slabs drains active requests and runs `PRAGMA wal_checkpoint(TRUNCATE)` before exit.
## 4. Verify and roll back fast if needed
Check `GET /health/ready` and `GET /_slabs/metrics`. Roll back immediately on failure with `kamal rollback <sha>`, `fly releases rollback`, or flipping `/opt/<app>/current` and restarting `systemd`.
"#;
const SKILL_FIX_INCIDENT: &str = r"---
name: fix-incident
description: Closed-loop procedure for triaging, reproducing, and fixing production runtime errors and performance bottlenecks reported in slabs_incidents and /_slabs/metrics.
---
# Fix an incident
Follow every step in order to turn a production error or slow route into a verified pull request with a co-located regression test.
## 1. Pull active incidents and slowest routes
```bash
slabs incidents list --json
slabs incidents perf --json
```
`slabs incidents list` defaults to `--status active` (`open` and `reopened`). Pass `--status open|reopened|resolved|all` when needed. Prioritize active runtime errors (`http_5xx`, `panic`, `job_dead`, `user_bug_report`) by occurrence count, then inspect `slow_request`, `slow_job`, and the slowest `p95` routes.
## 2. Inspect the single incident
```bash
slabs incidents show <id>
```
Record `source_file` (for example `slabs/rooms/send_message.rs` or `jobs/send_email.rs`), `route_pattern`, `git_sha`, `fingerprint`, `context_json`, `detail`, `repro_hint`, and `repro_test`.
## 3. Read only that single source file and `schema.sql`
Read only `source_file` and `schema.sql`. Do not scan unrelated slabs or extract shared helper layers.
## 4. Diagnose the root cause
- **Runtime errors (`http_5xx`, `panic`, `job_dead`, `user_bug_report`):** check bounds checks, SQL constraints, invalid job JSON payloads, and unhandled upstream errors.
- **Performance bottlenecks (`slow_request`, `slow_job`, high `p95`):** run `Db::explain_query_plan` in a test to spot SQLite `SCAN` full table scans, remove N+1 queries inside loops, switch unbounded queries to `CursorPage`, and move CPU-heavy work into `tokio::task::spawn_blocking`.
## 5. Add a failing co-located test first
Paste and complete the `repro_test` skeleton from `slabs incidents show <id>` inside `#[cfg(test)] mod tests` in `source_file` using `crate::test_app().await` so it reproduces the failure or asserts an indexed query plan (`USING INDEX`).
## 6. Implement the fix, verify, open a PR, and resolve
1. Patch `source_file` (and add an expand-and-contract migration plus `slabs db dump-schema` if adding an index).
2. Run `slabs check`.
3. Open a pull request citing the incident ID and fingerprint.
4. Mark the incident resolved after deploy:
```bash
slabs incidents resolve <id> --sha <git_sha>
```
";
#[cfg(test)]
mod tests {
use super::*;
fn temp_test_dir(prefix: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("slabs_cli_{prefix}_{}", slabs_core::id::new("tst")));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn validates_rust_identifiers() {
assert!(validate_rust_ident("rooms").is_ok());
assert!(validate_rust_ident("rename_room_2").is_ok());
assert!(validate_rust_ident("").is_err());
assert!(validate_rust_ident("2rooms").is_err());
assert!(validate_rust_ident("RoomName").is_err());
assert!(validate_rust_ident("rename-room").is_err());
assert!(validate_rust_ident("../etc").is_err());
assert!(validate_rust_ident("match").is_err());
assert!(validate_rust_ident("async").is_err());
assert!(validate_rust_ident("unsafe").is_err());
assert!(validate_rust_ident("gen").is_err());
}
#[test]
fn validates_app_names() {
assert!(validate_app_name("my_app").is_ok());
assert!(validate_app_name("my-app-2").is_ok());
assert!(validate_app_name("").is_err());
assert!(validate_app_name("MyApp").is_err());
assert!(validate_app_name("1app").is_err());
assert!(validate_app_name("../escape").is_err());
assert!(validate_app_name("app;rm -rf /").is_err());
assert!(validate_app_name(&"a".repeat(64)).is_ok());
assert!(validate_app_name(&"a".repeat(65)).is_err());
}
#[test]
fn validates_route_paths() {
assert!(validate_route_path("/api/rooms/{room_id}").is_ok());
assert!(validate_route_path("/assets/{*path}").is_ok());
assert!(validate_route_path("api/rooms").is_err());
assert!(validate_route_path("/api/rooms with space").is_err());
assert!(validate_route_path("/api/\"quote").is_err());
assert!(validate_route_path("/api/\\slash").is_err());
assert!(validate_route_path("/api/line\nbreak").is_err());
}
#[test]
fn infers_package_name_strictly_from_package_section() {
let tmp = temp_test_dir("infer_pkg");
fs::write(
tmp.join("Cargo.toml"),
r#"
[[bin]]
name = "wrong_bin"
path = "src/main.rs"
[package]
version = "0.1.0"
name = "campfire" # inline comment
[dependencies]
name = "wrong_dep"
"#,
)
.unwrap();
assert_eq!(infer_package_name(&tmp).unwrap(), "campfire");
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"Invalid Name!\"\n",
)
.unwrap();
assert!(infer_package_name(&tmp).is_err());
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn security_scanner_catches_all_six_rules() {
let tmp = temp_test_dir("sec_scan");
fs::create_dir_all(tmp.join("slabs/items")).unwrap();
fs::create_dir_all(tmp.join("jobs")).unwrap();
fs::create_dir_all(tmp.join("src")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"vuln_app\"\nversion = \"0.1.0\"\n",
)
.unwrap();
let bad_slab = format!(
r#"
async fn bad() {{
let q = sqlx::query(&format!("SELECT * FROM t WHERE id = {{}}", 1));
let q2 = sqlx::query_as("SELECT * FROM " + "items");
let ok_sql = sqlx::query("UPDATE counters SET n = n + 1 WHERE id = ?");
let ok_multiline = sqlx::query_as(
"UPDATE slabs_jobs
SET attempts = attempts + 1
WHERE id = ?"
);
let h = {pre}("<b>x</b>");
// slabs:allow-raw-html: static icon
let ok_h = {pre}("<svg/>");
let s1 = "{stripe}1234567890";
let s2 = "{resend}1234567890abcdef1234";
let s3 = "{pem}PRIVATE KEY-----";
let s4 = "{dev}";
let _ = Some(1).unwrap();
{unsafe_kw} {{ }}
}}
"#,
pre = concat!("Pre", "Escaped"),
stripe = concat!("sk_", "live_"),
resend = concat!("re", "_"),
pem = concat!("-----", "BEGIN "),
dev = concat!("dev-only-change-me-", "in-production"),
unsafe_kw = concat!("un", "safe"),
);
fs::write(tmp.join("slabs/items/create_item.rs"), bad_slab).unwrap();
let bad_job = "async fn run() { let _ = Some(1).expect(\"boom\"); }\n";
fs::write(tmp.join("jobs/notify.rs"), bad_job).unwrap();
let report = scan_security(&tmp, false).unwrap();
let rules: Vec<&str> = report.findings.iter().map(|f| f.rule).collect();
assert_eq!(
rules.iter().filter(|&&r| r == "sql-injection").count(),
2,
"expected exactly 2 sql-injection findings (and not the SQL + 1 literal): {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "raw-html").count(),
1,
"expected 1 unannotated raw-html finding: {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "unsafe-code").count(),
2,
"expected Cargo.toml + unsafe block findings: {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "hardcoded-secret").count(),
4,
"expected 4 hardcoded secret findings: {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "panic-hazard").count(),
2,
"expected 2 panic-hazard findings across slabs/ and jobs/: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "missing-test" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 missing-test warning: {:?}",
report.findings
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn security_scanner_catches_new_upstream_rules_and_allows_safe_patterns() {
let tmp = temp_test_dir("sec_scan_new_rules");
fs::create_dir_all(tmp.join("slabs/webhooks")).unwrap();
fs::create_dir_all(tmp.join("slabs/realtime")).unwrap();
fs::create_dir_all(tmp.join("slabs/uploads")).unwrap();
fs::create_dir_all(tmp.join("slabs/pages")).unwrap();
fs::create_dir_all(tmp.join("slabs/pwa")).unwrap();
fs::create_dir_all(tmp.join("slabs/auth")).unwrap();
fs::create_dir_all(tmp.join("slabs/web")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"audit_app\"\nversion = \"0.1.0\"\n\n[lints.rust]\nunsafe_code = \"forbid\"\n",
)
.unwrap();
fs::write(
tmp.join("slabs/webhooks/inbound.rs"),
r#"
async fn bad_hooks(ctx: AppCtx, body: &[u8]) {
let _ = Webhooks::verify_incoming_hmac_sha256(&ctx.config.secret_key, body, "sha256=00", "sha256=");
let _ = Webhooks::verify_signed_timestamped_webhook(
&ctx.config.secret_key,
123,
300,
body,
"v1=00",
"v1=",
);
let _ = Webhooks::verify_incoming_hmac_sha256("whsec_dedicated", body, "sha256=00", "sha256=");
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/realtime/bad_ws.rs"),
r"
async fn handle(ws: WebSocketUpgrade) { let _ = ws; }
#[cfg(test)]
mod tests {}
",
)
.unwrap();
fs::write(
tmp.join("slabs/realtime/good_ws.rs"),
r"
async fn handle(ws: WebSocketUpgrade, headers: HeaderMap) {
let _ = validate_ws_origin(&headers);
let _ = ws;
}
#[cfg(test)]
mod tests {}
",
)
.unwrap();
fs::write(
tmp.join("slabs/uploads/bad_download.rs"),
r#"
async fn handle(ctx: AppCtx) {
let (_meta, _bytes) = ctx.storage.get("blb_1").await;
let _hdr = header::CONTENT_DISPOSITION;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/uploads/good_download.rs"),
r#"
async fn handle(ctx: AppCtx) {
let (meta, bytes) = ctx.storage.get_scoped("blb_1", None).await;
let _ = meta.into_safe_response(bytes, true);
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/pages/card.rs"),
r#"
fn render(color: &str, id: &str) {
let _ = maud! {
div style=(format!("color: {color}")) hx-vals=(format!("{{\"id\":\"{id}\"}}")) {}
};
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/pwa/service_worker.rs"),
r##"
const SW_JS: &str = r#"
self.addEventListener("fetch", (event) => {
event.respondWith(fetch(event.request));
});
"#;
#[cfg(test)]
mod tests {}
"##,
)
.unwrap();
fs::write(
tmp.join("slabs/auth/login.rs"),
r#"
async fn handle(ctx: AppCtx) {
let _ = ctx.auth.verify_password("pw", "hash").await;
let _ = ctx.auth.create_session("usr_1", "member", 30).await;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/web/signin.rs"),
r#"
async fn handle(ctx: AppCtx) {
let _ = ctx.auth.verify_password_constant_time("pw", Some("hash")).await;
let _ = ctx.auth.rotate_session("old", "usr_1", "member", 30).await;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
let report = scan_security(&tmp, false).unwrap();
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "master-key-reuse" && f.severity == Severity::Error)
.count(),
2,
"expected 2 master-key-reuse errors: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "ws-missing-origin-check" && f.severity == Severity::Error)
.count(),
1,
"expected 1 ws-missing-origin-check error: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "unsafe-blob-response" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 unsafe-blob-response warning: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "template-attr-injection" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 template-attr-injection warning: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "service-worker-origin" && f.severity == Severity::Error)
.count(),
1,
"expected 1 service-worker-origin error: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "password-timing-enum" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 password-timing-enum warning: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "session-fixation" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 session-fixation warning: {:?}",
report.findings
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn dockerfile_hardening_check_detects_missing_directives() {
let hardened = r"
FROM debian:bookworm-slim
RUN cargo build --release --locked
USER slabs
ENV SLABS_ENV=production
ENV SLABS_COOKIE_SECURE=true
HEALTHCHECK CMD curl -fsS http://127.0.0.1:3000/health/ready || exit 1
";
assert_eq!(
missing_dockerfile_hardening_tokens(hardened, None),
Vec::<&str>::new()
);
let priv_drop_dockerfile = r#"
FROM debian:bookworm-slim
RUN cargo build --release --locked
ENV SLABS_ENV=production
ENV SLABS_COOKIE_SECURE=true
HEALTHCHECK CMD curl -fsS "http://127.0.0.1:${PORT:-3000}/health/ready" || exit 1
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
"#;
let priv_drop_entrypoint = r#"#!/bin/sh
if [ "$(id -u)" = "0" ]; then
chown -R 10001:10001 /data
exec setpriv --reuid=10001 --regid=10001 --clear-groups "$0" "$@"
fi
exec /usr/local/bin/app
"#;
assert_eq!(
missing_dockerfile_hardening_tokens(priv_drop_dockerfile, Some(priv_drop_entrypoint)),
Vec::<&str>::new()
);
let root_user_dockerfile = r"
FROM debian:bookworm-slim
RUN cargo build --release --locked
USER root
ENV SLABS_ENV=production
ENV SLABS_COOKIE_SECURE=true
HEALTHCHECK CMD curl -fsS http://127.0.0.1:3000/health/ready || exit 1
";
assert_eq!(
missing_dockerfile_hardening_tokens(root_user_dockerfile, None),
vec!["non-root USER (or setpriv/gosu/su-exec privilege drop in docker-entrypoint.sh)"]
);
let weak = r"
FROM debian:bookworm-slim
# USER slabs
RUN cargo build --release
ENV SLABS_ENV=development
";
let missing = missing_dockerfile_hardening_tokens(weak, None);
assert_eq!(
missing,
vec![
"SLABS_ENV=production",
"SLABS_COOKIE_SECURE=true",
"--locked",
"/health/ready",
"non-root USER (or setpriv/gosu/su-exec privilege drop in docker-entrypoint.sh)",
]
);
}
#[test]
fn deploy_init_generates_kamal_fly_and_vps_templates() {
let tmp = temp_test_dir("deploy_init");
let kamal_files = scaffold_deploy(&tmp, "my-app", DeployTarget::Kamal, false).unwrap();
assert_eq!(kamal_files.len(), 1);
let kamal = fs::read_to_string(tmp.join("config/deploy.yml")).unwrap();
assert!(kamal.contains("path: /health/ready"));
assert!(kamal.contains("drain_timeout: 20"));
assert!(kamal.contains("buffering:"));
assert!(kamal.contains("PRAGMA wal_checkpoint(TRUNCATE)"));
assert!(kamal.contains("SLABS_ENV: production"));
assert!(kamal.contains("SLABS_COOKIE_SECURE: \"true\""));
assert!(kamal.contains("SLABS_TRUST_PROXY: \"true\""));
assert!(kamal.contains("kamal rollback"));
assert!(kamal.contains("limit: 1"));
assert!(kamal.contains("/var/lib/my-app/data:/data"));
assert!(kamal.contains("LITESTREAM_BUCKET"));
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Kamal, false).is_err());
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Kamal, true).is_ok());
let fly_files = scaffold_deploy(&tmp, "my-app", DeployTarget::Fly, false).unwrap();
assert_eq!(fly_files.len(), 1);
let fly = fs::read_to_string(tmp.join("fly.toml")).unwrap();
assert!(fly.contains("path = \"/health/ready\""));
assert!(fly.contains("kill_signal = \"SIGTERM\""));
assert!(fly.contains("kill_timeout = \"20s\""));
assert!(fly.contains("strategy = \"immediate\""));
assert!(fly.contains("destination = \"/data\""));
assert!(fly.contains("SLABS_ENV = \"production\""));
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Fly, false).is_err());
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Fly, true).is_ok());
let vps_files = scaffold_deploy(&tmp, "my-app", DeployTarget::Vps, false).unwrap();
assert_eq!(vps_files.len(), 2);
let caddy = fs::read_to_string(tmp.join("deploy/Caddyfile")).unwrap();
assert!(caddy.contains("reverse_proxy 127.0.0.1:3000"));
assert!(caddy.contains("health_uri /health/ready"));
let unit = fs::read_to_string(tmp.join("deploy/my-app.service")).unwrap();
assert!(unit.contains("KillSignal=SIGTERM"));
assert!(unit.contains("TimeoutStopSec=20s"));
assert!(unit.contains("NoNewPrivileges=true"));
assert!(unit.contains("ProtectSystem=strict"));
assert!(unit.contains("ReadWritePaths=/data"));
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Vps, false).is_err());
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Vps, true).is_ok());
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn scaffolded_app_slab_and_job_pass_rustfmt_and_security_scan() {
let tmp = temp_test_dir("scaffold_v04");
let app_dir = tmp.join("demo_app");
scaffold_app("demo_app", &app_dir).unwrap();
fs::write(
app_dir.join("slabs/pages/create_item.rs"),
render_slab_template("pages", "create_item", HttpMethod::Post, "/api/items"),
)
.unwrap();
fs::write(
app_dir.join("slabs/pages/list_items.rs"),
render_slab_template("pages", "list_items", HttpMethod::Get, "/api/items"),
)
.unwrap();
fs::create_dir_all(app_dir.join("slabs/support")).unwrap();
fs::write(
app_dir.join("slabs/support/report_bug.rs"),
render_bug_report_template("support", "report_bug"),
)
.unwrap();
fs::write(
app_dir.join("jobs/send_digest.rs"),
render_job_template("send_digest"),
)
.unwrap();
let mut rs_files = vec![
app_dir.join("build.rs"),
app_dir.join("src/lib.rs"),
app_dir.join("src/main.rs"),
];
rs_files.extend(collect_discovered_rs_files(&app_dir).unwrap());
let output = std::process::Command::new("rustfmt")
.args(["--edition", "2021", "--check"])
.args(&rs_files)
.output()
.expect("rustfmt must be available");
assert!(
output.status.success(),
"scaffolded templates failed rustfmt:\n{}",
String::from_utf8_lossy(&output.stdout)
);
let report = scan_security(&app_dir, false).unwrap();
assert_eq!(
report.error_count(),
0,
"scaffolded app must have 0 security errors: {:?}",
report.findings
);
assert_eq!(
report.warning_count(),
0,
"scaffolded app must have 0 security warnings: {:?}",
report.findings
);
let cargo_toml = fs::read_to_string(app_dir.join("Cargo.toml")).unwrap();
assert!(cargo_toml.contains("unsafe_code = \"forbid\""));
assert!(cargo_toml.contains("slabs-framework = \"0.5\""));
assert!(cargo_toml.contains("slabs-build = \"0.5\""));
assert!(!cargo_toml.contains("git = "));
let bug_slab = fs::read_to_string(app_dir.join("slabs/support/report_bug.rs")).unwrap();
assert!(bug_slab.contains("SlabDef::post(\"/support/report_bug\", handle)"));
assert!(bug_slab.contains("ctx.auth.require_session(&jar).await?"));
assert!(bug_slab.contains("ctx.rate_limit.check_pair("));
assert!(bug_slab.contains(".storage"));
assert!(bug_slab.contains("\"bug_report\""));
assert!(bug_slab.contains(".put_scoped("));
assert!(bug_slab.contains("user_bug_report"));
assert!(bug_slab.contains("pub fn bug_report_form(source_file: &str) -> Markup"));
assert!(bug_slab.contains("#[cfg(test)]"));
let lib_rs = fs::read_to_string(app_dir.join("src/lib.rs")).unwrap();
assert!(lib_rs.contains("#[cfg(test)]\npub async fn test_app()"));
assert!(lib_rs.contains(".with_schedules(collect_schedules())"));
let gitignore = fs::read_to_string(app_dir.join(".gitignore")).unwrap();
assert!(gitignore.contains("assets/styles/app.css"));
let dockerfile = fs::read_to_string(app_dir.join("Dockerfile")).unwrap();
assert!(dockerfile.contains("lukemathwalker/cargo-chef:latest-rust-1-slim"));
assert!(dockerfile.contains("cargo build --release --locked"));
assert!(dockerfile.contains("LITESTREAM_VERSION=v0.3.13"));
assert!(dockerfile.contains("ARG TAILWIND_VERSION=v4.1.4"));
assert!(dockerfile.contains("tailwindcss-linux-${TW_ARCH}"));
assert!(dockerfile.contains(
"/usr/local/bin/tailwindcss -i /app/assets/input.css -o /app/assets/styles/app.css --minify"
));
assert!(dockerfile.contains("ENV SLABS_ENV=production"));
assert!(dockerfile.contains("ENV SLABS_COOKIE_SECURE=true"));
assert!(dockerfile.contains("ENV SLABS_TRUST_PROXY=true"));
assert!(dockerfile.contains("/health/ready"));
let entrypoint = fs::read_to_string(app_dir.join("docker-entrypoint.sh")).unwrap();
assert!(entrypoint.contains("setpriv --reuid=10001 --regid=10001 --clear-groups"));
assert!(entrypoint.contains("SLABS_BIND"));
assert!(entrypoint.contains("litestream restore"));
assert!(entrypoint.contains("litestream replicate"));
assert_eq!(
missing_dockerfile_hardening_tokens(&dockerfile, Some(&entrypoint)),
Vec::<&str>::new()
);
let dockerignore = fs::read_to_string(app_dir.join(".dockerignore")).unwrap();
assert!(dockerignore.contains(".git"));
assert!(dockerignore.contains("target"));
assert!(dockerignore.contains(".env.*"));
assert!(dockerignore.contains("*.db-wal"));
let sw = fs::read_to_string(app_dir.join("slabs/pwa/service_worker.rs")).unwrap();
assert!(sw.contains("url.origin !== self.location.origin"));
assert!(sw.contains("try {"));
assert!(sw.contains("resolved.origin === self.location.origin"));
let icon = fs::read_to_string(app_dir.join("assets/icon.svg")).unwrap();
assert!(icon.contains("slabs-mark-cuts"));
assert!(icon.contains("slabs-mark-s"));
assert!(icon.contains("#D34516"));
assert!(icon.contains("#A6330E"));
assert!(icon.contains("#8C2A0B"));
let ci = fs::read_to_string(app_dir.join(".github/workflows/ci.yml")).unwrap();
assert!(ci.contains("permissions:\n contents: read"));
let add_slab_skill =
fs::read_to_string(app_dir.join(".claude/skills/add-slab/SKILL.md")).unwrap();
assert!(add_slab_skill.contains("slabs/<feature>/_helpers.rs"));
assert!(add_slab_skill.contains("security invariants"));
assert!(app_dir
.join(".claude/skills/add-migration/SKILL.md")
.exists());
let review_slab_skill =
fs::read_to_string(app_dir.join(".claude/skills/review-slab/SKILL.md")).unwrap();
assert!(review_slab_skill.contains("slabs/<feature>/_helpers.rs"));
assert!(review_slab_skill.contains("security invariants"));
assert!(app_dir.join(".claude/skills/deploy-app/SKILL.md").exists());
assert!(app_dir
.join(".claude/skills/fix-incident/SKILL.md")
.exists());
let create_slab = fs::read_to_string(app_dir.join("slabs/pages/create_item.rs")).unwrap();
assert!(create_slab.contains("let session = ctx.auth.require_session(&jar).await?;"));
assert!(create_slab.contains("#[cfg(test)]"));
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn validates_incident_ids_and_base_urls() {
assert!(validate_incident_id("inc_01JABC123").is_ok());
assert!(validate_incident_id("inc-42").is_ok());
assert!(validate_incident_id("").is_err());
assert!(validate_incident_id("../etc/passwd").is_err());
assert!(validate_incident_id("inc/123").is_err());
assert!(validate_incident_id("inc 123").is_err());
assert_eq!(
normalize_base_url("https://app.example.com///").unwrap(),
"https://app.example.com"
);
assert_eq!(
normalize_base_url("http://127.0.0.1:3000/").unwrap(),
"http://127.0.0.1:3000"
);
assert!(normalize_base_url("ftp://example.com").is_err());
assert!(normalize_base_url("http://").is_err());
}
#[test]
fn formats_incidents_list_detail_and_perf_tables() {
let list_payload = json!({
"incidents": [
{
"id": "inc_01TEST",
"kind": "http_5xx",
"occurrences": 7,
"source_file": "slabs/rooms/send_message.rs",
"route_pattern": "POST /api/rooms/{room_id}/messages",
"error_message": "UNIQUE constraint failed: messages.id"
}
]
});
let list_table = format_incidents_list_table(&list_payload);
assert!(list_table.contains("ID"));
assert!(list_table.contains("OCCURRENCES"));
assert!(list_table.contains("SOURCE_FILE"));
assert!(list_table.contains("inc_01TEST"));
assert!(list_table.contains("slabs/rooms/send_message.rs"));
assert!(list_table.contains("UNIQUE constraint failed"));
let show_payload = json!({
"id": "inc_01TEST",
"status": "open",
"kind": "slow_request",
"occurrences": 3,
"fingerprint": "fp_abc123",
"source_file": "slabs/cards/list_cards.rs",
"route_pattern": "GET /api/boards/{board_id}/cards",
"git_sha": "deadbeef",
"error_message": "request exceeded 500ms threshold",
"context_json": "{\"latency_ms\": 812}",
"detail": "SCAN cards",
"repro_hint": "curl -s http://127.0.0.1:3000/api/boards/brd_1/cards",
"repro_test": "#[tokio::test]\nasync fn reproduces_inc_01test() {\n let app = crate::test_app().await;\n}"
});
let detail = format_incident_detail(&show_payload);
assert!(detail.contains("Source File: slabs/cards/list_cards.rs"));
assert!(detail.contains("Route Pattern: GET /api/boards/{board_id}/cards"));
assert!(detail.contains("Git SHA: deadbeef"));
assert!(detail.contains("\"latency_ms\": 812"));
assert!(detail.contains("SCAN cards"));
assert!(detail.contains("Repro Hint:"));
assert!(detail.contains("Repro Test (paste into source_file):"));
assert!(detail.contains("reproduces_inc_01test"));
let perf_payload = json!({
"http": {
"requests_total": 120,
"errors_5xx_total": 2,
"avg_latency_ms": 42.5
},
"jobs": {
"pending": 4,
"running": 1,
"dead": 2,
"completed": 99
},
"incidents": {
"open": 3
},
"realtime": {
"active_topics": 5
},
"routes": [
{
"source_file": "slabs/pages/show_home.rs",
"method": "GET",
"route_pattern": "/",
"p50_ms": 4.0,
"p95_ms": 12.0,
"p99_ms": 18.0,
"max_ms": 22.0,
"slow_count": 0,
"errors_5xx": 0,
"requests": 100
},
{
"source_file": "slabs/cards/list_cards.rs",
"method": "GET",
"route_pattern": "/api/boards/{board_id}/cards",
"p50_ms": 90.0,
"p95_ms": 620.0,
"p99_ms": 840.0,
"max_ms": 910.0,
"slow_count": 5,
"errors_5xx": 2,
"requests": 20
}
]
});
let perf = format_perf_table(&perf_payload);
assert!(perf.contains("SOURCE_FILE"));
assert!(perf.contains("METHOD ROUTE"));
assert!(perf.contains("P95"));
let slow_idx = perf.find("slabs/cards/list_cards.rs").unwrap();
let fast_idx = perf.find("slabs/pages/show_home.rs").unwrap();
assert!(
slow_idx < fast_idx,
"routes must be ranked slowest first:\n{perf}"
);
assert!(perf.contains("Jobs: pending=4 running=1 dead=2 completed=99"));
assert!(perf.contains("Incidents: open=3"));
}
#[test]
fn parses_incidents_cli_subcommands() {
let default_list = Cli::try_parse_from(["slabs", "incidents", "list"]).unwrap();
assert!(matches!(
default_list.command,
Commands::Incidents {
action: IncidentsAction::List {
status: IncidentStatusFilter::Active,
limit: 50,
json: false,
..
}
}
));
for (raw, expected) in [
("active", IncidentStatusFilter::Active),
("open", IncidentStatusFilter::Open),
("reopened", IncidentStatusFilter::Reopened),
("resolved", IncidentStatusFilter::Resolved),
("all", IncidentStatusFilter::All),
] {
let parsed =
Cli::try_parse_from(["slabs", "incidents", "list", "--status", raw]).unwrap();
assert!(matches!(
parsed.command,
Commands::Incidents {
action: IncidentsAction::List { status, .. }
} if status == expected && status.as_str() == raw
));
}
let cli = Cli::try_parse_from([
"slabs",
"incidents",
"list",
"--url",
"https://demo.example.com",
"--token",
"tok_123",
"--status",
"reopened",
"--limit",
"25",
"--json",
])
.unwrap();
assert!(matches!(
cli.command,
Commands::Incidents {
action: IncidentsAction::List {
status: IncidentStatusFilter::Reopened,
limit: 25,
json: true,
..
}
}
));
let show =
Cli::try_parse_from(["slabs", "incidents", "show", "inc_01ABC", "--json"]).unwrap();
assert!(matches!(
show.command,
Commands::Incidents {
action: IncidentsAction::Show { json: true, .. }
}
));
let resolve = Cli::try_parse_from([
"slabs",
"incidents",
"resolve",
"inc_01ABC",
"--sha",
"abcdef1",
])
.unwrap();
assert!(matches!(
resolve.command,
Commands::Incidents {
action: IncidentsAction::Resolve { sha: Some(_), .. }
}
));
let perf = Cli::try_parse_from(["slabs", "incidents", "perf", "--json"]).unwrap();
assert!(matches!(
perf.command,
Commands::Incidents {
action: IncidentsAction::Perf { json: true, .. }
}
));
assert!(Cli::try_parse_from(["slabs", "incidents", "claim", "inc_01ABC"]).is_err());
assert!(Cli::try_parse_from(["slabs", "incidents", "link", "inc_01ABC"]).is_err());
assert!(Cli::try_parse_from(["slabs", "incidents", "ignore", "inc_01ABC"]).is_err());
assert!(Cli::try_parse_from(["slabs", "mcp"]).is_err());
assert!(
Cli::try_parse_from(["slabs", "incidents", "list", "--status", "in_progress"]).is_err()
);
assert!(
Cli::try_parse_from(["slabs", "incidents", "list", "--status", "ignored"]).is_err()
);
let bug_default = Cli::try_parse_from(["slabs", "new", "bug-report"]).unwrap();
assert!(matches!(
bug_default.command,
Commands::New {
kind: NewKind::BugReport { ref feature, ref name }
} if feature == "support" && name == "report_bug"
));
let bug_custom = Cli::try_parse_from([
"slabs",
"new",
"bug-report",
"--feature",
"feedback",
"--name",
"submit_issue",
])
.unwrap();
assert!(matches!(
bug_custom.command,
Commands::New {
kind: NewKind::BugReport { ref feature, ref name }
} if feature == "feedback" && name == "submit_issue"
));
let deploy_default =
Cli::try_parse_from(["slabs", "deploy", "init", "--target", "kamal"]).unwrap();
assert!(matches!(
deploy_default.command,
Commands::Deploy {
action: DeployAction::Init {
target: DeployTarget::Kamal,
force: false,
..
}
}
));
let deploy_force =
Cli::try_parse_from(["slabs", "deploy", "init", "--target", "fly", "--force"]).unwrap();
assert!(matches!(
deploy_force.command,
Commands::Deploy {
action: DeployAction::Init {
target: DeployTarget::Fly,
force: true,
..
}
}
));
assert!(Cli::try_parse_from([
"slabs", "deploy", "init", "--target", "fly", "--db", "postgres",
])
.is_err());
}
#[test]
fn parses_v05_harness_cli_flags_and_builds_nextest_filters() {
let check_changed =
Cli::try_parse_from(["slabs", "check", "--changed", "--base", "origin/main"]).unwrap();
assert!(matches!(
check_changed.command,
Commands::Check {
changed: true,
base: Some(ref b),
slab: None,
explain: false,
strict_explain: false,
..
} if b == "origin/main"
));
let check_slab = Cli::try_parse_from([
"slabs",
"check",
"--slab",
"rooms/send_message",
"--strict-explain",
])
.unwrap();
assert!(matches!(
check_slab.command,
Commands::Check {
changed: false,
slab: Some(ref s),
strict_explain: true,
..
} if s == "rooms/send_message"
));
let manifest_cmd = Cli::try_parse_from([
"slabs",
"manifest",
"--json",
"--write",
"manifest.json",
"--diff",
"HEAD",
])
.unwrap();
assert!(matches!(
manifest_cmd.command,
Commands::Manifest {
json: true,
write: Some(_),
diff: Some(ref d),
} if d == "HEAD"
));
let dev_eph =
Cli::try_parse_from(["slabs", "dev", "--ephemeral", "--bind", "127.0.0.1:4123"])
.unwrap();
assert!(matches!(
dev_eph.command,
Commands::Dev {
ephemeral: true,
bind: Some(ref b),
..
} if b == "127.0.0.1:4123"
));
assert_eq!(
parse_slab_selector("rooms/send_message").unwrap(),
("rooms".to_string(), "send_message".to_string())
);
assert!(parse_slab_selector("rooms").is_err());
assert!(parse_slab_selector("rooms/send-message").is_err());
assert!(parse_slab_selector("rooms/a/b").is_err());
assert_eq!(
build_nextest_slab_filter(&[("rooms".into(), "send_message".into())]),
"test(discovered_slabs::rooms::send_message)"
);
assert_eq!(
build_nextest_slab_filter(&[
("rooms".into(), "send_message".into()),
("cards".into(), "create_card".into()),
("rooms".into(), "send_message".into()),
]),
"test(discovered_slabs::cards::create_card) | test(discovered_slabs::rooms::send_message)"
);
let tmp = temp_test_dir("changed_classify");
fs::create_dir_all(tmp.join("slabs/rooms")).unwrap();
fs::create_dir_all(tmp.join("src")).unwrap();
fs::write(tmp.join("slabs/rooms/send_message.rs"), "// ok\n").unwrap();
fs::write(tmp.join("slabs/rooms/_helper.rs"), "// helper\n").unwrap();
fs::write(tmp.join("src/lib.rs"), "// shared\n").unwrap();
assert_eq!(
classify_changed_paths(&tmp, &[]),
ChangedSelection::NoChanges
);
let only_slabs =
classify_changed_paths(&tmp, &[PathBuf::from("slabs/rooms/send_message.rs")]);
assert!(matches!(only_slabs, ChangedSelection::OnlySlabs(ref list) if list.len() == 1));
let helper_changed = classify_changed_paths(
&tmp,
&[
PathBuf::from("slabs/rooms/send_message.rs"),
PathBuf::from("slabs/rooms/_helper.rs"),
],
);
assert!(matches!(
helper_changed,
ChangedSelection::SharedFilesChanged(_)
));
let src_changed = classify_changed_paths(&tmp, &[PathBuf::from("src/lib.rs")]);
assert!(matches!(
src_changed,
ChangedSelection::SharedFilesChanged(_)
));
let _ = fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn explain_check_catches_unindexed_scan_passes_indexed_and_honors_allow_annotation() {
let tmp = temp_test_dir("explain_gate");
fs::create_dir_all(tmp.join("migrations")).unwrap();
fs::create_dir_all(tmp.join("slabs/messages")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"explain_demo\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(
tmp.join("migrations/0001_init.sql"),
r"
CREATE TABLE messages (
id TEXT PRIMARY KEY NOT NULL,
room_id TEXT NOT NULL,
body TEXT NOT NULL
);
CREATE INDEX idx_messages_room_id ON messages(room_id);
",
)
.unwrap();
let bad_file = tmp.join("slabs/messages/search_unindexed.rs");
fs::write(
&bad_file,
r##"
async fn handle(ctx: AppCtx, q: &str) {
let _ = sqlx::query_as::<_, (String,)>(
"SELECT id FROM messages WHERE body = ?"
);
// slabs:allow-scan: intentional small-table scan
let _ = sqlx::query(
r#"SELECT id FROM messages WHERE body LIKE ?"#
);
}
#[cfg(test)]
mod tests {
async fn test_query() {
let _ = sqlx::query("SELECT id FROM messages WHERE body = ?");
}
}
"##,
)
.unwrap();
let good_file = tmp.join("slabs/messages/list_indexed.rs");
fs::write(
&good_file,
r#"
async fn handle(ctx: AppCtx) {
let _ = sqlx::query("SELECT id, body FROM messages WHERE room_id = ?");
}
"#,
)
.unwrap();
let report = evaluate_explain_check(&tmp, &[bad_file.clone(), good_file.clone()])
.await
.unwrap();
assert_eq!(report.files_checked, 2);
assert_eq!(report.queries_checked, 2);
assert_eq!(
report.findings.len(),
1,
"expected exactly 1 unindexed SCAN finding: {:?}",
report.findings
);
assert!(report.findings[0].plan_detail.contains("SCAN messages"));
assert!(
report.findings[0]
.index_hint
.contains("CREATE INDEX idx_messages_body ON messages(body);"),
"unexpected hint: {}",
report.findings[0].index_hint
);
assert!(
run_explain_check(&tmp, std::slice::from_ref(&bad_file), false)
.await
.is_ok()
);
assert!(run_explain_check(&tmp, &[bad_file], true).await.is_err());
assert!(run_explain_check(&tmp, &[good_file], true).await.is_ok());
let _ = fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn sql_schema_check_validates_dml_catches_bad_sql_and_honors_allow_annotation() {
let tmp = temp_test_dir("sql_schema_check");
fs::create_dir_all(tmp.join("migrations")).unwrap();
fs::create_dir_all(tmp.join("slabs/items")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"sql_schema_demo\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(
tmp.join("migrations/0001_init.sql"),
r"
CREATE TABLE items (
id TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0
);
",
)
.unwrap();
let valid_file = tmp.join("slabs/items/crud.rs");
fs::write(
&valid_file,
r#"
async fn handle(ctx: AppCtx) {
let _ = sqlx::query_as::<_, (String, String)>("SELECT id, title FROM items WHERE done = ?");
let _ = sqlx::query_scalar::<_, i64>(
"WITH pending AS (SELECT id FROM items WHERE done = 0) SELECT COUNT(*) FROM pending",
);
let _ = sqlx::query("INSERT INTO items (id, title, done) VALUES (?, ?, ?)");
let _ = sqlx::query("UPDATE items SET title = ?, done = ? WHERE id = ?");
let _ = sqlx::query("DELETE FROM items WHERE id = ?");
let _ = sqlx::query("REPLACE INTO items (id, title, done) VALUES (?, ?, ?)");
// Non-DML statements (PRAGMA, empty strings) are skipped cleanly
let _ = sqlx::query("PRAGMA foreign_keys = ON");
let _ = sqlx::query(" ");
// Explicit opt-out suppresses validation
// slabs:allow-sql: dynamic virtual table created at runtime
let _ = sqlx::query("SELECT id FROM runtime_only_table WHERE id = ?");
}
#[cfg(test)]
mod tests {
async fn test_only_invalid_sql_is_ignored() {
let _ = sqlx::query("UPDATE nonexistent_test_table SET bogus = ? WHERE id = ?");
}
}
"#,
)
.unwrap();
let valid_report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&valid_file))
.await
.unwrap();
assert_eq!(valid_report.files_checked, 1);
assert_eq!(valid_report.queries_checked, 6);
assert!(
valid_report.findings.is_empty(),
"valid DML queries should have 0 errors: {:?}",
valid_report.findings
);
assert!(
run_sql_schema_check(&tmp, std::slice::from_ref(&valid_file))
.await
.is_ok()
);
let bad_file = tmp.join("slabs/items/broken.rs");
fs::write(
&bad_file,
r#"
async fn handle(ctx: AppCtx) {
let _ = sqlx::query("UPDATE items SET titel = ? WHERE id = ?");
let _ = sqlx::query("INSERT INTO itms (id, title) VALUES (?, ?)");
let _ = sqlx::query("INSERT INTO items (id, title) VALUES (?)");
let _ = sqlx::query("SELECT id FROM items WHERE id = ?"); // slabs:allow-sql: opted out on same line
// slabs:allow-sql: intentional opt-out for typo check
let _ = sqlx::query("DELETE FROM missing_table WHERE id = ?");
}
"#,
)
.unwrap();
let bad_report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&bad_file))
.await
.unwrap();
assert_eq!(bad_report.files_checked, 1);
assert_eq!(bad_report.queries_checked, 3);
assert_eq!(
bad_report.findings.len(),
3,
"expected 3 hard SQL errors: {:?}",
bad_report.findings
);
assert!(
bad_report.findings[0]
.error
.contains("no such column: titel"),
"unexpected error: {}",
bad_report.findings[0].error
);
assert!(
bad_report.findings[1].error.contains("no such table: itms"),
"unexpected error: {}",
bad_report.findings[1].error
);
assert!(
bad_report.findings[2]
.error
.contains("1 values for 2 columns"),
"unexpected error: {}",
bad_report.findings[2].error
);
assert!(run_sql_schema_check(&tmp, &[bad_file]).await.is_err());
let _ = fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn sql_schema_check_supports_schema_sql_fallback_with_system_tables() {
let tmp = temp_test_dir("sql_schema_fallback");
fs::create_dir_all(tmp.join("slabs/jobs_ui")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"schema_fallback_demo\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(
tmp.join("schema.sql"),
"CREATE TABLE widgets (id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL);\n",
)
.unwrap();
let slab_file = tmp.join("slabs/jobs_ui/list.rs");
fs::write(
&slab_file,
r#"
async fn handle(ctx: AppCtx) {
let _ = sqlx::query("SELECT id, name FROM widgets WHERE id = ?");
let _ = sqlx::query("SELECT id, status FROM slabs_jobs WHERE status = ?");
}
"#,
)
.unwrap();
assert!(has_sql_schema(&tmp, std::slice::from_ref(&slab_file)));
let report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&slab_file))
.await
.unwrap();
assert_eq!(report.files_checked, 1);
assert_eq!(report.queries_checked, 2);
assert!(report.findings.is_empty(), "{:?}", report.findings);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn manifest_builds_roundtrips_and_diffs_with_security_downgrade_detection() {
let tmp = temp_test_dir("manifest_diff");
fs::create_dir_all(tmp.join("slabs/rooms")).unwrap();
fs::create_dir_all(tmp.join("slabs/admin")).unwrap();
fs::create_dir_all(tmp.join("jobs")).unwrap();
fs::write(
tmp.join("slabs/rooms/send_message.rs"),
r#"
pub fn slab() -> SlabDef {
SlabDef::post("/api/rooms/{room_id}/messages", handle)
.name("rooms.send_message")
}
async fn handle(ctx: AppCtx, jar: CookieJar) {
let _s = ctx.auth.require_session(&jar).await;
let _ = sqlx::query("SELECT id FROM rooms WHERE id = ?");
let _ = sqlx::query("INSERT INTO messages (id, room_id) VALUES (?, ?)");
let _ = ctx.jobs.enqueue_in_tx(&mut tx, "notify_room", json!({})).await;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/admin/purge.rs"),
r#"
pub fn slab() -> SlabDef {
SlabDef::delete("/api/admin/purge", handle)
.name("admin.purge")
}
async fn handle(ctx: AppCtx, jar: CookieJar) {
let _s = ctx.auth.require_admin(&jar).await;
let _ = sqlx::query("DELETE FROM messages WHERE id = ?");
}
"#,
)
.unwrap();
fs::write(
tmp.join("jobs/notify_room.rs"),
r#"
pub fn job() -> JobDef {
JobDef::new("notify_room", run)
}
async fn run(ctx: AppCtx) {
let _ = sqlx::query("SELECT id FROM rooms WHERE id = ?");
}
"#,
)
.unwrap();
let baseline = build_manifest(&tmp).unwrap();
assert_eq!(baseline.slabs.len(), 2);
assert_eq!(baseline.jobs.len(), 1);
let send = baseline
.slabs
.iter()
.find(|s| s.file == "slabs/rooms/send_message.rs")
.unwrap();
assert_eq!(send.method, "POST");
assert_eq!(send.path, "/api/rooms/{room_id}/messages");
assert_eq!(send.auth, "require_session");
assert!(!send.skip_csrf);
assert_eq!(send.tables_read, vec!["rooms"]);
assert_eq!(send.tables_written, vec!["messages"]);
assert_eq!(send.jobs_enqueued, vec!["notify_room"]);
assert!(send.has_tests);
let roundtripped = StaticManifest::from_json(&baseline.to_json()).unwrap();
assert_eq!(roundtripped, baseline);
let table = format_manifest_table(&baseline);
assert!(table.contains("METHOD"));
assert!(table.contains("TABLES (R/W)"));
assert!(table.contains("R: rooms | W: messages"));
assert!(table.contains("notify_room"));
fs::remove_file(tmp.join("slabs/admin/purge.rs")).unwrap();
fs::write(
tmp.join("slabs/rooms/list_rooms.rs"),
r#"
pub fn slab() -> SlabDef {
SlabDef::get("/api/rooms", handle).name("rooms.list_rooms")
}
async fn handle(ctx: AppCtx) {
let _ = sqlx::query("SELECT id FROM rooms");
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/rooms/send_message.rs"),
r#"
pub fn slab() -> SlabDef {
SlabDef::post("/api/rooms/{room_id}/messages", handle)
.name("rooms.send_message")
.skip_csrf()
}
async fn handle(ctx: AppCtx) {
let _ = sqlx::query("INSERT INTO messages (id, room_id) VALUES (?, ?)");
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
let current = build_manifest(&tmp).unwrap();
let diff = diff_manifests(&baseline, ¤t);
assert_eq!(diff.added_slabs.len(), 1);
assert_eq!(diff.removed_slabs.len(), 1);
assert_eq!(diff.changed_slabs.len(), 1);
let rendered = format_manifest_diff(&diff);
assert!(rendered.contains("+ ADDED"));
assert!(rendered.contains("slabs/rooms/list_rooms.rs"));
assert!(rendered.contains("- REMOVED"));
assert!(rendered.contains("slabs/admin/purge.rs"));
assert!(rendered.contains("~ CHANGED"));
assert!(rendered.contains("[SECURITY] auth weakened: require_session -> public"));
assert!(rendered.contains("[SECURITY] skip_csrf enabled: false -> true"));
let _ = fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn ephemeral_sandbox_migrates_seeds_checkpoints_and_cleans_up() {
let app_dir = temp_test_dir("ephemeral_app");
fs::create_dir_all(app_dir.join("migrations")).unwrap();
fs::write(
app_dir.join("migrations/0001_init.sql"),
"CREATE TABLE items (id TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL);\n",
)
.unwrap();
fs::write(
app_dir.join("seeds.sql"),
"INSERT INTO items (id, name) VALUES ('itm_1', 'Seeded Widget');\n",
)
.unwrap();
let sandbox_dir = temp_test_dir("ephemeral_sandbox");
{
let _guard = SandboxDirGuard(sandbox_dir.clone());
let sandbox = prepare_ephemeral_sandbox(&app_dir, &sandbox_dir)
.await
.unwrap();
assert!(sandbox.seeded);
assert!(sandbox.db_path.is_file());
assert!(sandbox.storage_dir.is_dir());
let verify_db = Db::connect(&format!("sqlite://{}", sandbox.db_path.display()))
.await
.unwrap();
let schema_dump = verify_db.dump_schema_sql().await.unwrap();
assert!(schema_dump.contains("CREATE TABLE items"));
assert!(verify_db
.execute_sql_file(&app_dir.join("seeds.sql"))
.await
.is_err());
verify_db.checkpoint_and_close().await;
}
assert!(!sandbox_dir.exists());
fs::remove_file(app_dir.join("seeds.sql")).unwrap();
let sandbox_dir_2 = temp_test_dir("ephemeral_sandbox_unseeded");
let sandbox_2 = prepare_ephemeral_sandbox(&app_dir, &sandbox_dir_2)
.await
.unwrap();
assert!(!sandbox_2.seeded);
let key = ephemeral_secret_key();
assert_eq!(key.len(), 64);
assert_ne!(key, ephemeral_secret_key());
let bind_addr = pick_ephemeral_bind_addr(None).unwrap();
assert!(bind_addr.starts_with("127.0.0.1:"));
let _ = fs::remove_dir_all(&sandbox_dir_2);
let _ = fs::remove_dir_all(&app_dir);
}
#[test]
fn scaffolds_timestamped_migrations_with_unique_utc_prefixes() {
assert_eq!(format_utc_timestamp_secs(0), "19700101000000");
assert_eq!(format_utc_timestamp_secs(1_709_251_199), "20240229235959");
assert_eq!(format_utc_timestamp_secs(1_709_251_200), "20240301000000");
let parsed = Cli::try_parse_from(["slabs", "new", "migration", "add-card-labels"]).unwrap();
assert!(matches!(
parsed.command,
Commands::New {
kind: NewKind::Migration { ref name }
} if name == "add-card-labels"
));
let tmp = temp_test_dir("timestamped_migrations");
let first = scaffold_migration(&tmp, "Add Card Labels").unwrap();
let second = scaffold_migration(&tmp, "add_card_labels").unwrap();
let third = scaffold_migration(&tmp, "add-board-tags").unwrap();
assert_ne!(first, second);
assert_ne!(second, third);
let name1 = first.file_name().unwrap().to_str().unwrap();
let name2 = second.file_name().unwrap().to_str().unwrap();
let name3 = third.file_name().unwrap().to_str().unwrap();
for (fname, expected_suffix) in [
(name1, "_add_card_labels.sql"),
(name2, "_add_card_labels.sql"),
(name3, "_add_board_tags.sql"),
] {
assert!(
fname.ends_with(expected_suffix),
"unexpected migration filename: {fname}"
);
let prefix = &fname[..fname.len() - expected_suffix.len()];
assert_eq!(prefix.len(), 14, "expected 14-digit UTC prefix: {fname}");
assert!(
prefix.bytes().all(|b| b.is_ascii_digit()),
"prefix must be all digits: {fname}"
);
}
assert!(name1[..14] < name2[..14]);
assert!(name2[..14] < name3[..14]);
let migrations_dir = tmp.join("migrations");
let existing_ts = format_utc_timestamp_secs(1_709_251_199);
fs::write(migrations_dir.join(format!("{existing_ts}_seed.sql")), "").unwrap();
let next_ts = next_unique_migration_timestamp(&migrations_dir, 1_709_251_199).unwrap();
assert_eq!(next_ts, "20240301000000");
assert!(scaffold_migration(&tmp, "../evil").is_err());
assert!(scaffold_migration(&tmp, " ").is_err());
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn find_untested_selected_slabs_catches_untested_and_passes_tested_slabs() {
let tmp = temp_test_dir("untested_slabs");
fs::create_dir_all(tmp.join("slabs/cards")).unwrap();
let no_cfg = tmp.join("slabs/cards/no_tests.rs");
fs::write(
&no_cfg,
r#"
pub fn slab() -> SlabDef { SlabDef::get("/api/cards", handle) }
async fn handle() {}
"#,
)
.unwrap();
let empty_cfg = tmp.join("slabs/cards/empty_mod.rs");
fs::write(
&empty_cfg,
r#"
pub fn slab() -> SlabDef { SlabDef::get("/api/cards/empty", handle) }
async fn handle() {}
#[cfg(test)]
mod tests {
// #[tokio::test]
// async fn commented_out() {}
}
"#,
)
.unwrap();
let tokio_tested = tmp.join("slabs/cards/tokio_tested.rs");
fs::write(
&tokio_tested,
r#"
pub fn slab() -> SlabDef { SlabDef::get("/api/cards/ok", handle) }
async fn handle() {}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn works() {}
}
"#,
)
.unwrap();
let sync_tested = tmp.join("slabs/cards/sync_tested.rs");
fs::write(
&sync_tested,
r#"
pub fn slab() -> SlabDef { SlabDef::get("/api/cards/sync", handle) }
async fn handle() {}
#[cfg(test)]
mod tests {
#[test]
fn works_sync() {}
}
"#,
)
.unwrap();
let make_selected = |action: &str, file: PathBuf| SelectedSlab {
feature: "cards".to_string(),
action: action.to_string(),
file,
crate_dir: tmp.clone(),
};
let untested = find_untested_selected_slabs(&[
make_selected("no_tests", no_cfg.clone()),
make_selected("empty_mod", empty_cfg.clone()),
make_selected("tokio_tested", tokio_tested),
make_selected("sync_tested", sync_tested),
])
.unwrap();
assert_eq!(untested, vec![no_cfg, empty_cfg]);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn formats_compact_and_verbose_security_reports_and_parses_verbose_flag() {
let short_v = Cli::try_parse_from(["slabs", "check", "-v"]).unwrap();
assert!(matches!(
short_v.command,
Commands::Check { verbose: true, .. }
));
let long_v = Cli::try_parse_from(["slabs", "check", "--verbose"]).unwrap();
assert!(matches!(
long_v.command,
Commands::Check { verbose: true, .. }
));
let mut report = SecurityReport {
files_scanned: 7,
findings: vec![
SecurityFinding {
severity: Severity::Error,
rule: "panic-hazard",
file: PathBuf::from("slabs/a/err1.rs"),
line: 10,
message: "avoid unwrap".to_string(),
},
SecurityFinding {
severity: Severity::Warning,
rule: "missing-test",
file: PathBuf::from("slabs/a/w1.rs"),
line: 1,
message: "missing test".to_string(),
},
SecurityFinding {
severity: Severity::Warning,
rule: "missing-test",
file: PathBuf::from("slabs/a/w2.rs"),
line: 1,
message: "missing test".to_string(),
},
],
};
for idx in 1..=5 {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "possible-idor",
file: PathBuf::from(format!("slabs/cards/c{idx}.rs")),
line: idx * 10,
message: "possible idor".to_string(),
});
}
let compact = format_security_report(&report, false);
assert!(compact.contains(" [ERR ] (panic-hazard) slabs/a/err1.rs:10: avoid unwrap"));
assert!(compact.contains(" [WARN ] (missing-test) slabs/a/w1.rs:1: missing test"));
assert!(compact.contains(" [WARN ] (missing-test) slabs/a/w2.rs:1: missing test"));
assert!(compact.contains(
" [WARN ] (possible-idor) 5 finding(s) (e.g. slabs/cards/c1.rs:10, slabs/cards/c2.rs:20, slabs/cards/c3.rs:30; pass --verbose to list all)"
));
assert!(!compact.contains("slabs/cards/c4.rs:40"));
assert!(!compact.contains("slabs/cards/c5.rs:50"));
let verbose = format_security_report(&report, true);
assert!(verbose.contains(" [ERR ] (panic-hazard) slabs/a/err1.rs:10: avoid unwrap"));
assert!(verbose.contains(" [WARN ] (possible-idor) slabs/cards/c4.rs:40: possible idor"));
assert!(verbose.contains(" [WARN ] (possible-idor) slabs/cards/c5.rs:50: possible idor"));
assert!(!verbose.contains("pass --verbose to list all"));
}
#[tokio::test]
async fn sql_placeholder_vs_bind_check_catches_mismatches_and_avoids_false_positives() {
assert_eq!(
count_sql_placeholders("SELECT * FROM items WHERE id = ? AND title = '?'"),
Some(1)
);
assert_eq!(
count_sql_placeholders(
"SELECT 'it''s ?' AS label, \"col?\" FROM items WHERE id = ? -- ?\n/* ? */"
),
Some(1)
);
assert_eq!(
count_sql_placeholders(
"SELECT * FROM items WHERE id = ?1 OR parent_id = ?1 OR title = ?2"
),
Some(2)
);
assert_eq!(
count_sql_placeholders("SELECT * FROM items WHERE id = ?1 AND title = ?"),
None
);
assert_eq!(
count_sql_placeholders("SELECT * FROM items WHERE id = :id"),
None
);
assert_eq!(
count_sql_placeholders("SELECT * FROM items WHERE id = @id"),
None
);
assert_eq!(
count_sql_placeholders("SELECT * FROM items WHERE id = $1"),
None
);
let tmp = temp_test_dir("sql_bind_mismatch");
fs::create_dir_all(tmp.join("migrations")).unwrap();
fs::create_dir_all(tmp.join("slabs/items")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"bind_demo\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(
tmp.join("migrations/0001_init.sql"),
"CREATE TABLE items (id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0);\n",
)
.unwrap();
let ok_file = tmp.join("slabs/items/ok.rs");
fs::write(
&ok_file,
r#"
async fn handle(ctx: AppCtx, id: String, title: String, filter: bool) {
let _ = sqlx::query("SELECT id FROM items WHERE id = ? AND title = '?'")
.bind(&id)
.fetch_optional(ctx.db.reader())
.await;
let _ = sqlx::query_as::<_, (String,)>("SELECT id FROM items WHERE id = ? AND title = ?")
.bind(&id)
.bind(&title)
.fetch_one(ctx.db.reader())
.await;
// Variable-held query with conditional .bind() must be skipped (0 false positives)
let mut q = sqlx::query("SELECT id FROM items WHERE id = ? AND title = ?").bind(&id);
if filter {
q = q.bind(&title);
}
let _ = q.fetch_all(ctx.db.reader()).await;
// Explicit opt-out suppresses bind mismatch
// slabs:allow-sql: custom bind wrapper
let _ = sqlx::query("SELECT id FROM items WHERE id = ? AND title = ?")
.bind(&id)
.fetch_optional(ctx.db.reader())
.await;
}
"#,
)
.unwrap();
let ok_report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&ok_file))
.await
.unwrap();
assert!(
ok_report.findings.is_empty(),
"valid / variable-held / opted-out queries must pass: {:?}",
ok_report.findings
);
let bad_file = tmp.join("slabs/items/bad.rs");
fs::write(
&bad_file,
r#"
async fn handle(ctx: AppCtx, id: String, title: String) {
let _ = sqlx::query("SELECT id FROM items WHERE id = ? AND title = ?")
.bind(&id)
.fetch_optional(ctx.db.reader())
.await;
let _ = sqlx::query("DELETE FROM items WHERE id = ?")
.bind(&id)
.bind(&title)
.execute(ctx.db.writer())
.await;
}
"#,
)
.unwrap();
let bad_report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&bad_file))
.await
.unwrap();
assert_eq!(
bad_report.findings.len(),
2,
"expected 2 bind-count mismatch errors: {:?}",
bad_report.findings
);
assert!(
bad_report.findings[0].error.contains(
"SQL query has 2 placeholder(s) (`?`) but 1 chained `.bind(...)` call(s)"
),
"unexpected error 0: {}",
bad_report.findings[0].error
);
assert!(
bad_report.findings[1].error.contains(
"SQL query has 1 placeholder(s) (`?`) but 2 chained `.bind(...)` call(s)"
),
"unexpected error 1: {}",
bad_report.findings[1].error
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn possible_idor_heuristic_flags_unscoped_and_ignores_scoped_admin_or_annotated() {
let tmp = temp_test_dir("idor_heuristic");
fs::create_dir_all(tmp.join("slabs/cards")).unwrap();
let unscoped = tmp.join("slabs/cards/show_card.rs");
fs::write(
&unscoped,
r#"
pub fn slab() -> SlabDef {
SlabDef::get("/api/cards/{id}", handle)
}
async fn handle(ctx: AppCtx, jar: CookieJar, id: String) {
let _session = ctx.auth.require_session(&jar).await;
let _ = sqlx::query("SELECT * FROM cards WHERE id = ?")
.bind(&id)
.fetch_optional(ctx.db.reader())
.await;
}
#[cfg(test)]
mod tests {
#[test]
fn ok() {}
}
"#,
)
.unwrap();
let mut report = SecurityReport::default();
scan_rust_file(&unscoped, FileArea::Slabs, None, &mut report).unwrap();
assert!(
report
.findings
.iter()
.any(|f| f.severity == Severity::Warning && f.rule == "possible-idor"),
"expected possible-idor warning: {:?}",
report.findings
);
let scoped = tmp.join("slabs/cards/show_scoped.rs");
fs::write(
&scoped,
r#"
pub fn slab() -> SlabDef {
SlabDef::get("/api/cards/{id}", handle)
}
async fn handle(ctx: AppCtx, jar: CookieJar, id: String) {
let session = ctx.auth.require_session(&jar).await;
let _ = sqlx::query("SELECT * FROM cards WHERE id = ? AND account_id = ?")
.bind(&id)
.bind(&session.user_id)
.fetch_optional(ctx.db.reader())
.await;
}
#[cfg(test)]
mod tests {
#[test]
fn ok() {}
}
"#,
)
.unwrap();
let mut scoped_report = SecurityReport::default();
scan_rust_file(&scoped, FileArea::Slabs, None, &mut scoped_report).unwrap();
assert!(
!scoped_report
.findings
.iter()
.any(|f| f.rule == "possible-idor"),
"scoped query must not trigger possible-idor: {:?}",
scoped_report.findings
);
let admin = tmp.join("slabs/cards/admin_show.rs");
fs::write(
&admin,
r#"
pub fn slab() -> SlabDef {
SlabDef::get("/api/cards/{id}", handle)
}
async fn handle(ctx: AppCtx, jar: CookieJar, id: String) {
let _admin = ctx.auth.require_admin(&jar).await;
let _ = sqlx::query("SELECT * FROM cards WHERE id = ?")
.bind(&id)
.fetch_optional(ctx.db.reader())
.await;
}
#[cfg(test)]
mod tests {
#[test]
fn ok() {}
}
"#,
)
.unwrap();
let mut admin_report = SecurityReport::default();
scan_rust_file(&admin, FileArea::Slabs, None, &mut admin_report).unwrap();
assert!(
!admin_report
.findings
.iter()
.any(|f| f.rule == "possible-idor"),
"require_admin route must not trigger possible-idor: {:?}",
admin_report.findings
);
let annotated = tmp.join("slabs/cards/public_show.rs");
fs::write(
&annotated,
r#"
pub fn slab() -> SlabDef {
SlabDef::get("/api/cards/{id}", handle)
}
async fn handle(ctx: AppCtx, jar: CookieJar, id: String) {
let _session = ctx.auth.require_session(&jar).await;
// slabs:allow-unscoped: public card lookup
let _ = sqlx::query("SELECT * FROM cards WHERE id = ?")
.bind(&id)
.fetch_optional(ctx.db.reader())
.await;
}
#[cfg(test)]
mod tests {
#[test]
fn ok() {}
}
"#,
)
.unwrap();
let mut annotated_report = SecurityReport::default();
scan_rust_file(&annotated, FileArea::Slabs, None, &mut annotated_report).unwrap();
assert!(
!annotated_report
.findings
.iter()
.any(|f| f.rule == "possible-idor"),
"annotated slab must not trigger possible-idor: {:?}",
annotated_report.findings
);
let _ = fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn dump_schema_from_migrations_is_deterministic_without_live_db() {
let tmp = temp_test_dir("dump_schema_deterministic");
fs::create_dir_all(tmp.join("migrations")).unwrap();
fs::write(
tmp.join("migrations/0001_init.sql"),
"CREATE TABLE projects (\n id TEXT PRIMARY KEY NOT NULL,\n name TEXT NOT NULL\n);\n",
)
.unwrap();
fs::write(
tmp.join("migrations/0002_add_idx.sql"),
"CREATE INDEX idx_projects_name ON projects(name);\n",
)
.unwrap();
let first = dump_schema_from_migrations(&tmp).await.unwrap();
let second = dump_schema_from_migrations(&tmp).await.unwrap();
assert_eq!(
first, second,
"schema dump from migrations must be deterministic"
);
assert!(first.contains("CREATE TABLE projects"));
assert!(first.contains("CREATE INDEX idx_projects_name ON projects(name);"));
assert!(!first.contains("CREATE TABLE slabs_jobs"));
assert!(!first.contains("_sqlx_migrations"));
let _ = fs::remove_dir_all(&tmp);
}
#[tokio::test]
async fn sql_schema_check_detects_drifted_schema_sql_and_passes_when_synced() {
let tmp = temp_test_dir("sql_schema_drift");
fs::create_dir_all(tmp.join("migrations")).unwrap();
fs::create_dir_all(tmp.join("slabs/items")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"schema_drift_demo\"\nversion = \"0.1.0\"\n",
)
.unwrap();
fs::write(
tmp.join("migrations/0001_init.sql"),
"CREATE TABLE items (id TEXT PRIMARY KEY NOT NULL, title TEXT NOT NULL);\n",
)
.unwrap();
fs::write(
tmp.join("schema.sql"),
"-- stale snapshot\nCREATE TABLE items (id TEXT PRIMARY KEY NOT NULL);\n",
)
.unwrap();
let slab_file = tmp.join("slabs/items/list.rs");
fs::write(
&slab_file,
r#"
async fn handle(ctx: AppCtx) {
let _ = sqlx::query("SELECT id, title FROM items WHERE id = ?");
}
"#,
)
.unwrap();
let drifted_report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&slab_file))
.await
.unwrap();
assert!(
drifted_report.findings.is_empty(),
"valid SQL should have no findings: {:?}",
drifted_report.findings
);
assert_eq!(drifted_report.schema_drift, vec![tmp.join("schema.sql")]);
assert!(
run_sql_schema_check(&tmp, std::slice::from_ref(&slab_file))
.await
.is_err(),
"stale schema.sql must fail run_sql_schema_check"
);
let synced = dump_schema_from_migrations(&tmp).await.unwrap();
fs::write(tmp.join("schema.sql"), synced.replace('\n', "\r\n")).unwrap();
let synced_report = evaluate_sql_schema_check(&tmp, std::slice::from_ref(&slab_file))
.await
.unwrap();
assert!(
synced_report.findings.is_empty(),
"valid SQL should have no findings: {:?}",
synced_report.findings
);
assert!(
synced_report.schema_drift.is_empty(),
"synced schema.sql must have no drift: {:?}",
synced_report.schema_drift
);
assert!(
run_sql_schema_check(&tmp, std::slice::from_ref(&slab_file))
.await
.is_ok(),
"synced schema.sql must pass run_sql_schema_check"
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn db_migrate_and_dump_schema_cli_flags_parse() {
let migrate_default = Cli::try_parse_from([
"slabs",
"db",
"migrate",
"--database-url",
"sqlite://dev.db",
])
.unwrap();
assert!(matches!(
migrate_default.command,
Commands::Db {
action: DbAction::Migrate {
ref database_url,
no_dump: false,
}
} if database_url == "sqlite://dev.db"
));
let migrate_no_dump = Cli::try_parse_from([
"slabs",
"db",
"migrate",
"--database-url",
"sqlite://dev.db",
"--no-dump",
])
.unwrap();
assert!(matches!(
migrate_no_dump.command,
Commands::Db {
action: DbAction::Migrate {
ref database_url,
no_dump: true,
}
} if database_url == "sqlite://dev.db"
));
let dump_default = Cli::try_parse_from(["slabs", "db", "dump-schema"]).unwrap();
assert!(matches!(
dump_default.command,
Commands::Db {
action: DbAction::DumpSchema { database_url: None }
}
));
let dump_explicit = Cli::try_parse_from([
"slabs",
"db",
"dump-schema",
"--database-url",
"sqlite://live.db",
])
.unwrap();
assert!(matches!(
dump_explicit.command,
Commands::Db {
action: DbAction::DumpSchema {
database_url: Some(ref url),
}
} if url == "sqlite://live.db"
));
}
}