umbral-admin 0.0.10

Auto-generated CRUD admin UI for umbral models.
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Phase 1 shell integration tests.
//!
//! Tests the six deliverables from the phase 1 spec:
//!
//! 1. GET /admin/login returns 200 + HTML containing `<form` + a CSRF token field.
//! 2. GET /admin/ without a session redirects to /admin/login?next=/admin/ (302).
//! 3. POST /admin/login with valid creds sets a session cookie and redirects to `next`.
//! 4. POST /admin/login with bad creds returns the login template with a generic error
//!    (no username/password distinction).
//! 5. POST /admin/login with a malicious `next=//evil.com/` rejects the redirect (returns to /admin/).
//! 6. GET /admin/<table>/ (existing changelist) renders extending the new base — assert the
//!    response HTML contains the sidebar markup (id="umbral-admin-sidebar").
//! 7. The sidebar nav lists every registered model grouped by plugin.

#![allow(dead_code, private_interfaces)]

use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use http_body_util::BodyExt;
use serde::{Deserialize, Serialize};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use tokio::sync::OnceCell;
use tower::ServiceExt;

use umbral_admin::{AdminModel, AdminPlugin};
use umbral_auth::{AuthPlugin, AuthUser, create_user};
use umbral_sessions::SessionsPlugin;

/// A simple model so the sidebar has something to show.
#[derive(Debug, sqlx::FromRow, Serialize, Deserialize, umbral::orm::Model)]
struct Post {
    id: i64,
    title: String,
    body: String,
}

static BOOT: OnceCell<axum::Router> = OnceCell::const_new();

async fn boot() -> &'static axum::Router {
    BOOT.get_or_init(|| async {
        let settings =
            umbral::Settings::from_env().expect("figment defaults always load in test env");

        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("admin_phase1.sqlite");
        std::mem::forget(tmp);
        let pool = SqlitePoolOptions::new()
            .max_connections(5)
            .connect_with(
                SqliteConnectOptions::new()
                    .busy_timeout(std::time::Duration::from_secs(5))
                    .filename(&path)
                    .create_if_missing(true),
            )
            .await
            .expect("sqlite pool");

        let admin = AdminPlugin::default().register_for(
            "blog",
            AdminModel::new("post").label("Posts").icon("file-text"),
        );

        let app = umbral::App::builder()
            .settings(settings)
            .database("default", pool)
            .plugin(AuthPlugin::<AuthUser>::default())
            .plugin(SessionsPlugin::default().without_auto_layer())
            .plugin(admin)
            .model::<Post>()
            .build()
            .expect("App::build");

        umbral::migrate::create_tables_for_tests()
            .await
            .expect("create the test schema");

        let pool = umbral::db::pool();

        // Seed: one staff user, one non-staff.
        let staff = create_user("staff_user", "staff@test.com", "staffpass")
            .await
            .expect("create staff");
        sqlx::query("UPDATE auth_user SET is_staff = 1 WHERE id = ?")
            .bind(staff.id)
            .execute(&pool)
            .await
            .expect("mark staff");
        let _: AuthUser = create_user("reg_user", "reg@test.com", "regpass")
            .await
            .expect("create regular user");

        // Seed one post so the list has content.
        sqlx::query("INSERT INTO post (title, body) VALUES ('Hello world', 'First post body')")
            .execute(&pool)
            .await
            .expect("seed post");

        app.into_router()
    })
    .await
}

// =========================================================================
// Helpers.
// =========================================================================

async fn send_full(
    router: axum::Router,
    req: Request<Body>,
) -> (StatusCode, axum::http::HeaderMap, String) {
    let resp = router.oneshot(req).await.expect("oneshot");
    let status = resp.status();
    let headers = resp.headers().clone();
    let bytes = resp
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let body = String::from_utf8_lossy(&bytes).into_owned();
    (status, headers, body)
}

async fn send(router: axum::Router, req: Request<Body>) -> (StatusCode, String) {
    let (s, _, b) = send_full(router, req).await;
    (s, b)
}

fn extract_csrf_token(html: &str) -> Option<String> {
    // Find the input with name="csrf_token", then locate its value attribute
    // within a small window after it. Tolerant of whitespace / line breaks
    // between attributes so reformats of login.html don't break the test.
    let name_marker = r#"name="csrf_token""#;
    let pos = html.find(name_marker)?;
    let window_end = pos.saturating_add(400).min(html.len());
    let window = &html[pos..window_end];
    let value_marker = "value=\"";
    let vstart = window.find(value_marker)? + value_marker.len();
    let vend = window[vstart..].find('"')?;
    Some(window[vstart..vstart + vend].to_string())
}

