pqr 0.1.0

Post-quantum resistant encryption, decryption, and key generation from the command line. Easy to use, with sane defaults.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! End-to-end tests: run the real binary against a temporary PQR_DIR.

use std::fs;
use std::io::{Read, Write};
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Stdio};

use pgp::armor::Dearmor;
use pgp::composed::{
    Deserializable, EncryptionCaps, KeyType, SecretKeyParamsBuilder, SignedPublicKey,
    SubkeyParamsBuilder,
};
use pgp::crypto::public_key::PublicKeyAlgorithm;
use pgp::types::{KeyDetails, KeyVersion};
use tempfile::TempDir;

struct Out {
    code: i32,
    stdout: Vec<u8>,
    stderr: String,
}

impl Out {
    fn text(&self) -> String {
        String::from_utf8(self.stdout.clone()).expect("utf-8 stdout")
    }
}

fn pqr(dir: &Path, args: &[&str], stdin: Option<&[u8]>) -> Out {
    let mut child = Command::new(env!("CARGO_BIN_EXE_pqr"))
        .args(args)
        .env("PQR_DIR", dir)
        .env_remove("XDG_CONFIG_HOME")
        .stdin(if stdin.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn pqr");
    if let Some(data) = stdin {
        child
            .stdin
            .take()
            .expect("stdin pipe")
            .write_all(data)
            .expect("write stdin");
    }
    let out = child.wait_with_output().expect("wait pqr");
    Out {
        code: out.status.code().expect("exit code"),
        stdout: out.stdout,
        stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
    }
}

#[cfg(unix)]
fn mode(path: &Path) -> u32 {
    fs::metadata(path).expect("metadata").permissions().mode() & 0o777
}

fn with_identity(name: &str) -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    let out = pqr(dir.path(), &["keygen", "-i", name], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    dir
}

#[cfg(unix)]
#[test]
fn keygen_creates_both_files_with_modes() {
    let dir = TempDir::new().unwrap();
    let out = pqr(dir.path(), &["keygen"], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    let key = dir.path().join("keys/main.key");
    let public = dir.path().join("keys/main.pub");
    assert_eq!(mode(&key), 0o600);
    assert_eq!(mode(&public), 0o644);
    assert_eq!(out.text(), fs::read_to_string(&public).unwrap());
    assert!(
        out.text()
            .starts_with("-----BEGIN PGP PUBLIC KEY BLOCK-----")
    );
}

#[test]
fn second_keygen_refuses_and_leaves_files_untouched() {
    let dir = with_identity("main");
    let key = dir.path().join("keys/main.key");
    let public = dir.path().join("keys/main.pub");
    let (key_before, pub_before) = (fs::read(&key).unwrap(), fs::read(&public).unwrap());
    let out = pqr(dir.path(), &["keygen", "-i", "main"], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
    assert_eq!(fs::read(&key).unwrap(), key_before);
    assert_eq!(fs::read(&public).unwrap(), pub_before);
}

#[test]
fn argv_round_trip() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["Begun, the Clone War has."], None);
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    let plain = pqr(dir.path(), &["-d", &msg.text()], None);
    assert_eq!(plain.code, 0, "{}", plain.stderr);
    assert_eq!(plain.text(), "Begun, the Clone War has.");
}

#[test]
fn stdin_round_trip() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &[], Some(b"Do or do not.\n"));
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    assert!(msg.text().starts_with("-----BEGIN PGP MESSAGE-----"));
    let plain = pqr(dir.path(), &["-d"], Some(&msg.stdout));
    assert_eq!(plain.code, 0, "{}", plain.stderr);
    assert_eq!(plain.text(), "Do or do not.\n");
}

#[test]
fn same_text_encrypts_to_different_ciphertexts() {
    let dir = with_identity("main");
    let a = pqr(dir.path(), &["same"], None);
    let b = pqr(dir.path(), &["same"], None);
    assert_eq!((a.code, b.code), (0, 0));
    assert_ne!(a.stdout, b.stdout);
}

#[test]
fn flipped_byte_exits_3_with_empty_stdout() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["tamper target ".repeat(20).as_str()], None).text();
    // Flip one base64 character in the middle of the body (never in the header or CRC).
    let mut bytes = msg.into_bytes();
    let mid = bytes.len() / 2;
    let at = (mid..bytes.len())
        .find(|&i| bytes[i].is_ascii_alphabetic())
        .unwrap();
    bytes[at] = if bytes[at] == b'A' { b'B' } else { b'A' };
    let out = pqr(dir.path(), &["-d"], Some(&bytes));
    assert_eq!(out.code, 3, "{}", out.stderr);
    assert!(out.stdout.is_empty());
}

