agentkernel 0.18.1

Run AI coding agents in secure, isolated microVMs
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
//! SSH support for sandbox access.
//!
//! When `--ssh` is enabled, sandboxes get an sshd configured for
//! certificate-only authentication. Vault or a local CA signs
//! ephemeral client certificates.

use anyhow::{Context, Result, bail};
use ssh_key::{Algorithm, LineEnding, PrivateKey, certificate};

use crate::backend::FileInjection;

/// SSH configuration for a sandbox
#[derive(Debug, Clone)]
pub struct SshConfig {
    /// Enable SSH access
    pub enabled: bool,
    /// Port inside the sandbox for sshd (default: 22)
    pub port: u16,
    /// Host port to map sshd to (None = auto-assign)
    pub host_port: Option<u16>,
    /// Vault address for SSH CA (None = use built-in CA)
    pub vault_addr: Option<String>,
    /// Vault SSH secrets engine mount path
    pub vault_ssh_mount: String,
    /// Vault SSH role for signing
    pub vault_ssh_role: String,
    /// Certificate TTL
    pub cert_ttl: String,
    /// Username inside the sandbox
    pub user: String,
}

impl Default for SshConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            port: 22,
            host_port: None,
            vault_addr: None,
            vault_ssh_mount: "ssh".to_string(),
            vault_ssh_role: "agentkernel-client".to_string(),
            cert_ttl: "30m".to_string(),
            user: "sandbox".to_string(),
        }
    }
}

/// Generate an sshd_config string for certificate-only authentication.
pub fn generate_sshd_config(config: &SshConfig) -> String {
    format!(
        r#"# agentkernel sshd configuration — certificate-only auth
Port {port}
ListenAddress 0.0.0.0

# Host key
HostKey /etc/ssh/ssh_host_ed25519_key

# Certificate-based authentication
TrustedUserCAKeys /etc/ssh/ca.pub
AuthorizedPrincipalsFile /etc/ssh/principals
PubkeyAuthentication yes

# Disable all other auth methods
PasswordAuthentication no
KbdInteractiveAuthentication no

# Disable root login
PermitRootLogin no

# Logging
LogLevel INFO

# Misc hardening
X11Forwarding no
PrintMotd no
AcceptEnv LANG LC_*
"#,
        port = config.port
    )
}

/// Generate an ed25519 CA keypair for the built-in (non-Vault) path.
///
/// Returns `(private_key_openssh, public_key_openssh)`.
pub fn generate_ca_keypair() -> Result<(String, String)> {
    let mut rng = rand::thread_rng();
    let private_key = PrivateKey::random(&mut rng, Algorithm::Ed25519)
        .context("Failed to generate CA ed25519 keypair")?;

    let private_pem = private_key
        .to_openssh(LineEnding::LF)
        .context("Failed to encode CA private key")?;

    let public_openssh = private_key
        .public_key()
        .to_openssh()
        .context("Failed to encode CA public key")?;

    Ok((private_pem.to_string(), public_openssh))
}

/// Generate an ed25519 host keypair for sshd.
///
/// Returns `(private_key_openssh, public_key_openssh)`.
fn generate_host_keypair() -> Result<(String, String)> {
    let mut rng = rand::thread_rng();
    let private_key = PrivateKey::random(&mut rng, Algorithm::Ed25519)
        .context("Failed to generate host ed25519 keypair")?;

    let private_pem = private_key
        .to_openssh(LineEnding::LF)
        .context("Failed to encode host private key")?;

    let public_openssh = private_key
        .public_key()
        .to_openssh()
        .context("Failed to encode host public key")?;

    Ok((private_pem.to_string(), public_openssh))
}

