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
//! `acme-proxy eab` — mint, list, revoke and delete external-account
//! credentials (RFC 8555 §7.3.4).
//!
//! The secret is printed **once**, by `create`: nothing reads it back, and a
//! lost credential is replaced rather than recovered. A credential scoped to a
//! profile is checked against the mounted set here, as it is on `/api` and
//! `/ui`, because one scoped to an endpoint this configuration does not serve
//! would be accepted and then never usable.
//!
//! `delete` is the one command with a blast radius beyond its own row: it may
//! deactivate or delete the accounts the credential bound, and is refused
//! outright when that would leave a live certificate impossible to revoke.
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::EabDeleteOutcome;
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::db::Database;
use acme_proxy_store::eab::BoundAccounts;
use acme_proxy_store::eab::DeletedEab;
use acme_proxy_store::eab::Eab;
#[derive(Subcommand)]
pub enum EabCommand {
/// Generate a new EAB key and print its kid and secret. The secret is
/// shown this once and never again.
Create {
/// A name for the key, shown in listings and matched by `eab` filter
/// checks.
#[arg(long)]
label: Option<String>,
/// Bind the credential to one ACME endpoint. Omitted, it is accepted
/// at every profile — which is what an unscoped credential means.
#[arg(long)]
profile: Option<String>,
/// Print it as JSON.
#[arg(long)]
json: bool,
},
/// List EAB keys, newest first. Never shows the secret.
List {
/// 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 EAB key. Never shows the secret.
Show {
/// The key id.
kid: String,
/// Print it as JSON.
#[arg(long)]
json: bool,
},
/// Revoke a key. The row stays, so accounts registered with it still
/// resolve to it (and to its label, for `eab` filter checks).
Revoke {
/// The key id.
kid: String,
},
/// Delete a key. Accounts registered with it are kept unless told
/// otherwise, and then no longer resolve to any credential, so every `eab`
/// filter check refuses them.
Delete {
/// The key id.
kid: String,
/// Also deactivate every account registered with it. Their orders are
/// kept, so their certificates stay revocable.
#[arg(long, conflicts_with = "delete_accounts")]
deactivate_accounts: bool,
/// Also hard-delete every account registered with it, and their orders.
/// Refused while any of those orders holds a live certificate.
#[arg(long)]
delete_accounts: bool,
},
}
pub async fn run_eab_command(
command: EabCommand,
yes: bool,
palette: Palette,
reader: &mut impl BufRead,
config: &Config,
database: Arc<Database>,
) -> Result<(), CliError> {
match command {
EabCommand::Create {
label,
profile,
json,
} => {
// The same refusal the panel and the API make: a credential scoped
// to an endpoint this configuration does not mount is accepted and
// then never usable, and the operator is still looking at what they
// typed. Only where `--profile` was given — a credential valid
// everywhere needs no profile to exist, and resolving would refuse
// a configuration that mounts none.
if profile.is_some() {
let mounted = config
.resolve_profiles()
.map_err(|error| CliError::failed(format!("configuration error: {error}")))?;
if let Some(message) = admin::unmounted_profile_refusal(
|name| mounted.iter().any(|profile| profile.name == name),
profile.as_deref(),
"omit --profile",
) {
return Err(CliError::failed(message));
}
}
let eab = Eab::create(label, profile, &database).await?;
audit_admin::record_cli_action(&database, |actor, client| {
audit_admin::eab_created(
actor,
client,
&eab.kid.to_string(),
eab.profile.as_deref(),
eab.label.as_deref(),
)
})
.await;
if json {
println!("{}", admin::render_eab_created_json(&eab));
} else {
print!("{}", render::render_eab_created_text(&eab, palette));
}
}
EabCommand::List {
limit,
offset,
json,
} => {
let window = Window::resolve(limit, offset);
let (keys, total) = Eab::search(window.limit, window.offset, &database).await?;
render::print_page(&keys, total, window, json, admin::render_eab_json, |eab| {
render::render_eab_line(eab, palette)
});
}
EabCommand::Show { kid, json } => match Eab::find_any_by_kid(&kid, &database).await? {
None => return Err(not_found(&kid)),
Some(eab) if json => println!("{}", admin::render_eab_json(&eab)),
Some(eab) => println!("{}", render::render_eab_line(&eab, palette)),
},
EabCommand::Revoke { kid } => {
let subject = Eab::find_any_by_kid(&kid, &database).await?;
if !Eab::revoke(&kid, &database).await? {
return Err(not_found(&kid));
}
// A repeat revoke changes nothing, so it records nothing — the
// `RevokeOutcome::AlreadyRevoked` rule on the certificate side.
if subject.as_ref().is_some_and(|eab| eab.status == "active") {
let profile = subject.as_ref().and_then(|eab| eab.profile.as_deref());
audit_admin::record_cli_action(&database, |actor, client| {
audit_admin::eab_revoked(actor, client, &kid, profile)
})
.await;
}
println!("Revoked EAB key {kid}.");
}
EabCommand::Delete {
kid,
deactivate_accounts,
delete_accounts,
} => {
let accounts = if delete_accounts {
BoundAccounts::Delete
} else if deactivate_accounts {
BoundAccounts::Deactivate
} else {
BoundAccounts::Keep
};
match admin::confirm_delete_eab(&kid, accounts, yes, reader, database.clone()).await? {
EabDeleteOutcome::NotFound => return Err(not_found(&kid)),
EabDeleteOutcome::LiveCertificates {
accounts,
certificates,
} => {
return Err(CliError::bad_request(admin::eab_live_certificates_refusal(
&kid,
accounts,
certificates,
)));
}
EabDeleteOutcome::Cancelled => println!("Cancelled."),
EabDeleteOutcome::Deleted(deleted) => {
audit_admin::record_cli_actions(&database, |actor, client| {
audit_admin::eab_deleted_records(actor, client, &deleted)
})
.await;
println!("{}", deleted_line(&kid, &deleted));
}
}
}
}
Ok(())
}
/// What `eab delete` prints once it has happened.
fn deleted_line(kid: &str, deleted: &DeletedEab) -> String {
match deleted.accounts {
BoundAccounts::Keep => format!(
"Deleted EAB key {kid}; {} account(s) registered with it were kept.",
deleted.remaining
),
BoundAccounts::Deactivate => format!(
"Deleted EAB key {kid}; {} account(s) deactivated, their orders kept.",
deleted.deactivated.len()
),
BoundAccounts::Delete => format!(
"Deleted EAB key {kid} ({} account(s), {} order(s) deleted).",
deleted.deleted.len(),
deleted
.deleted
.iter()
.map(|(_, orders)| orders)
.sum::<u64>()
),
}
}
fn not_found(kid: &str) -> CliError {
CliError::bad_request(acme_proxy_admin::admin::subject::Subject::EabCredential.missing(kid))
}
#[cfg(test)]
mod tests {
use super::*;
/// A configuration with no profiles, which is all a command that does not
/// name one ever reads.
fn config() -> Config {
Config::default()
}
/// Loads a `Config` the way the server does, so `resolve_profiles` has the
/// raw sources it needs — `cli::profile`'s helper, and for its reason.
fn config_from(body: &str) -> Config {
let _lock = acme_proxy_core::config::ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = acme_proxy_core::testutil::TempDir::new("eab");
std::fs::write(dir.join("config.toml"), body).unwrap();
// SAFETY: single-threaded test holding ENV_LOCK; removed before return.
unsafe {
std::env::set_var("ACME_PROXY_CONFIG", dir.join("config").to_str().unwrap());
}
let config = Config::load().expect("the configuration must load");
unsafe {
std::env::remove_var("ACME_PROXY_CONFIG");
}
config
}
/// A credential scoped to an endpoint this configuration does not mount
/// would be accepted and then never usable, so it is refused where the
/// operator can still fix the spelling — the same rule `/api` and `/ui`
/// apply.
#[tokio::test]
async fn create_refuses_a_profile_that_is_not_mounted() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let config = config_from(
r#"
[profiles.default]
signer.backend = "local_ca"
"#,
);
let error = run_eab_command(
EabCommand::Create {
label: None,
profile: Some("typo".to_string()),
json: false,
},
true,
Palette::plain(),
&mut &b""[..],
&config,
database.clone(),
)
.await
.expect_err("a credential for an unmounted endpoint must be refused");
assert!(format!("{error:?}").contains("typo"), "{error:?}");
// And nothing was written.
let (rows, _) = Eab::search(50, 0, &database).await.unwrap();
assert!(rows.is_empty());
// The profile that is mounted is minted as usual.
run_eab_command(
EabCommand::Create {
label: None,
profile: Some("default".to_string()),
json: false,
},
true,
Palette::plain(),
&mut &b""[..],
&config,
database.clone(),
)
.await
.expect("a mounted endpoint is fine");
}
#[tokio::test]
async fn show_revoke_and_delete_refuse_an_unknown_kid() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let expected = CliError::bad_request("no such EAB credential: kid-nope".to_string());
for command in [
EabCommand::Show {
kid: "kid-nope".to_string(),
json: false,
},
EabCommand::Revoke {
kid: "kid-nope".to_string(),
},
EabCommand::Delete {
kid: "kid-nope".to_string(),
deactivate_accounts: false,
delete_accounts: true,
},
] {
let error = run_eab_command(
command,
true,
Palette::plain(),
&mut &b""[..],
&config(),
database.clone(),
)
.await
.expect_err("an unknown kid must fail");
assert_eq!(error, expected);
}
}
/// `revoke` matches on the `kid` alone, so revoking twice is idempotent
/// and still reports success — only an unknown `kid` is an error.
#[tokio::test]
async fn a_created_key_shows_lists_and_revokes() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let eab = Eab::create(Some("test".to_string()), None, &database)
.await
.unwrap();
// `--profile` is checked against the mounted set, so this one needs a
// configuration that mounts it.
let config = config_from(
r#"
[profiles.default]
signer.backend = "local_ca"
"#,
);
for command in [
EabCommand::Create {
label: None,
profile: Some("default".to_string()),
json: true,
},
EabCommand::List {
limit: DEFAULT_LIMIT,
offset: 0,
json: true,
},
EabCommand::Show {
kid: eab.kid.to_string(),
json: true,
},
EabCommand::Show {
kid: eab.kid.to_string(),
json: false,
},
EabCommand::Revoke {
kid: eab.kid.to_string(),
},
] {
run_eab_command(
command,
true,
Palette::plain(),
&mut &b""[..],
&config,
database.clone(),
)
.await
.unwrap();
}
run_eab_command(
EabCommand::Revoke {
kid: eab.kid.to_string(),
},
true,
Palette::plain(),
&mut &b""[..],
&config,
database.clone(),
)
.await
.expect("revoking an already-revoked key is a no-op, not a failure");
assert_eq!(
Eab::find_any_by_kid(eab.kid.to_string().as_str(), &database)
.await
.unwrap()
.unwrap()
.status,
"revoked"
);
}
/// `eab_kid`'s credential with one bound account holding a certificate that
/// expires at `not_after`.
async fn bound_account(
database: &Arc<Database>,
not_after: Option<i64>,
) -> (Eab, acme_proxy_store::account::Account) {
let eab = Eab::create(Some("tenant".to_string()), None, database)
.await
.unwrap();
let (mut account, _) = acme_proxy_store::account::Account::find_or_create(
"default",
&[7u8],
vec![],
&acme_proxy_core::audit::ClientContext::default(),
database,
)
.await
.unwrap();
account.set_eab_kid(eab.kid, database).await.unwrap();
acme_proxy_store::testutil::certified_order(database, account.id, not_after).await;
(eab, account)
}
async fn delete(
kid: &Eab,
deactivate_accounts: bool,
delete_accounts: bool,
database: &Arc<Database>,
) -> Result<(), CliError> {
run_eab_command(
EabCommand::Delete {
kid: kid.kid.to_string(),
deactivate_accounts,
delete_accounts,
},
true,
Palette::plain(),
&mut &b""[..],
&config(),
database.clone(),
)
.await
}
async fn audit_events(database: &Database) -> Vec<String> {
let (rows, _) = acme_proxy_store::audit::AuditEntry::search(
&acme_proxy_store::audit::AuditQuery {
limit: 50,
..Default::default()
},
database,
)
.await
.unwrap();
rows.into_iter().map(|row| row.event).collect()
}
/// `--delete-accounts` over a live certificate is refused with the shared
/// wording, writes no audit row, and changes nothing; deactivating instead
/// goes through and writes one row per account plus the credential's.
#[tokio::test]
async fn delete_with_accounts_refuses_a_live_certificate_and_deactivating_does_not() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let (eab, account) = bound_account(&database, None).await;
let error = delete(&eab, false, true, &database)
.await
.expect_err("a live certificate must refuse the delete");
assert_eq!(
error,
CliError::bad_request(admin::eab_live_certificates_refusal(
&eab.kid.to_string(),
1,
1
))
);
assert!(audit_events(&database).await.is_empty());
delete(&eab, true, false, &database).await.unwrap();
let mut events = audit_events(&database).await;
events.sort();
assert_eq!(events, ["account_deactivated", "eab_deleted"]);
assert_eq!(
acme_proxy_store::account::Account::find_any_by_id(
account.id.to_string().as_str(),
&database
)
.await
.unwrap()
.unwrap()
.status,
"deactivated"
);
}
/// With nothing live, `--delete-accounts` deletes the account and audits
/// both the account and the credential; a plain delete audits only the
/// credential.
#[tokio::test]
async fn delete_audits_the_credential_and_every_account_it_took() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let (eab, _) = bound_account(&database, Some(1)).await;
delete(&eab, false, true, &database).await.unwrap();
let mut events = audit_events(&database).await;
events.sort();
assert_eq!(events, ["account_deleted", "eab_deleted"]);
let kept = Eab::create(None, None, &database).await.unwrap();
delete(&kept, false, false, &database).await.unwrap();
assert_eq!(audit_events(&database).await[0], "eab_deleted");
}
#[test]
fn deleted_line_says_what_became_of_the_accounts() {
use acme_proxy_store::eab::DeletedEab;
let eab = || Eab {
kid: uuid::Uuid::nil(),
secret: Vec::new(),
label: None,
profile: None,
status: "active".to_string(),
created_at: 0,
};
let kid = uuid::Uuid::nil().to_string();
let kept = DeletedEab {
eab: eab(),
accounts: BoundAccounts::Keep,
deactivated: Vec::new(),
deleted: Vec::new(),
remaining: 3,
};
assert!(deleted_line(&kid, &kept).ends_with("3 account(s) registered with it were kept."));
let deactivated = DeletedEab {
accounts: BoundAccounts::Deactivate,
..kept
};
assert!(deleted_line(&kid, &deactivated).contains("0 account(s) deactivated"));
let deleted = DeletedEab {
eab: eab(),
accounts: BoundAccounts::Delete,
deactivated: Vec::new(),
deleted: Vec::new(),
remaining: 0,
};
assert!(deleted_line(&kid, &deleted).ends_with("(0 account(s), 0 order(s) deleted)."));
}
}