#[test]
fn flipped_binary_ciphertext_byte_exits_3() {
    let dir = with_identity("main");
    let armored = pqr(dir.path(), &["binary tamper"], None);
    let mut raw = dearmor(&armored.stdout);
    let last = raw.len() - 1;
    raw[last] ^= 0x01;
    let out = pqr(dir.path(), &["-d"], Some(&raw));
    assert_eq!(out.code, 3, "{}", out.stderr);
    assert!(out.stdout.is_empty());
}

#[test]
fn truncated_message_exits_3_with_empty_stdout() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["truncate me ".repeat(50).as_str()], None).stdout;
    let raw = dearmor(&msg);
    let cut = raw[..raw.len() - 10].to_vec();
    let out = pqr(dir.path(), &["-d"], Some(&cut));
    assert_eq!(out.code, 3, "{}", out.stderr);
    assert!(out.stdout.is_empty());
    let armored_cut = &msg[..msg.len() / 2];
    let out = pqr(dir.path(), &["-d"], Some(armored_cut));
    assert_eq!(out.code, 3, "{}", out.stderr);
    assert!(out.stdout.is_empty());
}

#[test]
fn message_for_another_identity_exits_2() {
    let dir = with_identity("main");
    pqr(dir.path(), &["keygen", "-i", "other"], None);
    let msg = pqr(dir.path(), &["-i", "other", "not for main"], None);
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    let out = pqr(dir.path(), &["-d"], Some(&msg.stdout));
    assert_eq!(out.code, 2, "{}", out.stderr);
    assert!(out.stdout.is_empty());
    let ok = pqr(dir.path(), &["-i", "other", "-d"], Some(&msg.stdout));
    assert_eq!(ok.text(), "not for main");
}

#[test]
fn missing_identity_hints_keygen() {
    let dir = TempDir::new().unwrap();
    let out = pqr(dir.path(), &["hi"], None);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("run: pqr keygen"));
}

#[test]
fn empty_decrypt_input_exits_1() {
    let dir = with_identity("main");
    let out = pqr(dir.path(), &["-d"], Some(b""));
    assert_eq!(out.code, 1);
}

#[test]
fn recipient_file_round_trip_server_and_laptop() {
    // "server" creates its identity; "laptop" encrypts with only server.pub.
    let server = with_identity("main");
    let laptop = TempDir::new().unwrap();
    let server_pub = laptop.path().join("server.pub");
    fs::copy(server.path().join("keys/main.pub"), &server_pub).unwrap();
    let pub_arg = server_pub.to_str().unwrap();
    let env_file = b"API_TOKEN=yoda-900\nDEBUG=false\n";
    let msg = pqr(laptop.path(), &["-r", pub_arg], Some(env_file));
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    assert!(!laptop.path().join("keys").exists(), "laptop made no keys");
    let plain = pqr(server.path(), &["-d"], Some(&msg.stdout));
    assert_eq!(plain.code, 0, "{}", plain.stderr);
    assert_eq!(plain.stdout, env_file);
    // The laptop has no secret key, so it cannot open the message.
    let nope = pqr(laptop.path(), &["-d"], Some(&msg.stdout));
    assert_eq!(nope.code, 1);
    assert!(nope.stderr.contains("run: pqr keygen"));
}

#[test]
fn recipient_flag_with_other_identity_pub() {
    let dir = with_identity("main");
    pqr(dir.path(), &["keygen", "-i", "other"], None);
    let pub_path = dir.path().join("keys/other.pub");
    let msg = pqr(
        dir.path(),
        &["-r", pub_path.to_str().unwrap(), "via -r"],
        None,
    );
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    let plain = pqr(dir.path(), &["-i", "other", "-d"], Some(&msg.stdout));
    assert_eq!(plain.text(), "via -r");
}

#[test]
fn recipient_and_identity_together_exit_1() {
    let dir = with_identity("main");
    let pub_path = dir.path().join("keys/main.pub");
    let out = pqr(
        dir.path(),
        &["-r", pub_path.to_str().unwrap(), "-i", "main", "x"],
        None,
    );
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
}

