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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! `acme-proxy account` — list, show, update the contacts of, deactivate and
//! delete ACME accounts.
//!
//! Each write goes through `admin::ops`, the same operation the web admin runs,
//! and records an audit row. `delete` is refused while any of the account's
//! orders holds a live certificate, since the order row is the certificate's
//! only record.

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_admin::admin::DeleteOutcome;
use acme_proxy_core::config::Config;
use acme_proxy_core::palette::Palette;
use acme_proxy_jobs::auditor::admin as audit_admin;
use acme_proxy_store::account::Account;
use acme_proxy_store::db::Database;

#[derive(Subcommand)]
pub enum AccountCommand {
    /// List accounts, newest first, of every profile unless one is named.
    List {
        /// Restrict the listing to one ACME endpoint.
        #[arg(long)]
        profile: Option<String>,
        /// Restrict the listing to the accounts one EAB credential bound.
        #[arg(long)]
        eab_kid: Option<String>,
        /// 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 account.
    Show {
        /// The account id.
        id: String,
        /// Print it as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Replace an account's contact list.
    UpdateContact {
        /// The account id.
        id: String,
        /// A contact URL, `mailto:` for an address. Repeat it for several;
        /// omit it to clear the list.
        #[arg(long = "contact")]
        contact: Vec<String>,
    },
    /// Deactivate an account (RFC 8555 §7.3.6). There is no way back.
    Deactivate {
        /// The account id.
        id: String,
    },
    /// Hard-delete the account and everything under it.
    Delete {
        /// The account id.
        id: String,
    },
}

pub async fn run_account_command(
    command: AccountCommand,
    yes: bool,
    palette: Palette,
    reader: &mut impl BufRead,
    config: &Config,
    database: Arc<Database>,
) -> Result<(), CliError> {
    match command {
        AccountCommand::List {
            profile,
            eab_kid,
            limit,
            offset,
            json,
        } => {
            let window = Window::resolve(limit, offset);
            let (accounts, total) = Account::search(
                profile.as_deref(),
                eab_kid.as_deref(),
                window.limit,
                window.offset,
                &database,
            )
            .await?;
            render::print_page(
                &accounts,
                total,
                window,
                json,
                |a| admin::render_account_json(a, &config.server.base_url),
                |a| render::render_account_line(a, palette),
            );
        }
        AccountCommand::Show { id, json } => match Account::find_any_by_id(&id, &database).await? {
            None => return Err(not_found(&id)),
            Some(account) if json => {
                println!(
                    "{}",
                    admin::render_account_json(&account, &config.server.base_url)
                );
            }
            Some(account) => print!("{}", render::render_account_detail_text(&account, palette)),
        },
        AccountCommand::UpdateContact { id, contact } => {
            match admin::update_account_contact(&id, contact, database.clone())
                .await
                .map_err(|error| match error {
                    admin::ContactError::Invalid(detail) => CliError::bad_request(detail),
                    admin::ContactError::Database(error) => CliError::from(error),
                })? {
                None => return Err(not_found(&id)),
                Some(account) => {
                    audit_admin::record_cli_action(&database, |actor, client| {
                        audit_admin::account_contact_updated(
                            actor,
                            client,
                            &account,
                            &account.contact,
                        )
                    })
                    .await;
                    println!("{}", render::render_account_line(&account, palette));
                }
            }
        }
        AccountCommand::Deactivate { id } => {
            // Queued, not sent: the running server's worker delivers it. A
            // configuration that mounts no profile has nothing to notify
            // through, which is not a reason to refuse the deactivation.
            let notifiers = super::offline_notifiers(config, database.clone()).unwrap_or_default();
            match admin::deactivate_account(
                &id,
                database.clone(),
                |profile| notifiers.get(profile).cloned(),
                None,
            )
            .await?
            {
                None => return Err(not_found(&id)),
                Some(account) => {
                    audit_admin::record_cli_action(&database, |actor, client| {
                        audit_admin::account_deactivated(actor, client, &account)
                    })
                    .await;
                    println!("{}", render::render_account_line(&account, palette));
                }
            }
        }
        AccountCommand::Delete { id } => {
            // Read the account before the delete: the audit row names its
            // profile, and the row is gone by the time the confirmation
            // returns. The *count* comes back with the outcome for the same
            // reason and a sharper one — counting afterwards counts the orders
            // the `ON DELETE CASCADE` has already removed, which is zero every
            // time.
            let doomed = Account::find_any_by_id(&id, &database).await?;
            match admin::confirm_delete_account(&id, yes, reader, database.clone()).await? {
                DeleteOutcome::NotFound => return Err(not_found(&id)),
                DeleteOutcome::LiveCertificates(live) => {
                    return Err(CliError::bad_request(admin::live_certificates_refusal(
                        &format!("account {id}"),
                        live,
                    )));
                }
                DeleteOutcome::Cancelled => println!("Cancelled."),
                DeleteOutcome::Deleted(deleted) => {
                    if let Some(account) = doomed {
                        audit_admin::record_cli_action(&database, |actor, client| {
                            audit_admin::account_deleted(actor, client, &account, deleted.cascaded)
                        })
                        .await;
                    }
                    println!(
                        "Deleted account {id} ({} order(s) cascaded).",
                        deleted.cascaded
                    );
                }
            }
        }
    }
    Ok(())
}

fn not_found(id: &str) -> CliError {
    CliError::bad_request(acme_proxy_admin::admin::subject::Subject::Account.missing(id))
}

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

    /// Every arm taking an id reports the same thing for one that does not
    /// exist — and reports it as a value, so the caller decides the exit code.
    #[tokio::test]
    async fn every_arm_refuses_an_unknown_account() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        let expected = CliError::bad_request("no such account: acct-nope".to_string());

        let commands = vec![
            AccountCommand::Show {
                id: "acct-nope".to_string(),
                json: false,
            },
            AccountCommand::UpdateContact {
                id: "acct-nope".to_string(),
                contact: vec!["mailto:someone@example.com".to_string()],
            },
            AccountCommand::Deactivate {
                id: "acct-nope".to_string(),
            },
            AccountCommand::Delete {
                id: "acct-nope".to_string(),
            },
        ];
        for command in commands {
            let mut reader: &[u8] = &[];
            let error = run_account_command(
                command,
                true,
                Palette::plain(),
                &mut reader,
                &config,
                database.clone(),
            )
            .await
            .expect_err("an unknown account must fail");
            assert_eq!(error, expected);
        }
    }

