autumn-cli 0.7.0

CLI tool for the Autumn web framework
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
//! Integration tests for the SaaS starter.
//!
//! ```text
//! cargo test                                   # smoke tests (instant, no Docker)
//! cargo test -- --include-ignored --test-threads=1   # full flow (needs Docker)
//! ```
//!
//! The ignored tests start a Postgres testcontainer and drive the real signup →
//! login → tenant-scoped dashboard flow, then prove one tenant cannot see
//! another's data.

use autumn_web::config::AutumnConfig;
use autumn_web::prelude::*;
use autumn_web::reexports::axum::middleware::from_fn;
use autumn_web::test::{TestApp, TestClient, TestDb};

use {{crate_name}}::routes;

fn app_routes() -> Vec<autumn_web::Route> {
    routes![
        {{crate_name}}::index,
        routes::auth::signup_form,
        routes::auth::signup,
        routes::auth::login_form,
        routes::auth::login,
        routes::auth::logout,
        routes::dashboard::dashboard,
        routes::dashboard::create_project,
    ]
}

/// Mirror the middleware-driven tenancy from `autumn.toml`: tenant resolved from
/// the session, public pages allowlisted, missing tenant redirected to login.
fn enable_tenancy(config: &mut AutumnConfig) {
    config.tenancy.enabled = true;
    config.tenancy.source = "session".to_string();
    config.tenancy.session_key = "tenant_id".to_string();
    config.tenancy.public_paths = vec![
        "/".to_string(),
        "/login".to_string(),
        "/signup".to_string(),
        "/logout".to_string(),
        "/static".to_string(),
    ];
    config.tenancy.login_redirect = Some("/login".to_string());
}

// ── Smoke tests (no Docker) ──────────────────────────────────────────────────

/// The login page renders without a database — proving the app wires up.
#[tokio::test]
async fn login_page_renders() {
    let client = TestApp::new().routes(app_routes()).build();
    client
        .get("/login")
        .send()
        .await
        .assert_ok()
        .assert_body_contains("Log in");
}

/// Regression guard for the multi-tenancy fix: with tenancy middleware enabled,
/// an allowlisted public page like `/login` must still be reachable by an
/// unauthenticated visitor (no session, no tenant) instead of being 401'd.
#[tokio::test]
async fn login_page_is_public_with_tenancy_enabled() {
    let mut config = AutumnConfig::default();
    enable_tenancy(&mut config);
    let client = TestApp::new().routes(app_routes()).config(config).build();
    client
        .get("/login")
        .send()
        .await
        .assert_ok()
        .assert_body_contains("Log in");
}

/// A protected route hit without a tenant redirects to the configured login page
/// rather than returning a raw 401. The middleware short-circuits before the
/// handler, so no database is required.
#[tokio::test]
async fn protected_route_redirects_to_login_when_unauthenticated() {
    let mut config = AutumnConfig::default();
    enable_tenancy(&mut config);
    let client = TestApp::new().routes(app_routes()).config(config).build();
    // A navigating browser advertises `Accept: text/html`, so it is bounced to the
    // login page rather than shown a raw 401.
    let resp = client
        .get("/dashboard")
        .header("accept", "text/html")
        .send()
        .await;
    resp.assert_status(303);
    assert_eq!(
        resp.header("location"),
        Some("/login"),
        "missing-tenant protected route should redirect a browser to the login page"
    );
}

/// An API client (`Accept: application/json`) hitting a protected route without a
/// tenant gets a raw 401, not an HTML login redirect, so its error handling works.
#[tokio::test]
async fn protected_route_returns_401_for_api_clients() {
    let mut config = AutumnConfig::default();
    enable_tenancy(&mut config);
    let client = TestApp::new().routes(app_routes()).config(config).build();
    let resp = client
        .get("/dashboard")
        .header("accept", "application/json")
        .send()
        .await;
    resp.assert_status(401);
}

// ── Full flow (requires Docker) ──────────────────────────────────────────────

