umbral-admin 0.0.2

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
//! Phase 4 dashboard widget system tests.
//!
//! 1. GET /admin/api/dashboard/catalog lists registered widgets (built-ins + custom).
//! 2. GET /admin/api/dashboard/widgets/{key}/data returns typed JSON payload.
//! 3. Unknown widget key returns 404.
//! 4. GET /admin/ renders with widget placeholder divs.
//! 5. PUT + GET /admin/api/dashboard/layout round-trips.

#![allow(dead_code)]

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

use umbral_admin::{
    AdminPlugin, HeatmapPayload, KpiPayload, ProgressPayload, RadialPayload, Span, Widget,
    WidgetDataFn, WidgetKind, WidgetPayload,
};
use umbral_auth::{AuthPlugin, AuthUser, create_user_with_flags};
use umbral_sessions::SessionsPlugin;

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

async fn boot() -> &'static axum::Router {
    BOOT.get_or_init(|| async {
        let settings = umbral::Settings::from_env().expect("settings");
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("phase4_dashboard.sqlite");
        std::mem::forget(tmp);
        let pool_obj = SqlitePoolOptions::new()
            .max_connections(5)
            .connect_with(
                SqliteConnectOptions::new()
                    .filename(&path)
                    .create_if_missing(true),
            )
            .await
            .expect("pool");

        let custom_widget = Widget {
            key: "test_kpi",
            title: "Test KPI".to_string(),
            kind: WidgetKind::Kpi,
            default_span: Span { cols: 3, rows: 1 },
            permission: None,
            default_period: None,
            data: WidgetDataFn::new(|_user| async move {
                WidgetPayload::Kpi(KpiPayload {
                    value: "99".to_string(),
                    unit: Some("items".to_string()),
                    delta: Some(5.2),
                    sparkline: None,
                })
            }),
        };

        // The newer widget kinds — each must render its HTML fragment
        // through the macro registered in engine.rs (regression guard
        // for "macro template never registered" -> import error ->
        // blank widget cell).
        let radial_widget = Widget {
            key: "test_radial",
            title: "Test Radial".to_string(),
            kind: WidgetKind::Radial,
            default_span: Span { cols: 3, rows: 2 },
            permission: None,
            default_period: None,
            data: WidgetDataFn::new(|_user| async move {
                WidgetPayload::Radial(RadialPayload::single("Done", 73.0))
            }),
        };
        let heatmap_widget = Widget {
            key: "test_heatmap",
            title: "Test Heatmap".to_string(),
            kind: WidgetKind::Heatmap,
            default_span: Span { cols: 6, rows: 3 },
            permission: None,
            default_period: None,
            data: WidgetDataFn::new(|_user| async move {
                WidgetPayload::Heatmap(HeatmapPayload::from_grid(
                    ["R1"],
                    ["a", "b"],
                    vec![vec![1.0, 2.0]],
                ))
            }),
        };
        let progress_widget = Widget {
            key: "test_progress",
            title: "Test Progress".to_string(),
            kind: WidgetKind::Progress,
            default_span: Span { cols: 3, rows: 3 },
            permission: None,
            default_period: None,
            data: WidgetDataFn::new(|_user| async move {
                WidgetPayload::Progress(ProgressPayload::from_pairs([("A", 10.0), ("B", 5.0)]))
            }),
        };

        let app = umbral::App::builder()
            .settings(settings)
            .database("default", pool_obj)
            .plugin(AuthPlugin::<AuthUser>::default())
            .plugin(SessionsPlugin::default().without_auto_layer())
            // Builtins are now opt-in (used to auto-prepend). The
            // test exercises the catalog endpoint with all three
            // shapes registered: both builtins + a custom widget.
            .plugin(
                AdminPlugin::default()
                    .register_widget(umbral_admin::builtin_total_models_widget())
                    .register_widget(umbral_admin::builtin_recent_users_widget())
                    .register_widget(custom_widget)
                    .register_widget(radial_widget)
                    .register_widget(heatmap_widget)
                    .register_widget(progress_widget),
            )
            .build()
            .expect("App::build");

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

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS auth_user (\
                id INTEGER PRIMARY KEY AUTOINCREMENT,\
                username TEXT NOT NULL UNIQUE,\
                email TEXT NOT NULL,\
                password_hash TEXT NOT NULL,\
                is_active INTEGER NOT NULL DEFAULT 1,\
                is_staff INTEGER NOT NULL DEFAULT 0,\
                is_superuser INTEGER NOT NULL DEFAULT 0,\
                date_joined TEXT NOT NULL,\
                last_login TEXT\
            )",
        )
        .execute(&pool)
        .await
        .ok();

        sqlx::query(
            "CREATE TABLE IF NOT EXISTS session (\
                id TEXT PRIMARY KEY,\
                user_id TEXT,\
                data TEXT NOT NULL DEFAULT '{}',\
                created_at TEXT NOT NULL,\
                expires_at TEXT NOT NULL\
            )",
        )
        .execute(&pool)
        .await
        .ok();

        umbral_admin::models::ensure_tables_for_tests(&pool)
            .await
            .expect("ensure_tables");

        app.into_router()
    })
    .await
}

