overbrainer 0.8.1

Distill a large LLM into a smaller open-weights model: generate questions, collect answers, fine-tune, visualize.
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
//! Per-run SSH keys and the per-run ssh config: `runs/<run-id>/ssh/`.
//!
//! The pod's host key is generated here and sent in the create call's `env`; its
//! public half is pinned in a `known_hosts` keyed by a `HostKeyAlias`, so a new
//! public port after a pod reset only changes the config, never the pinned key.
//! The config is passed to `ssh -F`, which then ignores `~/.ssh/config` and
//! `/etc/ssh/ssh_config`: no user setting can weaken or break the connection.

use std::fs;
use std::io;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use secrecy::SecretString;
use secrecy::zeroize::Zeroizing;

use crate::config::SshClient;
use crate::exec::PodEndpoint;
use crate::runs::is_safe_name;

use super::{PodError, SshEndpoint};

/// Directory of a run's SSH files, in its local run directory.
pub const SSH_DIR: &str = "ssh";
/// The run's client private key, in [`SSH_DIR`].
pub const CLIENT_KEY: &str = "id_ed25519";
/// The run's ssh config, in [`SSH_DIR`].
pub const SSH_CONFIG: &str = "config";
/// The pod's pinned host key, in [`SSH_DIR`].
pub const KNOWN_HOSTS: &str = "known_hosts";
/// Name of the host key while it is generated, in [`SSH_DIR`]; removed at once.
const HOST_KEY: &str = "host_ed25519";

/// The SSH host alias of a run's pod, also its `HostKeyAlias`.
#[must_use]
pub fn alias(run_id: &str) -> String {
    format!("overbrainer-{run_id}")
}

/// The keys of a run: the client key overbrainer logs in with, and the pod's host
/// key. The private host key only lives in memory, as the base64 of its OpenSSH
/// file, until it is sent in the create call.
#[derive(Debug, Clone)]
pub struct PodKeys {
    /// The client private key file, absolute.
    pub client_key: PathBuf,
    /// The client public key, one `ssh-ed25519 AAAA... comment` line.
    pub client_public: String,
    /// The pod's public host key, `ssh-ed25519 AAAA...`.
    pub host_public: String,
    host_private: SecretString,
}

impl PodKeys {
    /// Keys from their parts. `host_private` is the base64 of the OpenSSH private
    /// host key file.
    #[must_use]
    pub fn new(
        client_key: PathBuf,
        client_public: String,
        host_public: String,
        host_private: SecretString,
    ) -> Self {
        Self {
            client_key,
            client_public,
            host_public,
            host_private,
        }
    }

    /// Generates both keys (ed25519, no passphrase), the client key into `dir`
    /// (created with mode 700): with `ssh-keygen` for [`SshClient::Openssh`], in
    /// Rust for [`SshClient::Builtin`], which writes the same files in the same
    /// formats. In a build without the `builtin-ssh` feature `Builtin` is
    /// refused by the configuration and never gets here; it is generated with
    /// `ssh-keygen` like `Openssh`. The host key file is read and removed at
    /// once, whether the read succeeds or fails.
    ///
    /// # Errors
    ///
    /// Returns [`PodError::Keygen`] when `ssh-keygen` is missing or fails (or the
    /// Rust generation fails), and [`PodError::Io`] when a file cannot be
    /// written, read or removed.
    pub fn generate(dir: &Path, comment: &str, client: SshClient) -> Result<Self, PodError> {
        fs::create_dir_all(dir).map_err(io_error(dir))?;
        fs::set_permissions(dir, fs::Permissions::from_mode(0o700)).map_err(io_error(dir))?;
        let dir = std::path::absolute(dir).map_err(io_error(dir))?;
        let client_key = dir.join(CLIENT_KEY);
        make_pair(&client_key, comment, client)?;
        let client_public = read_public(&client_key)?;
        let host_key = dir.join(HOST_KEY);
        make_pair(&host_key, comment, client)?;
        let (host_public, host_private) = take_host_key(&host_key)?;
        Ok(Self {
            client_key,
            client_public,
            host_public,
            host_private,
        })
    }

    /// The base64 of the OpenSSH private host key file, for the create call.
    #[must_use]
    pub fn host_private(&self) -> &SecretString {
        &self.host_private
    }
}

