laterite-admin 0.9.12

Laterite CMF admin surface: the Axum router, session middleware, and login shell
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
//! The roles screen's create and edit form: the permission editor.
//!
//! Roles carry a `text[]` of dotted permission strings. This dedicated form
//! renders the registered permissions ([`crate::Permission`]) as grouped
//! checkboxes, checked for the ones the role holds, and persists the selection.
//! Only registered permissions are accepted, so a crafted submission cannot
//! grant a permission the deployment never declared. The roles list stays a
//! generic resource; only its form is specialised.

use askama::Template;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Form};
use laterite_auth::AuthenticatedUser;
use laterite_core::query::{bind_values, build as to_sql, text_cast};
use laterite_core::{t, AnyRowExt, Text};
use sea_query::{Alias, Expr, Query};

use crate::checklist::{Checklist, Choice, Entry};
use crate::{not_found, render, render_error, AdminState, Permission, Shell};

/// Renders an empty create form.
pub(crate) async fn new_form(
    State(state): State<AdminState>,
    Extension(shell): Extension<Shell>,
) -> Response {
    let action = format!("{}/roles/new", state.admin_path);
    render(build(&state, &action, None, "", "", &[], false, shell))
}

/// Persists a new role, then redirects to the list.
pub(crate) async fn create(
    State(state): State<AdminState>,
    Extension(shell): Extension<Shell>,
    Extension(session): Extension<crate::session::SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    headers: axum::http::HeaderMap,
    Form(pairs): Form<Vec<(String, String)>>,
) -> Response {
    let htmx = crate::form::is_htmx(&headers);
    let (code, name, perms) = parse(&pairs);
    let perms = registered_only(perms, &state.permissions);
    let action = format!("{}/roles/new", state.admin_path);
    if code.is_empty() || name.is_empty() {
        return invalid_response(
            htmx,
            build(
                &state,
                &action,
                Some(t!("Code and name are required.")),
                &code,
                &name,
                &perms,
                false,
                shell,
            ),
        );
    }
    match laterite_auth::store::create_role(&state.db, &code, &name, &perms).await {
        Ok(role_id) => {
            let detail = serde_json::json!({ "code": code, "name": name }).to_string();
            let target_id = role_id.to_string();
            crate::audit::record(
                &state,
                &user,
                "backend.role.create",
                Some("backend_role"),
                Some(target_id.as_str()),
                Some(name.as_str()),
                Some(detail.as_str()),
            )
            .await;
            session.push_flash(crate::session::FlashLevel::Success, t!("Role created."));
            crate::form::saved_response(htmx, &format!("{}/roles", state.admin_path))
        }
        Err(_) => invalid_response(
            htmx,
            build(
                &state,
                &action,
                Some(t!("Could not save. The code may already be in use.")),
                &code,
                &name,
                &perms,
                false,
                shell,
            ),
        ),
    }
}

/// Renders the form populated with an existing role.
pub(crate) async fn edit_form(
    State(state): State<AdminState>,
    Extension(shell): Extension<Shell>,
    Path(id): Path<String>,
) -> Response {
    let action = format!("{}/roles/{id}/edit", state.admin_path);
    // Scope the builder so it drops before the await, keeping the future `Send`.
    let (sql, values) = {
        let stmt = Query::select()
            .columns([
                Alias::new("code"),
                Alias::new("name"),
                Alias::new("permissions"),
                Alias::new("is_system"),
            ])
            .from(Alias::new("backend_roles"))
            .and_where(
                Expr::col(Alias::new("id"))
                    .cast_as(Alias::new(text_cast(state.db.backend)))
                    .eq(id.clone()),
            )
            .to_owned();
        to_sql(state.db.backend, stmt)
    };
    let row = match bind_values(sqlx::query(&sql), values)
        .fetch_optional(&state.db.pool)
        .await
    {
        Ok(row) => row,
        Err(_) => return render_error(),
    };
    let Some(row) = row else {
        return not_found();
    };
    let code = row.get_text("code").unwrap_or_default();
    let name = row.get_text("name").unwrap_or_default();
    let perms_json = row.get_text("permissions").unwrap_or_default();
    let perms: Vec<String> = serde_json::from_str(&perms_json).unwrap_or_default();
    let system = row.get_bool("is_system").unwrap_or(false);
    render(build(
        &state, &action, None, &code, &name, &perms, system, shell,
    ))
}