/// Generate a startup script that creates the user, sets permissions, and starts sshd.
fn generate_start_sshd_script(config: &SshConfig) -> String {
    format!(
        r#"#!/bin/sh
set -e

# Create the sandbox user if it doesn't exist
if ! id -u {user} >/dev/null 2>&1; then
    adduser -D -h /home/{user} -s /bin/sh {user} 2>/dev/null || \
        useradd -m -d /home/{user} -s /bin/sh {user} 2>/dev/null || true
fi

# Unlock the account for SSH cert auth.
# adduser -D creates a locked account (shadow password '!').
# OpenSSH without PAM rejects locked accounts even for cert/pubkey auth.
passwd -u {user} 2>/dev/null || \
    sed -i 's/^{user}:!/{user}:/' /etc/shadow 2>/dev/null || true

# Set up .ssh directory and clean login profile
mkdir -p /home/{user}/.ssh
chmod 700 /home/{user}/.ssh
touch /home/{user}/.hushlogin
cat > /home/{user}/.profile << 'PROFILE'
export PS1="agentkernel:$(basename "$PWD")\$ "
PROFILE
chown -R {user}:{user} /home/{user} 2>/dev/null || \
    chown -R {user} /home/{user}

# Fix ownership and permissions on sshd files
# (docker cp preserves host UID; sshd StrictModes requires root ownership)
chown root:root /etc/ssh/sshd_config /etc/ssh/ssh_host_ed25519_key \
    /etc/ssh/ssh_host_ed25519_key.pub /etc/ssh/ca.pub /etc/ssh/principals
chmod 600 /etc/ssh/ssh_host_ed25519_key
chmod 644 /etc/ssh/ssh_host_ed25519_key.pub
chmod 644 /etc/ssh/ca.pub
chmod 644 /etc/ssh/principals
chmod 644 /etc/ssh/sshd_config

# Generate host keys if sshd expects them (some distros require all types)
ssh-keygen -A 2>/dev/null || true

# Create privilege separation directory
mkdir -p /run/sshd 2>/dev/null || mkdir -p /var/run/sshd 2>/dev/null || true

# Start sshd in the background
/usr/sbin/sshd -f /etc/ssh/sshd_config -D &
echo "sshd started on port {port}"
"#,
        user = config.user,
        port = config.port,
    )
}

/// Build the list of files to inject into the sandbox for SSH support.
///
/// Includes sshd_config, CA public key, principals, host keypair, and startup script.
pub fn sshd_file_injections(
    ca_public_key: &str,
    ssh_config: &SshConfig,
) -> Result<Vec<FileInjection>> {
    let sshd_config_content = generate_sshd_config(ssh_config);
    let (host_private, host_public) = generate_host_keypair()?;
    let start_script = generate_start_sshd_script(ssh_config);

    let mut files = vec![
        FileInjection {
            content: sshd_config_content.into_bytes(),
            dest: "/etc/ssh/sshd_config".to_string(),
        },
        FileInjection {
            content: ca_public_key.as_bytes().to_vec(),
            dest: "/etc/ssh/ca.pub".to_string(),
        },
        FileInjection {
            content: format!("{}\n", ssh_config.user).into_bytes(),
            dest: "/etc/ssh/principals".to_string(),
        },
        FileInjection {
            content: host_private.into_bytes(),
            dest: "/etc/ssh/ssh_host_ed25519_key".to_string(),
        },
        FileInjection {
            content: host_public.into_bytes(),
            dest: "/etc/ssh/ssh_host_ed25519_key.pub".to_string(),
        },
        FileInjection {
            content: start_script.into_bytes(),
            dest: "/tmp/start-sshd.sh".to_string(),
        },
    ];

    // Placeholder for user .ssh directory — the startup script handles creation
    files.push(FileInjection {
        content: Vec::new(),
        dest: format!("/home/{}/.ssh/.keep", ssh_config.user),
    });

    Ok(files)
}

/// Sign a client public key with a local CA private key.
///
/// Returns the signed certificate in OpenSSH format.
pub fn sign_client_key_local(
    ca_private_key: &str,
    client_public_key: &str,
    principals: &[&str],
    ttl_secs: u64,
) -> Result<String> {
    let ca_key =
        PrivateKey::from_openssh(ca_private_key).context("Failed to parse CA private key")?;

    let client_pubkey = ssh_key::PublicKey::from_openssh(client_public_key)
        .context("Failed to parse client public key")?;

    let mut rng = rand::thread_rng();

    let valid_after = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .context("System time before UNIX epoch")?
        .as_secs();
    let valid_before = valid_after + ttl_secs;

    let mut builder = certificate::Builder::new_with_random_nonce(
        &mut rng,
        client_pubkey.key_data().clone(),
        valid_after,
        valid_before,
    )
    .context("Failed to create certificate builder")?;

    builder
        .cert_type(certificate::CertType::User)
        .context("Failed to set cert type")?;

    builder
        .key_id("agentkernel-client")
        .context("Failed to set key id")?;

    for principal in principals {
        builder
            .valid_principal(principal.to_string())
            .context("Failed to add principal")?;
    }

    // Add standard extensions (ssh-keygen includes these by default).
    // Without permit-pty, sshd rejects PTY allocation requests.
    for ext in &[
        "permit-X11-forwarding",
        "permit-agent-forwarding",
        "permit-port-forwarding",
        "permit-pty",
        "permit-user-rc",
    ] {
        builder
            .extension(*ext, "")
            .context("Failed to add extension")?;
    }

    let cert = builder
        .sign(&ca_key)
        .context("Failed to sign client certificate")?;

    cert.to_openssh().context("Failed to encode certificate")
}

