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
//! Unit tests for certificate parsing/verification, driven by fixtures
//! generated with `ssh-keygen -s` (see `tests/fixtures/cert/`).

use super::*;
use crate::key::base64;

/// Load a `*-cert.pub` fixture (`<type> <base64> <comment>`), returning the
/// decoded certificate blob.
fn load_cert_blob(name: &str) -> Vec<u8> {
    let path = concat_fixture(name);
    let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
    let b64 = text
        .split_whitespace()
        .nth(1)
        .unwrap_or_else(|| panic!("fixture {path} has no base64 field"));
    base64::decode(b64.as_bytes()).expect("decode cert base64")
}

/// Load a plain `.pub` fixture, returning its wire blob.
fn load_pub_blob(name: &str) -> Vec<u8> {
    let path = concat_fixture(name);
    let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
    let b64 = text.split_whitespace().nth(1).expect("base64 field");
    base64::decode(b64.as_bytes()).expect("decode pub base64")
}

fn concat_fixture(name: &str) -> String {
    format!(
        "{}/tests/fixtures/cert/{}",
        env!("CARGO_MANIFEST_DIR"),
        name
    )
}

/// The default CA-signature allow-list used by these tests (mirrors the
/// Phase 2 default, minus plain ssh-rsa).
const CA_ALGOS: &[&str] = &[
    "ssh-ed25519",
    "ecdsa-sha2-nistp256",
    "ecdsa-sha2-nistp384",
    "ecdsa-sha2-nistp521",
    "rsa-sha2-512",
    "rsa-sha2-256",
];

/// A "now" inside the 2020..2099 fixture window.
const NOW: u64 = 1_700_000_000; // 2023-11-14