/// Writes a fresh ed25519 key pair at `path` with the generator of `client`.
fn make_pair(path: &Path, comment: &str, client: SshClient) -> Result<(), PodError> {
    match client {
        #[cfg(feature = "builtin-ssh")]
        SshClient::Builtin => rust_keygen(path, comment),
        // Without the feature, `Builtin` is refused when the configuration is
        // validated; `ssh-keygen` is the only generator there is.
        #[cfg(not(feature = "builtin-ssh"))]
        SshClient::Builtin => keygen(path, comment),
        SshClient::Openssh => keygen(path, comment),
    }
}

/// Writes a fresh ed25519 key pair at `path` in Rust, in the files `ssh-keygen`
/// writes: the OpenSSH private key (mode 0600, never overwritten) and the
/// `.pub` line `ssh-ed25519 <key> <comment>`.
#[cfg(feature = "builtin-ssh")]
fn rust_keygen(path: &Path, comment: &str) -> Result<(), PodError> {
    use std::io::Write;
    use std::os::unix::fs::OpenOptionsExt;

    use russh::keys::ssh_key::LineEnding;
    use russh::keys::{Algorithm, PrivateKey};

    let failed = |what: &str| PodError::Keygen(format!("cannot generate an ed25519 key: {what}"));
    remove_pair(path)?;
    let mut key = PrivateKey::random(&mut rand::rng(), Algorithm::Ed25519)
        .map_err(|_| failed("the key pair was refused"))?;
    key.set_comment(comment);
    let private = key
        .to_openssh(LineEnding::LF)
        .map_err(|_| failed("the private key cannot be encoded"))?;
    let public = key
        .public_key()
        .to_openssh()
        .map_err(|_| failed("the public key cannot be encoded"))?;
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .map_err(io_error(path))?;
    file.write_all(private.as_bytes()).map_err(io_error(path))?;
    let public_file = public_path(path);
    fs::write(&public_file, format!("{public}\n")).map_err(io_error(&public_file))?;
    Ok(())
}

/// Runs `ssh-keygen` to write a fresh ed25519 key pair at `path`.
fn keygen(path: &Path, comment: &str) -> Result<(), PodError> {
    remove_pair(path)?;
    let output = Command::new("ssh-keygen")
        .args(["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f"])
        .arg(path)
        .stdin(Stdio::null())
        .output()
        .map_err(|error| {
            PodError::Keygen(format!(
                "cannot run ssh-keygen ({error}); it ships with the OpenSSH client"
            ))
        })?;
    if output.status.success() {
        Ok(())
    } else {
        Err(PodError::Keygen(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ))
    }
}

/// The public key next to the private key `path`, on one line.
fn read_public(path: &Path) -> Result<String, PodError> {
    let public = public_path(path);
    let text = fs::read_to_string(&public).map_err(io_error(&public))?;
    Ok(text.trim().to_string())
}

/// Reads the host key pair at `host_key` (its public key and the base64 of its
/// private key file, wiped from memory as soon as it is encoded) and removes
/// both files, whether the read succeeds or fails: the pair never stays on disk.
fn take_host_key(host_key: &Path) -> Result<(String, SecretString), PodError> {
    let read = read_public(host_key).and_then(|host_public| {
        fs::read(host_key)
            .map(Zeroizing::new)
            .map_err(io_error(host_key))
            .map(|raw| {
                let encoded = Zeroizing::new(base64(&raw));
                (
                    key_fields(&host_public),
                    SecretString::from(encoded.as_str()),
                )
            })
    });
    remove_pair(host_key)?;
    read
}

fn public_path(path: &Path) -> PathBuf {
    let mut public = path.as_os_str().to_owned();
    public.push(".pub");
    PathBuf::from(public)
}

/// Removes the key pair at `path`, if any.
fn remove_pair(path: &Path) -> Result<(), PodError> {
    for file in [path.to_path_buf(), public_path(path)] {
        match fs::remove_file(&file) {
            Ok(()) => {},
            Err(e) if e.kind() == io::ErrorKind::NotFound => {},
            Err(source) => return Err(PodError::Io { path: file, source }),
        }
    }
    Ok(())
}

/// The key type and the key of a public key line, without its comment.
fn key_fields(line: &str) -> String {
    line.split_whitespace()
        .take(2)
        .collect::<Vec<_>>()
        .join(" ")
}

