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
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
#![allow(dead_code, private_interfaces)]
//! Wave 4 — file/image upload widgets + multipart form handling in the
//! admin.
//!
//! Boots an admin router for a model carrying an `ImageField`, wires an
//! in-memory `Storage` backend (via a `provides_storage()` plugin so the
//! boot system check passes), and exercises the consumer wiring end to
//! end:
//!
//!   1. POST a `multipart/form-data` create with a file part → the row
//!      lands with the column = the stored key, and the bytes are
//!      retrievable through the ambient Storage.
//!   2. GET the change form → the rendered HTML carries
//!      `enctype="multipart/form-data"`, a `type="file"` input, and (for
//!      the image field) an `<img>` preview whose `src` is the resolved
//!      URL.
//!   3. POST an update WITHOUT a new file (empty file part) → the
//!      existing key is preserved, never nulled.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

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::orm::ImageField;
use umbral::plugin::Plugin;
use umbral::storage::{Storage, StorageError, StoredFile, set_storage};
use umbral_admin::{AdminModel, AdminPlugin};
use umbral_auth::{AuthPlugin, AuthUser, create_user};
use umbral_sessions::SessionsPlugin;

// =========================================================================
// Model + in-memory storage backend
// =========================================================================

#[derive(Debug, sqlx::FromRow, Serialize, Deserialize, umbral::orm::Model)]
struct Product {
    id: i64,
    name: String,
    cover: ImageField,
}

/// In-memory `Storage`: `store` keys files by filename and keeps the
/// bytes so the test can read them back; `url` returns a stable public
/// URL the template can render.
#[derive(Debug, Default)]
struct MemStorage {
    files: Mutex<HashMap<String, Vec<u8>>>,
}

#[umbral::storage::async_trait]
impl Storage for MemStorage {
    async fn store(
        &self,
        filename: &str,
        _content_type: &str,
        bytes: &[u8],
    ) -> Result<StoredFile, StorageError> {
        let key = format!("uploads/{filename}");
        self.files
            .lock()
            .unwrap()
            .insert(key.clone(), bytes.to_vec());
        let url = format!("https://cdn.test/{key}");
        Ok(StoredFile {
            key,
            url,
            size: bytes.len() as u64,
        })
    }
    async fn retrieve(&self, key: &str) -> Result<Vec<u8>, StorageError> {
        self.files
            .lock()
            .unwrap()
            .get(key)
            .cloned()
            .ok_or(StorageError::NotFound)
    }
    async fn delete(&self, key: &str) -> Result<(), StorageError> {
        self.files.lock().unwrap().remove(key);
        Ok(())
    }
    fn url(&self, key: &str) -> String {
        format!("https://cdn.test/{key}")
    }
}

/// Shared handle so the test body can `retrieve` what the upload stored.
static BACKEND: OnceCell<Arc<MemStorage>> = OnceCell::const_new();

/// Reports `provides_storage()` so the boot system check passes for the
/// `cover: ImageField` column, and registers the in-memory backend in
/// `on_ready` (the production posture — backends register there).
struct MemMediaPlugin;

impl Plugin for MemMediaPlugin {
    fn name(&self) -> &'static str {
        "mem_media"
    }
    fn provides_storage(&self) -> bool {
        true
    }
    fn on_ready(
        &self,
        _ctx: &umbral::plugin::AppContext,
    ) -> Result<(), umbral::plugin::PluginError> {
        let backend = BACKEND
            .get()
            .cloned()
            .expect("BACKEND set before App::build");
        set_storage(backend);
        Ok(())
    }
}

// =========================================================================
// Boot
// =========================================================================

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