/// Generate an ephemeral ed25519 client keypair.
///
/// Returns `(private_key_openssh, public_key_openssh)`.
pub fn generate_client_keypair() -> Result<(String, String)> {
    let mut rng = rand::thread_rng();
    let private_key = PrivateKey::random(&mut rng, Algorithm::Ed25519)
        .context("Failed to generate client ed25519 keypair")?;

    let private_pem = private_key
        .to_openssh(LineEnding::LF)
        .context("Failed to encode client private key")?;

    let public_openssh = private_key
        .public_key()
        .to_openssh()
        .context("Failed to encode client public key")?;

    Ok((private_pem.to_string(), public_openssh))
}

/// Parse a TTL string (e.g. "30m", "1h", "5m", "2h30m") to seconds.
///
/// Supports:
/// - `Ns` — seconds
/// - `Nm` — minutes
/// - `Nh` — hours
/// - plain integer — treated as seconds
pub fn parse_ttl_to_secs(ttl: &str) -> Result<u64> {
    let ttl = ttl.trim();
    if ttl.is_empty() {
        bail!("TTL string is empty");
    }

    // Plain integer = seconds
    if let Ok(secs) = ttl.parse::<u64>() {
        return Ok(secs);
    }

    let mut total: u64 = 0;
    let mut current_num = String::new();

    for ch in ttl.chars() {
        if ch.is_ascii_digit() {
            current_num.push(ch);
        } else {
            if current_num.is_empty() {
                bail!("Invalid TTL format: unexpected '{}' in \"{}\"", ch, ttl);
            }
            let n: u64 = current_num
                .parse()
                .context("Invalid number in TTL string")?;
            current_num.clear();
            match ch {
                's' => total += n,
                'm' => total += n * 60,
                'h' => total += n * 3600,
                _ => bail!("Unknown TTL unit '{}' in \"{}\"", ch, ttl),
            }
        }
    }

    // If there are trailing digits with no unit, reject (ambiguous)
    if !current_num.is_empty() {
        bail!(
            "Invalid TTL format: trailing digits without unit in \"{}\"",
            ttl
        );
    }

    if total == 0 {
        bail!("TTL resolves to 0 seconds: \"{}\"", ttl);
    }

    Ok(total)
}

/// Convenience wrapper that routes to Vault or local signing based on config.
///
/// If `ssh_config.vault_addr` is set, delegates to `sign_client_key_vault`
/// (requires an async runtime and the enterprise/nomad feature).
/// Otherwise, uses `sign_client_key_local` with the provided `ca_private_key`.
pub fn sign_client_key(
    ssh_config: &SshConfig,
    ca_private_key: Option<&str>,
    client_public_key: &str,
    principals: &[&str],
    ttl_secs: u64,
) -> Result<String> {
    if ssh_config.vault_addr.is_some() {
        // Vault path — we can't call async from a sync function directly.
        // Callers that need Vault signing should use sign_client_key_vault() directly
        // in an async context. For now, we bail to indicate the intent.
        bail!(
            "Vault SSH signing requires calling sign_client_key_vault() \
             in an async context. Set vault_addr=None to use local CA signing."
        );
    }

    let ca_key = ca_private_key.ok_or_else(|| {
        anyhow::anyhow!("Local CA signing requires a CA private key (ca_private_key is None)")
    })?;

    sign_client_key_local(ca_key, client_public_key, principals, ttl_secs)
}

