puressh 0.2.4

A pure-Rust SSH (Secure Shell) protocol library, in the spirit of libssh, built on purecrypto.
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
//! Integration tests for the `known_hosts` module.
//!
//! The lower-level format/hash modules have their own unit tests; this
//! file exercises the public [`KnownHosts`] API and cross-cutting
//! behaviours (parse → store → save → reload, lookup, TOFU-style add,
//! `hash_in_place`, marker semantics).

use super::format::{HostSpec, Marker};
use super::{KnownHosts, LookupResult};

/// Tiny on-disk scratch directory, modelled on `src/sftp/tests.rs::SftpTempDir` so
/// we don't pull in the `tempfile` crate.
struct TestTempDir {
    path: std::path::PathBuf,
}

impl TestTempDir {
    fn new(prefix: &str) -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let pid = std::process::id();
        let path = std::env::temp_dir().join(format!("puressh-kh-{prefix}-{pid}-{nanos}"));
        std::fs::create_dir_all(&path).expect("create tempdir");
        Self { path }
    }

    fn child(&self, name: &str) -> std::path::PathBuf {
        self.path.join(name)
    }
}

impl Drop for TestTempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

fn ed25519_blob(seed: u8) -> Vec<u8> {
    // Anything goes for these tests — `KnownHosts` treats key blobs
    // opaquely. Vary by seed so different "keys" don't collide.
    let mut v = vec![0u8; 32];
    v[0] = seed;
    v[31] = seed.wrapping_add(0xA5);
    v
}

#[test]
fn parse_then_save_roundtrips_lines_verbatim() {
    // Mix of comments, blank lines, plain entries, hashed entry,
    // bracketed-host-with-port, and an unparseable line — saving must
    // emit them all back.
    let src = b"# header comment\n\
                \n\
                example.com ssh-ed25519 AAAA my-comment\n\
                [example.com]:2222 ssh-rsa AAAB\n\
                |1|salt+salt+salt+salt+salt+s=|hash+hash+hash+hash+hash+ha= ssh-ed25519 AAAC\n\
                # tail comment\n";
    let kh = KnownHosts::from_bytes(src);
    let out = kh.to_bytes();
    // We don't require byte-for-byte identity (whitespace inside an
    // entry is normalized), but every information-bearing line must
    // round-trip.
    let out_str = String::from_utf8(out).unwrap();
    assert!(out_str.contains("# header comment"));
    assert!(out_str.contains("# tail comment"));
    assert!(out_str.contains("example.com ssh-ed25519 AAAA my-comment"));
    assert!(out_str.contains("[example.com]:2222 ssh-rsa AAAB"));
    assert!(
        out_str.contains(
            "|1|salt+salt+salt+salt+salt+s=|hash+hash+hash+hash+hash+ha= ssh-ed25519 AAAC"
        )
    );
}

#[test]
fn lookup_plain_match_mismatch_unknown() {
    let mut kh = KnownHosts::new();
    let good = ed25519_blob(1);
    let other = ed25519_blob(2);
    kh.add("example.com", 22, "ssh-ed25519", &good, false);

    match kh.lookup("example.com", 22, "ssh-ed25519", &good) {
        LookupResult::Match => {}
        r => panic!("expected Match, got {r:?}"),
    }
    match kh.lookup("example.com", 22, "ssh-ed25519", &other) {
        LookupResult::Mismatch { expected } => {
            assert_eq!(expected, vec![("ssh-ed25519".to_string(), good.clone())]);
        }
        r => panic!("expected Mismatch, got {r:?}"),
    }
    match kh.lookup("other.invalid", 22, "ssh-ed25519", &good) {
        LookupResult::Unknown => {}
        r => panic!("expected Unknown, got {r:?}"),
    }
}

#[test]
fn lookup_honours_port_in_bracketed_entries() {
    let mut kh = KnownHosts::new();
    let key = ed25519_blob(3);
    kh.add("example.com", 2222, "ssh-ed25519", &key, false);
    // Same host, default port — must not match the 2222 entry.
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &key),
        LookupResult::Unknown
    ));
    assert!(matches!(
        kh.lookup("example.com", 2222, "ssh-ed25519", &key),
        LookupResult::Match
    ));
}

