acme-proxy-admin 0.6.1

The operation layer and web admin panel of acme-proxy (internal crate, no semver promise)
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
//! `/ui` — the HTML the operator actually looks at.
//!
//! ## Why this is separate from `handlers/`
//!
//! `handlers/` answers JSON at `/api`; this answers HTML at `/ui`. Both are
//! thin layers over the same `crates/admin/src/admin/` operations, which is the whole point:
//! neither re-derives data, and neither is where a rule lives. Two small
//! handlers over one operation beat one handler content-negotiating itself into
//! two representations — htmx swaps markup, and a `text/html` branch inside a
//! JSON handler is where the two would start disagreeing.
//!
//! A write goes one step further: a page calls the **same** `apply_*` function
//! its `/api` twin does (see `handlers/mod.rs`), which owns the validation, the
//! audit rows and the log line. A page decides only which refusals are a banner
//! beside the card and which replace the page.
//! `every_shared_write_leaves_the_same_audit_rows_on_both_surfaces`
//! (`tests/admin_pages.rs`) compares the two.
//!
//! ## Pages and fragments
//!
//! Every list and detail route serves both. A normal navigation gets the full
//! document — the layout, the navigation, the page's content — and an htmx
//! request gets the bare partial it is going to swap in. The choice is made off
//! the `HX-Request` header ([`auth::is_htmx`]), not off the route, so there is
//! one URL per resource and it is bookmarkable.
//!
//! ## What makes a write safe here
//!
//! Exactly what makes it safe on the API: [`PageSessionWrite`] wraps
//! [`crate::webadmin::session::AuthenticatedWrite`], so the origin gate, the
//! session lookup and the CSRF check all run before a mutating handler can see
//! a session. The token reaches the browser through `hx-headers` on `<body>` in
//! `layout.html` and comes back as `X-CSRF-Token` — the same header the JSON
//! API uses, and the reason `check_csrf` needed no second code path.

pub mod account;
pub mod accounts;
pub mod assets;
pub mod audit;
pub mod auth;
pub mod eab;
pub mod error;
pub mod expiring;
pub mod filter;
pub mod jobs;
pub mod misc;
pub mod operators;
pub mod orders;
pub mod session;
pub mod templates;
pub mod upstream_orders;

pub use auth::{
    PageAdminRead, PageAdminWrite, PageAuth, PageSelfServiceWrite, PageSession, PageSessionWrite,
};
pub use error::PageError;

use axum::Router;
use axum::response::{Html, IntoResponse, Response};
use axum::routing::{get, post};
use serde_json::{Map, Value, json};

use crate::webadmin::AdminState;
use crate::webadmin::error::AdminError;
use crate::webadmin::handlers::paging::Page;