fn classical_public_armor() -> String {
    let subkey = SubkeyParamsBuilder::default()
        .version(KeyVersion::V6)
        .key_type(KeyType::X25519)
        .can_encrypt(EncryptionCaps::All)
        .build()
        .unwrap();
    let params = SecretKeyParamsBuilder::default()
        .version(KeyVersion::V6)
        .key_type(KeyType::Ed25519)
        .can_certify(true)
        .can_sign(true)
        .primary_user_id("classical".into())
        .subkey(subkey)
        .build()
        .unwrap();
    let secret = params.generate(rand::thread_rng()).unwrap();
    secret
        .to_public_key()
        .to_armored_string(None.into())
        .unwrap()
}

#[test]
fn classical_recipient_is_refused() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("classical.pub");
    fs::write(&path, classical_public_armor()).unwrap();
    let out = pqr(dir.path(), &["-r", path.to_str().unwrap(), "x"], None);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("classical keys are refused"));
    assert!(out.stdout.is_empty());
}

#[test]
fn recipient_accepts_the_key_text_itself() {
    let dir = with_identity("main");
    pqr(dir.path(), &["keygen", "-i", "other"], None);
    let key_text = fs::read_to_string(dir.path().join("keys/other.pub")).unwrap();
    let msg = pqr(dir.path(), &["-r", &key_text, "from text"], None);
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    let plain = pqr(dir.path(), &["-i", "other", "-d"], Some(&msg.stdout));
    assert_eq!(plain.text(), "from text");
}

#[test]
fn recipient_key_text_without_ml_kem_is_refused() {
    let dir = TempDir::new().unwrap();
    let out = pqr(dir.path(), &["-r", &classical_public_armor(), "x"], None);
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("classical keys are refused"));
    assert!(out.stdout.is_empty());
}

#[test]
fn recipient_that_is_neither_key_nor_file_exits_1() {
    let dir = TempDir::new().unwrap();
    let out = pqr(dir.path(), &["-r", "no-such-key.pub", "x"], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
}

#[test]
fn key_is_v6_with_ml_dsa_primary_and_ml_kem_subkey() {
    let dir = with_identity("main");
    let data = fs::read(dir.path().join("keys/main.pub")).unwrap();
    let (key, _) = SignedPublicKey::from_reader_single(data.as_slice()).unwrap();
    key.verify_bindings().unwrap();
    assert_eq!(key.primary_key.version(), KeyVersion::V6);
    assert_eq!(
        key.primary_key.algorithm(),
        PublicKeyAlgorithm::MlDsa65Ed25519
    );
    assert_eq!(key.public_subkeys.len(), 1);
    let sub = &key.public_subkeys[0];
    assert_eq!(sub.version(), KeyVersion::V6);
    assert_eq!(sub.algorithm(), PublicKeyAlgorithm::MlKem768X25519);
}

fn dearmor(armored: &[u8]) -> Vec<u8> {
    let mut raw = Vec::new();
    Dearmor::new(armored)
        .read_to_end(&mut raw)
        .expect("dearmor");
    raw
}

/// Read one new-format packet header: (tag, body start, body length).
fn packet(raw: &[u8], at: usize) -> (u8, usize, usize) {
    assert_eq!(raw[at] & 0xC0, 0xC0, "new-format packet header");
    let tag = raw[at] & 0x3F;
    let first = raw[at + 1] as usize;
    match first {
        0..=191 => (tag, at + 2, first),
        192..=223 => (
            tag,
            at + 3,
            ((first - 192) << 8) + raw[at + 2] as usize + 192,
        ),
        255 => {
            let len = u32::from_be_bytes(raw[at + 2..at + 6].try_into().unwrap()) as usize;
            (tag, at + 6, len)
        }
        _ => panic!("partial body length in a packet that must be sized"),
    }
}

#[test]
fn message_is_pkesk_v6_plus_seipd_v2() {
    let dir = with_identity("main");
    let armored = pqr(dir.path(), &["inspect me"], None);
    let raw = dearmor(&armored.stdout);
    let (tag, body, len) = packet(&raw, 0);
    assert_eq!(tag, 1, "first packet is a PKESK");
    assert_eq!(raw[body], 6, "PKESK version 6");
    let (tag, body, _) = packet(&raw, body + len);
    assert_eq!(tag, 18, "second packet is SEIPD");
    assert_eq!(raw[body], 2, "SEIPD version 2 (AEAD)");
}

#[test]
fn decrypt_flag_reads_an_armored_string_with_leading_whitespace() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["string form"], None);
    let padded = format!("\n  {}", msg.text());
    let out = pqr(dir.path(), &["-d", &padded], None);
    assert_eq!(out.code, 0, "{}", out.stderr);
    assert_eq!(out.text(), "string form");
}