#[test]
fn multiple_keys_per_host_all_accepted() {
    // OpenSSH allows multiple lines for the same host (e.g. ed25519 +
    // rsa). Any matching key returns Match.
    let mut kh = KnownHosts::new();
    let k1 = ed25519_blob(11);
    let k2 = ed25519_blob(22);
    kh.add("example.com", 22, "ssh-ed25519", &k1, false);
    kh.add("example.com", 22, "ssh-rsa", &k2, false);
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &k1),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-rsa", &k2),
        LookupResult::Match
    ));
    // A third unknown key produces Mismatch listing both expected.
    let k3 = ed25519_blob(33);
    match kh.lookup("example.com", 22, "ssh-ed25519", &k3) {
        LookupResult::Mismatch { expected } => {
            assert_eq!(expected.len(), 2);
        }
        r => panic!("expected Mismatch, got {r:?}"),
    }
}

#[test]
fn revoked_marker_refuses_matching_key() {
    let src = b"@revoked example.com ssh-ed25519 AAAA\n";
    let kh = KnownHosts::from_bytes(src);
    // We parsed AAAA as the key blob; reconstruct it and check refusal.
    let blob = crate::key::base64::decode(b"AAAA").unwrap();
    // A revoked key is a distinct, fail-closed verdict — not a `Mismatch`
    // that a lenient `on_mismatch` policy could wave through.
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &blob),
        LookupResult::Revoked
    ));
}

/// `@revoked` outranks a plain entry for the same host and key, wherever
/// the two lines sit in the file, and a revoked key for one host must not
/// affect a different host.
#[test]
fn revoked_marker_outranks_plain_entry_and_is_host_scoped() {
    let src = b"example.com ssh-ed25519 AAAA\n\
                @revoked example.com ssh-ed25519 AAAA\n\
                other.example.com ssh-ed25519 AAAA\n";
    let kh = KnownHosts::from_bytes(src);
    let blob = crate::key::base64::decode(b"AAAA").unwrap();
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &blob),
        LookupResult::Revoked
    ));
    // Same key, unrevoked host: still a plain match.
    assert!(matches!(
        kh.lookup("other.example.com", 22, "ssh-ed25519", &blob),
        LookupResult::Match
    ));
    // A different key for the revoked host is an ordinary mismatch.
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &ed25519_blob(9)),
        LookupResult::Mismatch { .. }
    ));
}

#[test]
fn cert_authority_marker_is_ignored_for_plain_host_keys() {
    // A `@cert-authority` line vouches for *certificates* signed by the CA
    // key; it says nothing about the host's plain key. So a plain-key host
    // under a CA wildcard is simply Unknown (not a false "HOST KEY
    // CHANGED"), and a host presenting the CA's own public key as its host
    // key must not be accepted on the strength of the CA line.
    let src = b"@cert-authority *.example.com ssh-ed25519 AAAA\n";
    let kh = KnownHosts::from_bytes(src);
    let ca_blob = crate::key::base64::decode(b"AAAA").unwrap();
    let other = ed25519_blob(42);
    assert!(matches!(
        kh.lookup("host.example.com", 22, "ssh-ed25519", &other),
        LookupResult::Unknown
    ));
    assert!(matches!(
        kh.lookup("host.example.com", 22, "ssh-ed25519", &ca_blob),
        LookupResult::Unknown
    ));
    // The CA line still exists for cert verification / `find`.
    assert_eq!(kh.find("host.example.com", 22).len(), 1);
}

/// Plain entries next to a CA wildcard behave normally: the plain key
/// decides Match / Mismatch, and the CA key is never listed as "expected".
#[test]
fn plain_entry_beside_cert_authority_wildcard_decides_alone() {
    let src = b"@cert-authority *.example.com ssh-ed25519 AAAA\n\
                host.example.com ssh-ed25519 AAAB\n";
    let kh = KnownHosts::from_bytes(src);
    let plain = crate::key::base64::decode(b"AAAB").unwrap();
    assert!(matches!(
        kh.lookup("host.example.com", 22, "ssh-ed25519", &plain),
        LookupResult::Match
    ));
    match kh.lookup("host.example.com", 22, "ssh-ed25519", &ed25519_blob(7)) {
        LookupResult::Mismatch { expected } => {
            assert_eq!(expected.len(), 1, "CA key must not be reported as expected");
            assert_eq!(expected[0].1, plain);
        }
        r => panic!("expected Mismatch, got {r:?}"),
    }
}

