umbral-admin 0.0.12

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
//! Tests for the AdminModel extensibility surface (gap 18 + phase 1).
//!
//! Covers:
//! 1. `list_display` — filters which columns the list view renders.
//! 2. `list_filter` — filter facets appear in the response HTML.
//! 3. `search_fields` — `?q=` produces a correct WHERE LIKE clause.
//! 4. `ordering` — list rows come back in the configured ORDER BY.
//! 5. Custom action — runs the handler and returns the flash message.
//! 6. `readonly_fields` — form renders `<input ... readonly>` for those fields.
//!
//! Auth is session-based (HTML form flow). Uses a shared `login_session`
//! helper to obtain a session cookie before each test.
//!
//! Uses the same OnceCell-boot pattern as `tests/integration.rs`.

#![allow(dead_code, private_interfaces)]

use std::path::PathBuf;

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

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

/// A simple model for these tests.
#[derive(Debug, sqlx::FromRow, Serialize, Deserialize, umbral::orm::Model)]
struct Article {
    id: i64,
    title: String,
    body: String,
    published: bool,
    created_at: Option<DateTime<Utc>>,
}

// =========================================================================
// Shared boot. Each test clones the router (same Arc'd state underneath).
// =========================================================================

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 a test env");

        let tmp = tempfile::tempdir().expect("tempdir for the test DB");
        let path = tmp.path().join("admin_extensibility.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 tempfile pool");

        // AdminModel (was AdminConfig) for the `article` table.
        let article_config = AdminModel::new("article")
            .list_display(&["title", "published"])
            .list_filter(&["published"])
            .search_fields(&["title", "body"])
            .ordering(&["-id"])
            .readonly_fields(&["created_at"])
            .actions(vec![
                Action::delete_selected(),
                Action::new(
                    "mark_published",
                    "Mark published",
                    "check-circle",
                    |inv| async move {
                        Ok(umbral_admin::ActionResult::Toast {
                            message: format!("Marked {} article(s) as published.", inv.ids.len()),
                            level: umbral_admin::ToastLevel::Success,
                        })
                    },
                ),
            ]);

        let admin = AdminPlugin::default().register(article_config);

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

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

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

        // Seed a staff user.
        let staff = create_user("admin_ext", "admin_ext@example.com", "password123")
            .await
            .expect("create staff user");
        sqlx::query("UPDATE auth_user SET is_staff = 1 WHERE id = ?")
            .bind(staff.id)
            .execute(&pool)
            .await
            .expect("mark staff");

        sqlx::query(
            "INSERT INTO article (title, body, published) VALUES \
             ('Alpha article', 'alpha body text', 0), \
             ('Beta article',  'beta body text',  1)",
        )
        .execute(&pool)
        .await
        .expect("seed articles");

        app.into_router()
    })
    .await
}

/// A staff user of this test's own, logged in.
///
/// gaps2 #11: a list visit with NO query params 303-redirects to the query string that
/// USER last used, so filters follow them across tabs and devices. Tests that assert the
/// DEFAULT (unfiltered) view therefore cannot share a user with a test that filters —
/// whichever runs first decides what the other sees. Saved preferences are per-user, so
/// the isolation belongs there rather than in a `DELETE FROM` that races the other tests.
///
/// This never used to matter: the suite never created `admin_user_pref` at all, so
/// `get_table_pref` errored, the restore silently never fired, and a bare GET always
/// returned 200. Deriving the schema from the models created the table, which switched a
/// shipped feature on in these tests for the first time.
async fn own_staff_cookie(router: &axum::Router, name: &str) -> String {
    let user = create_user(name, &format!("{name}@example.com"), "password123")
        .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, "password123").await
}

// =========================================================================
// Session auth helpers (same as integration.rs).
// =========================================================================

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

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 body_bytes = resp
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let body = String::from_utf8_lossy(&body_bytes).into_owned();
    (status, headers, body)
}

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 (_, headers, body) = send_full(
        router.clone(),
        Request::builder()
            .uri("/admin/login")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    // GET /admin/login mints (or echoes) the umbral_csrf_token cookie.
    // Find it in the Set-Cookie header(s).
    let csrf_cookie = headers
        .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_token = extract_csrf_token(&body).expect("login page must have csrf_token");

    let form_body = serde_urlencoded::to_string([
        ("username", username),
        ("password", password),
        ("csrf_token", &csrf_token),
        ("next", "/admin/"),
    ])
    .unwrap();
    let (status, headers2, _) = send_full(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri("/admin/login")
            .header(header::COOKIE, format!("umbral_csrf_token={csrf_cookie}"))
            .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
            .body(Body::from(form_body))
            .unwrap(),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::SEE_OTHER,
        "login_session should succeed"
    );
    headers2
        .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")
}

// =========================================================================
// 1. list_display: only listed columns appear in the list HTML.
// =========================================================================