    /// A contact `newAccount` would refuse is refused here too, as the
    /// operator's error, and the account keeps the contact it had.
    #[tokio::test]
    async fn update_contact_refuses_what_new_account_refuses() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        let (account, _) = Account::find_or_create(
            "default",
            &[2, 7, 1],
            vec!["mailto:ops@example.com".to_string()],
            &ClientContext::default(),
            &database,
        )
        .await
        .unwrap();

        let mut reader: &[u8] = &[];
        let error = run_account_command(
            AccountCommand::UpdateContact {
                id: account.id.to_string(),
                contact: vec!["tel:+15555550100".to_string()],
            },
            true,
            Palette::plain(),
            &mut reader,
            &config,
            database.clone(),
        )
        .await
        .expect_err("an unsupported scheme must be refused");
        assert_eq!(error.kind(), crate::cli::CliErrorKind::BadRequest);

        let reloaded = Account::find_any_by_id(&account.id.to_string(), &database)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(reloaded.contact, vec!["mailto:ops@example.com".to_string()]);
    }

    /// A successful mutation leaves one `cli`-attributed audit row carrying the
    /// account's own id and profile; a declined delete leaves none.
    #[tokio::test]
    async fn a_mutation_writes_an_audit_row_and_a_decline_does_not() {
        use acme_proxy_store::audit::AuditEntry;
        use acme_proxy_store::audit::AuditQuery;

        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        let (account, _) = Account::find_or_create(
            "default",
            &[3, 1, 4],
            vec![],
            &ClientContext::default(),
            &database,
        )
        .await
        .unwrap();

        let mut reader: &[u8] = &[];
        run_account_command(
            AccountCommand::Deactivate {
                id: account.id.to_string(),
            },
            true,
            Palette::plain(),
            &mut reader,
            &config,
            database.clone(),
        )
        .await
        .unwrap();

        let mut declined: &[u8] = b"n\n";
        run_account_command(
            AccountCommand::Delete {
                id: account.id.to_string(),
            },
            false,
            Palette::plain(),
            &mut declined,
            &config,
            database.clone(),
        )
        .await
        .unwrap();

        let (rows, _) = AuditEntry::search(
            &AuditQuery {
                limit: 50,
                ..AuditQuery::default()
            },
            &database,
        )
        .await
        .unwrap();
        assert_eq!(rows.len(), 1, "only the deactivation is a mutation");
        assert_eq!(rows[0].event, "account_deactivated");
        assert_eq!(rows[0].actor_kind, "cli");
        assert_eq!(rows[0].profile, "default");
        assert_eq!(
            rows[0].account_id.as_deref(),
            Some(account.id.to_string().as_str())
        );
    }

    /// `account delete`'s audit row names how many orders went with the
    /// account.
    ///
    /// It counted them *after* the delete, so the `ON DELETE CASCADE` had
    /// already removed them and every row read `0 order(s) cascaded` however
    /// many there were. The count now travels out of the confirmation, which is
    /// where it was already computed to word the prompt.
    #[tokio::test]
    async fn deleting_an_account_records_what_actually_cascaded() {
        use acme_proxy_core::identifier::Identifier;
        use acme_proxy_store::audit::AuditEntry;
        use acme_proxy_store::audit::AuditQuery;
        use acme_proxy_store::order::Order;

        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        let (account, _) = Account::find_or_create(
            "default",
            &[2, 7, 1],
            vec![],
            &ClientContext::default(),
            &database,
        )
        .await
        .unwrap();
        for name in ["a.example.com", "b.example.com"] {
            Order::create(
                "default",
                account.id,
                vec![Identifier::dns(name)],
                acme_proxy_store::nonce::now_secs() + 3600,
                None,
                None,
                &database,
            )
            .await
            .unwrap();
        }

        let mut reader: &[u8] = &[];
        run_account_command(
            AccountCommand::Delete {
                id: account.id.to_string(),
            },
            true,
            Palette::plain(),
            &mut reader,
            &config,
            database.clone(),
        )
        .await
        .unwrap();

        let (rows, _) = AuditEntry::search(
            &AuditQuery {
                limit: 5,
                ..AuditQuery::default()
            },
            &database,
        )
        .await
        .unwrap();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].event, "account_deleted");
        assert_eq!(
            rows[0].detail.as_deref(),
            Some("2 order(s) cascaded"),
            "the count must be what the cascade actually took"
        );
    }

    /// `delete` without `--yes` asks first, and a refusal is a success: the
    /// operator answered, nothing was destroyed.
    #[tokio::test]
    async fn a_declined_delete_is_not_a_failure() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        let (account, _) = Account::find_or_create(
            "default",
            &[7, 7, 7],
            vec![],
            &ClientContext::default(),
            &database,
        )
        .await
        .unwrap();

        let mut reader: &[u8] = b"n\n";
        run_account_command(
            AccountCommand::Delete {
                id: account.id.to_string(),
            },
            false,
            Palette::plain(),
            &mut reader,
            &config,
            database.clone(),
        )
        .await
        .unwrap();

        assert!(
            Account::find_any_by_id(account.id.to_string().as_str(), &database)
                .await
                .unwrap()
                .is_some(),
            "a declined delete must leave the account in place"
        );
    }

    /// The listing takes a window, and a nonsense one is corrected rather than
    /// handed to SQL — where `LIMIT -1` means *no limit* in SQLite, the one
    /// answer a page must never accidentally give. `audit list`'s rule, now
    /// this one's.
    #[tokio::test]
    async fn list_runs_in_both_shapes_and_clamps_a_nonsense_window() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        for key in [&[1u8][..], &[2u8][..], &[3u8][..]] {
            Account::find_or_create("default", key, vec![], &ClientContext::default(), &database)
                .await
                .unwrap();
        }

        let mut reader: &[u8] = &[];
        for (limit, offset, json) in [(2, 0, false), (2, 2, false), (2, 0, true), (0, -5, false)] {
            run_account_command(
                AccountCommand::List {
                    profile: None,
                    eab_kid: None,
                    limit,
                    offset,
                    json,
                },
                true,
                Palette::plain(),
                &mut reader,
                &config,
                database.clone(),
            )
            .await
            .unwrap_or_else(|error| panic!("--limit {limit} --offset {offset}: {error}"));
        }
    }

    /// The window reaches the query rather than being clamped and dropped: two
    /// pages of two over three rows do not overlap, and the total stays the
    /// unpaged count on both. Asserted against the model the command calls,
    /// since a command body prints rather than returns.
    #[tokio::test]
    async fn consecutive_pages_do_not_overlap_and_the_total_stays_unpaged() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        for key in [&[1u8][..], &[2u8][..], &[3u8][..]] {
            Account::find_or_create("default", key, vec![], &ClientContext::default(), &database)
                .await
                .unwrap();
        }

        let (first, total) = Account::search(None, None, 2, 0, &database).await.unwrap();
        let (second, also_total) = Account::search(None, None, 2, 2, &database).await.unwrap();

        assert_eq!(total, 3);
        assert_eq!(also_total, 3, "the total is the table, not the page");
        assert_eq!(first.len(), 2);
        assert_eq!(second.len(), 1);
        for account in &second {
            assert!(
                !first.iter().any(|earlier| earlier.id == account.id),
                "a row appeared on two pages"
            );
        }
    }

    /// The JSON arms render through `admin::render_account_json`, which needs
    /// the configured `base_url` — a separate branch from the line renderer.
    #[tokio::test]
    async fn the_json_arms_render() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let config = Config::default();
        let (account, _) = Account::find_or_create(
            "default",
            &[9, 9, 9],
            vec![],
            &ClientContext::default(),
            &database,
        )
        .await
        .unwrap();

        let mut reader: &[u8] = &[];
        run_account_command(
            AccountCommand::List {
                profile: Some("default".to_string()),
                eab_kid: None,
                limit: DEFAULT_LIMIT,
                offset: 0,
                json: true,
            },
            true,
            Palette::plain(),
            &mut reader,
            &config,
            database.clone(),
        )
        .await
        .unwrap();

        run_account_command(
            AccountCommand::Show {
                id: account.id.to_string(),
                json: true,
            },
            true,
            Palette::plain(),
            &mut reader,
            &config,
            database,
        )
        .await
        .unwrap();
    }

    /// `account delete` over a live certificate fails with the shared wording
    /// and writes no audit row, even with `--yes`.
    #[tokio::test]
    async fn delete_refuses_an_account_holding_a_live_certificate() {
        let database = Arc::new(Database::connect_in_memory().await.unwrap());
        let account = acme_proxy_store::testutil::account_id(&database).await;
        acme_proxy_store::testutil::certified_order(&database, account, None).await;

        let error = run_account_command(
            AccountCommand::Delete {
                id: account.to_string(),
            },
            true,
            Palette::plain(),
            &mut &b""[..],
            &Config::default(),
            database.clone(),
        )
        .await
        .expect_err("a live certificate must refuse the delete");
        assert_eq!(
            error,
            CliError::bad_request(admin::live_certificates_refusal(
                &format!("account {account}"),
                1
            ))
        );
        let (rows, _) = acme_proxy_store::audit::AuditEntry::search(
            &acme_proxy_store::audit::AuditQuery::default(),
            &database,
        )
        .await
        .unwrap();
        assert!(rows.is_empty());
    }
}