/// `remove_exact` (the key-rotation primitive) only drops marker-less
/// lines naming exactly this host — wildcard, multi-host, negated,
/// `@cert-authority` and `@revoked` lines shared with other hosts survive.
#[test]
fn remove_exact_spares_shared_and_marker_lines() {
    let src = b"@cert-authority *.example.com ssh-ed25519 AAAA\n\
                @revoked host.example.com ssh-ed25519 AAAB\n\
                *.example.com ssh-ed25519 AAAC\n\
                host.example.com,alias.example.com ssh-ed25519 AAAD\n\
                !bad.example.com,host.example.com ssh-ed25519 AAAE\n\
                HOST.example.com ssh-ed25519 AAAF\n\
                host.example.com ssh-rsa AAAG\n\
                [host.example.com]:2222 ssh-ed25519 AAAH\n";
    let mut kh = KnownHosts::from_bytes(src);
    // Sanity: the broad `remove` would take every one of these lines.
    assert_eq!(kh.find("host.example.com", 22).len(), 7);

    // Only the two literal `host.example.com` lines (case-insensitive) go.
    assert_eq!(kh.remove_exact("host.example.com", 22), 2);
    let out = String::from_utf8(kh.to_bytes()).unwrap();
    assert!(out.contains("@cert-authority *.example.com"));
    assert!(out.contains("@revoked host.example.com"));
    assert!(out.contains("*.example.com ssh-ed25519 AAAC"));
    assert!(out.contains("host.example.com,alias.example.com"));
    assert!(out.contains("!bad.example.com,host.example.com"));
    assert!(out.contains("[host.example.com]:2222"));
    assert!(!out.contains("HOST.example.com ssh-ed25519 AAAF"));
    assert!(!out.contains("host.example.com ssh-rsa AAAG"));

    // Revocation and CA trust are untouched by the rotation.
    let revoked = crate::key::base64::decode(b"AAAB").unwrap();
    assert!(matches!(
        kh.lookup("host.example.com", 22, "ssh-ed25519", &revoked),
        LookupResult::Revoked
    ));

    // Hashed entries for exactly this host are removed too; a hashed
    // entry for another host is not.
    let mut kh = KnownHosts::new();
    kh.add(
        "host.example.com",
        22,
        "ssh-ed25519",
        &ed25519_blob(1),
        true,
    );
    kh.add(
        "host.example.com",
        2222,
        "ssh-ed25519",
        &ed25519_blob(2),
        true,
    );
    kh.add(
        "other.example.com",
        22,
        "ssh-ed25519",
        &ed25519_blob(3),
        true,
    );
    assert_eq!(kh.remove_exact("host.example.com", 22), 1);
    assert!(matches!(
        kh.lookup("host.example.com", 22, "ssh-ed25519", &ed25519_blob(1)),
        LookupResult::Unknown
    ));
    assert!(matches!(
        kh.lookup("host.example.com", 2222, "ssh-ed25519", &ed25519_blob(2)),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("other.example.com", 22, "ssh-ed25519", &ed25519_blob(3)),
        LookupResult::Match
    ));
}

#[test]
fn add_then_save_then_load_roundtrip() {
    let dir = TestTempDir::new("save-load");
    let path = dir.child("known_hosts");
    let key = ed25519_blob(7);

    let mut kh = KnownHosts::new();
    kh.add("example.com", 22, "ssh-ed25519", &key, false);
    kh.add("alt.example.com", 2222, "ssh-rsa", &ed25519_blob(8), false);
    kh.save(&path).expect("save");

    let kh2 = KnownHosts::load(&path).expect("load");
    assert!(matches!(
        kh2.lookup("example.com", 22, "ssh-ed25519", &key),
        LookupResult::Match
    ));
    assert!(matches!(
        kh2.lookup("alt.example.com", 2222, "ssh-rsa", &ed25519_blob(8)),
        LookupResult::Match
    ));
}