/// Persists an edited role, then redirects to the list.
pub(crate) async fn update(
    State(state): State<AdminState>,
    Extension(shell): Extension<Shell>,
    Extension(session): Extension<crate::session::SessionHandle>,
    Extension(user): Extension<AuthenticatedUser>,
    Path(id): Path<String>,
    headers: axum::http::HeaderMap,
    Form(pairs): Form<Vec<(String, String)>>,
) -> Response {
    let htmx = crate::form::is_htmx(&headers);
    let (code, name, perms) = parse(&pairs);
    let perms = registered_only(perms, &state.permissions);
    let action = format!("{}/roles/{id}/edit", state.admin_path);
    // The framework rewrites its own roles at every boot, so a save here would
    // be undone without telling anyone. Refused, form or crafted POST alike.
    if let Ok(row_id) = id.parse::<i64>() {
        if laterite_auth::store::role_is_system(&state.db, row_id)
            .await
            .unwrap_or(false)
        {
            return invalid_response(
                htmx,
                build(
                    &state,
                    &action,
                    Some(t!(
                        "This role is maintained by the framework. Duplicate it to make your own."
                    )),
                    &code,
                    &name,
                    &perms,
                    true,
                    shell,
                ),
            );
        }
    }
    if code.is_empty() || name.is_empty() {
        return invalid_response(
            htmx,
            build(
                &state,
                &action,
                Some(t!("Code and name are required.")),
                &code,
                &name,
                &perms,
                false,
                shell,
            ),
        );
    }
    let perms_json = serde_json::to_string(&perms).unwrap_or_else(|_| "[]".to_string());
    // Scope the builder so it drops before the await, keeping the future `Send`.
    let (sql, values) = {
        let stmt = Query::update()
            .table(Alias::new("backend_roles"))
            .value(Alias::new("code"), code.clone())
            .value(Alias::new("name"), name.clone())
            .value(Alias::new("permissions"), perms_json)
            .and_where(
                Expr::col(Alias::new("id"))
                    .cast_as(Alias::new(text_cast(state.db.backend)))
                    .eq(id.clone()),
            )
            .to_owned();
        to_sql(state.db.backend, stmt)
    };
    match bind_values(sqlx::query(&sql), values)
        .execute(&state.db.pool)
        .await
    {
        Ok(_) => {
            let detail = serde_json::json!({ "code": code, "name": name }).to_string();
            crate::audit::record(
                &state,
                &user,
                "backend.role.update",
                Some("backend_role"),
                Some(id.as_str()),
                Some(name.as_str()),
                Some(detail.as_str()),
            )
            .await;
            session.push_flash(crate::session::FlashLevel::Success, t!("Role updated."));
            crate::form::saved_response(htmx, &format!("{}/roles", state.admin_path))
        }
        Err(_) => invalid_response(
            htmx,
            build(
                &state,
                &action,
                Some(t!("Could not save. The code may already be in use.")),
                &code,
                &name,
                &perms,
                false,
                shell,
            ),
        ),
    }
}

/// Pulls `code`, `name`, and the repeated `perm` values out of the submitted
/// form pairs. A checkbox list arrives as one `perm` pair per ticked box, so the
/// form is decoded as an ordered list of pairs rather than a map.
fn parse(pairs: &[(String, String)]) -> (String, String, Vec<String>) {
    let mut code = String::new();
    let mut name = String::new();
    let mut perms = Vec::new();
    for (key, value) in pairs {
        match key.as_str() {
            "code" => code = value.trim().to_string(),
            "name" => name = value.trim().to_string(),
            "perm" => perms.push(value.clone()),
            _ => {}
        }
    }
    (code, name, perms)
}

/// Keeps only the submitted permissions that the deployment has registered.
fn registered_only(perms: Vec<String>, registry: &[Permission]) -> Vec<String> {
    perms
        .into_iter()
        .filter(|p| registry.iter().any(|r| &r.code == p))
        .collect()
}