/// Longest ssh alias [`valid_alias`] accepts: room for [`alias`] of the longest
/// run ID, and a suffix.
const ALIAS_MAX: usize = 128;

/// Checks that `alias` is safe to interpolate into an ssh config or a
/// `known_hosts` line: the same allow-list as a run ID, letters, digits, `_`
/// and `-`, starting with a letter or a digit, non-empty.
fn valid_alias(alias: &str) -> Result<(), PodError> {
    if is_safe_name(alias, ALIAS_MAX) {
        Ok(())
    } else {
        Err(PodError::InvalidPath(format!(
            "{} is not a valid ssh alias: only letters, digits, `_` and `-`, starting with a letter or a digit, at most {ALIAS_MAX} characters",
            alias.escape_debug()
        )))
    }
}

/// Writes `known_hosts` into `dir`: one line pinning `host_public` for `alias`.
/// Returns its path.
///
/// # Errors
///
/// Returns [`PodError::InvalidPath`] when `alias` is not a safe ssh alias, and
/// [`PodError::Io`] when the file cannot be written.
pub fn write_known_hosts(dir: &Path, alias: &str, host_public: &str) -> Result<PathBuf, PodError> {
    valid_alias(alias)?;
    let path = dir.join(KNOWN_HOSTS);
    let line = format!("{alias} {}\n", key_fields(host_public));
    fs::write(&path, line).map_err(io_error(&path))?;
    Ok(path)
}

/// Writes the ssh config of a run into `dir` (created if needed), with
/// `endpoint` as the pod's address, and the `known_hosts` it points to. Rewritten before every connection,
/// since a pod reset changes its public port. Returns the config's path.
///
/// # Errors
///
/// Returns [`PodError::InvalidPath`] when a path cannot be written in an ssh
/// config or `alias` is not a safe ssh alias, [`PodError::InvalidEndpoint`] when
/// Runpod's endpoint holds characters no host or user name has, and
/// [`PodError::Io`] when a file cannot be written.
pub fn write_config(
    dir: &Path,
    alias: &str,
    endpoint: &SshEndpoint,
    keys: &PodKeys,
) -> Result<PathBuf, PodError> {
    fs::create_dir_all(dir).map_err(io_error(dir))?;
    let dir = std::path::absolute(dir).map_err(io_error(dir))?;
    let known_hosts = write_known_hosts(&dir, alias, &keys.host_public)?;
    let text = ssh_config(alias, endpoint, &keys.client_key, &known_hosts)?;
    let path = dir.join(SSH_CONFIG);
    fs::write(&path, text).map_err(io_error(&path))?;
    Ok(path)
}

/// Writes the run's ssh config (see [`write_config`]) and returns what reaches
/// the pod at `endpoint`, with either client: the config for OpenSSH, the
/// endpoint, client key and pinned host key for the built-in client.
///
/// # Errors
///
/// See [`write_config`].
pub fn pod_endpoint(
    dir: &Path,
    alias: &str,
    endpoint: &SshEndpoint,
    keys: &PodKeys,
) -> Result<PodEndpoint, PodError> {
    let config = write_config(dir, alias, endpoint, keys)?;
    Ok(PodEndpoint {
        alias: alias.to_string(),
        config,
        host: endpoint.host.clone(),
        port: endpoint.port,
        user: endpoint.user.clone(),
        key: keys.client_key.clone(),
        host_key: keys.host_public.clone(),
    })
}