#[test]
fn load_missing_file_returns_empty_store() {
    let dir = TestTempDir::new("missing");
    let path = dir.child("nope");
    let kh = KnownHosts::load(&path).expect("missing → empty");
    assert!(matches!(
        kh.lookup("anywhere", 22, "ssh-ed25519", b"x"),
        LookupResult::Unknown
    ));
}

#[test]
fn add_hashed_then_lookup_works() {
    let key = ed25519_blob(9);
    let mut kh = KnownHosts::new();
    kh.add("example.com", 22, "ssh-ed25519", &key, true);
    // The freshly added entry is a hashed token; lookup must HMAC and match.
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &key),
        LookupResult::Match
    ));
    // A different host hashed under the same salt produces a different
    // HMAC, so we must NOT match.
    assert!(matches!(
        kh.lookup("evil.example", 22, "ssh-ed25519", &key),
        LookupResult::Unknown
    ));

    // Confirm the entry on disk is actually hashed.
    let entries = kh.find("example.com", 22);
    assert_eq!(entries.len(), 1);
    match &entries[0].host_spec {
        HostSpec::Hashed(token) => assert!(token.starts_with("|1|")),
        _ => panic!("expected hashed host_spec"),
    }
}

#[test]
fn remove_drops_matching_entries() {
    let mut kh = KnownHosts::new();
    kh.add("a.example.com", 22, "ssh-ed25519", &ed25519_blob(1), false);
    kh.add("b.example.com", 22, "ssh-ed25519", &ed25519_blob(2), false);
    kh.add("a.example.com", 22, "ssh-rsa", &ed25519_blob(3), false);

    assert_eq!(kh.remove("a.example.com", 22), 2);
    // b. is still there; a. is gone.
    assert!(matches!(
        kh.lookup("b.example.com", 22, "ssh-ed25519", &ed25519_blob(2)),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("a.example.com", 22, "ssh-ed25519", &ed25519_blob(1)),
        LookupResult::Unknown
    ));
}

#[test]
fn hash_in_place_replaces_plain_entries_with_hashed_tokens() {
    let mut kh = KnownHosts::new();
    let key = ed25519_blob(15);
    kh.add("example.com", 22, "ssh-ed25519", &key, false);
    kh.add("alt.example.com", 2222, "ssh-rsa", &ed25519_blob(16), false);

    kh.hash_in_place();

    // After hashing, lookups still work — they HMAC the candidate host
    // and compare against the stored salted hash.
    assert!(matches!(
        kh.lookup("example.com", 22, "ssh-ed25519", &key),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("alt.example.com", 2222, "ssh-rsa", &ed25519_blob(16)),
        LookupResult::Match
    ));

    // All entries should now be hashed.
    let bytes = kh.to_bytes();
    let text = String::from_utf8(bytes).unwrap();
    for line in text.lines() {
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        assert!(
            line.starts_with("|1|"),
            "expected hashed line, got: {line:?}"
        );
    }
}

#[test]
fn hashed_entry_parses_and_matches_known_host() {
    // Use the runtime to mint a canonical hashed entry, then re-parse
    // it through `from_bytes` and confirm lookup succeeds.
    let key = ed25519_blob(21);
    let mut kh = KnownHosts::new();
    kh.add("example.com", 22, "ssh-ed25519", &key, true);
    let bytes = kh.to_bytes();

    let kh2 = KnownHosts::from_bytes(&bytes);
    assert!(matches!(
        kh2.lookup("example.com", 22, "ssh-ed25519", &key),
        LookupResult::Match
    ));
}

