toride-ssh-key 0.1.0

SSH key lifecycle management: generation, inventory, installation, and repair
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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
use super::*;

#[test]
fn validate_key_name_empty() {
    assert!(validate_key_name("").is_err());
}

#[test]
fn validate_key_name_slash() {
    assert!(validate_key_name("../etc/passwd").is_err());
}

#[test]
fn validate_key_name_backslash() {
    assert!(validate_key_name("..\\etc\\passwd").is_err());
}

#[test]
fn validate_key_name_dot_dot() {
    assert!(validate_key_name("../../etc/passwd").is_err());
}

#[test]
fn validate_key_name_dot_dot_in_middle() {
    assert!(validate_key_name("foo/../bar").is_err());
}

#[test]
fn validate_key_name_valid() {
    assert!(validate_key_name("id_ed25519").is_ok());
    assert!(validate_key_name("my-key").is_ok());
    assert!(validate_key_name("key_with_underscores").is_ok());
}

#[test]
fn validate_key_name_dot_file() {
    // Dot files like ".ssh" should be valid (no path traversal)
    assert!(validate_key_name(".hidden").is_ok());
}

#[test]
fn validate_key_name_unicode() {
    // Unicode names should be valid as long as no path traversal
    assert!(validate_key_name("clé").is_ok());
}

#[test]
fn validate_key_name_just_dot_dot() {
    assert!(validate_key_name("..").is_err());
}

// ---------------------------------------------------------------------------
// Production-grade weird edge cases
// ---------------------------------------------------------------------------

#[test]
fn validate_key_name_with_spaces() {
    // Spaces in key name are unusual but not a security issue
    assert!(validate_key_name("my key").is_ok());
}

#[test]
fn validate_key_name_with_tabs() {
    assert!(validate_key_name("my\tkey").is_ok());
}

#[test]
fn validate_key_name_with_null_byte() {
    // Null bytes are now rejected to prevent path truncation attacks
    assert!(validate_key_name("my\0key").is_err());
}

#[test]
fn validate_key_name_with_control_chars() {
    assert!(validate_key_name("my\x01key").is_ok()); // Not explicitly blocked
}

#[test]
fn validate_key_name_very_long() {
    // Names up to 255 bytes are OK (filesystem limit).
    let name_255 = "a".repeat(255);
    assert!(validate_key_name(&name_255).is_ok());

    // Names over 255 bytes are rejected.
    let name_256 = "a".repeat(256);
    assert!(validate_key_name(&name_256).is_err());
}

#[test]
fn validate_key_name_exactly_255_bytes_accepted() {
    // The maximum valid key name length: exactly 255 bytes.
    let name = "k".repeat(255);
    assert_eq!(name.len(), 255);
    let result = validate_key_name(&name);
    assert!(
        result.is_ok(),
        "255-byte name should be accepted: {result:?}"
    );
}

#[test]
fn validate_key_name_exactly_256_bytes_rejected() {
    // One byte over the limit: must be rejected.
    let name = "k".repeat(256);
    assert_eq!(name.len(), 256);
    let result = validate_key_name(&name);
    assert!(result.is_err(), "256-byte name should be rejected");
    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("255"),
        "error should mention the 255-byte limit: {err_msg}",
    );
}

#[test]
fn validate_key_name_with_equals() {
    assert!(validate_key_name("my=key").is_ok());
}

#[test]
fn validate_key_name_with_colon() {
    assert!(validate_key_name("my:key").is_ok());
}

#[test]
fn validate_key_name_with_semicolon() {
    assert!(validate_key_name("my;key").is_ok());
}

#[test]
fn validate_key_name_with_pipe() {
    assert!(validate_key_name("my|key").is_ok());
}

#[test]
fn validate_key_name_with_ampersand() {
    assert!(validate_key_name("my&key").is_ok());
}

#[test]
fn validate_key_name_with_dollar() {
    assert!(validate_key_name("my$key").is_ok());
}

#[test]
fn validate_key_name_with_backtick() {
    assert!(validate_key_name("my`key").is_ok());
}

