mads-core 0.7.0

Framework-neutral dependency injection, configuration, and lifecycle core for MADS.rs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
# MADS.rs

MADS.rs 0.7.0 is a Rust application framework with a framework-neutral core,
a scoped Axum HTTP runtime, and explainable PostgreSQL/Diesel conditional
defaults. A root module selects one application; startup validates its scoped
graph and routes before it starts lifecycle hooks, checks a database, or binds
a socket.

## CLI quick start

From a project containing one MADS package and binary:

```bash
mads doctor
mads routes
mads run
# during development
mads dev
```

See the [authoritative CLI reference](docs/CLI.md) for target selectors,
forwarded application arguments, diagnostics, watcher behavior, inspection
limits, and database commands.

## Standard application

```rust,no_run
use mads::prelude::*;

mod user {
    use mads::prelude::*;

    #[module]
    pub struct UserHttpModule;
}
use user::UserHttpModule;

#[module(imports = [UserHttpModule])]
struct AppModule;

#[mads::main]
async fn main() -> Result<(), HttpRuntimeError> {
    Mads::run::<AppModule>().await
}
```

`Mads::run` is the recommended application entry point. The root module
selects its direct imports and the providers, controllers, routes, guards,
strategies, and official auto-configurations reachable through that graph.

## Crates and boundaries

- `mads-core` owns construction, providers, lifecycle, diagnostics, and
  generic scalar TOML/dotenv configuration, plus official conditional-default
  evaluation and redacted inspection reports. It has no database or HTTP
  dependency.
- `mads-common` owns route validation, Axum delivery, cookies, JWT/Passport,
  the official Diesel default, PostgreSQL pools, database infrastructure
  lifecycle, and migration execution.
- `mads` is the stable facade. Its default `common` feature exposes the HTTP
  runtime and persistence; disable default features for the core-only boundary.

```toml
[dependencies]
mads = "0.7.0"
serde = { version = "1", features = ["derive"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
```

MADS.rs supports Rust 1.85 and uses Rust edition 2024.

The default `common` feature remains the compatibility aggregate for HTTP and
PostgreSQL; it does not silently enable authentication. For an HTTP API without
Diesel, use `default-features = false` with `features = ["http", "jwt",
"cookies", "runtime-tokio"]`. `jwt` alone does not pull in Axum, while
`cookies` includes HTTP. Passport strategies and Bearer guards require `http +
jwt`; cookie guards additionally require `cookies`.

## Conventional configuration and HTTP

Only `Mads::run` loads conventional configuration. It reads the process
current working directory in this order:

1. optional `.env`, used only for interpolation;
2. optional `mads.toml` as ordinary configuration;
3. final `MADS_*` environment overrides.

Process variables win during `${NAME}` interpolation, dotenv loading never
mutates the process environment, and `MADS_SERVER__PORT` maps to
`server.port`. Both files may be absent; a present unreadable or malformed file
is a bootstrap failure. MADS does not search parent directories or
`CARGO_MANIFEST_DIR`.

```toml
# mads.toml
[server]
host = "127.0.0.1" # default
port = 3000        # default

[server.cors]
origins = ["https://app.example.com"]
methods = ["GET", "POST"]
allowed_headers = ["authorization", "content-type"]
exposed_headers = ["x-request-id"]
credentials = false
max_age_seconds = 600
```

Wildcard-capable CORS fields use a scalar, not a one-element list:

```toml
[server.cors]
origins = "*"
methods = ["GET", "POST"]
allowed_headers = "*"
exposed_headers = "*"
```

CORS is opt-in, validated before lifecycle startup, and applied as the
outermost layer to both generated and native routes. Wildcard origins or
headers cannot be combined with credentials. It is a browser response-access
policy, not authorization or CSRF protection.

Use the tracked [`.env.example`](.env.example) as a local template, copy it to
the ignored `.env`, and put real secrets in process variables in CI and
production.

## Low-level builder

Use the builder when configuration, migrations, hooks, binding, or router
composition must be explicit. It never loads `.env`, `mads.toml`, or `MADS_*`
on its own. The explicit address overrides `[server]` binding and may use port
zero; merge native Axum routes before passing the raw router to `serve_router`.

```rust,ignore
let mut builder = Mads::builder_with_config(config);
builder.root::<AppModule>()?;
builder.database_migrations(MIGRATIONS)?;
// builder.lifecycle_hook(MyHook);
let application = builder.build().await?;
let router = build_router(&application)?.merge(native_router);
serve_router(application, router, "127.0.0.1:0").await?;
```

