1//! Test helpers.
23// @@ begin test lint list maintained by maint/add_warning @@
4#![allow(clippy::bool_assert_comparison)]
5#![allow(clippy::clone_on_copy)]
6#![allow(clippy::dbg_macro)]
7#![allow(clippy::mixed_attributes_style)]
8#![allow(clippy::print_stderr)]
9#![allow(clippy::print_stdout)]
10#![allow(clippy::single_char_pattern)]
11#![allow(clippy::unwrap_used)]
12#![allow(clippy::unchecked_duration_subtraction)]
13#![allow(clippy::useless_vec)]
14#![allow(clippy::needless_pass_by_value)]
15//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
1617use std::fmt::Debug;
1819use crate::{ArtiPath, KeyPath, KeySpecifier};
2021// TODO: #[cfg(test)] / feature `testing`:
22// https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/2873#note_3179873
23// > A better overall approach would've been to split out the test utils that are not
24// > pub into a different module (to avoid the confusing internal featute/test gating).
2526#[cfg(test)]
27use {
28 std::io::Error,
29 std::io::ErrorKind::{Interrupted, NotFound},
30 std::process::{Command, Stdio},
31 tempfile::tempdir,
32};
3334/// Check that `spec` produces the [`ArtiPath`] from `path`, and that `path` parses to `spec`
35///
36/// # Panics
37///
38/// Panics if `path` isn't valid as an `ArtiPath` or any of the checks fail.
39pub fn check_key_specifier<S, E>(spec: &S, path: &str)
40where
41S: KeySpecifier + Debug + PartialEq,
42 S: for<'p> TryFrom<&'p KeyPath, Error = E>,
43 E: Debug,
44{
45let apath = ArtiPath::new(path.to_string()).unwrap();
46assert_eq!(spec.arti_path().unwrap(), apath);
47assert_eq!(&S::try_from(&KeyPath::Arti(apath)).unwrap(), spec, "{path}");
48}
4950/// Generates a pair of encoded OpenSSH-formatted Ed25519 keys using `ssh-keygen`.
51/// Field `.0` is the Private Key, and field `.1` is the Public Key.
52///
53/// # Errors
54///
55/// Will return an error if
56///
57/// * A temporary directory could be not created to generate keys in
58/// * `ssh-keygen` was not found, it exited with a non-zero status
59/// code, or it was terminated by a signal
60/// * The generated keys could not be read from the temporary directory
61#[cfg(test)]
62pub(crate) fn sshkeygen_ed25519_strings() -> std::io::Result<(String, String)> {
63let tempdir = tempdir()?;
64const FILENAME: &str = "tmp_id_ed25519";
65let status = Command::new("ssh-keygen")
66 .current_dir(tempdir.path())
67 .stdout(Stdio::null())
68 .stderr(Stdio::null())
69 .args(["-q", "-P", "", "-t", "ed25519", "-f", FILENAME, "-C", ""])
70 .status()
71 .map_err(|e| match e.kind() {
72 NotFound => Error::new(NotFound, "could not find ssh-keygen"),
73_ => e,
74 })?;
7576match status.code() {
77Some(0) => {
78let key = tempdir.path().join(FILENAME);
79let key_pub = key.with_extension("pub");
8081let key = std::fs::read_to_string(key)?;
82let key_pub = std::fs::read_to_string(key_pub)?;
8384Ok((key, key_pub))
85 }
86Some(code) => Err(Error::other(format!(
87"ssh-keygen exited with status code: {code}"
88))),
89None => Err(Error::new(
90 Interrupted,
91"ssh-keygen was terminated by a signal",
92 )),
93 }
94}
9596/// OpenSSH keys used for testing.
97#[cfg(test)]
98pub(crate) mod ssh_keys {
99/// Helper macro for defining test key constants.
100 ///
101 /// Defines constants for the public and private key files
102 /// specified in the `PUB` and `PRIV` lists, respectively.
103 ///
104 /// The entries from the `PUB` and `PRIV` lists must specify the documentation of the constant,
105 /// and the basename of the file to include (`include_str`) from "../testdata".
106 /// The path of each key file is built like so:
107 ///
108 /// * `PUB` keys: `../testdata/<BASENAME>.public`
109 /// * `PRIV` keys: `../testdata/<BASENAME>.private`
110 ///
111 /// The names of the constants are derived from the basename:
112 /// * for `PUB` entries, the name is the uppercased basename, followed by `_PUB`
113 /// * for `PRIV` entries, the name is the uppercased basename
114macro_rules! define_key_consts {
115 (
116 PUB => { $($(#[ $docs_and_attrs:meta ])* $basename:literal,)* },
117 PRIV => { $($(#[ $docs_and_attrs_priv:meta ])* $basename_priv:literal,)* }
118 ) => {
119 $(
120paste::paste! {
121define_key_consts!(
122 @ $(#[ $docs_and_attrs ])*
123 [< $basename:upper _PUB >], $basename, ".public"
124);
125 }
126 )*
127128 $(
129paste::paste! {
130define_key_consts!(
131 @ $(#[ $docs_and_attrs_priv ])*
132 [< $basename_priv:upper >], $basename_priv, ".private"
133);
134 }
135 )*
136 };
137138 (
139 @ $($(#[ $docs_and_attrs:meta ])*
140$const_name:ident, $basename:literal, $extension:literal)*
141 ) => {
142 $(
143 $(#[ $docs_and_attrs ])*
144pub(crate) const $const_name: &str =
145include_str!(concat!("../testdata/", $basename, $extension));
146 )*
147 }
148 }
149150define_key_consts! {
151// Public key constants
152PUB => {
153/// An Ed25519 public key.
154"ed25519_openssh",
155/// An Ed25519 public key that fails to parse.
156"ed25519_openssh_bad",
157/// A public key using the ed25519-expanded@spec.torproject.org algorithm.
158 ///
159 /// Not valid because Ed25519 public keys can't be "expanded".
160"ed25519_expanded_openssh",
161/// A X25519 public key.
162"x25519_openssh",
163/// An invalid public key using the armadillo@torproject.org algorithm.
164"x25519_openssh_unknown_algorithm",
165 },
166// Keypair constants
167PRIV => {
168/// An Ed25519 keypair.
169"ed25519_openssh",
170/// An Ed25519 keypair that fails to parse.
171"ed25519_openssh_bad",
172/// An expanded Ed25519 keypair.
173"ed25519_expanded_openssh",
174/// An expanded Ed25519 keypair that fails to parse.
175"ed25519_expanded_openssh_bad",
176/// A DSA keypair.
177"dsa_openssh",
178/// A X25519 keypair.
179"x25519_openssh",
180/// An invalid keypair using the pangolin@torproject.org algorithm.
181"x25519_openssh_unknown_algorithm",
182 }
183 }
184}
185186/// A module exporting a key specifier used for testing.
187#[cfg(test)]
188mod specifier {
189use crate::{
190 ArtiPath, ArtiPathUnavailableError, CTorPath, KeyCertificateSpecifier, KeySpecifier,
191 KeySpecifierComponent,
192 };
193194/// A key specifier path.
195pub(crate) const TEST_SPECIFIER_PATH: &str = "parent1/parent2/parent3/test-specifier";
196197/// A [`KeySpecifier`] with a fixed [`ArtiPath`] prefix and custom suffix.
198 ///
199 /// The inner String is the suffix of its `ArtiPath`.
200#[derive(Default, PartialEq, Eq)]
201pub(crate) struct TestSpecifier(String);
202203impl TestSpecifier {
204/// Create a new [`TestSpecifier`] with the supplied `suffix`.
205pub(crate) fn new(suffix: impl AsRef<str>) -> Self {
206Self(suffix.as_ref().into())
207 }
208 }
209210impl KeySpecifier for TestSpecifier {
211fn arti_path(&self) -> Result<ArtiPath, ArtiPathUnavailableError> {
212Ok(ArtiPath::new(format!("{TEST_SPECIFIER_PATH}{}", self.0))
213 .map_err(|e| tor_error::internal!("{e}"))?)
214 }
215216fn ctor_path(&self) -> Option<CTorPath> {
217None
218}
219220fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>> {
221None
222}
223 }
224225/// A test client key specifiier
226#[derive(Debug, Clone)]
227pub(crate) struct TestCTorSpecifier(pub(crate) CTorPath);
228229impl KeySpecifier for TestCTorSpecifier {
230fn arti_path(&self) -> Result<ArtiPath, ArtiPathUnavailableError> {
231unimplemented!()
232 }
233234fn ctor_path(&self) -> Option<CTorPath> {
235Some(self.0.clone())
236 }
237238fn keypair_specifier(&self) -> Option<Box<dyn KeySpecifier>> {
239unimplemented!()
240 }
241 }
242243/// A test certificate specifier.
244pub(crate) struct TestCertSpecifier<SUBJ: KeySpecifier, SIGN: KeySpecifier> {
245/// The key specifier of the subject key.
246pub(crate) subject_key_spec: SUBJ,
247/// The key specifier of the signing key.
248pub(crate) signing_key_spec: SIGN,
249/// A list of denotators for distinguishing certs of this type.
250pub(crate) denotator: Vec<String>,
251 }
252253impl<SUBJ: KeySpecifier, SIGN: KeySpecifier> KeyCertificateSpecifier
254for TestCertSpecifier<SUBJ, SIGN>
255 {
256fn cert_denotators(&self) -> Vec<&dyn KeySpecifierComponent> {
257self.denotator
258 .iter()
259 .map(|s| s as &dyn KeySpecifierComponent)
260 .collect()
261 }
262263fn signing_key_specifier(&self) -> Option<&dyn KeySpecifier> {
264Some(&self.signing_key_spec)
265 }
266267/// The key specifier of the subject key.
268fn subject_key_specifier(&self) -> &dyn KeySpecifier {
269&self.subject_key_spec
270 }
271 }
272}
273274/// A module exporting key implementations used for testing.
275#[cfg(test)]
276mod key {
277use crate::EncodableItem;
278use tor_key_forge::{ItemType, KeystoreItem, KeystoreItemType};
279280/// A dummy key.
281 ///
282 /// Used as an argument placeholder for calling functions that require an [`EncodableItem`].
283 ///
284 /// Panics if its `EncodableItem` implementation is called.
285pub(crate) struct DummyKey;
286287impl ItemType for DummyKey {
288fn item_type() -> KeystoreItemType
289where
290Self: Sized,
291 {
292todo!()
293 }
294 }
295296impl EncodableItem for DummyKey {
297fn as_keystore_item(&self) -> tor_key_forge::Result<KeystoreItem> {
298todo!()
299 }
300 }
301}
302303#[cfg(test)]
304pub(crate) use specifier::*;
305306#[cfg(test)]
307pub(crate) use key::*;
308309#[cfg(test)]
310pub(crate) use internal::assert_found;
311312/// Private module for reexporting test helper macros macro.
313#[cfg(test)]
314mod internal {
315/// Assert that the specified key can be found (or not) in `key_store`.
316macro_rules! assert_found {
317 ($key_store:expr, $key_spec:expr, $key_type:expr, $found:expr) => {{
318let res = $key_store
319.get($key_spec, &$key_type.clone().into())
320 .unwrap();
321if $found {
322assert!(res.is_some());
323// Ensure contains() agrees with get()
324assert!($key_store
325.contains($key_spec, &$key_type.clone().into())
326 .unwrap());
327 } else {
328assert!(res.is_none());
329 }
330 }};
331 }
332333pub(crate) use assert_found;
334}