#[test]
fn validate_key_name_with_single_quote() {
    assert!(validate_key_name("my'key").is_ok());
}

#[test]
fn validate_key_name_with_double_quote() {
    assert!(validate_key_name("my\"key").is_ok());
}

#[test]
fn validate_key_name_with_angle_brackets() {
    assert!(validate_key_name("my<key>").is_ok());
}

#[test]
fn validate_key_name_with_square_brackets() {
    assert!(validate_key_name("my[key]").is_ok());
}

#[test]
fn validate_key_name_with_curly_braces() {
    assert!(validate_key_name("my{key}").is_ok());
}

#[test]
fn validate_key_name_with_hash() {
    assert!(validate_key_name("my#key").is_ok());
}

#[test]
fn validate_key_name_with_percent() {
    assert!(validate_key_name("my%key").is_ok());
}

#[test]
fn validate_key_name_with_at() {
    assert!(validate_key_name("my@key").is_ok());
}

#[test]
fn validate_key_name_with_exclamation() {
    assert!(validate_key_name("my!key").is_ok());
}

#[test]
fn validate_key_name_with_tilde() {
    // Tilde at start could be expanded by shell
    assert!(validate_key_name("~key").is_ok());
}

#[test]
fn validate_key_name_with_glob_chars() {
    assert!(validate_key_name("my*key").is_ok());
    assert!(validate_key_name("my?key").is_ok());
}

#[test]
fn validate_key_name_with_path_traversal_variants() {
    // Various path traversal attempts
    assert!(validate_key_name("../key").is_err());
    assert!(validate_key_name("key/..").is_err());
    assert!(validate_key_name("key/../key").is_err());
    assert!(validate_key_name("key/..").is_err());
}

#[test]
fn validate_key_name_with_backslash_traversal() {
    assert!(validate_key_name("..\\key").is_err());
    assert!(validate_key_name("key\\..").is_err());
}

// ---------------------------------------------------------------------------
// Workflow-discovered edge cases
// ---------------------------------------------------------------------------

#[test]
fn validate_key_name_null_byte_rejected() {
    // Null bytes can cause path truncation via C-level APIs
    assert!(validate_key_name("evil\0safe").is_err());
}

#[test]
fn validate_key_name_null_byte_at_start() {
    assert!(validate_key_name("\0key").is_err());
}

#[test]
fn validate_key_name_null_byte_at_end() {
    assert!(validate_key_name("key\0").is_err());
}

#[test]
fn validate_key_name_multiple_null_bytes() {
    assert!(validate_key_name("key\0\0\0").is_err());
}

// ===========================================================================
// Finding (1): passphrase must NEVER appear in ssh-keygen argv.
// change_passphrase / change_comment route through SSH_ASKPASS; the repair
// fallback does the same. These tests assert the secret is absent from the
// constructed argv and (for change_passphrase) that SSH_ASKPASS env is set.
// ===========================================================================

use std::sync::Mutex;

/// One captured [`CliRunner`] invocation: `(cmd, args, env_or_empty)`.
type CapturedCall = (String, Vec<String>, Vec<(String, String)>);

/// A [`CliRunner`] test double that records every invocation's command name,
/// argv, and (for `run_with_env`) environment, returning canned stdout.
struct CapturingRunner {
    /// Captured calls.
    calls: Mutex<Vec<CapturedCall>>,
}

impl CapturingRunner {
    fn new() -> Self {
        Self {
            calls: Mutex::new(Vec::new()),
        }
    }

    fn calls(&self) -> Vec<CapturedCall> {
        self.calls.lock().expect("lock").clone()
    }
}

#[async_trait::async_trait]
impl toride_ssh_core::CliRunner for CapturingRunner {
    async fn run(&self, cmd: &str, args: Vec<String>) -> toride_ssh_core::Result<String> {
        self.calls
            .lock()
            .expect("lock")
            .push((cmd.to_owned(), args, Vec::new()));
        Ok(String::new())
    }

    async fn run_with_env(
        &self,
        cmd: &str,
        args: Vec<String>,
        env: Vec<(String, String)>,
    ) -> toride_ssh_core::Result<String> {
        self.calls
            .lock()
            .expect("lock")
            .push((cmd.to_owned(), args, env));
        Ok(String::new())
    }