#[test]
fn decrypt_flag_reads_armored_and_binary_files() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["file form"], None);
    let armored = dir.path().join("msg.pgp");
    fs::write(&armored, &msg.stdout).unwrap();
    let out = pqr(dir.path(), &["-d", armored.to_str().unwrap()], None);
    assert_eq!((out.code, out.text()), (0, "file form".to_string()));
    let binary = dir.path().join("msg.bin");
    fs::write(&binary, dearmor(&msg.stdout)).unwrap();
    let out = pqr(dir.path(), &["-d", binary.to_str().unwrap()], None);
    assert_eq!((out.code, out.text()), (0, "file form".to_string()));
}

#[test]
fn decrypt_flag_reads_stdin_and_honors_identity() {
    let dir = with_identity("main");
    pqr(dir.path(), &["keygen", "-i", "other"], None);
    let msg = pqr(dir.path(), &["-i", "other", "via stdin"], None);
    let out = pqr(dir.path(), &["-i", "other", "-d"], Some(&msg.stdout));
    assert_eq!((out.code, out.text()), (0, "via stdin".to_string()));
}

#[test]
fn decrypt_flag_rejects_a_non_file_non_message() {
    let dir = with_identity("main");
    let out = pqr(dir.path(), &["-d", "no-such-file.pgp"], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
    assert!(out.stderr.contains("not a file or a PGP message"));
    assert!(!out.stderr.contains("no-such-file.pgp"));
}

#[test]
fn the_old_d_subcommand_is_gone() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["x"], None);
    // `d <message>` is now an extra positional argument: clap rejects it (exit 1).
    let out = pqr(dir.path(), &["d", &msg.text()], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
    // A lone `d` is plain text, so it is encrypted, not decrypted.
    let lone = pqr(dir.path(), &["d"], None);
    assert_eq!(lone.code, 0, "{}", lone.stderr);
    let back = pqr(dir.path(), &["-d"], Some(&lone.stdout));
    assert_eq!(back.text(), "d");
}

/// Encrypt `text` for identity `name` and save the armored message as `<name>.pgp` in `dir`.
fn saved_message(dir: &Path, name: &str, text: &str) -> (String, String) {
    let msg = pqr(dir, &["-i", name, text], None);
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    let path = dir.join(format!("{name}.pgp"));
    fs::write(&path, &msg.stdout).unwrap();
    (path.to_str().unwrap().to_string(), msg.text())
}

#[test]
fn decrypt_switch_works_in_every_argument_order() {
    let dir = with_identity("work");
    let (file, armor) = saved_message(dir.path(), "work", "any order");
    let wire = |args: &[&str], stdin: Option<&[u8]>| {
        let out = pqr(dir.path(), args, stdin);
        assert_eq!(out.code, 0, "{args:?}: {}", out.stderr);
        assert_eq!(out.text(), "any order", "{args:?}");
    };
    wire(&["-i", "work", "-d", &file], None);
    wire(&["-d", "-i", "work", &file], None);
    wire(&["-d", &file, "-i", "work"], None);
    wire(&["-i", "work", "--decrypt", &file], None);
    wire(&["-d", "-i", "work", &armor], None);
    wire(&["-i", "work", "-d", &armor], None);
    wire(&["-d", &armor, "-i", "work"], None);
    wire(&["-d", "-i", "work"], Some(armor.as_bytes()));
    wire(&["-i", "work", "-d"], Some(armor.as_bytes()));
}

#[test]
fn decrypt_switch_defaults_to_main_from_file_and_stdin() {
    let dir = with_identity("main");
    let (file, armor) = saved_message(dir.path(), "main", "default key");
    let out = pqr(dir.path(), &["-d", &file], None);
    assert_eq!(out.text(), "default key");
    let out = pqr(dir.path(), &["-d"], Some(armor.as_bytes()));
    assert_eq!(out.text(), "default key");
}