#[test]
fn marker_round_trips_through_save_load() {
    let dir = TestTempDir::new("marker");
    let path = dir.child("known_hosts");

    // Mint a small file with both markers, then load+save and confirm
    // marker semantics survive.
    let blob = crate::key::base64::decode(b"AAAA").unwrap();
    let src = b"@cert-authority *.example.com ssh-ed25519 AAAA\n\
                @revoked bad.example.com ssh-ed25519 AAAA\n";
    std::fs::write(&path, src).unwrap();

    let kh = KnownHosts::load(&path).expect("load");
    // A CA line never vouches for a plain host key — even the CA's own
    // public key presented as a host key is just Unknown.
    assert!(matches!(
        kh.lookup("host.example.com", 22, "ssh-ed25519", &blob),
        LookupResult::Unknown
    ));
    // Revoked refuses the same blob, fail-closed.
    assert!(matches!(
        kh.lookup("bad.example.com", 22, "ssh-ed25519", &blob),
        LookupResult::Revoked
    ));

    // Save + reload survives — both the wildcard cert-authority and
    // the targeted revoke entry come back, and the revoke still wins
    // for `bad.example.com`.
    kh.save(&path).unwrap();
    let kh2 = KnownHosts::load(&path).unwrap();
    let markers: Vec<_> = kh2
        .find("bad.example.com", 22)
        .iter()
        .map(|e| e.marker)
        .collect();
    assert!(markers.contains(&Some(Marker::Revoked)));
    assert!(markers.contains(&Some(Marker::CertAuthority)));
    assert!(matches!(
        kh2.lookup("bad.example.com", 22, "ssh-ed25519", &blob),
        LookupResult::Revoked
    ));
}

#[test]
fn lookup_ipv6_default_port_matches_bare_pattern() {
    // OpenSSH writes a v6 entry with the default port (22) as a bare
    // (unbracketed) pattern token, identical to a hostname entry. The
    // store must match that bare pattern when the candidate is the same
    // v6 host on port 22.
    let mut kh = KnownHosts::new();
    let key = ed25519_blob(20);
    kh.add("2001:db8::1", 22, "ssh-ed25519", &key, false);
    assert!(matches!(
        kh.lookup("2001:db8::1", 22, "ssh-ed25519", &key),
        LookupResult::Match
    ));
}

#[test]
fn lookup_ipv6_non_default_port_matches_bracketed_pattern() {
    // For a non-default port the on-disk form is `[v6-literal]:port`.
    // The lookup compares the bracketed pattern against the candidate
    // (host, port) and must accept it.
    let mut kh = KnownHosts::new();
    let key = ed25519_blob(21);
    kh.add("2001:db8::1", 2222, "ssh-ed25519", &key, false);
    // Must match at the non-default port.
    assert!(matches!(
        kh.lookup("2001:db8::1", 2222, "ssh-ed25519", &key),
        LookupResult::Match
    ));
    // Default-port lookup must NOT match — that's a different host record.
    assert!(matches!(
        kh.lookup("2001:db8::1", 22, "ssh-ed25519", &key),
        LookupResult::Unknown
    ));
}

#[test]
fn ipv6_save_load_roundtrip_preserves_match() {
    // Add a default-port v6 entry and a non-default-port v6 entry,
    // save the file, load it again, and re-look up both. Verifies the
    // wire format we produce is also the wire format we accept.
    let dir = TestTempDir::new("v6-roundtrip");
    let path = dir.child("known_hosts");
    let k1 = ed25519_blob(30);
    let k2 = ed25519_blob(31);

    let mut kh = KnownHosts::new();
    kh.add("2001:db8::1", 22, "ssh-ed25519", &k1, false);
    kh.add("2001:db8::2", 2222, "ssh-ed25519", &k2, false);
    kh.save(&path).expect("save");

    let kh2 = KnownHosts::load(&path).expect("load");
    assert!(matches!(
        kh2.lookup("2001:db8::1", 22, "ssh-ed25519", &k1),
        LookupResult::Match
    ));
    assert!(matches!(
        kh2.lookup("2001:db8::2", 2222, "ssh-ed25519", &k2),
        LookupResult::Match
    ));
}

#[test]
fn ipv6_hash_in_place_then_lookup_works() {
    // hash_in_place is the path that runs `split_host_port` under the
    // hood — it has to parse `[v6]:port` patterns correctly to compute
    // the canonical hashed host. A v6 entry on a non-default port must
    // survive the conversion and still match the candidate (host, port).
    let mut kh = KnownHosts::new();
    let key = ed25519_blob(32);
    kh.add("2001:db8::1", 2222, "ssh-ed25519", &key, false);
    kh.hash_in_place();
    assert!(matches!(
        kh.lookup("2001:db8::1", 2222, "ssh-ed25519", &key),
        LookupResult::Match
    ));
    // Now confirm the on-disk shape is hashed (not the original bracket
    // form) — proves the split_host_port → hash path actually fired.
    let entries = kh.find("2001:db8::1", 2222);
    assert_eq!(entries.len(), 1);
    match &entries[0].host_spec {
        HostSpec::Hashed(token) => assert!(token.starts_with("|1|")),
        _ => panic!("expected hashed host_spec after hash_in_place"),
    }
}