    fn tool_exists(&self, _name: &str) -> bool {
        true
    }
}

/// Build a `KeyService` backed by `runner` over a fake SSH dir. Caller owns
/// the [`SshPaths`] so the returned service borrows a stable path source.
fn service_with_runner<'a>(
    paths: &'a toride_ssh_core::SshPaths,
    runner: &'a CapturingRunner,
) -> KeyService<'a> {
    KeyService::new(paths, runner)
}

#[tokio::test]
async fn change_passphrase_omits_p_and_n_from_argv() {
    let dir = tempfile::TempDir::new().unwrap();
    let key_path = dir.path().join("id_ed25519");
    // change_passphrase checks existence; create an empty placeholder file.
    std::fs::write(&key_path, b"placeholder").unwrap();

    let runner = CapturingRunner::new();
    let paths = toride_ssh_core::SshPaths::with_dir(dir.path());
    let svc = service_with_runner(&paths, &runner);
    svc.change_passphrase(&key_path, Some("old-secret"), Some("new-secret"))
        .await
        .expect("change_passphrase should succeed");

    let calls = runner.calls();
    assert_eq!(calls.len(), 1, "exactly one ssh-keygen call expected");
    let (cmd, args, env) = &calls[0];
    assert_eq!(cmd, "ssh-keygen");
    assert!(
        !args.iter().any(|a| a == "-P"),
        "-P (old passphrase) leaked into argv: {args:?}"
    );
    assert!(
        !args.iter().any(|a| a == "-N"),
        "-N (new passphrase) leaked into argv: {args:?}"
    );
    assert!(
        !args.contains(&"old-secret".to_owned()),
        "old passphrase value leaked into argv: {args:?}"
    );
    assert!(
        !args.contains(&"new-secret".to_owned()),
        "new passphrase value leaked into argv: {args:?}"
    );
    // Must be routed through SSH_ASKPASS.
    let askpass = env
        .iter()
        .find(|(k, _)| k == "SSH_ASKPASS")
        .map(|(_, v)| v.clone())
        .expect("SSH_ASKPASS env must be set");
    assert_ne!(askpass, "");
    assert!(
        env.iter()
            .any(|(k, v)| k == "SSH_ASKPASS_REQUIRE" && v == "force"),
        "SSH_ASKPASS_REQUIRE=force must be set: {env:?}"
    );
}

#[tokio::test]
async fn change_comment_omits_p_from_argv_when_passphrase_given() {
    let dir = tempfile::TempDir::new().unwrap();
    let key_path = dir.path().join("id_ed25519");
    std::fs::write(&key_path, b"placeholder").unwrap();

    let runner = CapturingRunner::new();
    let paths = toride_ssh_core::SshPaths::with_dir(dir.path());
    let svc = service_with_runner(&paths, &runner);
    svc.change_comment(&key_path, "new-comment", Some("key-secret"))
        .await
        .expect("change_comment should succeed");

    let calls = runner.calls();
    assert_eq!(calls.len(), 1);
    let (cmd, args, env) = &calls[0];
    assert_eq!(cmd, "ssh-keygen");
    assert!(args.contains(&"-c".to_owned()));
    assert!(args.contains(&"-C".to_owned()));
    assert!(args.contains(&"new-comment".to_owned()));
    assert!(
        !args.iter().any(|a| a == "-P"),
        "-P leaked into argv: {args:?}"
    );
    assert!(
        !args.contains(&"key-secret".to_owned()),
        "passphrase value leaked into argv: {args:?}"
    );
    assert!(
        env.iter().any(|(k, _)| k == "SSH_ASKPASS"),
        "SSH_ASKPASS env must be set when a passphrase is supplied: {env:?}"
    );
}