#[tokio::test]
async fn list_display_filters_columns() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "ext_cols").await;
    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/article/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    assert!(body.contains("title"), "title column missing:\n{body}");
    assert!(
        body.contains("published"),
        "published column missing:\n{body}"
    );
    assert!(
        !body.contains("<th>body</th>"),
        "body column should be hidden:\n{body}"
    );
    assert!(
        !body.contains("<th>created_at</th>"),
        "created_at column should be hidden:\n{body}"
    );
    assert!(
        body.contains("Alpha article"),
        "Alpha article missing:\n{body}"
    );
}

// =========================================================================
// 2. list_filter: filter button appears in the toolbar.
// The filter dialog itself is a separate HTMX fragment loaded on demand,
// not embedded in the initial changelist HTML.
// =========================================================================

#[tokio::test]
async fn list_filter_shows_facets_in_sidebar() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "ext_facets").await;
    let (status, body) = send(
        router.clone(),
        Request::builder()
            .uri("/admin/article/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    // The Filter button (with sliders-horizontal icon) should be visible
    // because `list_filter` is configured.
    assert!(
        body.contains("filter-dialog")
            || body.contains("sliders-horizontal")
            || body.contains("Filter"),
        "filter button missing when list_filter is configured:\n{body}"
    );
    // The filter dialog endpoint should return 200 for authenticated requests.
    let (dialog_status, dialog_body) = send(
        router,
        Request::builder()
            .uri("/admin/article/filter-dialog")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .header("HX-Request", "true")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(
        dialog_status,
        StatusCode::OK,
        "filter-dialog endpoint failed:\n{dialog_body}"
    );
}

// =========================================================================
// 3. search_fields: ?q= narrows the list to matching rows.
// =========================================================================

#[tokio::test]
async fn search_fields_filters_rows() {
    let router = boot().await.clone();
    let cookie = login_session(&router, "admin_ext", "password123").await;
    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/article/?q=alpha")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    assert!(
        body.contains("Alpha article"),
        "Alpha article should match 'alpha':\n{body}"
    );
    assert!(
        !body.contains("Beta article"),
        "Beta article should not match 'alpha':\n{body}"
    );
}

#[tokio::test]
async fn search_fields_no_match_shows_empty() {
    let router = boot().await.clone();
    let cookie = login_session(&router, "admin_ext", "password123").await;
    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/article/?q=zzznomatch")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    assert!(
        !body.contains("Alpha article"),
        "Alpha article should not appear:\n{body}"
    );
    assert!(
        !body.contains("Beta article"),
        "Beta article should not appear:\n{body}"
    );
}

// =========================================================================
// 4. ordering: list rows appear in configured ORDER BY order.
// =========================================================================

#[tokio::test]
async fn ordering_applies_to_list() {
    let router = boot().await.clone();
    let cookie = own_staff_cookie(&router, "ext_order").await;
    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/article/")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "body:\n{body}");
    let alpha_pos = body.find("Alpha article").unwrap_or(usize::MAX);
    let beta_pos = body.find("Beta article").unwrap_or(usize::MAX);
    assert!(
        beta_pos < alpha_pos,
        "Beta (id=2) should appear before Alpha (id=1) with ORDER BY id DESC; \
         alpha_pos={alpha_pos}, beta_pos={beta_pos}"
    );
}

// =========================================================================
// 5. Custom action: runs the handler and redirects with flash message.
// =========================================================================

#[tokio::test]
async fn custom_action_runs_and_returns_flash() {
    let router = boot().await.clone();
    let cookie = login_session(&router, "admin_ext", "password123").await;

    let form_body = serde_urlencoded::to_string([
        ("action", "mark_published"),
        ("selected", "1"),
        ("selected", "2"),
    ])
    .unwrap();

    let resp = router
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/article/action")
                .header(header::COOKIE, format!("umbral_session={cookie}"))
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(Body::from(form_body))
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(
        resp.status(),
        StatusCode::SEE_OTHER,
        "action should redirect"
    );
    let location = resp
        .headers()
        .get(header::LOCATION)
        .unwrap()
        .to_str()
        .unwrap();
    assert!(
        location.contains("flash="),
        "redirect should include flash: {location}"
    );
    assert!(
        location.contains("article"),
        "redirect should point back to article list: {location}"
    );
}

// =========================================================================
// 6. readonly_fields: form renders <input ... readonly> for those fields.
// =========================================================================

#[tokio::test]
async fn readonly_fields_render_readonly_input() {
    let router = boot().await.clone();
    let cookie = login_session(&router, "admin_ext", "password123").await;
    let (status, body) = send(
        router,
        Request::builder()
            .uri("/admin/article/1/edit")
            .header(header::COOKIE, format!("umbral_session={cookie}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "edit form body:\n{body}");
    assert!(
        body.contains("readonly"),
        "readonly attribute missing from form:\n{body}"
    );
}

// =========================================================================
// Quiet unused import.
// =========================================================================
#[allow(dead_code)]
fn _unused_pathbuf_marker() -> Option<PathBuf> {
    None
}