ks 0.5.0

A local-first, age-encrypted secret manager in Rust
Documentation
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
//! age-based cryptography: the building blocks for the whole store.
//!
//! This module bundles three tightly-coupled concerns that all operate on age
//! key material:
//!
//! - **Encryption primitives.** [`encrypt`] targets one or more X25519
//!   recipients and needs only public keys, so secrets can be written without
//!   ever unlocking the identity. [`decrypt`] needs the user's
//!   [`x25519::Identity`].
//! - **Identity file.** [`create_identity`] / [`load_identity`] manage an age
//!   scrypt (passphrase) container whose plaintext is the bech32 secret key.
//!   The format is interoperable with the `age` / `rage` CLIs
//!   (`age -d identity.age`).
//! - **Recipient list.** [`load_recipients`] / [`save_recipients`] read and
//!   write the plaintext `age1…` allow-list stored alongside the secrets.

use std::io::{Read as _, Write as _};
use std::path::Path;
use std::str::FromStr as _;

use age::secrecy::{ExposeSecret as _, SecretString};
use age::x25519;
use zeroize::Zeroizing;

use crate::error::{Error, Result};

/// Encrypts `plaintext` to one or more X25519 recipients (age recipient mode).
///
/// # Errors
/// Returns [`Error::Encrypt`] if `recipients` is empty or the age encoder fails.
pub fn encrypt(plaintext: &[u8], recipients: &[x25519::Recipient]) -> Result<Vec<u8>> {
    if recipients.is_empty() {
        return Err(Error::Encrypt("no recipients".into()));
    }
    let encryptor =
        age::Encryptor::with_recipients(recipients.iter().map(|r| -> &dyn age::Recipient { r }))
            .map_err(|e| Error::Encrypt(e.to_string()))?;

    let mut output = Vec::with_capacity(plaintext.len() + 256);
    let mut writer = encryptor
        .wrap_output(&mut output)
        .map_err(|e| Error::Encrypt(e.to_string()))?;
    writer
        .write_all(plaintext)
        .map_err(|e| Error::Encrypt(e.to_string()))?;
    writer.finish().map_err(|e| Error::Encrypt(e.to_string()))?;
    Ok(output)
}

/// Decrypts a recipient-mode `ciphertext` with the given X25519 identity.
///
/// The plaintext is returned in a [`Zeroizing`] buffer, scrubbed on drop.
///
/// # Errors
/// Returns [`Error::Decrypt`] if the file is passphrase-encrypted (wrong mode)
/// or the age decoder fails.
pub fn decrypt(ciphertext: &[u8], identity: &x25519::Identity) -> Result<Zeroizing<Vec<u8>>> {
    let decryptor =
        age::Decryptor::new_buffered(ciphertext).map_err(|e| Error::Decrypt(e.to_string()))?;
    if decryptor.is_scrypt() {
        return Err(Error::Decrypt(
            "file was encrypted with a passphrase, not a recipient".into(),
        ));
    }
    let identities: [&dyn age::Identity; 1] = [identity];
    let mut reader = decryptor
        .decrypt(identities.into_iter())
        .map_err(|e| Error::Decrypt(e.to_string()))?;

    let mut buf = Zeroizing::new(Vec::with_capacity(ciphertext.len()));
    reader
        .read_to_end(&mut buf)
        .map_err(|e| Error::Decrypt(e.to_string()))?;
    Ok(buf)
}

/// Generates a new X25519 identity, encrypts it with `passphrase`, and writes
/// it to `path` (mode `0o600` on Unix). Refuses to overwrite an existing file.
///
/// # Errors
/// - [`Error::IdentityExists`] if `path` already exists.
/// - [`Error::Io`] / [`Error::Encrypt`] on filesystem or age failures.
pub fn create_identity(path: &Path, passphrase: SecretString) -> Result<x25519::Identity> {
    if path.exists() {
        return Err(Error::IdentityExists(path.to_path_buf()));
    }
    let identity = x25519::Identity::generate();
    let serialised = identity.to_string();
    let ciphertext = encrypt_with_passphrase(serialised.expose_secret().as_bytes(), passphrase)?;
    write_atomic(path, &ciphertext)?;
    Ok(identity)
}