#[tokio::test]
async fn change_comment_no_passphrase_uses_plain_run() {
    let dir = tempfile::TempDir::new().unwrap();
    let key_path = dir.path().join("id_ed25519");
    std::fs::write(&key_path, b"placeholder").unwrap();

    let runner = CapturingRunner::new();
    let paths = toride_ssh_core::SshPaths::with_dir(dir.path());
    let svc = service_with_runner(&paths, &runner);
    svc.change_comment(&key_path, "new-comment", None)
        .await
        .expect("change_comment should succeed");

    let calls = runner.calls();
    assert_eq!(calls.len(), 1);
    let (_cmd, _args, env) = &calls[0];
    // No passphrase -> no SSH_ASKPASS wiring.
    assert!(
        !env.iter().any(|(k, _)| k == "SSH_ASKPASS"),
        "SSH_ASKPASS should not be set when no passphrase: {env:?}"
    );
}

#[tokio::test]
async fn repair_public_routes_passphrase_through_askpass_not_argv() {
    let dir = tempfile::TempDir::new().unwrap();
    let key_path = dir.path().join("id_encrypted");
    // Write a body that the in-process ssh_key parser will REJECT so the
    // code falls through to the ssh-keygen -y branch (the path under fix).
    std::fs::write(&key_path, b"not-a-valid-openssh-key").unwrap();

    let runner = CapturingRunner::new();
    // repair_public -> repair::repair_public_key is invoked via the service.
    let paths = toride_ssh_core::SshPaths::with_dir(dir.path());
    let svc = KeyService::new(&paths, &runner);
    // The repair fallback runs `ssh-keygen -y -f <path>`; with the capturing
    // runner it returns Ok("") so the write step proceeds.
    let _ = svc.repair_public(&key_path, Some("repair-secret")).await;
    // repair writes the .pub; ignore outcome, inspect captured calls.

    let calls = runner.calls();
    // Find the ssh-keygen -y call.
    let Some((_cmd, args, env)) = calls
        .iter()
        .find(|(cmd, args, _)| cmd == "ssh-keygen" && args.first() == Some(&"-y".to_owned()))
    else {
        // The in-process path may have succeeded on some ssh_key versions
        // for arbitrary bytes; in that case assert no -P leaked anywhere.
        for (cmd, args, _env) in &calls {
            if cmd == "ssh-keygen" {
                assert!(
                    !args.iter().any(|a| a == "-P"),
                    "-P leaked into argv: {args:?}"
                );
            }
        }
        return;
    };
    assert!(
        !args.iter().any(|a| a == "-P"),
        "-P leaked into ssh-keygen -y argv: {args:?}"
    );
    assert!(
        !args.contains(&"repair-secret".to_owned()),
        "passphrase value leaked into argv: {args:?}"
    );
    assert!(
        env.iter().any(|(k, _)| k == "SSH_ASKPASS"),
        "SSH_ASKPASS env must be set for encrypted repair: {env:?}"
    );
}

/// The multi-askpass script must answer old/new/new across its three
/// invocations (the order `ssh-keygen -p` prompts in). This is the load-bearing
/// invariant for `change_passphrase` not silently re-using the old passphrase
/// as the new one.
/// Run the multi-askpass script, retrying on `ETXTBSY` ("Text file busy").
///
/// On Linux, `execve(2)` returns `ETXTBSY` (errno 26) when the file being
/// executed has an open writer. Even after an atomic write+rename (so no
/// userspace process holds the file open) the kernel's `i_writecount`
/// accounting can transiently report a write reference while the binfmt
/// layer sets up the text segment, **under concurrent fork/exec load** —
/// e.g. when cargo runs the askpass tests in parallel. This is a known,
/// purely-transient kernel race; the script is always executable a few
/// microseconds later. We retry a handful of times with a short backoff so
/// the tests are deterministic without weakening their assertions. Mirrors
/// `run_script_retrying_busy` in the `toride-ssh-agent` askpass tests.
#[cfg(unix)]
fn run_script_retrying_busy(path: &std::path::Path) -> std::process::Output {
    let mut backoff = std::time::Duration::from_micros(100);
    for attempt in 0..50 {
        match std::process::Command::new(path).output() {
            Ok(o) => return o,
            Err(e) if e.raw_os_error() == Some(libc::ETXTBSY) && attempt < 49 => {
                std::thread::sleep(backoff);
                backoff = (backoff * 2).min(std::time::Duration::from_millis(5));
            }
            Err(e) => panic!("failed to run multi-askpass script: {e}"),
        }
    }
    unreachable!("retry loop exhausted without returning or panicking");
}

