diff --git a/CHANGELOG.md b/CHANGELOG.md index 6df6869..4000c10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,13 @@ Per the same section, each tag is expected to pass `cargo xtask ci` and ### Added +- 2026-11-21 - Generated apps register the database, cache, and queue service + providers and connect their `database` queue connections after boot, like the + runnable app. Generated apps open the default database at boot to register + database queue connections, so an unreachable database delays startup by up to + the pool acquire timeout, after which the app serves with those queue + connections unregistered (M0; `feat(scaffold): register the framework service + providers in generated apps`). - 2026-11-20 - Database, cache, and queue bindings at boot: `rustasea::services` adds `DatabaseServiceProvider` (a lazily connecting `ConnectionResolver`), `CacheServiceProvider` (a `CacheManager`), and `QueueServiceProvider` (the @@ -159,6 +166,23 @@ Per the same section, each tag is expected to pass `cargo xtask ci` and ### Changed +- 2026-11-22 - A database URL with an unknown scheme is rejected with an error + that names only the scheme; it no longer echoes the URL, which could carry + credentials (`fix(orm): keep the database URL out of the unknown-scheme + error`). +- 2026-11-21 - The bound connection resolver honours `DATABASE_URL` (then + `DATABASE__URL`), which replaces the default connection as it does for the + CLI. The runnable app's database user provider and queue dashboard now open + their pools through that resolver instead of their own URL lookup, whose + fallback to a top-level `database_url` key is dropped (M0; `fix(rustasea): + honour DATABASE_URL in the bound connection resolver`; `refactor(app): open + the user provider and queue dashboard pools through the bound resolver`). +- 2026-11-21 - Review follow-ups merged with #12: host dispatch tries exact + domains before `{name}` domains and ignores a trailing dot on the host; + `JwtGuard::logout` also revokes the pair when given an expired access token; + the shutdown deadline is cancelled by dropping `GracefulShutdown::guard`; and + each `database` queue connection opens the database connection it names + (M0, M1, M3). - 2026-11-20 - Domain routes match the request host. A route under `Router::domain` previously answered every host and made the catch-all on the same method+path unreachable; a request is now routed by its `Host`, falling diff --git a/README.md b/README.md index cdf593e..f232d9f 100644 --- a/README.md +++ b/README.md @@ -213,7 +213,7 @@ Milestones are **dependency-ordered**: each builds only on predecessors. No circ | **Success Criteria** | Guard mismatch returns typed `Error::GuardMismatch`; CSRF rejects cross-site `POST` without valid `Sec-Fetch-Site`; `#[validate]` rejects strict-mismatch payloads; session cookie uses JSON serialization and hyphenated cache prefix. | | **Laravel 13 features** | #11 origin-aware CSRF, #12 cache/session hardening, #19 strict validation + `ErrorBag`. | -> **Status (2026-09-17):** Partial. JWT, CSRF, throttle, validation, and the `tower-sessions`-backed `SessionGuard` are real (`crates/rustasea-auth/src/session.rs:99`, login/parse/refresh/logout at `:296`–`:408`), and the declarative attributes are now consumed at runtime: `#[middleware]` resolves through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, applied in `dispatch.rs:109`) and `#[authorize]` resolves through `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, applied in `dispatch.rs:135`), while the job-policy attributes `#[tries]`/`#[backoff]`/`#[timeout]` bind through `JobPolicy` (`crates/rustasea-queue/src/policy.rs:21`, `crates/rustasea-queue/src/driver/worker.rs:66`). See [`docs/milestones.md`](docs/milestones.md) for the `GAP-003` reconciliation note. +> **Status (2026-09-17):** Partial. JWT, CSRF, throttle, validation, and the `tower-sessions`-backed `SessionGuard` are real (`crates/rustasea-auth/src/session.rs:99`, login/parse/refresh/logout at `:296`–`:408`), and the declarative attributes are now consumed at runtime: `#[middleware]` resolves through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, applied in `dispatch.rs:183`) and `#[authorize]` resolves through `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, applied in `dispatch.rs:209`), while the job-policy attributes `#[tries]`/`#[backoff]`/`#[timeout]` bind through `JobPolicy` (`crates/rustasea-queue/src/policy.rs:21`, `crates/rustasea-queue/src/driver/worker.rs:66`). See [`docs/milestones.md`](docs/milestones.md) for the `GAP-003` reconciliation note. ### M4 — Queue, Cache, Scheduling & Events diff --git a/crates/rustasea-app/src/bootstrap/app.rs b/crates/rustasea-app/src/bootstrap/app.rs index 50f7d73..d71aece 100644 --- a/crates/rustasea-app/src/bootstrap/app.rs +++ b/crates/rustasea-app/src/bootstrap/app.rs @@ -146,8 +146,9 @@ static SAMPLER_GUARD: std::sync::OnceLock> = std::sy /// /// Reads `[queue.dashboard]` from the boot-time config loader and always records /// it (so the route handlers can gate on `enabled`). When the dashboard is -/// enabled *and* a tokio runtime is current, it spawns a task that resolves the -/// database URL, connects the shared pool, installs it, and starts the sampler. +/// enabled *and* a tokio runtime is current, it spawns a task that opens the +/// default connection through the bound resolver, installs the pool, and starts +/// the sampler. /// /// Best-effort and idempotent: a config or connection failure is logged and boot /// continues; the [`SAMPLER_GUARD`] ensures at most one sampler task is spawned @@ -175,21 +176,22 @@ fn install_queue_dashboard(app: &Application) { let Ok(handle) = tokio::runtime::Handle::try_current() else { return; }; + let Some(resolver) = rustasea::services::database(app) else { + tracing::error!("queue dashboard: no database is bound"); + return; + }; SAMPLER_GUARD.get_or_init(|| { handle.spawn(async move { - match resolve_database_url(&loader) { - Ok(url) => match rustasea::orm::DbPool::connect(&url).await { - Ok(pool) => { - rustasea_queue_dashboard::set_pool(pool.clone()); - rustasea_queue_dashboard::sampler::spawn_sampler( - pool, - config.sample_interval(), - config.retention(), - ); - } - Err(error) => tracing::error!(%error, "queue dashboard pool failed"), - }, - Err(error) => tracing::error!(%error, "queue dashboard database URL failed"), + match resolver.resolve(None).await { + Ok(pool) => { + rustasea_queue_dashboard::set_pool(pool.clone()); + rustasea_queue_dashboard::sampler::spawn_sampler( + pool, + config.sample_interval(), + config.retention(), + ); + } + Err(error) => tracing::error!(%error, "queue dashboard pool failed"), } }) }); @@ -241,39 +243,6 @@ fn install_broadcasting(app: &Application) { #[cfg(not(feature = "broadcasting"))] fn install_broadcasting(_app: &Application) {} -/// Resolve the database connection URL from the environment, then config. -/// -/// Mirrors the CLI resolver (`crates/rustasea-cli/src/commands/ops/migration.rs`) -/// so the app and the console agree: `DATABASE_URL` wins over the nested -/// `DATABASE__URL` overlay, then the default connection from -/// `config/database.toml` (`DatabaseConfig::resolve_url(None)`), then the legacy -/// top-level `database_url` key. -pub(crate) fn resolve_database_url(loader: &rustasea::ConfigLoader) -> Result { - for key in ["DATABASE_URL", "DATABASE__URL"] { - if let Ok(url) = std::env::var(key) { - if !url.trim().is_empty() { - return Ok(url); - } - } - } - match rustasea::orm::DatabaseConfig::from_loader(loader) - .and_then(|config| config.resolve_url(None)) - { - Ok(url) => Ok(url), - Err(rustasea::orm::OrmError::Connection( - rustasea::orm::ConnectionError::NotConfigured, - )) => loader - .get_key::("database_url") - .ok() - .filter(|url| !url.trim().is_empty()) - .ok_or_else(|| { - "database URL not configured — set `database.url` in config/database.toml or DATABASE_URL" - .to_string() - }), - Err(error) => Err(error.to_string()), - } -} - /// Install the dev panic-location hook (ADOPT-010) when the app is in debug. /// /// The hook records `(message, file, line)` for the most recent panic so the dev diff --git a/crates/rustasea-app/src/bootstrap/auth.rs b/crates/rustasea-app/src/bootstrap/auth.rs index 3ed4792..94d58fa 100644 --- a/crates/rustasea-app/src/bootstrap/auth.rs +++ b/crates/rustasea-app/src/bootstrap/auth.rs @@ -278,14 +278,17 @@ pub fn uses_database_provider(loader: &ConfigLoader) -> bool { .is_some_and(|driver| driver == "eloquent" || driver == "database") } -/// Build the database-backed [`UserProvider`] over the `users` table at `url`. +/// Build the database-backed [`UserProvider`] over the `users` table of the +/// resolver's default connection. /// /// Returns `None` — so the caller keeps the fail-closed provider — when the /// database is unreachable or has no `users` table (the migrations have not /// run). The probe looks up an empty email: it matches no user, and succeeds /// only when the table can be queried. -pub async fn database_user_provider(url: &str) -> Option> { - let pool = match rustasea::orm::DbPool::connect(url).await { +pub async fn database_user_provider( + resolver: &rustasea::orm::ConnectionResolver, +) -> Option> { + let pool = match resolver.resolve(None).await { Ok(pool) => pool, // A sqlite-only build pointed at a Postgres/MySQL URL (the scaffold's // Docker default is Postgres) is a missing driver feature, not an @@ -323,8 +326,9 @@ pub async fn database_user_provider(url: &str) -> Option> /// Called once from `main` after boot. The provider replaces the fail-closed /// default only when all of these hold: no dev seed user is set (an explicit /// `RUSTASEA_DEV_SEED_USER` wins), the default guard's provider is ORM-backed -/// ([`uses_database_provider`]), a database URL resolves, and the `users` table -/// is reachable ([`database_user_provider`]). Otherwise nothing changes and auth +/// ([`uses_database_provider`]), the database is bound (see +/// [`rustasea::services::DatabaseServiceProvider`]), and the `users` table is +/// reachable ([`database_user_provider`]). Otherwise nothing changes and auth /// stays fail-closed. /// /// # Returns @@ -340,14 +344,11 @@ pub async fn install_database_user_provider(app: &rustasea::Application) -> bool if !uses_database_provider(loader) { return false; } - let url = match super::app::resolve_database_url(loader) { - Ok(url) => url, - Err(error) => { - eprintln!("auth: {error}; user provider stays fail-closed"); - return false; - } + let Some(resolver) = rustasea::services::database(app) else { + eprintln!("auth: no database is bound; user provider stays fail-closed"); + return false; }; - match database_user_provider(&url).await { + match database_user_provider(&resolver).await { Some(provider) => { crate::routes::install_user_provider(provider); println!("auth: users resolved from the database `users` table"); @@ -396,74 +397,4 @@ pub fn user_provider(container: &Container) -> Option> { } #[cfg(test)] -mod tests { - use super::*; - use rustasea::auth::NewUserRecord; - - /// A unique scratch path under the system temp directory. - fn scratch(name: &str) -> std::path::PathBuf { - std::env::temp_dir().join(format!("rustasea-app-{name}-{}", uuid::Uuid::new_v4())) - } - - /// Load an `[auth]` table whose default guard uses `driver`. - fn loader_with_provider_driver(driver: &str) -> ConfigLoader { - let base = scratch("auth"); - let toml = format!( - "[auth.defaults]\nguard = \"web\"\n\ - [auth.guards.web]\ndriver = \"session\"\nprovider = \"users\"\n\ - [auth.providers.users]\ndriver = \"{driver}\"\n" - ); - let file = base.with_extension("toml"); - std::fs::write(&file, toml).expect("write auth.toml"); - let loader = ConfigLoader::load_from(&[&base.to_string_lossy()]).expect("load"); - let _ = std::fs::remove_file(file); - loader - } - - #[test] - fn only_orm_backed_drivers_select_the_database_provider() { - assert!(uses_database_provider(&loader_with_provider_driver( - "eloquent" - ))); - assert!(uses_database_provider(&loader_with_provider_driver( - "Database" - ))); - assert!(!uses_database_provider(&loader_with_provider_driver( - "memory" - ))); - } - - #[tokio::test] - async fn database_provider_is_built_only_when_the_users_table_exists() { - let path = scratch("users").with_extension("sqlite"); - let url = format!("sqlite://{}?mode=rwc", path.display()); - - // No `users` table yet: stay fail-closed. - assert!(database_user_provider(&url).await.is_none()); - - let pool = rustasea::orm::DbPool::connect(&url).await.expect("pool"); - pool.execute_script( - "CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, \ - email VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, \ - email_verified_at TIMESTAMPTZ NULL, timezone VARCHAR(64) NULL, \ - created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, \ - deleted_at TIMESTAMPTZ NULL);", - ) - .await - .expect("schema"); - - let provider = database_user_provider(&url).await.expect("provider"); - let created = provider - .create(NewUserRecord::new("Ada", "ada@example.com", "phc-hash")) - .await - .expect("create"); - let found = provider - .find_by_email("ada@example.com") - .await - .expect("find"); - assert_eq!(found.map(|user| user.id), Some(created.id)); - - pool.close().await; - let _ = std::fs::remove_file(path); - } -} +mod tests; diff --git a/crates/rustasea-app/src/bootstrap/auth/tests.rs b/crates/rustasea-app/src/bootstrap/auth/tests.rs new file mode 100644 index 0000000..03ca3e0 --- /dev/null +++ b/crates/rustasea-app/src/bootstrap/auth/tests.rs @@ -0,0 +1,77 @@ +//! Tests for the auth bootstrap wiring. + +use super::*; +use rustasea::auth::NewUserRecord; + +/// A unique scratch path under the system temp directory. +fn scratch(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("rustasea-app-{name}-{}", uuid::Uuid::new_v4())) +} + +/// Load an `[auth]` table whose default guard uses `driver`. +fn loader_with_provider_driver(driver: &str) -> ConfigLoader { + let base = scratch("auth"); + let toml = format!( + "[auth.defaults]\nguard = \"web\"\n\ + [auth.guards.web]\ndriver = \"session\"\nprovider = \"users\"\n\ + [auth.providers.users]\ndriver = \"{driver}\"\n" + ); + let file = base.with_extension("toml"); + std::fs::write(&file, toml).expect("write auth.toml"); + let loader = ConfigLoader::load_from(&[&base.to_string_lossy()]).expect("load"); + let _ = std::fs::remove_file(file); + loader +} + +#[test] +fn only_orm_backed_drivers_select_the_database_provider() { + assert!(uses_database_provider(&loader_with_provider_driver( + "eloquent" + ))); + assert!(uses_database_provider(&loader_with_provider_driver( + "Database" + ))); + assert!(!uses_database_provider(&loader_with_provider_driver( + "memory" + ))); +} + +#[tokio::test] +async fn database_provider_is_built_only_when_the_users_table_exists() { + let path = scratch("users").with_extension("sqlite"); + let url = format!("sqlite://{}?mode=rwc", path.display()); + let mut config = rustasea::orm::DatabaseConfig { + url: Some(url.clone()), + ..Default::default() + }; + config.synthesize(); + let resolver = rustasea::orm::ConnectionResolver::new(config); + + // No `users` table yet: stay fail-closed. + assert!(database_user_provider(&resolver).await.is_none()); + + let pool = rustasea::orm::DbPool::connect(&url).await.expect("pool"); + pool.execute_script( + "CREATE TABLE users (id UUID PRIMARY KEY, name VARCHAR(255) NOT NULL, \ + email VARCHAR(255) NOT NULL UNIQUE, password VARCHAR(255) NOT NULL, \ + email_verified_at TIMESTAMPTZ NULL, timezone VARCHAR(64) NULL, \ + created_at TIMESTAMPTZ NOT NULL, updated_at TIMESTAMPTZ NOT NULL, \ + deleted_at TIMESTAMPTZ NULL);", + ) + .await + .expect("schema"); + + let provider = database_user_provider(&resolver).await.expect("provider"); + let created = provider + .create(NewUserRecord::new("Ada", "ada@example.com", "phc-hash")) + .await + .expect("create"); + let found = provider + .find_by_email("ada@example.com") + .await + .expect("find"); + assert_eq!(found.map(|user| user.id), Some(created.id)); + + pool.close().await; + let _ = std::fs::remove_file(path); +} diff --git a/crates/rustasea-orm/src/db.rs b/crates/rustasea-orm/src/db.rs index 6b3bbc3..3540ecf 100644 --- a/crates/rustasea-orm/src/db.rs +++ b/crates/rustasea-orm/src/db.rs @@ -76,8 +76,9 @@ impl DbPool { "sqlite" => Self::connect_sqlite(url, settings).await, "postgres" | "postgresql" => Self::connect_postgres(url, settings).await, "mysql" => Self::connect_mysql(url, settings).await, + // Name only the scheme: the URL may carry credentials. other => Err(OrmError::Pool(format!( - "invalid database URL `{url}`: unknown scheme `{other}`" + "invalid database URL: unknown scheme `{other}`" ))), } } @@ -301,4 +302,15 @@ mod tests { .unwrap_err(); assert!(matches!(error, OrmError::Pool(_)), "got {error:?}"); } + + /// Verifies an unknown-scheme error names the scheme, not the credentials. + #[tokio::test] + async fn unknown_scheme_error_omits_the_url() { + let error = DbPool::connect("mariadb://user:hunter2@db.internal/app") + .await + .unwrap_err() + .to_string(); + assert!(error.contains("`mariadb`"), "got {error}"); + assert!(!error.contains("hunter2"), "leaked the password: {error}"); + } } diff --git a/crates/rustasea-scaffold/src/templates/bootstrap.rs b/crates/rustasea-scaffold/src/templates/bootstrap.rs index 43b4f45..443b1ae 100644 --- a/crates/rustasea-scaffold/src/templates/bootstrap.rs +++ b/crates/rustasea-scaffold/src/templates/bootstrap.rs @@ -60,16 +60,26 @@ const BOOTSTRAP_PROVIDERS: &str = r##"//! Provider registry - service providers //! This registry is populated by the starter kit (previously empty) and is the //! registration site for providers generated with `cargo rustasea make:provider`. +use rustasea::services::{CacheServiceProvider, DatabaseServiceProvider, QueueServiceProvider}; use rustasea::ServiceProvider; use crate::app::providers::{AppServiceProvider, AuthServiceProvider}; /// Providers wired into the boot DAG, in registration order. /// -/// Order is the tie-breaker for providers without `dependencies()`; the -/// foundation `Application::boot` topologically sorts them regardless. +/// The framework providers bind the database connection resolver, the cache +/// manager, and the queue connections (see `rustasea::services`) ahead of the +/// application's own. Order is the tie-breaker for providers without +/// `dependencies()`; the foundation `Application::boot` topologically sorts +/// them regardless. pub fn providers() -> Vec> { - vec![Box::new(AppServiceProvider), Box::new(AuthServiceProvider)] + vec![ + Box::new(DatabaseServiceProvider), + Box::new(CacheServiceProvider), + Box::new(QueueServiceProvider), + Box::new(AppServiceProvider), + Box::new(AuthServiceProvider), + ] } "##; diff --git a/crates/rustasea-scaffold/src/templates/core.rs b/crates/rustasea-scaffold/src/templates/core.rs index be408b5..45f174c 100644 --- a/crates/rustasea-scaffold/src/templates/core.rs +++ b/crates/rustasea-scaffold/src/templates/core.rs @@ -6,6 +6,7 @@ //! kernel wiring lives in [`super::bootstrap`] and the developer-tooling config //! in [`super::tooling`]. +use super::entry::{LIB_RS, MAIN_RS}; use crate::variant::StarterKitVariant; use super::TemplateFile; @@ -350,6 +351,12 @@ cargo run The server binds `0.0.0.0:8000` by default (`APP_URL` overrides it). +Because the shipped config sets `[queue] default = "database"`, the app opens +the default database at boot to register the database queue connections. An +unreachable database delays startup by up to the pool acquire timeout (30 s by +default), after which the server starts with those queue connections +unregistered. + Console commands are run through the Artisan-style CLI: ```sh @@ -415,83 +422,6 @@ If you discover a security vulnerability within RustaSea, please review the disc This application is open-sourced software licensed under the [MIT license](LICENSE). "##; -const LIB_RS: &str = r##"//! @@app_pascal@@ — RustaSea application library. -//! -//! The module tree mirrors the Laravel layout: `app/` holds domain actions, -//! concerns, HTTP, models, and providers; `bootstrap/` wires the kernel; -//! `routes/` owns the route tables; `database/` holds migrations, factories, -//! and seeders. - -pub mod app; -pub mod bootstrap; -pub mod database; -pub mod routes; -"##; - -const MAIN_RS: &str = r##"//! @@app_pascal@@ HTTP entry point. - -use std::net::SocketAddr; -use std::sync::Arc; - -use @@app_snake@@::{bootstrap, routes}; -use rustasea::http::AppState; - -/// Default bind address for the dev server (Laravel `php artisan serve` parity). -const DEFAULT_BIND: &str = "0.0.0.0:8000"; - -#[tokio::main] -async fn main() -> Result<(), Box> { - // Configure the container and run the provider boot DAG. `configure` - // returns `Result` so a misconfigured boot aborts before the server starts - // instead of silently ignoring the failure. - let app = bootstrap::app::configure()?; - - // Create the shared HTTP state once; every route table receives this same - // instance so handlers resolve one application state, not a disconnected one. - let state = Arc::new(AppState::new("local", true)); - - // Build the axum router from the generated route tables. - let router = routes::router(state); - - // Resolve the bind address from `APP_URL` (host:port) so the advertised URL - // and the listening socket stay in sync; fall back to the default. - let addr: SocketAddr = bind_address(); - let listener = tokio::net::TcpListener::bind(addr).await?; - println!("@@app_pascal@@ listening on http://{addr}"); - - // `ConnectInfo` hands every request its client IP (throttle keys, audit logs). - axum::serve(listener, router.into_make_service_with_connect_info::()) - .with_graceful_shutdown(app.shutdown()) - .await?; - Ok(()) -} - -/// Resolve the bind address from `APP_URL` (host:port) or the default. -fn bind_address() -> SocketAddr { - std::env::var("APP_URL") - .ok() - .and_then(parse_host_port) - .unwrap_or_else(default_bind) -} - -/// The fallback bind address used when `APP_URL` is unset or carries no port. -fn default_bind() -> SocketAddr { - match DEFAULT_BIND.parse() { - Ok(addr) => addr, - // `DEFAULT_BIND` is a compile-time constant and always parses; this arm - // keeps the function panic-free without an `expect`. - Err(_) => SocketAddr::from(([0, 0, 0, 0], 8000)), - } -} - -/// Parse an `APP_URL` value into a `SocketAddr` when it carries a port. -fn parse_host_port(url: String) -> Option { - let authority = url.split("://").nth(1)?; - let host_port = authority.split('/').next()?; - host_port.parse().ok() -} -"##; - const ASKAMA_TOML: &str = r##"# askama template root — compiled into the binary at build time. [general] dirs = ["resources/views"] diff --git a/crates/rustasea-scaffold/src/templates/entry.rs b/crates/rustasea-scaffold/src/templates/entry.rs new file mode 100644 index 0000000..8d3ab2c --- /dev/null +++ b/crates/rustasea-scaffold/src/templates/entry.rs @@ -0,0 +1,86 @@ +//! Crate entry-point templates for a generated app: `lib.rs` and `main.rs`. +//! +//! Split out of [`super::core`] to keep that file under the 500-line limit. + +pub(super) const LIB_RS: &str = r##"//! @@app_pascal@@ — RustaSea application library. +//! +//! The module tree mirrors the Laravel layout: `app/` holds domain actions, +//! concerns, HTTP, models, and providers; `bootstrap/` wires the kernel; +//! `routes/` owns the route tables; `database/` holds migrations, factories, +//! and seeders. + +pub mod app; +pub mod bootstrap; +pub mod database; +pub mod routes; +"##; + +pub(super) const MAIN_RS: &str = r##"//! @@app_pascal@@ HTTP entry point. + +use std::net::SocketAddr; +use std::sync::Arc; + +use @@app_snake@@::{bootstrap, routes}; +use rustasea::http::AppState; + +/// Default bind address for the dev server (Laravel `php artisan serve` parity). +const DEFAULT_BIND: &str = "0.0.0.0:8000"; + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Configure the container and run the provider boot DAG. `configure` + // returns `Result` so a misconfigured boot aborts before the server starts + // instead of silently ignoring the failure. + let app = bootstrap::app::configure()?; + + // `database` queue connections need a live pool, which providers cannot + // open; register them now through the database connection bound at boot. + if let Err(error) = rustasea::services::connect_database_queues(&app).await { + eprintln!("queue: database connections not registered: {error}"); + } + + // Create the shared HTTP state once; every route table receives this same + // instance so handlers resolve one application state, not a disconnected one. + let state = Arc::new(AppState::new("local", true)); + + // Build the axum router from the generated route tables. + let router = routes::router(state); + + // Resolve the bind address from `APP_URL` (host:port) so the advertised URL + // and the listening socket stay in sync; fall back to the default. + let addr: SocketAddr = bind_address(); + let listener = tokio::net::TcpListener::bind(addr).await?; + println!("@@app_pascal@@ listening on http://{addr}"); + + // `ConnectInfo` hands every request its client IP (throttle keys, audit logs). + axum::serve(listener, router.into_make_service_with_connect_info::()) + .with_graceful_shutdown(app.shutdown()) + .await?; + Ok(()) +} + +/// Resolve the bind address from `APP_URL` (host:port) or the default. +fn bind_address() -> SocketAddr { + std::env::var("APP_URL") + .ok() + .and_then(parse_host_port) + .unwrap_or_else(default_bind) +} + +/// The fallback bind address used when `APP_URL` is unset or carries no port. +fn default_bind() -> SocketAddr { + match DEFAULT_BIND.parse() { + Ok(addr) => addr, + // `DEFAULT_BIND` is a compile-time constant and always parses; this arm + // keeps the function panic-free without an `expect`. + Err(_) => SocketAddr::from(([0, 0, 0, 0], 8000)), + } +} + +/// Parse an `APP_URL` value into a `SocketAddr` when it carries a port. +fn parse_host_port(url: String) -> Option { + let authority = url.split("://").nth(1)?; + let host_port = authority.split('/').next()?; + host_port.parse().ok() +} +"##; diff --git a/crates/rustasea-scaffold/src/templates/mod.rs b/crates/rustasea-scaffold/src/templates/mod.rs index 2d117a2..4cdad5d 100644 --- a/crates/rustasea-scaffold/src/templates/mod.rs +++ b/crates/rustasea-scaffold/src/templates/mod.rs @@ -15,6 +15,7 @@ mod config; mod core; mod database; mod docker; +mod entry; mod inertia; mod inertia_react; mod inertia_svelte; diff --git a/crates/rustasea/src/services.rs b/crates/rustasea/src/services.rs index f27a1c1..3d6a156 100644 --- a/crates/rustasea/src/services.rs +++ b/crates/rustasea/src/services.rs @@ -4,7 +4,11 @@ //! //! - [`DatabaseServiceProvider`] binds an [`orm::ConnectionResolver`] built from //! `[database]` under [`DATABASE_KEY`]. It connects lazily, on the first -//! [`orm::ConnectionResolver::resolve`], so boot does no I/O. +//! [`orm::ConnectionResolver::resolve`], so boot does no I/O. `DATABASE_URL` +//! (or `DATABASE__URL`) replaces the default connection wholesale, as it does +//! for the CLI: the pool settings carry over, but the connection's `read`, +//! `write`, and `charset` are not carried forward. The override still applies +//! when the `[database]` table fails to parse. //! - [`CacheServiceProvider`] binds a [`cache::CacheManager`] built from //! `[cache]` under [`CACHE_KEY`]. //! - [`QueueServiceProvider`] registers the `[queue]` connections that need no @@ -69,13 +73,71 @@ impl ServiceProvider for DatabaseServiceProvider { let Some(loader) = app.config().cloned() else { return; }; - match orm::ConnectionResolver::from_loader(&loader) { - Ok(resolver) => app.container.instance(DATABASE_KEY, Arc::new(resolver)), - Err(error) => eprintln!("database: invalid [database] config, not bound: {error}"), + match orm::DatabaseConfig::from_loader(&loader) { + Ok(mut config) => { + if let Some(url) = database_url_override() { + override_default_connection(&mut config, url); + } + let resolver = orm::ConnectionResolver::new(config); + app.container.instance(DATABASE_KEY, Arc::new(resolver)); + } + Err(error) => { + // A malformed `[database]` table must not hide an explicit URL: + // the environment outranks config, matching the CLI. Bind from + // an empty config so `DATABASE_URL` still takes effect. + match database_url_override() { + Some(url) => { + eprintln!( + "database: invalid [database] config, using DATABASE_URL: {error}" + ); + let mut config = orm::DatabaseConfig::default(); + override_default_connection(&mut config, url); + let resolver = orm::ConnectionResolver::new(config); + app.container.instance(DATABASE_KEY, Arc::new(resolver)); + } + None => { + eprintln!("database: invalid [database] config, not bound: {error}") + } + } + } } } } +/// The non-empty `DATABASE_URL`, else `DATABASE__URL`, from the environment. +fn database_url_override() -> Option { + ["DATABASE_URL", "DATABASE__URL"] + .into_iter() + .filter_map(|key| std::env::var(key).ok()) + .map(|url| url.trim().to_string()) + .find(|url| !url.is_empty()) +} + +/// Point the default connection (created if absent) at `url`, keeping the +/// other named connections and the pool settings. +/// +/// The default connection is replaced wholesale: `driver` comes from the URL +/// scheme and `url` from `url`, while a configured `read`, `write`, or +/// `charset` on that connection is discarded, because the replacement is built +/// from an empty `orm::ConnectionConfig`. +fn override_default_connection(config: &mut orm::DatabaseConfig, url: String) { + let name = config.default_name().unwrap_or("default").to_string(); + let pool = config + .connections + .get(&name) + .and_then(|connection| connection.pool.clone()) + .or_else(|| config.pool.clone()); + let driver = url.split(':').next().unwrap_or_default().to_string(); + let connection = orm::ConnectionConfig { + driver, + url: Some(url), + pool, + ..orm::ConnectionConfig::default() + }; + config.connections.insert(name.clone(), connection); + config.default = Some(name); +} + /// Binds the cache manager under [`CACHE_KEY`]. pub struct CacheServiceProvider; diff --git a/crates/rustasea/tests/services_database_url.rs b/crates/rustasea/tests/services_database_url.rs new file mode 100644 index 0000000..f05d44c --- /dev/null +++ b/crates/rustasea/tests/services_database_url.rs @@ -0,0 +1,239 @@ +//! `DATABASE_URL` overrides the default database connection at boot. +//! +//! Its own test binary: the variable is process-global, so it must not leak +//! into the other service-provider tests. Every case runs inside one +//! `#[tokio::test]` so the process-wide variables cannot race between tests. + +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + +use rustasea::services::{database, DatabaseServiceProvider}; + +static SCRATCH_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// Restore process-wide database URL variables after the test, including on panic. +struct DatabaseUrlEnv { + database_url: Option, + database_nested_url: Option, +} + +impl DatabaseUrlEnv { + /// Save the caller's environment before the test changes either URL key. + fn capture() -> Self { + Self { + database_url: std::env::var_os("DATABASE_URL"), + database_nested_url: std::env::var_os("DATABASE__URL"), + } + } +} + +impl Drop for DatabaseUrlEnv { + fn drop(&mut self) { + match self.database_url.take() { + Some(value) => std::env::set_var("DATABASE_URL", value), + None => std::env::remove_var("DATABASE_URL"), + } + match self.database_nested_url.take() { + Some(value) => std::env::set_var("DATABASE__URL", value), + None => std::env::remove_var("DATABASE__URL"), + } + } +} +use rustasea::Application; + +/// A scratch tag unique to this process, call, and moment. +/// +/// The PID separates concurrent test binaries; the counter separates repeated +/// calls even when the clock is coarse; the nanosecond stamp separates this run +/// from a stale file left by a crashed run that reused the PID. +fn scratch_tag() -> String { + let sequence = SCRATCH_COUNTER.fetch_add(1, Ordering::Relaxed); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_nanos()) + .unwrap_or_default(); + format!("{}-{nanos}-{sequence}", std::process::id()) +} + +/// Write `database.toml` whose default connection points at `db_path`. +fn write_config(dir: &Path, db_path: &Path) { + std::fs::create_dir_all(dir).expect("config dir"); + std::fs::write( + dir.join("database.toml"), + format!( + "[database]\ndefault = \"main\"\n\n\ + [database.connections.main]\ndriver = \"sqlite\"\nurl = \"sqlite://{}?mode=rwc\"\n\n\ + [database.connections.jobs]\ndriver = \"sqlite\"\nurl = \"sqlite://{}?mode=rwc\"\n", + db_path.display(), + db_path.display() + ), + ) + .expect("database.toml"); +} + +/// Boot a fresh application whose config directory is `dir`. +fn boot_app(dir: &Path) -> Application { + let mut app = Application::configure(|app| { + app.set_config_dir(dir); + }); + app.provider(DatabaseServiceProvider); + app.boot().expect("boot"); + app +} + +/// Remove a scratch config directory and database file, ignoring absence. +fn cleanup(dir: &Path, db: &Path) { + let _ = std::fs::remove_dir_all(dir); + let _ = std::fs::remove_file(db); +} + +#[tokio::test] +async fn database_url_replaces_the_default_connection_only() { + let _env = DatabaseUrlEnv::capture(); + let tmp = std::env::temp_dir(); + + // Case 1: `DATABASE_URL` replaces the default connection, others are kept. + { + let tag = scratch_tag(); + let configured = tmp.join(format!("rustasea-dburl-configured-{tag}.sqlite")); + let from_env = tmp.join(format!("rustasea-dburl-env-{tag}.sqlite")); + let dir = tmp.join(format!("rustasea-dburl-config-{tag}")); + write_config(&dir, &configured); + let env_url = format!("sqlite://{}?mode=rwc", from_env.display()); + std::env::remove_var("DATABASE__URL"); + std::env::set_var("DATABASE_URL", &env_url); + + let app = boot_app(&dir); + std::env::remove_var("DATABASE_URL"); + + let resolver = database(&app).expect("resolver bound"); + let config = resolver.config(); + assert_eq!(config.default.as_deref(), Some("main")); + assert_eq!( + config.connections["main"].url.as_deref(), + Some(env_url.as_str()) + ); + assert!( + config.connections.contains_key("jobs"), + "other connections are kept" + ); + + // The default connection now opens the database named by the variable. + resolver.resolve(None).await.expect("connect"); + assert!(from_env.exists(), "DATABASE_URL database was opened"); + assert!(!configured.exists(), "configured database was not opened"); + + cleanup(&dir, &from_env); + } + + // Case 2: `DATABASE__URL` is the fallback when `DATABASE_URL` is absent. + { + let tag = scratch_tag(); + let configured = tmp.join(format!("rustasea-dburl-configured-nested-{tag}.sqlite")); + let from_env = tmp.join(format!("rustasea-dburl-env-nested-{tag}.sqlite")); + let dir = tmp.join(format!("rustasea-dburl-config-nested-{tag}")); + write_config(&dir, &configured); + let env_url = format!("sqlite://{}?mode=rwc", from_env.display()); + std::env::remove_var("DATABASE_URL"); + std::env::set_var("DATABASE__URL", &env_url); + + let app = boot_app(&dir); + std::env::remove_var("DATABASE__URL"); + + let resolver = database(&app).expect("resolver bound"); + let config = resolver.config(); + assert_eq!( + config.connections["main"].url.as_deref(), + Some(env_url.as_str()), + "DATABASE__URL replaces the default connection" + ); + resolver.resolve(None).await.expect("connect"); + assert!(from_env.exists(), "DATABASE__URL database was opened"); + assert!(!configured.exists(), "configured database was not opened"); + + cleanup(&dir, &from_env); + } + + // Case 3: a blank `DATABASE_URL` falls back to the configured default. + { + let tag = scratch_tag(); + let configured = tmp.join(format!("rustasea-dburl-configured-blank-{tag}.sqlite")); + let dir = tmp.join(format!("rustasea-dburl-config-blank-{tag}")); + write_config(&dir, &configured); + let configured_url = format!("sqlite://{}?mode=rwc", configured.display()); + std::env::remove_var("DATABASE__URL"); + std::env::set_var("DATABASE_URL", " \t "); + + let app = boot_app(&dir); + std::env::remove_var("DATABASE_URL"); + + let resolver = database(&app).expect("resolver bound"); + let config = resolver.config(); + assert_eq!( + config.connections["main"].url.as_deref(), + Some(configured_url.as_str()), + "a blank DATABASE_URL leaves the configured default in place" + ); + resolver.resolve(None).await.expect("connect"); + assert!(configured.exists(), "configured database was opened"); + + cleanup(&dir, &configured); + } + + // Case 4: no variable at all leaves the configured default unchanged. + { + let tag = scratch_tag(); + let configured = tmp.join(format!("rustasea-dburl-configured-unset-{tag}.sqlite")); + let dir = tmp.join(format!("rustasea-dburl-config-unset-{tag}")); + write_config(&dir, &configured); + let configured_url = format!("sqlite://{}?mode=rwc", configured.display()); + std::env::remove_var("DATABASE_URL"); + std::env::remove_var("DATABASE__URL"); + + let app = boot_app(&dir); + + let resolver = database(&app).expect("resolver bound"); + let config = resolver.config(); + assert_eq!(config.default.as_deref(), Some("main")); + assert_eq!( + config.connections["main"].url.as_deref(), + Some(configured_url.as_str()), + "the configured default connection is unchanged" + ); + resolver.resolve(None).await.expect("connect"); + assert!(configured.exists(), "configured database was opened"); + + cleanup(&dir, &configured); + } + + // Case 5: a malformed `[database]` table does not hide `DATABASE_URL`. + { + let tag = scratch_tag(); + let from_env = tmp.join(format!("rustasea-dburl-env-malformed-{tag}.sqlite")); + let dir = tmp.join(format!("rustasea-dburl-config-malformed-{tag}")); + std::fs::create_dir_all(&dir).expect("config dir"); + std::fs::write( + dir.join("database.toml"), + "[database]\nconnections = \"not-a-table\"\n", + ) + .expect("database.toml"); + let env_url = format!("sqlite://{}?mode=rwc", from_env.display()); + std::env::remove_var("DATABASE__URL"); + std::env::set_var("DATABASE_URL", &env_url); + + let app = boot_app(&dir); + std::env::remove_var("DATABASE_URL"); + + let resolver = database(&app).expect("resolver bound despite malformed config"); + let config = resolver.config(); + assert_eq!( + config.connections["default"].url.as_deref(), + Some(env_url.as_str()), + "DATABASE_URL wins over a malformed [database] config" + ); + resolver.resolve(None).await.expect("connect"); + assert!(from_env.exists(), "DATABASE_URL database was opened"); + + cleanup(&dir, &from_env); + } +} diff --git a/docs/laravel-parity.md b/docs/laravel-parity.md index 952f4c4..4721377 100644 --- a/docs/laravel-parity.md +++ b/docs/laravel-parity.md @@ -71,8 +71,8 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | `Illuminate\Bus` | `rustasea-queue` (`BatchHandle`, `BatchId`) | **Partial** | Batch handles plus a durable `DatabaseBatchRepository` over the `job_batches` table (`crates/rustasea-queue/src/batch_db.rs:77`). | | `lorisleiva/laravel-actions` | `rustasea-action` (`Action`, `ActionController`, `ActionJob`, `ActionCommand`, `ActionListener`) | **Partial** | One action unit invoked from HTTP/queue/CLI/events with validate/authorize hooks; `make:action` generator; scaffold auth actions demonstrate the pattern (ADOPT-028). | | `Laravel\Horizon` | `rustasea-queue-dashboard` (`DashboardConfig`, `sampler`, `QueueMetricsHistory`) | **Partial** | Queue dashboard (`/queue`): live depth/age, `queue_metrics` history + retention, failed-job retry/forget, worker heartbeats; feature `queue-dashboard` (ADOPT-021). No supervisor/balancing/auto-scaling yet. | -| `Illuminate\Auth` | `rustasea-auth` (`AuthManager`, `Guard`, `JwtGuard`, `SessionGuard`) | **Partial** | JWT/CSRF/throttle real; session guard real over `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`) with an in-memory default store and a database store (`crates/rustasea-auth/src/session/database.rs:74`); users resolve through the database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`), which the runnable app installs at boot when the `users` table exists (`crates/rustasea-app/src/bootstrap/auth.rs:333`). | -| `Illuminate\Auth\Access` | `rustasea-router` (`AuthorizeRegistry`, `AuthorizeResource`, `#[authorize]` metadata) | **Adopted** | `#[authorize]` metadata is resolved and enforced at dispatch: `Router::authorize_meta` consumes the macro-emitted tuple (`crates/rustasea-router/src/authorize.rs:216`), and `apply_authorize` wraps the route in a fail-closed authorization layer (`crates/rustasea-router/src/dispatch.rs:202`). | +| `Illuminate\Auth` | `rustasea-auth` (`AuthManager`, `Guard`, `JwtGuard`, `SessionGuard`) | **Partial** | JWT/CSRF/throttle real; session guard real over `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`) with an in-memory default store and a database store (`crates/rustasea-auth/src/session/database.rs:74`); users resolve through the database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`), which the runnable app installs at boot when the `users` table exists (`crates/rustasea-app/src/bootstrap/auth.rs:337`). | +| `Illuminate\Auth\Access` | `rustasea-router` (`AuthorizeRegistry`, `AuthorizeResource`, `#[authorize]` metadata) | **Adopted** | `#[authorize]` metadata is resolved and enforced at dispatch: `Router::authorize_meta` consumes the macro-emitted tuple (`crates/rustasea-router/src/authorize.rs:216`), and `apply_authorize` wraps the route in a fail-closed authorization layer (`crates/rustasea-router/src/dispatch.rs:209`). | | `Illuminate\Validation` | `rustasea-validation` (`Validatable`, `Rules`, `ErrorBag`, `FormRequest`) | **Partial** | Rules + ErrorBag + form requests real; DB presence verifier absent. | | `Illuminate\Hashing` | `rustasea-auth` (`PasswordVerifier`, `Argon2Verifier`) | **Partial** | Argon2 verifier real; no hasher manager / rehash policy. | | `Illuminate\Session` | `rustasea-auth` (`SessionGuard`, `SessionPolicy`) | **Partial** | `tower-sessions`-backed session guard real (`crates/rustasea-auth/src/session.rs:99`); the default store is in-memory and `driver = "database"` in `config/session.toml` selects the persistent `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`, built by `from_config_database` `crates/rustasea-auth/src/session.rs:155`). No Redis/file/cookie store. | @@ -171,7 +171,7 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | `Illuminate\Contracts\Routing\UrlRoutable` | `rustasea-router::{ModelBinder, BindingRegistry}` | **Partial** | Implicit model binding for `{post:slug}` selector routes via registered binders (`crates/rustasea-router/src/binding.rs`); no named-route URL generation. | | `Illuminate\Routing\Contracts\ControllerDispatcher` | `rustasea-router::dispatch` | **Adopted** | Real controller dispatch landed in GAP-002. | | `Illuminate\Routing\Contracts\CallableDispatcher` | `rustasea-router::Handler` | **Partial** | Handler trait real; closure/callable dispatch breadth narrower. | -| `Illuminate\Routing\Controllers\HasMiddleware` | `rustasea-router::MiddlewareRegistry` + `rustasea-macros::#[middleware]` | **Adopted** | `#[middleware]` emits a doc-hidden spec list consumed by `Router::middleware_meta` (`crates/rustasea-router/src/metadata.rs:237`) and enforced by `apply_middleware` at dispatch (`crates/rustasea-router/src/dispatch.rs:176`). | +| `Illuminate\Routing\Controllers\HasMiddleware` | `rustasea-router::MiddlewareRegistry` + `rustasea-macros::#[middleware]` | **Adopted** | `#[middleware]` emits a doc-hidden spec list consumed by `Router::middleware_meta` (`crates/rustasea-router/src/metadata.rs:237`) and enforced by `apply_middleware` at dispatch (`crates/rustasea-router/src/dispatch.rs:183`). | | `Illuminate\Contracts\Http\Kernel` | `rustasea-http::AppState` | **Partial** | Middleware stack assembled via axum/tower; no single Kernel contract. | | `Illuminate\Http\Client\Factory` | `rustasea-http::HttpClient` | **Partial** | Client real; no fake/record-replay factory. | | `Illuminate\Http\Resources\JsonApi\Concerns\ResolvesJsonApiElements` | `rustasea-jsonapi::ResourceBuilder` | **Adopted** | Element resolution + document shaping implemented. | @@ -197,13 +197,13 @@ It is the API-surface parity layer. It is intentionally **not** a 1:1 inventory | Laravel interface/trait | RustaSea equivalent | Status | Rationale | |---|---|---|---| -| `Illuminate\Contracts\Auth\Guard` | `rustasea-auth::Guard` | **Adopted** | Guard trait + JWT implementation real; JWT `logout` revokes the token pair and refresh tokens are single-use (`crates/rustasea-auth/src/jwt.rs:298`, `:279`). | +| `Illuminate\Contracts\Auth\Guard` | `rustasea-auth::Guard` | **Adopted** | Guard trait + JWT implementation real; JWT `logout` revokes the token pair and refresh tokens are single-use (`crates/rustasea-auth/src/jwt.rs:314`, `:295`). | | `Illuminate\Contracts\Auth\StatefulGuard` | `rustasea-auth::SessionGuard` | **Partial** | `tower-sessions`-backed session guard real (`crates/rustasea-auth/src/session.rs:99`); default store is in-memory, with a database store selectable by config (`crates/rustasea-auth/src/session/database.rs:74`). | | `Illuminate\Contracts\Auth\Authenticatable` | `rustasea-auth::AuthUser` | **Adopted** | User identity type implemented. | | `Illuminate\Contracts\Auth\UserProvider` | `rustasea-auth::{UserProvider, UserLookup}` | **Adopted** | Async write+read `UserProvider` (`crates/rustasea-auth/src/users/provider.rs:110`) with a database implementation over the `users` table (`DatabaseUserProvider`, `crates/rustasea-auth/src/users/provider/database.rs:49`), an in-memory one, and a fail-closed default; the sync `UserLookup` remains for guard reads. The database provider is exercised on SQLite only. | | `Illuminate\Contracts\Auth\Factory` | `rustasea-auth::AuthManager` | **Adopted** | Named guard registration + `Auth::extend` real. | -| `Illuminate\Contracts\Auth\Access\Gate` | `rustasea-router::AuthorizeRegistry` | **Partial** | Record-level authorization enforced at dispatch: `#[authorize]` metadata resolves through `Router::authorize_meta` (`crates/rustasea-router/src/authorize.rs:216`) and `apply_authorize` fails closed on an unregistered resource (`crates/rustasea-router/src/dispatch.rs:202`). A general-purpose ability `Gate` (named abilities with `before`/`after` hooks) lives in `rustasea-auth` (`crates/rustasea-auth/src/gate/mod.rs:176`). | -| `Illuminate\Contracts\Auth\Access\Authorizable` | `rustasea-router::{AuthorizeRegistry, AuthorizeResource}` | **Partial** | `#[authorize]` metadata is enforced at runtime (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:202`); no `Authorizable` trait on models yet. | +| `Illuminate\Contracts\Auth\Access\Gate` | `rustasea-router::AuthorizeRegistry` | **Partial** | Record-level authorization enforced at dispatch: `#[authorize]` metadata resolves through `Router::authorize_meta` (`crates/rustasea-router/src/authorize.rs:216`) and `apply_authorize` fails closed on an unregistered resource (`crates/rustasea-router/src/dispatch.rs:209`). A general-purpose ability `Gate` (named abilities with `before`/`after` hooks) lives in `rustasea-auth` (`crates/rustasea-auth/src/gate/mod.rs:176`). | +| `Illuminate\Contracts\Auth\Access\Authorizable` | `rustasea-router::{AuthorizeRegistry, AuthorizeResource}` | **Partial** | `#[authorize]` metadata is enforced at runtime (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:209`); no `Authorizable` trait on models yet. | | `Illuminate\Contracts\Auth\CanResetPassword` | — | **Planned** | No password-reset broker. | | `Illuminate\Contracts\Auth\MustVerifyEmail` | `rustasea-auth::EmailVerification` | **Partial** | Verification trait + memory impl real; the runnable app delivers the verification mail through `rustasea-mail` (`crates/rustasea-app/src/routes/auth/verification.rs:165`). | | `Illuminate\Contracts\Auth\PasswordBroker` | `rustasea-auth::PasswordResetStore` | **Partial** | Token-store seam with hashed-at-rest tokens, an in-memory store, and a fail-closed default (`crates/rustasea-auth/src/password_reset.rs:73`, `:135`, `:174`); no database-backed token table yet. | diff --git a/docs/milestones.md b/docs/milestones.md index c92bfa1..1865bb0 100644 --- a/docs/milestones.md +++ b/docs/milestones.md @@ -1,6 +1,6 @@ # RustaSea Milestone Status -> **Last updated:** 2026-11-20 +> **Last updated:** 2026-11-21 > **Scope:** Authoritative done / partial / missing status for milestones **M0–M6**, plus the **gap-closure program** progress (P0–P5). ## Purpose @@ -40,10 +40,10 @@ section records the reason. | Milestone | Goal | Status | Headline evidence | |---|---|---|---| -| **M0** | Bootstrap & Core | **Partial** | Container, provider DAG, and config auto-discovery real (`crates/rustasea-foundation/src/lib.rs:275`, `:296`; `crates/rustasea-config/src/lib.rs:89`); bootstrap registries populated (`bootstrap/providers.rs:35`, `bootstrap/commands.rs:12`) ; boot mounts the config loader (`crates/rustasea-foundation/src/lib.rs:309`) and the app's `AppServiceProvider` binds environment-derived defaults (`crates/rustasea-app/src/bootstrap/providers.rs:124`); the framework providers bind the database resolver, cache manager, and queue config at boot (`crates/rustasea/src/services.rs:61`, `:80`, `:99`); remaining: the uncompiled root `bootstrap/` mirror | -| **M1** | Routing & HTTP | **Partial** | Router DSL + controller dispatch real (`crates/rustasea-router/src/dispatch.rs:119`, `:318`); `route:list` renders the live 6-column table published at boot via `RouteSource` (`crates/rustasea-cli/src/routes.rs:19`, `:33`; `crates/rustasea-app/src/bootstrap/app.rs:57`; `crates/rustasea-cli/src/commands/inspect.rs:44`); `show:model` now parses `app/models/{snake}.rs` with `syn` for source-level metadata (`crates/rustasea-cli/src/model_inspect.rs:123`, `:217`; `crates/rustasea-cli/src/commands/inspect.rs:129`) and the HTTP client idle (inter-chunk) timeout is now enforced for streamed bodies (`crates/rustasea-http/src/idle.rs:23`, wired in `crates/rustasea-http/src/lib.rs:448`) | +| **M0** | Bootstrap & Core | **Partial** | Container, provider DAG, and config auto-discovery real (`crates/rustasea-foundation/src/lib.rs:275`, `:296`; `crates/rustasea-config/src/lib.rs:89`); bootstrap registries populated (`bootstrap/providers.rs:35`, `bootstrap/commands.rs:12`) ; boot mounts the config loader (`crates/rustasea-foundation/src/lib.rs:309`) and the app's `AppServiceProvider` binds environment-derived defaults (`crates/rustasea-app/src/bootstrap/providers.rs:124`); the framework providers bind the database resolver, cache manager, and queue config at boot (`crates/rustasea/src/services.rs:63`, `:117`, `:136`), in the runnable app and in generated apps; remaining: the uncompiled root `bootstrap/` mirror | +| **M1** | Routing & HTTP | **Partial** | Router DSL + controller dispatch real (`crates/rustasea-router/src/dispatch.rs:126`, `:325`); `route:list` renders the live 6-column table published at boot via `RouteSource` (`crates/rustasea-cli/src/routes.rs:19`, `:33`; `crates/rustasea-app/src/bootstrap/app.rs:57`; `crates/rustasea-cli/src/commands/inspect.rs:44`); `show:model` now parses `app/models/{snake}.rs` with `syn` for source-level metadata (`crates/rustasea-cli/src/model_inspect.rs:123`, `:217`; `crates/rustasea-cli/src/commands/inspect.rs:129`) and the HTTP client idle (inter-chunk) timeout is now enforced for streamed bodies (`crates/rustasea-http/src/idle.rs:23`, wired in `crates/rustasea-http/src/lib.rs:448`) | | **M2** | ORM & Database | **Done** | Real sqlx pool + async execution (`crates/rustasea-orm/src/db.rs:24`, `db/exec.rs:72`); model CRUD (`model_ops.rs:28`), transactions (`tx.rs:67`), custom `Migrator` (`migration.rs:131`, `:189`), eager loading (`eager.rs:59`), pgvector (`vector.rs:100`); `raw`/`raw_sql` remain display-only fragments (`execution.rs:239`, `:247`) | -| **M3** | Auth, Middleware & Validation | **Partial** | JWT/CSRF/throttle/validation real; session guard now real via `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`, `impl Guard` `:291`, login `:296`, parse `:352`, refresh `:380`, logout `:408`); declarative attributes are consumed at runtime through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:176`) and `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:202`); store-backed options are real: `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`) and `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`); remaining: scaffolded apps do not wire the database user provider yet (see section) | +| **M3** | Auth, Middleware & Validation | **Partial** | JWT/CSRF/throttle/validation real; session guard now real via `tower-sessions` (`crates/rustasea-auth/src/session.rs:99`, `impl Guard` `:291`, login `:296`, parse `:352`, refresh `:380`, logout `:408`); declarative attributes are consumed at runtime through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:183`) and `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:209`); store-backed options are real: `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`) and `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`); remaining: scaffolded apps do not wire the database user provider yet (see section) | | **M4** | Queue, Cache, Scheduling & Events | **Partial** | Database/Redis queue drivers + worker + persistent failed jobs real (`crates/rustasea-queue/src/driver/database.rs:36`, `driver/worker.rs:75`); `queue:work`/`queue:failed`/`queue:retry` CLI real (`crates/rustasea-cli/src/commands/queue.rs:18`, `ops.rs:21`, `:72`); Redis cache store real behind the `redis` feature (`crates/rustasea-cache/src/redis.rs:155`); async listeners enqueue (`crates/rustasea-events/src/dispatcher.rs:82`); declarative job attributes bind through `JobPolicy` at registration (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`); failed `sync` dispatches are dead-lettered through the configured default queue connection (`crates/rustasea-queue/src/driver.rs:192`); remaining: the scheduler cannot dispatch a due command (`crates/rustasea-schedule/src/scheduler.rs:146`), schedule pause state is per-process, and after-response events are never flushed (`crates/rustasea-events/src/dispatcher.rs:254`) | | **M5** | DX, CLI & Testing | **Partial** | CLI + 17 `make:*` generators real (canonical `enum Kind`: `crates/rustasea-cli/src/generators/mod.rs:19-54`; registrations `crates/rustasea-cli/src/commands/mod.rs:17-31`); `cargo rustasea new --variant` real (`crates/rustasea/src/bin/cargo-rustasea.rs:46`); real `xtask` cycle detection (`xtask/src/cycles.rs:32`) and `xtask migrate` (`xtask/src/main.rs:37`); testcontainers-backed `PostgresTestDb` (`crates/rustasea-testing/src/fixtures.rs:49`) with a Docker-gated suite (`crates/rustasea/tests/feature/`); remaining: integration tests are opt-in and generated controllers still need manual route registration (`crates/rustasea-cli/src/generators/kinds/controller.rs:35`) | | **M6** | Advanced (Broadcast, Search, FS, AI) | **Partial** | Broadcast WS/SSE, `object_store` storage + `config/storage.toml` facade, JSON:API, `rustasea-mail`, `rustasea-view`/`rustasea-inertia`/`rustasea-livewire`/`rustasea-scaffold`, real AI HTTP providers (`crates/rustasea-ai/src/providers/mod.rs:28`), AI queueing (`crates/rustasea-ai/src/queue.rs:41`), MCP client (`crates/rustasea-ai/src/mcp/client.rs:40`), and feature-gated pgvector (`crates/rustasea-search/src/pgvector.rs:24`) all real; Gemini/Bedrock served through their OpenAI-compatible endpoints (`crates/rustasea-ai/src/providers/client.rs:225`, `:382`); remaining: the agent runtime does not call a provider (`crates/rustasea-ai/src/agent.rs:247`), provider-native Gemini/Bedrock APIs, and `InProcessProvider` kept for deterministic tests | @@ -59,15 +59,16 @@ container, provider lifecycle, and graceful shutdown. providers by a real dependency DAG, loads all `config/*.toml`, and shuts down gracefully within a bounded drain. Boot mounts the config loader in the container; framework providers bind the database connection resolver, the cache -manager, and the queue configuration, and the runnable app registers them. +manager, and the queue configuration, and both the runnable app and generated +apps register them. Remaining: the uncompiled root `bootstrap/` mirror. **Done** - Service container with `bind` / `singleton` / `instance` / `get` — `crates/rustasea-foundation/src/lib.rs:103`, `:114`, `:125`, `:136`. - `Application::boot` runs register → boot with a real topological sort — `crates/rustasea-foundation/src/lib.rs:275`, `:296`. - Provider dependency declaration + typed cycle detection — `crates/rustasea-foundation/src/lib.rs:27` (`ServiceProvider::dependencies`), `:187` (`BootError::DependencyCycle`), `:311`/`:338` (cycle extraction); tests `crates/rustasea-foundation/tests/boot_dag.rs`. -- Graceful shutdown on `SIGTERM`/`SIGINT` with a bounded drain: after the signal, `graceful` exits the process with status 1 if the drain outlives its timeout (`crates/rustasea-foundation/src/shutdown.rs:20`; 30 s through `Application::shutdown`). -- Database, cache, and queue bindings at boot — `rustasea::services` (`crates/rustasea/src/services.rs:61` `DatabaseServiceProvider` binds a lazily connecting `ConnectionResolver`, `:80` `CacheServiceProvider` binds a `CacheManager`, `:99` `QueueServiceProvider` registers the `sync`/`redis` connections and binds `QueueConfig`; `:139` `connect_database_queues` registers `database` connections after boot). The runnable app registers them (`crates/rustasea-app/src/bootstrap/providers.rs:199`, `crates/rustasea-app/src/main.rs:32`). +- Graceful shutdown on `SIGTERM`/`SIGINT` with a bounded drain: after the signal, `graceful` exits the process with status 1 if the drain outlives its timeout (`crates/rustasea-foundation/src/shutdown.rs:128`; `DEFAULT_DRAIN_TIMEOUT` is 30 s, `:28`). A caller that keeps running after draining holds `GracefulShutdown::guard` (`:89`) for the drain; dropping the guard cancels the deadline. The runnable app does this (`crates/rustasea-app/src/main.rs`). +- Database, cache, and queue bindings at boot — `rustasea::services` (`crates/rustasea/src/services.rs:63` `DatabaseServiceProvider` binds a lazily connecting `ConnectionResolver`, with `DATABASE_URL` (then `DATABASE__URL`) replacing the default connection as it does for the CLI (`:88`); `:117` `CacheServiceProvider` binds a `CacheManager`; `:136` `QueueServiceProvider` registers the `sync`/`redis` connections and binds `QueueConfig`; `:181` `connect_database_queues` registers each `database` queue connection on the database connection it names, after boot). The runnable app registers them (`crates/rustasea-app/src/bootstrap/providers.rs:199`, `crates/rustasea-app/src/main.rs:33`) and opens its database user provider and queue dashboard through the bound resolver; generated apps register them too (`crates/rustasea-scaffold/src/templates/bootstrap.rs:75`, `crates/rustasea-scaffold/src/templates/entry.rs:38`). - Config loader auto-discovers all `config/*.toml` with TOML + `.env` overlay (`__` separator, TOML only) — `crates/rustasea-config/src/lib.rs:32`, `:40`, `:57`, `:89`. - Populated bootstrap registries — `bootstrap/providers.rs:35` (provider vec), `bootstrap/commands.rs:12` (`register_default()` loads the CLI command registry); mirror in `crates/rustasea-app/src/bootstrap/{providers.rs:33,commands.rs:13}`. - Project scaffolder `cargo rustasea new --variant {blade|react|vue|svelte|livewire}` — `crates/rustasea/src/bin/cargo-rustasea.rs:46`, `:64-74`; starter kits in `crates/rustasea-scaffold/src/variant.rs:13`. @@ -75,16 +76,14 @@ Remaining: the uncompiled root `bootstrap/` mirror. **Partial (reason)** - The runnable app's `AppServiceProvider` binds only environment-derived defaults (environment name, password policy, destructive-command guard) — `crates/rustasea-app/src/bootstrap/providers.rs:124`; `AuthServiceProvider` installs the session guard (`:173`). -- Features that predate the service providers still open their own pool instead of the bound resolver: the queue dashboard and the database user provider (`crates/rustasea-app/src/bootstrap/auth.rs:333`). The scaffold templates do not register the service providers yet. - The root `bootstrap/` directory is an uncompiled skeleton mirror; its `AppServiceProvider` is a no-op (`bootstrap/providers.rs:17`). The compiled bootstrap is `crates/rustasea-app/src/bootstrap/`. **Missing** -- Service provider registration in the scaffold templates. +- None beyond the partial items above. **Evidence:** `crates/rustasea-foundation/src/lib.rs:27-452`; `crates/rustasea-config/src/lib.rs:32-89`; `bootstrap/{app.rs,providers.rs,commands.rs}`; `crates/rustasea-app/src/main.rs`; tasks `GAP-001`, `GAP-019`. **Next actions** -- Register the service providers in the scaffold templates, and move the queue dashboard and the database user provider onto the bound resolver. - Remove or regenerate the uncompiled root `bootstrap/` mirror. --- @@ -103,14 +102,14 @@ reflected. **Done** - Router DSL: `get`/`post`/`put`/`delete`/`patch`/`options`/`any`, `group`, prefix/name/domain/resource — `crates/rustasea-router/src/router.rs:46` (`prefix`), `:61` (`domain`), `:73` (`get`), `:288` (`group`), `:317` (`resource`). -- Controller dispatch to real handlers (`GAP-002`) — `crates/rustasea-router/src/dispatch.rs:119` (`into_axum_router`), `:318` (`resolve`). +- Controller dispatch to real handlers (`GAP-002`) — `crates/rustasea-router/src/dispatch.rs:126` (`into_axum_router`), `:325` (`resolve`). - `#[route]` metadata consumed at registration — `crates/rustasea-router/src/router.rs:218` (`route_meta`); route table introspection surface — `:358` (`get_routes`). - `route:list` renders the live 6-column table (Method, URI, Name, Action, Middleware, Binding). The application publishes a `RouteSource` closure at boot (`crates/rustasea-app/src/bootstrap/app.rs:57`), stored process-wide (`crates/rustasea-cli/src/routes.rs:19` `RouteSource`, `:33` `set_route_source`, `:52` `routes`) and read back by the command (`crates/rustasea-cli/src/commands/inspect.rs:44`, rendered at `:49-67`). Covered by `crates/rustasea-cli/src/commands/inspect.rs:182-274` and `crates/rustasea-app/src/bootstrap/app.rs:347-356`. - `show:model` introspects `app/models/{snake}.rs` with `syn`: the struct name, resolved table (`#[model(table)]` override, hand-written `table_name()`, else `snake_plural`), attributes (name/type/nullable), declared casts, soft-delete/timestamps flags, and best-effort relations from the `relations()` body; `--json` emits the `model-inspector` contract shape. Both the `#[derive(Model)]` style and the hand-written `impl Model` emitted by `make:model` / the app scaffold are recognised. Parser in `crates/rustasea-cli/src/model_inspect.rs:123` (`inspect_source`), `:217` (`inspect_model`), hand-written `impl` metadata in `crates/rustasea-cli/src/model_inspect/impl_model.rs:37` (`model_impl_target`), `:55` (`parse_impl_model`), relation-token scanning in `crates/rustasea-cli/src/model_inspect/relations.rs:14` (`scan_tokens`); command in `crates/rustasea-cli/src/commands/inspect.rs:129` (`run`), `:152` (`render_model`), `:164` (`render_human`). - HTTP client `throw` / `try_throw` callbacks and typed `HttpError` — `crates/rustasea-http/src/lib.rs:286`, `:298`, `:207`. - HTTP client idle (inter-chunk) timeout enforced for streamed bodies: when `idle_timeout` is set, the response body is drained chunk by chunk under a per-chunk `tokio::time::timeout`, aborting with `HttpError::Timeout { kind: TimeoutKind::Idle }` on a stall longer than the budget; the plain path returns the response untouched (`crates/rustasea-http/src/idle.rs:23`, `buffer_with_idle_timeout`), wired in `crates/rustasea-http/src/lib.rs:448`; tests in `crates/rustasea-http/tests/idle_timeout.rs`. - Runnable app serves real handlers from `routes/web.rs` (welcome page rendered through `rustasea::view::MinijinjaEngine`). -- Domain routes match the request host: routes sharing a method+path are served by `HostDispatch`, which picks the first route whose domain matches the `Host` header (a `{name}` label matches one DNS label) and falls back to the route without a domain (`crates/rustasea-router/src/host.rs:28`, `:60`; `crates/rustasea-router/src/dispatch.rs:151`). Captured `{name}` labels are not exposed as route parameters. +- Domain routes match the request host: routes sharing a method+path are served by `HostDispatch`, which picks the route whose domain matches the `Host` header, trying exact domains before `{name}` domains (a `{name}` label matches one DNS label, and a trailing dot on the host is ignored), and falls back to the route without a domain (`crates/rustasea-router/src/host.rs:36`, `:77`; `crates/rustasea-router/src/dispatch.rs:158`). Captured `{name}` labels are not exposed as route parameters. **Partial (reason)** - `show:model` reports declared source metadata only; live DB column types/constraints are not queried (the console has no pool handle). @@ -118,7 +117,7 @@ reflected. **Missing** - Live database column introspection for `show:model` (source metadata is implemented). -**Evidence:** `crates/rustasea-router/src/router.rs:46-358`; `crates/rustasea-router/src/dispatch.rs:49-124`; `crates/rustasea-http/src/lib.rs:241-379`; `crates/rustasea-http/src/idle.rs:23-60`; `crates/rustasea-http/tests/idle_timeout.rs`; `crates/rustasea-cli/src/routes.rs:19-57`; `crates/rustasea-cli/src/commands/inspect.rs:44-67`, `:129-176`; `crates/rustasea-cli/src/model_inspect.rs:123-231`; `crates/rustasea-cli/src/model_inspect/impl_model.rs:37-88`; `crates/rustasea-cli/src/model_inspect/relations.rs:14-87`; `crates/rustasea-app/src/bootstrap/app.rs:57`; task `GAP-002` (completed), `GAP-029` (completed), `GAP-030` (completed). +**Evidence:** `crates/rustasea-router/src/router.rs:46-358`; `crates/rustasea-router/src/dispatch.rs:50-131`; `crates/rustasea-http/src/lib.rs:241-379`; `crates/rustasea-http/src/idle.rs:23-60`; `crates/rustasea-http/tests/idle_timeout.rs`; `crates/rustasea-cli/src/routes.rs:19-57`; `crates/rustasea-cli/src/commands/inspect.rs:44-67`, `:129-176`; `crates/rustasea-cli/src/model_inspect.rs:123-231`; `crates/rustasea-cli/src/model_inspect/impl_model.rs:37-88`; `crates/rustasea-cli/src/model_inspect/relations.rs:14-87`; `crates/rustasea-app/src/bootstrap/app.rs:57`; task `GAP-002` (completed), `GAP-029` (completed), `GAP-030` (completed). **Next actions** - Optionally add live DB column introspection to `show:model` when a pool is available. @@ -176,13 +175,13 @@ selectable. Remaining: both defaults stay in-memory / fail-closed until configured, and scaffolded apps do not wire the database user provider yet. **Done** -- JWT guard — `crates/rustasea-auth/src/jwt.rs`. Each login issues an access/refresh pair sharing a session id; `logout` revokes the pair (`:298`) and `refresh` is single-use (`:279`), both through a cache `Store` that is per-process memory by default and shareable through `with_revocation_store` (`:142`; `crates/rustasea-auth/src/jwt/revoke.rs`). +- JWT guard — `crates/rustasea-auth/src/jwt.rs`. Each login issues an access/refresh pair sharing a session id; `logout` revokes the pair, even from an expired access token (`:314`), and `refresh` is single-use (`:295`), both through a cache `Store` that is per-process memory by default and shareable through `with_revocation_store` (`:142`; `crates/rustasea-auth/src/jwt/revoke.rs`). - Origin-aware CSRF protection (`Sec-Fetch-Site`) — `crates/rustasea-auth/src/csrf.rs`. - Rate limiter / throttle — `crates/rustasea-auth/src/throttle/`. - Validation crate (rules, ErrorBag, form requests) — `crates/rustasea-validation/`. `in:` / `in_array:` read each list item as JSON when it parses and as text otherwise, so `in:admin,editor` works (`crates/rustasea-validation/src/rules/support.rs:134`). - Guard manager with typed `GuardMismatch` errors — `crates/rustasea-auth/src/guard.rs:197`, `:302`. - Real session guard over `tower-sessions` (`GAP-007`): `crates/rustasea-auth/src/session.rs:99` (`SessionGuard`), `:291` (`impl Guard`), `:296` (`login`, fresh session id on login), `:331` (`login_using_id`, opt-in via `:194`), `:352` (`parse`), `:380` (`refresh`, id cycling), `:408` (`logout`, flushes the store), `:427` (`user`), `:442` (`id`); dependency `crates/rustasea-auth/Cargo.toml:20`. -- Declarative attributes consumed at runtime: `#[middleware]` emits a doc-hidden `__RUSTASEA_MIDDLEWARE_` spec list consumed by `Router::middleware_meta` (`crates/rustasea-router/src/metadata.rs:237`) and enforced by `apply_middleware` (`crates/rustasea-router/src/dispatch.rs:176`); `#[authorize]` emits `__RUSTASEA_AUTHORIZE_` tuples consumed by `Router::authorize_meta` (`crates/rustasea-router/src/authorize.rs:216`) and enforced by `apply_authorize` (`crates/rustasea-router/src/dispatch.rs:202`), a missing/ambiguous resource failing closed with `RouteError::UnknownAuthorization`. +- Declarative attributes consumed at runtime: `#[middleware]` emits a doc-hidden `__RUSTASEA_MIDDLEWARE_` spec list consumed by `Router::middleware_meta` (`crates/rustasea-router/src/metadata.rs:237`) and enforced by `apply_middleware` (`crates/rustasea-router/src/dispatch.rs:183`); `#[authorize]` emits `__RUSTASEA_AUTHORIZE_` tuples consumed by `Router::authorize_meta` (`crates/rustasea-router/src/authorize.rs:216`) and enforced by `apply_authorize` (`crates/rustasea-router/src/dispatch.rs:209`), a missing/ambiguous resource failing closed with `RouteError::UnknownAuthorization`. - Role-based access control (ADOPT-001, `spatie/laravel-permission` parity): `crates/rustasea-auth/src/rbac/` (`Role`, `RbacRegistry`, `HasRoles`, `PermissionResolver`): roles hold permissions, permission checks are the union over a user's roles, lookups are cache-backed, and the ability `Gate` consults an optional `PermissionResolver` after its defined abilities (`crates/rustasea-auth/src/rbac/{mod,role,registry,has_roles}.rs`). - Model-change audit trail (ADOPT-002, `spatie/laravel-activitylog` parity): `crates/rustasea-activitylog` (`ActivityLogger`, `ActivityEvent`): `#[logs_activity]` opts a model in, the ORM write path builds a diff event, and the logger persists it to the `audit_log` table with an optional `batch_uuid` (`crates/rustasea-activitylog/src/{lib,recorder,model}.rs`). - Authentication log (ADOPT-003, `rappasoft/laravel-authentication-log` parity): `crates/rustasea-authlog` (`AuthenticationLogLogger`, `NewDeviceNotifier`): one row per login/failed/lockout/logout with client IP and `User-Agent`, plus a queued new-device notification on an unknown IP (`crates/rustasea-authlog/src/{lib,recorder,notifier}.rs`). @@ -190,15 +189,15 @@ configured, and scaffolded apps do not wire the database user provider yet. **Partial (reason)** - The default session store is in-memory (`MemoryStore`). `driver = "database"` in `config/session.toml` selects the persistent `DatabaseSessionStore` (`crates/rustasea-auth/src/session/database.rs:74`), built by `SessionGuard::from_config_database` (`crates/rustasea-auth/src/session.rs:155`); the `redis` driver is rejected at load time. -- The guard's default synchronous lookup is the fail-closed `StaticLookup` (`crates/rustasea-auth/src/session.rs:194`). The database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`) covers registration, login, password reset, verification, and profile updates over the `users` table; the runnable app installs it at boot when the default guard's provider is ORM-backed and the table exists (`crates/rustasea-app/src/bootstrap/auth.rs:333`, called from `crates/rustasea-app/src/main.rs:40`). +- The guard's default synchronous lookup is the fail-closed `StaticLookup` (`crates/rustasea-auth/src/session.rs:194`). The database-backed `DatabaseUserProvider` (`crates/rustasea-auth/src/users/provider/database.rs:49`) covers registration, login, password reset, verification, and profile updates over the `users` table; the runnable app installs it at boot when the default guard's provider is ORM-backed and the table exists, opening it through the bound connection resolver (`crates/rustasea-app/src/bootstrap/auth.rs:337`, called from `crates/rustasea-app/src/main.rs:41`). - `DatabaseUserProvider` is exercised on SQLite only (`crates/rustasea-auth/tests/database_user_provider.rs`); it has not been run against Postgres or MySQL. - The deserialization allow-list (`SessionPolicy::allow`) is defined but not called; `cache.serializable_classes` is parsed and unused (`crates/rustasea-cache/src/config.rs:191`). **Missing** -- Database user provider wiring in the scaffold templates (`crates/rustasea-scaffold/src/templates/`), so generated apps get it without hand-wiring. +- Database user provider wiring in the scaffold templates (`crates/rustasea-scaffold/src/templates/`), so generated apps get it without hand-wiring. Generated apps have no login flow yet to wire it into: their auth controllers and `attempt` action are `todo!()` stubs (`crates/rustasea-scaffold/src/templates/app_http.rs`, `app_auth.rs`). - A Redis session store. -**Evidence:** `crates/rustasea-auth/src/{jwt,csrf,guard,session}.rs`; `crates/rustasea-auth/src/rbac/`; `crates/rustasea-activitylog/`; `crates/rustasea-authlog/`; `crates/rustasea-http/src/sentry.rs`; `crates/rustasea-logging/src/sentry/`; `crates/rustasea-auth/Cargo.toml:20`; `crates/rustasea-router/src/{metadata.rs:237,authorize.rs:216,dispatch.rs:176,202}`; tasks `GAP-003`, `GAP-007`, `ADOPT-001`–`ADOPT-004`. +**Evidence:** `crates/rustasea-auth/src/{jwt,csrf,guard,session}.rs`; `crates/rustasea-auth/src/rbac/`; `crates/rustasea-activitylog/`; `crates/rustasea-authlog/`; `crates/rustasea-http/src/sentry.rs`; `crates/rustasea-logging/src/sentry/`; `crates/rustasea-auth/Cargo.toml:20`; `crates/rustasea-router/src/{metadata.rs:237,authorize.rs:216,dispatch.rs:183,209}`; tasks `GAP-003`, `GAP-007`, `ADOPT-001`–`ADOPT-004`. **Next actions** - Wire `DatabaseUserProvider` into the scaffold templates. @@ -378,8 +377,8 @@ AI provider is kept for tests. | Task | Title | Status | Evidence | |---|---|---|---| | **GAP-001** | Wire sqlx DB backend + connection pool into `rustasea-orm` | **Done** | `crates/rustasea-orm/src/db.rs:24`, `crates/rustasea-orm/src/db/exec.rs:72` | -| **GAP-002** | Router → controller dispatch (real handler binding) | **Done** | `crates/rustasea-router/src/dispatch.rs:49-124` | -| **GAP-003** | Runtime consumer for declarative attributes (`#[middleware]`, `#[authorize]`, `#[tries]`, `#[backoff]`, `#[timeout]`) | **Done** | `#[middleware]` resolves through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:176`); `#[authorize]` resolves through `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:202`); job policy binds through `JobPolicy` (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`) | +| **GAP-002** | Router → controller dispatch (real handler binding) | **Done** | `crates/rustasea-router/src/dispatch.rs:50-131` | +| **GAP-003** | Runtime consumer for declarative attributes (`#[middleware]`, `#[authorize]`, `#[tries]`, `#[backoff]`, `#[timeout]`) | **Done** | `#[middleware]` resolves through `MiddlewareRegistry` (`crates/rustasea-router/src/metadata.rs:237`, `dispatch.rs:183`); `#[authorize]` resolves through `AuthorizeRegistry` (`crates/rustasea-router/src/authorize.rs:216`, `dispatch.rs:209`); job policy binds through `JobPolicy` (`crates/rustasea-queue/src/policy.rs:21`, `driver/worker.rs:66`) | **Other gap phases (all completed):** `GAP-004`–`GAP-009` (P1), `GAP-010`–`GAP-013` (P2), `GAP-014`–`GAP-015` (P3), `GAP-016`–`GAP-018` (P4), `GAP-019`–`GAP-020`