/// Loads and decrypts an identity file with the supplied passphrase.
///
/// # Errors
/// - [`Error::IdentityNotFound`] if the file is absent.
/// - [`Error::WrongPassphrase`] if `passphrase` does not match.
/// - [`Error::Decrypt`] / [`Error::Io`] on other failures.
pub fn load_identity(path: &Path, passphrase: SecretString) -> Result<x25519::Identity> {
    if !path.exists() {
        return Err(Error::IdentityNotFound(path.to_path_buf()));
    }
    identity_from_ciphertext(&std::fs::read(path)?, passphrase)
}

/// Decrypts a passphrase-protected identity container and extracts its key.
fn identity_from_ciphertext(
    ciphertext: &[u8],
    passphrase: SecretString,
) -> Result<x25519::Identity> {
    let plaintext = decrypt_with_passphrase(ciphertext, passphrase)?;
    parse_identity(&plaintext)
}

/// Re-encrypts an existing identity file with a new passphrase.
///
/// # Errors
/// Same as [`load_identity`] plus any encryption errors.
pub fn change_passphrase(path: &Path, current: SecretString, new: SecretString) -> Result<()> {
    let identity = load_identity(path, current)?;
    let serialised = identity.to_string();
    let ciphertext = encrypt_with_passphrase(serialised.expose_secret().as_bytes(), new)?;
    write_atomic(path, &ciphertext)?;
    Ok(())
}

/// Writes a backup copy of the encrypted identity at `src` to `dst`.
///
/// The copy is still passphrase-protected age — exporting never exposes the
/// secret key in the clear. With `armor`, the copy is ASCII-armored (printable /
/// pasteable); otherwise the raw bytes are copied verbatim. The destination is
/// created owner-only and must not already exist.
///
/// # Errors
/// [`Error::IdentityNotFound`] if `src` is absent, [`Error::IdentityExists`] if
/// `dst` already exists, or [`Error::Io`] / [`Error::Encrypt`] on failure.
pub fn export_identity(src: &Path, dst: &Path, armor: bool) -> Result<()> {
    if !src.exists() {
        return Err(Error::IdentityNotFound(src.to_path_buf()));
    }
    if dst.exists() {
        return Err(Error::IdentityExists(dst.to_path_buf()));
    }
    let raw = std::fs::read(src)?;
    let bytes = if armor { to_armor(&raw)? } else { raw };
    write_atomic(dst, &bytes)
}

/// Returns the encrypted identity at `src` as ASCII-armored age text, suitable
/// for printing and storing in a password manager. Still passphrase-protected.
///
/// # Errors
/// [`Error::IdentityNotFound`] if `src` is absent, or [`Error::Io`] /
/// [`Error::Encrypt`] on failure.
pub fn armored_identity(src: &Path) -> Result<String> {
    if !src.exists() {
        return Err(Error::IdentityNotFound(src.to_path_buf()));
    }
    let armored = to_armor(&std::fs::read(src)?)?;
    String::from_utf8(armored)
        .map_err(|e| Error::Encrypt(format!("armored identity is not valid UTF-8: {e}")))
}

/// Restores an identity from a backup (binary or ASCII-armored) into `dst`.
///
/// Validates that `passphrase` decrypts the backup *before* writing. The restored
/// file is always canonical binary age, created owner-only. Refuses to overwrite
/// an existing identity unless `force` is set. Returns the unlocked identity so
/// the caller can confirm the public key.
///
/// # Errors
/// [`Error::WrongPassphrase`] if the passphrase does not match the backup,
/// [`Error::IdentityExists`] if `dst` exists and `force` is false, or
/// [`Error::Decrypt`] / [`Error::Io`] on other failures.
pub fn import_identity(
    backup: &[u8],
    dst: &Path,
    passphrase: SecretString,
    force: bool,
) -> Result<x25519::Identity> {
    let raw = from_armor(backup)?;
    let identity = identity_from_ciphertext(&raw, passphrase)?;
    if dst.exists() && !force {
        return Err(Error::IdentityExists(dst.to_path_buf()));
    }
    write_atomic(dst, &raw)?;
    Ok(identity)
}

