Debian Codegraph @

tests/integration/common.rs

raw
1 #![allow(unused)]
2
3 use std::borrow::Borrow;
4 use std::collections::BTreeMap;
5 use std::collections::BTreeSet;
6 use std::ffi::OsStr;
7 use std::ffi::OsString;
8 use std::fs::File;
9 use std::path::Path;
10 use std::path::PathBuf;
11 use std::process::Output;
12 use std::sync::atomic::AtomicUsize;
13 use std::sync::atomic::Ordering;
14
15 use anyhow::anyhow;
16 use anyhow::Context;
17
18 use assert_cmd::Command;
19
20 use chrono::DateTime;
21 use chrono::Duration;
22 use chrono::TimeZone;
23 use chrono::Utc;
24
25 use sequoia_openpgp as openpgp;
26 use openpgp::Cert;
27 use openpgp::Fingerprint;
28 use openpgp::KeyHandle;
29 use openpgp::Result;
30 use openpgp::cert::CertParser;
31 use openpgp::packet::Signature;
32 use openpgp::packet::UserID;
33 use openpgp::parse::Parse;
34 use openpgp::policy::NullPolicy;
35 use openpgp::policy::StandardPolicy;
36 use openpgp::serialize::Serialize;
37
38 use tempfile::TempDir;
39
40 pub const STANDARD_POLICY: &StandardPolicy = &StandardPolicy::new();
41 pub const NULL_POLICY: &NullPolicy = unsafe { &NullPolicy::new() };
42
43 pub fn artifact(filename: &str) -> PathBuf {
44 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
45 .join("tests").join("data").join(filename)
46 }
47
48 pub fn artifact_s(filename: &str) -> String {
49 artifact(filename).display().to_string()
50 }
51
52 // Returns the power set excluding the empty set.
53 pub fn power_set<T: Clone>(set: &[T]) -> Vec<Vec<T>> {
54 let mut power_set: Vec<Vec<T>> = Vec::new();
55 for element in set.iter() {
56 power_set.extend(
57 power_set.clone().into_iter().map(|mut v: Vec<T>| {
58 v.push(element.clone());
59 v
60 }));
61 power_set.push(vec![ element.clone() ]);
62 }
63 power_set
64 }
65
66 /// Returns the time formatted as an ISO 8106 string.
67 pub fn time_as_string(t: DateTime<Utc>) -> String {
68 t.format("%Y-%m-%dT%H:%M:%SZ").to_string()
69 }
70
71 /// Extracts fingerprints from human readable output and returns a map
72 /// from fingerprint to count.
73 pub fn extract_fingerprints(output: &str) -> BTreeMap<Fingerprint, usize> {
74 use regex::Regex;
75
76 // v6 and v4 fingerprints without spaces.
77 let re = Regex::new(r"(\b[A-F0-9]{64}\b)|(\b[A-F0-9]{40}\b)").unwrap();
78
79 let mut fprs: Vec<(Fingerprint, usize)> = re
80 .captures_iter(output).map(|c| c.extract())
81 .map(|(_, [fpr])| {
82 (fpr.parse::<Fingerprint>().expect("valid fingerprint"), 1)
83 })
84 .collect();
85
86 fprs.sort();
87 fprs.dedup_by(|a, b| {
88 if a.0 == b.0 {
89 // a is removed
90 b.1 += a.1;
91 true
92 } else {
93 false
94 }
95 });
96
97 fprs.into_iter().collect()
98 }
99
100 pub fn check_fingerprints<B>(output: &str,
101 expected: B)
102 where B: Into<BTreeMap<Fingerprint, usize>>
103 {
104 let expected = expected.into();
105
106 let got = extract_fingerprints(output);
107
108 if got == expected {
109 return;
110 }
111
112 let mut bad = false;
113 for (fpr, got_count) in got.iter() {
114 let expected_count = expected.get(fpr).unwrap_or(&0);
115 if got_count != expected_count {
116 eprintln!("Got {} {} times, but expected it {} times",
117 fpr, got_count, expected_count);
118 bad = true;
119 }
120 }
121 for (fpr, expected_count) in expected.iter() {
122 let got_count = got.get(fpr).unwrap_or(&0);
123 if *got_count == 0 && *expected_count > 0 {
124 eprintln!("Got {} {} times, but expected it {} times",
125 fpr, got_count, expected_count);
126 bad = true;
127 }
128 }
129
130 if bad {
131 eprintln!("Output is:\n{}", output);
132 panic!("Fingerprint mismatch");
133 }
134 }
135
136 pub fn check_certifications(
137 certs: &[Cert],
138 expected_certifications: &[
139 // Certifier, cert, user ID, trust amount, count.
140 (Fingerprint, Fingerprint, &str, usize, usize)
141 ])
142 {
143 let got: Vec<(&Cert, UserID, Signature)> = certs.into_iter()
144 .flat_map(|cert| {
145 cert.userids()
146 .flat_map(|ua| {
147 ua.certifications()
148 .map(|certification| {
149 (cert,
150 ua.userid().clone(),
151 certification.clone())
152 })
153 .collect::<Vec<_>>()
154 })
155 .collect::<Vec<_>>()
156 })
157 .collect();
158 eprintln!("Have {} certifications", got.len());
159
160 let certs: BTreeMap<Fingerprint, &Cert> = certs
161 .into_iter()
162 .map(|cert| {
163 (cert.fingerprint(), cert)
164 })
165 .collect();
166
167 let mut got: Vec<_> = got
168 .into_iter()
169 .map(|(cert, userid, sig)| {
170 let issuers = sig.get_issuers();
171 for issuer in issuers.iter() {
172 let fpr = match issuer {
173 KeyHandle::Fingerprint(fpr) => fpr,
174 KeyHandle::KeyID(keyid) => {
175 eprintln!("Skipping key ID: {}", keyid);
176 continue;
177 }
178 };
179
180 if let Some(certifier) = certs.get(fpr) {
181 if let Ok(_) = sig.verify_userid_binding(
182 certifier.primary_key().key(),
183 cert.primary_key().key(),
184 &userid)
185 {
186 return (certifier, cert, userid, sig);
187 }
188 }
189 }
190
191 panic!("Unable to find certifier for certification of {}, {}; \
192 alleged issuers: {}",
193 cert.fingerprint(),
194 String::from_utf8_lossy(userid.value()),
195 issuers
196 .iter()
197 .map(|i| i.to_string())
198 .collect::<Vec<String>>()
199 .join(", "));
200 })
201 .map(|(certifier, cert, userid, sig)| {
202 // Get it in to a similar form as expected.
203 let (_depth, amount) = sig.trust_signature()
204 .unwrap_or((0, sequoia_wot::FULLY_TRUSTED as u8));
205
206 eprintln!("Certification: {} on {}, {}; amount: {}",
207 certifier.fingerprint(),
208 cert.fingerprint(),
209 String::from_utf8_lossy(userid.value()),
210 amount);
211
212 (certifier.fingerprint(),
213 cert.fingerprint(),
214 String::from_utf8_lossy(userid.value()).to_string(),
215 amount as usize,
216 // Count.
217 1)
218 })
219 .collect();
220
221 got.sort();
222 got.dedup_by(
223 |(a_certifier, a_cert, a_userid, a_amount, a_count),
224 (b_certifier, b_cert, b_userid, b_amount, b_count)|
225 {
226 if a_certifier == b_certifier
227 && a_cert == b_cert
228 && a_userid == b_userid
229 && a_amount == b_amount
230 {
231 *b_count += *a_count;
232 true
233 } else {
234 false
235 }
236 });
237 let got = BTreeSet::from_iter(got.into_iter());
238
239 let expected = BTreeSet::from_iter(
240 expected_certifications.iter()
241 .map(|(certifier, cert, userid, amount, count)| {
242 (certifier.clone(),
243 cert.clone(),
244 userid.to_string(),
245 *amount,
246 *count)
247 }));
248
249 eprintln!();
250
251 let mut bad = false;
252 for (certifier, cert, userid, amount, count) in expected.difference(&got) {
253 let certifier_uid = certs.get(certifier).unwrap()
254 .userids().map(|ua| ua.userid()).next().unwrap().clone();
255
256 eprintln!("Expected {} certification(s) by {}, {} for {}, {}, amount: {}",
257 count,
258 certifier,
259 String::from_utf8_lossy(certifier_uid.value()),
260 cert, userid, amount);
261 bad = true;
262 }
263 for (certifier, cert, userid, amount, count) in got.difference(&expected) {
264 let certifier_uid = certs.get(certifier).unwrap()
265 .userids().map(|ua| ua.userid()).next().unwrap().clone();
266
267 eprintln!("Unexpectedly got {} certification(s) by {}, {} for {}, {}, amount: {}",
268 count,
269 certifier,
270 String::from_utf8_lossy(certifier_uid.value()),
271 cert, userid, amount);
272 bad = true;
273 }
274
275 if bad {
276 panic!("Certification mismatch.");
277 }
278 }
279
280 /// Designates a certificate by path, or by key handle.
281 #[derive(Clone, Debug)]
282 pub enum FileOrKeyHandle {
283 FileOrStdin(PathBuf),
284 KeyHandle((KeyHandle, OsString)),
285 }
286
287 impl From<&str> for FileOrKeyHandle {
288 fn from(path: &str) -> Self {
289 PathBuf::from(path).into()
290 }
291 }
292
293 impl From<String> for FileOrKeyHandle {
294 fn from(path: String) -> Self {
295 PathBuf::from(path).into()
296 }
297 }
298
299 impl From<&Path> for FileOrKeyHandle {
300 fn from(path: &Path) -> Self {
301 path.to_path_buf().into()
302 }
303 }
304
305 impl From<&PathBuf> for FileOrKeyHandle {
306 fn from(path: &PathBuf) -> Self {
307 path.clone().into()
308 }
309 }
310
311 impl From<PathBuf> for FileOrKeyHandle {
312 fn from(path: PathBuf) -> Self {
313 FileOrKeyHandle::FileOrStdin(path.into())
314 }
315 }
316
317 impl From<&KeyHandle> for FileOrKeyHandle {
318 fn from(kh: &KeyHandle) -> Self {
319 FileOrKeyHandle::KeyHandle((kh.clone(), kh.to_string().into()))
320 }
321 }
322
323 impl From<KeyHandle> for FileOrKeyHandle {
324 fn from(kh: KeyHandle) -> Self {
325 let s = kh.to_string().into();
326 FileOrKeyHandle::KeyHandle((kh, s))
327 }
328 }
329
330 impl From<&Fingerprint> for FileOrKeyHandle {
331 fn from(fpr: &Fingerprint) -> Self {
332 KeyHandle::from(fpr).into()
333 }
334 }
335
336 impl From<Fingerprint> for FileOrKeyHandle {
337 fn from(fpr: Fingerprint) -> Self {
338 KeyHandle::from(fpr).into()
339 }
340 }
341
342 impl From<&FileOrKeyHandle> for FileOrKeyHandle {
343 fn from(h: &FileOrKeyHandle) -> Self {
344 h.clone()
345 }
346 }
347
348 impl AsRef<OsStr> for FileOrKeyHandle {
349 fn as_ref(&self) -> &OsStr {
350 match self {
351 FileOrKeyHandle::FileOrStdin(file) => file.as_os_str(),
352 FileOrKeyHandle::KeyHandle((kh, s)) => s.as_os_str(),
353 }
354 }
355 }
356
357 impl FileOrKeyHandle {
358 /// Returns whether this contains a `FileOrStdin`.
359 pub fn is_file(&self) -> bool {
360 match self {
361 FileOrKeyHandle::FileOrStdin(_) => true,
362 FileOrKeyHandle::KeyHandle(_) => false,
363 }
364 }
365
366 /// Returns whether this contains a `KeyHandle`.
367 pub fn is_key_handle(&self) -> bool {
368 match self {
369 FileOrKeyHandle::FileOrStdin(_) => false,
370 FileOrKeyHandle::KeyHandle(_) => true,
371 }
372 }
373 }
374
375 /// Designates data by path, or bytes (which are fed to stdin).
376 #[derive(Clone, Debug)]
377 pub enum FileOrBytes {
378 FileOrStdin(PathBuf),
379 Bytes(Vec<u8>),
380 }
381
382 impl From<&[u8]> for FileOrBytes {
383 fn from(s: &[u8]) -> Self {
384 FileOrBytes::Bytes(s.to_vec())
385 }
386 }
387
388 impl From<Vec<u8>> for FileOrBytes {
389 fn from(s: Vec<u8>) -> Self {
390 FileOrBytes::Bytes(s)
391 }
392 }
393
394 impl From<&Vec<u8>> for FileOrBytes {
395 fn from(s: &Vec<u8>) -> Self {
396 FileOrBytes::Bytes(s.clone())
397 }
398 }
399
400 impl From<&Path> for FileOrBytes {
401 fn from(path: &Path) -> Self {
402 path.to_path_buf().into()
403 }
404 }
405
406 impl From<&PathBuf> for FileOrBytes {
407 fn from(path: &PathBuf) -> Self {
408 path.clone().into()
409 }
410 }
411
412 impl From<PathBuf> for FileOrBytes {
413 fn from(path: PathBuf) -> Self {
414 FileOrBytes::FileOrStdin(path.into())
415 }
416 }
417
418 impl From<&FileOrBytes> for FileOrBytes {
419 fn from(h: &FileOrBytes) -> Self {
420 h.clone()
421 }
422 }
423
424 impl FileOrBytes {
425 /// Returns whether this contains a `FileOrStdin`.
426 pub fn is_file(&self) -> bool {
427 match self {
428 FileOrBytes::FileOrStdin(_) => true,
429 FileOrBytes::Bytes(_) => false,
430 }
431 }
432
433 /// Returns whether this contains bytes.
434 pub fn is_bytes(&self) -> bool {
435 match self {
436 FileOrBytes::FileOrStdin(_) => false,
437 FileOrBytes::Bytes(_) => true,
438 }
439 }
440 }
441
442 /// An enum for user ID arguments.
443 #[derive(Debug, Clone)]
444 pub enum UserIDArg<'a> {
445 UserID(&'a str),
446 Email(&'a str),
447 Name(&'a str),
448 AddUserID(&'a str),
449 AddEmail(&'a str),
450 ByEmail(&'a str),
451 }
452
453 impl<'a> From<&'a str> for UserIDArg<'a> {
454 fn from(userid: &'a str) -> Self {
455 UserIDArg::UserID(userid)
456 }
457 }
458
459 impl<'a> From<&'a &'a str> for UserIDArg<'a> {
460 fn from(userid: &'a &'a str) -> Self {
461 UserIDArg::UserID(userid)
462 }
463 }
464
465 impl<'a> From<&'a String> for UserIDArg<'a> {
466 fn from(userid: &'a String) -> Self {
467 UserIDArg::UserID(&userid)
468 }
469 }
470
471 impl UserIDArg<'_> {
472 /// Return the raw string.
473 pub fn raw(&self) -> &str {
474 match self {
475 UserIDArg::UserID(s)
476 | UserIDArg::Email(s)
477 | UserIDArg::Name(s)
478 | UserIDArg::AddUserID(s)
479 | UserIDArg::AddEmail(s)
480 | UserIDArg::ByEmail(s) =>
481 {
482 s
483 }
484 }
485 }
486
487 /// Add the argument to a `Command`.
488 pub fn as_arg(&self, cmd: &mut Command) {
489 match self {
490 UserIDArg::UserID(userid) =>
491 cmd.arg("--userid").arg(userid),
492 UserIDArg::Email(email) =>
493 cmd.arg("--email").arg(email),
494 UserIDArg::Name(name) =>
495 cmd.arg("--name").arg(name),
496 UserIDArg::AddUserID(userid) =>
497 cmd.arg("--add-userid").arg(userid),
498 UserIDArg::AddEmail(email) =>
499 cmd.arg("--add-email").arg(email),
500 UserIDArg::ByEmail(email) =>
501 cmd.arg("--userid-by-email").arg(email),
502 };
503 }
504
505 /// Add the argument to a `Command` as a cert designator.
506 ///
507 /// Note: only a subset of user ID arguments are expressible as
508 /// cert designators.
509 pub fn as_cert_designator(&self, cmd: &mut Command) {
510 match self {
511 UserIDArg::UserID(userid) =>
512 cmd.arg("--cert-userid").arg(userid),
513 UserIDArg::Email(email) =>
514 cmd.arg("--cert-email").arg(email),
515 UserIDArg::Name(name) =>
516 unreachable!(),
517 UserIDArg::AddUserID(userid) =>
518 unreachable!(),
519 UserIDArg::AddEmail(email) =>
520 unreachable!(),
521 UserIDArg::ByEmail(userid) =>
522 unreachable!(),
523 };
524 }
525 }
526
527 impl std::fmt::Display for UserIDArg<'_> {
528 fn fmt(&self, f: &mut std::fmt::Formatter<'_>)
529 -> std::result::Result<(), std::fmt::Error>
530 {
531 write!(f, "{}", self.raw())
532 }
533 }
534
535 /// An enum for user ID arguments.
536 #[derive(Debug, Clone)]
537 pub enum CertArg<'a> {
538 Stdin(),
539 File(PathBuf),
540 Cert(KeyHandle),
541 UserID(&'a str),
542 Email(&'a str),
543 Domain(&'a str),
544 Grep(&'a str),
545 Special(&'a str),
546 Self_(),
547 }
548
549 impl From<PathBuf> for CertArg<'_> {
550 fn from(path: PathBuf) -> Self {
551 CertArg::File(path)
552 }
553 }
554
555 impl<'a> From<&'a Path> for CertArg<'_> {
556 fn from(path: &'a Path) -> Self {
557 CertArg::File(path.to_path_buf())
558 }
559 }
560
561 impl From<KeyHandle> for CertArg<'_> {
562 fn from(kh: KeyHandle) -> Self {
563 CertArg::Cert(kh)
564 }
565 }
566
567 impl<'a> From<&'a KeyHandle> for CertArg<'_> {
568 fn from(kh: &'a KeyHandle) -> Self {
569 CertArg::Cert(kh.clone())
570 }
571 }
572
573 impl From<Fingerprint> for CertArg<'_> {
574 fn from(fpr: Fingerprint) -> Self {
575 CertArg::Cert(fpr.into())
576 }
577 }
578
579 impl<'a> From<&'a Fingerprint> for CertArg<'_> {
580 fn from(fpr: &'a Fingerprint) -> Self {
581 CertArg::Cert(fpr.into())
582 }
583 }
584
585 impl<'a> From<&'a Cert> for CertArg<'_> {
586 fn from(cert: &'a Cert) -> Self {
587 CertArg::Cert(cert.key_handle())
588 }
589 }
590
591 impl CertArg<'_> {
592 /// Add the argument to a `Command`.
593 pub fn as_arg<'a, P>(&self, cmd: &mut Command, prefix: P)
594 where P: Into<Option<&'a str>>
595 {
596 cmd.args(self.raw(prefix));
597 }
598
599 pub fn raw<'a, P>(&self, prefix: P) -> Vec<String>
600 where P: Into<Option<&'a str>>
601 {
602 let prefix = prefix.into();
603
604 let s;
605 let (suffix, value) = match self {
606 CertArg::Stdin() => (Some("file"), Some("-")),
607 CertArg::File(p) => {
608 s = p.display().to_string();
609 (Some("file"), Some(&s[..]))
610 }
611 CertArg::Cert(kh) => {
612 s = kh.to_string();
613 if prefix.is_none() {
614 (Some("cert"), Some(&s[..]))
615 } else {
616 (None, Some(&s[..]))
617 }
618 }
619 CertArg::UserID(userid) => (Some("userid"), Some(*userid)),
620 CertArg::Email(email) => (Some("email"), Some(*email)),
621 CertArg::Domain(domain) => (Some("domain"), Some(*domain)),
622 CertArg::Grep(pattern) => (Some("grep"), Some(*pattern)),
623 CertArg::Special(special) => (Some("special"), Some(*special)),
624 CertArg::Self_() => (Some("self"), None),
625 };
626
627 let arg = match (prefix, suffix) {
628 (Some(prefix), Some(suffix)) => {
629 format!("--{}-{}", prefix, suffix)
630 }
631 (None, Some(suffix)) => {
632 format!("--{}", suffix)
633 }
634 (Some(prefix), None) => {
635 format!("--{}", prefix)
636 }
637 (None, None) => panic!("No prefix and no suffix specified"),
638 };
639
640 if let Some(value) = value {
641 vec![ arg, value.to_string() ]
642 } else {
643 vec![ arg ]
644 }
645 }
646 }
647
648 impl std::fmt::Display for CertArg<'_> {
649 fn fmt(&self, f: &mut std::fmt::Formatter<'_>)
650 -> std::result::Result<(), std::fmt::Error>
651 {
652 write!(f, "{}", self.raw(None).join(" "))
653 }
654 }
655
656 // When calling a function like `Sq::key_generate` that has an `&[U]
657 // where U: Into<UserIDArg` parameter, we can't pass `&[]`, because
658 // rust can't infer a type for `U`. Instead, we can use this.
659 pub const NO_USERIDS: &[UserIDArg] = &[];
660
661 pub struct Sq {
662 base: TempDir,
663 // Whether to preserve the directory on exit. Normally we clean
664 // it up, but preserving it can simplify debugging when a test
665 // fails.
666 preserve: bool,
667 home: PathBuf,
668
669 /// The working directory to invoke commands in.
670 working_dir: PathBuf,
671
672 policy: PathBuf,
673 certd: PathBuf,
674 now: std::time::SystemTime,
675 scratch: AtomicUsize,
676 }
677
678 impl Drop for Sq {
679 fn drop(&mut self) {
680 if self.preserve {
681 self.preserve = false;
682
683 match TempDir::new() {
684 Ok(tmp) => {
685 let base = std::mem::replace(&mut self.base, tmp);
686 let path = base.into_path();
687 eprintln!("Preserving state in {}", path.display());
688 }
689 Err(err) => {
690 eprintln!("Error preserving state in {}: {}",
691 self.base.path().display(), err);
692 }
693 }
694 }
695 }
696 }
697
698 impl Sq {
699 /// Creates a new Sq context in a new, emphemeral home directory.
700 /// The clock is set to the specified time.
701 pub fn at_str(t: &str) -> Self {
702 if let Ok(d) = chrono::NaiveDateTime::parse_from_str(t, "%Y-%m-%dT%H:%M:%S") {
703 return Self::at(Utc.from_utc_datetime(&d).into());
704 }
705 if let Ok(d) = chrono::NaiveDate::parse_from_str(t, "%Y-%m-%d") {
706 let pad_date_with = chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap();
707 return Self::at(Utc.from_utc_datetime(&d.and_time(pad_date_with)).into());
708 }
709 panic!("Invalid timestamp, must be YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS");
710 }
711
712 /// Creates a new Sq context in a new, emphemeral home directory.
713 /// The clock is set to the specified time.
714 pub fn at(now: std::time::SystemTime) -> Self {
715 let base = TempDir::new()
716 .expect("can create a temporary directory");
717 let home = base.path().join("home");
718
719 let working_dir = base.path().join("working-dir");
720 std::fs::create_dir_all(&working_dir).unwrap();
721
722 // Create an empty policy configuration file. We use this
723 // instead of the system-wide policy configuration file, which
724 // might be more strict than what our test vectors expect.
725 let policy = base.path().join("empty-policy.toml");
726 std::fs::write(&policy, "").unwrap();
727
728 let certd = home.join("data").join("pgp.cert.d");
729
730 Sq {
731 base,
732 preserve: false,
733 home,
734 working_dir,
735 policy,
736 certd,
737 now,
738 scratch: 0.into(),
739 }
740 }
741
742 /// Creates a new Sq context in a new, emphemeral home directory.
743 /// The clock is set to the current time.
744 pub fn new() -> Self {
745 // The current time.
746 let mut now = std::time::SystemTime::now();
747 let since_epoch = now.duration_since(std::time::UNIX_EPOCH).unwrap();
748 now = now - std::time::Duration::new(0, since_epoch.subsec_nanos());
749
750 Self::at(now)
751 }
752
753 /// Preserves the files on exit.
754 ///
755 /// Normally we clean delete all files and directories. This
756 /// suppresses that behavior. Preserving the state can facilitate
757 /// debugging. Normally, you'll only enable this to debug a test,
758 /// and then disable it again.
759 pub fn preserve(&mut self) {
760 self.preserve = true;
761 }
762
763 /// Returns the base directory.
764 ///
765 /// The sequoia home directory is under the `home` subdirectory.
766 /// The rest can be used as scratch space.
767 pub fn base(&self) -> &Path {
768 self.base.path()
769 }
770
771 /// Returns the home directory.
772 pub fn home(&self) -> &Path {
773 &self.home
774 }
775
776 /// Returns the working directory.
777 pub fn working_dir(&self) -> &Path {
778 &self.working_dir
779 }
780
781 /// Returns the path to the cert.d.
782 pub fn certd(&self) -> &Path {
783 &self.certd
784 }
785
786 /// Returns the path to the test data.
787 pub fn test_data(&self) -> PathBuf {
788 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
789 .join("tests").join("data")
790 }
791
792 /// Returns the scratch directory.
793 pub fn scratch_dir(&self) -> PathBuf {
794 let dir = self.home.join("scratch");
795 std::fs::create_dir_all(&dir)
796 .expect("can create scratch directory");
797 dir
798 }
799
800 /// Returns a new scratch file.
801 ///
802 /// The file is guaranteed to not exist, but it isn't actually
803 /// created.
804 pub fn scratch_file<'a, S>(&self, name: S) -> PathBuf
805 where S: Into<Option<&'a str>>
806 {
807 let name = name.into();
808
809 let name_;
810 let name = if let Some(name) = name {
811 name_ = name.chars()
812 .map(|c| {
813 if c.is_ascii_alphanumeric() {
814 c
815 } else {
816 '-'
817 }
818 })
819 .collect::<String>();
820 &name_
821 } else {
822 name.unwrap_or("scratch-file")
823 };
824
825 let dir = self.scratch_dir();
826 loop {
827 let i = self.scratch.fetch_add(1, Ordering::Relaxed);
828 let file = dir.join(format!("{}-{}", i, name));
829 if ! file.exists() {
830 return file;
831 }
832 }
833 }
834
835 /// Returns the current time.
836 pub fn now(&self) -> std::time::SystemTime {
837 self.now
838 }
839
840 /// Returns the current time formatted as an ISO 8106 string.
841 pub fn now_as_string(&self) -> String {
842 time_as_string(self.now.into())
843 }
844
845 /// Advances the clock by `sec` number of seconds.
846 pub fn tick(&mut self, secs: u64)
847 {
848 self.now += std::time::Duration::new(secs, 0);
849 }
850
851 /// Rewinds the clock by `sec` number of seconds.
852 pub fn rewind(&mut self, secs: u64)
853 {
854 self.now -= std::time::Duration::new(secs, 0);
855 }
856
857 /// Returns a command that is set to run `sq`. The home directory
858 /// and time are already set.
859 pub fn command(&self) -> Command {
860 self.command_args(&[])
861 }
862
863 /// Returns a command that is set to run `sq`. The home directory
864 /// and time are already set. The arguments in `pre` are added at
865 /// the beginning of the command line.
866 pub fn command_args(&self, pre: &[&str]) -> Command {
867 let mut cmd = Command::cargo_bin("sq")
868 .expect("can run sq");
869 cmd.current_dir(&self.working_dir);
870 cmd.env("RUST_BACKTRACE", "1");
871 cmd.env("RUST_LOG", "trace");
872 cmd.env("SEQUOIA_CRYPTO_POLICY", &self.policy);
873 for arg in pre {
874 cmd.arg(arg);
875 }
876 cmd.arg("--batch");
877 cmd.arg("--home").arg(self.home());
878 cmd.arg("--time").arg(&self.now_as_string());
879
880 cmd
881 }
882
883 /// Runs the command. If `expect` is `Some`, asserts that the
884 /// command succeeds or fails as per the boolean.
885 pub fn run<E>(&self, mut cmd: Command, expect: E) -> Output
886 where E: Into<Option<bool>>
887 {
888 eprintln!("Running: {}",
889 std::iter::once(cmd.get_program())
890 .chain(cmd.get_args())
891 .map(|arg| {
892 let arg = arg.to_string_lossy();
893 if arg.contains(" ") {
894 format!("{:?}", arg)
895 } else {
896 arg.into_owned()
897 }
898 })
899 .collect::<Vec<_>>()
900 .join(" "));
901
902 let output = cmd.output().expect("can run command");
903 let expect = expect.into();
904 match (output.status.success(), expect) {
905 (true, Some(true)) | (false, Some(false)) | (_, None) => {
906 eprintln!("Exit status:");
907
908 let dump = |id, stream| {
909 let limit = 4096;
910
911 let data = String::from_utf8_lossy(stream)
912 .chars()
913 .collect::<Vec<_>>();
914
915 if data.is_empty() {
916 eprintln!("{}: empty", id);
917 } else {
918 eprintln!("{}: {}{}",
919 id,
920 data.iter().take(limit).collect::<String>(),
921 if data.len() > limit {
922 format!("... {} more bytes",
923 data.len() - limit)
924 } else {
925 "".to_string()
926 });
927 }
928 };
929
930 dump("stdout", &output.stdout);
931 dump("stderr", &output.stderr);
932 }
933 (got, expected) => {
934 let expected = expect.unwrap();
935
936 panic!(
937 "Running {:?}: {}, but should have {}:\n\
938 stdout: {}\n\
939 stderr: {}",
940 cmd,
941 if got { "succeeded" } else { "failed" },
942 if expected { "succeeded" } else { "failed" },
943 &String::from_utf8_lossy(&output.stdout),
944 &String::from_utf8_lossy(&output.stderr));
945 }
946 }
947 output
948 }
949
950 // A helper function that handles a command's output when the
951 // output is a certificate.
952 //
953 // If the command fails, returns an error.
954 //
955 // If `output_file` is `Some`, then reads the key or certificate
956 // from stdin or the specified file, and returns it. Otherwise,
957 // exports the key or certificate, and returns it.
958 //
959 // `is_key` is whether the returned certificate is expected to
960 // include secret key material. If `is_key` is `None`, then it
961 // may or may not (e.g., `sq key subkey delete`, which may delete
962 // the last bit of secret key material, or not).
963 fn handle_cert_output<'a, O, K>(&self, output: Output,
964 cert: FileOrKeyHandle, output_file: O,
965 is_key: K)
966 -> Result<Cert>
967 where
968 O: Into<Option<&'a Path>>,
969 K: Into<Option<bool>>
970 {
971 let output_file = output_file.into();
972 let is_key = is_key.into();
973
974 if output.status.success() {
975 let cert = match (output_file, cert) {
976 (Some(output_file), _) => {
977 // An output file was specified.
978 if output_file == &PathBuf::from("-") {
979 Cert::from_bytes(&output.stdout)
980 .with_context(|| {
981 format!("Importing result from stdout")
982 })
983 .expect("can parse certificate")
984 } else {
985 Cert::from_file(output_file)
986 .with_context(|| {
987 format!("Importing result from the file {}",
988 output_file.display())
989 })
990 .expect("can parse certificate")
991 }
992 }
993 (None, FileOrKeyHandle::KeyHandle((kh, _s))) => {
994 // No output file was specified, input was read
995 // from the certificate store => the updated
996 // certificate is written to the certificate
997 // store.
998 match is_key {
999 None => {
1000 // Try the key store, and then fallback to
1001 // the cert store.
1002 self.key_export_maybe(kh.clone())
1003 .unwrap_or_else(|_| self.cert_export(kh))
1004 }
1005 Some(true) => self.key_export(kh),
1006 Some(false) => self.cert_export(kh),
1007 }
1008 }
1009 (None, FileOrKeyHandle::FileOrStdin(_path)) => {
1010 // No output file was specified, input was read
1011 // from a file => the certificate is written to
1012 // stdout.
1013 Cert::from_bytes(&output.stdout)
1014 .with_context(|| {
1015 format!("Importing result from stdout")
1016 })
1017 .expect("can parse certificate")
1018 }
1019 };
1020
1021 if let Some(is_key) = is_key {
1022 assert_eq!(cert.is_tsk(), is_key);
1023 }
1024
1025 Ok(cert)
1026 } else {
1027 Err(anyhow::anyhow!(format!(
1028 "Failed (expected):\n{}",
1029 String::from_utf8_lossy(&output.stderr))))
1030 }
1031 }
1032
1033
1034 /// Decrypts a message.
1035 pub fn decrypt<M>(&self, args: &[&str], msg: M) -> Vec<u8>
1036 where M: Into<FileOrBytes>,
1037 {
1038 self.decrypt_maybe(args, msg).expect("can decrypt")
1039 }
1040
1041 /// Decrypts a message.
1042 pub fn decrypt_maybe<M>(&self, args: &[&str], msg: M) -> Result<Vec<u8>>
1043 where M: Into<FileOrBytes>,
1044 {
1045 let mut cmd = self.command();
1046 cmd.args([ "decrypt" ]);
1047 for arg in args {
1048 cmd.arg(arg);
1049 }
1050
1051 match msg.into() {
1052 FileOrBytes::FileOrStdin(path) => {
1053 cmd.arg(path);
1054 }
1055 FileOrBytes::Bytes(bytes) => {
1056 cmd.write_stdin(bytes);
1057 }
1058 }
1059
1060 let output = self.run(cmd, None);
1061
1062 if output.status.success() {
1063 Ok(output.stdout.to_vec())
1064 } else {
1065 Err(anyhow::anyhow!("sq decrypt returned an error"))
1066 }
1067 }
1068
1069 /// Encrypts a message.
1070 pub fn encrypt<A, M>(&self, args: &[A], msg: M) -> Vec<u8>
1071 where A: AsRef<str>,
1072 M: Into<FileOrBytes>,
1073 {
1074 self.encrypt_maybe(args, msg).expect("can encrypt")
1075 }
1076
1077 /// Encrypts a message.
1078 pub fn encrypt_maybe<A, M>(&self, args: &[A], msg: M) -> Result<Vec<u8>>
1079 where A: AsRef<str>,
1080 M: Into<FileOrBytes>,
1081 {
1082 let mut cmd = self.command();
1083 cmd.args([ "encrypt" ]);
1084 for arg in args {
1085 cmd.arg(arg.as_ref());
1086 }
1087
1088 if ! args.iter().any(|a| a.as_ref().starts_with("--signer")) {
1089 cmd.arg("--without-signature");
1090 }
1091
1092 match msg.into() {
1093 FileOrBytes::FileOrStdin(path) => {
1094 cmd.arg(path);
1095 }
1096 FileOrBytes::Bytes(bytes) => {
1097 cmd.write_stdin(bytes);
1098 }
1099 }
1100
1101 let output = self.run(cmd, None);
1102
1103 if output.status.success() {
1104 Ok(output.stdout.to_vec())
1105 } else {
1106 Err(anyhow::anyhow!("sq encrypt returned an error"))
1107 }
1108 }
1109
1110 /// Generates a new key.
1111 ///
1112 /// The certificate is not imported into the cert store or key
1113 /// store, but saved in a file.
1114 ///
1115 /// Returns the certificate, the certificate's filename, and the
1116 /// revocation certificate's filename.
1117 pub fn key_generate<'a, U>(&self,
1118 extra_args: &[&str],
1119 userids: &[U])
1120 -> (Cert, PathBuf, PathBuf)
1121 where U: Into<UserIDArg<'a>> + Clone
1122 {
1123 let userids: Vec<UserIDArg> = userids.iter()
1124 .cloned()
1125 .map(|u| u.into())
1126 .collect();
1127
1128 let mut cmd = self.command();
1129 cmd.args([ "key", "generate", "--own-key" ]);
1130
1131 if ! extra_args.contains(&"--new-password-file") {
1132 cmd.arg("--without-password");
1133 }
1134
1135 for arg in extra_args {
1136 cmd.arg(arg);
1137 }
1138
1139 let any_userids = ! userids.is_empty()
1140 || extra_args.iter().any(|a| a.starts_with("--name")
1141 || a.starts_with("--email")
1142 || a.starts_with("--userid"));
1143 if ! any_userids {
1144 cmd.arg("--no-userids");
1145 } else {
1146 for userid in userids.iter() {
1147 userid.as_arg(&mut cmd);
1148 }
1149 }
1150
1151 let cert_filename = self.scratch_file(
1152 userids.get(0).map(|u| format!("{}-cert", u.raw())).as_deref());
1153 cmd.arg("--output").arg(&cert_filename);
1154
1155 let rev_filename = self.scratch_file(
1156 userids.get(0).map(|u| format!("{}-rev", u.raw())).as_deref());
1157 cmd.arg("--rev-cert").arg(&rev_filename);
1158
1159 let output = self.run(cmd, Some(true));
1160
1161 let cert = Cert::from_file(&cert_filename)
1162 .expect("can parse certificate");
1163 assert!(cert.is_tsk());
1164
1165 (cert, cert_filename, rev_filename)
1166 }
1167
1168 /// Run `sq key rotate`.
1169 ///
1170 /// If `output_file` is not `None`, then it is parsed and
1171 /// returned. Otherwise, an empty vector is returned.
1172 pub fn try_key_rotate<'a, O>(&self, extra_args: &[&str],
1173 cert: CertArg,
1174 output_file: O)
1175 -> Result<Vec<Cert>>
1176 where O: Into<Option<&'a Path>>,
1177 {
1178 let mut cmd = self.command();
1179 cmd.args([ "key", "rotate" ]);
1180 for arg in extra_args {
1181 cmd.arg(arg);
1182 }
1183 if ! extra_args.contains(&"--new-password-file") {
1184 cmd.arg("--without-password");
1185 }
1186 if let Some(cert) = cert.into() {
1187 cert.as_arg(&mut cmd, "cert");
1188 }
1189
1190 let output = self.run(cmd, None);
1191 if output.status.success() {
1192 if let Some(output_file) = output_file.into() {
1193 let parser = if PathBuf::from("-").as_path() == output_file {
1194 CertParser::from_bytes(&output.stdout)
1195 .expect("can parse certificate")
1196 } else {
1197 CertParser::from_file(&output_file)
1198 .expect("can parse certificate")
1199 };
1200 parser.collect::<Result<Vec<_>>>()
1201 } else {
1202 // We don't try to figure out what was certificated,
1203 // but just return an empty vector.
1204 Ok(Vec::new())
1205 }
1206 } else {
1207 Err(anyhow::anyhow!(
1208 "Failed: {}",
1209 String::from_utf8_lossy(&output.stderr).to_string()))
1210 }
1211 }
1212
1213 /// Run `sq key rotate`.
1214 ///
1215 /// If `output_file` is not `None`, then it is parsed and
1216 /// returned. Otherwise, an empty vector is returned.
1217 pub fn key_rotate<'a, O>(&self, extra_args: &[&str],
1218 cert: CertArg,
1219 output_file: O)
1220 -> Vec<Cert>
1221 where O: Into<Option<&'a Path>>,
1222 {
1223 self.try_key_rotate(extra_args, cert, output_file)
1224 .expect("success")
1225 }
1226
1227 /// Run `sq inspect` and return stdout.
1228 pub fn inspect<H>(&self, handle: H) -> String
1229 where H: Into<FileOrKeyHandle>
1230 {
1231 let mut cmd = self.command();
1232 cmd.arg("inspect");
1233 match handle.into() {
1234 FileOrKeyHandle::FileOrStdin(path) => {
1235 cmd.arg(path);
1236 }
1237 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1238 cmd.arg("--cert").arg(&s);
1239 }
1240 };
1241
1242 let output = self.run(cmd, Some(true));
1243 String::from_utf8_lossy(&output.stdout).to_string()
1244 }
1245
1246 /// Delete the specified key.
1247 pub fn try_key_delete<'a, H, Q>(&self,
1248 cert_handle: H,
1249 output_file: Q)
1250 -> Result<Cert>
1251 where H: Into<FileOrKeyHandle>,
1252 Q: Into<Option<&'a Path>>,
1253 {
1254 let cert_handle = cert_handle.into();
1255 let output_file = output_file.into();
1256
1257 let mut cmd = self.command();
1258 cmd.arg("key").arg("delete");
1259
1260 match &cert_handle {
1261 FileOrKeyHandle::FileOrStdin(path) => {
1262 cmd.arg("--cert-file").arg(path);
1263 if let Some(output_file) = output_file {
1264 cmd.arg("--output").arg(output_file);
1265 } else {
1266 cmd.arg("--output").arg("-");
1267 }
1268 }
1269 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1270 cmd.arg("--cert").arg(&s);
1271 if let Some(output_file) = output_file {
1272 cmd.arg("--output").arg(output_file);
1273 }
1274 }
1275 };
1276
1277 let output = self.run(cmd, None);
1278 self.handle_cert_output(output, cert_handle, output_file, None)
1279 }
1280
1281 /// Delete the specified key.
1282 pub fn key_delete<'a, H, Q>(&self,
1283 cert_handle: H,
1284 output_file: Q)
1285 -> Cert
1286 where H: Into<FileOrKeyHandle>,
1287 Q: Into<Option<&'a Path>>,
1288 {
1289 self.try_key_delete(cert_handle, output_file)
1290 .expect("success")
1291 }
1292
1293 /// Run `sq key revoked` and return the revocation certificate.
1294 pub fn key_revoke<'a, H, I, Q>(&self,
1295 cert_handle: H,
1296 revoker_handle: I,
1297 reason: &str,
1298 message: &str,
1299 revocation_time: Option<DateTime<Utc>>,
1300 notations: &[(&str, &str)],
1301 output_file: Q)
1302 -> Cert
1303 where H: Into<FileOrKeyHandle>,
1304 I: Into<Option<FileOrKeyHandle>>,
1305 Q: Into<Option<&'a Path>>,
1306 {
1307 let cert_handle = cert_handle.into();
1308 let revoker_handle = revoker_handle.into();
1309 let output_file = output_file.into();
1310
1311 let mut cmd = self.command();
1312 cmd.arg("key").arg("revoke")
1313 .arg("--reason").arg(reason)
1314 .arg("--message").arg(message);
1315
1316 match &cert_handle {
1317 FileOrKeyHandle::FileOrStdin(path) => {
1318 cmd.arg("--cert-file").arg(path);
1319 assert!(output_file.is_some());
1320 }
1321 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1322 cmd.arg("--cert").arg(&s);
1323 }
1324 };
1325 match revoker_handle.as_ref() {
1326 Some(FileOrKeyHandle::FileOrStdin(path)) => {
1327 cmd.arg("--revoker-file").arg(path);
1328 }
1329 Some(FileOrKeyHandle::KeyHandle((_kh, s))) => {
1330 cmd.arg("--revoker").arg(&s);
1331 }
1332 None => (),
1333 };
1334
1335 if let Some(output_file) = output_file {
1336 cmd.arg("--output").arg(output_file);
1337 }
1338
1339 for (k, v) in notations {
1340 cmd.args(["--signature-notation", k, v]);
1341 }
1342
1343 if let Some(time) = revocation_time {
1344 cmd.args([
1345 "--time",
1346 &time.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1347 ]);
1348 }
1349
1350 let output = self.run(cmd, Some(true));
1351 assert!(output.status.success());
1352 self.handle_cert_output(output, cert_handle, output_file, false)
1353 .expect("can parse certificate")
1354 }
1355
1356 /// Imports the specified key into the keystore.
1357 pub fn key_import<P>(&self, path: P)
1358 where P: AsRef<Path>
1359 {
1360 let mut cmd = self.command();
1361 cmd.arg("key").arg("import").arg(path.as_ref());
1362 self.run(cmd, Some(true));
1363 }
1364
1365 /// Runs `sq key list` with the supplied arguments.
1366 pub fn try_key_list(&self, args: &[&str]) -> Result<Vec<u8>> {
1367 let mut cmd = self.command();
1368 cmd.arg("key").arg("list");
1369 for arg in args {
1370 cmd.arg(arg);
1371 }
1372 let output = self.run(cmd, None);
1373 if output.status.success() {
1374 Ok(output.stdout)
1375 } else {
1376 Err(anyhow::anyhow!("sq cert list returned an error"))
1377 }
1378 }
1379
1380 /// Runs `sq key list` with the supplied arguments.
1381 pub fn key_list(&self, args: &[&str]) -> Vec<u8> {
1382 self.try_key_list(args).expect("success")
1383 }
1384
1385 /// Exports the specified key.
1386 pub fn key_export(&self, kh: KeyHandle) -> Cert {
1387 self.key_export_maybe(kh)
1388 .expect("can export key")
1389 }
1390
1391 /// Exports the specified key from the key store.
1392 ///
1393 /// Returns an error if `sq key export` fails. This happens if
1394 /// the certificate is known, but the key store doesn't manage any
1395 /// of its secret key material.
1396 pub fn key_export_maybe(&self, kh: KeyHandle) -> Result<Cert> {
1397 let mut cmd = self.command();
1398 cmd.args([ "key", "export", "--cert", &kh.to_string() ]);
1399 let output = self.run(cmd, None);
1400
1401 if output.status.success() {
1402 Ok(Cert::from_bytes(&output.stdout).expect("can parse certificate"))
1403 } else {
1404 Err(anyhow::anyhow!("sq key export returned an error"))
1405 }
1406 }
1407
1408 /// Change the key's password.
1409 pub fn try_key_password<'a, H, Q>(&self,
1410 cert_handle: H,
1411 old_password_file: Option<&'a Path>,
1412 new_password_file: Option<&'a Path>,
1413 output_file: Q)
1414 -> Result<Cert>
1415 where
1416 H: Into<FileOrKeyHandle>,
1417 Q: Into<Option<&'a Path>>,
1418 {
1419 let cert_handle = cert_handle.into();
1420 let output_file = output_file.into();
1421
1422 let mut cmd = self.command();
1423 cmd.arg("key").arg("password");
1424
1425 if cert_handle.is_file() {
1426 cmd.arg("--cert-file").arg(&cert_handle);
1427 if output_file.is_none() {
1428 cmd.arg("--output").arg("-");
1429 }
1430 } else {
1431 cmd.arg("--cert").arg(&cert_handle);
1432 };
1433
1434 if let Some(p) = old_password_file {
1435 cmd.arg("--password-file").arg(p);
1436 }
1437
1438 if let Some(p) = new_password_file {
1439 cmd.arg("--new-password-file").arg(p);
1440 } else {
1441 cmd.arg("--clear-password");
1442 }
1443
1444 if let Some(output_file) = output_file {
1445 cmd.arg("--output").arg(output_file);
1446 }
1447
1448 let output = self.run(cmd, None);
1449 self.handle_cert_output(output, cert_handle, output_file, true)
1450 }
1451
1452 /// Change the key's password.
1453 pub fn key_password<'a, H, Q>(&self,
1454 cert_handle: H,
1455 old_password_file: Option<&'a Path>,
1456 new_password_file: Option<&'a Path>,
1457 output_file: Q)
1458 -> Cert
1459 where
1460 H: Into<FileOrKeyHandle>,
1461 Q: Into<Option<&'a Path>>,
1462 {
1463 self.try_key_password(
1464 cert_handle, old_password_file, new_password_file, output_file)
1465 .expect("success")
1466 }
1467
1468 /// Calls `sq key bind`.
1469 ///
1470 /// `keyrings` are a list of files to pass to `--keyring`. They
1471 /// usually contain the key to bind.
1472 ///
1473 /// `target` is the certificate that will bind the key.
1474 ///
1475 /// `keys` is the set of keys to bind.
1476 ///
1477 /// The resulting certificate is NOT imported into the key store
1478 /// or the cert store.
1479 pub fn key_subkey_bind_maybe<P, T, K, Q>(&self,
1480 extra_args: &[&str],
1481 keyrings: Vec<P>,
1482 target: T,
1483 keys: Vec<K>,
1484 output_file: Q)
1485 -> Result<Cert>
1486 where
1487 P: AsRef<Path>,
1488 T: Into<FileOrKeyHandle>,
1489 K: Into<KeyHandle>,
1490 Q: AsRef<Path>,
1491 {
1492 let target = target.into();
1493 let output_file = output_file.as_ref();
1494
1495 let mut cmd = self.command();
1496 cmd.arg("key").arg("subkey").arg("bind");
1497
1498 for arg in extra_args {
1499 cmd.arg(arg);
1500 }
1501
1502 for k in keyrings.into_iter() {
1503 cmd.arg("--keyring").arg(k.as_ref());
1504 }
1505
1506 if target.is_file() {
1507 cmd.arg("--cert-file").arg(&target);
1508 } else {
1509 cmd.arg("--cert").arg(&target);
1510 };
1511
1512 assert!(! keys.is_empty());
1513 for k in keys.into_iter() {
1514 let k: KeyHandle = k.into();
1515 cmd.arg("--key").arg(k.to_string());
1516 }
1517
1518 cmd.arg("--output").arg(&output_file);
1519
1520 let output = self.run(cmd, None);
1521 self.handle_cert_output(output, target, output_file, None)
1522 }
1523
1524 /// Calls `sq key bind`.
1525 ///
1526 /// `keyrings` are a list of files to pass to `--keyring`. They
1527 /// usually contain the key to bind.
1528 ///
1529 /// `target` is the certificate that will bind the key.
1530 ///
1531 /// `keys` is the set of keys to bind.
1532 ///
1533 /// The resulting certificate is NOT imported into the key store
1534 /// or the cert store.
1535 ///
1536 /// This version panics if `sq key bind` fails.
1537 pub fn key_subkey_bind<P, T, K, Q>(&self,
1538 extra_args: &[&str],
1539 keyrings: Vec<P>,
1540 target: T,
1541 keys: Vec<K>,
1542 output_file: Q)
1543 -> Cert
1544 where
1545 P: AsRef<Path>,
1546 T: Into<FileOrKeyHandle>,
1547 K: Into<KeyHandle>,
1548 Q: AsRef<Path>,
1549 {
1550 self.key_subkey_bind_maybe(
1551 extra_args, keyrings, target, keys, output_file)
1552 .expect("sq key subkey bind succeeds")
1553 }
1554
1555 pub fn try_key_approvals_list<'a, H, U>(&self,
1556 args: &[&str],
1557 cert: H,
1558 userids: &[U])
1559 -> Result<Vec<u8>>
1560 where H: Into<FileOrKeyHandle>,
1561 U: Into<UserIDArg<'a>> + Clone,
1562 {
1563 let cert = cert.into();
1564 let userids: Vec<UserIDArg> = userids.iter()
1565 .cloned()
1566 .map(|u| u.into())
1567 .collect();
1568
1569 let mut cmd = self.command();
1570 cmd.arg("key").arg("approvals").arg("list");
1571
1572 cmd.args(args);
1573
1574 match &cert {
1575 FileOrKeyHandle::FileOrStdin(file) => {
1576 cmd.arg("--cert-file").arg(file);
1577 }
1578 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1579 cmd.arg("--cert").arg(s);
1580 }
1581 }
1582
1583 for userid in userids.iter() {
1584 userid.as_arg(&mut cmd);
1585 }
1586
1587 let output = self.run(cmd, None);
1588 if output.status.success() {
1589 Ok(output.stdout)
1590 } else {
1591 Err(anyhow::anyhow!("sq key approvals list returned an error"))
1592 }
1593 }
1594
1595 pub fn key_approvals_list<'a, H, U>(&self,
1596 args: &[&str],
1597 cert: H,
1598 userids: &[U])
1599 -> Vec<u8>
1600 where H: Into<FileOrKeyHandle>,
1601 U: Into<UserIDArg<'a>> + Clone,
1602 {
1603 self.try_key_approvals_list(args, cert, userids)
1604 .expect("success")
1605 }
1606
1607 pub fn try_key_approvals_update<'a, H, U, Q>(&self,
1608 args: &[&str],
1609 cert: H,
1610 userids: &[U],
1611 output_file: Q)
1612 -> Result<Cert>
1613 where H: Into<FileOrKeyHandle>,
1614 U: Into<UserIDArg<'a>> + Clone,
1615 Q: Into<Option<&'a Path>>,
1616 {
1617 let cert = cert.into();
1618 let userids: Vec<UserIDArg> = userids.iter()
1619 .cloned()
1620 .map(|u| u.into())
1621 .collect();
1622 let output_file = output_file.into();
1623
1624 let mut cmd = self.command();
1625 cmd.arg("key").arg("approvals").arg("update");
1626
1627 cmd.args(args);
1628
1629 match &cert {
1630 FileOrKeyHandle::FileOrStdin(file) => {
1631 cmd.arg("--cert-file").arg(file);
1632 assert!(output_file.is_some());
1633 }
1634 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1635 cmd.arg("--cert").arg(s);
1636 }
1637 }
1638
1639 for userid in userids.iter() {
1640 userid.as_arg(&mut cmd);
1641 }
1642
1643 if let Some(output_file) = output_file {
1644 cmd.arg("--output").arg(output_file);
1645 }
1646
1647 let output = self.run(cmd, None);
1648 self.handle_cert_output(output, cert, output_file, None)
1649 }
1650
1651 pub fn key_approvals_update<'a, H, U, Q>(&self,
1652 args: &[&str],
1653 cert: H,
1654 userids: &[U],
1655 output_file: Q)
1656 -> Cert
1657 where H: Into<FileOrKeyHandle>,
1658 U: Into<UserIDArg<'a>> + Clone,
1659 Q: Into<Option<&'a Path>>,
1660 {
1661 self.try_key_approvals_update(args, cert, userids, output_file)
1662 .expect("success")
1663 }
1664
1665 /// Change the certificate's expiration.
1666 pub fn key_expire<'a, H, Q>(&self,
1667 cert_handle: H,
1668 expire: &str,
1669 password_file: Option<&'a Path>,
1670 output_file: Q,
1671 success: bool)
1672 -> Result<Cert>
1673 where
1674 H: Into<FileOrKeyHandle>,
1675 Q: Into<Option<&'a Path>>,
1676 {
1677 let cert_handle = cert_handle.into();
1678 let output_file = output_file.into();
1679
1680 let mut cmd = self.command();
1681 cmd.arg("key").arg("expire")
1682 .arg("--expiration").arg(expire);
1683
1684 if cert_handle.is_file() {
1685 cmd.arg("--cert-file").arg(&cert_handle);
1686 assert!(output_file.is_some());
1687 } else {
1688 cmd.arg("--cert").arg(&cert_handle);
1689 };
1690
1691 if let Some(p) = password_file {
1692 cmd.arg("--password-file").arg(p);
1693 }
1694
1695 if let Some(output_file) = output_file {
1696 cmd.arg("--output").arg(output_file);
1697 }
1698
1699 let output = self.run(cmd, Some(success));
1700 self.handle_cert_output(output, cert_handle, output_file, None)
1701 }
1702
1703 /// Exports the specified keys.
1704 pub fn key_subkey_export<H1, H2>(&self, cert: H1, khs: Vec<H2>)
1705 -> Cert
1706 where H1: Into<KeyHandle>,
1707 H2: Into<KeyHandle>
1708 {
1709 self.key_subkey_export_maybe(cert, khs)
1710 .expect("can export key")
1711 }
1712
1713 /// Exports the specified keys from the key store.
1714 ///
1715 /// Returns an error if `sq key subkey export` fails. This
1716 /// happens if the key is known, but the key store doesn't manage
1717 /// any of its secret key material.
1718 pub fn key_subkey_export_maybe<H1, H2>(&self, cert: H1, khs: Vec<H2>)
1719 -> Result<Cert>
1720 where H1: Into<KeyHandle>,
1721 H2: Into<KeyHandle>,
1722 {
1723 let cert = cert.into();
1724
1725 let mut cmd = self.command();
1726 cmd.args([ "key", "subkey", "export" ]);
1727 cmd.arg("--cert").arg(cert.to_string());
1728 for kh in khs.into_iter() {
1729 let kh: KeyHandle = kh.into();
1730 cmd.arg("--key").arg(kh.to_string());
1731 }
1732 let output = self.run(cmd, None);
1733 self.handle_cert_output(
1734 output, cert.into(), Some(PathBuf::from("-").as_path()), true)
1735 }
1736
1737 /// Run `sq key subkey revoke` and return the revocation certificate.
1738 pub fn key_subkey_revoke<'a, H, I, Q>(&self,
1739 cert_handle: H,
1740 key_handles: &[KeyHandle],
1741 revoker_handle: I,
1742 reason: &str,
1743 message: &str,
1744 revocation_time: Option<DateTime<Utc>>,
1745 notations: &[(&str, &str)],
1746 output_file: Q)
1747 -> Cert
1748 where H: Into<FileOrKeyHandle>,
1749 I: Into<Option<FileOrKeyHandle>>,
1750 Q: Into<Option<&'a Path>>,
1751 {
1752 let cert_handle = cert_handle.into();
1753 let revoker_handle = revoker_handle.into();
1754 let output_file = output_file.into();
1755
1756 let mut cmd = self.command();
1757 cmd.arg("key").arg("subkey").arg("revoke")
1758 .arg("--reason").arg(reason)
1759 .arg("--message").arg(message);
1760
1761 for key in key_handles {
1762 cmd.arg("--key").arg(key.to_string());
1763 }
1764
1765 match &cert_handle {
1766 FileOrKeyHandle::FileOrStdin(path) => {
1767 cmd.arg("--cert-file").arg(path);
1768 assert!(output_file.is_some());
1769 }
1770 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1771 cmd.arg("--cert").arg(&s);
1772 }
1773 };
1774 match revoker_handle.as_ref() {
1775 Some(FileOrKeyHandle::FileOrStdin(path)) => {
1776 cmd.arg("--revoker-file").arg(path);
1777 }
1778 Some(FileOrKeyHandle::KeyHandle((_kh, s))) => {
1779 cmd.arg("--revoker").arg(&s);
1780 }
1781 None => (),
1782 };
1783
1784 if let Some(output_file) = output_file {
1785 cmd.arg("--output").arg(output_file);
1786 }
1787
1788 for (k, v) in notations {
1789 cmd.args(["--signature-notation", k, v]);
1790 }
1791
1792 if let Some(time) = revocation_time {
1793 cmd.args([
1794 "--time",
1795 &time.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
1796 ]);
1797 }
1798
1799 let output = self.run(cmd, Some(true));
1800 self.handle_cert_output(output, cert_handle, output_file, false)
1801 .expect("can parse certificate")
1802 }
1803
1804 /// Delete the specified keys.
1805 pub fn try_key_subkey_delete<'a, H, Q>(&self,
1806 cert_handle: H,
1807 key_handles: &[KeyHandle],
1808 output_file: Q)
1809 -> Result<Cert>
1810 where H: Into<FileOrKeyHandle>,
1811 Q: Into<Option<&'a Path>>,
1812 {
1813 let cert_handle = cert_handle.into();
1814 let output_file = output_file.into();
1815
1816 let mut cmd = self.command();
1817 cmd.arg("key").arg("subkey").arg("delete");
1818
1819 match &cert_handle {
1820 FileOrKeyHandle::FileOrStdin(path) => {
1821 cmd.arg("--cert-file").arg(path);
1822 if let Some(output_file) = output_file {
1823 cmd.arg("--output").arg(output_file);
1824 } else {
1825 cmd.arg("--output").arg("-");
1826 }
1827 }
1828 FileOrKeyHandle::KeyHandle((_kh, s)) => {
1829 cmd.arg("--cert").arg(&s);
1830 if let Some(output_file) = output_file {
1831 cmd.arg("--output").arg(output_file);
1832 }
1833 }
1834 };
1835
1836 for kh in key_handles {
1837 cmd.arg("--key").arg(kh.to_string());
1838 }
1839
1840 let output = self.run(cmd, None);
1841 self.handle_cert_output(output, cert_handle, output_file, None)
1842 }
1843
1844 /// Delete the specified keys.
1845 pub fn key_subkey_delete<'a, H, Q>(&self,
1846 cert_handle: H,
1847 key_handles: &[KeyHandle],
1848 output_file: Q)
1849 -> Cert
1850 where H: Into<FileOrKeyHandle>,
1851 Q: Into<Option<&'a Path>>,
1852 {
1853 self.try_key_subkey_delete(cert_handle, key_handles, output_file)
1854 .expect("success")
1855 }
1856
1857 /// Change the key's password.
1858 pub fn try_key_subkey_password<'a, H, Q>(
1859 &self,
1860 cert_handle: H,
1861 keys: &[KeyHandle],
1862 old_password_file: Option<&'a Path>,
1863 new_password_file: Option<&'a Path>,
1864 output_file: Q)
1865 -> Result<Cert>
1866 where
1867 H: Into<FileOrKeyHandle>,
1868 Q: Into<Option<&'a Path>>,
1869 {
1870 let cert_handle = cert_handle.into();
1871 let output_file = output_file.into();
1872
1873 let mut cmd = self.command();
1874 cmd.arg("key").arg("subkey").arg("password");
1875
1876 if cert_handle.is_file() {
1877 cmd.arg("--cert-file").arg(&cert_handle);
1878 if let Some(output_file) = output_file {
1879 cmd.arg("--output").arg(output_file);
1880 } else {
1881 cmd.arg("--output").arg("-");
1882 }
1883 } else {
1884 cmd.arg("--cert").arg(&cert_handle);
1885 if let Some(output_file) = output_file {
1886 cmd.arg("--output").arg(output_file);
1887 }
1888 };
1889
1890 for key in keys.iter() {
1891 cmd.arg("--key").arg(key.to_string());
1892 }
1893
1894 if let Some(p) = old_password_file {
1895 cmd.arg("--password-file").arg(p);
1896 }
1897
1898 if let Some(p) = new_password_file {
1899 cmd.arg("--new-password-file").arg(p);
1900 } else {
1901 cmd.arg("--clear-password");
1902 }
1903
1904 let output = self.run(cmd, None);
1905 self.handle_cert_output(output, cert_handle, output_file, None)
1906 }
1907
1908 /// Change the key's password.
1909 pub fn key_subkey_password<'a, H, Q>(&self,
1910 cert_handle: H,
1911 keys: &[KeyHandle],
1912 old_password_file: Option<&'a Path>,
1913 new_password_file: Option<&'a Path>,
1914 output_file: Q)
1915 -> Cert
1916 where
1917 H: Into<FileOrKeyHandle>,
1918 Q: Into<Option<&'a Path>>,
1919 {
1920 self.try_key_subkey_password(
1921 cert_handle, keys,
1922 old_password_file, new_password_file,
1923 output_file)
1924 .expect("success")
1925 }
1926
1927 /// Change the key's expiration.
1928 pub fn key_subkey_expire<'a, H, Q>(&self,
1929 cert_handle: H,
1930 keys: &[KeyHandle],
1931 expire: &str,
1932 password_file: Option<&'a Path>,
1933 output_file: Q,
1934 success: bool)
1935 -> Result<Cert>
1936 where
1937 H: Into<FileOrKeyHandle>,
1938 Q: Into<Option<&'a Path>>,
1939 {
1940 let cert_handle = cert_handle.into();
1941 let output_file = output_file.into();
1942
1943 let mut cmd = self.command();
1944 cmd.arg("key").arg("subkey").arg("expire")
1945 .arg("--expiration").arg(expire);
1946
1947 if cert_handle.is_file() {
1948 cmd.arg("--cert-file").arg(&cert_handle);
1949 assert!(output_file.is_some());
1950 } else {
1951 cmd.arg("--cert").arg(&cert_handle);
1952 };
1953
1954 for key in keys.iter() {
1955 cmd.arg("--key").arg(key.to_string());
1956 }
1957
1958 if let Some(p) = password_file {
1959 cmd.arg("--password-file").arg(p);
1960 }
1961
1962 if let Some(output_file) = output_file {
1963 cmd.arg("--output").arg(output_file);
1964 }
1965
1966 let output = self.run(cmd, Some(success));
1967 self.handle_cert_output(output, cert_handle, output_file, None)
1968 }
1969
1970 /// Adds user IDs to the given key.
1971 pub fn key_userid_add<'a, U>(&self, args: &[&str],
1972 key: Cert, userids: &[U])
1973 -> Result<Cert>
1974 where U: Into<UserIDArg<'a>> + Clone
1975 {
1976 let userids = userids.iter()
1977 .cloned()
1978 .map(|u| u.into())
1979 .collect::<Vec<_>>();
1980
1981 let mut cmd = self.command();
1982 cmd.args(["key", "userid", "add"]);
1983 for arg in args {
1984 cmd.arg(arg);
1985 }
1986
1987 let in_filename = self.scratch_file(None);
1988 key.as_tsk().serialize(&mut File::create(&in_filename)?)?;
1989 cmd.arg("--cert-file").arg(&in_filename);
1990
1991 for userid in userids.iter() {
1992 userid.as_arg(&mut cmd);
1993 }
1994
1995 let out_filename = self.scratch_file(None);
1996 cmd.arg("--output").arg(&out_filename);
1997
1998 let output = self.run(cmd, Some(true));
1999
2000 let out_key = Cert::from_file(&out_filename)?;
2001 assert!(out_key.is_tsk());
2002 Ok(out_key)
2003 }
2004
2005 /// Revokes a user ID.
2006 pub fn key_userid_revoke_maybe<'a, 'b, C, O, U>(&self, args: &[&str],
2007 cert: C, userid: U,
2008 reason: &str,
2009 message: &str,
2010 output_file: O)
2011 -> Result<Cert>
2012 where C: Into<FileOrKeyHandle>,
2013 U: Into<UserIDArg<'a>>,
2014 O: Into<Option<&'b Path>>,
2015 {
2016 let cert = cert.into();
2017 let output_file = output_file.into();
2018
2019 let mut cmd = self.command();
2020 cmd.args([
2021 "key", "userid", "revoke",
2022 "--reason", reason,
2023 "--message", message,
2024 ]);
2025 for arg in args {
2026 cmd.arg(arg);
2027 }
2028
2029 match &cert {
2030 FileOrKeyHandle::FileOrStdin(file) => {
2031 cmd.arg("--cert-file").arg(file);
2032 }
2033 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2034 cmd.arg("--cert").arg(s);
2035 }
2036 }
2037 userid.into().as_arg(&mut cmd);
2038
2039 if let Some(output_file) = output_file {
2040 cmd.arg("--overwrite").arg("--output").arg(output_file);
2041 }
2042
2043 let output = self.run(cmd, None);
2044 self.handle_cert_output(output, cert, output_file, false)
2045 }
2046
2047 pub fn key_userid_revoke<'a, 'b, C, O, U>(&self, args: &[&str],
2048 cert: C, userid: U,
2049 reason: &str,
2050 message: &str,
2051 output_file: O)
2052 -> Cert
2053 where C: Into<FileOrKeyHandle>,
2054 U: Into<UserIDArg<'a>>,
2055 O: Into<Option<&'b Path>>,
2056 {
2057 self.key_userid_revoke_maybe(args, cert, userid, reason, message, output_file)
2058 .expect("succeeds")
2059 }
2060
2061 /// Runs `sq cert list` with the supplied arguments.
2062 pub fn cert_list_maybe(&self, args: &[&str]) -> Result<Vec<u8>> {
2063 let mut cmd = self.command();
2064 cmd.arg("cert").arg("list");
2065 for arg in args {
2066 cmd.arg(arg);
2067 }
2068 let output = self.run(cmd, None);
2069 if output.status.success() {
2070 Ok(output.stdout)
2071 } else {
2072 Err(anyhow::anyhow!("sq cert list returned an error"))
2073 }
2074 }
2075
2076 /// Runs `sq cert list` with the supplied arguments.
2077 pub fn cert_list(&self, args: &[&str]) -> Vec<u8> {
2078 self.cert_list_maybe(args).expect("success")
2079 }
2080
2081 /// Imports the specified certificate into the keystore.
2082 pub fn cert_import_maybe<P>(&self, path: P) -> Result<()>
2083 where P: AsRef<Path>
2084 {
2085 let mut cmd = self.command();
2086 cmd.arg("cert").arg("import").arg(path.as_ref());
2087 let output = self.run(cmd, None);
2088 if output.status.success() {
2089 Ok(())
2090 } else {
2091 Err(anyhow::anyhow!("sq cert import returned an error"))
2092 }
2093 }
2094
2095 /// Imports the specified certificate into the keystore.
2096 pub fn cert_import<P>(&self, path: P)
2097 where P: AsRef<Path>
2098 {
2099 self.cert_import_maybe(path)
2100 .expect("succeeds")
2101 }
2102
2103 /// Exports the specified certificate.
2104 pub fn cert_export<H>(&self, kh: H) -> Cert
2105 where
2106 H: Borrow<KeyHandle>,
2107 {
2108 let mut cmd = self.command();
2109 cmd.args([ "cert", "export", "--cert", &kh.borrow().to_string() ]);
2110 let output = self.run(cmd, Some(true));
2111
2112 Cert::from_bytes(&output.stdout)
2113 .expect("can parse certificate")
2114 }
2115
2116 pub fn cert_export_all(&self) -> Vec<Cert>
2117 {
2118 let mut cmd = self.command();
2119 cmd.args([ "cert", "export", "--all" ]);
2120 let output = self.run(cmd, Some(true));
2121
2122 CertParser::from_bytes(&output.stdout)
2123 .expect("can parse certificate")
2124 .collect::<Result<Vec<Cert>>>()
2125 .expect("can export")
2126 }
2127
2128 /// Try to certify the user ID binding.
2129 ///
2130 /// If `output_file` is `Some`, then the output is written to that
2131 /// file. Otherwise, the default behavior is followed.
2132 pub fn try_pki_vouch_add<'a, 'b, H, C, U, Q>(
2133 &self, extra_args: &[&str],
2134 certifier: H,
2135 cert: C, userids: &[U],
2136 output_file: Q)
2137 -> Result<Cert>
2138 where H: Into<FileOrKeyHandle>,
2139 C: Into<FileOrKeyHandle>,
2140 U: Into<UserIDArg<'a>> + Clone,
2141 Q: Into<Option<&'b Path>>,
2142 {
2143 let certifier = certifier.into();
2144 let cert = cert.into();
2145 let userids = userids.iter()
2146 .cloned()
2147 .map(|u| u.into())
2148 .collect::<Vec<_>>();
2149 let output_file = output_file.into();
2150
2151 let mut cmd = self.command();
2152 cmd.args([ "pki", "vouch", "add" ]);
2153 for arg in extra_args {
2154 cmd.arg(arg);
2155 }
2156 match &certifier {
2157 FileOrKeyHandle::FileOrStdin(file) => {
2158 cmd.arg("--certifier-file").arg(file);
2159 }
2160 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2161 cmd.arg("--certifier").arg(s);
2162 }
2163 }
2164 match &cert {
2165 FileOrKeyHandle::FileOrStdin(file) => {
2166 cmd.arg("--cert-file").arg(file);
2167 }
2168 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2169 cmd.arg("--cert").arg(s);
2170 }
2171 }
2172 for userid in userids.iter() {
2173 userid.as_arg(&mut cmd);
2174 }
2175
2176 if let Some(output_file) = output_file {
2177 cmd.arg("--overwrite").arg("--output").arg(output_file);
2178 }
2179
2180 let output = self.run(cmd, None);
2181 self.handle_cert_output(output, cert, output_file, false)
2182 }
2183
2184 /// Certify the user ID binding.
2185 pub fn pki_vouch_add<'a, 'b, H, C, U, Q>(
2186 &self, extra_args: &[&str],
2187 certifier: H,
2188 cert: C, userids: &[U],
2189 output_file: Q)
2190 -> Cert
2191 where H: Into<FileOrKeyHandle>,
2192 C: Into<FileOrKeyHandle>,
2193 U: Into<UserIDArg<'a>> + Clone,
2194 Q: Into<Option<&'b Path>>,
2195 {
2196 self.try_pki_vouch_add(
2197 extra_args, certifier, cert, userids, output_file)
2198 .expect("success")
2199 }
2200
2201 /// Try to make an authorization.
2202 ///
2203 /// If `output_file` is `Some`, then the output is written to that
2204 /// file. Otherwise, the default behavior is followed.
2205 pub fn try_pki_vouch_authorize<'a, 'b, H, C, U, Q>(
2206 &self, extra_args: &[&str],
2207 certifier: H,
2208 cert: C, userids: &[U],
2209 output_file: Q)
2210 -> Result<Cert>
2211 where H: Into<FileOrKeyHandle>,
2212 C: Into<FileOrKeyHandle>,
2213 U: Into<UserIDArg<'a>> + Clone,
2214 Q: Into<Option<&'b Path>>,
2215 {
2216 let certifier = certifier.into();
2217 let cert = cert.into();
2218 let userids = userids.iter()
2219 .cloned()
2220 .map(|u| u.into())
2221 .collect::<Vec<_>>();
2222 let output_file = output_file.into();
2223
2224 let mut cmd = self.command();
2225 cmd.args([ "pki", "vouch", "authorize" ]);
2226 for arg in extra_args {
2227 cmd.arg(arg);
2228 }
2229 match &certifier {
2230 FileOrKeyHandle::FileOrStdin(file) => {
2231 cmd.arg("--certifier-file").arg(file);
2232 }
2233 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2234 cmd.arg("--certifier").arg(s);
2235 }
2236 }
2237 match &cert {
2238 FileOrKeyHandle::FileOrStdin(file) => {
2239 cmd.arg("--cert-file").arg(file);
2240 }
2241 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2242 cmd.arg("--cert").arg(s);
2243 }
2244 }
2245 for userid in userids.iter() {
2246 userid.as_arg(&mut cmd);
2247 }
2248
2249 if let Some(output_file) = output_file {
2250 cmd.arg("--overwrite").arg("--output").arg(output_file);
2251 }
2252
2253 let output = self.run(cmd, None);
2254 self.handle_cert_output(output, cert, output_file, false)
2255 }
2256
2257 /// Authorize a certificate.
2258 pub fn pki_vouch_authorize<'a, 'b, H, C, U, Q>(
2259 &self, extra_args: &[&str],
2260 certifier: H,
2261 cert: C, userids: &[U],
2262 output_file: Q)
2263 -> Cert
2264 where H: Into<FileOrKeyHandle>,
2265 C: Into<FileOrKeyHandle>,
2266 U: Into<UserIDArg<'a>> + Clone,
2267 Q: Into<Option<&'b Path>>,
2268 {
2269 self.try_pki_vouch_authorize(
2270 extra_args, certifier, cert, userids, output_file)
2271 .expect("success")
2272 }
2273
2274 /// List certifications made by certifier.
2275 pub fn try_pki_vouch_list<'a, C1, C2>(&self, extra_args: &[&str],
2276 certifier: C1, cert: C2)
2277 -> Result<String>
2278 where C1: Into<Option<CertArg<'a>>>,
2279 C2: Into<Option<CertArg<'a>>>
2280 {
2281 let mut cmd = self.command();
2282 cmd.args([ "pki", "vouch", "list" ]);
2283 for arg in extra_args {
2284 cmd.arg(arg);
2285 }
2286 if let Some(certifier) = certifier.into() {
2287 certifier.as_arg(&mut cmd, "certifier");
2288 }
2289 if let Some(cert) = cert.into() {
2290 cert.as_arg(&mut cmd, "cert");
2291 }
2292
2293 let output = self.run(cmd, None);
2294 if output.status.success() {
2295 Ok(String::from_utf8_lossy(&output.stdout).to_string())
2296 } else {
2297 Err(anyhow::anyhow!(
2298 "Failed: {}",
2299 String::from_utf8_lossy(&output.stderr).to_string()))
2300 }
2301 }
2302
2303 /// List certifications made by certifier.
2304 pub fn pki_vouch_list<'a, C1, C2>(&self, extra_args: &[&str],
2305 certifier: C1, cert: C2)
2306 -> String
2307 where C1: Into<Option<CertArg<'a>>>,
2308 C2: Into<Option<CertArg<'a>>>
2309 {
2310 self.try_pki_vouch_list(extra_args, certifier, cert)
2311 .expect("success")
2312 }
2313
2314 /// Replays active certifications made by `source` using `target`.
2315 ///
2316 /// If `output_file` is not `None`, then the output is parsed and
2317 /// returned. If `output_file` is `None`, then an empty vector is
2318 /// returned.
2319 pub fn try_pki_vouch_replay<'a, O>(&self, extra_args: &[&str],
2320 source: CertArg,
2321 target: CertArg,
2322 output_file: O)
2323 -> Result<Vec<Cert>>
2324 where O: Into<Option<&'a Path>>,
2325 {
2326 let mut cmd = self.command();
2327 cmd.args([ "pki", "vouch", "replay" ]);
2328 for arg in extra_args {
2329 cmd.arg(arg);
2330 }
2331 if let Some(source) = source.into() {
2332 source.as_arg(&mut cmd, "source");
2333 }
2334 if let Some(target) = target.into() {
2335 target.as_arg(&mut cmd, "target");
2336 }
2337
2338 let output = self.run(cmd, None);
2339 if output.status.success() {
2340 if let Some(output_file) = output_file.into() {
2341 let parser = if PathBuf::from("-").as_path() == output_file {
2342 CertParser::from_bytes(&output.stdout)
2343 .expect("can parse certificate")
2344 } else {
2345 CertParser::from_file(&output_file)
2346 .expect("can parse certificate")
2347 };
2348 parser.collect::<Result<Vec<_>>>()
2349 } else {
2350 // We don't try to figure out what was certificated,
2351 // but just return an empty vector.
2352 Ok(Vec::new())
2353 }
2354 } else {
2355 Err(anyhow::anyhow!(
2356 "Failed: {}",
2357 String::from_utf8_lossy(&output.stderr).to_string()))
2358 }
2359 }
2360
2361 /// Replays active certifications made by `source` using `target`.
2362 ///
2363 /// If `output_file` is not `None`, then the output is parsed and
2364 /// returned. If `output_file` is `None`, then an empty vector is
2365 /// returned.
2366 pub fn pki_vouch_replay<'a, O>(&self, extra_args: &[&str],
2367 source: CertArg,
2368 target: CertArg,
2369 output_file: O)
2370 -> Vec<Cert>
2371 where O: Into<Option<&'a Path>>,
2372 {
2373 self.try_pki_vouch_replay(extra_args, source, target, output_file)
2374 .expect("success")
2375 }
2376
2377 /// Add a link for the binding.
2378 pub fn pki_link_add_maybe<'a, U>(&self, extra_args: &[&str],
2379 cert: KeyHandle, userids: &[U])
2380 -> Result<()>
2381 where U: Into<UserIDArg<'a>> + Clone,
2382 {
2383 let userids = userids.iter()
2384 .cloned()
2385 .map(|u| u.into())
2386 .collect::<Vec<_>>();
2387
2388 let mut cmd = self.command();
2389 cmd.args([ "pki", "link", "add" ]);
2390 for arg in extra_args {
2391 cmd.arg(arg);
2392 }
2393 cmd.arg("--cert").arg(cert.to_string());
2394 for userid in userids.iter() {
2395 userid.as_arg(&mut cmd);
2396 }
2397
2398 let output = self.run(cmd, None);
2399 if output.status.success() {
2400 Ok(())
2401 } else {
2402 Err(anyhow::anyhow!(format!(
2403 "Command failed:\n{}",
2404 String::from_utf8_lossy(&output.stderr))))
2405 }
2406 }
2407
2408 /// Add a link for the binding.
2409 pub fn pki_link_add<'a, U>(&self, args: &[&str],
2410 cert: KeyHandle, userids: &[U])
2411 where U: Into<UserIDArg<'a>> + Clone,
2412 {
2413 self.pki_link_add_maybe(args, cert, userids).expect("success")
2414 }
2415
2416 /// Add a link for the binding.
2417 pub fn pki_link_retract_maybe<'a, U>(&self, extra_args: &[&str],
2418 cert: KeyHandle,
2419 userids: &[U])
2420 -> Result<()>
2421 where U: Into<UserIDArg<'a>> + Clone,
2422 {
2423 let userids = userids.iter()
2424 .cloned()
2425 .map(|u| u.into())
2426 .collect::<Vec<_>>();
2427
2428 let mut cmd = self.command();
2429 cmd.args([ "pki", "link", "retract" ]);
2430 for arg in extra_args {
2431 cmd.arg(arg);
2432 }
2433 cmd.arg("--cert").arg(cert.to_string());
2434 for userid in userids.iter() {
2435 userid.as_arg(&mut cmd);
2436 }
2437
2438 let output = self.run(cmd, None);
2439 if output.status.success() {
2440 Ok(())
2441 } else {
2442 Err(anyhow::anyhow!(format!(
2443 "Command failed:\n{}",
2444 String::from_utf8_lossy(&output.stderr))))
2445 }
2446 }
2447
2448 /// Add a link for the binding.
2449 pub fn pki_link_retract<'a, U>(&self, args: &[&str],
2450 cert: KeyHandle, userids: &[U])
2451 where U: Into<UserIDArg<'a>> + Clone,
2452 {
2453 self.pki_link_retract_maybe(args, cert, userids)
2454 .expect("success")
2455 }
2456
2457 /// Add a link for the binding.
2458 pub fn pki_link_authorize_maybe<'a, U>(&self, extra_args: &[&str],
2459 cert: KeyHandle,
2460 userids: &[U])
2461 -> Result<()>
2462 where U: Into<UserIDArg<'a>> + Clone,
2463 {
2464 let userids = userids.iter()
2465 .cloned()
2466 .map(|u| u.into())
2467 .collect::<Vec<_>>();
2468
2469 let mut cmd = self.command();
2470 cmd.args([ "pki", "link", "authorize" ]);
2471 for arg in extra_args {
2472 cmd.arg(arg);
2473 }
2474 cmd.arg("--cert").arg(cert.to_string());
2475 for userid in userids.iter() {
2476 userid.as_arg(&mut cmd);
2477 }
2478
2479 let output = self.run(cmd, None);
2480 if output.status.success() {
2481 Ok(())
2482 } else {
2483 Err(anyhow::anyhow!(format!(
2484 "Command failed:\n{}",
2485 String::from_utf8_lossy(&output.stderr))))
2486 }
2487 }
2488
2489 /// Add a link for the binding.
2490 pub fn pki_link_authorize<'a, U>(&self, args: &[&str],
2491 cert: KeyHandle, userids: &[U])
2492 where U: Into<UserIDArg<'a>> + Clone,
2493 {
2494 self.pki_link_authorize_maybe(args, cert, userids)
2495 .expect("success")
2496 }
2497
2498 /// Runs `sq pki link list` with the supplied arguments.
2499 pub fn try_pki_link_list(&self, args: &[&str]) -> Result<Vec<u8>> {
2500 let mut cmd = self.command();
2501 cmd.arg("pki").arg("link").arg("list");
2502 for arg in args {
2503 cmd.arg(arg);
2504 }
2505 let output = self.run(cmd, None);
2506 if output.status.success() {
2507 Ok(output.stdout)
2508 } else {
2509 Err(anyhow::anyhow!("sq cert list returned an error"))
2510 }
2511 }
2512
2513 /// Runs `sq pki link list` with the supplied arguments.
2514 pub fn pki_link_list(&self, args: &[&str]) -> Vec<u8> {
2515 self.try_pki_link_list(args).expect("success")
2516 }
2517
2518 /// Authenticate a binding.
2519 pub fn pki_authenticate<'a, U>(&self, extra_args: &[&str],
2520 cert: &str, userid: U)
2521 -> Result<()>
2522 where U: Into<UserIDArg<'a>>,
2523 {
2524 let mut cmd = self.command();
2525 cmd.args([ "pki", "authenticate", "--show-paths" ]);
2526 for arg in extra_args {
2527 cmd.arg(arg);
2528 }
2529 cmd.arg("--cert").arg(cert);
2530 userid.into().as_arg(&mut cmd);
2531
2532 let output = self.run(cmd, None);
2533 if output.status.success() {
2534 Ok(())
2535 } else {
2536 Err(anyhow::anyhow!(format!(
2537 "Command failed:\n{}",
2538 String::from_utf8_lossy(&output.stderr))))
2539 }
2540 }
2541
2542 /// Lookup a binding.
2543 pub fn pki_lookup<'a, U>(&self, extra_args: &[&str],
2544 userid: U)
2545 -> Result<()>
2546 where U: Into<UserIDArg<'a>>,
2547 {
2548 let mut cmd = self.command();
2549 cmd.args([ "pki", "lookup", "--show-paths" ]);
2550 for arg in extra_args {
2551 cmd.arg(arg);
2552 }
2553 userid.into().as_arg(&mut cmd);
2554
2555 let output = self.run(cmd, None);
2556 if output.status.success() {
2557 Ok(())
2558 } else {
2559 Err(anyhow::anyhow!(format!(
2560 "Command failed:\n{}",
2561 String::from_utf8_lossy(&output.stderr))))
2562 }
2563 }
2564
2565 pub fn sign<'a, H, Q>(&self,
2566 signer: H,
2567 password_file: Option<&Path>,
2568 input_file: &Path,
2569 output_file: Q)
2570 -> Vec<u8>
2571 where H: Into<FileOrKeyHandle>,
2572 Q: Into<Option<&'a Path>>,
2573 {
2574 self.sign_args(&[], signer, password_file, input_file, output_file)
2575 }
2576
2577 pub fn sign_args<'a, H, Q>(&self,
2578 args: &[&str],
2579 signer: H,
2580 password_file: Option<&Path>,
2581 input_file: &Path,
2582 output_file: Q)
2583 -> Vec<u8>
2584 where
2585 H: Into<FileOrKeyHandle>,
2586 Q: Into<Option<&'a Path>>,
2587 {
2588 let signer = signer.into();
2589 let output_file = output_file.into();
2590
2591 let mut cmd = self.command();
2592 cmd.arg("sign").arg("--message");
2593 cmd.args(args);
2594
2595 match &signer {
2596 FileOrKeyHandle::FileOrStdin(path) => {
2597 cmd.arg("--signer-file").arg(path);
2598 }
2599 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2600 cmd.arg("--signer").arg(&s);
2601 }
2602 };
2603
2604 if let Some(password_file) = password_file {
2605 cmd.arg("--password-file").arg(password_file);
2606 }
2607
2608 cmd.arg(input_file);
2609
2610 if let Some(output_file) = output_file {
2611 cmd.arg("--output").arg(output_file);
2612 };
2613
2614 let output = self.run(cmd, Some(true));
2615 assert!(output.status.success());
2616
2617 if let Some(output_file) = output_file {
2618 std::fs::read(output_file).expect("can read file")
2619 } else {
2620 output.stdout
2621 }
2622 }
2623
2624 pub fn sign_detached<'a, H, O>(&self,
2625 args: &[&str],
2626 signer: H,
2627 input_file: &Path,
2628 output_file: O)
2629 -> Vec<u8>
2630 where H: Into<FileOrKeyHandle>,
2631 O: Into<Option<&'a Path>>,
2632 {
2633 self.try_sign_detached(args, signer, input_file, output_file)
2634 .unwrap()
2635 }
2636
2637 pub fn try_sign_detached<'a, H, O>(&self,
2638 args: &[&str],
2639 signer: H,
2640 input_file: &Path,
2641 output_file: O)
2642 -> Result<Vec<u8>>
2643 where
2644 H: Into<FileOrKeyHandle>,
2645 O: Into<Option<&'a Path>>,
2646 {
2647 let signer = signer.into();
2648 let output_file = output_file.into();
2649
2650 let mut cmd = self.command();
2651 let stdout: PathBuf = "-".into();
2652 cmd.arg("sign")
2653 .arg("--signature-file").arg(output_file.unwrap_or(&stdout));
2654
2655 for arg in args {
2656 cmd.arg(arg);
2657 }
2658
2659 match &signer {
2660 FileOrKeyHandle::FileOrStdin(path) => {
2661 cmd.arg("--signer-file").arg(path);
2662 }
2663 FileOrKeyHandle::KeyHandle((_kh, s)) => {
2664 cmd.arg("--signer").arg(&s);
2665 }
2666 };
2667
2668 cmd.arg(input_file);
2669
2670 let output = self.run(cmd, None);
2671 if output.status.success() {
2672 if let Some(output_file) = output_file {
2673 Ok(std::fs::read(output_file).expect("can read file"))
2674 } else {
2675 Ok(output.stdout)
2676 }
2677 } else {
2678 Err(anyhow::anyhow!("{}", String::from_utf8_lossy(&output.stderr)))
2679 }
2680 }
2681
2682 pub fn verify_maybe<'a, P, Q>(&self,
2683 args: &[&str],
2684 op: Verify,
2685 input: P,
2686 output_file: Q)
2687 -> Result<Vec<u8>>
2688 where P: AsRef<Path>,
2689 Q: Into<Option<&'a Path>>,
2690 {
2691 let output_file = output_file.into();
2692
2693 let mut cmd = self.command();
2694 cmd.args([ "verify" ]);
2695 for arg in args {
2696 cmd.arg(arg);
2697 }
2698 op.apply(&mut cmd);
2699 cmd.arg(input.as_ref());
2700 if let Some(output_file) = output_file {
2701 cmd.arg("--output").arg(output_file);
2702 }
2703
2704 let output = self.run(cmd, None);
2705 if output.status.success() {
2706 if let Some(output_file) = output_file {
2707 if output_file != &PathBuf::from("-") {
2708 return Ok(std::fs::read(output_file)?);
2709 }
2710 }
2711
2712 Ok(output.stdout)
2713 } else {
2714 Err(anyhow::anyhow!(format!(
2715 "Command failed:\n{}",
2716 String::from_utf8_lossy(&output.stderr))))
2717 }
2718 }
2719
2720 pub fn verify<'a, P, Q>(&self,
2721 args: &[&str],
2722 op: Verify,
2723 input: P,
2724 output_file: Q)
2725 -> Vec<u8>
2726 where P: AsRef<Path>,
2727 Q: Into<Option<&'a Path>>,
2728 {
2729 self.verify_maybe(args, op, input, output_file)
2730 .expect("success")
2731 }
2732
2733 // Merges the certificates.
2734 pub fn keyring_merge_maybe<'a, P, Q>(&self,
2735 input_files: &[P],
2736 input_bytes: Option<&[u8]>,
2737 output_file: Q)
2738 -> Result<Vec<Cert>>
2739 where P: AsRef<Path>,
2740 Q: Into<Option<&'a Path>>,
2741 {
2742 let output_file = output_file.into();
2743
2744 let mut cmd = self.command();
2745 cmd.args([ "keyring", "merge" ]);
2746
2747 for input_file in input_files.into_iter() {
2748 cmd.arg(input_file.as_ref());
2749 }
2750 if let Some(input_bytes) = input_bytes {
2751 cmd.arg("-");
2752 cmd.write_stdin(input_bytes);
2753 }
2754
2755 if let Some(output_file) = output_file {
2756 cmd.arg("--output").arg(output_file);
2757 }
2758
2759 let output = self.run(cmd, None);
2760
2761 if output.status.success() {
2762 let mut parser = None;
2763 if let Some(output_file) = output_file {
2764 if PathBuf::from("-").as_path() != output_file {
2765 parser = Some(CertParser::from_file(&output_file)
2766 .expect("can parse certificate"));
2767 }
2768 }
2769 let parser = if let Some(parser) = parser {
2770 parser
2771 } else {
2772 // Read from stdout.
2773 CertParser::from_bytes(&output.stdout)
2774 .expect("can parse certificate")
2775 };
2776
2777 parser.collect::<Result<Vec<_>>>()
2778 } else {
2779 Err(anyhow::anyhow!("sq key export returned an error"))
2780 }
2781 }
2782
2783 // Merges the certificates.
2784 pub fn keyring_merge<'a, P, Q>(&self,
2785 input_files: &[P],
2786 input_bytes: Option<&[u8]>,
2787 output_file: Q)
2788 -> Vec<Cert>
2789 where P: AsRef<Path>,
2790 Q: Into<Option<&'a Path>>,
2791 {
2792 self.keyring_merge_maybe(input_files, input_bytes, output_file)
2793 .expect("success")
2794 }
2795 }
2796
2797 pub enum Verify {
2798 Message,
2799 SignatureFile(PathBuf),
2800 Cleartext,
2801 }
2802
2803 impl Verify {
2804 fn apply(self, cmd: &mut Command) {
2805 match self {
2806 Verify::Message => cmd.arg("--message"),
2807 Verify::SignatureFile(f) => cmd.arg("--signature-file").arg(f),
2808 Verify::Cleartext => cmd.arg("--cleartext"),
2809 };
2810 }
2811 }
2812
2813 /// Ensure notations can be found in a Signature
2814 ///
2815 /// ## Errors
2816 ///
2817 /// Returns an error if a notation can not be found in the Signature
2818 pub fn compare_notations(
2819 signature: &Signature,
2820 notations: &[(&str, &str)],
2821 ) -> Result<()> {
2822 if ! notations.is_empty() {
2823 let found_notations: Vec<(&str, String)> = signature
2824 .notation_data()
2825 .map(|n| (n.name(), String::from_utf8_lossy(n.value()).into()))
2826 .collect();
2827
2828 for (key, value) in notations {
2829 if !found_notations.contains(&(key, String::from(*value))) {
2830 return Err(anyhow!(format!(
2831 "Expected notation \"{}: {}\" in {:?}",
2832 key, value, found_notations
2833 )));
2834 }
2835 }
2836 }
2837 Ok(())
2838 }