1use std::{collections::HashSet, future::Future, pin::Pin, sync::Arc};
2
3use async_channel::{Receiver, Sender};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7#[derive(Debug)]
9pub enum ContainerExecOutcome {
10 Completed(std::process::Output),
12 Killed,
14}
15
16pub trait ContainerExec: Send + Sync {
22 fn exec(
29 &self,
30 container_id: &str,
31 script: &str,
32 working_dir: &str,
33 kill_rx: Receiver<()>,
34 stdin_rx: Receiver<Vec<u8>>,
35 stdin_blocked_notice: Option<Sender<String>>,
36 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send;
37}
38
39pub trait ContainerExecObject: Send + Sync {
41 fn exec_boxed<'a>(
43 &'a self,
44 container_id: &'a str,
45 script: &'a str,
46 working_dir: &'a str,
47 kill_rx: Receiver<()>,
48 stdin_rx: Receiver<Vec<u8>>,
49 stdin_blocked_notice: Option<Sender<String>>,
50 ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>>;
51}
52
53#[derive(Clone)]
59pub struct ContainerExecHandle {
60 inner: Arc<dyn ContainerExecObject>,
61}
62
63impl std::fmt::Debug for ContainerExecHandle {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 f.debug_struct("ContainerExecHandle")
66 .finish_non_exhaustive()
67 }
68}
69
70impl ContainerExecHandle {
71 #[must_use]
73 pub fn new<T>(inner: Arc<T>) -> Self
74 where
75 T: ContainerExec + 'static,
76 {
77 Self { inner }
78 }
79}
80
81impl ContainerExec for ContainerExecHandle {
82 fn exec(
83 &self,
84 container_id: &str,
85 script: &str,
86 working_dir: &str,
87 kill_rx: Receiver<()>,
88 stdin_rx: Receiver<Vec<u8>>,
89 stdin_blocked_notice: Option<Sender<String>>,
90 ) -> impl Future<Output = Result<ContainerExecOutcome, String>> + Send {
91 let inner = Arc::clone(&self.inner);
92 let container_id = container_id.to_string();
93 let script = script.to_string();
94 let working_dir = working_dir.to_string();
95
96 async move {
97 inner
98 .exec_boxed(
99 &container_id,
100 &script,
101 &working_dir,
102 kill_rx,
103 stdin_rx,
104 stdin_blocked_notice,
105 )
106 .await
107 }
108 }
109}
110
111#[derive(Clone)]
113pub struct ContainerShellRuntime {
114 exec: Arc<dyn ContainerExecObject>,
115 container_id: String,
116 ipc_host: String,
117}
118
119impl std::fmt::Debug for ContainerShellRuntime {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 f.debug_struct("ContainerShellRuntime")
122 .field("container_id", &self.container_id)
123 .field("ipc_host", &self.ipc_host)
124 .finish_non_exhaustive()
125 }
126}
127
128impl ContainerShellRuntime {
129 #[must_use]
134 pub fn new(
135 container_id: impl Into<String>,
136 ipc_host: impl Into<String>,
137 exec: ContainerExecHandle,
138 ) -> Self {
139 let container_id = container_id.into();
140 let ipc_host = ipc_host.into();
141 assert!(
142 !container_id.trim().is_empty(),
143 "container runtime requires a non-empty container_id"
144 );
145 assert!(
146 !ipc_host.trim().is_empty(),
147 "container runtime requires a non-empty ipc_host"
148 );
149 Self {
150 exec: exec.inner,
151 container_id,
152 ipc_host,
153 }
154 }
155
156 #[must_use]
157 pub fn container_id(&self) -> &str {
159 &self.container_id
160 }
161
162 #[must_use]
163 pub fn ipc_host(&self) -> &str {
165 &self.ipc_host
166 }
167
168 pub(crate) fn exec(&self) -> Arc<dyn ContainerExecObject> {
169 Arc::clone(&self.exec)
170 }
171}
172
173impl<T: ContainerExec> ContainerExecObject for T {
174 fn exec_boxed<'a>(
175 &'a self,
176 container_id: &'a str,
177 script: &'a str,
178 working_dir: &'a str,
179 kill_rx: Receiver<()>,
180 stdin_rx: Receiver<Vec<u8>>,
181 stdin_blocked_notice: Option<Sender<String>>,
182 ) -> Pin<Box<dyn Future<Output = Result<ContainerExecOutcome, String>> + Send + 'a>> {
183 Box::pin(self.exec(
184 container_id,
185 script,
186 working_dir,
187 kill_rx,
188 stdin_rx,
189 stdin_blocked_notice,
190 ))
191 }
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
196#[serde(rename_all = "lowercase")]
197pub enum ShellBackend {
198 Local,
200 Container,
202 Ssh,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
208pub struct SshServer {
209 pub name: String,
211 pub target: String,
213}
214
215impl SshServer {
216 #[must_use]
218 pub fn id(&self) -> &str {
219 &self.name
220 }
221}
222
223#[derive(Debug, Clone)]
225pub enum SshRuntimeProfile {
226 Heel {
228 binary: String,
230 },
231}
232
233#[derive(Debug, Clone, Serialize)]
237pub struct ShellRuntimeAvailability {
238 pub local: bool,
240 pub container: bool,
242 pub ssh: bool,
244}
245
246impl Default for ShellRuntimeAvailability {
247 fn default() -> Self {
248 Self {
249 local: true,
250 container: false,
251 ssh: false,
252 }
253 }
254}
255
256pub trait SshSessionAuthorizer: Send + Sync {
261 fn authorize_connect(
263 &self,
264 target: &str,
265 ) -> Pin<Box<dyn Future<Output = Result<bool, String>> + Send + '_>>;
266
267 fn authorize_heel_install(
271 &self,
272 target: &str,
273 details: &str,
274 ) -> Pin<Box<dyn Future<Output = Result<bool, String>> + Send + '_>>;
275}
276
277#[derive(Clone)]
282pub struct ShellSessionRegistry {
283 availability: ShellRuntimeAvailability,
284 ssh_servers: Vec<SshServer>,
285 ssh_authorizer: Option<Arc<dyn SshSessionAuthorizer>>,
286 container_runtime: Option<ContainerShellRuntime>,
287}
288
289impl std::fmt::Debug for ShellSessionRegistry {
290 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
291 f.debug_struct("ShellSessionRegistry")
292 .finish_non_exhaustive()
293 }
294}
295
296impl ShellSessionRegistry {
297 #[must_use]
299 pub fn new(availability: ShellRuntimeAvailability) -> Self {
300 Self {
301 availability,
302 ssh_servers: Vec::new(),
303 ssh_authorizer: None,
304 container_runtime: None,
305 }
306 }
307
308 #[must_use]
310 pub const fn with_availability(mut self, availability: ShellRuntimeAvailability) -> Self {
311 self.availability = availability;
312 self
313 }
314
315 #[must_use]
317 pub fn with_ssh_authorizer(mut self, authorizer: Arc<dyn SshSessionAuthorizer>) -> Self {
318 self.ssh_authorizer = Some(authorizer);
319 self
320 }
321
322 #[must_use]
324 pub fn with_container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
325 self.container_runtime = Some(runtime);
326 self
327 }
328
329 #[must_use]
330 pub fn availability(&self) -> ShellRuntimeAvailability {
332 self.availability.clone()
333 }
334
335 pub fn with_ssh_servers(mut self, servers: Vec<SshServer>) -> Result<Self, String> {
340 let mut seen = HashSet::new();
341 let mut deduped = Vec::new();
342 for server in servers {
343 let id = server.id().trim().to_string();
344 let target = server.target.trim().to_string();
345 if id.is_empty() || target.is_empty() {
346 return Err("ssh server entries require non-empty name and target".to_string());
347 }
348 if !seen.insert(id.clone()) {
349 return Err(format!("duplicate ssh server id: {id}"));
350 }
351 deduped.push(SshServer { name: id, target });
352 }
353
354 self.ssh_servers = deduped;
355 Ok(self)
356 }
357
358 #[must_use]
360 pub fn list_ssh_servers(&self) -> Vec<SshServer> {
362 self.ssh_servers.clone()
363 }
364
365 pub(crate) const fn container_runtime(&self) -> Option<&ContainerShellRuntime> {
366 self.container_runtime.as_ref()
367 }
368
369 pub fn default_ssh_server(&self) -> Result<SshServer, String> {
374 match self.ssh_servers.as_slice() {
375 [] => Err("no ssh servers are configured".to_string()),
376 [server] => Ok(server.clone()),
377 _ => Err(
378 "ssh_server_id is required because multiple ssh servers are configured".to_string(),
379 ),
380 }
381 }
382
383 pub fn resolve_ssh_server(&self, server_id: &str) -> Result<SshServer, String> {
390 let wanted = server_id.trim();
391 if wanted.is_empty() {
392 return Err("ssh_server_id is required for ssh mode".to_string());
393 }
394 self.ssh_servers
395 .iter()
396 .find(|s| s.id() == wanted)
397 .cloned()
398 .ok_or_else(|| format!("unknown ssh_server_id: {wanted}"))
399 }
400
401 pub fn resolve_local_backend(&self) -> Result<ShellBackend, String> {
410 let availability = self.availability();
411 if availability.container {
412 return Ok(ShellBackend::Container);
413 }
414 if availability.local {
415 return Ok(ShellBackend::Local);
416 }
417 Err("no local backend available".to_string())
418 }
419
420 pub fn ensure_ssh_available(&self) -> Result<(), String> {
426 if self.availability().ssh {
427 Ok(())
428 } else {
429 Err("ssh backend is not available".to_string())
430 }
431 }
432
433 #[must_use]
434 pub fn ssh_authorizer(&self) -> Option<Arc<dyn SshSessionAuthorizer>> {
436 self.ssh_authorizer.clone()
437 }
438}
439
440pub async fn bootstrap_ssh_runtime(
451 target: &str,
452 authorizer: &Option<Arc<dyn SshSessionAuthorizer>>,
453) -> Result<SshRuntimeProfile, anyhow::Error> {
454 if let Some(auth) = authorizer {
455 let allowed = auth
456 .authorize_connect(target)
457 .await
458 .map_err(anyhow::Error::msg)?;
459 if !allowed {
460 return Err(anyhow::anyhow!("user denied ssh connection authorization"));
461 }
462 }
463
464 let remote = detect_remote(target).await?;
465 if remote.heel_found {
466 return Ok(SshRuntimeProfile::Heel {
467 binary: remote.heel_path,
468 });
469 }
470
471 if let Some(auth) = authorizer {
472 let details = format!(
473 "Remote {} ({}) does not have heel installed.",
474 remote.os, remote.arch
475 );
476 let approve_install = auth
477 .authorize_heel_install(target, &details)
478 .await
479 .map_err(anyhow::Error::msg)?;
480 if approve_install && install_heel(target, &remote).await? {
481 let verified = detect_remote(target).await?;
482 if verified.heel_found {
483 return Ok(SshRuntimeProfile::Heel {
484 binary: verified.heel_path,
485 });
486 }
487 }
488 }
489
490 Err(anyhow::anyhow!(
491 "remote heel runtime unavailable; ssh mode requires heel on the remote host"
492 ))
493}
494
495struct RemoteInfo {
496 os: String,
497 arch: String,
498 heel_found: bool,
499 heel_path: String,
500}
501
502async fn detect_remote(target: &str) -> Result<RemoteInfo, anyhow::Error> {
503 let probe = "uname -s; uname -m; if command -v heel >/dev/null 2>&1; then command -v heel; elif [ -x \"$HOME/.local/bin/heel\" ]; then printf '%s\\n' \"$HOME/.local/bin/heel\"; else echo __NO_HEEL__; fi";
504 let output = async_process::Command::new("ssh")
505 .arg("-o")
506 .arg("BatchMode=yes")
507 .arg("-o")
508 .arg("ConnectTimeout=10")
509 .arg(target)
510 .arg(probe)
511 .stdin(async_process::Stdio::null())
512 .output()
513 .await
514 .map_err(|e| anyhow::anyhow!("ssh probe failed: {e}"))?;
515
516 if !output.status.success() {
517 return Err(anyhow::anyhow!(
518 "ssh probe failed: {}",
519 String::from_utf8_lossy(&output.stderr)
520 ));
521 }
522
523 parse_remote_probe_output(&output.stdout)
524}
525
526fn parse_remote_probe_output(stdout: &[u8]) -> Result<RemoteInfo, anyhow::Error> {
527 let lines = String::from_utf8_lossy(stdout)
528 .lines()
529 .map(|s| s.trim().to_string())
530 .collect::<Vec<_>>();
531 if lines.len() < 3 {
532 return Err(anyhow::anyhow!("ssh probe returned unexpected output"));
533 }
534
535 let heel_line = lines[2].clone();
536 let heel_found = heel_line != "__NO_HEEL__";
537 if !heel_found {
538 return Ok(RemoteInfo {
539 os: lines[0].clone(),
540 arch: lines[1].clone(),
541 heel_found,
542 heel_path: String::new(),
543 });
544 }
545
546 Ok(RemoteInfo {
547 os: lines[0].clone(),
548 arch: lines[1].clone(),
549 heel_found,
550 heel_path: heel_line,
551 })
552}
553
554async fn install_heel(target: &str, remote: &RemoteInfo) -> Result<bool, anyhow::Error> {
555 let local_os = std::env::consts::OS;
556 let remote_os = remote.os.to_lowercase();
557 let os_match = (local_os == "macos" && remote_os.contains("darwin"))
558 || (local_os == "linux" && remote_os.contains("linux"));
559 if !os_match {
560 return Ok(false);
561 }
562
563 let local_arch = std::env::consts::ARCH;
564 if normalize_arch(local_arch) != normalize_arch(&remote.arch) {
565 return Ok(false);
566 }
567
568 let local_heel = find_local_heel().await?;
569 if local_heel.is_empty() {
570 return Ok(false);
571 }
572
573 let mkdir_status = async_process::Command::new("ssh")
574 .arg("-o")
575 .arg("BatchMode=yes")
576 .arg("-o")
577 .arg("ConnectTimeout=10")
578 .arg(target)
579 .arg("mkdir -p ~/.local/bin")
580 .stdin(async_process::Stdio::null())
581 .status()
582 .await
583 .map_err(|e| anyhow::anyhow!("ssh mkdir failed: {e}"))?;
584 if !mkdir_status.success() {
585 return Ok(false);
586 }
587
588 let dest = format!("{target}:~/.local/bin/heel");
589 let scp_status = async_process::Command::new("scp")
590 .arg("-o")
591 .arg("BatchMode=yes")
592 .arg("-o")
593 .arg("ConnectTimeout=10")
594 .arg(&local_heel)
595 .arg(&dest)
596 .stdin(async_process::Stdio::null())
597 .status()
598 .await
599 .map_err(|e| anyhow::anyhow!("scp heel failed: {e}"))?;
600 if !scp_status.success() {
601 return Ok(false);
602 }
603
604 let verify_status = async_process::Command::new("ssh")
605 .arg("-o")
606 .arg("BatchMode=yes")
607 .arg("-o")
608 .arg("ConnectTimeout=10")
609 .arg(target)
610 .arg("chmod +x ~/.local/bin/heel && ~/.local/bin/heel --version")
611 .stdin(async_process::Stdio::null())
612 .status()
613 .await
614 .map_err(|e| anyhow::anyhow!("verify heel failed: {e}"))?;
615
616 Ok(verify_status.success())
617}
618
619async fn find_local_heel() -> Result<String, anyhow::Error> {
620 let out = async_process::Command::new("sh")
621 .arg("-c")
622 .arg("command -v heel || true")
623 .stdin(async_process::Stdio::null())
624 .output()
625 .await
626 .map_err(|e| anyhow::anyhow!("failed to locate local heel: {e}"))?;
627 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
628}
629
630fn normalize_arch(raw: &str) -> &str {
631 match raw {
632 "x86_64" | "amd64" => "x86_64",
633 "aarch64" | "arm64" => "arm64",
634 other => other,
635 }
636}
637
638#[cfg(test)]
639mod tests {
640 use super::{
641 ShellRuntimeAvailability, ShellSessionRegistry, SshServer, parse_remote_probe_output,
642 };
643
644 #[test]
645 fn parse_remote_probe_detects_local_bin_heel_path() {
646 let stdout = b"Linux\nx86_64\n/home/test/.local/bin/heel\n";
647 let remote = parse_remote_probe_output(stdout).expect("probe output should parse");
648 assert_eq!(remote.os, "Linux");
649 assert_eq!(remote.arch, "x86_64");
650 assert!(remote.heel_found);
651 assert_eq!(remote.heel_path, "/home/test/.local/bin/heel");
652 }
653
654 #[test]
655 fn parse_remote_probe_handles_missing_heel() {
656 let stdout = b"Linux\naarch64\n__NO_HEEL__\n";
657 let remote = parse_remote_probe_output(stdout).expect("probe output should parse");
658 assert!(!remote.heel_found);
659 assert!(remote.heel_path.is_empty());
660 }
661
662 #[test]
663 fn default_ssh_server_uses_single_configured_target() {
664 let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
665 local: false,
666 container: false,
667 ssh: true,
668 })
669 .with_ssh_servers(vec![SshServer {
670 name: "prod".to_string(),
671 target: "root@example.com".to_string(),
672 }])
673 .expect("ssh server should configure");
674
675 let server = registry
676 .default_ssh_server()
677 .expect("single ssh server should become default");
678 assert_eq!(server.id(), "prod");
679 assert_eq!(server.target, "root@example.com");
680 }
681
682 #[test]
683 fn default_ssh_server_requires_disambiguation_when_multiple_exist() {
684 let registry = ShellSessionRegistry::new(ShellRuntimeAvailability {
685 local: false,
686 container: false,
687 ssh: true,
688 })
689 .with_ssh_servers(vec![
690 SshServer {
691 name: "prod".to_string(),
692 target: "root@example.com".to_string(),
693 },
694 SshServer {
695 name: "staging".to_string(),
696 target: "root@staging.example.com".to_string(),
697 },
698 ])
699 .expect("ssh servers should configure");
700
701 let error = registry
702 .default_ssh_server()
703 .expect_err("multiple ssh servers must require explicit selection");
704 assert!(
705 error.contains("ssh_server_id is required"),
706 "unexpected error: {error}"
707 );
708 }
709}