/// Create the schema and return a CSRF-disabled, DB-backed client.
async fn db_client() -> TestClient {
    let db = TestDb::shared().await;
    db.execute_sql(
        "CREATE TABLE IF NOT EXISTS users (
            id            BIGSERIAL PRIMARY KEY,
            email         TEXT      NOT NULL UNIQUE,
            password_hash TEXT      NOT NULL,
            tenant_id     TEXT      NOT NULL,
            created_at    TIMESTAMP NOT NULL DEFAULT NOW()
        )",
    )
    .await;
    db.execute_sql(
        "CREATE TABLE IF NOT EXISTS projects (
            id         BIGSERIAL PRIMARY KEY,
            tenant_id  TEXT      NOT NULL,
            name       TEXT      NOT NULL,
            created_at TIMESTAMP NOT NULL DEFAULT NOW()
        )",
    )
    .await;
    // Persistent "remember-me" chains (issue #1397).
    db.execute_sql(
        "CREATE TABLE IF NOT EXISTS remember_tokens (
            series       TEXT        PRIMARY KEY,
            user_id      BIGINT      NOT NULL REFERENCES users (id) ON DELETE CASCADE,
            tenant_id    TEXT        NOT NULL,
            token_hash   TEXT        NOT NULL,
            previous_token_hash TEXT NULL,
            rotated_at   TIMESTAMPTZ NULL,
            expires_at   TIMESTAMPTZ NOT NULL,
            ip           TEXT        NOT NULL DEFAULT '',
            user_agent   TEXT        NOT NULL DEFAULT '',
            ua_family    TEXT        NOT NULL DEFAULT '',
            ua_os        TEXT        NOT NULL DEFAULT '',
            ua_device    TEXT        NOT NULL DEFAULT '',
            label        TEXT,
            created_at   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
            last_used_at TIMESTAMPTZ
        )",
    )
    .await;
    db.execute_sql("TRUNCATE users, projects, remember_tokens RESTART IDENTITY")
        .await;

    // The forms post normally; disable CSRF so the test does not have to scrape
    // a token out of the rendered HTML.
    let mut config = AutumnConfig::default();
    config.security.csrf.enabled = false;
    // Drive tenancy through the middleware exactly as `autumn.toml` does.
    enable_tenancy(&mut config);

    // Hand the remember middleware the shared pool and resolved config, exactly
    // as `main`'s startup hook does, and register the middleware layer so a
    // remember cookie rotates into a session before the tenancy gate.
    {{crate_name}}::remember::init_remember_pool(db.pool(), autumn_web::auth::RememberConfig::default());

    TestApp::new()
        .routes(app_routes())
        .config(config)
        .with_db(db.pool())
        .layer(from_fn({{crate_name}}::remember::remember_me_middleware))
        .build()
}

/// Pull the session cookie pair (`name=value`) out of a `Set-Cookie` response.
fn session_cookie(resp: &autumn_web::test::TestResponse) -> String {
    let set_cookie = resp
        .header("set-cookie")
        .expect("auth response should set a session cookie");
    set_cookie
        .split(';')
        .next()
        .expect("cookie has a name=value pair")
        .to_owned()
}

/// Return the `name=value` value half of a named cookie from any of the
/// response's `Set-Cookie` headers (a login with remember-me sets two).
fn named_cookie(resp: &autumn_web::test::TestResponse, name: &str) -> Option<String> {
    for (key, value) in &resp.headers {
        if key.eq_ignore_ascii_case("set-cookie") {
            let pair = value.split(';').next().unwrap_or("");
            if let Some((cookie_name, cookie_value)) = pair.split_once('=')
                && cookie_name.trim() == name
            {
                return Some(cookie_value.trim().to_owned());
            }
        }
    }
    None
}

/// Sign up a user and return their session cookie.
async fn signup(client: &TestClient, email: &str) -> String {
    let resp = client
        .post("/signup")
        .form(&format!(
            "email={email}&password=Tr0ubad0ur-Xy7-correct-horse"
        ))
        .send()
        .await;
    resp.assert_status(303);
    session_cookie(&resp)
}

