diff --git a/app/src-tauri/build.rs b/app/src-tauri/build.rs index cf8ad8d..7d0c76c 100644 --- a/app/src-tauri/build.rs +++ b/app/src-tauri/build.rs @@ -14,6 +14,8 @@ #[path = "src/command_census.rs"] mod command_census; +#[path = "src/sidecar_placeholder.rs"] +mod sidecar_placeholder; use std::path::Path; @@ -79,6 +81,7 @@ fn main() { } prune_permissions(&commands); + ensure_ssm_sidecar(); // `AppManifest::commands` takes `&'static [&'static str]` and the struct is `Copy`, so // there is no owned form; leaking is fine in a process that exits right after. @@ -206,3 +209,50 @@ fn check_tauri_config() { fail("capabilities declared outside capabilities/", &problems, LAYOUT_HINT); } } + +/// `bundle.externalBin` names `binaries/session-manager-plugin`, and tauri-build stops on a +/// missing `binaries/session-manager-plugin-[.exe]` for every build, tests +/// included. The real one comes from `scripts/fetch-ssm-plugin.sh` (`.ps1` on Windows), which +/// CI runs before `tauri build`. +/// +/// - **Release profile:** the real plugin is required. A missing file or a placeholder stops +/// the build here, so a placeholder can never ship. +/// - **Debug profile** (`cargo test`, `cargo check`, `tauri dev`): a missing file is replaced +/// by a placeholder (`src/sidecar_placeholder.rs`) so no test run needs AWS's S3. The app's +/// `find_plugin` skips a placeholder and falls back to an installed plugin. +fn ensure_ssm_sidecar() { + let target = std::env::var("TARGET").expect("cargo sets TARGET"); + let ext = if target.contains("windows") { ".exe" } else { "" }; + let path = Path::new("binaries").join(format!("session-manager-plugin-{target}{ext}")); + println!("cargo:rerun-if-changed={}", path.display()); + let release = std::env::var("PROFILE").as_deref() == Ok("release"); + let head = std::fs::read(&path).ok().map(|b| sidecar_placeholder::is_placeholder(&b)); + let fetch = if target.contains("windows") { + "scripts\\fetch-ssm-plugin.ps1" + } else { + "scripts/fetch-ssm-plugin.sh" + }; + match (head, release) { + (Some(false), _) => {} + (state, true) => fail( + "the AWS Session Manager plugin sidecar is missing", + &[format!( + "{} is {} (release builds bundle the real plugin)", + path.display(), + if state.is_some() { "a debug-build placeholder" } else { "missing" } + )], + &format!("Run {fetch} {target} from the repository root first."), + ), + (None, false) => { + std::fs::create_dir_all("binaries").expect("create src-tauri/binaries"); + std::fs::write(&path, sidecar_placeholder::contents()) + .unwrap_or_else(|e| panic!("cannot write {}: {e}", path.display())); + println!( + "cargo:warning=no {} - wrote a placeholder (debug only; AWS workspaces use an \ + installed plugin). Run {fetch} to bundle the real one.", + path.display() + ); + } + (Some(true), false) => {} + } +} diff --git a/app/src-tauri/src/host/ssm.rs b/app/src-tauri/src/host/ssm.rs index a76e6d2..521e083 100644 --- a/app/src-tauri/src/host/ssm.rs +++ b/app/src-tauri/src/host/ssm.rs @@ -198,27 +198,48 @@ fn sdk_error(e: &(dyn std::error::Error + 'static)) -> String { // ── The plugin ─────────────────────────────────────────────────────────────── -/// Find `session-manager-plugin`: `TRIPLEC_SSM_PLUGIN` if set, then `PATH`, -/// then where AWS's installers put it (the GUI app on macOS does not get the -/// shell's `PATH`, so the install locations are not optional). +/// The plugin's file name on this platform: what the bundle holds (Tauri strips the +/// `-` suffix of `bundle.externalBin` when it copies the sidecar in) and what +/// AWS's installers put on `PATH`. +const PLUGIN_FILE: &str = + if cfg!(windows) { "session-manager-plugin.exe" } else { "session-manager-plugin" }; + +const PLUGIN_INSTALL_HINT: &str = "The AWS Session Manager plugin (session-manager-plugin) is \ + not installed. It is what connects to a workspace on AWS; install it from \ + https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html"; + +/// Find `session-manager-plugin`, in this order: +/// +/// 1. `TRIPLEC_SSM_PLUGIN`, if set (an error if it names no file — an explicit choice is never +/// silently replaced by another plugin); +/// 2. **the copy bundled with the app** (`bundle.externalBin`), beside the app's own +/// executable: `usr/bin` in the AppImage, `Contents/MacOS` in the macOS bundle, the install +/// directory on Windows (and `target/` under `tauri dev`, where tauri-build copies +/// it). A debug build's placeholder (`sidecar_placeholder`) is skipped; +/// 3. `PATH`; +/// 4. where AWS's installers put it (the GUI app on macOS does not get the shell's `PATH`, so +/// the install locations are not optional). +/// +/// 3 and 4 remain for dev builds without a fetched sidecar. pub fn find_plugin() -> Result { - if let Some(p) = std::env::var_os("TRIPLEC_SSM_PLUGIN").filter(|p| !p.is_empty()) { - let p = PathBuf::from(p); - return if p.is_file() { - Ok(p) - } else { - Err(format!("TRIPLEC_SSM_PLUGIN names {}, which is not a file", p.display())) - }; - } - let name = if cfg!(windows) { "session-manager-plugin.exe" } else { "session-manager-plugin" }; - let on_path = std::env::var_os("PATH") - .map(|paths| std::env::split_paths(&paths).map(|d| d.join(name)).collect::>()) - .unwrap_or_default(); - let installed: Vec = if cfg!(windows) { + let exe_dir = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(Path::to_path_buf)); + resolve_plugin(&PluginSearch { + override_path: std::env::var_os("TRIPLEC_SSM_PLUGIN"), + exe_dir, + path_var: std::env::var_os("PATH"), + install_dirs: plugin_install_dirs(), + }) +} + +/// Where AWS's installers put the plugin, in the order they are tried. +fn plugin_install_dirs() -> Vec { + if cfg!(windows) { ["ProgramFiles", "ProgramFiles(x86)"] .iter() .filter_map(|v| std::env::var_os(v)) - .map(|d| PathBuf::from(d).join(r"Amazon\SessionManagerPlugin\bin").join(name)) + .map(|d| PathBuf::from(d).join(r"Amazon\SessionManagerPlugin\bin")) .collect() } else { [ @@ -228,19 +249,54 @@ pub fn find_plugin() -> Result { "/usr/bin", ] .iter() - .map(|d| Path::new(d).join(name)) + .map(PathBuf::from) .collect() - }; + } +} + +/// Everything [`find_plugin`] reads from the process, so the order is testable. +struct PluginSearch { + override_path: Option, + exe_dir: Option, + path_var: Option, + install_dirs: Vec, +} + +fn resolve_plugin(search: &PluginSearch) -> Result { + if let Some(p) = search.override_path.as_ref().filter(|p| !p.is_empty()) { + let p = PathBuf::from(p); + return if p.is_file() { + Ok(p) + } else { + Err(format!("TRIPLEC_SSM_PLUGIN names {}, which is not a file", p.display())) + }; + } + if let Some(bundled) = search.exe_dir.as_ref().map(|d| d.join(PLUGIN_FILE)) { + if bundled.is_file() && !is_sidecar_placeholder(&bundled) { + return Ok(bundled); + } + } + let on_path = search + .path_var + .as_ref() + .map(|paths| std::env::split_paths(paths).map(|d| d.join(PLUGIN_FILE)).collect::>()) + .unwrap_or_default(); on_path .into_iter() - .chain(installed) + .chain(search.install_dirs.iter().map(|d| d.join(PLUGIN_FILE))) .find(|p| p.is_file()) - .ok_or_else(|| { - "The AWS Session Manager plugin (session-manager-plugin) is not installed. It is \ - what connects to a workspace on AWS; install it from \ - https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html" - .to_string() - }) + .ok_or_else(|| PLUGIN_INSTALL_HINT.to_string()) +} + +/// Whether `path` is the stand-in a debug build bundles when no real plugin was fetched. +/// Unreadable counts as "not a placeholder": the spawn then reports the real error. +fn is_sidecar_placeholder(path: &Path) -> bool { + use std::io::Read; + let mut head = [0u8; crate::sidecar_placeholder::MARKER.len()]; + std::fs::File::open(path) + .and_then(|mut f| f.read_exact(&mut head)) + .map(|()| crate::sidecar_placeholder::is_placeholder(&head)) + .unwrap_or(false) } /// A running plugin process with a listener on the local port. diff --git a/app/src-tauri/src/host/ssm/tests.rs b/app/src-tauri/src/host/ssm/tests.rs index ba1bf7d..b3265e8 100644 --- a/app/src-tauri/src/host/ssm/tests.rs +++ b/app/src-tauri/src/host/ssm/tests.rs @@ -400,3 +400,135 @@ async fn the_keepalive_asks_for_health_without_a_token() { assert!(req.starts_with("GET /v1/health HTTP/1.1\r\n"), "{req}"); assert!(!req.to_ascii_lowercase().contains("authorization"), "{req}"); } + +// ── Finding the plugin ─────────────────────────────────────────────────────── + +mod plugin_resolution { + use super::super::{resolve_plugin, PluginSearch, PLUGIN_FILE, PLUGIN_INSTALL_HINT}; + use std::path::{Path, PathBuf}; + + /// A directory holding a fake plugin (contents are never run). + fn dir_with_plugin(root: &Path, name: &str) -> PathBuf { + let d = root.join(name); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join(PLUGIN_FILE), b"\x7fELF fake plugin").unwrap(); + d + } + + fn search( + override_path: Option<&Path>, + exe_dir: Option<&Path>, + path: &[&Path], + install: &[&Path], + ) -> PluginSearch { + PluginSearch { + override_path: override_path.map(|p| p.as_os_str().to_owned()), + exe_dir: exe_dir.map(Path::to_path_buf), + path_var: Some(std::env::join_paths(path).unwrap()), + install_dirs: install.iter().map(|p| p.to_path_buf()).collect(), + } + } + + #[test] + fn the_override_wins_over_everything() { + let t = tempfile::tempdir().unwrap(); + let chosen = t.path().join("my-plugin"); + std::fs::write(&chosen, b"x").unwrap(); + let bundled = dir_with_plugin(t.path(), "app"); + let on_path = dir_with_plugin(t.path(), "path"); + let s = search(Some(&chosen), Some(&bundled), &[&on_path], &[]); + assert_eq!(resolve_plugin(&s).unwrap(), chosen); + } + + #[test] + fn an_override_naming_no_file_is_an_error_not_a_fallback() { + let t = tempfile::tempdir().unwrap(); + let bundled = dir_with_plugin(t.path(), "app"); + let s = search(Some(&t.path().join("missing")), Some(&bundled), &[], &[]); + let e = resolve_plugin(&s).unwrap_err(); + assert!(e.contains("TRIPLEC_SSM_PLUGIN names"), "{e}"); + } + + #[test] + fn an_empty_override_is_ignored() { + let t = tempfile::tempdir().unwrap(); + let bundled = dir_with_plugin(t.path(), "app"); + let mut s = search(None, Some(&bundled), &[], &[]); + s.override_path = Some(std::ffi::OsString::new()); + assert_eq!(resolve_plugin(&s).unwrap(), bundled.join(PLUGIN_FILE)); + } + + #[test] + fn the_bundled_sidecar_wins_over_path_and_installs() { + let t = tempfile::tempdir().unwrap(); + let bundled = dir_with_plugin(t.path(), "app"); + let on_path = dir_with_plugin(t.path(), "path"); + let installed = dir_with_plugin(t.path(), "installed"); + let s = search(None, Some(&bundled), &[&on_path], &[&installed]); + assert_eq!(resolve_plugin(&s).unwrap(), bundled.join(PLUGIN_FILE)); + } + + #[test] + fn without_a_sidecar_path_comes_before_the_install_locations() { + let t = tempfile::tempdir().unwrap(); + let empty_app = t.path().join("app"); + std::fs::create_dir_all(&empty_app).unwrap(); + let first = t.path().join("path-first-empty"); + std::fs::create_dir_all(&first).unwrap(); + let on_path = dir_with_plugin(t.path(), "path"); + let installed = dir_with_plugin(t.path(), "installed"); + let s = search(None, Some(&empty_app), &[&first, &on_path], &[&installed]); + assert_eq!(resolve_plugin(&s).unwrap(), on_path.join(PLUGIN_FILE)); + + let s = search(None, Some(&empty_app), &[&first], &[&installed]); + assert_eq!(resolve_plugin(&s).unwrap(), installed.join(PLUGIN_FILE)); + } + + #[test] + fn a_debug_placeholder_beside_the_exe_is_skipped() { + let t = tempfile::tempdir().unwrap(); + let app = t.path().join("app"); + std::fs::create_dir_all(&app).unwrap(); + std::fs::write(app.join(PLUGIN_FILE), crate::sidecar_placeholder::contents()).unwrap(); + let on_path = dir_with_plugin(t.path(), "path"); + let s = search(None, Some(&app), &[&on_path], &[]); + assert_eq!(resolve_plugin(&s).unwrap(), on_path.join(PLUGIN_FILE)); + + // And with nothing else installed, the install hint, not the placeholder. + let s = search(None, Some(&app), &[], &[]); + assert_eq!(resolve_plugin(&s).unwrap_err(), PLUGIN_INSTALL_HINT); + } + + #[test] + fn a_directory_named_like_the_plugin_is_not_a_plugin() { + let t = tempfile::tempdir().unwrap(); + let app = t.path().join("app"); + std::fs::create_dir_all(app.join(PLUGIN_FILE)).unwrap(); + let installed = dir_with_plugin(t.path(), "installed"); + let s = search(None, Some(&app), &[], &[&installed]); + assert_eq!(resolve_plugin(&s).unwrap(), installed.join(PLUGIN_FILE)); + } + + #[test] + fn nothing_anywhere_is_the_install_hint() { + let t = tempfile::tempdir().unwrap(); + let s = search(None, None, &[t.path()], &[t.path()]); + let e = resolve_plugin(&s).unwrap_err(); + assert!(e.contains("is not installed") && e.contains("docs.aws.amazon.com"), "{e}"); + } + + #[test] + fn the_bundled_name_is_what_tauri_gives_the_sidecar() { + // tauri-build/-bundler strip "-" from bundle.externalBin's + // "binaries/session-manager-plugin"; the .exe stays on Windows. + let conf: serde_json::Value = + serde_json::from_str(include_str!("../../../tauri.conf.json")).unwrap(); + let bins = conf["bundle"]["externalBin"].as_array().expect("bundle.externalBin"); + let stems: Vec<&str> = bins + .iter() + .map(|b| b.as_str().unwrap().rsplit('/').next().unwrap()) + .collect(); + let expected = PLUGIN_FILE.trim_end_matches(".exe"); + assert!(stems.contains(&expected), "{stems:?} has no {expected}"); + } +} diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index e6e3e64..3869f28 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -15,6 +15,7 @@ mod logging; mod marketplace; mod models; mod project_lock; +mod sidecar_placeholder; mod storage; pub mod url_open; pub mod web_terminal; diff --git a/app/src-tauri/src/sidecar_placeholder.rs b/app/src-tauri/src/sidecar_placeholder.rs new file mode 100644 index 0000000..85908a4 --- /dev/null +++ b/app/src-tauri/src/sidecar_placeholder.rs @@ -0,0 +1,31 @@ +//! The stand-in `build.rs` writes for the bundled `session-manager-plugin` sidecar in a +//! **debug** build that has no real one, and how the app recognises it. +//! +//! `bundle.externalBin` makes tauri-build fail outright when the per-target file is missing, +//! for `cargo test`, `cargo check` and `tauri dev` as much as for a release. The real binary +//! comes from `scripts/fetch-ssm-plugin.sh` (`.ps1` on Windows), which downloads a pinned, +//! hash-checked AWS release; requiring that for every test run would put AWS's S3 on the path +//! of every `cargo test`. So debug builds get this placeholder instead, a release build refuses +//! it (`build.rs`), and `host::ssm::find_plugin` skips it and falls back to an installed plugin. +//! +//! Shared by `build.rs` (through `#[path]`) and the app, so the two cannot disagree. + +/// The first bytes of a placeholder. Not an executable format on any platform. +pub const MARKER: &[u8] = b"TRIPLE-C SSM PLUGIN PLACEHOLDER"; + +/// The whole placeholder file. +#[allow(dead_code)] // build.rs only +pub fn contents() -> Vec { + let mut v = MARKER.to_vec(); + v.extend_from_slice( + b"\nNot the AWS Session Manager plugin. Debug builds get this when \ + app/src-tauri/binaries has no real one; run scripts/fetch-ssm-plugin.sh \ + (scripts/fetch-ssm-plugin.ps1 on Windows) to bundle the real plugin.\n", + ); + v +} + +/// Whether `bytes` (the start of a file) is a placeholder. +pub fn is_placeholder(bytes: &[u8]) -> bool { + bytes.starts_with(MARKER) +} diff --git a/app/src-tauri/tauri.conf.json b/app/src-tauri/tauri.conf.json index 48fce27..cdb6d40 100644 --- a/app/src-tauri/tauri.conf.json +++ b/app/src-tauri/tauri.conf.json @@ -36,6 +36,12 @@ "icons/icon.icns", "icons/icon.png" ], + "externalBin": [ + "binaries/session-manager-plugin" + ], + "resources": { + "THIRD_PARTY_NOTICES": "THIRD_PARTY_NOTICES" + }, "linux": { "appimage": { "bundleMediaFramework": true