Skip to content
Merged
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
65 changes: 17 additions & 48 deletions crates/rustasea-app/src/bootstrap/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,9 @@ static SAMPLER_GUARD: std::sync::OnceLock<tokio::task::JoinHandle<()>> = 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
Expand Down Expand Up @@ -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"),
}
})
});
Expand Down Expand Up @@ -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<String, String> {
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::<String>("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
Expand Down
97 changes: 14 additions & 83 deletions crates/rustasea-app/src/bootstrap/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Arc<dyn UserProvider>> {
let pool = match rustasea::orm::DbPool::connect(url).await {
pub async fn database_user_provider(
resolver: &rustasea::orm::ConnectionResolver,
) -> Option<Arc<dyn UserProvider>> {
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
Expand Down Expand Up @@ -323,8 +326,9 @@ pub async fn database_user_provider(url: &str) -> Option<Arc<dyn UserProvider>>
/// 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
Expand All @@ -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");
Expand Down Expand Up @@ -396,74 +397,4 @@ pub fn user_provider(container: &Container) -> Option<Arc<dyn UserProvider>> {
}

#[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;
77 changes: 77 additions & 0 deletions crates/rustasea-app/src/bootstrap/auth/tests.rs
Original file line number Diff line number Diff line change
@@ -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);
}
14 changes: 13 additions & 1 deletion crates/rustasea-orm/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}`"
))),
}
}
Expand Down Expand Up @@ -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}");
}
}
16 changes: 13 additions & 3 deletions crates/rustasea-scaffold/src/templates/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Box<dyn ServiceProvider>> {
vec![Box::new(AppServiceProvider), Box::new(AuthServiceProvider)]
vec![
Box::new(DatabaseServiceProvider),
Box::new(CacheServiceProvider),
Box::new(QueueServiceProvider),
Box::new(AppServiceProvider),
Box::new(AuthServiceProvider),
]
}
"##;

Expand Down
Loading
Loading