For direct in-process router use, call `configure_router(&application, router)`
after the merge. A builder without `root::<AppModule>()` intentionally retains
the complete-catalog compatibility behavior.

## Database provisioning

This is zero **database** bootstrap, not zero application configuration. A
provider in the selected application scope that directly requires `Database`
activates the linked default only after configuration and virtual graph
validation. `database_migrations` separately registers one embedded source; it
does not create a pool, connect, or run migrations. It is required only when
`database.migrate = true`; existing pending embedded migrations then run after
readiness, and no pending migrations are a successful no-op. Normal startup
never generates or auto-applies migrations. The explicit `mads db generate`
command can create one review-required schema-diff migration from `src/schema.rs`
or recursively loaded `src/schema/**/*.rs`; inspect the generated `up.sql` and
`down.sql` before applying it with `mads db migrate`.

Inspect the retained, redacted decision records without exposing configuration
values:

```rust,ignore
for report in application.auto_configurations() {
    println!(
        "{} {:?} {}",
        report.identifier(),
        report.status(),
        report.reason_code().as_str(),
    );
}
```

`DatabaseBootstrap` remains the explicit native Diesel override. It backs off
the conditional default completely and contributes its database lifecycle as
framework infrastructure. An application-provided `Database` instead owns its
complete readiness, migration, and shutdown lifecycle:

```rust,ignore
use mads::{core::{ConfigBuilder, MapSource}, prelude::*};

let config = ConfigBuilder::new()
    .source(MapSource::new(
        "application",
        [("database.url", "postgres://localhost/mads")],
    ))
    .build()?;
let database = DatabaseConfig::from_config(&config)?;
let mut builder = Mads::builder_with_config(config);
builder.database(DatabaseBootstrap::new(database))?;
let application = builder.build().await?;
# Ok::<(), Box<dyn std::error::Error>>(())
```

Use the direct `mads::diesel` and
`mads::diesel_migrations` re-exports when native Diesel APIs are the right
tool.

`serve(application, "127.0.0.1:3000")` remains the explicit generated-router
escape hatch. Its address overrides automatic server binding; use
`serve_router` when the raw generated router has been merged with native Axum
routes.

## Passport configuration and JWT profiles

`Mads::run` supplies the standard conventional source order; the low-level
builder stays explicit. Dotenv sources provide interpolation values, and
ordinary sources merge from first to last; a later scalar or string array
replaces an earlier value at the same key completely. Process variables override
dotenv values during `${NAME}` interpolation. `EnvSource` is scalar-only, so
arrays such as `algorithms` and `audiences` belong in TOML or a programmatic
`ConfigDocument`/`MapSource`.

```toml
# mads.toml
[passport]
secret = "${JWT_SECRET}"
algorithms = ["HS256"]
issuer = "https://auth.example.com"
audiences = ["mads-api"]
```

Simple `secret` mode permits one HMAC algorithm: HS256 by default, or one of
HS384/HS512 when explicitly selected. Minimum secret sizes are 32/48/64 bytes.
For rotation, configure a named key ring; the active key signs and all retained
keys verify by `kid`:

```toml
[passport]
active_key = "2026-08"
algorithms = ["RS256"]

[passport.keys."2026-08"]
algorithm = "RS256"
private_key_file = "keys/current-private.pem"
public_key_file = "keys/current-public.pem"

[passport.keys."2026-07"]
algorithm = "RS256"
public_key_file = "keys/previous-public.pem"
```

MADS supports HS256/384/512, RS256/384/512, and ES256/384. The configured
allowlist—not an untrusted token header—selects eligible algorithms, and every
named key is bound to one algorithm. Relative paths from TOML resolve beside
that TOML file; paths from environment or programmatic sources resolve from the
process working directory.

```rust,ignore
use std::time::Duration;
use mads::prelude::*;

let access = jwt.sign(
    UserClaims { user_id: 7 },
    JwtSignOptions::access(Duration::from_secs(900)).subject("7"),
)?;
let refresh = jwt.sign(
    UserClaims { user_id: 7 },
    JwtSignOptions::refresh(Duration::from_secs(604_800)).subject("7"),
)?;
let verified_access = jwt.verify::<UserClaims>(&access, JwtValidation::access())?;
let verified_refresh = jwt.verify::<UserClaims>(&refresh, JwtValidation::refresh())?;
```

Access and refresh tokens have different protected `typ` values and
`token_use` claims. They are not interchangeable. Unverified decode APIs are
inspection-only and must never authenticate a request.