/// The registered permissions as a checklist: grouped by their `group` in
/// registry order, with the ones the role holds ticked. A role the framework
/// owns is shown and cannot be changed.
fn group_permissions(
    registry: &[Permission],
    selected: &[String],
    system: bool,
    shell: &Shell,
) -> Checklist {
    let mut groups: Vec<(String, Vec<Entry>)> = Vec::new();
    for permission in registry {
        let choice = Choice::new("perm", permission.code.clone(), shell.tt(&permission.label))
            .checked(selected.iter().any(|s| s == &permission.code));
        // Merge by the localized group heading (same source localizes identically).
        let heading = shell.tt(&permission.group);
        match groups.iter_mut().find(|(name, _)| *name == heading) {
            Some((_, entries)) => entries.push(choice.into()),
            None => groups.push((heading, vec![choice.into()])),
        }
    }
    let mut list = Checklist::new(shell.tt(&t!("Permissions"))).read_only(system);
    for (heading, entries) in groups {
        list = list.group(heading, entries);
    }
    list
}

#[allow(clippy::too_many_arguments)]
fn build(
    state: &AdminState,
    action: &str,
    error: Option<Text>,
    code: &str,
    name: &str,
    selected: &[String],
    system: bool,
    shell: Shell,
) -> RolesFormTemplate {
    let permissions = group_permissions(&state.permissions, selected, system, &shell)
        .render(shell.i18n())
        .into_string();
    let title = shell.tt(&t!("Role"));
    let error = error.map(|e| shell.tt(&e));
    RolesFormTemplate {
        shell,
        title,
        action: action.to_string(),
        cancel_path: format!("{}/roles", state.admin_path),
        error,
        code: code.to_string(),
        name: name.to_string(),
        permissions,
        system,
        duplicate_path: format!("{}/roles/new", state.admin_path),
    }
}

#[derive(Template)]
#[template(path = "roles_form.html")]
struct RolesFormTemplate {
    shell: Shell,
    title: String,
    action: String,
    cancel_path: String,
    error: Option<String>,
    code: String,
    name: String,
    /// The permission checklist, rendered.
    permissions: String,
    /// A role the framework owns: shown, never saved.
    system: bool,
    duplicate_path: String,
}

/// The form alone, for an HTMX submit that swaps it in place.
#[derive(Template)]
#[template(path = "_roles_form_fields.html")]
struct RolesFormFragment {
    shell: Shell,
    action: String,
    cancel_path: String,
    error: Option<String>,
    code: String,
    name: String,
    /// The permission checklist, rendered.
    permissions: String,
    system: bool,
    duplicate_path: String,
}