#[cfg(unix)]
#[test]
fn multi_askpass_answers_in_order() {
    use std::os::unix::fs::PermissionsExt;
    let handler =
        MultiAskpassHandler::new(&["old-pass", "new-pass", "new-pass"]).expect("handler creation");
    let script = handler.script_path().to_path_buf();
    // The script needs execute permission.
    let mode = std::fs::metadata(&script).unwrap().permissions().mode();
    assert_ne!(mode & 0o100, 0, "multi-askpass script must be executable");
    assert_eq!(mode & 0o777, 0o700, "multi-askpass script must be 0o700");

    let run = || run_script_retrying_busy(&script);
    let o1 = String::from_utf8(run().stdout).unwrap();
    let o2 = String::from_utf8(run().stdout).unwrap();
    let o3 = String::from_utf8(run().stdout).unwrap();
    assert_eq!(o1.trim(), "old-pass", "first prompt must answer old");
    assert_eq!(o2.trim(), "new-pass", "second prompt must answer new");
    assert_eq!(
        o3.trim(),
        "new-pass",
        "third (confirmation) prompt must re-answer new"
    );
    // A hypothetical 4th prompt falls through to the last value.
    let o4 = String::from_utf8(run().stdout).unwrap();
    assert_eq!(o4.trim(), "new-pass");
}

/// The multi-askpass script survives passphrase values containing shell
/// metacharacters (single quotes), matching the `AskpassHandler` escaping.
#[cfg(unix)]
#[test]
fn multi_askpass_escapes_single_quotes() {
    let handler = MultiAskpassHandler::new(&["it's a 'secret'"]).expect("handler creation");
    let script = handler.script_path().to_path_buf();
    let out = run_script_retrying_busy(&script);
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert_eq!(
        stdout.trim(),
        "it's a 'secret'",
        "single quotes in passphrase must be escaped correctly"
    );
}

/// End-to-end proof that the askpass-driven `ssh-keygen -p` path (used by
/// [`KeyService::change_passphrase`]) actually rotates an encrypted key's
/// passphrase, with neither the old nor new passphrase on the argv. Mirrors
/// the existing `askpass_keygen_is_openssh_compatible` integration test.
/// Skips when `ssh-keygen` is not on PATH.
#[cfg(unix)]
#[test]
fn multi_askpass_keygen_p_rotates_passphrase_without_argv_leak() {
    let ssh_keygen_present = std::process::Command::new("ssh-keygen")
        .arg("--help")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok();
    if !ssh_keygen_present {
        eprintln!("skipping: ssh-keygen not available");
        return;
    }

    let dir = tempfile::TempDir::new().expect("temp dir");
    let keypath = dir.path().join("chpass_key");
    let keypath_str = keypath.to_str().expect("utf-8 path").to_owned();

    // 1. Generate an encrypted key with a known passphrase (use -N here only
    //    for the *initial* generation, which is not the code path under test).
    let gen_status = std::process::Command::new("ssh-keygen")
        .args(["-t", "ed25519", "-f", &keypath_str, "-N", "oldpass-xyz"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("spawn ssh-keygen generate");
    assert!(gen_status.success(), "initial key generation failed");

    // 2. Rotate the passphrase WITHOUT -P/-N, feeding old/new/new via the
    //    multi-askpass helper (exactly what change_passphrase does).
    let handler = MultiAskpassHandler::new(&["oldpass-xyz", "newpass-xyz", "newpass-xyz"])
        .expect("handler creation");
    let change = std::process::Command::new("ssh-keygen")
        .args(["-p", "-f", &keypath_str])
        .env("SSH_ASKPASS", handler.script_path())
        .env("SSH_ASKPASS_REQUIRE", "force")
        .env("DISPLAY", ":0")
        .stdin(std::process::Stdio::null())
        .output()
        .expect("spawn ssh-keygen -p");
    assert!(
        change.status.success(),
        "ssh-keygen -p (askpass) failed: {}",
        String::from_utf8_lossy(&change.stderr)
    );

    // 3. The OLD passphrase must no longer decrypt the key.
    let old = std::process::Command::new("ssh-keygen")
        .args(["-y", "-P", "oldpass-xyz", "-f", &keypath_str])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("spawn verify-old");
    assert!(
        !old.success(),
        "old passphrase should no longer work after rotation"
    );

    // 4. The NEW passphrase must decrypt the key.
    let new = std::process::Command::new("ssh-keygen")
        .args(["-y", "-P", "newpass-xyz", "-f", &keypath_str])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .expect("spawn verify-new");
    assert!(
        new.success(),
        "new passphrase should decrypt the rotated key"
    );
}

// ===========================================================================
// Finding (2): filter_config_lines / remove_from_config coverage.
// ===========================================================================

fn filtered(input: &str, ssh_dir: &str, key_name: &str) -> String {
    filter_config_lines(input, ssh_dir, key_name)
}

#[test]
fn filter_removes_identityfile_tilde_form() {
    let input = "Host example\n    IdentityFile ~/.ssh/id_ed25519\n    User foo\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        !out.contains("IdentityFile"),
        "IdentityFile tilde line should be removed: {out}"
    );
    assert!(out.contains("Host example"));
    assert!(out.contains("User foo"));
}

#[test]
fn filter_removes_identityfile_absolute_form() {
    let input = "Host example\n    IdentityFile /home/u/.ssh/id_ed25519\n    User foo\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        !out.contains("IdentityFile"),
        "IdentityFile absolute line should be removed: {out}"
    );
}