async fn staff_cookie() -> String {
    let user = match create_user_with_flags("dash_user", "dash@example.com", "pass123", true, false)
        .await
    {
        Ok(u) => u,
        Err(_) => {
            let pool = umbral::db::pool();
            sqlx::query_as::<_, umbral_auth::AuthUser>(
                "SELECT id, username, email, password_hash, is_active, is_staff, is_superuser, date_joined, last_login \
                 FROM auth_user WHERE username = 'dash_user'",
            )
            .fetch_one(&pool)
            .await
            .expect("lookup dash_user")
        }
    };
    let tok = umbral_sessions::create_session(Some(user.id.to_string()), None)
        .await
        .expect("session");
    format!("umbral_session={tok}")
}

// =========================================================================
// Tests
// =========================================================================

#[tokio::test]
async fn catalog_lists_registered_widgets() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    let req = Request::builder()
        .uri("/admin/api/dashboard/catalog")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
    let arr = json.as_array().unwrap();

    // Built-ins (2) + custom = at least 3
    assert!(arr.len() >= 3, "expected ≥3 widgets, got {}", arr.len());

    let keys: Vec<&str> = arr.iter().filter_map(|v| v["key"].as_str()).collect();
    assert!(
        keys.contains(&"umbral_total_models"),
        "missing umbral_total_models"
    );
    assert!(
        keys.contains(&"umbral_recent_users"),
        "missing umbral_recent_users"
    );
    assert!(keys.contains(&"test_kpi"), "missing test_kpi");
}

#[tokio::test]
async fn widget_data_returns_typed_payload() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    let req = Request::builder()
        .uri("/admin/api/dashboard/widgets/test_kpi/data")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
    assert_eq!(json["key"].as_str().unwrap_or(""), "test_kpi");
    assert_eq!(json["kind"].as_str().unwrap_or(""), "kpi");
    assert_eq!(json["payload"]["value"].as_str().unwrap_or(""), "99");
    assert_eq!(json["payload"]["unit"].as_str().unwrap_or(""), "items");
}

/// Every widget kind must render its HTML fragment through the macro
/// registered in `engine.rs`. Regression guard: the radial/heatmap/
/// progress macro templates were initially added to `widget_data.html`
/// but NOT registered with the minijinja env, so the `{% from ... %}`
/// import failed at render time and the widget cell stayed blank.
#[tokio::test]
async fn new_widget_kinds_render_html_fragments() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    for (key, marker) in [
        ("test_radial", "data-umbral-chart=\"radial\""),
        ("test_heatmap", "data-umbral-chart=\"heatmap\""),
        ("test_progress", "progress-widget"),
    ] {
        let req = Request::builder()
            .uri(format!("/admin/api/dashboard/widgets/{key}/data"))
            .header(header::COOKIE, cookie.clone())
            // HTML path (the dashboard cell's hx-get), not the JSON API.
            .header("hx-request", "true")
            .body(Body::empty())
            .unwrap();
        let resp = router.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK, "{key} should render 200");
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        let html = String::from_utf8_lossy(&body);
        assert!(
            html.contains(marker),
            "{key} fragment must contain `{marker}` (macro not registered?); got: {html}"
        );
    }
}

#[tokio::test]
async fn unknown_widget_key_returns_404() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    let req = Request::builder()
        .uri("/admin/api/dashboard/widgets/no_such_widget/data")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn dashboard_page_renders_widget_placeholders() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    let req = Request::builder()
        .uri("/admin/")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8_lossy(&body);
    assert!(
        html.contains("hx-get=\"/admin/api/dashboard/widgets/"),
        "expected HTMX widget placeholders in dashboard HTML"
    );
}

