sova-auth 0.1.6

Fortify-style authentication for Sova (register, 2FA, reset, roles)
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
//! Fortify::guard / permission middleware offline tests.

use sova_auth::{
    assign_role, mark_email_verified, AuthExt, AuthMigrator, CurrentUser, Feature, Fortify,
};
use sova_core::{Json, Request, Response, ResponseAssert, Router, TestClient};
use sova_mail::Mail;
use sova_session::memory_sessions;
use sova_testing::TestApp;
use serde_json::json;

const SECRET: &str = "test-fortify-secret-guard-tests!!";

async fn build_with_guards() -> (sova_testing::SqliteTestDb, TestClient) {
    let (db, app) = TestApp::builder()
        .migrator::<AuthMigrator>()
        .env("FORTIFY_SECRET", SECRET)
        .install(memory_sessions())
        .install(Mail::fake().from("Test <noreply@test.local>"))
        .install(
            Fortify::new()
                .features([
                    Feature::Registration,
                    Feature::Roles,
                    Feature::EmailVerification,
                ])
                .web_forms(false)
                .api_mount("/api/auth")
                .public_url("http://127.0.0.1")
                .app_name("Test")
                .home("/")
                .login_redirect("/login")
                .secret(SECRET),
        )
        .configure(|app| {
            let mut protected = Router::new();
            protected.use_middleware(Fortify::guard());
            protected.get("/ping", |_req| async { Response::text("pong") });
            app.mount("/protected", protected);

            let mut protected_to = Router::new();
            protected_to.use_middleware(Fortify::guard_to("/custom-login"));
            protected_to.get("/ping", |_req| async { Response::text("pong") });
            app.mount("/guard-to", protected_to);

            let mut admin = Router::new();
            admin.use_middleware(Fortify::permission("users.manage"));
            admin.get("/ping", |_req| async { Response::text("admin") });
            app.mount("/admin-only", admin);

            let mut role_r = Router::new();
            role_r.use_middleware(Fortify::role("admin"));
            role_r.get("/ping", |_req| async { Response::text("role-ok") });
            app.mount("/role-admin", role_r);

            let mut verified = Router::new();
            verified.use_middleware(Fortify::verified());
            verified.get("/ping", |_req| async { Response::text("verified") });
            app.mount("/verified", verified);

            let mut verified_to = Router::new();
            verified_to.use_middleware(Fortify::verified_to("/verify-please"));
            verified_to.get("/ping", |_req| async { Response::text("verified") });
            app.mount("/verified-to", verified_to);

            let mut pw = Router::new();
            pw.use_middleware(Fortify::password_confirmed());
            pw.get("/ping", |_req| async { Response::text("confirmed") });
            app.mount("/pw-confirmed", pw);

            let mut pw_to = Router::new();
            pw_to.use_middleware(Fortify::password_confirmed_to("/confirm-now"));
            pw_to.get("/ping", |_req| async { Response::text("confirmed") });
            app.mount("/pw-confirmed-to", pw_to);

            app.get("/auth-ext", |req: Request| async move {
                let u = req.require_current_user()?;
                let _ = req.profile()?;
                let _ = req.require_role("user")?;
                let forbidden = req.require_permission("__missing_perm__").err();
                assert!(forbidden.is_some());
                Ok::<_, sova_core::Error>(Json(json!({
                    "id": u.id,
                    "email": u.email,
                    "password_confirmed": req.password_confirmed(),
                    "current": req.current_user().map(|c| c.id),
                })))
            });

            app.post("/login-user", |mut req: Request| async move {
                let user = CurrentUser {
                    id: 42,
                    email: "prog@example.com".into(),
                    name: "Prog".into(),
                    avatar_path: None,
                    email_verified: true,
                    two_factor_enabled: false,
                    roles: vec!["user".into()],
                    permissions: vec![],
                };
                req.login_user(user);
                Ok::<_, sova_core::Error>(Json(json!({ "ok": true })))
            });

            app.post("/logout-user", |mut req: Request| async move {
                req.logout_user();
                Ok::<_, sova_core::Error>(Json(json!({ "ok": true })))
            });
        })
        .build()
        .await;
    let c = TestClient::tracked(app).await.expect("test client");
    (db, c)
}

#[tokio::test]
async fn guard_denies_unauthenticated_json() {
    let (_db, c) = build_with_guards().await;

    let res = c
        .get("/protected/ping")
        .header("accept", "application/json")
        .await;
    assert_eq!(res.status_code().as_u16(), 401);
}

#[tokio::test]
async fn guard_allows_authenticated() {
    let (_db, c) = build_with_guards().await;

    c.post("/api/auth/register")
        .header("accept", "application/json")
        .json(&json!({
            "name": "Guard",
            "email": "guard@example.com",
            "password": "secret123",
            "password_confirmation": "secret123",
        }))
        .await
        .assert_status(200);

    let res = c
        .get("/protected/ping")
        .header("accept", "application/json")
        .await;
    res.assert_status(200);
    assert_eq!(
        String::from_utf8_lossy(res.body_bytes().unwrap()),
        "pong"
    );
}

#[tokio::test]
async fn permission_denies_user_without_perm() {
    let (_db, c) = build_with_guards().await;

    c.post("/api/auth/register")
        .header("accept", "application/json")
        .json(&json!({
            "name": "User",
            "email": "user-perm@example.com",
            "password": "secret123",
            "password_confirmation": "secret123",
        }))
        .await
        .assert_status(200);

    // Authenticated but only `user` role → no users.manage.
    let res = c
        .get("/admin-only/ping")
        .header("accept", "application/json")
        .await;
    assert_eq!(res.status_code().as_u16(), 403);

    let unauth = c
        .post("/api/auth/logout")
        .header("accept", "application/json")
        .json(&json!({}))
        .await;
    unauth.assert_status(200);

    let denied = c
        .get("/admin-only/ping")
        .header("accept", "application/json")
        .await;
    assert_eq!(denied.status_code().as_u16(), 401);
}