#[tokio::test]
#[ignore = "requires Docker (testcontainers)"]
async fn signup_login_dashboard_returns_200() {
    let client = db_client().await;
    let cookie = signup(&client, "founder@acme.test").await;

    // The tenant-scoped dashboard renders for the signed-in session.
    client
        .get("/dashboard")
        .header("cookie", &cookie)
        .send()
        .await
        .assert_ok()
        .assert_body_contains("Projects");

    // Logging back in lands on the same tenant dashboard.
    let login = client
        .post("/login")
        .form("email=founder@acme.test&password=Tr0ubad0ur-Xy7-correct-horse")
        .send()
        .await;
    login.assert_status(303);
    let cookie = session_cookie(&login);
    client
        .get("/dashboard")
        .header("cookie", &cookie)
        .send()
        .await
        .assert_ok();
}

/// A weak password (present in the bundled common-password corpus) is rejected
/// at signup: the form re-renders with the policy error at HTTP 200 — not a
/// redirect and not a 5xx — and no account is created, so a follow-up login
/// attempt with those credentials is unauthorized.
#[tokio::test]
#[ignore = "requires Docker (testcontainers)"]
async fn signup_rejects_weak_password() {
    let client = db_client().await;

    let resp = client
        .post("/signup")
        .form("email=weak@acme.test&password=password")
        .send()
        .await;
    // Re-rendered form with the field error, not an accepted account (303) or a
    // server error.
    resp.assert_ok();
    assert!(
        resp.text().contains("too common"),
        "expected the weak-password policy error in the re-rendered form, got: {}",
        resp.text()
    );

    // No account was created, so logging in with those credentials fails.
    let login = client
        .post("/login")
        .form("email=weak@acme.test&password=password")
        .send()
        .await;
    login.assert_status(401);
}

#[tokio::test]
#[ignore = "requires Docker (testcontainers)"]
async fn tenants_are_isolated() {
    let client = db_client().await;

    let acme = signup(&client, "a@acme.test").await;
    let globex = signup(&client, "b@globex.test").await;

    // Acme creates a project.
    client
        .post("/dashboard/projects")
        .header("cookie", &acme)
        .form("name=Alpha")
        .send()
        .await
        .assert_status(303);

    // Acme sees its project …
    client
        .get("/dashboard")
        .header("cookie", &acme)
        .send()
        .await
        .assert_ok()
        .assert_body_contains("Alpha");

    // … but Globex (a different tenant) does not.
    let globex_view = client
        .get("/dashboard")
        .header("cookie", &globex)
        .send()
        .await;
    globex_view.assert_ok();
    assert!(
        !globex_view.text().contains("Alpha"),
        "tenant isolation breached: Globex can see Acme's project"
    );
}