async fn boot() -> &'static axum::Router {
    BOOT.get_or_init(|| async {
        let backend = Arc::new(MemStorage::default());
        BACKEND.set(backend).expect("set backend once");

        let settings = umbral::Settings::from_env().expect("settings");
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("file_image_upload.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("pool");

        let product_config = AdminModel::new("product").list_display(&["name", "cover"]);

        let app = umbral::App::builder()
            .settings(settings)
            .database("default", pool)
            .plugin(AuthPlugin::<AuthUser>::default())
            .plugin(SessionsPlugin::default().without_auto_layer())
            .plugin(MemMediaPlugin)
            .plugin(AdminPlugin::default().register(product_config))
            .model::<Product>()
            .build()
            .expect("build");

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

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

        let staff = create_user("media_admin", "media@example.com", "pass123")
            .await
            .expect("user");
        sqlx::query("UPDATE auth_user SET is_staff = 1, is_superuser = 1 WHERE id = ?")
            .bind(staff.id)
            .execute(&pool)
            .await
            .expect("set staff");

        app.into_router()
    })
    .await
}

// =========================================================================
// Helpers
// =========================================================================

const BOUNDARY: &str = "X-UMBRAL-ADMIN-UPLOAD";

/// `(name, filename, content_type, value)`; `None` filename = text field.
type PartSpec<'a> = (&'a str, Option<&'a str>, Option<&'a str>, &'a [u8]);

fn multipart_body(parts: &[PartSpec<'_>]) -> Vec<u8> {
    let mut out = Vec::new();
    for (name, filename, content_type, value) in parts {
        out.extend_from_slice(format!("--{BOUNDARY}\r\n").as_bytes());
        match filename {
            Some(fname) => {
                out.extend_from_slice(
                    format!(
                        "Content-Disposition: form-data; name=\"{name}\"; filename=\"{fname}\"\r\n"
                    )
                    .as_bytes(),
                );
                if let Some(ct) = content_type {
                    out.extend_from_slice(format!("Content-Type: {ct}\r\n").as_bytes());
                }
            }
            None => {
                out.extend_from_slice(
                    format!("Content-Disposition: form-data; name=\"{name}\"\r\n").as_bytes(),
                );
            }
        }
        out.extend_from_slice(b"\r\n");
        out.extend_from_slice(value);
        out.extend_from_slice(b"\r\n");
    }
    out.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
    out
}

async fn send(
    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();
    (
        status,
        headers,
        String::from_utf8_lossy(&bytes).into_owned(),
    )
}

fn extract_csrf(html: &str) -> String {
    let marker = r#"name="csrf_token""#;
    let pos = html.find(marker).unwrap_or(0);
    let window = &html[pos..(pos + 200).min(html.len())];
    let val = r#"value=""#;
    let vpos = window.find(val).unwrap_or(0);
    let after = &window[vpos + val.len()..];
    after[..after.find('"').unwrap_or(0)].to_string()
}

/// Log in `media_admin` and return the session cookie value.
async fn login(router: axum::Router) -> String {
    let resp = router
        .clone()
        .oneshot(
            Request::builder()
                .uri("/admin/login")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .expect("get login");
    let csrf_cookie = resp
        .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("login sets umbral_csrf_token cookie");
    let bytes = resp
        .into_body()
        .collect()
        .await
        .expect("collect")
        .to_bytes();
    let csrf = extract_csrf(&String::from_utf8_lossy(&bytes));
    let form = serde_urlencoded::to_string([
        ("username", "media_admin"),
        ("password", "pass123"),
        ("csrf_token", csrf.as_str()),
        ("next", "/admin/"),
    ])
    .unwrap();
    let resp2 = router
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/admin/login")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .header(header::COOKIE, format!("umbral_csrf_token={csrf_cookie}"))
                .body(Body::from(form))
                .unwrap(),
        )
        .await
        .expect("post login");
    resp2
        .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_session" {
                Some(v.to_string())
            } else {
                None
            }
        })
        .expect("login sets umbral_session cookie")
}

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