## Managed strategies, principals, and guards

A custom strategy is both a managed provider and an annotated
`PassportStrategy` implementation. Framework signature, registered-claim, and
token-kind verification always happens before `validate`; the strategy sees
verified claims and a credential-sanitized, read-only `PassportContext`.

```rust,ignore
#[derive(PassportPrincipal)]
struct UserPrincipal {
    user_id: u64,
    #[roles]
    roles: Vec<String>,
    #[permissions]
    permissions: std::collections::BTreeSet<String>,
}

#[service]
struct AppJwtStrategy { users: UserService }

#[passport_strategy(name = "jwt")]
impl PassportStrategy for AppJwtStrategy {
    type Claims = UserClaims;
    type Principal = UserPrincipal;
    const TOKEN_KIND: JwtTokenKind = JwtTokenKind::Access;

    async fn validate(
        &self,
        context: &PassportContext<'_>,
        claims: &JwtClaims<Self::Claims>,
    ) -> PassportResult<Self::Principal> {
        self.users.authenticate_current(context, claims.custom.user_id).await
    }
}
```

`jwt` is the built-in access strategy and can authorize directly as
`ClaimsPrincipal<C>`. A custom `jwt` strategy overrides it. `jwt-refresh` is not
built in: applications define it with `JwtTokenKind::Refresh` and own any
persistence, rotation, reuse detection, and revocation.

```rust,ignore
fn owns_profile(principal: &UserPrincipal) -> bool { principal.user_id == 7 }

#[routes(prefix = "/users")]
#[guard(
    strategy = "jwt",
    principal = UserPrincipal,
    source = bearer,
    roles(any = ["user", "admin"]),
)]
trait UserRoutes {
    #[get("/profile")]
    #[guard(
        permissions(all = ["profile:read"]),
        predicate = owns_profile,
    )]
    async fn profile(
        &self,
        principal: Authenticated<UserPrincipal>,
        token: VerifiedToken<UserClaims>,
    ) -> HttpResult<Json<Profile>>;

    #[post("/login")]
    #[guard(skip)]
    async fn login(&self) -> HttpResult<Json<LoginResponse>>;
}
```

Trait policies inherit. A method replaces only fields it supplies;
`#[guard(skip)]` is the sole opt-out. Roles, permissions, and predicates are
ANDed; `any`/`all` controls matching inside one role or permission clause, and
every predicate must be a synchronous `fn(&UserPrincipal) -> bool`. A guard
uses exactly one source. With `cookies`, select
`source = cookie("refresh_token")`; there is no Bearer fallback.

Authentication and strategy rejection map to generic `401 Unauthorized` with
`WWW-Authenticate: Bearer`, authorization policy failures to `403 Forbidden`,
and operational failures to `500 Internal Server Error`. Ordinary malformed
cookie extraction remains `400 Bad Request`; a missing, malformed, or duplicate
guard cookie is a generic `401`.

Cookie jars compose with response tuples and emit checked `Set-Cookie` headers:

```rust,ignore
let cookie = Cookie::build(("refresh_token", refresh))
    .path("/")
    .http_only(true)
    .secure(true)
    .same_site(SameSite::Strict)
    .max_age(cookie::time::Duration::days(7))
    .build();
Ok((jar.add(cookie), Json(response)))
```

For native Axum routes, apply a typed `PassportGuard<P>` Tower layer. This is a
runtime escape hatch, not static MADS guard metadata, so it cannot activate JWT
auto-configuration. Before `PassportGuard::build()`, a managed provider must
directly require `JwtService`, or the builder must explicitly provide a
concrete `JwtService`; otherwise construction fails with `MADS131`.

See the complete [Passport/JWT example](docs/examples/passport_jwt.md) and the
[v0.5.5 security and release notes](docs/importance/version_0.5.5/passport-jwt-and-cookies.md).

## CLI migrations

From a project root containing `mads.toml` and `migrations/`:

```text
mads db migrate   # apply pending file migrations
mads db rollback  # revert the latest migration from this source
mads db status    # report applied and pending versions
mads db generate  # create one automatically named, review-required diff
```

`mads db generate` never applies its output and has no positional name. It
loads split Diesel schema files recursively and warns when a change needs
manual SQL review. `mads db migrate` prints `applied <version>` for work
performed or `database is up to date`; `rollback` prints `reverted <version>`;
`status` prints individual versions plus an applied/pending summary. Invalid
command syntax exits with 2; configuration, pool, or migration failures exit
with 1.

## A typed HTTP route

