acme-proxy-admin 0.6.0

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
//! `/ui/operators` — every operator this process has, and acting on one
//! *other* than the caller.
//!
//! [`crate::webadmin::handlers::operators`]'s page twin, the `handlers`/`pages`
//! split every other resource in this tree follows: both call the same
//! `crates/admin/src/admin/` operations, this one renders HTML. Managing *yourself* stays on
//! `/ui/account`, which is why `GET /ui/operators/{username}` redirects there
//! the moment `username` resolves to the caller rather than rendering a
//! half-disabled copy of this page's own template.

use axum::extract::{Path, Query, State};
use axum::response::{Html, IntoResponse, Response};
use serde::Deserialize;
use serde_json::{Map, Value};

use crate::admin;
use crate::admin::{mfa, users};
use crate::webadmin::AdminState;
use crate::webadmin::error::AdminError;
use crate::webadmin::handlers::mfa::verify_current_password;
use crate::webadmin::handlers::operators::{
    OperatorAction, apply_operator_action, find, refuse_self_target,
};
use crate::webadmin::handlers::paging::{Page, PageParams};
use crate::webadmin::pages::auth::{PageAdminRead, PageAdminWrite};
use crate::webadmin::pages::error::{PageError, redirect};
use crate::webadmin::pages::{chrome, flash, page_value, pager, respond, respond_fragment};
use crate::webadmin::session::AdminClientIp;
use acme_proxy_store::admin_session::AdminSession;
use acme_proxy_store::admin_user::AdminRole;
use acme_proxy_store::admin_user::AdminUser;

/// The `/ui` twin of [`crate::webadmin::handlers::mfa::StepUpRequest`] — the
/// password a form field collects, pulled in by `hx-include`, the
/// `account::StepUpForm` precedent.
#[derive(Debug, Default, Deserialize)]
pub struct StepUpForm {
    #[serde(default)]
    pub password: String,
}

/// `GET /ui/operators?limit=&offset=`
pub async fn list_operators(
    State(state): State<AdminState>,
    Query(params): Query<PageParams>,
    session: PageAdminRead,
) -> Result<Html<String>, PageError> {
    let page = params.resolve(&state.config);
    let (operators, total) = rows(page, &state).await?;

    let mut context = chrome(&session, "operators", "Operators");
    context.insert("page".to_string(), page_value(operators, total));
    context.insert(
        "pager".to_string(),
        pager(page, total, "/ui/operators", &[], "#operators-table"),
    );

    respond(
        &state,
        session.hx,
        "operators/list.html",
        "operators/_table.html",
        context,
    )
}

/// `GET /ui/operators/{username}` — redirects to `/ui/account` when `username`
/// is the caller.
pub async fn get_operator(
    State(state): State<AdminState>,
    Path(username): Path<String>,
    session: PageAdminRead,
) -> Result<Response, PageError> {
    let target = find(&username, &state).await?;
    if target.id == session.auth.user.id {
        return Ok(redirect("/ui/account", session.hx));
    }

    let mut context = chrome(&session, "operators", "Operator");
    for (key, value) in detail_context(&state, &target).await? {
        context.insert(key, value);
    }

    Ok(respond(
        &state,
        session.hx,
        "operators/detail.html",
        "operators/_card.html",
        context,
    )?
    .into_response())
}
/// `POST /ui/operators/{username}/disable`
pub async fn disable_operator(
    State(state): State<AdminState>,
    Path(username): Path<String>,
    AdminClientIp(client): AdminClientIp,
    session: PageAdminWrite,
    request_context: acme_proxy_core::audit::RequestContext,
    axum::Form(body): axum::Form<StepUpForm>,
) -> Result<Response, PageError> {
    act(
        &state,
        &session,
        &username,
        &body.password,
        client,
        &request_context,
        OperatorAction::SetStatus { active: false },
        flash("ok", "Operator disabled. Their sessions were revoked."),
    )
    .await
}

/// `POST /ui/operators/{username}/enable`
pub async fn enable_operator(
    State(state): State<AdminState>,
    Path(username): Path<String>,
    AdminClientIp(client): AdminClientIp,
    session: PageAdminWrite,
    request_context: acme_proxy_core::audit::RequestContext,
    axum::Form(body): axum::Form<StepUpForm>,
) -> Result<Response, PageError> {
    act(
        &state,
        &session,
        &username,
        &body.password,
        client,
        &request_context,
        OperatorAction::SetStatus { active: true },
        flash("ok", "Operator enabled."),
    )
    .await
}