#[test]
fn explicit_encrypt_matches_bare_encrypt() {
    let dir = with_identity("main");
    let msg = pqr(dir.path(), &["-e", "x"], None);
    assert_eq!(msg.code, 0, "{}", msg.stderr);
    let back = pqr(dir.path(), &["-d"], Some(&msg.stdout));
    assert_eq!(back.text(), "x");
    let from_stdin = pqr(dir.path(), &["-e"], Some(b"piped\n"));
    assert_eq!(from_stdin.code, 0, "{}", from_stdin.stderr);
    let back = pqr(dir.path(), &["-d"], Some(&from_stdin.stdout));
    assert_eq!(back.text(), "piped\n");
}

#[test]
fn explicit_encrypt_takes_recipient_and_identity_flags() {
    let dir = with_identity("main");
    pqr(dir.path(), &["keygen", "-i", "other"], None);
    let pub_path = dir.path().join("keys/other.pub");
    let msg = pqr(
        dir.path(),
        &["-e", "-r", pub_path.to_str().unwrap(), "for other"],
        None,
    );
    let back = pqr(dir.path(), &["-i", "other", "-d"], Some(&msg.stdout));
    assert_eq!(back.text(), "for other");
    let msg = pqr(dir.path(), &["-e", "-i", "other", "again"], None);
    let back = pqr(dir.path(), &["-d", "-i", "other"], Some(&msg.stdout));
    assert_eq!(back.text(), "again");
}

