Skip to main content

acme_proxy/webadmin/handlers/
eab.rs

1//! `/api/eab` — External Account Binding credentials.
2
3use axum::Json;
4use axum::extract::{Path, Query, State};
5use axum::http::StatusCode;
6use axum::response::{IntoResponse, Response};
7use serde::Deserialize;
8use serde_json::Value;
9
10use crate::admin;
11use crate::sqlite::eab::Eab;
12use crate::webadmin::AdminState;
13use crate::webadmin::error::AdminError;
14use crate::webadmin::handlers::paging::{PageParams, page_envelope};
15use crate::webadmin::session::{Authenticated, AuthenticatedWrite};
16
17#[derive(Debug, Deserialize, Default)]
18pub struct CreateEab {
19    pub label: Option<String>,
20    /// Bind the credential to one endpoint. Absent means every profile.
21    pub profile: Option<String>,
22}
23
24/// `GET /api/eab?limit=&offset=` — one page of credentials. Never the secret.
25///
26/// Takes `Query<PageParams>` directly rather than declaring the window inline:
27/// the `#[serde(flatten)]` trap documented on `AccountListParams` needs a
28/// filter to flatten *around*, and this listing has none. `oldest first` here,
29/// where the other lists are newest first — see [`Eab::search`].
30pub async fn list_eab(
31    State(state): State<AdminState>,
32    Query(params): Query<PageParams>,
33    _auth: Authenticated,
34) -> Result<Json<Value>, AdminError> {
35    let page = params.resolve(&state.config);
36    let (keys, total) = Eab::search(page.limit, page.offset, &state.database).await?;
37    let items: Vec<Value> = keys.iter().map(admin::render_eab_json).collect();
38    Ok(Json(page_envelope(items, total, page)))
39}
40
41/// `GET /api/eab/{kid}` — one credential. Never the secret.
42pub async fn get_eab(
43    State(state): State<AdminState>,
44    Path(kid): Path<String>,
45    _auth: Authenticated,
46) -> Result<Json<Value>, AdminError> {
47    let eab = Eab::find_any_by_kid(&kid, &state.database)
48        .await?
49        .ok_or_else(|| not_found(&kid))?;
50    Ok(Json(admin::render_eab_json(&eab)))
51}
52
53/// `POST /api/eab` — mint a credential.
54///
55/// **The only response in this API that carries a secret.** It is shown once
56/// and is not recoverable afterwards, exactly as `acme-proxy eab create`
57/// behaves — a lost credential is replaced, never read back. The log records
58/// the kid and never the secret.
59pub async fn create_eab(
60    State(state): State<AdminState>,
61    AuthenticatedWrite(auth): AuthenticatedWrite,
62    body: Option<Json<CreateEab>>,
63) -> Result<Response, AdminError> {
64    let Json(body) = body.unwrap_or_default();
65
66    require_mounted_profile(&state, body.profile.as_deref(), "omit `profile`")?;
67
68    let eab = Eab::create(body.label, body.profile, &state.database).await?;
69    tracing::info!(event = "admin_eab_created",
70                   outcome = "success",
71                   surface = "api",
72                   kid = %eab.kid,
73                   profile = ?eab.profile,
74                   username = %auth.user.username);
75
76    Ok((
77        StatusCode::CREATED,
78        Json(admin::render_eab_created_json(&eab)),
79    )
80        .into_response())
81}
82
83/// `POST /api/eab/{kid}/revoke`
84///
85/// Spelled `revoke` rather than `DELETE`, because the row survives: the model
86/// moves it to `revoked` and the CLI calls it the same thing. Accounts already
87/// bound under it are deliberately unaffected.
88pub async fn revoke_eab(
89    State(state): State<AdminState>,
90    Path(kid): Path<String>,
91    AuthenticatedWrite(auth): AuthenticatedWrite,
92) -> Result<StatusCode, AdminError> {
93    if !Eab::revoke(&kid, &state.database).await? {
94        return Err(not_found(&kid));
95    }
96    tracing::info!(event = "admin_eab_revoked", outcome = "success", surface = "api", kid = %kid, username = %auth.user.username);
97    Ok(StatusCode::NO_CONTENT)
98}
99
100/// Refuses a credential scoped to an endpoint this process does not serve.
101///
102/// Shared by both front ends, because the *condition* is one rule and two
103/// copies of it drift: such a credential would be accepted and then never be
104/// usable, which is worth catching while the operator is still looking at what
105/// they typed. `hint` is the one part that is legitimately per-front-end — a
106/// JSON caller omits a field, someone at a form leaves an input blank.
107pub(crate) fn require_mounted_profile(
108    state: &AdminState,
109    profile: Option<&str>,
110    hint: &str,
111) -> Result<(), AdminError> {
112    if let Some(name) = profile
113        && !state.profiles.contains_key(name)
114    {
115        return Err(AdminError::bad_request(format!(
116            "no profile named `{name}` is mounted; {hint} for a credential valid at \
117             every endpoint"
118        )));
119    }
120    Ok(())
121}
122
123fn not_found(kid: &str) -> AdminError {
124    AdminError::not_found(format!("no such EAB credential: {kid}"))
125}