/// `POST /ui/operators/{username}/totp/reset`
pub async fn reset_operator_totp(
    State(state): State<AdminState>,
    Path(username): Path<String>,
    AdminClientIp(client): AdminClientIp,
    session: PageAdminWrite,
    request_context: acme_proxy_core::audit::RequestContext,
    axum::Form(body): axum::Form<StepUpForm>,
) -> Result<Response, PageError> {
    act(
        &state,
        &session,
        &username,
        &body.password,
        client,
        &request_context,
        OperatorAction::ResetTotp,
        flash(
            "warn",
            "Their second factor and recovery codes were removed. They can \
             sign in with a password alone until they enrol again.",
        ),
    )
    .await
}

/// `POST /ui/operators/{username}/sessions/{id}/revoke`
pub async fn revoke_operator_session(
    State(state): State<AdminState>,
    Path((username, id)): Path<(String, String)>,
    AdminClientIp(client): AdminClientIp,
    session: PageAdminWrite,
    request_context: acme_proxy_core::audit::RequestContext,
    axum::Form(body): axum::Form<StepUpForm>,
) -> Result<Response, PageError> {
    act(
        &state,
        &session,
        &username,
        &body.password,
        client,
        &request_context,
        OperatorAction::RevokeSession { fingerprint: &id },
        flash("ok", "Session revoked."),
    )
    .await
}

/// The contact form on the operator card: the address, plus the step-up
/// password `hx-include` pulls in. A blank address clears it.
#[derive(Debug, Default, Deserialize)]
pub struct OperatorContactForm {
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub contact: String,
}

/// The role form on the operator card.
#[derive(Debug, Default, Deserialize)]
pub struct OperatorRoleForm {
    #[serde(default)]
    pub password: String,
    #[serde(default)]
    pub role: String,
}

/// `POST /ui/operators/{username}/contact`
pub async fn set_operator_contact(
    State(state): State<AdminState>,
    Path(username): Path<String>,
    AdminClientIp(client): AdminClientIp,
    session: PageAdminWrite,
    request_context: acme_proxy_core::audit::RequestContext,
    axum::Form(form): axum::Form<OperatorContactForm>,
) -> Result<Response, PageError> {
    let banner = if form.contact.trim().is_empty() {
        flash(
            "warn",
            "Their notification address was cleared: security notifications cannot reach them.",
        )
    } else {
        flash(
            "ok",
            "Their notification address was changed. The previous one was told.",
        )
    };
    act(
        &state,
        &session,
        &username,
        &form.password,
        client,
        &request_context,
        OperatorAction::SetContact {
            contact: Some(form.contact.as_str()),
        },
        banner,
    )
    .await
}

/// `POST /ui/operators/{username}/role`
pub async fn set_operator_role(
    State(state): State<AdminState>,
    Path(username): Path<String>,
    AdminClientIp(client): AdminClientIp,
    session: PageAdminWrite,
    request_context: acme_proxy_core::audit::RequestContext,
    axum::Form(form): axum::Form<OperatorRoleForm>,
) -> Result<Response, PageError> {
    let role = match form.role.parse::<AdminRole>() {
        Ok(role) => role,
        // A value outside the select is a banner beside it, like every other
        // refusal on this card -- once the target and the self-target rule
        // have had their say, so a typo is not how an operator learns who
        // exists.
        Err(message) => {
            let target = find(&username, &state).await?;
            refuse_self_target(&session.auth.user, &target)?;
            let context = detail_context(&state, &target).await?;
            return super::refuse_with_card(
                &state,
                "operators/_card.html",
                context,
                &AdminError::bad_request(message),
            );
        }
    };
    act(
        &state,
        &session,
        &username,
        &form.password,
        client,
        &request_context,
        OperatorAction::SetRole { role },
        flash(
            "ok",
            format!(
                "Role changed to {}. Their sessions were revoked.",
                role.as_str()
            ),
        ),
    )
    .await
}

/// The `/ui` spelling of the shared sequence — the twin of
/// [`crate::webadmin::handlers::operators`]'s own `act`.
///
/// Identical up to two things, which is the whole of what separates the two
/// front ends here: the password refusal is rendered as the operator card's own
/// banner rather than returned as an error document, and success re-renders
/// that card instead of answering `204`.
#[allow(clippy::too_many_arguments)]
async fn act(
    state: &AdminState,
    session: &PageAdminWrite,
    username: &str,
    password: &str,
    client: Option<std::net::IpAddr>,
    request_context: &acme_proxy_core::audit::RequestContext,
    action: OperatorAction<'_>,
    banner: Value,
) -> Result<Response, PageError> {
    let mut target = find(username, state).await?;
    refuse_self_target(&session.auth.user, &target)?;
    if let Some(refusal) =
        refuse_without_password(state, session, &target, password, client).await?
    {
        return Ok(refusal);
    }

    if let Err(error) = apply_operator_action(
        state,
        &session.auth.user,
        &mut target,
        action,
        client,
        request_context,
        "ui",
    )
    .await
    {
        // "The row's state is a banner, the server's problem is a page": a
        // refused value (an address that is not a mailbox) belongs beside the
        // control it came from. A `404` still replaces the page, since the
        // operator or session it named is gone.
        if error.status.is_client_error() && error.status != axum::http::StatusCode::NOT_FOUND {
            let context = detail_context(state, &target).await?;
            return super::refuse_with_card(state, "operators/_card.html", context, &error);
        }
        return Err(error.into());
    }

    respond_card(state, &target, banner).await
}

