acme-proxy 0.5.0

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
use std::io::BufRead;
use std::sync::Arc;

use clap::Subcommand;

use crate::admin::{self, DeleteOutcome};
use crate::audit::admin as audit_admin;
use crate::cli::CliError;
use crate::cli::render;
use crate::cli::style::Palette;
use crate::cli::window::{DEFAULT_LIMIT, Window};
use crate::config::Config;
use crate::sqlite::account::Account;
use crate::sqlite::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>,
        #[arg(long, default_value_t = DEFAULT_LIMIT)]
        limit: i64,
        #[arg(long, default_value_t = 0)]
        offset: i64,
        #[arg(long)]
        json: bool,
    },
    /// Show one account.
    Show {
        id: String,
        #[arg(long)]
        json: bool,
    },
    /// Replace an account's contact list.
    UpdateContact {
        id: String,
        #[arg(long = "contact")]
        contact: Vec<String>,
    },
    /// Set status = deactivated (RFC 8555 §7.3.6, terminal).
    Deactivate { id: String },
    /// Hard-delete the account and everything under it.
    Delete { 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,
            limit,
            offset,
            json,
        } => {
            let window = Window::resolve(limit, offset);
            let (accounts, total) =
                Account::search(profile.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? {
                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 } => {
            match admin::deactivate_account(&id, database.clone()).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::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(format!("no such account: {id}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::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 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 crate::sqlite::audit::{AuditEntry, 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 crate::sqlite::audit::{AuditEntry, AuditQuery};
        use crate::sqlite::order::{Identifier, 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)],
                crate::sqlite::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,
                    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, 2, 0, &database).await.unwrap();
        let (second, also_total) = Account::search(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()),
                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();
    }
}