/// Everything under `/ui`, including the assets and the two unauthenticated
/// sign-in routes.
///
/// Full paths rather than a `nest`: the admin listener's fallback is HTML (a
/// browser-facing listener should answer a browser), and the JSON fallback the
/// API needs is already scoped inside its own nest. One fewer nesting level is
/// one fewer place for a path to be assembled twice.
pub(crate) fn pages_router() -> Router<AdminState> {
    Router::new()
        // No session: the sign-in page, and the assets it needs to render.
        .route(
            "/ui/login",
            get(session::get_login).post(session::post_login),
        )
        // The second half of signing in. It takes a `pending_mfa` cookie, which
        // is the one thing `PageSession` refuses -- so it belongs here, above
        // the line, and not below it.
        .route(
            "/ui/login/mfa",
            get(session::get_login_mfa).post(session::post_login_mfa),
        )
        .route("/ui/static/{file}", get(assets::get_asset))
        // Everything below needs one.
        .route("/ui/", get(misc::get_index))
        // The operator's own page. No id in any of these paths: there is
        // exactly one account they can be about, and the session names it.
        .route("/ui/account", get(account::get_account))
        .route("/ui/account/mfa/totp", post(account::begin_totp))
        .route("/ui/account/mfa/totp/confirm", post(account::confirm_totp))
        .route("/ui/account/mfa/totp/disable", post(account::disable_totp))
        .route(
            "/ui/account/mfa/recovery-codes",
            post(account::regenerate_recovery_codes),
        )
        .route("/ui/account/password", post(account::change_password))
        .route("/ui/account/contact", post(account::change_contact))
        .route(
            "/ui/account/sessions/{id}/revoke",
            post(account::revoke_own_session),
        )
        .route("/ui/logout", post(session::post_logout))
        // The operators surface: every operator this process has, and acting
        // on one *other* than the caller — see `pages::operators`. Every
        // mutating route here sits behind `verify_current_password`, unlike the
        // `/ui/account/*` routes just above.
        .route("/ui/operators", get(operators::list_operators))
        .route("/ui/operators/{username}", get(operators::get_operator))
        .route(
            "/ui/operators/{username}/disable",
            post(operators::disable_operator),
        )
        .route(
            "/ui/operators/{username}/enable",
            post(operators::enable_operator),
        )
        .route(
            "/ui/operators/{username}/totp/reset",
            post(operators::reset_operator_totp),
        )
        .route(
            "/ui/operators/{username}/contact",
            post(operators::set_operator_contact),
        )
        .route(
            "/ui/operators/{username}/role",
            post(operators::set_operator_role),
        )
        .route(
            "/ui/operators/{username}/sessions/{id}/revoke",
            post(operators::revoke_operator_session),
        )
        .route("/ui/accounts", get(accounts::list_accounts))
        .route(
            "/ui/accounts/{id}",
            get(accounts::get_account).delete(accounts::delete_account),
        )
        .route(
            "/ui/accounts/{id}/orders",
            get(accounts::list_account_orders),
        )
        .route(
            "/ui/accounts/{id}/contact",
            post(accounts::post_account_contact),
        )
        .route(
            "/ui/accounts/{id}/deactivate",
            post(accounts::deactivate_account),
        )
        // Read-only, and the only list here with no control in its rows.
        .route("/ui/expiring", get(expiring::list_expiring))
        .route("/ui/audit", get(audit::list_audit))
        .route("/ui/audit/{id}", get(audit::get_audit))
        .route("/ui/orders", get(orders::list_orders))
        .route(
            "/ui/orders/{id}",
            get(orders::get_order).delete(orders::delete_order),
        )
        .route("/ui/orders/{id}/revoke", post(orders::revoke_order))
        // A `GET`, so it is absent from `mutating_page_endpoints()` by right
        // rather than by omission.
        .route("/ui/orders/{id}/chain.pem", get(orders::download_chain))
        .route("/ui/jobs", get(jobs::list_jobs))
        .route("/ui/jobs/{id}", get(jobs::get_job))
        .route("/ui/jobs/{id}/cancel", post(jobs::cancel_job))
        .route("/ui/jobs/{id}/run", post(jobs::run_job))
        // Read-only, absent from `mutating_page_endpoints()` by design.
        .route(
            "/ui/upstream-orders",
            get(upstream_orders::list_upstream_orders),
        )
        .route(
            "/ui/upstream-orders/{id}",
            get(upstream_orders::get_upstream_order),
        )
        .route("/ui/eab", get(eab::list_eab).post(eab::create_eab))
        .route("/ui/eab/{kid}", get(eab::get_eab).delete(eab::delete_eab))
        .route("/ui/eab/{kid}/revoke", post(eab::revoke_eab))
        .route("/ui/nonces", get(misc::get_nonces))
        .route("/ui/nonces/cleanup", post(misc::cleanup_nonces))
        .route("/ui/profiles", get(misc::list_profiles))
        // Read-only: a policy is configuration, and `filter explain` -- the
        // one that would need a form -- has no web surface at all. Absent from
        // `mutating_page_endpoints()` accordingly.
        .route(
            "/ui/profiles/{name}/filter",
            get(filter::get_profile_filter),
        )
}

/// The context every full page needs on top of its own data.
///
/// `csrf_token` is the load-bearing member: `layout.html` puts it on `<body>`
/// as an `hx-headers` attribute, and every mutating request htmx issues carries
/// it back. A page rendered without it loses every write at once, which is the
/// intended failure mode — a partial loss would be worse.
pub(crate) fn chrome<S: PageAuth>(
    session: &S,
    nav: &'static str,
    title: &str,
) -> Map<String, Value> {
    let mut context = fragment_context(session.auth());
    context.insert("nav".to_string(), Value::String(nav.to_string()));
    context.insert("title".to_string(), Value::String(title.to_string()));
    context
}