/// ASCII-armors raw age bytes for printable backup.
fn to_armor(raw: &[u8]) -> Result<Vec<u8>> {
    use age::armor::{ArmoredWriter, Format};
    let mut out = Vec::with_capacity(raw.len());
    let mut writer = ArmoredWriter::wrap_output(&mut out, Format::AsciiArmor)
        .map_err(|e| Error::Encrypt(e.to_string()))?;
    writer
        .write_all(raw)
        .map_err(|e| Error::Encrypt(e.to_string()))?;
    writer.finish().map_err(|e| Error::Encrypt(e.to_string()))?;
    Ok(out)
}

/// De-armors age input when it is ASCII-armored, otherwise passes the binary
/// bytes through unchanged.
fn from_armor(input: &[u8]) -> Result<Vec<u8>> {
    use age::armor::ArmoredReader;
    let mut reader = ArmoredReader::new(input);
    let mut out = Vec::with_capacity(input.len());
    reader
        .read_to_end(&mut out)
        .map_err(|e| Error::Decrypt(e.to_string()))?;
    Ok(out)
}

/// Parses a recipients-file body into unique public keys.
///
/// Strips `#` comments and blank lines. Duplicates — which a git `merge=union`
/// resolution of concurrent edits can introduce — are collapsed, keeping
/// first-seen order.
///
/// # Errors
/// Returns [`Error::InvalidRecipient`] if a non-comment line fails to parse.
pub fn parse_recipients(text: &str) -> Result<Vec<x25519::Recipient>> {
    let mut out = Vec::new();
    for (idx, raw) in text.lines().enumerate() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let recipient = x25519::Recipient::from_str(line)
            .map_err(|e| Error::InvalidRecipient(format!("line {}: {e}", idx.saturating_add(1))))?;
        if !recipients_contain(&out, &recipient) {
            out.push(recipient);
        }
    }
    Ok(out)
}

/// Reads and parses the recipients file at `path`.
///
/// # Errors
/// - [`Error::NoRecipients`] if the file is missing or contains no keys.
/// - [`Error::Io`] / [`Error::InvalidRecipient`] on read or parse failures.
pub fn load_recipients(path: &Path) -> Result<Vec<x25519::Recipient>> {
    if !path.exists() {
        return Err(Error::NoRecipients(path.to_path_buf()));
    }
    let recipients = parse_recipients(&std::fs::read_to_string(path)?)?;
    if recipients.is_empty() {
        return Err(Error::NoRecipients(path.to_path_buf()));
    }
    Ok(recipients)
}

/// Atomically writes the recipients file at `path`, sorted and de-duplicated.
///
/// A canonical on-disk form keeps git diffs minimal and lets a `merge=union`
/// resolution of concurrent edits converge cleanly.
///
/// # Errors
/// Returns [`Error::Io`] on any filesystem failure.
pub fn save_recipients(path: &Path, recipients: &[x25519::Recipient]) -> Result<()> {
    let mut keys: Vec<String> = recipients.iter().map(ToString::to_string).collect();
    keys.sort_unstable();
    keys.dedup();
    let mut body = String::from(
        "# ks recipients — public keys allowed to decrypt this store.\n\
         # Add one with `ks recipients add <age1...>`.\n",
    );
    for key in &keys {
        body.push_str(key);
        body.push('\n');
    }
    write_atomic(path, body.as_bytes())
}

/// Returns `true` if `target` is present in `list` (by textual public-key form).
#[must_use]
pub fn recipients_contain(list: &[x25519::Recipient], target: &x25519::Recipient) -> bool {
    let needle = target.to_string();
    list.iter().any(|r| r.to_string() == needle)
}