async fn login_session(router: &axum::Router, username: &str, password: &str) -> String {
    let (_, hdrs, body) = send_full(
        router.clone(),
        Request::builder()
            .uri("/admin/login")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    let anon_cookie = hdrs
        .get_all(header::SET_COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .find_map(|s| {
            let first = s.split(';').next()?;
            let (k, v) = first.split_once('=')?;
            if k.trim() == "umbral_csrf_token" {
                Some(v.to_string())
            } else {
                None
            }
        })
        .expect("GET /admin/login must set umbral_csrf_token cookie");
    let csrf = extract_csrf_token(&body).expect("login page must have csrf_token");

    let form = serde_urlencoded::to_string([
        ("username", username),
        ("password", password),
        ("csrf_token", &csrf),
        ("next", "/admin/"),
    ])
    .unwrap();
    let (_, hdrs2, _) = send_full(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri("/admin/login")
            .header(header::COOKIE, format!("umbral_csrf_token={anon_cookie}"))
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(Body::from(form))
            .unwrap(),
    )
    .await;
    hdrs2
        .get(header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| {
            s.split(';')
                .next()
                .and_then(|p| p.split_once('=').map(|(_, v)| v.to_string()))
        })
        .expect("POST /admin/login must set authenticated session cookie")
}

/// A staff user of this test's own, logged in.
///
/// The admin persists per-user UI state (gaps2 #11): a list visit with no query params
/// 303-redirects to the query string that USER last used, and `/admin/` redirects to the
/// path they last visited. Tests asserting a DEFAULT view therefore cannot share a user
/// with a test that filters — whichever runs first decides what the other sees.
///
/// It never used to matter: this suite never created `admin_user_pref`, so the lookups
/// errored and the restore silently never fired. Deriving the schema from the models
/// created the table and switched a shipped feature on here for the first time.
async fn own_staff_cookie(router: &axum::Router, name: &str) -> String {
    let user = create_user(name, &format!("{name}@test.com"), "staffpass")
        .await
        .expect("create staff user");
    sqlx::query("UPDATE auth_user SET is_staff = 1 WHERE id = ?")
        .bind(user.id)
        .execute(&umbral::db::pool())
        .await
        .expect("mark staff");
    login_session(router, name, "staffpass").await
}

// =========================================================================
// Test 1: GET /admin/login returns 200 + <form + CSRF token field.
// =========================================================================

#[tokio::test]
async fn login_page_returns_200_with_form_and_csrf() {
    let router = boot().await.clone();
    let (status, _, body) = send_full(
        router,
        Request::builder()
            .uri("/admin/login")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "GET /admin/login should be 200");
    assert!(
        body.contains("<form"),
        "login page must contain a form element; body:\n{body}"
    );
    assert!(
        body.contains(r#"name="csrf_token""#),
        "login page must have a csrf_token field; body:\n{body}"
    );
    // The CSRF token value must be non-empty.
    let token = extract_csrf_token(&body);
    assert!(
        token.as_deref().is_some_and(|t| !t.is_empty()),
        "csrf_token value must be non-empty; body:\n{body}"
    );
}

// =========================================================================
// Test 2: GET /admin/ without a session redirects to /admin/login?next=...
// =========================================================================

#[tokio::test]
async fn unauthenticated_admin_redirects_to_login_with_next() {
    let router = boot().await.clone();
    let (status, headers, _) = send_full(
        router,
        Request::builder()
            .uri("/admin/")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::SEE_OTHER, "should be 302");
    let location = headers.get(header::LOCATION).unwrap().to_str().unwrap();
    assert!(
        location.contains("/admin/login"),
        "should redirect to /admin/login; got {location}"
    );
    assert!(
        location.contains("next="),
        "redirect should include next= param; got {location}"
    );
    assert!(
        location.contains("%2Fadmin%2F") || location.contains("/admin/"),
        "next should encode the admin path; got {location}"
    );
}

// =========================================================================
// Test 3: POST /admin/login with valid creds sets session cookie + redirects to next.
// =========================================================================

#[tokio::test]
async fn login_with_valid_creds_sets_session_and_redirects() {
    let router = boot().await.clone();

    // Step 1: GET /admin/login to obtain session cookie + CSRF token.
    let (status, hdrs, body) = send_full(
        router.clone(),
        Request::builder()
            .uri("/admin/login")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK);
    let anon_cookie = hdrs
        .get(header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| {
            s.split(';')
                .next()
                .and_then(|p| p.split_once('=').map(|(_, v)| v.to_string()))
        })
        .expect("session cookie from GET /admin/login");
    let csrf = extract_csrf_token(&body).expect("csrf_token from login page");

    // Step 2: POST with valid staff credentials.
    let form = serde_urlencoded::to_string([
        ("username", "staff_user"),
        ("password", "staffpass"),
        ("csrf_token", &csrf),
        ("next", "/admin/"),
    ])
    .unwrap();
    let (status2, hdrs2, _) = send_full(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri("/admin/login")
            .header(header::COOKIE, format!("umbral_csrf_token={anon_cookie}"))
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(Body::from(form))
            .unwrap(),
    )
    .await;

    assert_eq!(status2, StatusCode::SEE_OTHER, "valid login should 302");
    // Response must set a new session cookie.
    let new_cookie = hdrs2.get(header::SET_COOKIE).and_then(|v| v.to_str().ok());
    assert!(
        new_cookie.is_some_and(|s| s.contains("umbral_session")),
        "login should set umbral_session cookie; got {:?}",
        new_cookie
    );
    // Redirect target should be the requested `next`.
    let location = hdrs2.get(header::LOCATION).unwrap().to_str().unwrap();
    assert_eq!(
        location, "/admin/",
        "should redirect to /admin/; got {location}"
    );
}

// =========================================================================
// Test 4: POST /admin/login with bad creds returns generic error (no disclosure).
// =========================================================================

#[tokio::test]
async fn login_with_bad_creds_returns_generic_error() {
    let router = boot().await.clone();

    let (_, hdrs, body) = send_full(
        router.clone(),
        Request::builder()
            .uri("/admin/login")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    let anon_cookie = hdrs
        .get(header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| {
            s.split(';')
                .next()
                .and_then(|p| p.split_once('=').map(|(_, v)| v.to_string()))
        })
        .unwrap();
    let csrf = extract_csrf_token(&body).unwrap();

    let form = serde_urlencoded::to_string([
        ("username", "staff_user"),
        ("password", "wrongpassword"),
        ("csrf_token", &csrf),
        ("next", "/admin/"),
    ])
    .unwrap();
    let (status, _, body2) = send_full(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri("/admin/login")
            .header(header::COOKIE, format!("umbral_csrf_token={anon_cookie}"))
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(Body::from(form))
            .unwrap(),
    )
    .await;

    // Must NOT be a redirect.
    assert_ne!(status, StatusCode::SEE_OTHER, "bad creds must not redirect");
    // Must render the form again (HTML response).
    assert!(
        body2.contains("<form"),
        "must re-render the login form; body:\n{body2}"
    );
    // Error message must be generic — must not say "password" or "username" specifically.
    // The spec: "NEVER reveal whether username or password was wrong specifically".
    let error_msg = "incorrect"; // matches the message in lib.rs
    assert!(
        body2.contains(error_msg),
        "error message should say 'incorrect'; body:\n{body2}"
    );
    // Sanity: must not say "wrong password" specifically.
    assert!(
        !body2.contains("wrong password"),
        "must not reveal which field was wrong; body:\n{body2}"
    );
}

// =========================================================================
// Test 5: POST /admin/login with malicious next= rejects the redirect.
// =========================================================================

#[tokio::test]
async fn login_malicious_next_is_rejected() {
    let router = boot().await.clone();

    let (_, hdrs, body) = send_full(
        router.clone(),
        Request::builder()
            .uri("/admin/login")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    let anon_cookie = hdrs
        .get(header::SET_COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|s| {
            s.split(';')
                .next()
                .and_then(|p| p.split_once('=').map(|(_, v)| v.to_string()))
        })
        .unwrap();
    let csrf = extract_csrf_token(&body).unwrap();

    // Attempt open redirect via protocol-relative URL.
    let form = serde_urlencoded::to_string([
        ("username", "staff_user"),
        ("password", "staffpass"),
        ("csrf_token", &csrf),
        ("next", "//evil.com/steal"),
    ])
    .unwrap();
    let (status, hdrs2, _) = send_full(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri("/admin/login")
            .header(header::COOKIE, format!("umbral_csrf_token={anon_cookie}"))
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(Body::from(form))
            .unwrap(),
    )
    .await;

    assert_eq!(
        status,
        StatusCode::SEE_OTHER,
        "valid login should still redirect"
    );
    let location = hdrs2.get(header::LOCATION).unwrap().to_str().unwrap();
    // Must NOT redirect to evil.com.
    assert!(
        !location.contains("evil.com"),
        "must not redirect to external URL; got {location}"
    );
    // Should redirect to the safe fallback (/admin/).
    assert!(
        location.starts_with("/admin"),
        "should redirect within /admin; got {location}"
    );
}

// =========================================================================
// Test 6: GET /admin/<table>/ renders extending base.html (sidebar present).
// =========================================================================

#[tokio::test]
async fn changelist_renders_with_sidebar() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "u_changelist_renders_with_sidebar").await;

    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/post/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::OK,
        "changelist should be 200; body:\n{body}"
    );
    // The base.html shell must be present.
    assert!(
        body.contains(r#"id="umbral-admin-sidebar""#),
        "base.html sidebar must be rendered; body:\n{body}"
    );
}

// =========================================================================
// Test 7: Sidebar nav lists registered models grouped by plugin.
// =========================================================================

#[tokio::test]
async fn sidebar_nav_lists_models_by_plugin() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "shell_nav").await;

    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    // The sidebar should contain the "blog" plugin group (from register_for("blog", ...)).
    assert!(
        body.contains("sidebar-group-blog"),
        "sidebar must show the 'blog' plugin group; body:\n{body}"
    );
    // And the post model link must be present.
    assert!(
        body.contains("/admin/post/"),
        "sidebar must link to /admin/post/; body:\n{body}"
    );
}

// =========================================================================
// Test 8 (gap 44): Model::DISPLAY propagates into sidebar label (explicit
// registration with .label() overrides it).
// =========================================================================

#[tokio::test]
async fn explicit_label_overrides_model_display() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "u_explicit_label_overrides_model_display").await;

    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    // The "blog" plugin's post model was registered with .label("Posts"),
    // which should appear in the sidebar and override any model-level DISPLAY.
    assert!(
        body.contains("Posts"),
        "sidebar must show the explicit label 'Posts'; body:\n{body}"
    );
}