/// The context every rendering for a signed-in caller starts from: the half of
/// [`chrome`] that a mutation's fragment needs too.
///
/// `can_write` is what templates gate their controls on. Six of them used to
/// spell it `not user is defined or user.role != "viewer"`, on the reasoning
/// that a fragment rendered without `user` must be answering a mutation whose
/// caller had already passed a write extractor. That held only while every
/// fragment was assembled by hand the same way: a read path rendering one
/// without `user` would have shown a `viewer` every control. Now the decision
/// is computed once, from the role, and travels with every rendering — and a
/// template that meets no `can_write` at all hides the control.
///
/// `csrf_token` rides along for the forms that carry it explicitly: a fragment
/// rendered standalone is not yet inside the `<body>` whose `hx-headers` it
/// would otherwise inherit.
pub(crate) fn fragment_context(
    auth: &crate::webadmin::session::Authenticated,
) -> Map<String, Value> {
    let mut context = Map::new();
    context.insert(
        "csrf_token".to_string(),
        Value::String(auth.session.csrf_token.clone()),
    );
    context.insert(
        "user".to_string(),
        crate::admin::render_admin_user_json(&auth.user),
    );
    context.insert(
        "can_write".to_string(),
        Value::Bool(auth.user.role() >= acme_proxy_store::admin_user::AdminRole::Operator),
    );
    context
}

/// Renders `page` for a navigation and `fragment` for an htmx swap.
///
/// The single place the page/fragment choice is expressed, so a route cannot
/// accidentally serve a bare partial to the address bar (a document with no
/// `<html>`) or a whole document into a `<div>`.
pub(crate) fn respond(
    state: &AdminState,
    hx: bool,
    page: &str,
    fragment: &str,
    context: Map<String, Value>,
) -> Result<Html<String>, PageError> {
    let name = if hx { fragment } else { page };
    templates::render(
        &state.templates,
        name,
        minijinja::Value::from_serialize(Value::Object(context)),
    )
}

/// Renders a fragment only — the answer to every mutation, which is always a
/// swap and never a navigation.
pub(crate) fn respond_fragment(
    state: &AdminState,
    fragment: &str,
    context: Map<String, Value>,
) -> Result<Html<String>, PageError> {
    templates::render(
        &state.templates,
        fragment,
        minijinja::Value::from_serialize(Value::Object(context)),
    )
}

/// A banner for a partial to render: `kind` is `ok`, `error` or `warn`.
#[must_use]
pub(crate) fn flash(kind: &str, message: impl Into<String>) -> Value {
    json!({ "kind": kind, "message": message.into() })
}

/// The banner form of a refusal that is worth showing rather than replacing the
/// page with.
///
/// A `409 already_revoked` is the motivating case: the operator asked for
/// something the row's state does not allow, the answer belongs next to the
/// button they pressed, and the code is the same string the JSON API returns.
#[must_use]
pub(crate) fn flash_error(code: &str, message: impl Into<String>) -> Value {
    json!({ "kind": "error", "message": message.into(), "code": code })
}

/// A refusal rendered as a card's own banner, keeping the refusal's status and
/// its headers.
///
/// The shape four handlers had each written out for themselves: an
/// [`AdminError`] the caller judged worth *showing beside* the control rather
/// than replacing the page with (a wrong password on a step-up, a `409` on a
/// row whose state moved), rendered into the same fragment the success path
/// re-renders.
///
/// One place rather than four, and the reason is the thing three of them
/// dropped: `AdminError::rate_limited` sets a `Retry-After` header, and a
/// hand-rebuilt `(status, body)` tuple loses it. Building from
/// `error.into_response()` and swapping the body keeps every header the error
/// carries, whatever a later constructor adds.
///
/// A `401` is reworded: on this path it means "that password is not correct",
/// not "sign in again" — the session making the request is perfectly live, and
/// the API's own wording would read as a bounce.
pub(crate) fn refuse_with_card(
    state: &AdminState,
    fragment: &str,
    mut context: Map<String, Value>,
    error: &AdminError,
) -> Result<Response, PageError> {
    let message = if error.status == axum::http::StatusCode::UNAUTHORIZED {
        "That password is not correct.".to_string()
    } else {
        error.message.clone()
    };
    context.insert("flash".to_string(), flash_error(error.code, message));
    let body = respond_fragment(state, fragment, context)?;

    let mut response = error.clone().into_response();
    *response.body_mut() = body.into_response().into_body();
    response.headers_mut().insert(
        axum::http::header::CONTENT_TYPE,
        axum::http::HeaderValue::from_static("text/html; charset=utf-8"),
    );
    Ok(response)
}