/// The text of a run's ssh config.
///
/// # Errors
///
/// See [`write_config`].
pub fn ssh_config(
    alias: &str,
    endpoint: &SshEndpoint,
    identity: &Path,
    known_hosts: &Path,
) -> Result<String, PodError> {
    valid_alias(alias)?;
    let host_ok = !endpoint.host.is_empty()
        && endpoint
            .host
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '-'));
    let user_ok = !endpoint.user.is_empty()
        && endpoint
            .user
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
    if !host_ok || !user_ok || endpoint.port == 0 {
        return Err(PodError::InvalidEndpoint(format!(
            "{}@{}:{}",
            endpoint.user.escape_debug(),
            endpoint.host.escape_debug(),
            endpoint.port
        )));
    }
    let lines = [
        format!("Host {alias}"),
        format!("  HostName {}", endpoint.host),
        format!("  Port {}", endpoint.port),
        format!("  User {}", endpoint.user),
        format!("  IdentityFile {}", config_path(identity)?),
        "  IdentitiesOnly yes".to_string(),
        "  IdentityAgent none".to_string(),
        format!("  UserKnownHostsFile {}", config_path(known_hosts)?),
        "  GlobalKnownHostsFile /dev/null".to_string(),
        format!("  HostKeyAlias {alias}"),
        "  CheckHostIP no".to_string(),
        "  StrictHostKeyChecking yes".to_string(),
        "  UpdateHostKeys no".to_string(),
        "  PasswordAuthentication no".to_string(),
        "  KbdInteractiveAuthentication no".to_string(),
    ];
    Ok(format!("{}\n", lines.join("\n")))
}

/// `path` as a double-quoted ssh config value, `%` doubled (ssh expands `%`
/// tokens in these options).
fn config_path(path: &Path) -> Result<String, PodError> {
    let text = path
        .to_str()
        .ok_or_else(|| PodError::InvalidPath(format!("{} is not valid UTF-8", path.display())))?;
    if text.contains(['"', '\n', '\r']) {
        return Err(PodError::InvalidPath(format!(
            "{} holds a double quote or a line break, which an ssh config cannot hold: move the project",
            text.escape_debug()
        )));
    }
    Ok(format!("\"{}\"", text.replace('%', "%%")))
}

/// `bytes` in standard base64, with padding and no line break.
#[must_use]
pub fn base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            chunk.get(1).copied().unwrap_or(0),
            chunk.get(2).copied().unwrap_or(0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        for (index, shift) in [18, 12, 6, 0].into_iter().enumerate() {
            if index <= chunk.len() {
                let sextet = usize::try_from((n >> shift) & 63).unwrap_or(0);
                out.push(char::from(ALPHABET[sextet]));
            } else {
                out.push('=');
            }
        }
    }
    out
}

fn io_error(path: &Path) -> impl FnOnce(io::Error) -> PodError + '_ {
    move |source| PodError::Io {
        path: path.to_path_buf(),
        source,
    }
}

#[cfg(test)]
mod tests {
    use secrecy::ExposeSecret;

    use super::*;

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    #[test]
    fn base64_matches_the_rfc_vectors() {
        let vectors = [
            ("", ""),
            ("f", "Zg=="),
            ("fo", "Zm8="),
            ("foo", "Zm9v"),
            ("foob", "Zm9vYg=="),
            ("fooba", "Zm9vYmE="),
            ("foobar", "Zm9vYmFy"),
        ];
        for (plain, encoded) in vectors {
            assert_eq!(base64(plain.as_bytes()), encoded, "{plain}");
        }
        assert_eq!(base64(&[0xff, 0xfe, 0xfd]), "//79");
    }

    fn endpoint() -> SshEndpoint {
        SshEndpoint {
            host: "203.0.113.7".into(),
            port: 40122,
            user: "root".into(),
        }
    }

    #[test]
    fn the_config_pins_the_alias_and_ignores_the_agent() -> TestResult {
        let text = ssh_config(
            "overbrainer-r1",
            &endpoint(),
            Path::new("/p/a b%c/runs/r1/ssh/id_ed25519"),
            Path::new("/p/a b%c/runs/r1/ssh/known_hosts"),
        )?;
        assert_eq!(
            text,
            "Host overbrainer-r1\n  HostName 203.0.113.7\n  Port 40122\n  User root\n  IdentityFile \"/p/a b%%c/runs/r1/ssh/id_ed25519\"\n  IdentitiesOnly yes\n  IdentityAgent none\n  UserKnownHostsFile \"/p/a b%%c/runs/r1/ssh/known_hosts\"\n  GlobalKnownHostsFile /dev/null\n  HostKeyAlias overbrainer-r1\n  CheckHostIP no\n  StrictHostKeyChecking yes\n  UpdateHostKeys no\n  PasswordAuthentication no\n  KbdInteractiveAuthentication no\n"
        );
        Ok(())
    }