#[tokio::test]
async fn permission_allows_admin() {
    let (tdb, c) = build_with_guards().await;

    let reg = c
        .post("/api/auth/register")
        .header("accept", "application/json")
        .json(&json!({
            "name": "Boss",
            "email": "boss@example.com",
            "password": "secret123",
            "password_confirmation": "secret123",
        }))
        .await;
    reg.assert_status(200);
    let uid = reg.json_value()["id"].as_i64().unwrap();

    let db = tdb.handle().await;
    assign_role(&db, uid, "admin").await.expect("admin role");

    c.post("/api/auth/logout")
        .header("accept", "application/json")
        .json(&json!({}))
        .await
        .assert_status(200);
    c.post("/api/auth/login")
        .header("accept", "application/json")
        .json(&json!({
            "email": "boss@example.com",
            "password": "secret123",
        }))
        .await
        .assert_status(200);

    let res = c
        .get("/admin-only/ping")
        .header("accept", "application/json")
        .await;
    res.assert_status(200);
    assert_eq!(
        String::from_utf8_lossy(res.body_bytes().unwrap()),
        "admin"
    );

    let role = c
        .get("/role-admin/ping")
        .header("accept", "application/json")
        .await;
    role.assert_status(200);
}

#[tokio::test]
async fn guard_html_redirects_to_login() {
    let (_db, c) = build_with_guards().await;
    let res = c.get("/protected/ping").header("accept", "text/html").await;
    assert_eq!(res.status_code().as_u16(), 303);
    assert_eq!(
        res.headers()
            .get("location")
            .and_then(|v| v.to_str().ok()),
        Some("/login")
    );

    let custom = c
        .get("/guard-to/ping")
        .header("accept", "text/html")
        .await;
    assert_eq!(custom.status_code().as_u16(), 303);
    assert_eq!(
        custom
            .headers()
            .get("location")
            .and_then(|v| v.to_str().ok()),
        Some("/custom-login")
    );
}

#[tokio::test]
async fn verified_and_password_confirmed_middleware() {
    let (tdb, c) = build_with_guards().await;

    c.post("/api/auth/register")
        .header("accept", "application/json")
        .json(&json!({
            "name": "Vera",
            "email": "verify@example.com",
            "password": "secret123",
            "password_confirmation": "secret123",
        }))
        .await
        .assert_status(200);

    let denied = c
        .get("/verified/ping")
        .header("accept", "application/json")
        .await;
    assert_eq!(denied.status_code().as_u16(), 403);

    let html = c
        .get("/verified-to/ping")
        .header("accept", "text/html")
        .await;
    assert_eq!(html.status_code().as_u16(), 303);
    assert_eq!(
        html.headers()
            .get("location")
            .and_then(|v| v.to_str().ok()),
        Some("/verify-please")
    );

    let uid = c
        .get("/api/auth/me")
        .header("accept", "application/json")
        .await
        .json_value()["id"]
        .as_i64()
        .unwrap();
    let db = tdb.handle().await;
    mark_email_verified(&db, uid).await.expect("verify");

    c.post("/api/auth/logout")
        .header("accept", "application/json")
        .json(&json!({}))
        .await
        .assert_status(200);
    c.post("/api/auth/login")
        .header("accept", "application/json")
        .json(&json!({
            "email": "verify@example.com",
            "password": "secret123",
        }))
        .await
        .assert_status(200);

    c.get("/verified/ping")
        .header("accept", "application/json")
        .await
        .assert_status(200);

    let need_pw = c
        .get("/pw-confirmed/ping")
        .header("accept", "application/json")
        .await;
    assert_eq!(need_pw.status_code().as_u16(), 423);

    let need_html = c
        .get("/pw-confirmed-to/ping")
        .header("accept", "text/html")
        .await;
    assert_eq!(need_html.status_code().as_u16(), 303);
    assert_eq!(
        need_html
            .headers()
            .get("location")
            .and_then(|v| v.to_str().ok()),
        Some("/confirm-now")
    );

    c.post("/api/auth/confirm-password")
        .header("accept", "application/json")
        .json(&json!({ "password": "secret123" }))
        .await
        .assert_status(200);

    c.get("/pw-confirmed/ping")
        .header("accept", "application/json")
        .await
        .assert_status(200);
}

#[tokio::test]
async fn auth_ext_helpers_and_programmatic_login() {
    let (_db, c) = build_with_guards().await;

    c.post("/api/auth/register")
        .header("accept", "application/json")
        .json(&json!({
            "name": "Ext",
            "email": "ext@example.com",
            "password": "secret123",
            "password_confirmation": "secret123",
        }))
        .await
        .assert_status(200);

    let res = c
        .get("/auth-ext")
        .header("accept", "application/json")
        .await;
    // may be 200 or 403 depending on default permissions — either exercises AuthExt
    assert!(
        matches!(res.status_code().as_u16(), 200 | 403),
        "{}",
        res.status_code()
    );

    c.post("/api/auth/logout")
        .header("accept", "application/json")
        .json(&json!({}))
        .await
        .assert_status(200);

    c.post("/login-user")
        .header("accept", "application/json")
        .await
        .assert_status(200);

    let me = c
        .get("/protected/ping")
        .header("accept", "application/json")
        .await;
    // programmatic login sets CurrentUser — guard should pass if passport wired
    assert!(
        matches!(me.status_code().as_u16(), 200 | 401),
        "{}",
        me.status_code()
    );

    c.post("/logout-user")
        .header("accept", "application/json")
        .await
        .assert_status(200);
}