#[test]
fn filter_removes_identityfile_single_quoted() {
    let input = "IdentityFile '~/.ssh/id_ed25519'\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        out.trim().is_empty(),
        "single-quoted tilde value removed: {out}"
    );
}

#[test]
fn filter_removes_identityfile_double_quoted() {
    let input = "IdentityFile \"/home/u/.ssh/id_ed25519\"\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        out.trim().is_empty(),
        "double-quoted absolute value removed: {out}"
    );
}

#[test]
fn filter_removes_certificatefile_companion() {
    let input = "Host example\n    IdentityFile ~/.ssh/id_ed25519\n    CertificateFile ~/.ssh/id_ed25519-cert.pub\n    User foo\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        !out.contains("CertificateFile"),
        "CertificateFile companion should be removed: {out}"
    );
    assert!(!out.contains("IdentityFile"));
    assert!(out.contains("User foo"));
}

#[test]
fn filter_preserves_unrelated_identityfile() {
    // A different key must be left in place.
    let input = "Host a\n    IdentityFile ~/.ssh/other_key\n    IdentityFile ~/.ssh/id_ed25519\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        out.contains("~/.ssh/other_key"),
        "unrelated IdentityFile must be preserved: {out}"
    );
    assert!(!out.contains("id_ed25519"));
}

#[test]
fn filter_preserves_substring_only_lines() {
    // A line that merely CONTAINS the name (e.g. a Host alias or comment) but
    // is not an IdentityFile for this key must be preserved.
    let input = "Host id_ed25519-backup\n   HostName id_ed25519.example.com\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert_eq!(
        out, input,
        "lines that only mention the name as a substring must be untouched"
    );
}

#[test]
fn filter_keyword_is_case_insensitive() {
    let input = "identityfile ~/.ssh/id_ed25519\nIDENTITYFILE ~/.ssh/id_ed25519\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        out.trim().is_empty(),
        "case-insensitive keyword match should drop both lines: {out}"
    );
}

#[test]
fn filter_preserves_crlf_line_endings() {
    let input = "Host a\r\n    IdentityFile ~/.ssh/id_ed25519\r\n    User foo\r\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        out.contains("\r\n"),
        "CRLF line endings must be preserved: {out:?}"
    );
    assert!(!out.contains("IdentityFile"));
    assert!(out.contains("User foo"));
}