    #[test]
    fn unquotable_paths_and_odd_endpoints_are_refused() {
        let refused = ssh_config(
            "overbrainer-r1",
            &endpoint(),
            Path::new("/p/a\"b/id"),
            Path::new("/p/known_hosts"),
        );
        assert!(matches!(refused, Err(PodError::InvalidPath(_))));
        for bad in [
            SshEndpoint {
                host: "1.2.3.4\n  ProxyCommand x".into(),
                ..endpoint()
            },
            SshEndpoint {
                user: "root x".into(),
                ..endpoint()
            },
            SshEndpoint {
                port: 0,
                ..endpoint()
            },
        ] {
            let result = ssh_config("a", &bad, Path::new("/id"), Path::new("/kh"));
            assert!(
                matches!(result, Err(PodError::InvalidEndpoint(_))),
                "{bad:?}"
            );
        }
    }

    #[test]
    fn known_hosts_pins_the_key_under_the_alias() -> TestResult {
        let dir = tempfile::tempdir()?;
        let path = write_known_hosts(dir.path(), "overbrainer-r1", "ssh-ed25519 AAAAkey comment")?;
        assert_eq!(
            fs::read_to_string(path)?,
            "overbrainer-r1 ssh-ed25519 AAAAkey\n"
        );
        Ok(())
    }

    #[test]
    fn the_alias_of_the_longest_run_id_is_accepted() -> TestResult {
        let id = format!("{}_20260930-120000_99", "a".repeat(40));
        assert!(crate::runs::is_valid_run_id(&id));
        let dir = tempfile::tempdir()?;
        write_known_hosts(dir.path(), &alias(&id), "ssh-ed25519 AAAAkey")?;
        let config = ssh_config(&alias(&id), &endpoint(), Path::new("/id"), Path::new("/kh"));
        assert!(config.is_ok(), "{config:?}");
        Ok(())
    }

    #[test]
    fn a_bad_alias_is_refused_everywhere_it_is_interpolated() -> TestResult {
        let long = "a".repeat(ALIAS_MAX + 1);
        for bad in ["a b", "a*b", "a,b", "a\nb", "", "-a", "a.b", &long] {
            let config = ssh_config(bad, &endpoint(), Path::new("/id"), Path::new("/kh"));
            assert!(matches!(config, Err(PodError::InvalidPath(_))), "{bad:?}");

            let dir = tempfile::tempdir()?;
            let known_hosts = write_known_hosts(dir.path(), bad, "ssh-ed25519 AAAAkey");
            assert!(
                matches!(known_hosts, Err(PodError::InvalidPath(_))),
                "{bad:?}"
            );
        }
        Ok(())
    }

    #[test]
    fn take_host_key_removes_the_pair_even_when_the_public_half_is_missing() -> TestResult {
        let dir = tempfile::tempdir()?;
        let host_key = dir.path().join(HOST_KEY);
        fs::write(&host_key, b"not a real private key")?;
        // No `.pub` file next to it: `read_public` fails.
        let result = take_host_key(&host_key);
        assert!(result.is_err());
        assert!(!host_key.exists(), "the private key was left on disk");
        Ok(())
    }

    /// Whether the OpenSSH `ssh-keygen` is installed on `PATH`.
    fn keygen_available() -> bool {
        Command::new("ssh-keygen")
            .arg("-?")
            .stderr(Stdio::null())
            .stdout(Stdio::null())
            .status()
            .is_ok()
    }

    /// Generates keys with `client` and checks the files, the modes and the
    /// shapes of the public lines; the pair is then usable by either client.
    fn check_generated(
        client: SshClient,
    ) -> Result<(tempfile::TempDir, PodKeys), Box<dyn std::error::Error>> {
        let root = tempfile::tempdir()?;
        let dir = root.path().join("ssh");
        let keys = PodKeys::generate(&dir, "overbrainer-r1", client)?;
        assert_eq!(fs::metadata(&dir)?.permissions().mode() & 0o777, 0o700);
        assert_eq!(
            fs::metadata(&keys.client_key)?.permissions().mode() & 0o777,
            0o600
        );
        assert!(keys.client_public.starts_with("ssh-ed25519 "));
        assert!(keys.client_public.ends_with(" overbrainer-r1"));
        assert!(keys.host_public.starts_with("ssh-ed25519 "));
        assert_eq!(keys.host_public.split_whitespace().count(), 2);
        assert!(!dir.join(HOST_KEY).exists());
        assert!(!dir.join(format!("{HOST_KEY}.pub")).exists());
        assert!(!format!("{keys:?}").contains(keys.host_private().expose_secret()));
        Ok((root, keys))
    }