#[test]
fn known_hosts_file_with_bracketed_v6_line_loads_and_matches() {
    // Hand-write a known_hosts file with both forms and verify the
    // parser + matcher accept them as a unit.
    let dir = TestTempDir::new("v6-handwritten");
    let path = dir.child("known_hosts");
    let blob = crate::key::base64::decode(b"AAAA").unwrap();
    let src = b"2001:db8::1 ssh-ed25519 AAAA\n\
                [2001:db8::2]:2222 ssh-ed25519 AAAA\n";
    std::fs::write(&path, src).unwrap();

    let kh = KnownHosts::load(&path).expect("load");
    assert!(matches!(
        kh.lookup("2001:db8::1", 22, "ssh-ed25519", &blob),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("2001:db8::2", 2222, "ssh-ed25519", &blob),
        LookupResult::Match
    ));
}

#[cfg(unix)]
#[test]
fn save_produces_mode_0600_file() {
    use std::os::unix::fs::PermissionsExt as _;
    let dir = TestTempDir::new("perms");
    let path = dir.child("known_hosts");
    let mut kh = KnownHosts::new();
    kh.add("example.com", 22, "ssh-ed25519", &ed25519_blob(1), false);
    kh.save(&path).expect("save");
    let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
    assert_eq!(
        mode, 0o600,
        "known_hosts must be owner-only (0o600), got {mode:o}"
    );
}

#[test]
fn non_default_port_falls_back_to_bare_host_key() {
    // OpenSSH: with no `[host]:port` entry, the key recorded under the bare
    // host name is accepted; a different key there is not a mismatch.
    let mut kh = KnownHosts::new();
    let key = ed25519_blob(5);
    let other = ed25519_blob(6);
    kh.add("example.com", 22, "ssh-ed25519", &key, false);
    assert!(matches!(
        kh.lookup("example.com", 2222, "ssh-ed25519", &key),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("example.com", 2222, "ssh-ed25519", &other),
        LookupResult::Unknown
    ));
    // A `[host]:port` entry takes precedence: its mismatch stands.
    kh.add("example.com", 2222, "ssh-ed25519", &other, false);
    assert!(matches!(
        kh.lookup("example.com", 2222, "ssh-ed25519", &key),
        LookupResult::Mismatch { .. }
    ));
}

#[test]
fn revoked_host_keys_list_and_krl() {
    use crate::known_hosts::RevokedHostKeys;
    let a = ed25519_blob(7);
    let b = ed25519_blob(8);
    let text = format!(
        "# revoked\n\nssh-ed25519 {} old host\n",
        crate::key::base64::encode(&a)
    );
    let r = RevokedHostKeys::parse(text.as_bytes()).unwrap();
    assert!(r.is_revoked_key(&a));
    assert!(!r.is_revoked_key(&b));
    // A malformed line fails the file instead of being skipped.
    assert!(RevokedHostKeys::parse(b"garbage\n").is_err());
    // An empty file revokes nothing.
    assert!(!RevokedHostKeys::parse(b"").unwrap().is_revoked_key(&a));
}

#[test]
fn rsa_entry_under_a_signature_name_is_an_rsa_key() {
    // `AAAB` decodes to the opaque blob [0x00, 0x00, 0x01].
    let kh = KnownHosts::from_bytes(b"example.com rsa-sha2-512 AAAB\n");
    match kh.lookup("example.com", 22, "ssh-rsa", &[0, 0, 1]) {
        LookupResult::Match => {}
        r => panic!("expected Match, got {r:?}"),
    }
}

