acme-proxy 0.6.1

An ACME (RFC 8555) server that issues from a local CA, relays to an upstream CA, or delegates to a script
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
//! `acme-proxy audit` — read the audit trail, and prune it.
//!
//! An unknown `--event` or `--outcome` is refused by name rather than passed
//! to SQL, where it would answer "no rows". `cleanup` is the only command in the
//! binary that destroys audit history, so it prompts with the row count and
//! records its own row.

use std::io::BufRead;
use std::sync::Arc;

use clap::Subcommand;

use crate::cli::CliError;
use crate::cli::render;
use crate::cli::window::{DEFAULT_LIMIT, Window};
use acme_proxy_admin::admin;
use acme_proxy_core::audit::ALL_AUDIT_EVENTS;
use acme_proxy_core::palette::Palette;
use acme_proxy_store::audit::AuditQuery;
use acme_proxy_store::db::Database;

#[derive(Subcommand)]
pub enum AuditCommand {
    /// List audit rows, newest first.
    List {
        /// Only rows about this ACME endpoint.
        #[arg(long)]
        profile: Option<String>,
        /// Only rows about this account.
        #[arg(long = "account-id")]
        account_id: Option<String>,
        /// Only rows about this order.
        #[arg(long = "order-id")]
        order_id: Option<String>,
        /// Only rows about the certificate with this serial, in hex. Case and
        /// `:` or `-` separators do not matter.
        #[arg(long = "cert-serial")]
        cert_serial: Option<String>,
        /// An audit event name — `certificate_issued`, `account_deleted`,
        /// `operator_disabled`, … An unknown value is refused by name and the
        /// full list printed.
        #[arg(long)]
        event: Option<String>,
        /// `success` or `failure`.
        #[arg(long)]
        outcome: Option<String>,
        /// Only rows from the last N days.
        #[arg(long = "since-days")]
        since_days: Option<u64>,
        /// Rows per page. A value below 1 is read as 1.
        #[arg(long, default_value_t = DEFAULT_LIMIT)]
        limit: i64,
        /// Rows to skip before the page starts.
        #[arg(long, default_value_t = 0)]
        offset: i64,
        /// Print the page as JSON: `{items, total, limit, offset}`.
        #[arg(long)]
        json: bool,
    },
    /// Show one audit row in full.
    Show {
        /// The row id, as `audit list` prints it.
        id: i64,
        /// Print it as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Delete audit rows older than a number of days.
    ///
    /// The only command in this binary that destroys audit history, which is
    /// why it prompts with the number of rows it is about to remove.
    Cleanup {
        /// Delete rows older than this many days.
        #[arg(long = "older-than", value_name = "DAYS")]
        older_than: u64,
    },
}

/// Rejects an `--event`/`--outcome` this build does not know.
///
/// Refused here rather than passed through to SQL, where an unknown value is
/// not an error but an empty result — and "no rows" for a typo'd filter is the
/// single most misleading answer an audit tool can give.
fn check_filters(event: Option<&str>, outcome: Option<&str>) -> Result<(), CliError> {
    if let Some(event) = event
        && acme_proxy_core::audit::AuditEvent::parse(event).is_none()
    {
        let known: Vec<&str> = ALL_AUDIT_EVENTS.iter().map(|e| e.as_str()).collect();
        return Err(CliError::bad_request(format!(
            "unknown --event `{event}`; known events are {}",
            known.join(", ")
        )));
    }
    if let Some(outcome) = outcome
        && !matches!(outcome, "success" | "failure")
    {
        return Err(CliError::bad_request(format!(
            "unknown --outcome `{outcome}`; expected `success` or `failure`"
        )));
    }
    Ok(())
}

pub async fn run_audit_command(
    command: AuditCommand,
    yes: bool,
    palette: Palette,
    reader: &mut impl BufRead,
    database: Arc<Database>,
) -> Result<(), CliError> {
    match command {
        AuditCommand::List {
            profile,
            account_id,
            order_id,
            cert_serial,
            event,
            outcome,
            since_days,
            limit,
            offset,
            json,
        } => {
            check_filters(event.as_deref(), outcome.as_deref())?;
            let window = Window::resolve(limit, offset);
            let query = AuditQuery {
                profile,
                account_id,
                order_id,
                // See `order list --cert-serial`: the same fold, for the same
                // reason, on the same column.
                cert_serial: cert_serial
                    .as_deref()
                    .map(acme_proxy_core::cert::normalize_serial),
                event,
                outcome,
                since: since_days.map(acme_proxy_store::audit::audit_cutoff),
                limit: window.limit,
                offset: window.offset,
            };
            let (entries, total) = admin::list_audit(&query, database).await?;
            render::print_page(
                &entries,
                total,
                window,
                json,
                acme_proxy_store::audit::AuditEntry::to_json,
                |entry| render::render_audit_line(entry, palette),
            );
        }
        AuditCommand::Show { id, json } => {
            let Some(entry) = admin::find_audit(id, database).await? else {
                return Err(CliError::bad_request(format!("audit row {id} not found")));
            };
            if json {
                println!("{}", entry.to_json());
            } else {
                print!("{}", render::render_audit_detail_text(&entry, palette));
            }
        }
        AuditCommand::Cleanup { older_than } => {
            match admin::confirm_cleanup_audit(older_than, yes, reader, database.clone()).await? {
                None => println!("Cancelled."),
                Some(removed) => {
                    // Written after the sweep, so the prune records its own
                    // action rather than being caught by it. Only when it
                    // actually removed something — a no-op prune changed
                    // nothing, the `RevokeOutcome::AlreadyRevoked` rule.
                    if removed > 0 {
                        acme_proxy_jobs::auditor::admin::record_cli_action(
                            &database,
                            |actor, client| {
                                acme_proxy_jobs::auditor::admin::audit_pruned(
                                    actor, client, removed, older_than,
                                )
                            },
                        )
                        .await;
                    }
                    println!("Removed {removed} audit row(s).");
                }
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::CliErrorKind;
    use acme_proxy_core::audit::{Actor, AuditRecord};
    use acme_proxy_store::audit::AuditEntry;
    use acme_proxy_store::db::Database;

    async fn db_with_rows() -> Arc<Database> {
        let db = Arc::new(Database::connect_in_memory().await.unwrap());
        for event in ALL_AUDIT_EVENTS {
            AuditEntry::insert(
                AuditRecord::new(*event, "default", Actor::acme("acct-1"))
                    .with_account("acct-1")
                    .with_serial("0a0b"),
                &db,
            )
            .await
            .unwrap();
        }
        db
    }

    /// A typo'd filter must be an error, not an empty result. "No rows" for a
    /// misspelt `--event` is the most misleading answer an audit tool can give,
    /// because it looks exactly like "nothing happened".
    #[test]
    fn an_unknown_event_or_outcome_is_refused_by_name() {
        assert!(check_filters(None, None).is_ok());
        assert!(check_filters(Some("certificate_issued"), Some("success")).is_ok());

        let error = check_filters(Some("certificate_renewed"), None).unwrap_err();
        assert!(error.message.contains("certificate_renewed"), "{error}");
        // The message lists what *is* accepted, so the operator can fix it
        // without reaching for the docs.
        assert!(error.message.contains("certificate_issued"), "{error}");
        assert!(
            error.message.contains("certificate_revoke_failed"),
            "{error}"
        );

        let error = check_filters(None, Some("maybe")).unwrap_err();
        assert!(error.message.contains("maybe"), "{error}");
        assert!(error.message.contains("success"), "{error}");
        assert_eq!(error.kind(), CliErrorKind::BadRequest);
    }

    /// `AuditCommand::List` is an enum variant, so there is no functional
    /// record update to lean on — each shape is spelled out.
    fn list(json: bool) -> AuditCommand {
        AuditCommand::List {
            profile: None,
            account_id: None,
            order_id: None,
            cert_serial: None,
            event: None,
            outcome: None,
            since_days: None,
            limit: DEFAULT_LIMIT,
            offset: 0,
            json,
        }
    }

    fn list_window(limit: i64, offset: i64) -> AuditCommand {
        AuditCommand::List {
            profile: None,
            account_id: None,
            order_id: None,
            cert_serial: None,
            event: None,
            outcome: None,
            since_days: None,
            limit,
            offset,
            json: false,
        }
    }

    fn list_event(event: &str) -> AuditCommand {
        AuditCommand::List {
            profile: None,
            account_id: None,
            order_id: None,
            cert_serial: None,
            event: Some(event.to_string()),
            outcome: None,
            since_days: None,
            limit: DEFAULT_LIMIT,
            offset: 0,
            json: false,
        }
    }

    /// Every filter set at once, so none of them is a predicate that fails to
    /// build once combined.
    fn list_every_filter() -> AuditCommand {
        AuditCommand::List {
            profile: Some("default".to_string()),
            account_id: Some("acct-1".to_string()),
            order_id: Some("order-1".to_string()),
            cert_serial: Some("0a0b".to_string()),
            event: Some("certificate_issued".to_string()),
            outcome: Some("success".to_string()),
            since_days: Some(7),
            limit: DEFAULT_LIMIT,
            offset: 0,
            json: false,
        }
    }

    /// Both output shapes of `list`, plus the clamps: a `--limit 0` or a
    /// negative `--offset` is nonsense the command corrects rather than a SQL
    /// error the operator has to decode.
    #[tokio::test]
    async fn list_runs_in_both_shapes_and_clamps_a_nonsense_window() {
        let db = db_with_rows().await;
        let mut reader: &[u8] = &[];

        run_audit_command(list(false), true, Palette::plain(), &mut reader, db.clone())
            .await
            .unwrap();
        run_audit_command(list(true), true, Palette::plain(), &mut reader, db.clone())
            .await
            .unwrap();
        run_audit_command(
            list_window(0, -5),
            true,
            Palette::plain(),
            &mut reader,
            db.clone(),
        )
        .await
        .unwrap();
        run_audit_command(list_every_filter(), true, Palette::plain(), &mut reader, db)
            .await
            .unwrap();
    }

    /// The filter check runs before the query, so a bad `--event` fails without
    /// touching the database.
    #[tokio::test]
    async fn list_refuses_an_unknown_event_before_querying() {
        let db = Arc::new(Database::connect_in_memory().await.unwrap());
        let mut reader: &[u8] = &[];
        let error = run_audit_command(list_event("nope"), true, Palette::plain(), &mut reader, db)
            .await
            .unwrap_err();
        assert!(error.message.contains("unknown --event"), "{error}");
        assert_eq!(error.kind(), CliErrorKind::BadRequest);
    }

    #[tokio::test]
    async fn show_renders_both_shapes_and_names_an_unknown_id() {
        let db = db_with_rows().await;
        let mut reader: &[u8] = &[];

        for json in [false, true] {
            run_audit_command(
                AuditCommand::Show { id: 1, json },
                true,
                Palette::plain(),
                &mut reader,
                db.clone(),
            )
            .await
            .unwrap();
        }

        let error = run_audit_command(
            AuditCommand::Show {
                id: 9_999,
                json: false,
            },
            true,
            Palette::plain(),
            &mut reader,
            db,
        )
        .await
        .unwrap_err();
        assert!(error.message.contains("9999"), "{error}");
        assert_eq!(error.kind(), CliErrorKind::BadRequest);
    }

    /// Declining leaves the trail alone; accepting prunes by age.
    #[tokio::test]
    async fn cleanup_honours_the_prompt() {
        let db = db_with_rows().await;

        let mut declined: &[u8] = b"n\n";
        run_audit_command(
            AuditCommand::Cleanup { older_than: 0 },
            false,
            Palette::plain(),
            &mut declined,
            db.clone(),
        )
        .await
        .unwrap();
        assert_eq!(
            AuditEntry::count_older_than(i64::MAX, &db).await.unwrap(),
            ALL_AUDIT_EVENTS.len() as i64
        );

        // Nothing is a year old, so an accepted sweep still removes nothing —
        // the cutoff, not the confirmation, is what bounds it.
        let mut reader: &[u8] = &[];
        run_audit_command(
            AuditCommand::Cleanup { older_than: 365 },
            true,
            Palette::plain(),
            &mut reader,
            db.clone(),
        )
        .await
        .unwrap();
        assert_eq!(
            AuditEntry::count_older_than(i64::MAX, &db).await.unwrap(),
            ALL_AUDIT_EVENTS.len() as i64
        );
    }
}