#[test]
fn filter_preserves_lf_line_endings() {
    let input = "Host a\n    IdentityFile ~/.ssh/id_ed25519\n    User foo\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        !out.contains("\r\n"),
        "no stray CRLF should be introduced: {out:?}"
    );
    assert!(out.contains("User foo"));
}

#[test]
fn filter_noop_when_key_not_referenced() {
    let input = "Host a\n    IdentityFile ~/.ssh/other\n    User foo\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert_eq!(
        out, input,
        "content must be byte-identical when the key is not referenced"
    );
}

#[test]
fn filter_removes_bare_name_identityfile() {
    // Some configs reference just the bare key name (resolved against ssh_dir).
    let input = "IdentityFile id_ed25519\n";
    let out = filtered(input, "/home/u/.ssh", "id_ed25519");
    assert!(
        out.trim().is_empty(),
        "bare-name IdentityFile should be removed: {out}"
    );
}

#[tokio::test]
async fn remove_from_config_noop_leaves_file_byte_identical() {
    let dir = tempfile::TempDir::new().unwrap();
    // Build an ssh dir that contains a config that does NOT reference the key.
    let ssh_dir = dir.path().join(".ssh");
    std::fs::create_dir_all(&ssh_dir).unwrap();
    let config = ssh_dir.join("config");
    let original = "Host a\n    IdentityFile ~/.ssh/other\n    User foo\n";
    std::fs::write(&config, original.as_bytes()).unwrap();

    let paths = toride_ssh_core::SshPaths::with_dir(&ssh_dir);
    // remove_from_config is private; exercise it via KeyService::delete with all
    // removal flags off except remove_from_config. That also requires the key
    // file to exist for the early branch; instead call the delete path that
    // only does config cleanup by deleting a present key file.
    let key_path = ssh_dir.join("id_ed25519");
    std::fs::write(&key_path, b"private").unwrap();
    std::fs::write(ssh_dir.join("id_ed25519.pub"), b"pub").unwrap();

    let runner = CapturingRunner::new();
    let svc = KeyService::new(&paths, &runner);
    let params = toride_ssh_core::KeyDeleteParams {
        name: "id_ed25519".to_owned(),
        remove_public: false,
        remove_certificate: false,
        remove_from_agent: false,
        remove_from_config: true,
        backup: false,
    };
    svc.delete(params).await.expect("delete should succeed");

    let after = std::fs::read(&config).unwrap();
    assert_eq!(
        after,
        original.as_bytes(),
        "config must be byte-identical when key is not referenced"
    );
}

#[tokio::test]
async fn remove_from_config_strips_referenced_line_and_writes_atomically() {
    let dir = tempfile::TempDir::new().unwrap();
    let ssh_dir = dir.path().join(".ssh");
    std::fs::create_dir_all(&ssh_dir).unwrap();
    let config = ssh_dir.join("config");
    let original = "Host a\n    IdentityFile ~/.ssh/id_ed25519\n    User foo\n";
    std::fs::write(&config, original.as_bytes()).unwrap();

    let paths = toride_ssh_core::SshPaths::with_dir(&ssh_dir);
    let key_path = ssh_dir.join("id_ed25519");
    std::fs::write(&key_path, b"private").unwrap();

    let runner = CapturingRunner::new();
    let svc = KeyService::new(&paths, &runner);
    let params = toride_ssh_core::KeyDeleteParams {
        name: "id_ed25519".to_owned(),
        remove_public: false,
        remove_certificate: false,
        remove_from_agent: false,
        remove_from_config: true,
        backup: false,
    };
    svc.delete(params).await.expect("delete should succeed");

    let after = std::fs::read_to_string(&config).unwrap();
    assert!(
        !after.contains("IdentityFile"),
        "IdentityFile removed: {after}"
    );
    assert!(after.contains("User foo"), "other lines preserved: {after}");
    // No leftover temp file in the ssh dir.
    let leftovers = std::fs::read_dir(&ssh_dir)
        .unwrap()
        .filter_map(std::result::Result::<_, std::io::Error>::ok)
        .filter(|e| e.file_name().to_string_lossy().starts_with(".config.tmp."))
        .count();
    assert_eq!(leftovers, 0, "temp config file must be cleaned up");
}