#[test]
fn parse_ed25519_user_cert() {
    let blob = load_cert_blob("u_ed25519-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    assert_eq!(cert.key_type, "ssh-ed25519-cert-v01@openssh.com");
    assert_eq!(cert.embedded_algorithm(), "ssh-ed25519");
    assert_eq!(cert.cert_type, CertType::User);
    assert_eq!(cert.serial, 1);
    assert_eq!(cert.key_id, "alice");
    assert_eq!(cert.valid_principals, vec!["alice", "bob"]);
    // The reconstructed embedded blob must equal the plain key's wire blob.
    assert_eq!(cert.embedded_pubkey_blob(), load_pub_blob("u_ed25519.pub"));
}

#[test]
fn parse_ecdsa_user_cert() {
    for (file, algo) in [
        ("u_ecdsa-cert.pub", "ecdsa-sha2-nistp256"),
        ("u_ecdsa384-cert.pub", "ecdsa-sha2-nistp384"),
        ("u_ecdsa521-cert.pub", "ecdsa-sha2-nistp521"),
    ] {
        let blob = load_cert_blob(file);
        let cert = Certificate::parse(&blob).unwrap();
        assert_eq!(cert.embedded_algorithm(), algo, "{file}");
        assert_eq!(cert.cert_type, CertType::User);
        cert.verify_ca_signature(CA_ALGOS).unwrap();
    }
}

#[test]
fn parse_rsa_user_cert() {
    let blob = load_cert_blob("u_rsa-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    assert_eq!(cert.key_type, "ssh-rsa-cert-v01@openssh.com");
    assert_eq!(cert.embedded_algorithm(), "ssh-rsa");
    // The CA signed this cert with rsa-sha2-512 (carried in the signature).
    assert_eq!(cert.ca_algorithm().unwrap(), "rsa-sha2-512");
    assert_eq!(cert.cert_type, CertType::User);
    assert_eq!(cert.embedded_pubkey_blob(), load_pub_blob("u_rsa.pub"));
    cert.verify_ca_signature(CA_ALGOS).unwrap();
}

#[test]
fn parse_host_cert() {
    let blob = load_cert_blob("h_ed25519-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    assert_eq!(cert.cert_type, CertType::Host);
    assert_eq!(
        cert.valid_principals,
        vec!["host.example.com", "host2.example.com"]
    );
    cert.verify_ca_signature(CA_ALGOS).unwrap();
    cert.check_type(CertType::Host).unwrap();
    cert.check_principal("host.example.com").unwrap();
    assert!(cert.check_principal("evil.example.com").is_err());
}

#[test]
fn good_ca_signature_verifies() {
    let blob = load_cert_blob("u_ed25519-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    cert.verify_ca_signature(CA_ALGOS).unwrap();
}

#[test]
fn tampered_cert_fails_ca_signature() {
    let mut blob = load_cert_blob("u_ed25519-cert.pub");
    // Flip a byte in the key-id region (well inside the signed range).
    let cert = Certificate::parse(&blob).unwrap();
    // Mutate a byte that lies before signed_len but is not in a length prefix
    // we depend on for parsing — flip a byte in the embedded principals area.
    let idx = cert.signed_len / 2;
    blob[idx] ^= 0xff;
    // It may still parse (or not); if it parses, the CA sig must fail.
    if let Ok(c2) = Certificate::parse(&blob) {
        assert!(matches!(
            c2.verify_ca_signature(CA_ALGOS),
            Err(Error::CertBadCaSignature)
        ));
    }
}

#[test]
fn wrong_ca_algo_set_rejected() {
    let blob = load_cert_blob("u_ed25519-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    // CA signed with ssh-ed25519; an allow-list without it must reject.
    assert!(matches!(
        cert.verify_ca_signature(&["rsa-sha2-512"]),
        Err(Error::CertBadCaSignature)
    ));
    // Empty set rejects everything.
    assert!(matches!(
        cert.verify_ca_signature(&[]),
        Err(Error::CertBadCaSignature)
    ));
}

#[test]
fn wrong_ca_key_rejected() {
    // Take the ed25519 cert but swap in a different CA key blob: re-encode the
    // cert with signature_key_blob replaced by the ecdsa CA's blob. The CA
    // algorithm in the signature then won't match the swapped key, or the
    // signature won't verify.
    let blob = load_cert_blob("u_ecdsa-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    // Build a verifier whose CA key is the ed25519 CA but algo claims ecdsa —
    // the cleanest "wrong CA" test is: parse a cert and verify against an
    // allow-list that permits the algo but the embedded signature_key is from a
    // different CA. We simulate by checking that the *ecdsa* cert does not
    // verify if we corrupt its signature_key_blob.
    let mut raw = cert.raw.clone();
    // Corrupt within the signed region's signature-key area: flip last byte of
    // signed region.
    raw[cert.signed_len - 1] ^= 0xff;
    if let Ok(c2) = Certificate::parse(&raw) {
        assert!(c2.verify_ca_signature(CA_ALGOS).is_err());
    }
}

#[test]
fn expired_cert_rejected() {
    let blob = load_cert_blob("u_ed25519_expired-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    cert.verify_ca_signature(CA_ALGOS).unwrap(); // signature is still valid
    assert!(matches!(cert.check_validity(NOW), Err(Error::CertExpired)));
}

#[test]
fn not_yet_valid_cert_rejected() {
    let blob = load_cert_blob("u_ed25519_notyet-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    assert!(matches!(
        cert.check_validity(NOW),
        Err(Error::CertNotYetValid)
    ));
}

#[test]
fn principal_mismatch_rejected() {
    let blob = load_cert_blob("u_ecdsa-cert.pub"); // principals = ["bob"]
    let cert = Certificate::parse(&blob).unwrap();
    cert.check_principal("bob").unwrap();
    assert!(matches!(
        cert.check_principal("alice"),
        Err(Error::CertPrincipalMismatch)
    ));
}

#[test]
fn host_principal_match_is_case_insensitive() {
    // Host-cert principals are DNS host names: case-insensitive per OpenSSH.
    let mut cert = Certificate::parse(&load_cert_blob("h_ed25519-cert.pub")).unwrap();
    assert_eq!(cert.cert_type, CertType::Host);
    assert_eq!(
        cert.valid_principals,
        vec!["host.example.com", "host2.example.com"]
    );
    // Mixed-case query must match a lowercase principal for a host cert.
    cert.check_principal("Host.Example.Com").unwrap();
    cert.check_principal("HOST2.EXAMPLE.COM").unwrap();
    // A genuinely different host still fails.
    assert!(matches!(
        cert.check_principal("evil.example.com"),
        Err(Error::CertPrincipalMismatch)
    ));

    // Sanity: forcing the *same* cert to user type makes the comparison
    // case-sensitive, so the mixed-case query no longer matches.
    cert.cert_type = CertType::User;
    assert!(matches!(
        cert.check_principal("Host.Example.Com"),
        Err(Error::CertPrincipalMismatch)
    ));
    cert.check_principal("host.example.com").unwrap();
}

#[test]
fn user_principal_match_is_case_sensitive() {
    // User-cert principals are login names: case-sensitive per OpenSSH.
    let cert = Certificate::parse(&load_cert_blob("u_ed25519-cert.pub")).unwrap();
    assert_eq!(cert.cert_type, CertType::User);
    assert_eq!(cert.valid_principals, vec!["alice", "bob"]);
    cert.check_principal("alice").unwrap();
    // A case variant must NOT match a user-cert login name.
    assert!(matches!(
        cert.check_principal("Alice"),
        Err(Error::CertPrincipalMismatch)
    ));
    assert!(matches!(
        cert.check_principal("BOB"),
        Err(Error::CertPrincipalMismatch)
    ));
}

#[test]
fn type_mismatch_rejected() {
    let user = Certificate::parse(&load_cert_blob("u_ed25519-cert.pub")).unwrap();
    assert!(matches!(
        user.check_type(CertType::Host),
        Err(Error::CertTypeMismatch)
    ));
    let host = Certificate::parse(&load_cert_blob("h_ed25519-cert.pub")).unwrap();
    assert!(matches!(
        host.check_type(CertType::User),
        Err(Error::CertTypeMismatch)
    ));
}

#[test]
fn critical_options_parsed_and_known() {
    let blob = load_cert_blob("u_ed25519_crit-cert.pub");
    let cert = Certificate::parse(&blob).unwrap();
    // force-command and source-address are both understood.
    assert!(cert.unknown_critical_options().is_empty());
    cert.require_known_critical_options().unwrap();
    assert_eq!(
        cert.critical_option("force-command").unwrap(),
        // Inner string is itself length-prefixed per PROTOCOL.certkeys.
        encode_str(b"/usr/bin/uptime").as_slice()
    );
}

#[test]
fn unknown_critical_option_rejected() {
    // Synthesize a cert with an unknown critical option by re-encoding the
    // crit fixture's critical-options field. Easiest: hand-build a tiny cert is
    // overkill; instead assert the predicate on a constructed Certificate.
    let mut cert = Certificate::parse(&load_cert_blob("u_ed25519-cert.pub")).unwrap();
    cert.critical_options
        .push(("totally-unknown-option".to_string(), Vec::new()));
    assert_eq!(
        cert.unknown_critical_options(),
        vec!["totally-unknown-option"]
    );
    assert!(matches!(
        cert.require_known_critical_options(),
        Err(Error::CertUnknownCriticalOption)
    ));
}

#[test]
fn oversized_blob_rejected() {
    let big = vec![0u8; MAX_CERT_BLOB + 1];
    assert!(Certificate::parse(&big).is_err());
}

#[test]
fn trailing_data_rejected() {
    let mut blob = load_cert_blob("u_ed25519-cert.pub");
    blob.push(0x00); // one stray byte after the signature
    assert!(matches!(Certificate::parse(&blob), Err(Error::Format(_))));
}

#[test]
fn truncated_blob_rejected() {
    let blob = load_cert_blob("u_ed25519-cert.pub");
    assert!(Certificate::parse(&blob[..blob.len() / 2]).is_err());
}

#[test]
fn embedded_verifier_matches_underlying_key() {
    // Sign a message with each user key's private half (loaded from the
    // OpenSSH private key fixture) and verify via the cert's embedded verifier.
    use crate::key::PrivateKey;

    for (cert_file, priv_file) in [
        ("u_ed25519-cert.pub", "u_ed25519"),
        ("u_ecdsa-cert.pub", "u_ecdsa"),
        ("u_rsa-cert.pub", "u_rsa"),
    ] {
        let cert = Certificate::parse(&load_cert_blob(cert_file)).unwrap();
        let pem = std::fs::read_to_string(concat_fixture(priv_file)).unwrap();
        let sk = PrivateKey::parse_openssh_pem(&pem, None).unwrap();
        let signer = sk.into_host_key().unwrap();
        let msg = b"exchange-hash stand-in";
        let sig = signer.sign(msg).unwrap();
        let verifier = cert.embedded_verifier(&sig).unwrap();
        verifier.verify(msg, &sig).unwrap();
        // A tampered message must fail.
        assert!(verifier.verify(b"different", &sig).is_err());
    }
}

/// Build a syntactically-complete `ssh-rsa-cert-v01@openssh.com` blob whose
/// embedded modulus is `n_bits` bits. The CA signature is garbage — parse()
/// does not verify it, and the modulus floor is enforced *before* any
/// signature work, so a too-short modulus must be rejected at parse.
fn build_rsa_cert_blob(n_bits: usize) -> Vec<u8> {
    build_rsa_cert_blob_with_e(n_bits, &[0x01u8, 0x00, 0x01]) // e = 65537
}

/// [`build_rsa_cert_blob`] with an explicit public-exponent mpint.
fn build_rsa_cert_blob_with_e(n_bits: usize, e_mpint: &[u8]) -> Vec<u8> {
    assert_eq!(n_bits % 8, 0);
    let n_len = n_bits / 8;
    // Modulus: top bit of the leading magnitude byte set, so the value is
    // exactly `n_bits` bits wide. Encode as a proper non-negative mpint by
    // prepending a 0x00 sign byte.
    let mut n_mag = alloc::vec![0xa5u8; n_len];
    n_mag[0] = 0x80;
    let mut n_mpint = alloc::vec![0x00u8];
    n_mpint.extend_from_slice(&n_mag);

    let mut w = Writer::new();
    w.write_string(b"ssh-rsa-cert-v01@openssh.com");
    w.write_string(&[0u8; 16]); // nonce
    w.write_string(e_mpint); // mpint e
    w.write_string(&n_mpint); // mpint n
    w.write_u64(1); // serial
    w.write_u32(1); // type = user
    w.write_string(b"weak-rsa"); // key id
    w.write_string(b""); // valid principals (empty list)
    w.write_u64(0); // valid after
    w.write_u64(u64::MAX); // valid before
    w.write_string(b""); // critical options (empty)
    w.write_string(b""); // extensions (empty)
    w.write_string(b""); // reserved
    w.write_string(b"\x00\x00\x00\x07ssh-rsa"); // signature key (arbitrary)
    w.write_string(b"\x00\x00\x00\x07ssh-rsasig"); // signature (arbitrary)
    w.into_vec()
}

#[test]
fn rsa_cert_with_weak_modulus_rejected_at_parse() {
    // A cert wrapping a 1024-bit RSA key must be refused at parse time, with
    // the same 2048-bit-floor error the plain ssh-rsa parser raises.
    let blob = build_rsa_cert_blob(1024);
    match Certificate::parse(&blob) {
        Err(Error::Format(msg)) => {
            assert!(
                msg.contains("2048"),
                "expected 2048-bit floor error, got {msg:?}"
            )
        }
        Err(other) => panic!("expected Format(2048), got {other:?}"),
        Ok(_) => panic!("expected 1024-bit embedded RSA key to be rejected at parse"),
    }
}

#[test]
fn rsa_cert_with_2048_modulus_parses() {
    // The same construction at 2048 bits must clear the floor (it then fails
    // only later at CA-signature verification, which we don't run here).
    let blob = build_rsa_cert_blob(2048);
    let cert = Certificate::parse(&blob).expect("2048-bit embedded RSA must parse");
    assert_eq!(cert.embedded_algorithm(), "ssh-rsa");
}

#[test]
fn rsa_cert_with_oversized_exponent_rejected_at_parse() {
    // A cert whose embedded RSA key carries a 2047-bit `e` must be refused
    // at parse time (verify cost is linear in the exponent width), just
    // like the plain-key parser refuses it.
    let mut e_mpint = alloc::vec![0xffu8; 256];
    e_mpint[0] = 0x7f;
    let blob = build_rsa_cert_blob_with_e(2048, &e_mpint);
    match Certificate::parse(&blob) {
        Err(Error::Format(msg)) => assert!(msg.contains("exponent"), "got {msg:?}"),
        Err(other) => panic!("expected Format(exponent), got {other:?}"),
        Ok(_) => panic!("expected oversized embedded exponent to be rejected at parse"),
    }
}

#[test]
fn rsa_ca_key_with_oversized_exponent_rejected_at_verify() {
    // The CA key is parsed lazily by `verify_ca_signature`; a hostile CA
    // blob with a huge `e` must be refused there (before any modexp) with
    // the usual CA-signature error rather than burning CPU.
    let mut n_mag = alloc::vec![0xa5u8; 256];
    n_mag[0] = 0x80;
    let mut e_mag = alloc::vec![0xffu8; 256];
    e_mag[0] = 0x7f;
    let mut ca = Writer::new();
    ca.write_string(b"ssh-rsa");
    crate::format::write_mpint(&mut ca, &e_mag);
    crate::format::write_mpint(&mut ca, &n_mag);
    let ca_blob = ca.into_vec();

    let mut cert = Certificate::parse(&load_cert_blob("u_ed25519-cert.pub")).unwrap();
    cert.signature_key_blob = ca_blob;
    // Claim an RSA CA signature so the RSA parser is the one consulted.
    let mut sig = Writer::new();
    sig.write_string(b"rsa-sha2-512");
    sig.write_string(&[0u8; 256]);
    cert.signature = sig.into_vec();
    assert!(matches!(
        cert.verify_ca_signature(CA_ALGOS),
        Err(Error::CertBadCaSignature)
    ));
}

#[test]
fn malformed_critical_option_payload_rejected() {
    // `force-command` / `source-address` payloads are themselves SSH
    // strings. A payload that does not decode as exactly one string must
    // fail closed (OpenSSH rejects the cert) rather than being treated as
    // "no force-command".
    let base = Certificate::parse(&load_cert_blob("u_ed25519-cert.pub")).unwrap();
    for bad in [
        alloc::vec![0xffu8, 0xff, 0xff, 0xff], // length overruns the payload
        alloc::vec![0x00u8, 0x00, 0x00, 0x02, b'a'], // truncated string
        {
            let mut v = encode_str(b"/bin/true");
            v.push(0x00); // trailing garbage after the string
            v
        },
        alloc::vec![0x00u8, 0x00, 0x00, 0x01, 0xff], // not UTF-8
        Vec::new(),                                  // empty payload
    ] {
        let mut cert = base.clone();
        cert.critical_options = alloc::vec![("force-command".to_string(), bad.clone())];
        assert!(
            cert.require_known_critical_options().is_err(),
            "force-command payload {bad:?} must be rejected"
        );
        let mut cert = base.clone();
        cert.critical_options = alloc::vec![("source-address".to_string(), bad.clone())];
        assert!(
            cert.require_known_critical_options().is_err(),
            "source-address payload {bad:?} must be rejected"
        );
    }
    // Well-formed payloads still pass.
    let mut cert = base.clone();
    cert.critical_options = alloc::vec![
        ("force-command".to_string(), encode_str(b"/usr/bin/uptime")),
        ("source-address".to_string(), encode_str(b"10.0.0.0/8")),
    ];
    cert.require_known_critical_options().unwrap();
}

/// Helper mirroring SSH string encoding for the force-command assertion.
fn encode_str(s: &[u8]) -> Vec<u8> {
    let mut w = Writer::new();
    w.write_string(s);
    w.into_vec()
}

#[test]
fn openssh_rsa_cert_line_parses() {
    let text = std::fs::read_to_string(concat_fixture("u_rsa-cert.pub")).unwrap();
    assert!(text.starts_with("ssh-rsa-cert-v01@openssh.com "));
    let cert = Certificate::parse_openssh_line(&text).unwrap();
    assert_eq!(cert.key_type, "ssh-rsa-cert-v01@openssh.com");
    // The negotiated name for the same blob is accepted too.
    let renamed = text.replacen(
        "ssh-rsa-cert-v01@openssh.com",
        "rsa-sha2-512-cert-v01@openssh.com",
        1,
    );
    Certificate::parse_openssh_line(&renamed).unwrap();
}

/// Rebuilding an OpenSSH-made certificate from its fields (and its CA
/// signature) gives back the identical blob.
#[test]
fn builder_reproduces_openssh_cert() {
    for name in [
        "u_ed25519-cert.pub",
        "u_ed25519_crit-cert.pub",
        "h_ed25519-cert.pub",
        "u_rsa-cert.pub",
        "u_ecdsa-cert.pub",
    ] {
        let orig = Certificate::parse(&load_cert_blob(name)).unwrap();
        let mut b = CertificateBuilder::new(
            orig.embedded_pubkey_blob.clone(),
            orig.cert_type,
            orig.nonce.clone(),
        );
        b.serial = orig.serial;
        b.key_id = orig.key_id.clone();
        b.valid_principals = orig.valid_principals.clone();
        b.valid_after = orig.valid_after;
        b.valid_before = orig.valid_before;
        b.critical_options = orig.critical_options.clone();
        // Order must not matter: the builder sorts.
        b.extensions = orig.extensions.iter().rev().cloned().collect();
        let rebuilt = b
            .sign(&orig.signature_key_blob, |data| {
                assert_eq!(data, &orig.raw[..orig.signed_len]);
                Ok(orig.signature.clone())
            })
            .unwrap();
        assert_eq!(rebuilt.raw, orig.raw, "{name}");
    }
}

#[test]
fn builder_signs_verifiable_cert() {
    use crate::hostkey::{Ed25519HostKey, HostKey};
    let ca = Ed25519HostKey::from_seed([7u8; 32]);
    let user = Ed25519HostKey::from_seed([8u8; 32]);
    let mut b = CertificateBuilder::new(user.public_blob(), CertType::User, alloc::vec![1u8; 32]);
    b.key_id = "alice".into();
    b.valid_principals = alloc::vec!["alice".into(), "root".into()];
    b.critical_options = alloc::vec![("force-command".into(), encode_option_string("/bin/true"))];
    b.extensions = DEFAULT_USER_EXTENSIONS
        .iter()
        .map(|e| (e.to_string(), Vec::new()))
        .collect();
    let cert = b.sign(&ca.public_blob(), |d| ca.sign(d)).unwrap();
    cert.verify_ca_signature(CA_ALGOS).unwrap();
    cert.check_principal("root").unwrap();
    assert_eq!(
        cert.critical_option_string("force-command").as_deref(),
        Some("/bin/true")
    );
    assert!(cert.has_extension("permit-pty"));
    let line = cert.to_openssh_line("alice@host");
    let back = Certificate::parse_openssh_line(&line).unwrap();
    assert_eq!(back.raw, cert.raw);
    // Duplicate extensions are refused.
    b.extensions.push(("permit-pty".into(), Vec::new()));
    assert!(b.sign(&ca.public_blob(), |d| ca.sign(d)).is_err());
}

#[test]
fn cert_names_for_key_types() {
    assert_eq!(
        cert_name_for_key_type("ssh-rsa"),
        Some("rsa-sha2-512-cert-v01@openssh.com")
    );
    assert_eq!(
        cert_name_for_key_type("rsa-sha2-256"),
        Some("rsa-sha2-256-cert-v01@openssh.com")
    );
    assert_eq!(
        cert_name_for_key_type("ssh-ed25519"),
        Some("ssh-ed25519-cert-v01@openssh.com")
    );
    assert_eq!(
        cert_name_for_key_type("ecdsa-sha2-nistp384"),
        Some("ecdsa-sha2-nistp384-cert-v01@openssh.com")
    );
    assert_eq!(cert_name_for_key_type("ssh-dss"), None);
}

#[test]
fn host_principals_are_patterns_and_must_be_present() {
    let mut cert = Certificate::parse(&load_cert_blob("h_ed25519-cert.pub")).unwrap();
    cert.valid_principals = vec!["*.example.com".into(), "loc?lhost".into()];
    cert.check_principal("host.example.com").unwrap();
    cert.check_principal("LOCALHOST").unwrap();
    assert!(cert.check_principal("example.org").is_err());
    // A certificate naming no host / user is refused, as OpenSSH 10 does.
    cert.valid_principals.clear();
    assert!(matches!(
        cert.check_principal("host.example.com"),
        Err(Error::CertPrincipalMismatch)
    ));
    cert.cert_type = CertType::User;
    assert!(cert.check_principal("anyone").is_err());
}