/// The 422 response for a rejected save: the form alone under HTMX, the whole
/// page otherwise, so the screen still works with scripting off.
fn invalid_response(htmx: bool, page: RolesFormTemplate) -> Response {
    let body = if htmx {
        render(RolesFormFragment {
            shell: page.shell,
            action: page.action,
            cancel_path: page.cancel_path,
            error: page.error,
            code: page.code,
            name: page.name,
            permissions: page.permissions,
            system: page.system,
            duplicate_path: page.duplicate_path,
        })
    } else {
        render(page)
    };
    (StatusCode::UNPROCESSABLE_ENTITY, body).into_response()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn registry() -> Vec<Permission> {
        vec![
            Permission::new("backend.manage_users", "Manage backend users", "Backend"),
            Permission::new("acme.publish", "Publish", "Content"),
        ]
    }

    #[test]
    fn parse_pulls_scalars_and_repeated_perms() {
        let pairs = vec![
            ("code".to_string(), "  editor ".to_string()),
            ("name".to_string(), "Editor".to_string()),
            ("perm".to_string(), "backend.manage_users".to_string()),
            ("perm".to_string(), "acme.publish".to_string()),
        ];
        let (code, name, perms) = parse(&pairs);
        assert_eq!(code, "editor");
        assert_eq!(name, "Editor");
        assert_eq!(perms, ["backend.manage_users", "acme.publish"]);
    }

    #[test]
    fn only_registered_permissions_survive() {
        let kept = registered_only(
            vec![
                "backend.manage_users".to_string(),
                "nope.invalid".to_string(),
            ],
            &registry(),
        );
        assert_eq!(kept, ["backend.manage_users"]);
    }

    #[test]
    fn grouping_preserves_order_and_marks_selected() {
        let shell = Shell::test();
        let list = group_permissions(&registry(), &["acme.publish".to_string()], false, &shell);
        assert_eq!((list.checked(), list.total()), (1, 2));
        let html = list.render(shell.i18n()).into_string();
        let backend = html.find("Backend").unwrap();
        let content = html.find("Content").unwrap();
        assert!(backend < content);
        assert!(html.contains(r#"name="perm" value="backend.manage_users">"#));
        assert!(html.contains(r#"name="perm" value="acme.publish" checked>"#));
    }

    #[test]
    fn a_system_role_is_shown_locked() {
        let shell = Shell::test();
        let html = group_permissions(&registry(), &["acme.publish".to_string()], true, &shell)
            .render(shell.i18n())
            .into_string();
        assert!(html.contains(r#"name="perm" value="acme.publish" checked disabled>"#));
    }
}

/// The roles form answers HTMX the same way the descriptor form does.
#[cfg(test)]
mod htmx_tests {
    use super::*;
    use laterite_core::testing::{connect_test, TestGuard};
    use laterite_core::Db;

    async fn test_db() -> (Db, TestGuard) {
        connect_test(&[laterite_auth::migrations()]).await
    }

    fn htmx_headers() -> axum::http::HeaderMap {
        let mut h = axum::http::HeaderMap::new();
        h.insert("hx-request", "true".parse().unwrap());
        h
    }

    /// Missing the required code, so the handler refuses before touching the db.
    fn invalid() -> Vec<(String, String)> {
        vec![("name".to_string(), "Editor".to_string())]
    }

    fn valid() -> Vec<(String, String)> {
        vec![
            ("code".to_string(), "editor".to_string()),
            ("name".to_string(), "Editor".to_string()),
        ]
    }

    async fn post(pairs: Vec<(String, String)>, headers: axum::http::HeaderMap) -> Response {
        let (db, _guard) = test_db().await;
        let state = AdminState::new(
            laterite_auth::AuthService::new(db.clone(), laterite_auth::AuthConfig::default()),
            db,
        );
        create(
            State(state),
            Extension(Shell::test()),
            Extension(crate::session::SessionHandle::from_blob(None)),
            Extension(crate::audit::test_actor()),
            headers,
            Form(pairs),
        )
        .await
    }

    async fn body_of(resp: Response) -> String {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    #[tokio::test]
    async fn an_htmx_submit_that_fails_returns_the_form_alone() {
        let resp = post(invalid(), htmx_headers()).await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let html = body_of(resp).await;
        assert!(html.contains("<form"), "the form comes back");
        assert!(html.contains("lat-alert"), "carrying the error");
        assert!(
            html.contains(r#"data-lat-widget="checklist""#),
            "and the permission editor"
        );
        assert!(!html.contains("<body"), "no page chrome");
    }

    #[tokio::test]
    async fn a_plain_submit_that_fails_returns_the_whole_page() {
        let resp = post(invalid(), axum::http::HeaderMap::new()).await;
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let html = body_of(resp).await;
        assert!(
            html.contains("<body"),
            "the screen still works without htmx"
        );
        assert!(html.contains("lat-alert"));
    }

    #[tokio::test]
    async fn an_htmx_submit_that_succeeds_redirects_by_header() {
        let resp = post(valid(), htmx_headers()).await;
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert_eq!(resp.headers().get("HX-Redirect").unwrap(), "/admin/roles");
    }

    #[tokio::test]
    async fn a_plain_submit_that_succeeds_redirects_normally() {
        let resp = post(valid(), axum::http::HeaderMap::new()).await;
        assert_eq!(resp.status(), StatusCode::SEE_OTHER);
        assert_eq!(resp.headers().get("location").unwrap(), "/admin/roles");
    }
}