// =========================================================================
// Test 9 (gap 44): Sidebar icon from explicit AdminModel::icon().
// =========================================================================

#[tokio::test]
async fn explicit_icon_appears_in_sidebar() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "u_explicit_icon_appears_in_sidebar").await;

    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    // The "blog" plugin's post model was registered with .icon("file-text").
    assert!(
        body.contains("data-lucide=\"file-text\""),
        "sidebar must contain the file-text icon; body:\n{body}"
    );
}

// =========================================================================
// Test 10 (gap 44): Auto-discovery — model registered via .model::<Post>()
// without an explicit AdminModel shows up in the sidebar.
// The boot() setup registers Post both via register_for("blog", ...) AND
// via .model::<Post>(). The explicit registration wins, but models with
// ONLY a .model::<T>() registration must still appear.
// =========================================================================

#[tokio::test]
async fn auto_discovered_model_appears_in_sidebar() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "u_auto_discovered_model_appears_in_sideb").await;

    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    // The post model must appear regardless (explicit registration wins over
    // auto-discovery for the same table name, but the model must be present).
    assert!(
        body.contains("/admin/post/"),
        "auto-discovered model must appear in sidebar; body:\n{body}"
    );
}

// =========================================================================
// Test 11 (gap 45): Theme toggle button has onclick="umbral.toggleTheme()"
// so clicking it actually works (gap 1 of the four tasks).
// =========================================================================

#[tokio::test]
async fn theme_toggle_button_has_onclick() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "u_theme_toggle_button_has_onclick").await;

    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    // The theme toggle button must exist.
    assert!(
        body.contains(r#"id="theme-toggle""#),
        "page must contain the theme-toggle button; body:\n{body}"
    );
    // The button must have onclick wiring.
    assert!(
        body.contains(r#"onclick="umbral.toggleTheme()""#),
        "theme-toggle must have onclick=\"umbral.toggleTheme()\"; body:\n{body}"
    );
}