/// The `{items, total}` half of a list context; the window itself is [`pager`].
///
/// Every paged fragment template reads `page.items` and the pager reads the
/// window, so the two halves are built separately and land in the context under
/// their own names.
#[must_use]
pub(crate) fn page_value(items: Vec<Value>, total: i64) -> Value {
    json!({ "items": items, "total": total })
}

/// A closed vocabulary as the filter `<select>` offers it: every value of the
/// enum the matching `?status=` is parsed against, so a status added there is
/// offered here rather than being filterable only by a hand-typed URL.
#[must_use]
pub(crate) fn vocabulary<T: Copy>(all: &[T], name: impl Fn(T) -> &'static str) -> Value {
    Value::Array(all.iter().map(|value| Value::from(name(*value))).collect())
}

/// The filters a list page is showing, stated once.
///
/// Each list handler used to spell its filter set three times — the
/// `unwrap_or_default` locals, the slice handed to [`pager`] and the `filters`
/// object the form echoes — and `/ui/audit` let two of the three drift: it
/// filtered on `orderId`/`certSerial` and carried neither to the next page, so
/// a deep link lost its filter on page two. One list, two views of it.
#[derive(Debug, Default)]
pub(crate) struct ListFilters(Vec<(&'static str, String)>);

impl ListFilters {
    #[must_use]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// One filter under its query-string name; absent is the empty string, the
    /// "any" option every control on this listener sends.
    #[must_use]
    pub(crate) fn with(mut self, key: &'static str, value: Option<&str>) -> Self {
        self.0.push((key, value.unwrap_or_default().to_string()));
        self
    }

    /// The `(key, value)` pairs [`pager`] carries forward, blank ones included
    /// (it drops those itself).
    #[must_use]
    pub(crate) fn pairs(&self) -> Vec<(&str, &str)> {
        self.0
            .iter()
            .map(|(key, value)| (*key, value.as_str()))
            .collect()
    }

    /// The `filters` object a list template echoes into its form controls.
    #[must_use]
    pub(crate) fn to_value(&self) -> Value {
        Value::Object(
            self.0
                .iter()
                .map(|(key, value)| ((*key).to_string(), Value::String(value.clone())))
                .collect(),
        )
    }
}

/// The offset-pagination controls for a list fragment.
///
/// Built here rather than in the template because the previous and next URLs
/// have to carry whatever filters the list was already showing — assembling a
/// query string is not a template's job, and getting it wrong silently drops a
/// filter on the second page.
pub(crate) fn pager(
    page: Page,
    total: i64,
    path: &str,
    filters: &[(&str, &str)],
    target: &str,
) -> Value {
    let url = |offset: i64| {
        let mut query = url::form_urlencoded::Serializer::new(String::new());
        query.append_pair("limit", &page.limit.to_string());
        query.append_pair("offset", &offset.to_string());
        for (key, value) in filters {
            if !value.is_empty() {
                query.append_pair(key, value);
            }
        }
        format!("{path}?{}", query.finish())
    };

    // Saturating throughout. `PageParams::resolve` already clamps `offset` so
    // this cannot overflow from the query string, but `limit`'s ceiling is
    // `admin.page_size_max`, an operator-set `i64` with no upper bound of its
    // own — and a page control is not worth a panicking arithmetic path.
    let next = page.offset.saturating_add(page.limit);
    json!({
        "total": total,
        "limit": page.limit,
        "offset": page.offset,
        // Human numbering: "1–50 of 312", and an empty page says 0–0.
        "from": if total == 0 { 0 } else { page.offset.saturating_add(1) },
        "to": next.min(total).max(0),
        "prev": (page.offset > 0).then(|| url(page.offset.saturating_sub(page.limit).max(0))),
        "next": (next < total).then(|| url(next)),
        "target": target,
        // Whether a page step rewrites the address bar. On for every list that
        // owns its page; off for a table embedded in another resource's page,
        // whose URL belongs to that resource.
        "push": true,
    })
}

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

    fn page(limit: i64, offset: i64) -> Page {
        Page { limit, offset }
    }

    #[test]
    fn the_first_page_of_several_offers_next_and_not_previous() {
        let value = pager(page(50, 0), 312, "/ui/accounts", &[], "#accounts-table");
        assert_eq!(value["from"], 1);
        assert_eq!(value["to"], 50);
        assert_eq!(value["total"], 312);
        assert!(value["prev"].is_null());
        assert_eq!(value["next"], "/ui/accounts?limit=50&offset=50");
    }

    #[test]
    fn the_last_page_offers_previous_and_not_next() {
        let value = pager(page(50, 300), 312, "/ui/accounts", &[], "#accounts-table");
        assert_eq!(value["from"], 301);
        // The final page is short, and the count must say so rather than
        // running past the total.
        assert_eq!(value["to"], 312);
        assert_eq!(value["prev"], "/ui/accounts?limit=50&offset=250");
        assert!(value["next"].is_null());
    }

    /// The bug this function exists to prevent: paging away from page one must
    /// not drop the filter the operator was looking through.
    #[test]
    fn the_filters_survive_a_page_step_and_are_encoded() {
        let value = pager(
            page(10, 0),
            40,
            "/ui/orders",
            &[("profile", "le"), ("status", ""), ("accountId", "a b&c")],
            "#orders-table",
        );
        let next = value["next"].as_str().unwrap();
        assert!(next.contains("profile=le"));
        // An empty filter is absent, not `status=`.
        assert!(!next.contains("status="));
        assert!(next.contains("accountId=a+b%26c"));
    }

    #[test]
    fn an_empty_result_set_renders_no_controls() {
        let value = pager(page(50, 0), 0, "/ui/eab", &[], "#eab-table");
        assert_eq!(value["total"], 0);
        assert_eq!(value["from"], 0);
        assert_eq!(value["to"], 0);
        assert!(value["prev"].is_null());
        assert!(value["next"].is_null());
    }

    /// `PageParams::resolve` clamps the offset, but `limit`'s own ceiling is
    /// `admin.page_size_max`, an operator-set `i64`. Neither end may panic.
    #[test]
    fn an_extreme_window_saturates_instead_of_overflowing() {
        let value = pager(page(i64::MAX, i64::MAX / 2), 10, "/ui/orders", &[], "#t");
        assert_eq!(value["to"], 10);
        assert!(value["next"].is_null());
        assert!(value["prev"].is_string());
    }

    /// Both views come from the one list, so a filter the page echoes is a
    /// filter the next page keeps — the `/ui/audit` regression, structurally.
    #[test]
    fn list_filters_echo_every_key_and_the_pager_carries_the_set_ones() {
        let filters = ListFilters::new()
            .with("certSerial", Some("0a0b"))
            .with("orderId", None);

        let echoed = filters.to_value();
        assert_eq!(echoed["certSerial"], "0a0b");
        // Absent is the empty string, which is what the form's "any" sends.
        assert_eq!(echoed["orderId"], "");

        let value = pager(page(1, 0), 5, "/ui/audit", &filters.pairs(), "#t");
        let next = value["next"].as_str().unwrap();
        assert!(next.contains("certSerial=0a0b"), "{next}");
        assert!(!next.contains("orderId"), "{next}");
        assert_eq!(value["push"], true);
    }

    #[test]
    fn a_single_full_page_offers_neither_control() {
        let value = pager(page(50, 0), 50, "/ui/accounts", &[], "#accounts-table");
        assert!(value["prev"].is_null());
        assert!(value["next"].is_null());
    }

    #[test]
    fn flashes_carry_their_kind_and_a_code_only_when_there_was_one() {
        let ok = flash("ok", "saved");
        assert_eq!(ok["kind"], "ok");
        assert!(ok.get("code").is_none());

        let error = flash_error("already_revoked", "already revoked");
        assert_eq!(error["kind"], "error");
        assert_eq!(error["code"], "already_revoked");
    }
}