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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
use std::io::BufRead;
use std::sync::Arc;
use uuid::Uuid;
use clap::Subcommand;
use crate::admin::{self, DeleteOutcome};
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::signer;
use crate::sqlite::authz::Authorization;
use crate::sqlite::db::Database;
use crate::sqlite::order::{Order, OrderQuery};
use crate::sqlite::status::OrderStatus;
#[derive(Subcommand)]
pub enum OrderCommand {
/// List orders, optionally filtered.
List {
/// Restrict the listing to one ACME endpoint.
#[arg(long)]
profile: Option<String>,
#[arg(long = "account-id")]
account_id: Option<String>,
#[arg(long)]
status: Option<String>,
/// Only orders naming this identifier exactly (case-insensitive).
#[arg(long)]
identifier: Option<String>,
/// Only orders naming an identifier that contains this substring
/// (case-insensitive). Mutually exclusive with `--identifier`.
#[arg(long = "identifier-contains", conflicts_with = "identifier")]
identifier_contains: Option<String>,
/// Only the order whose issued certificate has this serial (hex, no
/// separators) -- the value an abuse report hands you.
#[arg(long = "cert-serial")]
cert_serial: Option<String>,
/// Instead: the certificates lapsing within N days, soonest first,
/// each annotated with whatever has already replaced it.
#[arg(long = "expiring-in")]
expiring_in: Option<u64>,
/// Omit certificates something has already replaced. Needs
/// `--expiring-in`, which is where the annotation comes from.
#[arg(long = "hide-superseded")]
hide_superseded: bool,
#[arg(long, default_value_t = DEFAULT_LIMIT)]
limit: i64,
#[arg(long, default_value_t = 0)]
offset: i64,
#[arg(long)]
json: bool,
},
/// Show one order plus its authorizations and challenges.
Show {
id: String,
#[arg(long)]
json: bool,
},
/// Print the issued certificate chain, as PEM, on stdout.
Chain { id: String },
/// Hard-delete the order and everything under it.
Delete { id: String },
/// Revoke the order's issued certificate.
Revoke {
id: String,
#[arg(long)]
reason: Option<u32>,
},
}
pub async fn run_order_command(
command: OrderCommand,
yes: bool,
palette: Palette,
reader: &mut impl BufRead,
config: &Config,
database: Arc<Database>,
) -> Result<(), CliError> {
match command {
OrderCommand::List {
profile,
account_id,
status,
identifier,
identifier_contains,
cert_serial,
expiring_in,
hide_superseded,
limit,
offset,
json,
} => {
let window = Window::resolve(limit, offset);
// `--expiring-in` is a different question over a different query,
// and the flags that do not compose with it are refused **by name**
// rather than ignored -- `--status`'s own rule, and for its reason:
// an argument silently dropped answers with rows that look like it
// was honoured. The window is not among them: it is the one flag
// that means the same thing on both queries, so it is passed
// straight through.
if let Some(days) = expiring_in {
return run_expiring(
days,
profile,
account_id.as_deref(),
status.as_deref(),
identifier.as_deref(),
identifier_contains.as_deref(),
cert_serial.as_deref(),
hide_superseded,
window,
json,
palette,
database,
)
.await;
}
if hide_superseded {
return Err(CliError::bad_request(
"--hide-superseded needs --expiring-in: it filters on the supersession \
annotation, which only the expiry listing carries"
.to_string(),
));
}
// Refused by name rather than passed through: an unknown status
// would match no rows, which reads exactly like "nothing is in
// that state". The same rule `audit list --event` follows.
let status = status
.map(|value| value.parse::<OrderStatus>())
.transpose()
.map_err(|error| CliError::bad_request(format!("--status: {error}")))?;
// Filtered in SQL, by the same `Order::search` the web admin uses.
// It used to load every order in the database and filter the three
// fields in Rust, which is one policy written twice — and the two
// could drift into disagreeing about what `--status` means.
let query = OrderQuery {
profile,
account_id,
status,
identifier,
identifier_contains,
// Folded here rather than bound raw: an operator pastes a
// serial out of `openssl` or an abuse report, and the column
// only ever holds lowercase unseparated hex.
cert_serial: cert_serial.as_deref().map(crate::cert::normalize_serial),
limit: window.limit,
offset: window.offset,
};
let (orders, total) = Order::search(&query, &database).await?;
// Not `render::print_page`, and this is the only listing that opts
// out: the `--json` rendering needs one batched authorization
// lookup for the whole page, not one query per row — the N+1 the
// web admin's `render_orders` already avoids, and what
// `find_ids_by_orders` exists for. Handing that closure to
// `print_page` would make the text path pay for a query it never
// reads, so the two halves are spelled out and the shared envelope
// and footer are called directly.
if json {
let ids: Vec<Uuid> = orders.iter().map(|o| o.id).collect();
let mut authz_ids = Authorization::find_ids_by_orders(&ids, &database).await?;
let rendered: Vec<_> = orders
.iter()
.map(|order| {
admin::render_order_json(
order,
&config.server.base_url,
&authz_ids.remove(&order.id).unwrap_or_default(),
)
})
.collect();
println!("{}", render::json_page(rendered, total, window));
} else {
for order in &orders {
println!("{}", render::render_order_line(order, palette));
}
render::print_footer(orders.len(), total);
}
}
OrderCommand::Show { id, json } => match admin::load_order_detail(&id, database).await? {
None => return Err(not_found(&id)),
Some(detail) if json => {
println!(
"{}",
admin::render_order_detail_json(&detail, &config.server.base_url)
);
}
Some(detail) => print!("{}", render::render_order_detail_text(&detail, palette)),
},
OrderCommand::Chain { id } => {
// The whole of stdout, so it pipes: `order chain <id> > cert.pem`.
// Deliberately not a flag on `show` -- a flag that discards the rest
// of its command's output is a mode wearing a flag's clothes. The
// JSON side already had this as `certificatePem` on
// `render_order_detail_json`; what was missing was the raw bytes.
let Some(order) = Order::find_by_id(&id, &database).await? else {
return Err(not_found(&id));
};
// Refused rather than answered with zero bytes, the rule
// `GET /ui/orders/{id}/chain.pem` already keeps: an empty file named
// `.pem` reads as a broken certificate rather than an absent one.
let Some(pem) = order.certificate else {
return Err(CliError::bad_request(format!(
"order {id} has no certificate: it has not been finalized"
)));
};
// `print!`: the stored chain already ends in a newline, and a second
// one would make the output differ from the file the panel serves.
print!("{pem}");
}
OrderCommand::Delete { id } => {
// Read the order first, for its profile and identifiers: the audit
// row names them and the row is gone once the delete returns. Both
// web front ends already wrote `order_deleted`; this one hard-
// deleted an order and left the trail silent.
let doomed = Order::find_by_id(&id, &database).await?;
match admin::confirm_delete_order(&id, yes, reader, database.clone()).await? {
DeleteOutcome::NotFound => return Err(not_found(&id)),
DeleteOutcome::Cancelled => println!("Cancelled."),
DeleteOutcome::Deleted(deleted) => {
if let Some(order) = doomed {
crate::audit::admin::record_cli_action(&database, |actor, client| {
crate::audit::admin::order_deleted(
actor,
client,
&order,
deleted.cascaded,
)
})
.await;
}
println!(
"Deleted order {id} ({} authorization(s) cascaded).",
deleted.cascaded
);
}
}
}
OrderCommand::Revoke { id, reason } => {
// Revocation goes through the endpoint that issued the certificate:
// another profile's backend holds a different CA, or none at all.
let Some(order) = Order::find_by_id(&id, &database).await? else {
return Err(not_found(&id));
};
let profiles = config
.resolve_profiles()
.map_err(|error| CliError::failed(format!("configuration error: {error}")))?;
let Some(profile) = profiles.iter().find(|p| p.name == order.profile) else {
return Err(CliError::bad_request(format!(
"order {id} was issued by profile `{}`, which this configuration does not \
define — revoking it needs the endpoint that signed it",
order.profile
)));
};
// No notifiers: this is a one-off admin invocation, not the long-
// running server — there is no background completion task here
// for a notifier to ever be reached from.
// A throwaway egress: this is a one-shot admin command, not the
// long-running server, so there is no shared resolver or proxy
// policy to reuse — both come from the same `[dns]`/`[proxy]`
// sections `serve` reads.
let egress = Arc::new(
crate::Egress::from_config(config)
.map_err(|error| CliError::failed(format!("configuration error: {error}")))?,
);
// A queue nothing drains: this command revokes, which every backend
// answers inline, so no job is ever enqueued. Handing over a live
// queue would be worse than useless — it would let a one-shot CLI
// invocation write rows that only the running server can work off.
let jobs = crate::jobs::JobQueue::new(database.clone(), &config.jobs);
// A registry nothing scrapes, for the same reason as the queue
// above: this process exits when the command does, and the counters
// that matter belong to the server that is serving `/metrics`.
let metrics = Arc::new(crate::metrics::Metrics::new(database.clone()));
let signer = signer::from_config(
&profile.sections.signer,
&signer::SignerParts {
database: database.clone(),
notifiers: std::collections::HashMap::new().into(),
metrics,
egress,
jobs,
},
// Nothing to adopt: there is no previous generation in a process
// that exits when this command does.
&signer::CarriedState::new(),
)
.map_err(|error| CliError::failed(format!("signer error: {error}")))?;
// `Actor::cli` and an empty client context: there is no request
// here, and the audit row says so rather than inventing an address.
match admin::revoke_order(
&id,
reason,
crate::audit::Actor::cli(),
crate::audit::ClientContext::default(),
database,
signer,
)
.await
// A bad `--reason` code is the operator's to fix (exit 3); every
// other revoke failure is the host's (a signer or database error).
.map_err(|error| match error {
admin::RevokeError::BadReason(_) => CliError::bad_request(error.to_string()),
other => CliError::failed(other.to_string()),
})? {
admin::RevokeOutcome::NotFound => return Err(not_found(&id)),
admin::RevokeOutcome::NotIssued => {
return Err(CliError::bad_request(format!(
"order {id} has no issued certificate"
)));
}
admin::RevokeOutcome::AlreadyRevoked => {
return Err(CliError::bad_request(format!(
"order {id}'s certificate is already revoked"
)));
}
admin::RevokeOutcome::Revoked(order) => {
println!("{}", render::render_order_line(&order, palette));
}
}
}
}
Ok(())
}
/// `order list --expiring-in <days>`.
///
/// A branch rather than a sibling subcommand because it is still "list orders",
/// asked with a different filter -- but it is a different *query*
/// (`Order::find_expiring`, ordered by expiry rather than by age) with its own
/// fixed status set, so the two filters that cannot mean anything here are
/// refused instead of ignored.
///
/// Paged like the rest of `order list`, and reporting `hidden` beside the total
/// exactly as `GET /api/expiring` does -- `total` counts the *window*, not the
/// answer, because supersession is computed per row and cannot become a SQL
/// predicate. `admin::annotate_expiring` still reads each account's orders once
/// for the whole page rather than once per row, which is what keeps a page over
/// a single busy account from re-reading its history fifty times.
#[allow(clippy::too_many_arguments)]
async fn run_expiring(
days: u64,
profile: Option<String>,
account_id: Option<&str>,
status: Option<&str>,
identifier: Option<&str>,
identifier_contains: Option<&str>,
cert_serial: Option<&str>,
hide_superseded: bool,
window: Window,
json: bool,
palette: Palette,
database: Arc<Database>,
) -> Result<(), CliError> {
if status.is_some() {
return Err(CliError::bad_request(
"--status does not apply with --expiring-in: the expiry listing is issued, \
unrevoked certificates by definition, so a status filter here would mean \
something other than it does everywhere else"
.to_string(),
));
}
if account_id.is_some() {
return Err(CliError::bad_request(
"--account-id does not apply with --expiring-in: the expiry listing has no \
account predicate, and answering as though it did would report one \
subscriber's certificates as every subscriber's"
.to_string(),
));
}
if identifier.is_some() || identifier_contains.is_some() || cert_serial.is_some() {
return Err(CliError::bad_request(
"--identifier, --identifier-contains and --cert-serial do not apply with \
--expiring-in: the expiry listing is ordered by expiry over a fixed status \
set, so a name or serial filter here would mean something other than it \
does on the plain listing"
.to_string(),
));
}
let query = admin::ExpiringQuery {
profile,
before: admin::expiring_horizon(days),
include_superseded: !hide_superseded,
limit: window.limit,
offset: window.offset,
};
let (entries, total, hidden) = admin::list_expiring(&query, database).await?;
if json {
let items = entries.iter().map(admin::render_expiring_json).collect();
let mut envelope = render::json_page(items, total, window);
if let Some(object) = envelope.as_object_mut() {
// The same two extra members `GET /api/expiring` adds, spelled the
// same way: one answer to "what is expiring" rendered identically
// wherever it is asked.
object.insert("hidden".to_string(), serde_json::json!(hidden));
object.insert("days".to_string(), serde_json::json!(days));
}
println!("{envelope}");
} else {
for entry in &entries {
println!("{}", render::render_expiring_line(entry, palette));
}
render::print_expiring_footer(entries.len(), total, hidden);
}
Ok(())
}
fn not_found(id: &str) -> CliError {
CliError::bad_request(format!("no such order: {id}"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::audit::ClientContext;
use crate::cli::CliErrorKind;
use crate::signer::{IssueOutcome, RequestedValidity, SignerBackend};
use crate::sqlite::account::Account;
/// A configuration whose single `default` profile signs with a local CA
/// living under `dir` — what `Revoke` needs, since it rebuilds the signer
/// from the profile that issued the certificate.
fn config_in(dir: impl AsRef<std::path::Path>, profile: &str) -> Config {
let dir = dir.as_ref();
let _lock = crate::config::ENV_LOCK
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let ca = dir.join("ca");
std::fs::write(
dir.join("config.toml"),
format!(
r#"
[profiles.{profile}]
signer.local_ca.cert_path = "{ca}.pem"
signer.local_ca.key_path = "{ca}.key"
signer.local_ca.crl_path = "{ca}.crl"
"#,
ca = ca.display(),
),
)
.unwrap();
// SAFETY: the lock above makes this the only thread touching the
// environment, and the variable is removed before returning.
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
}
fn temp_dir() -> crate::testutil::TempDir {
crate::testutil::TempDir::new("cli-order")
}
/// `order delete` records what it removed.
///
/// It recorded nothing at all: both web front ends wrote `order_deleted`,
/// and the CLI — the only front end that hard-deletes an order from a
/// shell — left the trail silent. A declined prompt still writes nothing,
/// which is the rule for this whole half of the vocabulary.
#[tokio::test]
async fn deleting_an_order_writes_a_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 order = seed_order(&database, "default").await;
let id = order.id.to_string();
let mut declined: &[u8] = b"n\n";
run_order_command(
OrderCommand::Delete { id: id.clone() },
false,
Palette::plain(),
&mut declined,
&config,
database.clone(),
)
.await
.unwrap();
assert_eq!(
AuditEntry::search(&AuditQuery::default(), &database)
.await
.unwrap()
.1,
0,
"a declined delete is not an administrative action"
);
let mut reader: &[u8] = &[];
run_order_command(
OrderCommand::Delete { id: id.clone() },
true,
Palette::plain(),
&mut reader,
&config,
database.clone(),
)
.await
.unwrap();
let (rows, total) = AuditEntry::search(
&AuditQuery {
limit: 5,
..AuditQuery::default()
},
&database,
)
.await
.unwrap();
assert_eq!(total, 1);
assert_eq!(rows[0].event, "order_deleted");
assert_eq!(rows[0].actor_kind, "cli");
assert_eq!(rows[0].profile, "default");
assert_eq!(rows[0].order_id.as_deref(), Some(id.as_str()));
// The row outlives the order it names — `audit_log` has no foreign
// keys, which is the whole reason it can record a deletion.
assert!(
Order::find_by_id(&id, &database).await.unwrap().is_none(),
"the order really went"
);
}
async fn seed_order(database: &Arc<Database>, profile: &str) -> Order {
let (account, _) = Account::find_or_create(
profile,
&[4, 5, 6],
vec![],
&ClientContext::default(),
database,
)
.await
.unwrap();
Order::create(
profile,
account.id,
vec![crate::sqlite::order::Identifier::dns("example.com")],
crate::sqlite::nonce::now_secs() + 3600,
None,
None,
database,
)
.await
.unwrap()
}
/// Issues against `config`'s own CA and records the result on `order`, so
/// the certificate the CLI later revokes is one that CA actually signed.
async fn issue_onto(order: &mut Order, config: &Config, database: Arc<Database>) {
let profile = &config.resolve_profiles().unwrap()[0];
let resolver = crate::dns::resolver_addr(&config.dns)
.and_then(crate::challenge::build_resolver)
.expect("the default dns configuration must build a resolver");
let signer: Arc<dyn SignerBackend> = signer::from_config(
&profile.sections.signer,
&crate::testutil::signer_parts(database.clone(), resolver),
&signer::CarriedState::new(),
)
.unwrap();
let key_pair = rcgen::KeyPair::generate().unwrap();
let params = rcgen::CertificateParams::new(vec!["example.com".to_string()]).unwrap();
let csr = params.serialize_request(&key_pair).unwrap();
let chain = match signer
.issue(
order.id.to_string().as_str(),
csr.der(),
&order.identifiers,
RequestedValidity::default(),
)
.await
.unwrap()
{
IssueOutcome::Issued(chain) => chain,
IssueOutcome::Processing => panic!("the local CA issues synchronously"),
};
let leaf = crate::cert::leaf_der_from_chain(&chain).unwrap();
let (serial, pubkey) = crate::cert::cert_serial_and_spki(&leaf).unwrap();
let not_after = crate::cert::cert_validity(&leaf).ok().map(|(_, na)| na);
order
.finalize(chain, serial, pubkey, not_after, &database)
.await
.unwrap();
}
#[tokio::test]
async fn every_arm_refuses_an_unknown_order() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let config = Config::default();
let expected = CliError::bad_request("no such order: ord-nope".to_string());
let commands = vec![
OrderCommand::Show {
id: "ord-nope".to_string(),
json: false,
},
OrderCommand::Chain {
id: "ord-nope".to_string(),
},
OrderCommand::Delete {
id: "ord-nope".to_string(),
},
OrderCommand::Revoke {
id: "ord-nope".to_string(),
reason: None,
},
];
for command in commands {
let mut reader: &[u8] = &[];
let error = run_order_command(
command,
true,
Palette::plain(),
&mut reader,
&config,
database.clone(),
)
.await
.expect_err("an unknown order must fail");
assert_eq!(error, expected);
}
}
/// The PEM on stdout, and the refusal that keeps it honest: an order that
/// never reached issuance is an error, not an empty file --
/// `GET /ui/orders/{id}/chain.pem`'s own rule, since zero bytes named
/// `.pem` read as a broken certificate rather than an absent one.
#[tokio::test]
async fn chain_prints_the_issued_pem_and_refuses_an_order_with_none() {
let dir = temp_dir();
let config = config_in(&dir, "default");
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let mut order = seed_order(&database, "default").await;
let mut reader: &[u8] = &[];
let error = run_order_command(
OrderCommand::Chain {
id: order.id.to_string(),
},
true,
Palette::plain(),
&mut reader,
&config,
database.clone(),
)
.await
.expect_err("an order with no certificate has no chain to print");
assert_eq!(
error,
CliError::bad_request(format!(
"order {} has no certificate: it has not been finalized",
order.id
))
);
issue_onto(&mut order, &config, database.clone()).await;
// What the command prints is the column, verbatim -- the same string
// `render_order_detail_json`'s `certificatePem` and the panel's download
// both hand over.
let stored = Order::find_by_id(order.id.to_string().as_str(), &database)
.await
.unwrap()
.unwrap()
.certificate
.expect("finalize stored the chain");
assert!(stored.starts_with("-----BEGIN CERTIFICATE-----"));
let mut reader: &[u8] = &[];
run_order_command(
OrderCommand::Chain {
id: order.id.to_string(),
},
true,
Palette::plain(),
&mut reader,
&config,
database,
)
.await
.unwrap();
}
/// `revoke` needs the endpoint that signed the certificate. A profile the
/// running configuration no longer defines says so, rather than silently
/// revoking against some other profile's CA.
#[tokio::test]
async fn revoking_an_order_from_an_undefined_profile_is_refused() {
let dir = temp_dir();
let database = Arc::new(Database::connect_in_memory().await.unwrap());
// The order belongs to `default`; the configuration only mounts `other`.
let order = seed_order(&database, "default").await;
let config = config_in(&dir, "other");
let mut reader: &[u8] = &[];
let error = run_order_command(
OrderCommand::Revoke {
id: order.id.to_string(),
reason: None,
},
true,
Palette::plain(),
&mut reader,
&config,
database,
)
.await
.expect_err("a profile this configuration does not define must be refused");
assert!(
error.to_string().contains("which this configuration"),
"{error}"
);
}
/// A configuration that mounts nothing at all cannot name a signer either.
#[tokio::test]
async fn revoking_without_a_resolvable_configuration_is_refused() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let order = seed_order(&database, "default").await;
let mut reader: &[u8] = &[];
let error = run_order_command(
OrderCommand::Revoke {
id: order.id.to_string(),
reason: None,
},
true,
Palette::plain(),
&mut reader,
&Config::default(),
database,
)
.await
.expect_err("a configuration mounting nothing must be refused");
assert!(
error.to_string().starts_with("configuration error: "),
"{error}"
);
}
#[tokio::test]
async fn revoking_an_order_with_no_certificate_is_refused() {
let dir = temp_dir();
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let order = seed_order(&database, "default").await;
let config = config_in(&dir, "default");
let mut reader: &[u8] = &[];
let error = run_order_command(
OrderCommand::Revoke {
id: order.id.to_string(),
reason: None,
},
true,
Palette::plain(),
&mut reader,
&config,
database,
)
.await
.expect_err("there is nothing to revoke");
assert_eq!(
error,
CliError::bad_request(format!("order {} has no issued certificate", order.id))
);
}
/// The whole arm end to end: issue, revoke through the CLI, then find the
/// second attempt refused because the first one stuck.
#[tokio::test]
async fn an_issued_order_revokes_once() {
let dir = temp_dir();
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let config = config_in(&dir, "default");
let mut order = seed_order(&database, "default").await;
issue_onto(&mut order, &config, database.clone()).await;
let mut reader: &[u8] = &[];
run_order_command(
OrderCommand::Revoke {
id: order.id.to_string(),
reason: Some(1),
},
true,
Palette::plain(),
&mut reader,
&config,
database.clone(),
)
.await
.expect("a certificate issued by this profile's CA must revoke");
assert!(
Order::find_by_id(order.id.to_string().as_str(), &database)
.await
.unwrap()
.unwrap()
.revoked_at
.is_some()
);
let error = run_order_command(
OrderCommand::Revoke {
id: order.id.to_string(),
reason: None,
},
true,
Palette::plain(),
&mut reader,
&config,
database.clone(),
)
.await
.expect_err("a second revocation has nothing left to do");
assert_eq!(
error,
CliError::bad_request(format!(
"order {}'s certificate is already revoked",
order.id
))
);
}
/// An out-of-range reason code comes back from `admin::revoke_order` as a
/// typed error, not a database one.
#[tokio::test]
async fn an_invalid_revocation_reason_is_refused() {
let dir = temp_dir();
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let config = config_in(&dir, "default");
let mut order = seed_order(&database, "default").await;
issue_onto(&mut order, &config, database.clone()).await;
let mut reader: &[u8] = &[];
let error = run_order_command(
OrderCommand::Revoke {
id: order.id.to_string(),
reason: Some(7),
},
true,
Palette::plain(),
&mut reader,
&config,
database,
)
.await
.expect_err("7 is not a defined CRLReason");
assert!(error.to_string().contains('7'), "{error}");
assert_eq!(error.kind(), CliErrorKind::BadRequest);
}
/// A declined delete leaves the order in place and is not a failure.
#[tokio::test]
async fn a_declined_delete_is_not_a_failure() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let order = seed_order(&database, "default").await;
let mut reader: &[u8] = b"n\n";
run_order_command(
OrderCommand::Delete {
id: order.id.to_string(),
},
false,
Palette::plain(),
&mut reader,
&Config::default(),
database.clone(),
)
.await
.unwrap();
assert!(
Order::find_by_id(order.id.to_string().as_str(), &database)
.await
.unwrap()
.is_some()
);
}
/// `show --json` renders through a different branch than the text form,
/// and `list --json` additionally walks each order's authorizations.
#[tokio::test]
async fn the_json_arms_render() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let order = seed_order(&database, "default").await;
let mut reader: &[u8] = &[];
for command in [
OrderCommand::List {
profile: Some("default".to_string()),
account_id: None,
status: None,
identifier: None,
identifier_contains: None,
cert_serial: None,
expiring_in: None,
hide_superseded: false,
limit: DEFAULT_LIMIT,
offset: 0,
json: true,
},
// The identifier and serial filters walk the same render paths.
OrderCommand::List {
profile: None,
account_id: None,
status: None,
identifier: Some("seeded.example.com".to_string()),
identifier_contains: None,
cert_serial: None,
expiring_in: None,
hide_superseded: false,
limit: DEFAULT_LIMIT,
offset: 0,
json: true,
},
OrderCommand::List {
profile: None,
account_id: None,
status: None,
identifier: None,
identifier_contains: Some("example".to_string()),
cert_serial: Some("deadbeef".to_string()),
expiring_in: None,
hide_superseded: false,
limit: DEFAULT_LIMIT,
offset: 0,
json: false,
},
OrderCommand::Show {
id: order.id.to_string(),
json: true,
},
OrderCommand::Show {
id: order.id.to_string(),
json: false,
},
] {
run_order_command(
command,
true,
Palette::plain(),
&mut reader,
&Config::default(),
database.clone(),
)
.await
.unwrap();
}
}
/// An unknown `--status` is refused **by name**, not passed to SQL.
///
/// The distinction is the whole point: a typo handed through to the query
/// answers "no rows", which an operator cannot tell from "nothing is in
/// that state". The same rule `audit list --event` follows.
#[tokio::test]
async fn an_unknown_status_is_refused_by_name_rather_than_matching_nothing() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
seed_order(&database, "default").await;
let mut reader: &[u8] = &[];
let error = run_order_command(
OrderCommand::List {
profile: None,
account_id: None,
status: Some("readyy".to_string()),
identifier: None,
identifier_contains: None,
cert_serial: None,
expiring_in: None,
hide_superseded: false,
limit: DEFAULT_LIMIT,
offset: 0,
json: false,
},
true,
Palette::plain(),
&mut reader,
&Config::default(),
database.clone(),
)
.await
.unwrap_err();
assert!(error.message.contains("--status"), "{error}");
assert!(error.message.contains("`readyy`"), "{error}");
// The operator typed it, so re-running it unchanged cannot help: exit 3.
assert_eq!(error.kind(), CliErrorKind::BadRequest);
// ...and it names the alternatives, so the operator does not guess.
assert!(
error
.message
.contains("pending, ready, processing, valid, invalid"),
"{error}"
);
}
/// Every status the CLI *does* accept reaches `Order::search`.
///
/// Guards the other half: a refusal that also rejected valid input would
/// pass the test above and break the command.
#[tokio::test]
async fn every_order_status_is_accepted_as_a_filter() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
seed_order(&database, "default").await;
let mut reader: &[u8] = &[];
for status in OrderStatus::ALL {
run_order_command(
OrderCommand::List {
profile: None,
account_id: None,
status: Some(status.as_str().to_string()),
identifier: None,
identifier_contains: None,
cert_serial: None,
expiring_in: None,
hide_superseded: false,
limit: DEFAULT_LIMIT,
offset: 0,
json: false,
},
true,
Palette::plain(),
&mut reader,
&Config::default(),
database.clone(),
)
.await
.unwrap_or_else(|error| panic!("--status {status} was refused: {error}"));
}
}
/// A helper for the expiry arm: `order list` with only the flags under
/// test, run to completion.
#[allow(clippy::too_many_arguments)]
async fn list_with(
expiring_in: Option<u64>,
account_id: Option<&str>,
status: Option<&str>,
identifier: Option<&str>,
identifier_contains: Option<&str>,
cert_serial: Option<&str>,
hide_superseded: bool,
json: bool,
database: Arc<Database>,
) -> Result<(), CliError> {
let mut reader: &[u8] = &[];
run_order_command(
OrderCommand::List {
profile: None,
account_id: account_id.map(str::to_string),
status: status.map(str::to_string),
identifier: identifier.map(str::to_string),
identifier_contains: identifier_contains.map(str::to_string),
cert_serial: cert_serial.map(str::to_string),
expiring_in,
hide_superseded,
limit: DEFAULT_LIMIT,
offset: 0,
json,
},
true,
Palette::plain(),
&mut reader,
&Config::default(),
database,
)
.await
}
/// The expiry listing, both output branches, with a row something has
/// replaced and a row nothing has.
#[tokio::test]
async fn the_expiring_arm_lists_and_renders_both_ways() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
let acct = crate::testutil::account_id(&database).await;
crate::testutil::issued_order(&database, "default", acct, &["a.example.com"], 3).await;
crate::testutil::issued_order(&database, "default", acct, &["b.example.com"], 5).await;
// Renews the first, so one row carries the annotation and one does not.
crate::testutil::issued_order(&database, "default", acct, &["a.example.com"], 90).await;
for json in [false, true] {
list_with(
Some(30),
None,
None,
None,
None,
None,
false,
json,
database.clone(),
)
.await
.unwrap();
// ...and with the replaced row filtered out.
list_with(
Some(30),
None,
None,
None,
None,
None,
true,
json,
database.clone(),
)
.await
.unwrap();
}
}
/// Both queries take the same window, and a nonsense one is corrected
/// rather than handed to SQL — where `LIMIT -1` means *no limit* in SQLite.
/// `--expiring-in` is included on purpose: the window is the one flag that
/// means the same thing on both, so unlike `--status` it is not refused
/// beside it.
#[tokio::test]
async fn both_listings_take_a_window_and_clamp_a_nonsense_one() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
seed_order(&database, "default").await;
let mut reader: &[u8] = &[];
for expiring_in in [None, Some(30)] {
for (limit, offset, json) in
[(1, 0, false), (1, 1, false), (1, 0, true), (0, -5, false)]
{
run_order_command(
OrderCommand::List {
profile: None,
account_id: None,
status: None,
identifier: None,
identifier_contains: None,
cert_serial: None,
expiring_in,
hide_superseded: false,
limit,
offset,
json,
},
true,
Palette::plain(),
&mut reader,
&Config::default(),
database.clone(),
)
.await
.unwrap_or_else(|error| {
panic!(
"--expiring-in {expiring_in:?} --limit {limit} --offset {offset}: {error}"
)
});
}
}
}
/// The flag combinations refused **by name** beside `--expiring-in`.
///
/// `--status`, `--account-id`, `--identifier`, `--identifier-contains` and
/// `--cert-serial` do not apply to the expiry query, and `--hide-superseded`
/// has no annotation to filter on without it. Each is refused rather than
/// ignored for `--status`'s own reason: an argument silently dropped answers
/// with rows that look like it was honoured.
#[tokio::test]
async fn the_flags_that_do_not_compose_with_expiring_in_are_refused_by_name() {
let database = Arc::new(Database::connect_in_memory().await.unwrap());
seed_order(&database, "default").await;
let error = list_with(
Some(30),
None,
Some("valid"),
None,
None,
None,
false,
false,
database.clone(),
)
.await
.unwrap_err();
assert!(error.message.contains("--status"), "{error}");
assert!(error.message.contains("--expiring-in"), "{error}");
// Contradictory flags are the operator's to fix: exit 3.
assert_eq!(error.kind(), CliErrorKind::BadRequest);
let error = list_with(
Some(30),
Some("acct-1"),
None,
None,
None,
None,
false,
false,
database.clone(),
)
.await
.unwrap_err();
assert!(error.message.contains("--account-id"), "{error}");
assert!(error.message.contains("--expiring-in"), "{error}");
let error = list_with(
None,
None,
None,
None,
None,
None,
true,
false,
database.clone(),
)
.await
.unwrap_err();
assert!(error.message.contains("--hide-superseded"), "{error}");
assert!(error.message.contains("--expiring-in"), "{error}");
// The name and serial filters are refused beside it too, each named.
for (identifier, contains, serial, needle) in [
(Some("a.example.com"), None, None, "--identifier"),
(None, Some("example"), None, "--identifier-contains"),
(None, None, Some("deadbeef"), "--cert-serial"),
] {
let error = list_with(
Some(30),
None,
None,
identifier,
contains,
serial,
false,
false,
database.clone(),
)
.await
.unwrap_err();
assert!(error.message.contains(needle), "{error}");
assert!(error.message.contains("--expiring-in"), "{error}");
}
// And the ordinary listing is untouched by any of it.
list_with(
None,
None,
Some("valid"),
Some("a.example.com"),
None,
None,
false,
false,
database,
)
.await
.unwrap();
}
}