/// Atomically writes `bytes` to `path`: create a uniquely-named sibling temp
/// file with `O_EXCL` (owner-only `0o600` on Unix), fsync it, rename it over the
/// target, then fsync the parent directory so the rename is durable.
///
/// The temp name is randomised so concurrent writers to the same target never
/// share a scratch file, and `O_EXCL` refuses to follow a pre-planted symlink.
/// On any failure the temp file is removed.
///
/// # Errors
/// Returns [`Error::Io`] on any filesystem failure.
pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    create_dir_all_secure(parent)?;

    let file_name = path
        .file_name()
        .and_then(|s| s.to_str())
        .ok_or_else(|| Error::Io(std::io::Error::other("invalid target file name")))?;
    let tmp = parent.join(format!(".{file_name}.{:016x}.tmp", rand::random::<u64>()));

    let write = || -> Result<()> {
        let mut file = open_excl_owner_only(&tmp)?;
        file.write_all(bytes)?;
        file.sync_all()?;
        Ok(())
    };
    if let Err(e) = write() {
        std::fs::remove_file(&tmp).ok();
        return Err(e);
    }
    if let Err(e) = std::fs::rename(&tmp, path) {
        std::fs::remove_file(&tmp).ok();
        return Err(Error::Io(e));
    }
    fsync_dir(parent);
    Ok(())
}

/// Renames `src` over `dst` (replacing any existing file), creating `dst`'s
/// parent if needed and fsyncing it so the replacement survives a crash. Used to
/// commit a file previously staged with [`write_atomic`].
///
/// # Errors
/// Returns [`Error::Io`] on any filesystem failure.
pub(crate) fn rename_replace(src: &Path, dst: &Path) -> Result<()> {
    let parent = dst.parent().unwrap_or_else(|| Path::new("."));
    create_dir_all_secure(parent)?;
    std::fs::rename(src, dst)?;
    fsync_dir(parent);
    Ok(())
}

fn encrypt_with_passphrase(plaintext: &[u8], passphrase: SecretString) -> Result<Vec<u8>> {
    let encryptor = age::Encryptor::with_user_passphrase(passphrase);
    let mut output = Vec::with_capacity(plaintext.len() + 256);
    let mut writer = encryptor
        .wrap_output(&mut output)
        .map_err(|e| Error::Encrypt(e.to_string()))?;
    writer
        .write_all(plaintext)
        .map_err(|e| Error::Encrypt(e.to_string()))?;
    writer.finish().map_err(|e| Error::Encrypt(e.to_string()))?;
    Ok(output)
}

fn decrypt_with_passphrase(
    ciphertext: &[u8],
    passphrase: SecretString,
) -> Result<Zeroizing<Vec<u8>>> {
    let decryptor =
        age::Decryptor::new_buffered(ciphertext).map_err(|e| Error::Decrypt(e.to_string()))?;
    if !decryptor.is_scrypt() {
        return Err(Error::Decrypt(
            "file was encrypted to a recipient, not a passphrase".into(),
        ));
    }
    let identity = age::scrypt::Identity::new(passphrase);
    let identities: [&dyn age::Identity; 1] = [&identity];
    let mut reader = decryptor
        .decrypt(identities.into_iter())
        .map_err(|_| Error::WrongPassphrase)?;

    let mut buf = Zeroizing::new(Vec::with_capacity(ciphertext.len()));
    reader
        .read_to_end(&mut buf)
        .map_err(|e| Error::Decrypt(e.to_string()))?;
    Ok(buf)
}

/// Extracts an [`x25519::Identity`] from a decrypted identity payload.
///
/// Accepts bare (`AGE-SECRET-KEY-1…`) and age-keygen formatted input; the
/// first non-comment, non-empty line is treated as the secret key.
fn parse_identity(plaintext: &[u8]) -> Result<x25519::Identity> {
    let text = std::str::from_utf8(plaintext)
        .map_err(|e| Error::Decrypt(format!("identity is not valid UTF-8: {e}")))?;
    for raw in text.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        return x25519::Identity::from_str(line)
            .map_err(|e| Error::Decrypt(format!("invalid identity payload: {e}")));
    }
    Err(Error::Decrypt("identity file is empty".into()))
}

/// Creates `dir` and any missing parents, restricting newly-created directories
/// to the owner (`0o700`) on Unix. Pre-existing directories are left untouched.
#[cfg(unix)]
pub(crate) fn create_dir_all_secure(dir: &Path) -> Result<()> {
    use std::os::unix::fs::DirBuilderExt as _;
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(dir)
        .map_err(Error::Io)
}