/// [`verify_current_password`] with the refusal rendered as the operator card's
/// own banner — the `account::refuse_without_password` shape: the session is
/// live and the page is the right page, only this one action was refused.
///
/// `verify_current_password`, not `check_step_up`: see
/// [`crate::webadmin::handlers::operators`]'s module doc for why this surface
/// asks even of a caller who has enrolled no second factor.
async fn refuse_without_password(
    state: &AdminState,
    session: &PageAdminWrite,
    target: &AdminUser,
    password: &str,
    client: Option<std::net::IpAddr>,
) -> Result<Option<Response>, PageError> {
    let Err(error) =
        verify_current_password(&session.auth.user, password, client, &state.logins).await
    else {
        return Ok(None);
    };
    let context = detail_context(state, target).await?;
    Ok(Some(super::refuse_with_card(
        state,
        "operators/_card.html",
        context,
        &error,
    )?))
}

/// Re-renders the operator card after a successful mutation.
///
/// Renders from the `target` [`apply_operator_action`] updated in place rather
/// than re-reading the row: the two would agree, and the extra read is a second
/// answer waiting to disagree. The sessions table inside it *is* re-read, since
/// a disable or a revoke is exactly what changed it.
async fn respond_card(
    state: &AdminState,
    target: &AdminUser,
    banner: Value,
) -> Result<Response, PageError> {
    let mut context = detail_context(state, target).await?;
    context.insert("flash".to_string(), banner);
    Ok(respond_fragment(state, "operators/_card.html", context)?.into_response())
}

async fn rows(page: Page, state: &AdminState) -> Result<(Vec<Value>, i64), PageError> {
    let (operators, total) =
        users::list_users(page.limit, page.offset, state.database.clone()).await?;
    Ok((
        operators
            .iter()
            .map(admin::render_admin_user_json)
            .collect(),
        total,
    ))
}

/// Everything `operators/_card.html` reads, minus `csrf_token` and `flash` --
/// both are per-call (the token because a fragment rendered standalone cannot
/// inherit `<body>`'s `hx-headers`, the banner because it differs by action).
async fn detail_context(
    state: &AdminState,
    target: &AdminUser,
) -> Result<Map<String, Value>, PageError> {
    let remaining = mfa::recovery_codes_remaining(target.id, state.database.clone()).await?;
    let mut context = Map::new();
    context.insert(
        "operator".to_string(),
        admin::render_admin_user_detail_json(target, remaining),
    );
    // From the enum `AdminRole::from_str` parses against, so the role select
    // cannot offer a tier the handler would refuse, or miss one it accepts.
    context.insert(
        "roles".to_string(),
        Value::Array(
            AdminRole::ALL
                .iter()
                .map(|role| Value::from(role.as_str()))
                .collect(),
        ),
    );
    context.insert(
        "sessions".to_string(),
        Value::Array(operator_sessions(state, target.id).await?),
    );
    context.insert(
        "sessions_revoke_prefix".to_string(),
        Value::String(format!("/ui/operators/{}/sessions", target.username)),
    );
    context.insert(
        "sessions_target".to_string(),
        Value::String("#operator-detail".to_string()),
    );
    // Present, unlike the account page's own sessions card: every mutation on
    // this surface -- including revoking one of *another* operator's sessions
    // -- re-proves the caller's own password. `#operator-step-up-password` is
    // the field `operators/_card.html` renders once, shared by every button.
    context.insert(
        "sessions_step_up".to_string(),
        Value::String("#operator-step-up-password".to_string()),
    );
    Ok(context)
}

/// One operator's live sessions, newest first, unmarked -- see
/// [`crate::webadmin::handlers::operators::list_operator_sessions`] for why
/// there is no `current` member here.
async fn operator_sessions(
    state: &AdminState,
    user_id: uuid::Uuid,
) -> Result<Vec<Value>, PageError> {
    let page = PageParams::default().resolve(&state.config);
    let (sessions, _total) =
        AdminSession::search(Some(user_id), page.limit, page.offset, &state.database).await?;
    Ok(sessions
        .iter()
        .map(admin::render_admin_session_json)
        .collect())
}