/// Fetch the CA public key from Vault's SSH secrets engine.
///
/// Makes a GET request to `{vault_addr}/v1/{mount}/config/ca`.
/// This is needed so that Vault-signed certificates can be verified by
/// sshd inside sandboxes (inject the returned public key as `ca.pub`).
#[cfg(any(feature = "enterprise", feature = "nomad"))]
#[allow(dead_code)]
pub async fn get_vault_ca_public_key(
    vault_addr: &str,
    vault_token: &str,
    ssh_config: &SshConfig,
) -> Result<String> {
    let url = format!(
        "{}/v1/{}/config/ca",
        vault_addr.trim_end_matches('/'),
        ssh_config.vault_ssh_mount,
    );

    let client = reqwest::Client::new();
    let resp = client
        .get(&url)
        .header("X-Vault-Token", vault_token)
        .send()
        .await
        .context("Failed to contact Vault for CA public key")?;

    if !resp.status().is_success() {
        let status = resp.status();
        let text = resp.text().await.unwrap_or_default();
        bail!("Vault CA public key fetch failed ({}): {}", status, text);
    }

    let result: serde_json::Value = resp
        .json()
        .await
        .context("Failed to parse Vault CA response")?;

    let public_key = result["data"]["public_key"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Vault response missing data.public_key"))?;

    Ok(public_key.to_string())
}

/// Sign a client public key via Vault SSH secrets engine.
///
/// Makes an HTTP POST to `{vault_addr}/v1/{mount}/sign/{role}`.
/// Requires `VAULT_TOKEN` environment variable or explicit token.
#[allow(dead_code)]
pub async fn sign_client_key_vault(
    vault_addr: &str,
    vault_token: &str,
    ssh_config: &SshConfig,
    client_public_key: &str,
) -> Result<String> {
    // Vault SSH sign endpoint
    let url = format!(
        "{}/v1/{}/sign/{}",
        vault_addr.trim_end_matches('/'),
        ssh_config.vault_ssh_mount,
        ssh_config.vault_ssh_role
    );

    // Build the request body
    let body = serde_json::json!({
        "public_key": client_public_key,
        "valid_principals": ssh_config.user,
        "ttl": ssh_config.cert_ttl,
        "cert_type": "user",
    });

    // Use reqwest if available (behind enterprise/nomad feature), otherwise use hyper
    #[cfg(any(feature = "enterprise", feature = "nomad"))]
    {
        let client = reqwest::Client::new();
        let resp = client
            .post(&url)
            .header("X-Vault-Token", vault_token)
            .json(&body)
            .send()
            .await
            .context("Failed to contact Vault")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let text = resp.text().await.unwrap_or_default();
            bail!("Vault SSH sign failed ({}): {}", status, text);
        }

        let result: serde_json::Value = resp
            .json()
            .await
            .context("Failed to parse Vault response")?;

        let signed_key = result["data"]["signed_key"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Vault response missing signed_key"))?;

        Ok(signed_key.to_string())
    }

    #[cfg(not(any(feature = "enterprise", feature = "nomad")))]
    {
        let _ = (url, body, vault_token);
        bail!(
            "Vault SSH signing requires the 'enterprise' or 'nomad' feature \
             (for reqwest HTTP client). Rebuild with --features enterprise"
        )
    }
}

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

    #[test]
    fn test_ssh_config_defaults() {
        let config = SshConfig::default();
        assert!(!config.enabled);
        assert_eq!(config.port, 22);
        assert!(config.host_port.is_none());
        assert!(config.vault_addr.is_none());
        assert_eq!(config.vault_ssh_mount, "ssh");
        assert_eq!(config.vault_ssh_role, "agentkernel-client");
        assert_eq!(config.cert_ttl, "30m");
        assert_eq!(config.user, "sandbox");
    }

    #[test]
    fn test_generate_sshd_config_contains_directives() {
        let config = SshConfig::default();
        let sshd_config = generate_sshd_config(&config);

        assert!(sshd_config.contains("Port 22"));
        assert!(sshd_config.contains("TrustedUserCAKeys /etc/ssh/ca.pub"));
        assert!(sshd_config.contains("PasswordAuthentication no"));
        assert!(sshd_config.contains("PermitRootLogin no"));
        assert!(sshd_config.contains("AuthorizedPrincipalsFile /etc/ssh/principals"));
        assert!(sshd_config.contains("PubkeyAuthentication yes"));
        assert!(sshd_config.contains("HostKey /etc/ssh/ssh_host_ed25519_key"));
    }

    #[test]
    fn test_generate_sshd_config_custom_port() {
        let config = SshConfig {
            port: 2222,
            ..SshConfig::default()
        };
        let sshd_config = generate_sshd_config(&config);
        assert!(sshd_config.contains("Port 2222"));
        assert!(!sshd_config.contains("Port 22\n"));
    }

    #[test]
    fn test_generate_ca_keypair() {
        let (private_key, public_key) = generate_ca_keypair().unwrap();

        // Private key should be in OpenSSH PEM format
        assert!(private_key.contains("BEGIN OPENSSH PRIVATE KEY"));
        assert!(private_key.contains("END OPENSSH PRIVATE KEY"));

        // Public key should start with ssh-ed25519
        assert!(public_key.starts_with("ssh-ed25519 "));
    }

    #[test]
    fn test_sshd_file_injections_returns_correct_files() {
        let config = SshConfig::default();
        let (_, ca_pub) = generate_ca_keypair().unwrap();
        let files = sshd_file_injections(&ca_pub, &config).unwrap();

        let dests: Vec<&str> = files.iter().map(|f| f.dest.as_str()).collect();

        assert!(dests.contains(&"/etc/ssh/sshd_config"));
        assert!(dests.contains(&"/etc/ssh/ca.pub"));
        assert!(dests.contains(&"/etc/ssh/principals"));
        assert!(dests.contains(&"/etc/ssh/ssh_host_ed25519_key"));
        assert!(dests.contains(&"/etc/ssh/ssh_host_ed25519_key.pub"));
        assert!(dests.contains(&"/tmp/start-sshd.sh"));
        assert!(dests.contains(&"/home/sandbox/.ssh/.keep"));
    }

    #[test]
    fn test_sshd_file_injections_principals_content() {
        let config = SshConfig {
            user: "testuser".to_string(),
            ..SshConfig::default()
        };
        let (_, ca_pub) = generate_ca_keypair().unwrap();
        let files = sshd_file_injections(&ca_pub, &config).unwrap();

        let principals = files
            .iter()
            .find(|f| f.dest == "/etc/ssh/principals")
            .unwrap();
        assert_eq!(String::from_utf8_lossy(&principals.content), "testuser\n");
    }

    #[test]
    fn test_sshd_file_injections_custom_user_path() {
        let config = SshConfig {
            user: "agent".to_string(),
            ..SshConfig::default()
        };
        let (_, ca_pub) = generate_ca_keypair().unwrap();
        let files = sshd_file_injections(&ca_pub, &config).unwrap();

        let dests: Vec<&str> = files.iter().map(|f| f.dest.as_str()).collect();
        assert!(dests.contains(&"/home/agent/.ssh/.keep"));
    }

    #[test]
    fn test_sign_client_key_local() {
        let (ca_priv, _ca_pub) = generate_ca_keypair().unwrap();

        // Generate a client keypair
        let mut rng = rand::thread_rng();
        let client_key = PrivateKey::random(&mut rng, Algorithm::Ed25519).unwrap();
        let client_pub = client_key.public_key().to_openssh().unwrap();

        let cert = sign_client_key_local(
            &ca_priv,
            &client_pub,
            &["sandbox"],
            1800, // 30 minutes
        )
        .unwrap();

        // Certificate should be parseable and in OpenSSH format
        assert!(cert.contains("ssh-ed25519-cert-v01@openssh.com"));

        // Verify the cert includes permit-pty and other standard extensions
        let parsed = ssh_key::Certificate::from_openssh(&cert).unwrap();
        let extensions = parsed.extensions();
        assert!(
            extensions.get("permit-pty").is_some(),
            "Certificate must include permit-pty extension for PTY allocation"
        );
        assert!(extensions.get("permit-port-forwarding").is_some());
        assert!(extensions.get("permit-agent-forwarding").is_some());
    }

    #[test]
    fn test_start_sshd_script_content() {
        let config = SshConfig {
            user: "myuser".to_string(),
            port: 2222,
            ..SshConfig::default()
        };
        let script = generate_start_sshd_script(&config);

        assert!(script.contains("#!/bin/sh"));
        assert!(script.contains("myuser"));
        assert!(script.contains("port 2222"));
        assert!(script.contains("chmod 600 /etc/ssh/ssh_host_ed25519_key"));
        assert!(script.contains("/usr/sbin/sshd"));
    }

    #[test]
    fn test_generate_host_keypair() {
        let (private_key, public_key) = generate_host_keypair().unwrap();
        assert!(private_key.contains("BEGIN OPENSSH PRIVATE KEY"));
        assert!(public_key.starts_with("ssh-ed25519 "));
    }

    #[test]
    fn test_generate_client_keypair() {
        let (private_key, public_key) = generate_client_keypair().unwrap();

        // Private key should be in OpenSSH PEM format
        assert!(private_key.contains("BEGIN OPENSSH PRIVATE KEY"));
        assert!(private_key.contains("END OPENSSH PRIVATE KEY"));

        // Public key should start with ssh-ed25519
        assert!(public_key.starts_with("ssh-ed25519 "));
    }

    #[test]
    fn test_generate_client_keypair_is_unique() {
        let (priv1, pub1) = generate_client_keypair().unwrap();
        let (priv2, pub2) = generate_client_keypair().unwrap();
        // Each call should produce a different keypair
        assert_ne!(priv1, priv2);
        assert_ne!(pub1, pub2);
    }

    #[test]
    fn test_parse_ttl_to_secs_minutes() {
        assert_eq!(parse_ttl_to_secs("30m").unwrap(), 1800);
        assert_eq!(parse_ttl_to_secs("5m").unwrap(), 300);
        assert_eq!(parse_ttl_to_secs("1m").unwrap(), 60);
    }

    #[test]
    fn test_parse_ttl_to_secs_hours() {
        assert_eq!(parse_ttl_to_secs("1h").unwrap(), 3600);
        assert_eq!(parse_ttl_to_secs("2h").unwrap(), 7200);
    }

    #[test]
    fn test_parse_ttl_to_secs_seconds() {
        assert_eq!(parse_ttl_to_secs("90s").unwrap(), 90);
        assert_eq!(parse_ttl_to_secs("1s").unwrap(), 1);
    }

    #[test]
    fn test_parse_ttl_to_secs_combined() {
        assert_eq!(parse_ttl_to_secs("1h30m").unwrap(), 5400);
        assert_eq!(parse_ttl_to_secs("2h15m30s").unwrap(), 8130);
    }

    #[test]
    fn test_parse_ttl_to_secs_plain_integer() {
        assert_eq!(parse_ttl_to_secs("3600").unwrap(), 3600);
        assert_eq!(parse_ttl_to_secs("0").unwrap(), 0);
    }

    #[test]
    fn test_parse_ttl_to_secs_invalid() {
        assert!(parse_ttl_to_secs("").is_err());
        assert!(parse_ttl_to_secs("abc").is_err());
        assert!(parse_ttl_to_secs("30x").is_err());
        assert!(parse_ttl_to_secs("m30").is_err());
    }

    #[test]
    fn test_parse_ttl_to_secs_trailing_digits_rejected() {
        // "30m15" has trailing digits without a unit — ambiguous
        assert!(parse_ttl_to_secs("30m15").is_err());
    }

    #[test]
    fn test_sign_client_key_local_routing() {
        let (ca_priv, _) = generate_ca_keypair().unwrap();
        let (_, client_pub) = generate_client_keypair().unwrap();

        let config = SshConfig::default();

        // Local signing should work
        let cert =
            sign_client_key(&config, Some(&ca_priv), &client_pub, &["sandbox"], 1800).unwrap();
        assert!(cert.contains("ssh-ed25519-cert-v01@openssh.com"));
    }

    #[test]
    fn test_sign_client_key_vault_routing_errors() {
        let (_, client_pub) = generate_client_keypair().unwrap();

        // With vault_addr set, sign_client_key should bail (no async context)
        let config = SshConfig {
            vault_addr: Some("https://vault.example.com".to_string()),
            ..SshConfig::default()
        };
        assert!(sign_client_key(&config, None, &client_pub, &["sandbox"], 1800).is_err());
    }

    #[test]
    fn test_sign_client_key_no_ca_key_errors() {
        let (_, client_pub) = generate_client_keypair().unwrap();
        let config = SshConfig::default();

        // No CA key provided for local signing should error
        assert!(sign_client_key(&config, None, &client_pub, &["sandbox"], 1800).is_err());
    }

    #[test]
    fn test_sign_client_key_with_generated_keypair() {
        // End-to-end: generate CA, generate client, sign, verify format
        let (ca_priv, _ca_pub) = generate_ca_keypair().unwrap();
        let (_, client_pub) = generate_client_keypair().unwrap();

        let cert =
            sign_client_key_local(&ca_priv, &client_pub, &["sandbox", "agent"], 600).unwrap();
        assert!(cert.contains("ssh-ed25519-cert-v01@openssh.com"));
    }
}