#[test]
fn host_keys_update_plans_new_and_obsolete_keys() {
    let (a, b, c) = (ed25519_blob(1), ed25519_blob(2), ed25519_blob(3));
    let mut kh = KnownHosts::new();
    kh.add("h", 22, "ssh-ed25519", &a, false);
    kh.add("h", 22, "ssh-ed25519", &b, false);
    kh.add("other", 22, "ssh-ed25519", &c, false);
    // The server now offers a and a new key d: d is new, b is obsolete.
    let d = ed25519_blob(4);
    let plan = kh.host_keys_update("h", 22, &[a.clone(), d.clone()]);
    assert_eq!(plan.new, vec![1]);
    assert_eq!(plan.old, vec![b.clone()]);
    assert_eq!(plan.blocked, None);
    kh.update_host_keys(
        "h",
        22,
        &plan.old,
        &[("ssh-ed25519".into(), d.clone())],
        false,
    );
    assert!(matches!(
        kh.lookup("h", 22, "ssh-ed25519", &d),
        LookupResult::Match
    ));
    assert!(matches!(
        kh.lookup("h", 22, "ssh-ed25519", &b),
        LookupResult::Mismatch { .. }
    ));
    assert!(matches!(
        kh.lookup("other", 22, "ssh-ed25519", &c),
        LookupResult::Match
    ));
    // A key the server offers that is recorded under another name: hands off.
    assert!(kh.host_keys_update("h", 22, &[c]).blocked.is_some());
}

/// `add` / `try_add` refuse a key type or host that would not stay a single
/// well-formed field: a `\n` in a server-chosen key type used to inject a
/// wildcard line trusting an attacker key for every host.
#[test]
fn add_refuses_fields_that_would_inject_lines() {
    let mut kh = KnownHosts::new();
    kh.add("victim.example", 22, "ssh-ed25519", &ed25519_blob(1), false);
    let evil = "ssh-ed25519 AAAA\n* ssh-ed25519 YXR0YWNrZXJrZXk=\n#";
    kh.add("malicious.example", 22, evil, b"whatever", false);
    for (host, key_type) in [
        ("h", "ssh-ed25519\r"),
        ("h", "ssh-ed25519 x"),
        ("h", "ssh-ed25519,ssh-rsa"),
        ("h", "@cert-authority"),
        ("h", "#c"),
        ("h", ""),
        ("a\nb", "ssh-ed25519"),
        ("a b", "ssh-ed25519"),
        ("a,*", "ssh-ed25519"),
        ("@revoked", "ssh-ed25519"),
        ("|1|x", "ssh-ed25519"),
        ("#x", "ssh-ed25519"),
        ("", "ssh-ed25519"),
    ] {
        assert!(
            kh.try_add(host, 22, key_type, &ed25519_blob(2), false)
                .is_err(),
            "{host:?} {key_type:?}"
        );
    }
    let out = kh.to_bytes();
    assert_eq!(out.iter().filter(|&&b| b == b'\n').count(), 1);
    let reloaded = KnownHosts::from_bytes(&out);
    assert!(matches!(
        reloaded.lookup("victim.example", 22, "ssh-ed25519", b"attackerkey"),
        LookupResult::Mismatch { .. }
    ));
    // IPv6 / non-default port and hashing still work.
    kh.try_add("2001:db8::1", 2222, "ssh-ed25519", &ed25519_blob(3), true)
        .unwrap();
}

/// A non-UTF-8 line (e.g. a Latin-1 comment) survives load → save
/// byte-for-byte, and an `@revoked` one keeps revoking its key.
#[test]
fn non_utf8_lines_preserved_and_revoked_still_revokes() {
    let key = ed25519_blob(9);
    let b64 = crate::key::base64::encode(&key);
    let mut data = Vec::new();
    data.extend_from_slice(format!("@revoked * ssh-ed25519 {b64} caf").as_bytes());
    data.push(0xE9); // Latin-1 'é'
    data.push(b'\n');
    data.extend_from_slice(b"junk \xff\xfe\n");
    data.extend_from_slice(format!("host.example ssh-ed25519 {b64}\n").as_bytes());

    let kh = KnownHosts::from_bytes(&data);
    assert_eq!(kh.to_bytes(), data, "raw lines kept verbatim");
    assert!(matches!(
        kh.lookup("host.example", 22, "ssh-ed25519", &key),
        LookupResult::Revoked
    ));
}