/// Multipart create stores the file via Storage and writes the returned
/// key to the column; the bytes are retrievable from the backend.
#[tokio::test]
async fn multipart_create_stores_file_and_writes_key() {
    let router = boot().await.clone();
    let session = login(router.clone()).await;

    let png = b"\x89PNG\r\n\x1a\nFAKEIMAGE";
    let body = multipart_body(&[
        ("name", None, None, b"Widget"),
        ("cover", Some("hero.png"), Some("image/png"), png),
    ]);

    let (status, _h, _b) = send(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri("/admin/product/new")
            .header(
                header::CONTENT_TYPE,
                format!("multipart/form-data; boundary={BOUNDARY}"),
            )
            .header(header::COOKIE, format!("umbral_session={session}"))
            .body(Body::from(body))
            .unwrap(),
    )
    .await;
    // Full-page create redirects to the changelist on success.
    assert!(
        status == StatusCode::SEE_OTHER || status == StatusCode::OK,
        "create should succeed, got {status}"
    );

    // The row exists with cover = the stored key.
    let pool = umbral::db::pool();
    let key: String = sqlx::query_scalar("SELECT cover FROM product WHERE name = 'Widget'")
        .fetch_one(&pool)
        .await
        .expect("row created");
    assert_eq!(key, "uploads/hero.png", "cover column holds the stored key");

    // And the bytes are retrievable through the ambient Storage.
    let backend = BACKEND.get().cloned().unwrap();
    let got = backend.retrieve(&key).await.expect("file stored");
    assert_eq!(got, png, "stored bytes match the upload");
}

