Skip to main content

uselesskey_pgp/
keypair.rs

1use std::fmt;
2use std::sync::Arc;
3
4use pgp::composed::{EncryptionCaps, KeyType, SecretKeyParamsBuilder, SignedPublicKey};
5use pgp::ser::Serialize;
6use pgp::types::KeyDetails;
7use rand_chacha::ChaCha20Rng;
8use rand_core::SeedableRng;
9use uselesskey_core::negative::{
10    CorruptPem, corrupt_der_deterministic, corrupt_pem, corrupt_pem_deterministic, truncate_der,
11};
12use uselesskey_core::sink::TempArtifact;
13use uselesskey_core::{Error, Factory};
14
15use crate::PgpSpec;
16
17/// Cache domain for OpenPGP keypair fixtures.
18///
19/// Keep this stable: changing it changes deterministic outputs.
20pub const DOMAIN_PGP_KEYPAIR: &str = "uselesskey:pgp:keypair";
21
22#[derive(Clone)]
23pub struct PgpKeyPair {
24    factory: Factory,
25    label: String,
26    spec: PgpSpec,
27    inner: Arc<Inner>,
28}
29
30struct Inner {
31    user_id: String,
32    fingerprint: String,
33    private_binary: Arc<[u8]>,
34    private_armor: String,
35    public_binary: Arc<[u8]>,
36    public_armor: String,
37}
38
39impl fmt::Debug for PgpKeyPair {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.debug_struct("PgpKeyPair")
42            .field("label", &self.label)
43            .field("spec", &self.spec)
44            .field("fingerprint", &self.inner.fingerprint)
45            .finish_non_exhaustive()
46    }
47}
48
49/// Extension trait to hang OpenPGP helpers off the core [`Factory`].
50pub trait PgpFactoryExt {
51    fn pgp(&self, label: impl AsRef<str>, spec: PgpSpec) -> PgpKeyPair;
52}
53
54impl PgpFactoryExt for Factory {
55    fn pgp(&self, label: impl AsRef<str>, spec: PgpSpec) -> PgpKeyPair {
56        PgpKeyPair::new(self.clone(), label.as_ref(), spec)
57    }
58}
59
60impl PgpKeyPair {
61    fn new(factory: Factory, label: &str, spec: PgpSpec) -> Self {
62        let inner = load_inner(&factory, label, spec, "good");
63        Self {
64            factory,
65            label: label.to_string(),
66            spec,
67            inner,
68        }
69    }
70
71    fn load_variant(&self, variant: &str) -> Arc<Inner> {
72        load_inner(&self.factory, &self.label, self.spec, variant)
73    }
74
75    /// Returns the fixture spec.
76    pub fn spec(&self) -> PgpSpec {
77        self.spec
78    }
79
80    /// Returns the generated OpenPGP user id.
81    pub fn user_id(&self) -> &str {
82        &self.inner.user_id
83    }
84
85    /// Returns the OpenPGP key fingerprint.
86    pub fn fingerprint(&self) -> &str {
87        &self.inner.fingerprint
88    }
89
90    /// Binary transferable secret key bytes.
91    pub fn private_key_binary(&self) -> &[u8] {
92        &self.inner.private_binary
93    }
94
95    /// Armored transferable secret key.
96    pub fn private_key_armored(&self) -> &str {
97        &self.inner.private_armor
98    }
99
100    /// Binary transferable public key bytes.
101    pub fn public_key_binary(&self) -> &[u8] {
102        &self.inner.public_binary
103    }
104
105    /// Armored transferable public key.
106    pub fn public_key_armored(&self) -> &str {
107        &self.inner.public_armor
108    }
109
110    /// Write the armored private key to a tempfile.
111    pub fn write_private_key_armored(&self) -> Result<TempArtifact, Error> {
112        TempArtifact::new_string("uselesskey-", ".pgp.priv.asc", self.private_key_armored())
113    }
114
115    /// Write the armored public key to a tempfile.
116    pub fn write_public_key_armored(&self) -> Result<TempArtifact, Error> {
117        TempArtifact::new_string("uselesskey-", ".pgp.pub.asc", self.public_key_armored())
118    }
119
120    /// Produce a corrupted armored private key variant.
121    pub fn private_key_armored_corrupt(&self, how: CorruptPem) -> String {
122        corrupt_pem(self.private_key_armored(), how)
123    }
124
125    /// Produce a deterministic corrupted armored private key using a variant string.
126    pub fn private_key_armored_corrupt_deterministic(&self, variant: &str) -> String {
127        corrupt_pem_deterministic(self.private_key_armored(), variant)
128    }
129
130    /// Produce a truncated private key binary variant.
131    pub fn private_key_binary_truncated(&self, len: usize) -> Vec<u8> {
132        truncate_der(self.private_key_binary(), len)
133    }
134
135    /// Produce a deterministic corrupted private key binary using a variant string.
136    pub fn private_key_binary_corrupt_deterministic(&self, variant: &str) -> Vec<u8> {
137        corrupt_der_deterministic(self.private_key_binary(), variant)
138    }
139
140    /// Return a valid (parseable) public key that does not match this private key.
141    pub fn mismatched_public_key_binary(&self) -> Vec<u8> {
142        let other = self.load_variant("mismatch");
143        other.public_binary.as_ref().to_vec()
144    }
145
146    /// Return an armored public key that does not match this private key.
147    pub fn mismatched_public_key_armored(&self) -> String {
148        let other = self.load_variant("mismatch");
149        other.public_armor.clone()
150    }
151}
152
153fn load_inner(factory: &Factory, label: &str, spec: PgpSpec, variant: &str) -> Arc<Inner> {
154    let spec_bytes = spec.stable_bytes();
155
156    factory.get_or_init(DOMAIN_PGP_KEYPAIR, label, &spec_bytes, variant, |seed| {
157        let mut rng = ChaCha20Rng::from_seed(*seed.bytes());
158        let user_id = build_user_id(label);
159
160        let mut key_params = SecretKeyParamsBuilder::default();
161        key_params
162            .key_type(spec_to_key_type(spec))
163            .can_certify(true)
164            .can_sign(true)
165            .can_encrypt(EncryptionCaps::None)
166            .primary_user_id(user_id.clone());
167
168        let secret_key_params = key_params
169            .build()
170            .expect("failed to build OpenPGP secret key params");
171
172        let secret_key = secret_key_params
173            .generate(&mut rng)
174            .expect("OpenPGP key generation failed");
175        let public_key = SignedPublicKey::from(secret_key.clone());
176
177        let mut private_binary = Vec::new();
178        secret_key
179            .to_writer(&mut private_binary)
180            .expect("failed to encode OpenPGP private key bytes");
181
182        let mut public_binary = Vec::new();
183        public_key
184            .to_writer(&mut public_binary)
185            .expect("failed to encode OpenPGP public key bytes");
186
187        let private_armor = secret_key
188            .to_armored_string(None.into())
189            .expect("failed to armor OpenPGP private key");
190        let public_armor = public_key
191            .to_armored_string(None.into())
192            .expect("failed to armor OpenPGP public key");
193
194        Inner {
195            user_id,
196            fingerprint: secret_key.fingerprint().to_string(),
197            private_binary: Arc::from(private_binary),
198            private_armor,
199            public_binary: Arc::from(public_binary),
200            public_armor,
201        }
202    })
203}
204
205fn spec_to_key_type(spec: PgpSpec) -> KeyType {
206    match spec {
207        PgpSpec::Rsa2048 => KeyType::Rsa(2048),
208        PgpSpec::Rsa3072 => KeyType::Rsa(3072),
209        PgpSpec::Ed25519 => KeyType::Ed25519,
210    }
211}
212
213fn build_user_id(label: &str) -> String {
214    let display = if label.trim().is_empty() {
215        "fixture"
216    } else {
217        label.trim()
218    };
219
220    let mut local = String::new();
221    for ch in display.chars() {
222        if ch.is_ascii_alphanumeric() {
223            local.push(ch.to_ascii_lowercase());
224        } else if !local.ends_with('-') {
225            local.push('-');
226        }
227    }
228
229    let local = local.trim_matches('-');
230    let local = if local.is_empty() { "fixture" } else { local };
231
232    format!("{display} <{local}@uselesskey.test>")
233}
234
235#[cfg(test)]
236mod tests {
237    use std::io::Cursor;
238
239    use pgp::composed::{Deserializable, SignedPublicKey, SignedSecretKey};
240    use pgp::types::KeyDetails;
241    use uselesskey_core::Seed;
242
243    use super::*;
244
245    #[test]
246    fn deterministic_key_is_stable() {
247        let fx = Factory::deterministic(Seed::from_env_value("pgp-det").unwrap());
248        let a = fx.pgp("issuer", PgpSpec::ed25519());
249        let b = fx.pgp("issuer", PgpSpec::ed25519());
250
251        assert_eq!(a.private_key_armored(), b.private_key_armored());
252        assert_eq!(a.public_key_armored(), b.public_key_armored());
253        assert_eq!(a.fingerprint(), b.fingerprint());
254    }
255
256    #[test]
257    fn random_mode_caches_per_identity() {
258        let fx = Factory::random();
259        let a = fx.pgp("issuer", PgpSpec::rsa_2048());
260        let b = fx.pgp("issuer", PgpSpec::rsa_2048());
261
262        assert_eq!(a.private_key_armored(), b.private_key_armored());
263    }
264
265    #[test]
266    fn different_labels_produce_different_keys() {
267        let fx = Factory::deterministic(Seed::from_env_value("pgp-label").unwrap());
268        let a = fx.pgp("a", PgpSpec::rsa_3072());
269        let b = fx.pgp("b", PgpSpec::rsa_3072());
270
271        assert_ne!(a.private_key_binary(), b.private_key_binary());
272        assert_ne!(a.fingerprint(), b.fingerprint());
273    }
274
275    #[test]
276    fn armored_outputs_have_expected_headers() {
277        let fx = Factory::random();
278        let key = fx.pgp("issuer", PgpSpec::ed25519());
279
280        assert!(
281            key.private_key_armored()
282                .contains("BEGIN PGP PRIVATE KEY BLOCK")
283        );
284        assert!(
285            key.public_key_armored()
286                .contains("BEGIN PGP PUBLIC KEY BLOCK")
287        );
288    }
289
290    #[test]
291    fn armored_outputs_parse_and_match_fingerprint() {
292        let fx = Factory::random();
293        let key = fx.pgp("parser", PgpSpec::ed25519());
294
295        let (secret, _) =
296            SignedSecretKey::from_armor_single(Cursor::new(key.private_key_armored()))
297                .expect("parse armored private key");
298        secret.verify_bindings().expect("verify private bindings");
299
300        let (public, _) = SignedPublicKey::from_armor_single(Cursor::new(key.public_key_armored()))
301            .expect("parse armored public key");
302        public.verify_bindings().expect("verify public bindings");
303
304        assert_eq!(secret.fingerprint().to_string(), key.fingerprint());
305        assert_eq!(public.fingerprint().to_string(), key.fingerprint());
306    }
307
308    #[test]
309    fn binary_outputs_parse() {
310        let fx = Factory::random();
311        let key = fx.pgp("binary", PgpSpec::rsa_2048());
312
313        let secret = SignedSecretKey::from_bytes(Cursor::new(key.private_key_binary()))
314            .expect("parse private key bytes");
315        let public = SignedPublicKey::from_bytes(Cursor::new(key.public_key_binary()))
316            .expect("parse public key bytes");
317
318        assert_eq!(secret.fingerprint().to_string(), key.fingerprint());
319        assert_eq!(public.fingerprint().to_string(), key.fingerprint());
320    }
321
322    #[test]
323    fn mismatched_public_key_differs() {
324        let fx = Factory::deterministic(Seed::from_env_value("pgp-mismatch").unwrap());
325        let key = fx.pgp("issuer", PgpSpec::ed25519());
326
327        let mismatch = key.mismatched_public_key_binary();
328        assert_ne!(mismatch, key.public_key_binary());
329    }
330
331    #[test]
332    fn user_id_is_exposed_and_sanitized() {
333        let fx = Factory::deterministic(Seed::from_env_value("pgp-user-id").unwrap());
334        let key = fx.pgp("Test User!@#", PgpSpec::ed25519());
335        let blank = fx.pgp("   ", PgpSpec::ed25519());
336
337        assert_eq!(key.user_id(), "Test User!@# <test-user@uselesskey.test>");
338        assert_eq!(blank.user_id(), "fixture <fixture@uselesskey.test>");
339    }
340
341    #[test]
342    fn armored_corruption_helpers_are_invalid_and_stable() {
343        let fx = Factory::deterministic(Seed::from_env_value("pgp-corrupt-armor").unwrap());
344        let key = fx.pgp("issuer", PgpSpec::ed25519());
345
346        let bad = key.private_key_armored_corrupt(CorruptPem::BadBase64);
347        assert_ne!(bad, key.private_key_armored());
348        assert!(bad.contains("THIS_IS_NOT_BASE64!!!"));
349        assert!(SignedSecretKey::from_armor_single(Cursor::new(&bad)).is_err());
350
351        let det_a = key.private_key_armored_corrupt_deterministic("corrupt:v1");
352        let det_b = key.private_key_armored_corrupt_deterministic("corrupt:v1");
353        assert_eq!(det_a, det_b);
354        assert_ne!(det_a, key.private_key_armored());
355        assert!(det_a.starts_with('-'));
356        assert!(SignedSecretKey::from_armor_single(Cursor::new(&det_a)).is_err());
357    }
358
359    #[test]
360    fn binary_corruption_helpers_are_invalid_and_stable() {
361        let fx = Factory::deterministic(Seed::from_env_value("pgp-corrupt-bin").unwrap());
362        let key = fx.pgp("issuer", PgpSpec::ed25519());
363
364        let truncated = key.private_key_binary_truncated(32);
365        assert_eq!(truncated.len(), 32);
366        assert!(SignedSecretKey::from_bytes(Cursor::new(&truncated)).is_err());
367
368        let det_a = key.private_key_binary_corrupt_deterministic("corrupt:v1");
369        let det_b = key.private_key_binary_corrupt_deterministic("corrupt:v1");
370        assert_eq!(det_a, det_b);
371        assert_ne!(det_a, key.private_key_binary());
372        assert_eq!(det_a.len(), key.private_key_binary().len());
373    }
374
375    #[test]
376    fn mismatched_public_key_variants_parse_and_fingerprint_differs() {
377        let fx = Factory::deterministic(Seed::from_env_value("pgp-mismatch-parse").unwrap());
378        let key = fx.pgp("issuer", PgpSpec::ed25519());
379
380        let mismatch_bin = key.mismatched_public_key_binary();
381        let mismatch_pub = SignedPublicKey::from_bytes(Cursor::new(&mismatch_bin))
382            .expect("parse mismatched public binary");
383        assert_ne!(mismatch_pub.fingerprint().to_string(), key.fingerprint());
384
385        let mismatch_arm = key.mismatched_public_key_armored();
386        assert_ne!(mismatch_arm, key.public_key_armored());
387        let (mismatch_pub_arm, _) = SignedPublicKey::from_armor_single(Cursor::new(&mismatch_arm))
388            .expect("parse mismatched public armor");
389        assert_ne!(
390            mismatch_pub_arm.fingerprint().to_string(),
391            key.fingerprint()
392        );
393    }
394
395    #[test]
396    fn debug_does_not_leak_key_material() {
397        let fx = Factory::random();
398        let key = fx.pgp("debug", PgpSpec::ed25519());
399        let dbg = format!("{key:?}");
400
401        assert!(dbg.contains("PgpKeyPair"));
402        assert!(dbg.contains("debug"));
403        assert!(!dbg.contains("BEGIN PGP PRIVATE KEY BLOCK"));
404    }
405}