`#[mads::routes]` records immutable metadata and emits a typed registration
adapter. `#[mads::controller]` resolves the managed controller once while the
router is built; handlers do not receive manual `State<AppState>` or perform
per-request provider resolution.

```rust,no_run
use mads::prelude::*;

#[derive(Clone, serde::Serialize)]
struct User {
    id: u64,
}

#[mads::routes(prefix = "/readme-users")]
trait UserRoutes {
    #[mads::get("/:id")]
    async fn get_user(&self, id: Path<u64>) -> HttpResult<Json<User>>;
}

#[mads::controller(routes = [UserRoutes])]
struct UserController;

impl UserRoutes for UserController {
    async fn get_user(&self, Path(id): Path<u64>) -> HttpResult<Json<User>> {
        Ok(Json(User { id }))
    }
}

#[module]
struct AppModule;

#[mads::main]
async fn main() -> Result<(), HttpRuntimeError> {
    Mads::run::<AppModule>().await
}
```

## Extractors, responses, and routing

The prelude exports `Path<T>`, `Query<T>`, `Json<T>`, `Header<T>`, `Request`,
`HttpResult<T>`, `Created<T>`, `NoContent`, `build_router`, `configure_router`,
`serve`, and `serve_router`.
`mads::common::axum` remains the native Axum escape hatch for extractors,
responses, routers, middleware, and Tower composition.

MADS route metadata uses `/:parameter`; the validated adapter translates it to
Axum 0.8 syntax only while registering the route. Invalid metadata and
conflicts fail with `MADS030` before router construction. GET also handles
HEAD, OPTIONS is not synthesized, static routes win over parameter routes, and
trailing slashes remain strict. `build_router(&application)` returns the raw
generated router; merge native routes before `configure_router` or
`serve_router` applies final application-wide CORS. Use the configured router
with Tower's `ServiceExt::oneshot` for in-process route tests without binding a
listener.

## Benchmarks

The current benchmark suite covers native Axum/MADS throughput and
process-start-to-ready comparisons with Axum, Go/Gin, and NestJS/Fastify.

| Application | Startup P50 | Startup P95 |
| --- | ---: | ---: |
| Native Axum | 21 ms | 30 ms |
| Go/Gin | 22 ms | 29 ms |
| MADS | 22 ms | 30 ms |
| NestJS/Fastify | 428 ms | 443 ms |

The startup comparison uses 1,000 release-build starts per application and an
equivalent PostgreSQL readiness check. In the exploratory throughput suite,
every native Axum/MADS saturation range overlaps, while both sustain the fixed
1,000 requests/second target with closely grouped latency.

See [BENCHMARK.md](BENCHMARK.md) for the complete results, methodology,
limitations, resource measurements, and interpretation guidance.

## Current scope

Version 0.7.0 provides root-module scope, Rust-namespace ownership, direct
public cross-module access, scoped providers/controllers/routes/guards/
strategies/auto-configuration, conventional configuration, automatic one-listener
HTTP startup, strict application-wide CORS, raw native-router composition, the
Cargo-native run/dev CLI, compiled route/graph/doctor inspection, and bounded
PostgreSQL schema-diff generation. It preserves the low-level builder and
complete-catalog rootless compatibility.

It does **not** implement trait or interface bindings, `Inject<dyn Trait>`,
request-validation derives or schemas, login or credential validation, refresh
endpoints or persistence/rotation/revocation, password hashing, CSRF, remote
JWKS, JWE, generic typed configuration, third-party auto-configuration, or
multiple-listener/TLS/HTTP2 server configuration. Database errors are not
automatically mapped to HTTP responses; applications choose their delivery
policy. Input validation, expanded standard HTTP errors, generic typed
configuration, compiler-diagnostic rewriting, and machine-readable CLI output
are v0.8 work.

## Development

Run the available release checks locally:

```sh
cargo fmt --all --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-features
cargo test --workspace --all-features --doc
RUSTDOCFLAGS="-D warnings" cargo doc --workspace --all-features --no-deps
cargo +1.85.0 test --locked --workspace --all-features
```

CI also provisions PostgreSQL 16 and runs the ignored database suites plus the
85% line-coverage gate. To run those locally, set `MADS_TEST_DATABASE_URL` to a
PostgreSQL 16 database and use the commands in the [v0.5 requirements](docs/importance/version_0.5/auto-configuration.md).

## License

MADS.rs is licensed under either the [Apache License 2.0](LICENSE-APACHE) or
the [MIT License](LICENSE-MIT), at your option.