/// gaps2 #4 — the admin runtime JS is served as a single external
/// asset (now on the unified `/static/admin/admin.js` URL) rather than
/// ~1080 lines of inline `<script>` blocks in wrapper.html. Four pins:
///
/// 1. The unified `/static/admin/admin.js` endpoint serves a valid
///    `application/javascript` response whose body is the EMBEDDED bytes
///    (proves the re-point onto `/static/admin/…` resolves through the
///    real Phase-5.4 specific route, beating the pipeline fallback —
///    zero-config single-binary serving preserved on the new URL).
/// 2. wrapper.html references the external file (via `static()`) + sets
///    the `umbralAdminBase` bootstrap.
/// 3. The pre-fix inline IIFE marker (`// Sheet stack state machine.`,
///    the comment at the top of old Block 5) no longer appears in
///    the served wrapper HTML — would catch a revert that re-inlines
///    the JS without updating the gap status.
#[tokio::test]
async fn admin_js_served_as_external_asset_not_inline() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    // 1. Unified static-pipeline asset endpoint. The specific Phase-5.4
    //    route serves the embedded bytes, winning over the nested pipeline
    //    fallback at `static_url`.
    let asset_req = Request::builder()
        .uri("/static/admin/admin.js")
        .body(Body::empty())
        .unwrap();
    let asset_resp = router.clone().oneshot(asset_req).await.unwrap();
    assert_eq!(asset_resp.status(), StatusCode::OK);
    let ct = asset_resp
        .headers()
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");
    assert!(
        ct.starts_with("application/javascript"),
        "admin.js Content-Type should be application/javascript, got `{ct}`"
    );
    let body = asset_resp.into_body().collect().await.unwrap().to_bytes();
    assert!(
        body.len() > 1000,
        "admin.js body should be non-trivial, got {} bytes",
        body.len()
    );
    // The served bytes ARE the embedded include_bytes! content — proves the
    // re-point serves the in-binary asset end to end, not a disk file.
    assert_eq!(
        body.as_ref(),
        include_bytes!("../src/assets/admin.js").as_slice(),
        "/static/admin/admin.js should serve the embedded admin.js bytes"
    );

    // 2. wrapper.html references the external file
    let page_req = Request::builder()
        .uri("/admin/?dashboard=1")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let page_resp = router.clone().oneshot(page_req).await.unwrap();
    let html = String::from_utf8_lossy(&page_resp.into_body().collect().await.unwrap().to_bytes())
        .into_owned();
    assert!(
        html.contains("var umbralAdminBase = '/admin'"),
        "umbralAdminBase bootstrap should be inline (read by admin.js)"
    );
    assert!(
        html.contains("/static/admin/admin.js"),
        "wrapper.html should reference the external admin.js on the unified static URL"
    );

    // 3. The old inline IIFE comments must be gone — if they reappear
    //    in wrapper.html, the gap got reverted without updating tests.
    assert!(
        !html.contains("// Sheet stack state machine."),
        "old inline block-5 IIFE comment should be gone from wrapper.html"
    );
    assert!(
        !html.contains("// Extend the early-declared window.umbral stub"),
        "old inline block-3 IIFE comment should be gone from wrapper.html"
    );
}

/// gaps2 #3 — change-password dialog lives as an HTML `<template>`
/// in wrapper.html rather than JS-string concatenation. The opener
/// (`umbral._openChangePasswordDialog`) clones the template and
/// patches `hx-post` to the target URL.
///
/// Regression pin: ensure both the template element AND the form
/// selector hook (`data-change-pw-form`) are present, and that the
/// old JS-built shape is fully gone.
#[tokio::test]
async fn change_password_dialog_uses_html_template_not_js_concat() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    let req = Request::builder()
        .uri("/admin/?dashboard=1")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let resp = router.clone().oneshot(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let html = String::from_utf8_lossy(&body);

    assert!(
        html.contains("<template id=\"umbral-change-password-dialog-template\">"),
        "expected change-password <template> block in wrapper.html"
    );
    assert!(
        html.contains("data-change-pw-form"),
        "expected `data-change-pw-form` selector hook on the form"
    );
    // Negative pin: the old JS-string-concat shape's literal
    // `'/' + id + '/change-password"' + ...` should be gone. If
    // someone reverts to the pre-fix builder, this test catches it.
    assert!(
        !html.contains("change-password\"' +"),
        "old JS-string-concat change-password builder should be removed"
    );
}

#[tokio::test]
async fn dashboard_layout_round_trips() {
    let _guard = LOCK.lock().await;
    let router = boot().await;
    let cookie = staff_cookie().await;

    let layout = r#"[{"key":"test_kpi","span":{"cols":6,"rows":2}}]"#;

    let put_req = Request::builder()
        .method("PUT")
        .uri("/admin/api/dashboard/layout")
        .header(header::COOKIE, cookie.clone())
        .header(header::CONTENT_TYPE, "application/json")
        .body(Body::from(layout))
        .unwrap();
    let put_resp = router.clone().oneshot(put_req).await.unwrap();
    assert_eq!(put_resp.status(), StatusCode::OK);

    let get_req = Request::builder()
        .uri("/admin/api/dashboard/layout")
        .header(header::COOKIE, cookie)
        .body(Body::empty())
        .unwrap();
    let get_resp = router.clone().oneshot(get_req).await.unwrap();
    assert_eq!(get_resp.status(), StatusCode::OK);

    let body = get_resp.into_body().collect().await.unwrap().to_bytes();
    let body_str = String::from_utf8_lossy(&body);
    assert!(body_str.contains("test_kpi"), "layout not saved/returned");
}