#[cfg(not(unix))]
pub(crate) fn create_dir_all_secure(dir: &Path) -> Result<()> {
    std::fs::create_dir_all(dir).map_err(Error::Io)
}

/// Opens a freshly-created file for writing, failing if it already exists
/// (`O_EXCL`). On Unix the file is created with mode `0o600` in one step, so
/// there is no window during which it is world-readable.
#[cfg(unix)]
fn open_excl_owner_only(path: &Path) -> Result<std::fs::File> {
    use std::os::unix::fs::OpenOptionsExt as _;
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .map_err(Error::Io)
}

#[cfg(not(unix))]
fn open_excl_owner_only(path: &Path) -> Result<std::fs::File> {
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(Error::Io)
}

/// Best-effort fsync of a directory so a prior rename is durable. Unix-only;
/// Windows has no portable directory fsync, so this is a no-op there.
#[cfg(unix)]
fn fsync_dir(dir: &Path) {
    if let Ok(f) = std::fs::File::open(dir) {
        f.sync_all().ok();
    }
}

#[cfg(not(unix))]
const fn fsync_dir(_dir: &Path) {}

#[cfg(test)]
mod tests {
    use super::*;

    fn tempdir() -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("ks-crypto-{}", rand::random::<u64>()));
        std::fs::create_dir_all(&dir).expect("create temp dir");
        dir
    }

    #[test]
    fn recipient_roundtrip() {
        let identity = x25519::Identity::generate();
        let ct = encrypt(b"super secret api token", &[identity.to_public()]).expect("encrypt");
        let pt = decrypt(&ct, &identity).expect("decrypt");
        assert_eq!(&pt[..], b"super secret api token");
    }

    #[test]
    fn identity_create_load_roundtrip() {
        let path = tempdir().join("identity.age");
        let pp = SecretString::from("hunter2".to_owned());
        let created = create_identity(&path, pp.clone()).expect("create");
        let loaded = load_identity(&path, pp).expect("load");
        assert_eq!(
            created.to_public().to_string(),
            loaded.to_public().to_string()
        );
    }

    #[test]
    fn identity_refuses_overwrite() {
        let path = tempdir().join("identity.age");
        let pp = SecretString::from("pw".to_owned());
        create_identity(&path, pp.clone()).expect("first");
        assert!(matches!(
            create_identity(&path, pp),
            Err(Error::IdentityExists(_))
        ));
    }

    #[test]
    fn identity_wrong_passphrase_distinguishable() {
        let path = tempdir().join("identity.age");
        create_identity(&path, SecretString::from("right".to_owned())).expect("create");
        let err = load_identity(&path, SecretString::from("wrong".to_owned()))
            .err()
            .expect("must fail");
        assert!(matches!(err, Error::WrongPassphrase));
    }

    #[test]
    fn change_passphrase_works() {
        let path = tempdir().join("identity.age");
        let one = SecretString::from("one".to_owned());
        let two = SecretString::from("two".to_owned());
        create_identity(&path, one.clone()).expect("create");
        change_passphrase(&path, one.clone(), two.clone()).expect("change");
        assert!(load_identity(&path, one).is_err());
        assert!(load_identity(&path, two).is_ok());
    }

    #[test]
    fn identity_export_import_roundtrip_binary() {
        let dir = tempdir();
        let src = dir.join("identity.age");
        let pp = SecretString::from("backup-pw".to_owned());
        let created = create_identity(&src, pp.clone()).expect("create");

        let backup = dir.join("backup.age");
        export_identity(&src, &backup, false).expect("export");
        assert!(
            matches!(
                export_identity(&src, &backup, false),
                Err(Error::IdentityExists(_))
            ),
            "export must refuse to overwrite an existing backup"
        );

        let restored_path = dir.join("restored.age");
        let bytes = std::fs::read(&backup).expect("read backup");
        let restored = import_identity(&bytes, &restored_path, pp, false).expect("import");
        assert_eq!(
            created.to_public().to_string(),
            restored.to_public().to_string()
        );
        load_identity(&restored_path, SecretString::from("backup-pw".to_owned()))
            .expect("restored identity loads normally");
    }

    #[test]
    fn identity_export_import_roundtrip_armored() {
        let dir = tempdir();
        let src = dir.join("identity.age");
        let pp = SecretString::from("backup-pw".to_owned());
        let created = create_identity(&src, pp.clone()).expect("create");

        let armored = armored_identity(&src).expect("armor");
        assert!(
            armored.contains("BEGIN AGE ENCRYPTED FILE"),
            "armored output must carry the age armor header"
        );

        let restored_path = dir.join("restored.age");
        let restored =
            import_identity(armored.as_bytes(), &restored_path, pp, false).expect("import armored");
        assert_eq!(
            created.to_public().to_string(),
            restored.to_public().to_string()
        );
    }

    #[test]
    fn identity_import_rejects_wrong_passphrase() {
        let dir = tempdir();
        let src = dir.join("identity.age");
        create_identity(&src, SecretString::from("right".to_owned())).expect("create");
        let bytes = std::fs::read(&src).expect("read");
        let restored = dir.join("restored.age");
        let err = import_identity(
            &bytes,
            &restored,
            SecretString::from("wrong".to_owned()),
            false,
        )
        .err()
        .expect("must fail");
        assert!(matches!(err, Error::WrongPassphrase));
        assert!(
            !restored.exists(),
            "a failed import must not write the destination"
        );
    }

    #[test]
    fn identity_import_refuses_overwrite_without_force() {
        let dir = tempdir();
        let src = dir.join("identity.age");
        let pp = SecretString::from("pw".to_owned());
        create_identity(&src, pp.clone()).expect("create");
        let bytes = std::fs::read(&src).expect("read");
        let dst = dir.join("existing.age");
        std::fs::write(&dst, b"do not clobber").expect("write existing");
        assert!(matches!(
            import_identity(&bytes, &dst, pp.clone(), false),
            Err(Error::IdentityExists(_))
        ));
        import_identity(&bytes, &dst, pp, true).expect("force import");
        load_identity(&dst, SecretString::from("pw".to_owned())).expect("load forced");
    }

    #[test]
    fn recipients_parse_skips_comments() {
        let id = x25519::Identity::generate();
        let pubkey = id.to_public().to_string();
        let parsed = parse_recipients(&format!("# c\n\n{pubkey}\n")).expect("parse");
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed.first().expect("one recipient").to_string(), pubkey);
    }

    #[test]
    fn recipients_save_load_roundtrip() {
        let path = tempdir().join(".age-recipients");
        let id = x25519::Identity::generate();
        let r = id.to_public();
        save_recipients(&path, std::slice::from_ref(&r)).expect("save");
        let loaded = load_recipients(&path).expect("load");
        assert_eq!(loaded.len(), 1);
        assert!(recipients_contain(&loaded, &r));
    }

    #[test]
    fn recipients_reject_invalid() {
        assert!(parse_recipients("not-a-key").is_err());
    }

    #[test]
    fn recipients_parse_collapses_duplicates() {
        let pubkey = x25519::Identity::generate().to_public().to_string();
        // A git `merge=union` resolution can leave the same key twice.
        let parsed = parse_recipients(&format!("{pubkey}\n{pubkey}\n")).expect("parse");
        assert_eq!(parsed.len(), 1, "duplicate keys must be collapsed");
    }

    #[test]
    fn recipients_save_is_sorted_and_deduped() {
        let path = tempdir().join(".age-recipients");
        let a = x25519::Identity::generate().to_public();
        let b = x25519::Identity::generate().to_public();
        save_recipients(&path, &[b.clone(), a, b]).expect("save");
        let body = std::fs::read_to_string(&path).expect("read");
        let keys: Vec<&str> = body
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .collect();
        assert_eq!(keys.len(), 2, "duplicates must be removed on save");
        let mut sorted = keys.clone();
        sorted.sort_unstable();
        assert_eq!(
            keys, sorted,
            "keys must be written in canonical sorted order"
        );
    }
}