/// The change form renders multipart enctype, a file input, and an image
/// preview whose src is the resolved URL.
#[tokio::test]
async fn change_form_renders_multipart_and_image_preview() {
    let router = boot().await.clone();
    let session = login(router.clone()).await;

    // Seed a row directly with a known key.
    let pool = umbral::db::pool();
    sqlx::query("INSERT INTO product (name, cover) VALUES ('Seeded', 'uploads/seed.png')")
        .execute(&pool)
        .await
        .expect("seed");
    let id: i64 = sqlx::query_scalar("SELECT id FROM product WHERE name = 'Seeded'")
        .fetch_one(&pool)
        .await
        .expect("id");

    let (status, _h, html) = send(
        router.clone(),
        Request::builder()
            .method("GET")
            .uri(format!("/admin/product/{id}/edit"))
            .header(header::COOKIE, format!("umbral_session={session}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "edit form loads");

    assert!(
        html.contains(r#"enctype="multipart/form-data""#),
        "form carries multipart enctype when a file field is present"
    );
    assert!(
        html.contains(r#"type="file""#) && html.contains(r#"name="cover""#),
        "file input rendered for the cover field"
    );
    // Image preview <img> with the resolved URL (not the raw key).
    assert!(
        html.contains("<img "),
        "an <img> thumbnail is rendered for the current image value"
    );
    // The preview src is the storage-resolved URL (not the raw key).
    // minijinja entity-escapes the `/` in attribute values, so compare
    // against the un-escaped HTML to keep the assertion about the URL,
    // not the escaping scheme.
    let unescaped = html.replace("&#x2f;", "/").replace("&#47;", "/");
    assert!(
        unescaped.contains("src=\"https://cdn.test/uploads/seed.png\""),
        "image preview src is the resolved storage URL"
    );
    assert!(
        !html.contains("src=\"uploads/seed.png\"")
            && !unescaped.contains("src=\"uploads/seed.png\""),
        "preview must use the resolved URL, never the raw key"
    );
}

/// An update with an EMPTY file part leaves the existing key untouched.
#[tokio::test]
async fn update_without_new_file_preserves_existing_key() {
    let router = boot().await.clone();
    let session = login(router.clone()).await;

    let pool = umbral::db::pool();
    sqlx::query("INSERT INTO product (name, cover) VALUES ('Keepme', 'uploads/keep.png')")
        .execute(&pool)
        .await
        .expect("seed");
    let id: i64 = sqlx::query_scalar("SELECT id FROM product WHERE name = 'Keepme'")
        .fetch_one(&pool)
        .await
        .expect("id");

    // Submit the edit form changing only the name, with an EMPTY file
    // part for cover (what a browser sends when no new file is chosen).
    let body = multipart_body(&[
        ("name", None, None, b"Keepme Renamed"),
        ("cover", Some(""), Some("application/octet-stream"), b""),
    ]);
    let (status, _h, _b) = send(
        router.clone(),
        Request::builder()
            .method("POST")
            .uri(format!("/admin/product/{id}/edit"))
            .header(
                header::CONTENT_TYPE,
                format!("multipart/form-data; boundary={BOUNDARY}"),
            )
            .header(header::COOKIE, format!("umbral_session={session}"))
            .body(Body::from(body))
            .unwrap(),
    )
    .await;
    assert!(
        status == StatusCode::SEE_OTHER || status == StatusCode::OK,
        "update should succeed, got {status}"
    );

    let (name, cover): (String, String) =
        sqlx::query_as("SELECT name, cover FROM product WHERE id = ?")
            .bind(id)
            .fetch_one(&pool)
            .await
            .expect("row");
    assert_eq!(name, "Keepme Renamed", "name updated");
    assert_eq!(
        cover, "uploads/keep.png",
        "existing cover key preserved when no new file uploaded"
    );
}

/// The CHANGELIST renders an image column as an `<img>` thumbnail whose
/// `src` is the resolved storage URL — not the raw key printed as text.
#[tokio::test]
async fn changelist_renders_image_thumbnail_not_raw_key() {
    let router = boot().await.clone();
    let session = login(router.clone()).await;

    // Seed a row with a known image key.
    let pool = umbral::db::pool();
    sqlx::query("INSERT INTO product (name, cover) VALUES ('Listed', 'uploads/list.png')")
        .execute(&pool)
        .await
        .expect("seed");

    let (status, _h, html) = send(
        router.clone(),
        Request::builder()
            .method("GET")
            .uri("/admin/product/")
            .header(header::COOKIE, format!("umbral_session={session}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "changelist loads");

    // minijinja entity-escapes `/` in attribute values; compare against
    // the un-escaped HTML so the assertion is about the URL not escaping.
    let unescaped = html.replace("&#x2f;", "/").replace("&#47;", "/");
    assert!(
        unescaped.contains("<img src=\"https://cdn.test/uploads/list.png\""),
        "changelist renders an <img> thumbnail with the resolved URL"
    );
    // The raw key must NOT appear as bare cell text (it's only inside the
    // resolved src/href URL).
    assert!(
        !unescaped.contains(">uploads/list.png<"),
        "raw storage key must not be printed as cell text"
    );
}

/// The PREVIEW sheet renders an image column as an `<img>` whose `src`
/// is the resolved storage URL.
#[tokio::test]
async fn preview_sheet_renders_image_not_raw_key() {
    let router = boot().await.clone();
    let session = login(router.clone()).await;

    let pool = umbral::db::pool();
    sqlx::query("INSERT INTO product (name, cover) VALUES ('Previewed', 'uploads/prev.png')")
        .execute(&pool)
        .await
        .expect("seed");
    let id: i64 = sqlx::query_scalar("SELECT id FROM product WHERE name = 'Previewed'")
        .fetch_one(&pool)
        .await
        .expect("id");

    let (status, _h, html) = send(
        router.clone(),
        Request::builder()
            .method("GET")
            .uri(format!("/admin/product/{id}/sheet"))
            .header(header::COOKIE, format!("umbral_session={session}"))
            // The preview sheet only renders the fragment for HTMX
            // requests; otherwise it redirects to the changelist.
            .header("HX-Request", "true")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "preview sheet loads");

    let unescaped = html.replace("&#x2f;", "/").replace("&#47;", "/");
    assert!(
        unescaped.contains("<img src=\"https://cdn.test/uploads/prev.png\""),
        "preview sheet renders an <img> with the resolved URL, not the raw key"
    );
    assert!(
        !unescaped.contains("src=\"uploads/prev.png\""),
        "preview must use the resolved URL, never the raw key"
    );
}