Skip to main content

acme_proxy/admin/
render.rs

1//! The JSON renderings, shared by both front ends.
2//!
3//! One shape per admin resource, and **the boundary this module exists to
4//! hold**: everything here is read by the CLI's `--json` branches *and* by
5//! `src/webadmin/`, so a change is a change to a wire format two callers parse.
6//! The human-readable renderings are the CLI's alone and live in
7//! [`crate::cli::render`], which is where colour is woven in — none of it can
8//! reach this file, so `--json` output stays byte-identical whatever the
9//! terminal is.
10//!
11//! Each surfaces the admin-only fields the ACME wire format deliberately does
12//! not carry (an order's revocation, an account's traceability columns), and
13//! each **omits** rather than nulls an absent one, so a template asking
14//! `{% if account.createdIp %}` is asking the question it looks like it is
15//! asking.
16
17use base64::prelude::*;
18use serde_json::Value;
19
20use crate::admin::ops::OrderDetail;
21use crate::sqlite::account::{Account, pubkey_fingerprint};
22use crate::sqlite::admin_session::AdminSession;
23use crate::sqlite::admin_user::AdminUser;
24use crate::sqlite::eab::Eab;
25use crate::sqlite::order::{Order, rfc3339};
26
27/// The public base URL of one endpoint, as the server itself derives it.
28///
29/// Admin output is rendered from `server.base_url`, which names the process,
30/// not an endpoint — every URL a client was ever handed carries the owning
31/// profile's prefix, so this puts it back.
32#[must_use]
33pub fn profile_base_url(base_url: &str, profile: &str) -> String {
34    format!(
35        "{}{}/{profile}",
36        base_url.trim_end_matches('/'),
37        crate::PROFILE_PREFIX
38    )
39}
40
41/// JSON representation for account admin display.
42///
43/// The traceability members are admin-only: [`Account::to_json`] is the RFC 8555
44/// object and deliberately carries none of them. Each is **omitted** rather than
45/// rendered as `null` when the column is unset, so a template asking `{% if
46/// account.createdIp %}` is asking the question it looks like it is asking.
47#[must_use]
48pub fn render_account_json(account: &Account, base_url: &str) -> Value {
49    let mut object = account
50        .to_json(&profile_base_url(base_url, &account.profile))
51        .as_object()
52        .cloned()
53        .unwrap_or_default();
54    object.insert("id".to_string(), Value::String(account.id.clone()));
55    object.insert(
56        "profile".to_string(),
57        Value::String(account.profile.clone()),
58    );
59    object.insert(
60        "createdAt".to_string(),
61        Value::String(rfc3339(account.created_at)),
62    );
63    object.insert(
64        "pubkeyFingerprint".to_string(),
65        Value::String(pubkey_fingerprint(&account.pubkey)),
66    );
67    if let Some(seen) = account.last_seen_at {
68        object.insert("lastSeenAt".to_string(), Value::String(rfc3339(seen)));
69    }
70    for (key, value) in [
71        ("createdIp", account.created_ip.as_ref()),
72        ("createdPtr", account.created_ptr.as_ref()),
73        ("lastSeenIp", account.last_seen_ip.as_ref()),
74        ("lastSeenPtr", account.last_seen_ptr.as_ref()),
75    ] {
76        if let Some(value) = value {
77            object.insert(key.to_string(), Value::String(value.clone()));
78        }
79    }
80    Value::Object(object)
81}
82
83/// JSON representation for order admin display.
84#[must_use]
85pub fn render_order_json(order: &Order, base_url: &str, authz_ids: &[String]) -> Value {
86    let mut object = order
87        .to_json(&profile_base_url(base_url, &order.profile), authz_ids)
88        .as_object()
89        .cloned()
90        .unwrap_or_default();
91    object.insert("id".to_string(), Value::String(order.id.clone()));
92    object.insert("profile".to_string(), Value::String(order.profile.clone()));
93    // Admin-only, like `id` and `profile`: the ACME order object deliberately
94    // never names its account, but an operator looking at an order almost
95    // always wants to get to the account behind it, and without this neither
96    // front end can offer that link.
97    object.insert(
98        "accountId".to_string(),
99        Value::String(order.account_id.clone()),
100    );
101    object.insert(
102        "createdAt".to_string(),
103        Value::String(rfc3339(order.created_at)),
104    );
105    if let Some(revoked_at) = order.revoked_at {
106        object.insert("revokedAt".to_string(), Value::String(rfc3339(revoked_at)));
107        if let Some(reason) = order.revocation_reason {
108            object.insert("revocationReason".to_string(), Value::from(reason));
109        }
110    }
111    Value::Object(object)
112}
113
114/// `order show --json` JSON output.
115#[must_use]
116pub fn render_order_detail_json(detail: &OrderDetail, base_url: &str) -> Value {
117    let authz_ids: Vec<String> = detail
118        .authorizations
119        .iter()
120        .map(|(a, _)| a.id.clone())
121        .collect();
122    let profile_base = profile_base_url(base_url, &detail.order.profile);
123    let authorizations: Vec<Value> = detail
124        .authorizations
125        .iter()
126        .map(|(a, c)| a.to_json(&profile_base, c))
127        .collect();
128    let mut order = render_order_json(&detail.order, base_url, &authz_ids);
129    // The issued chain itself, admin-only and **detail-only**.
130    //
131    // `certificate` beside it is the ACME *URL*, reachable only by signed
132    // POST-as-GET — a browser following it gets nothing, so on its own it is a
133    // dead string on the order card. The PEM is the thing an operator actually
134    // wants, and it is already in the row.
135    //
136    // Deliberately not in `render_order_json`, which also renders every row of
137    // every listing: a page of fifty orders would carry fifty chains for a
138    // field no list can show.
139    if let (Some(object), Some(pem)) = (order.as_object_mut(), detail.order.certificate.as_ref()) {
140        object.insert("certificatePem".to_string(), Value::String(pem.clone()));
141    }
142
143    let mut root = serde_json::Map::new();
144    root.insert("order".to_string(), order);
145    root.insert("authorizations".to_string(), Value::Array(authorizations));
146    Value::Object(root)
147}
148
149/// `eab list --json` / `eab show --json`.
150#[must_use]
151pub fn render_eab_json(eab: &Eab) -> Value {
152    eab.to_json()
153}
154
155/// `eab create` JSON output (includes secret).
156#[must_use]
157pub fn render_eab_created_json(eab: &Eab) -> Value {
158    let mut object = eab.to_json().as_object().cloned().unwrap_or_default();
159    object.insert(
160        "hmacKey".to_string(),
161        Value::String(BASE64_URL_SAFE_NO_PAD.encode(&eab.secret)),
162    );
163    Value::Object(object)
164}
165
166/// `admin user list --json` / `admin user show --json`.
167///
168/// A straight pass-through: unlike an account or an order, an operator has no
169/// ACME wire form to augment -- [`AdminUser::to_json`] is already the only
170/// representation, and it is the one that omits the password hash.
171#[must_use]
172pub fn render_admin_user_json(user: &AdminUser) -> Value {
173    user.to_json()
174}
175
176/// `admin session list --json`.
177#[must_use]
178pub fn render_admin_session_json(session: &AdminSession) -> Value {
179    session.to_json()
180}
181
182#[cfg(test)]
183mod tests {
184    use std::sync::Arc;
185
186    use super::*;
187    use crate::admin::ops::load_order_detail;
188    use crate::audit::ClientContext;
189    use crate::sqlite::authz::{Authorization, Challenge};
190    use crate::sqlite::db::Database;
191    use crate::sqlite::order::Identifier;
192    use crate::sqlite::status::OrderStatus;
193    use crate::testutil::{
194        account_id, account_seen_from, admin_session_fixture, admin_user_fixture, client_context,
195        order_fixture,
196    };
197
198    #[tokio::test]
199    async fn render_account_json_includes_id_and_base_fields() {
200        let db = Arc::new(Database::connect_in_memory().await.unwrap());
201        let account = account_seen_from(
202            &[1u8, 2, 3],
203            &client_context(Some("203.0.113.7"), Some("host.example.com")),
204            &db,
205        )
206        .await;
207
208        let json = render_account_json(&account, "http://localhost:3000");
209        assert_eq!(json["id"], account.id);
210        assert_eq!(json["status"], "valid");
211        assert!(json["orders"].as_str().unwrap().contains(&account.id));
212        assert!(json["pubkeyFingerprint"].is_string());
213        assert_eq!(json["createdIp"], "203.0.113.7");
214        assert_eq!(json["createdPtr"], "host.example.com");
215        assert_eq!(json["lastSeenIp"], "203.0.113.7");
216        assert_eq!(json["lastSeenPtr"], "host.example.com");
217        assert!(json["lastSeenAt"].as_str().unwrap().contains('T'));
218    }
219
220    /// Absent, not `null`: a template asking `{% if account.createdIp %}` must
221    /// be asking the question it looks like it is asking.
222    #[tokio::test]
223    async fn render_account_json_omits_the_traceability_members_it_has_no_value_for() {
224        let db = Arc::new(Database::connect_in_memory().await.unwrap());
225        let account = account_seen_from(&[1u8, 2, 3], &ClientContext::default(), &db).await;
226
227        let json = render_account_json(&account, "http://localhost:3000");
228        let object = json.as_object().unwrap();
229        for key in ["createdIp", "createdPtr", "lastSeenIp", "lastSeenPtr"] {
230            assert!(!object.contains_key(key), "{key} in {json}");
231        }
232    }
233
234    #[test]
235    fn render_order_json_includes_id_and_authorizations() {
236        let order = order_fixture("acct", OrderStatus::Pending);
237        let authz_ids = vec!["authz-1".to_string()];
238        let json = render_order_json(&order, "http://localhost:3000", &authz_ids);
239        assert_eq!(json["id"], order.id);
240        // Admin output is rendered against the *profile's* base URL, not the
241        // server's: that is the URL the client was handed.
242        assert_eq!(json["profile"], "default");
243        // Admin-only, and absent from the ACME order object: without it
244        // neither front end could link an order back to its account.
245        assert_eq!(json["accountId"], "acct");
246        assert_eq!(
247            json["authorizations"],
248            serde_json::json!(["http://localhost:3000/profile/default/authz/authz-1"])
249        );
250    }
251
252    #[tokio::test]
253    async fn render_order_detail_json_nests_authorizations_and_challenges() {
254        let db = Arc::new(Database::connect_in_memory().await.unwrap());
255        let acct = account_id(&db).await;
256        let order = Order::create(
257            "default",
258            &acct,
259            vec![Identifier::dns("example.com")],
260            crate::sqlite::nonce::now_secs() + 3600,
261            None,
262            None,
263            &db,
264        )
265        .await
266        .unwrap();
267        let authz = Authorization::create(
268            &order.id,
269            Identifier::dns("example.com"),
270            crate::sqlite::nonce::now_secs() + 3600,
271            &db,
272        )
273        .await
274        .unwrap();
275        Challenge::create(&authz.id, "http-01", &db).await.unwrap();
276
277        let detail = load_order_detail(&order.id, db).await.unwrap().unwrap();
278        let json = render_order_detail_json(&detail, "http://localhost:3000");
279        assert_eq!(json["order"]["id"], order.id);
280        assert_eq!(json["authorizations"].as_array().unwrap().len(), 1);
281        assert_eq!(
282            json["authorizations"][0]["challenges"]
283                .as_array()
284                .unwrap()
285                .len(),
286            1
287        );
288    }
289
290    #[tokio::test]
291    async fn render_eab_created_json_includes_the_hmac_key_and_line_json_does_not() {
292        let db = Arc::new(Database::connect_in_memory().await.unwrap());
293        let eab = Eab::create(None, None, &db).await.unwrap();
294
295        let created = render_eab_created_json(&eab);
296        assert!(created["hmacKey"].is_string());
297
298        let listed = render_eab_json(&eab);
299        assert!(listed.get("hmacKey").is_none());
300    }
301
302    #[test]
303    fn render_order_json_revoked_includes_reason_and_time() {
304        let mut order = order_fixture("acct", OrderStatus::Valid);
305        order.revoked_at = Some(1700000000);
306        order.revocation_reason = Some(1);
307        let json = render_order_json(&order, "http://localhost:3000", &[]);
308        assert_eq!(json["revokedAt"].as_str().unwrap().len(), 20);
309        assert_eq!(json["revocationReason"], 1);
310    }
311
312    #[test]
313    fn render_admin_user_json_omits_every_secret() {
314        let mut user = admin_user_fixture();
315        user.totp_secret = Some(vec![9, 9, 9]);
316        let json = render_admin_user_json(&user);
317        let rendered = json.to_string();
318        assert!(!rendered.contains("pbkdf2"));
319        assert!(!rendered.contains("totpSecret"));
320        assert_eq!(json["username"], "alice");
321        assert_eq!(json["totpEnabled"], true);
322    }
323
324    #[test]
325    fn render_admin_session_json_omits_the_hash_and_the_csrf_token() {
326        let json = render_admin_session_json(&admin_session_fixture());
327        let rendered = json.to_string();
328        assert!(!rendered.contains("0123456789abcdef0123456789abcdef"));
329        assert!(!rendered.contains("the-csrf-token"));
330        assert_eq!(json["id"], "01234567");
331        assert_eq!(json["state"], "active");
332    }
333}