/// AC8 (issue #1397): the whole persistent remember-me lifecycle, under the
/// grace-window rotation model —
///   1. `POST /login` with `remember=on` sets BOTH a session cookie and a
///      remember cookie (T0);
///   2. after a browser restart (session cookie dropped, remember cookie kept),
///      a protected route authenticates via the remember chain and ROTATES the
///      remember cookie to a fresh value (T1);
///   3. a SECOND restart rotates again (T2), pushing the ORIGINAL T0 out of the
///      one-slot previous-token window — so replaying T0 can no longer be
///      confused with a benign concurrent request;
///   4. replaying the ORIGINAL T0 (matching neither current T2 nor previous T1)
///      is detected as theft — the request is unauthorized and the whole chain
///      is revoked, so even the latest rotated cookie (T2) no longer
///      authenticates.
///
/// This demonstrates theft in a grace-INDEPENDENT way: an immediate replay of
/// the just-rotated-out token is `Accept` (see the grace test below), so theft
/// is proven by replaying a token that is two rotations stale.
#[tokio::test]
#[ignore = "requires Docker (testcontainers)"]
async fn remember_me_rotates_across_restart_and_detects_theft() {
    let client = db_client().await;

    // Seed a confirmed account. `signup` logs the browser in; drop that session
    // so the next login is a clean "remember me" opt-in.
    signup(&client, "remember@acme.test").await;
    client.log_out();

    // 1. Log in WITH the remember box ticked.
    let login = client
        .post("/login")
        .form("email=remember@acme.test&password=Tr0ubad0ur-Xy7-correct-horse&remember=on")
        .send()
        .await;
    login.assert_status(303);
    let original_remember = named_cookie(&login, "autumn.remember")
        .expect("login with remember=on must set a remember cookie");
    assert!(
        named_cookie(&login, "autumn.sid").is_some(),
        "login must also set a session cookie"
    );

    // Sanity: the freshly-authenticated jar reaches the dashboard.
    client
        .get("/dashboard")
        .send()
        .await
        .assert_ok()
        .assert_body_contains("Projects");

    // 2. Browser restart: the session cookie (no Max-Age) is cleared but the
    //    persistent remember cookie survives. A protected route must now
    //    authenticate via the remember chain and rotate the cookie T0 → T1.
    client.log_out(); // clears only the session cookie
    let restart = client.get("/dashboard").send().await;
    restart.assert_ok();
    let rotated_once = named_cookie(&restart, "autumn.remember")
        .expect("a rotated request must set a fresh remember cookie");
    assert_ne!(
        rotated_once, original_remember,
        "the remember cookie must rotate on use"
    );

    // 3. Second restart: rotate again T1 → T2. Now the stored previous token is
    //    T1, and the ORIGINAL T0 is beyond the one-slot grace window.
    client.log_out();
    let restart2 = client.get("/dashboard").send().await;
    restart2.assert_ok();
    let rotated_twice = named_cookie(&restart2, "autumn.remember")
        .expect("a second rotated request must set another fresh remember cookie");
    assert_ne!(
        rotated_twice, rotated_once,
        "the remember cookie must rotate again on the second use"
    );

    // 4. Theft: replay the ORIGINAL (two-rotations-stale) remember cookie with
    //    no session cookie (an explicit `cookie` header bypasses the jar). It
    //    matches neither the current nor the previous token → theft:
    //    unauthorized, chain nuked.
    client.log_out();
    let theft = client
        .get("/dashboard")
        .header("accept", "application/json")
        .header("cookie", &format!("autumn.remember={original_remember}"))
        .send()
        .await;
    theft.assert_status(401);

    // The chain was revoked, so even the *latest* rotated cookie (T2) no longer
    // authenticates.
    let after_theft = client
        .get("/dashboard")
        .header("accept", "application/json")
        .header("cookie", &format!("autumn.remember={rotated_twice}"))
        .send()
        .await;
    after_theft.assert_status(401);
}

/// AC8 grace path (issue #1397): immediately replaying the just-rotated-out
/// token — before any second rotation — is a benign concurrent request within
/// the grace window (`Accept`), so it still authenticates and does NOT trip
/// theft detection. This documents the intended concurrency behaviour that the
/// theft test above deliberately steps around.
#[tokio::test]
#[ignore = "requires Docker (testcontainers)"]
async fn remember_me_accepts_previous_token_within_grace() {
    let client = db_client().await;

    signup(&client, "grace@acme.test").await;
    client.log_out();

    // Log in with remember, capture T0.
    let login = client
        .post("/login")
        .form("email=grace@acme.test&password=Tr0ubad0ur-Xy7-correct-horse&remember=on")
        .send()
        .await;
    login.assert_status(303);
    let original_remember = named_cookie(&login, "autumn.remember")
        .expect("login with remember=on must set a remember cookie");

    // Browser restart: one rotation T0 → T1.
    client.log_out();
    let restart = client.get("/dashboard").send().await;
    restart.assert_ok();
    let rotated_once = named_cookie(&restart, "autumn.remember")
        .expect("a rotated request must set a fresh remember cookie");
    assert_ne!(rotated_once, original_remember);

    // Immediately replay the just-rotated-out T0 with no session. It is the
    // stored previous token, still inside the grace window → Accept: the
    // dashboard renders (authenticated) rather than 401.
    client.log_out();
    let within_grace = client
        .get("/dashboard")
        .header("cookie", &format!("autumn.remember={original_remember}"))
        .send()
        .await;
    within_grace.assert_ok().assert_body_contains("Projects");

    // The chain is intact, so the latest rotated cookie T1 still authenticates.
    client.log_out();
    client
        .get("/dashboard")
        .header("cookie", &format!("autumn.remember={rotated_once}"))
        .send()
        .await
        .assert_ok();
}