/// docs/decisions/2026-06-10-automatic-csrf.md: every htmx request the
/// admin makes must carry the ambient CSRF token. `hx-headers` on
/// `<body>` is inherited by all descendant hx-* requests, so one
/// attribute covers sheet create/edit, inline edit, delete, and actions.
#[test]
fn wrapper_body_carries_csrf_hx_headers() {
    let wrapper = include_str!("../templates/wrapper.html");
    let body_line = wrapper
        .lines()
        .find(|l| l.trim_start().starts_with("<body"))
        .expect("wrapper.html must have a <body> tag");
    assert!(
        body_line.contains("hx-headers"),
        "missing hx-headers: {body_line}"
    );
    assert!(
        body_line.contains("X-CSRF-Token"),
        "missing X-CSRF-Token: {body_line}"
    );
    assert!(
        body_line.contains("{{ csrf_token }}"),
        "must use the ambient token: {body_line}"
    );
}

/// Raw fetch() writes in admin.js (the PUT /api/prefs persistence calls)
/// bypass htmx's hx-headers inheritance, so each one must spread the
/// csrfHeaders() helper that reads the (deliberately non-HttpOnly) cookie.
#[test]
fn admin_js_fetches_send_csrf_header() {
    let js = include_str!("../src/assets/admin.js");
    assert!(
        js.contains("function csrfHeaders()"),
        "admin.js needs the csrfHeaders helper"
    );
    let writes = js.matches("method: 'PUT'").count() + js.matches("method: 'POST'").count();
    let wired = js.matches("csrfHeaders()").count();
    assert!(
        writes > 0 && wired >= writes,
        "every write fetch must spread csrfHeaders(): {wired} uses for {writes} writes"
    );
}

/// features.md #4: the admin lazy-mounts a markdown editor (EasyMDE)
/// and an RTE (Quill) onto the `data-widget` textareas the field
/// editor renders, on every form-render path (page load, htmx swap,
/// sheet open).
#[test]
fn admin_js_mounts_widget_editors() {
    let js = include_str!("../src/assets/admin.js");
    assert!(js.contains("initWidgetEditors"), "no widget-editor init");
    assert!(
        js.contains("new EasyMDE"),
        "markdown editor (EasyMDE) not mounted"
    );
    assert!(js.contains("new Quill"), "rte editor (Quill) not mounted");
    assert!(
        js.contains("CodeMirror.fromTextArea"),
        "code editor (CodeMirror) not mounted"
    );
    // Claims the textareas the field editor emits for each widget
    // (the selector is built dynamically from these names).
    assert!(
        js.contains("claim(root, 'markdown')"),
        "markdown widget not claimed"
    );
    assert!(js.contains("claim(root, 'rte')"), "rte widget not claimed");
    assert!(
        js.contains("claim(root, 'code')"),
        "code widget not claimed"
    );
    // Previews are sandboxed through DOMPurify (EasyMDE preview render +
    // Quill initial load), never rendering authored HTML raw.
    assert!(
        js.contains("DOMPurify"),
        "previews not sandboxed via DOMPurify"
    );
    assert!(
        js.contains("sanitizerFunction"),
        "EasyMDE preview not routed through the sanitizer"
    );
    assert!(
        js.contains(r#"data-widget="' + selector + '"#),
        "dynamic widget selector missing"
    );
    // Lazy-loaded, not eagerly bundled, and idempotent across re-scans.
    assert!(
        js.contains("loadScript"),
        "editors should be lazy-loaded from CDN"
    );
    assert!(js.contains("data-widget-mounted"), "no idempotency marker");
    // Mounted on the sheet's innerHTML path too (not just htmx swaps).
    assert!(
        js.matches("umbral.initWidgetEditors").count() >= 3,
        "must mount on DOMContentLoaded, htmx:afterSwap, AND the sheet path"
    );
}

/// The editor libraries ship light themes; the wrapper re-skins them
/// with the admin design tokens so they track the dark/light toggle.
#[test]
fn wrapper_themes_the_editors() {
    let wrapper = include_str!("../templates/wrapper.html");
    assert!(
        wrapper.contains("umbral-editor-theme"),
        "no editor theme block"
    );
    assert!(wrapper.contains(".EasyMDEContainer"), "EasyMDE not themed");
    assert!(wrapper.contains(".umbral-rte .ql-"), "Quill not themed");
    assert!(
        wrapper.contains("var(--surface-container-low)"),
        "editor theme must use admin design tokens, not hardcoded colors"
    );
}