    /// Decodes the private host key the way the pod's bootstrap does and asks
    /// `ssh-keygen -y` for its public key.
    fn host_public_through_keygen(
        root: &Path,
        keys: &PodKeys,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let decoded = root.join("decoded");
        let output = Command::new("sh")
            .arg("-c")
            .arg("printf '%s' \"$KEY\" | base64 -d > \"$OUT\" && chmod 600 \"$OUT\" && ssh-keygen -y -f \"$OUT\"")
            .env("KEY", keys.host_private().expose_secret())
            .env("OUT", &decoded)
            .output()?;
        assert!(output.status.success(), "ssh-keygen -y failed");
        Ok(key_fields(&String::from_utf8(output.stdout)?))
    }

    /// Keys from `ssh-keygen` hold together: the pod's bootstrap decodes the
    /// private host key back to the pinned public key.
    #[test]
    fn generated_keys_hold_together() -> TestResult {
        if !keygen_available() {
            eprintln!("skipped: ssh-keygen is not installed");
            return Ok(());
        }
        let (root, keys) = check_generated(SshClient::Openssh)?;
        // Decoded the way the pod's bootstrap does, the private host key gives back
        // the pinned public key.
        assert_eq!(
            host_public_through_keygen(root.path(), &keys)?,
            keys.host_public
        );
        Ok(())
    }

    /// Keys from the built-in generator hold together: the client's public
    /// line matches its private key and its `.pub` file.
    #[cfg(feature = "builtin-ssh")]
    #[test]
    fn rust_generated_keys_hold_together() -> TestResult {
        let (_root, keys) = check_generated(SshClient::Builtin)?;
        // The public line of the client key matches its private key.
        let private = russh::keys::load_secret_key(&keys.client_key, None)?;
        assert_eq!(
            key_fields(&private.public_key().to_openssh()?),
            key_fields(&keys.client_public)
        );
        assert_eq!(
            fs::read_to_string(public_path(&keys.client_key))?,
            format!("{}\n", keys.client_public)
        );
        Ok(())
    }

    /// Two runs never share a key.
    #[cfg(feature = "builtin-ssh")]
    #[test]
    fn rust_generated_keys_are_fresh() -> TestResult {
        let (_a, first) = check_generated(SshClient::Builtin)?;
        let (_b, second) = check_generated(SshClient::Builtin)?;
        assert_ne!(first.client_public, second.client_public);
        assert_ne!(first.host_public, second.host_public);
        assert_ne!(first.client_public, first.host_public);
        Ok(())
    }

    /// Cross-checks the Rust-written files with the real `ssh-keygen -y`. It runs
    /// only when `/usr/bin/ssh-keygen` exists and is skipped otherwise.
    #[cfg(feature = "builtin-ssh")]
    #[test]
    fn rust_generated_keys_are_read_by_ssh_keygen() -> TestResult {
        let keygen = Path::new("/usr/bin/ssh-keygen");
        if !keygen.exists() {
            eprintln!("skipped: /usr/bin/ssh-keygen is not installed");
            return Ok(());
        }
        let (root, keys) = check_generated(SshClient::Builtin)?;
        let output = Command::new(keygen)
            .arg("-y")
            .arg("-f")
            .arg(&keys.client_key)
            .stdin(Stdio::null())
            .output()?;
        assert!(output.status.success(), "ssh-keygen -y failed");
        assert_eq!(
            key_fields(&String::from_utf8(output.stdout)?),
            key_fields(&keys.client_public)
        );
        let decoded = root.path().join("decoded");
        let host = Command::new("sh")
            .arg("-c")
            .arg("printf '%s' \"$KEY\" | base64 -d > \"$OUT\" && chmod 600 \"$OUT\" && /usr/bin/ssh-keygen -y -f \"$OUT\"")
            .env("KEY", keys.host_private().expose_secret())
            .env("OUT", &decoded)
            .output()?;
        assert!(host.status.success(), "ssh-keygen -y failed");
        assert_eq!(
            key_fields(&String::from_utf8(host.stdout)?),
            keys.host_public
        );
        Ok(())
    }
}