#[test]
fn encrypt_and_decrypt_switches_conflict() {
    let dir = with_identity("main");
    let out = pqr(dir.path(), &["-e", "-d", "x"], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
}

#[test]
fn unknown_flag_is_refused_not_encrypted() {
    let dir = with_identity("main");
    let out = pqr(dir.path(), &["--bogus"], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
    assert!(out.stderr.contains("unknown option: --bogus"));
    let out = pqr(dir.path(), &["-e", "-n"], None);
    assert_eq!(out.code, 1);
    assert!(out.stdout.is_empty());
}

#[test]
fn double_dash_allows_text_starting_with_a_hyphen() {
    let dir = with_identity("main");
    let enc = pqr(dir.path(), &["--", "-text"], None);
    assert_eq!(enc.code, 0, "{}", enc.stderr);
    let dec = pqr(dir.path(), &["-d"], Some(&enc.stdout));
    assert_eq!(dec.text(), "-text");
}

#[test]
fn decrypt_flag_still_takes_an_armored_string_argument() {
    let dir = with_identity("main");
    let enc = pqr(dir.path(), &["hello"], None).text();
    let dec = pqr(dir.path(), &["-d", &enc], None);
    assert_eq!(dec.code, 0, "{}", dec.stderr);
    assert_eq!(dec.text(), "hello");
}

#[test]
fn raw_input_never_appears_in_error_messages() {
    let dir = with_identity("main");
    let out = pqr(dir.path(), &["-d"], Some(b"SECRET_TOKEN_12345"));
    assert_ne!(out.code, 0);
    assert!(!out.stderr.contains("SECRET_TOKEN"), "{}", out.stderr);

    let armored = pqr(dir.path(), &["hello"], None).text();
    let cut = &armored[..armored.len() / 2];
    let out = pqr(dir.path(), &["-d"], Some(cut.as_bytes()));
    assert_ne!(out.code, 0);
    assert!(!out.stderr.contains(&cut[40..80]), "{}", out.stderr);

    let key = dir.path().join("keys/main.key");
    let text = fs::read_to_string(&key).unwrap();
    fs::write(
        &key,
        format!("{}SECRET_TOKEN_12345", &text[..text.len() / 2]),
    )
    .unwrap();
    let out = pqr(dir.path(), &["-d"], Some(armored.as_bytes()));
    assert_eq!(out.code, 1);
    assert!(out.stderr.contains("not a valid pqr key"), "{}", out.stderr);
    assert!(!out.stderr.contains("SECRET_TOKEN"), "{}", out.stderr);
    assert!(!out.stderr.contains(&text[40..80]), "{}", out.stderr);
}

#[test]
fn compressed_message_is_refused_with_exit_3_and_empty_stdout() {
    use pgp::composed::{ArmorOptions, MessageBuilder};
    use pgp::crypto::{aead::AeadAlgorithm, sym::SymmetricKeyAlgorithm};
    use pgp::types::CompressionAlgorithm;

    let dir = with_identity("main");
    let public = fs::read_to_string(dir.path().join("keys/main.pub")).unwrap();
    let (key, _) = SignedPublicKey::from_string(&public).unwrap();
    let subkey = key
        .public_subkeys
        .iter()
        .find(|sub| sub.algorithm() == PublicKeyAlgorithm::MlKem768X25519)
        .unwrap();
    let mut rng = rand::thread_rng();
    let mut builder = MessageBuilder::from_bytes("", b"zip bomb".to_vec()).seipd_v2(
        &mut rng,
        SymmetricKeyAlgorithm::AES256,
        AeadAlgorithm::Ocb,
        Default::default(),
    );
    builder.compression(CompressionAlgorithm::ZLIB);
    builder.encrypt_to_key(&mut rng, subkey).unwrap();
    let armored = builder
        .to_armored_string(&mut rng, ArmorOptions::default())
        .unwrap();
    let out = pqr(dir.path(), &["-d"], Some(armored.as_bytes()));
    assert_eq!(out.code, 3, "{}", out.stderr);
    assert!(out.stdout.is_empty());
    assert!(out.stderr.contains("compressed messages are not supported"));
}

/// A public key in pqr's profile whose encryption subkey is expired or revoked.
fn pq_public_armor_with_dead_subkey(revoked: bool) -> String {
    use pgp::packet::KeyFlags;
    use pgp::packet::{SignatureConfig, SignatureType, Subpacket, SubpacketData};
    use pgp::types::{Duration, Password, Timestamp};

    let now = Timestamp::now().as_secs();
    let subkey = SubkeyParamsBuilder::default()
        .version(KeyVersion::V6)
        .key_type(KeyType::MlKem768X25519)
        .can_encrypt(EncryptionCaps::All)
        .created_at(Timestamp::from_secs(now - 1000))
        .build()
        .unwrap();
    let params = SecretKeyParamsBuilder::default()
        .version(KeyVersion::V6)
        .key_type(KeyType::MlDsa65Ed25519)
        .can_certify(true)
        .can_sign(true)
        .primary_user_id("dead subkey".into())
        .subkey(subkey)
        .build()
        .unwrap();
    let secret = params.generate(rand::thread_rng()).unwrap();
    let mut public = secret.to_public_key();
    let primary_pub = secret.primary_key.public_key();
    let typ = if revoked {
        SignatureType::SubkeyRevocation
    } else {
        SignatureType::SubkeyBinding
    };
    let mut config =
        SignatureConfig::from_key(rand::thread_rng(), &secret.primary_key, typ).unwrap();
    let mut flags = KeyFlags::default();
    flags.set_encrypt_comms(true);
    flags.set_encrypt_storage(true);
    config.hashed_subpackets = vec![
        Subpacket::regular(SubpacketData::SignatureCreationTime(Timestamp::from_secs(
            now - 500,
        )))
        .unwrap(),
        Subpacket::regular(SubpacketData::KeyFlags(flags)).unwrap(),
        Subpacket::regular(SubpacketData::IssuerFingerprint(
            secret.primary_key.fingerprint(),
        ))
        .unwrap(),
    ];
    if !revoked {
        // Valid for 60 seconds after creation (1000 seconds ago).
        config.hashed_subpackets.push(
            Subpacket::regular(SubpacketData::KeyExpirationTime(Duration::from_secs(60))).unwrap(),
        );
    }
    let sig = config
        .sign_subkey_binding(
            &secret.primary_key,
            &primary_pub,
            &Password::empty(),
            &public.public_subkeys[0].key,
        )
        .unwrap();
    if revoked {
        public.public_subkeys[0].signatures.push(sig);
    } else {
        public.public_subkeys[0].signatures = vec![sig];
    }
    public.to_armored_string(None.into()).unwrap()
}

#[test]
fn recipient_with_expired_encryption_subkey_is_refused() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("expired.pub");
    fs::write(&path, pq_public_armor_with_dead_subkey(false)).unwrap();
    let out = pqr(dir.path(), &["-r", path.to_str().unwrap(), "x"], None);
    assert_eq!(out.code, 1, "{}", out.stderr);
    assert!(out.stderr.contains("encryption key is expired or revoked"));
    assert!(out.stdout.is_empty());
}

#[test]
fn recipient_with_revoked_encryption_subkey_is_refused() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("revoked.pub");
    fs::write(&path, pq_public_armor_with_dead_subkey(true)).unwrap();
    let out = pqr(dir.path(), &["-r", path.to_str().unwrap(), "x"], None);
    assert_eq!(out.code, 1, "{}", out.stderr);
    assert!(out.stderr.contains("encryption key is expired or revoked"));
    assert!(out.stdout.is_empty());
}