From efe40cd79e2b742d05e2c98febb5184de43c868f Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 10:30:28 +0800 Subject: [PATCH 1/4] fix(remote-ssh): distinguish SSH servers by port Servers behind one address that differ only by SSH port (cluster nodes mapped to different ports) shared a connection id, saved profile, workspace stable id, runtime root, and session mirror. - New non-22 profiles use ssh-user@host#port ids; port 22 keeps ssh-user@host. '#' was never generated by released builds, so legacy ssh-user@host:port aliases still canonicalize as before and older peers treat the new ids as opaque. - Workspace identity (stable id, runtime key, session/runtime paths, permission project id, session recovery runtime key) derives from host#scope only for port-scoped ids; every existing id keeps its identity and on-disk layout byte-for-byte. - Saving a profile no longer replaces a profile for another port; only the same id or a legacy :port alias for the exact endpoint is replaced. - The dialog reuses an existing profile id for the same endpoint and never takes an id owned by another port. Fixes #3451 --- docs/features/remote-workspaces.md | 11 + src/apps/desktop/src/api/commands.rs | 8 +- src/apps/desktop/src/api/path_target.rs | 7 +- .../src/agentic/session/session_store_port.rs | 8 +- .../agentic/tools/pipeline/tool_pipeline.rs | 2 +- .../src/agentic/tools/tool_context_runtime.rs | 2 +- .../assembly/core/src/agentic/workspace.rs | 2 +- .../src/service/remote_ssh/workspace_state.rs | 67 ++++- .../core/src/service/remote_ssh_compat.rs | 5 +- .../core/src/service/snapshot/manager.rs | 8 +- .../src/service/workspace/legacy_compat.rs | 6 +- .../core/src/service/workspace/manager.rs | 102 +++++++- .../core/src/service/workspace/service.rs | 23 +- .../src/service/workspace_runtime/service.rs | 2 +- .../src/session_recovery/identity.rs | 6 +- .../services-core/src/workspace_identity.rs | 229 +++++++++++++++++- .../src/remote_ssh/manager.rs | 222 ++++++++++++++++- .../ssh-remote/SSHConnectionDialog.tsx | 20 +- .../ssh-remote/sshConnectionId.test.ts | 39 +++ .../features/ssh-remote/sshConnectionId.ts | 54 +++++ .../ssh-remote/useWorkspaceSourceOptions.ts | 3 +- 21 files changed, 780 insertions(+), 46 deletions(-) create mode 100644 src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts create mode 100644 src/web-ui/src/features/ssh-remote/sshConnectionId.ts diff --git a/docs/features/remote-workspaces.md b/docs/features/remote-workspaces.md index eb8ba9e759..3dc7800448 100644 --- a/docs/features/remote-workspaces.md +++ b/docs/features/remote-workspaces.md @@ -242,6 +242,17 @@ Existing remote-workspace records keep their paths and connection metadata. Legacy connection IDs that included the SSH port are migrated together with their password-vault and workspace references. +The SSH port is part of a connection's identity. Servers behind one address that +differ only by port (for example cluster nodes mapped to ports 2201 and 2202) +are separate profiles, workspaces, and session stores. Default-port (22) +profiles keep the `ssh-user@host` id, workspace id, and on-disk runtime and +session paths unchanged. New profiles on other ports use `ssh-user@host#port`; +`#` was never produced by an earlier build, so older peers treat these ids as +opaque instead of folding them into the legacy `ssh-user@host:port` alias. +Profiles saved by earlier builds keep their id when the port is edited, and +their workspaces and sessions stay where they are; saving a profile for another +port never overwrites them. + Legacy local-Docker profiles do not need an SSH password-vault entry, even if their old serialized auth placeholder is an empty password. diff --git a/src/apps/desktop/src/api/commands.rs b/src/apps/desktop/src/api/commands.rs index 10c0d3046e..af989e85ec 100644 --- a/src/apps/desktop/src/api/commands.rs +++ b/src/apps/desktop/src/api/commands.rs @@ -1396,7 +1396,7 @@ pub async fn open_remote_workspace( request: OpenRemoteWorkspaceRequest, ) -> Result { use openbitfun_core::service::remote_ssh::normalize_remote_workspace_path; - use openbitfun_core::service::remote_ssh::workspace_state::remote_workspace_stable_id; + use openbitfun_core::service::remote_ssh::workspace_state::remote_workspace_stable_id_for_connection; use openbitfun_core::service::workspace::{ remote_workspace_connection_conflict_message, RemoteConnectionRebind, WorkspaceCreateOptions, @@ -1465,7 +1465,11 @@ pub async fn open_remote_workspace( request.connection_name.clone() }); - let stable_workspace_id = remote_workspace_stable_id(&ssh_host, &remote_path); + let stable_workspace_id = remote_workspace_stable_id_for_connection( + &ssh_host, + Some(&request.connection_id), + &remote_path, + ); let display_name = remote_path .split('/') diff --git a/src/apps/desktop/src/api/path_target.rs b/src/apps/desktop/src/api/path_target.rs index 1ffd99546e..29b6346265 100644 --- a/src/apps/desktop/src/api/path_target.rs +++ b/src/apps/desktop/src/api/path_target.rs @@ -76,7 +76,12 @@ fn runtime_root_for_workspace_info(workspace: &WorkspaceInfo) -> Result { - if identity.hostname != *ssh_host + if identity.identity_host() != *ssh_host || identity.logical_workspace_path != *remote_root || identity.hostname.trim().is_empty() || identity @@ -639,8 +639,10 @@ pub async fn open_snapshot_history_for_workspace( let identity = &binding.session_identity; let runtime_service = get_workspace_runtime_service_arc(); let context = if identity.is_remote() { - runtime_service - .context_for_remote_workspace(&identity.hostname, &identity.logical_workspace_path) + runtime_service.context_for_remote_workspace( + &identity.identity_host(), + &identity.logical_workspace_path, + ) } else { runtime_service.context_for_local_workspace(Path::new(&identity.logical_workspace_path)) }; diff --git a/src/crates/assembly/core/src/service/workspace/legacy_compat.rs b/src/crates/assembly/core/src/service/workspace/legacy_compat.rs index 20864e4cdb..f364ac4c6e 100644 --- a/src/crates/assembly/core/src/service/workspace/legacy_compat.rs +++ b/src/crates/assembly/core/src/service/workspace/legacy_compat.rs @@ -377,8 +377,10 @@ pub(crate) async fn register_remote_fixture_with_id( remote_connection_id: Some(connection.to_owned()), remote_ssh_host: Some(host.to_owned()), stable_workspace_id: Some( - openbitfun_services_core::workspace_identity::remote_workspace_stable_id( - host, path, + openbitfun_services_core::workspace_identity::remote_workspace_stable_id_for_connection( + host, + Some(connection), + path, ), ), ..Default::default() diff --git a/src/crates/assembly/core/src/service/workspace/manager.rs b/src/crates/assembly/core/src/service/workspace/manager.rs index 2875003302..eae16a178f 100644 --- a/src/crates/assembly/core/src/service/workspace/manager.rs +++ b/src/crates/assembly/core/src/service/workspace/manager.rs @@ -13,7 +13,8 @@ pub use openbitfun_runtime_ports::RelatedPath; use openbitfun_services_core::workspace_identity::{ canonical_ssh_connection_id, canonicalize_local_workspace_root, local_workspace_stable_storage_id, normalize_local_workspace_root_for_stable_id, - normalize_remote_workspace_path, remote_workspace_stable_id, LOCAL_WORKSPACE_SSH_HOST, + normalize_remote_workspace_path, remote_workspace_stable_id_for_connection, + LOCAL_WORKSPACE_SSH_HOST, }; use serde::{Deserialize, Serialize}; @@ -359,7 +360,7 @@ impl WorkspaceInfoRuntimeExt for WorkspaceInfo { "Remote workspace requires a non-empty sshHost in the current OpenBitFun format", ) })?; - options + let connection_id = options .remote_connection_id .as_deref() .map(str::trim) @@ -377,7 +378,11 @@ impl WorkspaceInfoRuntimeExt for WorkspaceInfo { root_path.display() ))); } - let expected_id = remote_workspace_stable_id(ssh_host, &normalized_root); + let expected_id = remote_workspace_stable_id_for_connection( + ssh_host, + Some(connection_id), + &normalized_root, + ); let supplied_id = options .stable_workspace_id .as_ref() @@ -1252,7 +1257,15 @@ impl WorkspaceManager { .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string) - .or_else(|| host.map(|host| remote_workspace_stable_id(host, &path_norm)))?; + .or_else(|| { + host.map(|host| { + remote_workspace_stable_id_for_connection( + host, + options.remote_connection_id.as_deref(), + &path_norm, + ) + }) + })?; self.workspaces.get(&stable).filter(|workspace| { workspace.workspace_kind == WorkspaceKind::Remote && normalize_remote_workspace_path(&workspace.root_path.to_string_lossy()) @@ -1680,6 +1693,87 @@ mod tests { ); } + #[tokio::test] + async fn port_scoped_connections_open_distinct_workspaces_beside_legacy_records() { + use super::{ + remote_workspace_stable_id_for_connection, RemoteConnectionRebind, WorkspaceKind, + WorkspaceManager, WorkspaceManagerConfig, WorkspaceOpenOptions, + }; + use openbitfun_services_core::workspace_identity::remote_workspace_stable_id; + + let mut manager = WorkspaceManager::new(WorkspaceManagerConfig::default()); + let open = |connection_id: &str| WorkspaceOpenOptions { + workspace_kind: WorkspaceKind::Remote, + remote_connection_id: Some(connection_id.into()), + remote_ssh_host: Some("cluster.example".into()), + remote_connection_rebind: RemoteConnectionRebind::Reject, + ..Default::default() + }; + + // A record created by an older build (port-less id, any port) keeps + // the host + root stable id byte-for-byte. + let legacy = manager + .open_workspace_with_options("/srv/app".into(), open("ssh-root@cluster.example")) + .await + .unwrap(); + assert_eq!( + legacy.id, + remote_workspace_stable_id("cluster.example", "/srv/app") + ); + + // Nodes behind the same address on other ports are separate + // workspaces instead of a rebind conflict on the legacy record. + let node_a = manager + .open_workspace_with_options("/srv/app".into(), open("ssh-root@cluster.example#2201")) + .await + .unwrap(); + let node_b = manager + .open_workspace_with_options("/srv/app".into(), open("ssh-root@cluster.example#2202")) + .await + .unwrap(); + assert_eq!( + node_a.id, + remote_workspace_stable_id_for_connection( + "cluster.example", + Some("ssh-root@cluster.example#2201"), + "/srv/app" + ) + ); + assert_ne!(node_a.id, legacy.id); + assert_ne!(node_b.id, legacy.id); + assert_ne!(node_a.id, node_b.id); + assert_eq!( + manager + .get_workspace(&legacy.id) + .unwrap() + .remote_ssh_connection_id(), + Some("ssh-root@cluster.example") + ); + assert_eq!( + node_a + .metadata + .get("sshHost") + .and_then(|value| value.as_str()), + Some("cluster.example"), + "sshHost metadata keeps the plain host" + ); + + // A supplied id that ignores the port scope is still rejected. + let mismatched = manager + .open_workspace_with_options( + "/srv/other".into(), + WorkspaceOpenOptions { + stable_workspace_id: Some(remote_workspace_stable_id( + "cluster.example", + "/srv/other", + )), + ..open("ssh-root@cluster.example#2201") + }, + ) + .await; + assert!(mismatched.is_err()); + } + #[tokio::test] async fn remote_workspace_reopen_rebinds_connection_only_with_an_allowed_reason() { use super::{ diff --git a/src/crates/assembly/core/src/service/workspace/service.rs b/src/crates/assembly/core/src/service/workspace/service.rs index 97a6fc3eb3..5564d5e868 100644 --- a/src/crates/assembly/core/src/service/workspace/service.rs +++ b/src/crates/assembly/core/src/service/workspace/service.rs @@ -33,7 +33,7 @@ use log::{info, warn}; use openbitfun_core_types::product_identity::product_id; use openbitfun_services_core::workspace_identity::{ canonicalize_local_workspace_root, local_workspace_roots_equal, - normalize_remote_workspace_path, remote_workspace_stable_id, + normalize_remote_workspace_path, remote_workspace_stable_id_for_connection, }; use serde::{Deserialize, Serialize}; @@ -234,9 +234,14 @@ impl WorkspaceService { return; }; + let identity_host = + openbitfun_services_core::workspace_identity::ssh_workspace_identity_host( + ssh_host, + workspace.remote_ssh_connection_id(), + ); self.runtime_service .ensure_remote_workspace_runtime( - ssh_host, + &identity_host, &workspace.root_path.to_string_lossy(), ) .await @@ -543,7 +548,11 @@ impl WorkspaceService { display_name, remote_connection_id: Some(connection_id.to_string()), remote_ssh_host: Some(host.clone()), - stable_workspace_id: Some(remote_workspace_stable_id(&host, &path)), + stable_workspace_id: Some(remote_workspace_stable_id_for_connection( + &host, + Some(connection_id), + &path, + )), ..Default::default() }; return WorkspaceInfo::new_without_worktree(PathBuf::from(path), options).await; @@ -2187,8 +2196,9 @@ impl WorkspaceService { .map(str::trim) .filter(|value| !value.is_empty()) { - options.stable_workspace_id = Some(remote_workspace_stable_id( + options.stable_workspace_id = Some(remote_workspace_stable_id_for_connection( ssh_host, + options.remote_connection_id.as_deref(), &normalize_remote_workspace_path(&path.to_string_lossy()), )); } @@ -3546,7 +3556,10 @@ mod tests { assert_eq!( tracked.id, - remote_workspace_stable_id("example-host", "/srv/openbitfun/project") + openbitfun_services_core::workspace_identity::remote_workspace_stable_id( + "example-host", + "/srv/openbitfun/project" + ) ); assert_eq!(tracked.root_path, remote_workspace_root); assert!(service.get_opened_workspaces().await.is_empty()); diff --git a/src/crates/assembly/core/src/service/workspace_runtime/service.rs b/src/crates/assembly/core/src/service/workspace_runtime/service.rs index b0b7050f0c..9855246cf0 100644 --- a/src/crates/assembly/core/src/service/workspace_runtime/service.rs +++ b/src/crates/assembly/core/src/service/workspace_runtime/service.rs @@ -113,7 +113,7 @@ impl WorkspaceRuntimeService { ) -> OpenBitFunResult { if workspace.is_remote() { self.ensure_remote_workspace_runtime( - &workspace.session_identity.hostname, + &workspace.session_identity.identity_host(), workspace.session_identity.logical_workspace_path(), ) .await diff --git a/src/crates/services/services-core/src/session_recovery/identity.rs b/src/crates/services/services-core/src/session_recovery/identity.rs index 0ca1512852..2468bcb66f 100644 --- a/src/crates/services/services-core/src/session_recovery/identity.rs +++ b/src/crates/services/services-core/src/session_recovery/identity.rs @@ -85,8 +85,12 @@ fn host(record: &Value) -> Result { pub(super) fn runtime_key(record: &Value) -> Result { let root = record_root(record)?; if string(record, "workspaceKind") == Some("remote") { - Ok(wi::remote_workspace_runtime_key( + let identity_host = wi::ssh_workspace_identity_host( &host(record)?, + string(&record["metadata"], "connectionId"), + ); + Ok(wi::remote_workspace_runtime_key( + &identity_host, &remote_path(&root)?, )) } else { diff --git a/src/crates/services/services-core/src/workspace_identity.rs b/src/crates/services/services-core/src/workspace_identity.rs index 9803dea71d..be0ce150b0 100644 --- a/src/crates/services/services-core/src/workspace_identity.rs +++ b/src/crates/services/services-core/src/workspace_identity.rs @@ -24,6 +24,11 @@ impl WorkspaceSessionIdentity { pub fn logical_workspace_path(&self) -> &str { &self.logical_workspace_path } + + /// Host string for runtime and session paths; see [`ssh_workspace_identity_host`]. + pub fn identity_host(&self) -> String { + ssh_workspace_identity_host(&self.hostname, self.remote_connection_id.as_deref()) + } } /// Normalize a remote POSIX workspace path for registry lookup on any client OS. @@ -40,9 +45,12 @@ pub fn normalize_remote_workspace_path(path: &str) -> String { /// Canonical form of an SSH connection id. /// -/// Older builds generated `ssh-user@host:port`; current profiles use -/// `ssh-user@host`. Both spellings name the same saved connection, so persisted -/// workspace records written by either build compare equal after this mapping. +/// Older builds generated `ssh-user@host:port`; current default-port profiles +/// use `ssh-user@host`. Both spellings name the same saved connection, so +/// persisted workspace records written by either build compare equal after this +/// mapping. Port-scoped ids (`ssh-user@host#port`, see +/// [`ssh_connection_id_for_endpoint`]) are distinct connections and are never +/// collapsed. pub fn canonical_ssh_connection_id(id: &str) -> String { if let Some(rest) = id.strip_prefix("ssh-") { if let (Some(at), Some(colon)) = (rest.find('@'), rest.rfind(':')) { @@ -54,6 +62,92 @@ pub fn canonical_ssh_connection_id(id: &str) -> String { id.to_string() } +/// SSH port that keeps the legacy, port-less connection and workspace identity. +pub const DEFAULT_SSH_PORT: u16 = 22; + +/// Separator between the host and the port scope of a port-scoped SSH +/// connection id (`ssh-{user}@{host}#{port}`). +/// +/// Builds before #710 generated `ssh-{user}@{host}:{port}` for every port and +/// [`canonical_ssh_connection_id`] treats that spelling as an alias of +/// `ssh-{user}@{host}`. Port-scoped ids therefore use a separator no released +/// build ever produced or collapses, so older peers keep treating them as +/// opaque, distinct ids. +pub const SSH_CONNECTION_ID_PORT_SEPARATOR: char = '#'; + +/// Connection id for a new SSH profile. +/// +/// The default port keeps the historical `ssh-{user}@{host}` id byte-for-byte; +/// any other port appends `#{port}` so servers behind one address stay +/// distinct. +pub fn ssh_connection_id_for_endpoint(username: &str, host: &str, port: u16) -> String { + if port == DEFAULT_SSH_PORT { + format!("ssh-{username}@{host}") + } else { + format!("ssh-{username}@{host}{SSH_CONNECTION_ID_PORT_SEPARATOR}{port}") + } +} + +/// Port scope carried by a port-scoped SSH connection id. +/// +/// Returns the text after `#` (a port, optionally followed by a `~{n}` +/// disambiguator) for ids shaped `ssh-{user}@{host}#{scope}` and for container +/// ids derived from them (`...#{scope}-container-{name}`). Legacy ids, including +/// pre-#710 `ssh-{user}@{host}:{port}` ids, return `None`. +pub fn ssh_connection_id_port_scope(connection_id: &str) -> Option<&str> { + let rest = connection_id.trim().strip_prefix("ssh-")?; + let at = rest.find('@')?; + let after_at = &rest[at + 1..]; + let separator = after_at.find(SSH_CONNECTION_ID_PORT_SEPARATOR)?; + let scope_and_suffix = &after_at[separator + 1..]; + let scope = scope_and_suffix + .split_once('-') + .map_or(scope_and_suffix, |(scope, _)| scope); + let (port, disambiguator) = match scope.split_once('~') { + Some((port, n)) => (port, Some(n)), + None => (scope, None), + }; + if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) || port.parse::().is_err() + { + return None; + } + if disambiguator.is_some_and(|n| n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit())) { + return None; + } + Some(scope) +} + +/// SSH host string used for workspace identity (stable id, runtime key, and +/// session mirror path). +/// +/// Connections whose id carries no port scope (every id written by released +/// builds, including all default-port profiles) return `ssh_host` unchanged, +/// so their workspace identity and on-disk layout stay byte-for-byte the same. +/// Port-scoped connections return `{ssh_host}#{scope}`; `#` never appears in a +/// real SSH host, so these identities cannot collide with legacy ones and are +/// a safe path component on every client OS. +pub fn ssh_workspace_identity_host(ssh_host: &str, connection_id: Option<&str>) -> String { + match connection_id.and_then(ssh_connection_id_port_scope) { + Some(scope) => format!( + "{}{SSH_CONNECTION_ID_PORT_SEPARATOR}{scope}", + ssh_host.trim() + ), + None => ssh_host.to_string(), + } +} + +/// Stable workspace id for a remote workspace owned by `connection_id`. +pub fn remote_workspace_stable_id_for_connection( + ssh_host: &str, + connection_id: Option<&str>, + remote_root_norm: &str, +) -> String { + remote_workspace_stable_id( + &ssh_workspace_identity_host(ssh_host, connection_id), + remote_root_norm, + ) +} + /// Connection id as one safe local path component. pub fn sanitize_ssh_connection_id_for_local_dir(connection_id: &str) -> String { if connection_id == "." { @@ -393,7 +487,134 @@ pub fn build_project_runtime_slug(canonical: &str) -> String { #[cfg(test)] mod tests { - use super::canonical_ssh_connection_id; + use super::{ + canonical_ssh_connection_id, remote_workspace_runtime_key, + remote_workspace_session_mirror_dir, remote_workspace_stable_id, + remote_workspace_stable_id_for_connection, ssh_connection_id_for_endpoint, + ssh_connection_id_port_scope, ssh_workspace_identity_host, + }; + use std::path::Path; + + #[test] + fn default_port_connection_ids_keep_the_legacy_spelling() { + assert_eq!( + ssh_connection_id_for_endpoint("root", "example.com", 22), + "ssh-root@example.com" + ); + assert_eq!( + ssh_connection_id_for_endpoint("root", "example.com", 2222), + "ssh-root@example.com#2222" + ); + } + + #[test] + fn port_scope_is_parsed_only_from_port_scoped_ids() { + assert_eq!( + ssh_connection_id_port_scope("ssh-root@example.com#2222"), + Some("2222") + ); + assert_eq!( + ssh_connection_id_port_scope("ssh-root@example.com#2222~2"), + Some("2222~2") + ); + assert_eq!( + ssh_connection_id_port_scope("ssh-root@example.com#2222-container-web"), + Some("2222") + ); + assert_eq!( + ssh_connection_id_port_scope("ssh-root@fe80::1#2201"), + Some("2201") + ); + // Every id shape written by released builds stays legacy. + for legacy in [ + "ssh-root@example.com", + "ssh-root@example.com:2222", + "ssh-root@example.com:22", + "ssh-root@example.com-container-web", + "wsl-Ubuntu@root", + "0c9f6c1e-profile", + "ssh-root@example.com#", + "ssh-root@example.com#99999", + "ssh-root@example.com#22x", + "ssh-root@example.com#22~", + ] { + assert_eq!(ssh_connection_id_port_scope(legacy), None, "{legacy}"); + } + } + + #[test] + fn legacy_connection_ids_keep_workspace_identity_byte_for_byte() { + let root = "/home/user/repo"; + let legacy_id = remote_workspace_stable_id("example.com", root); + for connection_id in [ + None, + Some("ssh-root@example.com"), + Some("ssh-root@example.com:2222"), + Some("ssh-root@example.com-container-web"), + ] { + assert_eq!( + ssh_workspace_identity_host("example.com", connection_id), + "example.com" + ); + assert_eq!( + remote_workspace_stable_id_for_connection("example.com", connection_id, root), + legacy_id + ); + } + } + + #[test] + fn port_scoped_connections_get_distinct_workspace_identity() { + let root = "/home/user/repo"; + let legacy = remote_workspace_stable_id("example.com", root); + let port_a = remote_workspace_stable_id_for_connection( + "example.com", + Some("ssh-u@example.com#2201"), + root, + ); + let port_b = remote_workspace_stable_id_for_connection( + "example.com", + Some("ssh-u@example.com#2202"), + root, + ); + assert_ne!(port_a, legacy); + assert_ne!(port_b, legacy); + assert_ne!(port_a, port_b); + assert_eq!( + ssh_workspace_identity_host(" Example.com ", Some("ssh-u@example.com#2201")), + "Example.com#2201" + ); + assert_ne!( + remote_workspace_runtime_key("example.com#2201", root), + remote_workspace_runtime_key("example.com", root) + ); + let mirror = remote_workspace_session_mirror_dir( + Path::new("/mirror"), + &ssh_workspace_identity_host("example.com", Some("ssh-u@example.com#2201")), + root, + ); + assert_eq!( + mirror, + Path::new("/mirror") + .join("example.com#2201") + .join("home") + .join("user") + .join("repo") + .join("sessions") + ); + } + + #[test] + fn canonical_ssh_connection_id_never_collapses_port_scoped_ids() { + assert_eq!( + canonical_ssh_connection_id("ssh-root@example.com#2222"), + "ssh-root@example.com#2222" + ); + assert_eq!( + canonical_ssh_connection_id("ssh-root@fe80::1#2222"), + "ssh-root@fe80::1#2222" + ); + } #[test] fn canonical_ssh_connection_id_strips_only_legacy_port_suffixes() { diff --git a/src/crates/services/services-integrations/src/remote_ssh/manager.rs b/src/crates/services/services-integrations/src/remote_ssh/manager.rs index 898f5a0761..e2d5bb00f8 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/manager.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/manager.rs @@ -2917,15 +2917,22 @@ impl SSHConnectionManager { let mut guard = self.saved_connections.write().await; - // Remove existing entry with same id OR same host+username (dedup). - // Using host+username (without port) so that changing the port replaces - // the old entry instead of creating a duplicate. + // Remove the existing entry with the same id (an edit keeps its id, so + // changing the port of a saved profile still replaces it in place) OR a + // legacy alias of it (`ssh-user@host:port`, which workspace records + // already treat as the same connection) for the exact same endpoint. + // The port is part of the endpoint: servers behind one address that + // differ only by port are distinct profiles and never overwrite each + // other. A different, non-alias id for the same endpoint is kept, since + // workspace and session records may still reference it. guard.retain(|c| { c.id != config.id && !(c.host == config.host + && c.port == config.port && c.username == config.username && c.container == config.container - && c.wsl == config.wsl) + && c.wsl == config.wsl + && Self::connection_ids_are_aliases(&c.id, &config.id)) }); // Add new entry @@ -2969,6 +2976,15 @@ impl SSHConnectionManager { self.save_connections().await } + /// Whether two saved-profile ids name the same connection through the + /// legacy `ssh-user@host:port` spelling. + fn connection_ids_are_aliases(left: &str, right: &str) -> bool { + use openbitfun_services_core::workspace_identity::canonical_ssh_connection_id; + left == right + || canonical_ssh_connection_id(left) == right + || canonical_ssh_connection_id(right) == left + } + /// Decrypt stored password for password-based saved connections (auto-reconnect). pub async fn load_stored_password( &self, @@ -9273,6 +9289,204 @@ mod tests { let _ = tokio::fs::remove_dir_all(&dir).await; } + fn key_profile(id: &str, host: &str, port: u16, username: &str) -> SSHConnectionConfig { + SSHConnectionConfig { + id: id.to_string(), + name: format!("{username}@{host}:{port}"), + host: host.to_string(), + port, + username: username.to_string(), + auth: SSHAuthMethod::PrivateKey { + key_path: "~/.ssh/id_ed25519".to_string(), + passphrase: None, + certificate_path: None, + }, + default_workspace: None, + proxy_jump: None, + container: None, + wsl: None, + options: Default::default(), + } + } + + #[tokio::test] + async fn saving_a_second_port_on_the_same_host_keeps_both_profiles() { + let dir = test_data_dir("port-scoped-profiles"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + + manager + .save_connection(&key_profile("ssh-root@cluster", "cluster", 22, "root")) + .await + .unwrap(); + manager + .save_connection(&key_profile( + "ssh-root@cluster#2201", + "cluster", + 2201, + "root", + )) + .await + .unwrap(); + manager + .save_connection(&key_profile( + "ssh-root@cluster#2202", + "cluster", + 2202, + "root", + )) + .await + .unwrap(); + + let mut saved: Vec<(String, u16)> = manager + .get_saved_connections() + .await + .into_iter() + .map(|c| (c.id, c.port)) + .collect(); + saved.sort(); + assert_eq!( + saved, + vec![ + ("ssh-root@cluster".to_string(), 22), + ("ssh-root@cluster#2201".to_string(), 2201), + ("ssh-root@cluster#2202".to_string(), 2202), + ] + ); + + // A legacy `:port` alias of the same endpoint is replaced; a distinct + // id for the same endpoint is kept because records may reference it. + manager + .save_connection(&key_profile("ssh-root@cluster:22", "cluster", 22, "root")) + .await + .unwrap(); + manager + .save_connection(&key_profile("ssh-root@cluster", "cluster", 22, "root")) + .await + .unwrap(); + manager + .save_connection(&key_profile( + "ssh-root@cluster#2202~2", + "cluster", + 2202, + "root", + )) + .await + .unwrap(); + let mut ids: Vec = manager + .get_saved_connections() + .await + .into_iter() + .map(|c| c.id) + .collect(); + ids.sort(); + assert_eq!( + ids, + vec![ + "ssh-root@cluster".to_string(), + "ssh-root@cluster#2201".to_string(), + "ssh-root@cluster#2202".to_string(), + "ssh-root@cluster#2202~2".to_string(), + ] + ); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn editing_the_port_of_a_saved_profile_keeps_its_id() { + let dir = test_data_dir("port-edit-keeps-id"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + let manager = SSHConnectionManager::new(dir.clone()); + + manager + .save_connection(&key_profile( + "ssh-root@cluster#2201", + "cluster", + 2201, + "root", + )) + .await + .unwrap(); + manager + .save_connection(&key_profile( + "ssh-root@cluster#2201", + "cluster", + 2299, + "root", + )) + .await + .unwrap(); + + let saved = manager.get_saved_connections().await; + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].id, "ssh-root@cluster#2201"); + assert_eq!(saved[0].port, 2299); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + + #[tokio::test] + async fn legacy_port_profiles_round_trip_unchanged_next_to_port_scoped_ones() { + let dir = test_data_dir("legacy-port-profiles"); + tokio::fs::create_dir_all(&dir).await.unwrap(); + // Shapes written by released builds: a post-#710 port-less id that + // points at a non-default port, and a pre-#710 `:port` id. + tokio::fs::write( + dir.join("ssh_connections.json"), + serde_json::to_string_pretty(&serde_json::json!([ + { + "id": "ssh-root@cluster", + "name": "cluster node", + "host": "cluster", + "port": 2201, + "username": "root", + "authType": { "type": "PrivateKey", "keyPath": "~/.ssh/id_ed25519" }, + "lastConnected": 1 + }, + { + "id": "ssh-alice@legacy.example:2222", + "name": "legacy", + "host": "legacy.example", + "port": 2222, + "username": "alice", + "authType": { "type": "PrivateKey", "keyPath": "~/.ssh/id_ed25519" }, + "lastConnected": 1 + } + ])) + .unwrap(), + ) + .await + .unwrap(); + + let manager = SSHConnectionManager::new(dir.clone()); + manager.load_saved_connections().await.unwrap(); + // A new default-port profile on the same host must not overwrite the + // legacy profile; the dialog gives it a port-scoped id because the + // port-less id is already taken by another port. + manager + .save_connection(&key_profile("ssh-root@cluster#22", "cluster", 22, "root")) + .await + .unwrap(); + + let reloaded = SSHConnectionManager::new(dir.clone()); + reloaded.load_saved_connections().await.unwrap(); + let mut saved: Vec<(String, u16)> = reloaded + .get_saved_connections() + .await + .into_iter() + .map(|c| (c.id, c.port)) + .collect(); + saved.sort(); + assert_eq!( + saved, + vec![ + ("ssh-alice@legacy.example:2222".to_string(), 2222), + ("ssh-root@cluster".to_string(), 2201), + ("ssh-root@cluster#22".to_string(), 22), + ] + ); + let _ = tokio::fs::remove_dir_all(&dir).await; + } + #[tokio::test] async fn prunes_remote_workspaces_without_saved_connection() { let dir = test_data_dir("missing-saved"); diff --git a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx index a81115ef6e..47fa42fd8e 100644 --- a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx @@ -54,6 +54,7 @@ import { workspaceSourceErrorKey, isSshAuthenticationError } from './workspaceSo import { savedConnectionConfig } from './savedConnectionConfig'; import type { WorkspaceConnectionPreset } from './useWorkspaceSourceOptions'; import { sameWorkspaceSource, savedConnectionTarget } from './workspaceSource'; +import { sshConnectionIdForEndpoint } from './sshConnectionId'; import { pickSshCertificatePath, pickSshPrivateKeyPath, @@ -362,12 +363,6 @@ export const SSHConnectionDialog: React.FC = ({ if (path) setFormData((prev) => ({ ...prev, certificatePath: path })); }, [isConnecting, status, t]); - // Port is intentionally excluded so that the ID stays stable when the user - // changes the SSH port. - const generateConnectionId = (host: string, _port: number, username: string) => { - return `ssh-${username}@${host}`; - }; - const buildAuthMethod = (): SSHAuthMethod => { switch (formData.authType) { case 'password': @@ -516,9 +511,20 @@ export const SSHConnectionDialog: React.FC = ({ // Direct SSH already identifies the container. Keep legacy metadata when editing; // new profiles derive it from the endpoint instead of asking for a Docker ID. const containerName = formData.containerName.trim() || (formData.targetType === 'containerSshd' ? connectHost : 'discovery'); + // Editing keeps the saved id (so a port change never moves sessions); + // new profiles get a port-aware id that cannot overwrite another endpoint. + const knownConnections = editingProfile || isLocalDocker + ? savedConnections + : await sshApi.listSavedConnections().catch(() => savedConnections); const id = isLocalDocker ? `docker-local-${containerName}` - : `${generateConnectionId(connectHost, port, username)}${usesContainer ? `-container-${containerName}` : ''}`; + : sshConnectionIdForEndpoint( + { host: connectHost, port, username, suffix: usesContainer ? `-container-${containerName}` : '' }, + knownConnections, + connection => !connection.wsl && (usesContainer + ? !connection.container?.local && connection.container?.name === containerName + : !connection.container), + ); return { id: editingProfile?.id ?? id, name: formData.name || (isLocalDocker ? containerName : `${username}@${hostInput}`), diff --git a/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts b/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts new file mode 100644 index 0000000000..7cda2bd0c3 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest'; +import { sshConnectionIdForEndpoint } from './sshConnectionId'; +import type { SavedConnection } from './types'; + +const saved = (id: string, host: string, port: number, username = 'root', extra: Partial = {}): SavedConnection => ({ + id, name: id, host, port, username, authType: { type: 'Agent' }, ...extra, +}); + +describe('sshConnectionIdForEndpoint', () => { + it('keeps the legacy id for the default port', () => { + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' })).toBe('ssh-root@cluster'); + }); + + it('distinguishes servers behind one address by port', () => { + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' })).toBe('ssh-root@cluster#2201'); + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2202, username: 'root' })).toBe('ssh-root@cluster#2202'); + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root', suffix: '-container-web' })) + .toBe('ssh-root@cluster#2201-container-web'); + }); + + it('reuses the id of a saved profile for the same endpoint, including legacy port-less ids', () => { + const connections = [saved('ssh-root@cluster', 'cluster', 2201)]; + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, connections)).toBe('ssh-root@cluster'); + }); + + it('never takes an id owned by a profile for another port', () => { + const connections = [saved('ssh-root@cluster', 'cluster', 2201), saved('ssh-root@cluster#2202', 'cluster', 2299)]; + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, connections)).toBe('ssh-root@cluster#22'); + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2202, username: 'root' }, connections)).toBe('ssh-root@cluster#2202~2'); + }); + + it('only reuses profiles of the same target kind', () => { + const connections = [saved('ssh-root@cluster', 'cluster', 22, 'root', { + container: { name: 'web', local: false, access: 'auto', dockerPath: 'docker', shell: '/bin/sh', interactive: true }, + })]; + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, connections, connection => !connection.container)) + .toBe('ssh-root@cluster#22'); + }); +}); diff --git a/src/web-ui/src/features/ssh-remote/sshConnectionId.ts b/src/web-ui/src/features/ssh-remote/sshConnectionId.ts new file mode 100644 index 0000000000..dc81ed1ec5 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/sshConnectionId.ts @@ -0,0 +1,54 @@ +import type { SavedConnection } from './types'; + +export const DEFAULT_SSH_PORT = 22; + +/** + * Separator between host and port in port-scoped SSH connection ids. Builds + * before #710 generated `ssh-user@host:port` for every port and the backend + * treats that spelling as an alias of `ssh-user@host`, so port-scoped ids use + * a separator no released build produced or collapses. + */ +const PORT_SEPARATOR = '#'; + +interface SshEndpoint { + host: string; + port: number; + username: string; + /** Suffix appended to the id, e.g. `-container-web` for container profiles. */ + suffix?: string; +} + +const sameEndpoint = (connection: SavedConnection, endpoint: SshEndpoint) => + connection.host === endpoint.host + && connection.port === endpoint.port + && connection.username === endpoint.username; + +/** + * Connection id for a new SSH profile. + * + * - Port 22 keeps the historical `ssh-user@host` id byte-for-byte. + * - Other ports use `ssh-user@host#port`, so servers behind one address that + * differ only by port stay distinct connections and workspaces. + * - A saved profile for the same endpoint keeps its existing id, so legacy + * port-less ids for non-default ports are reused instead of replaced. + * - An id already owned by a profile for another endpoint is never reused; + * the port-scoped form (with a `~n` disambiguator when needed) is used. + */ +export function sshConnectionIdForEndpoint( + endpoint: SshEndpoint, + saved: readonly SavedConnection[] = [], + isSameTarget: (connection: SavedConnection) => boolean = () => true, +): string { + const suffix = endpoint.suffix ?? ''; + const existing = saved.find(connection => sameEndpoint(connection, endpoint) && isSameTarget(connection)); + if (existing) return existing.id; + + const taken = (id: string) => saved.some(connection => connection.id === id); + const portLess = `ssh-${endpoint.username}@${endpoint.host}`; + const scoped = `${portLess}${PORT_SEPARATOR}${endpoint.port}`; + const preferred = endpoint.port === DEFAULT_SSH_PORT ? `${portLess}${suffix}` : `${scoped}${suffix}`; + if (!taken(preferred)) return preferred; + let candidate = `${scoped}${suffix}`; + for (let n = 2; taken(candidate); n += 1) candidate = `${scoped}~${n}${suffix}`; + return candidate; +} diff --git a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts index 69e2ff0a05..5043ee7392 100644 --- a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts +++ b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts @@ -7,6 +7,7 @@ import { createLogger } from '@/shared/utils/logger'; const log = createLogger('WorkspaceSourceOptions'); import { sameWorkspaceSource, savedConnectionTarget, type WorkspaceSource } from './workspaceSource'; import type { SavedConnection, SSHConfigEntry, SSHConnectionConfig } from './types'; +import { DEFAULT_SSH_PORT, sshConnectionIdForEndpoint } from './sshConnectionId'; export type WorkspaceConnectionPreset = ( | { kind: 'new'; host?: SavedConnection } @@ -25,7 +26,7 @@ export function workspacePresetHost(preset?: WorkspaceConnectionPreset): SavedCo if (preset?.kind !== 'sshConfig') return undefined; const { entry } = preset; return { - id: `ssh-${entry.user || ''}@${entry.hostname || entry.host}`, + id: sshConnectionIdForEndpoint({ host: entry.hostname || entry.host, port: entry.port || DEFAULT_SSH_PORT, username: entry.user || '' }), name: entry.host, host: entry.hostname || entry.host, port: entry.port || 22, username: entry.user || '', authType: entry.identityFile ? { type: 'PrivateKey', keyPath: entry.identityFile, certificatePath: entry.certificateFile } : entry.agent ? { type: 'Agent' } : { type: 'Password' }, From 08dfc8285c6c71811587ed99c29dc982d0267340 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 13:00:14 +0800 Subject: [PATCH 2/4] fix(remote-ssh): close port-identity review gaps - Resolve ~/.ssh/config preset ids against saved profiles; when they cannot be listed, route to the connection dialog instead of a one-click connect. - Count pre-#710 ssh-user@host:port aliases as taken, and reuse an orphaned legacy id that workspace records still reference. - Advertise ssh_port_scoped_identity_v1 from Desktop hosts. Against older peers the controller keeps legacy ids and blocks adding a second port for the same host and user; the peer adapter rejects port-scoped ids. - Pin the host-only identity per (connection, root) for records an older host stored under the legacy stable id, including session recovery. - Connection-less legacy workspace references never select port-scoped records (Rust, Web UI, mobile web, Kotlin mobile). - Parse port scopes through synthetic workspace-host container wrappers. --- docs/features/remote-workspaces.md | 7 +- src/apps/desktop/src/api/path_target.rs | 1 + .../domain/LegacyWorkspaceCompatibility.kt | 36 +++ .../LegacyWorkspaceCompatibilityTest.kt | 12 + .../src/agentic/session/session_store_port.rs | 1 + .../src/service/remote_ssh/workspace_state.rs | 8 +- .../src/service/workspace/legacy_compat.rs | 116 ++++++++ .../core/src/service/workspace/service.rs | 3 + .../generated/remote-surface-registry.json | 4 +- .../src/remote_surface/capabilities.rs | 15 +- .../src/session_recovery/identity.rs | 18 +- .../services-core/src/workspace_identity.rs | 253 ++++++++++++++++-- .../src/services/workspaceIdentity.ts | 20 ++ .../tests/workspace-identity.test.mjs | 9 + .../ssh-remote/SSHConnectionDialog.tsx | 30 ++- .../ssh-remote/resolveSshConnectionId.ts | 80 ++++++ .../ssh-remote/sshConnectionId.test.ts | 96 ++++++- .../features/ssh-remote/sshConnectionId.ts | 57 +++- .../useWorkspaceSourceOptions.test.tsx | 25 +- .../ssh-remote/useWorkspaceSourceOptions.ts | 37 ++- .../api/adapters/peer-device-adapter.test.ts | 21 ++ .../api/adapters/peer-device-adapter.ts | 15 ++ .../api/generated/remoteSurface.ts | 4 +- .../legacyWorkspaceCompatibility.test.ts | 8 + .../legacyWorkspaceCompatibility.ts | 5 + .../peer-device/PeerConnectionManager.ts | 7 + src/web-ui/src/locales/en-US/common.json | 1 + src/web-ui/src/locales/zh-CN/common.json | 1 + src/web-ui/src/locales/zh-TW/common.json | 1 + .../src/shared/utils/sshConnectionIdentity.ts | 45 ++++ 30 files changed, 876 insertions(+), 60 deletions(-) create mode 100644 src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts create mode 100644 src/web-ui/src/shared/utils/sshConnectionIdentity.ts diff --git a/docs/features/remote-workspaces.md b/docs/features/remote-workspaces.md index 3dc7800448..7afa6ce492 100644 --- a/docs/features/remote-workspaces.md +++ b/docs/features/remote-workspaces.md @@ -251,7 +251,12 @@ session paths unchanged. New profiles on other ports use `ssh-user@host#port`; opaque instead of folding them into the legacy `ssh-user@host:port` alias. Profiles saved by earlier builds keep their id when the port is edited, and their workspaces and sessions stay where they are; saving a profile for another -port never overwrites them. +port never overwrites them. Re-adding a deleted legacy profile reuses its old id +while workspace records still reference it. Workspace records that an older +host stored under the host-only identity keep that identity after an upgrade. +Peer hosts advertise `ssh_port_scoped_identity_v1`; against an older peer the +controller keeps legacy ids and refuses to add a second port for the same host +and user instead of replacing the existing profile. Legacy local-Docker profiles do not need an SSH password-vault entry, even if their old serialized auth placeholder is an empty password. diff --git a/src/apps/desktop/src/api/path_target.rs b/src/apps/desktop/src/api/path_target.rs index 29b6346265..06e609f965 100644 --- a/src/apps/desktop/src/api/path_target.rs +++ b/src/apps/desktop/src/api/path_target.rs @@ -80,6 +80,7 @@ fn runtime_root_for_workspace_info(workspace: &WorkspaceInfo) -> Result host != LOCALHOST || connectionId != null } val candidates = catalog.filter { candidate -> normalizedRoot(candidate.path) == root && + // A reference without a connection id predates port-scoped SSH + // profiles (`ssh-user@host#port`) and can never name one. + (connectionId != null || !isPortScopedSshConnectionId(candidate.remoteConnectionId)) && (connectionId == null || candidate.remoteConnectionId?.trim() == connectionId) && (sshHost == null || candidate.remoteSshHost?.trim() == sshHost) } @@ -87,6 +90,39 @@ public object LegacyWorkspaceCompatibility { resolveReference(reference, catalog).identityOrNull private const val LOCALHOST: String = "localhost" + private const val WORKSPACE_HOST_PREFIX: String = "workspace-host-" + private val PORT_SCOPED_SSH_ID = Regex("""^ssh-[^@]*@[^#]*#(\d+)(?:~\d+)?(?:-.*)?$""") + + /** + * Mirrors `ssh_connection_id_port_scope` in the Rust workspace identity + * owner: `ssh-user@host#port` ids (also wrapped as + * `workspace-host-...`) name a distinct connection per port. + */ + public fun isPortScopedSshConnectionId(connectionId: String?): Boolean { + var id = connectionId?.trim().orEmpty() + if (id.startsWith(WORKSPACE_HOST_PREFIX)) { + id = percentDecode(id.removePrefix(WORKSPACE_HOST_PREFIX)) ?: return false + } + val port = PORT_SCOPED_SSH_ID.matchEntire(id)?.groupValues?.get(1) ?: return false + return (port.toIntOrNull() ?: Int.MAX_VALUE) <= 65535 + } + + private fun percentDecode(value: String): String? { + val bytes = ArrayList(value.length) + var index = 0 + while (index < value.length) { + if (value[index] == '%') { + if (index + 2 >= value.length) return null + val hex = value.substring(index + 1, index + 3).toIntOrNull(16) ?: return null + bytes.add(hex.toByte()) + index += 3 + } else { + value[index].toString().encodeToByteArray().forEach(bytes::add) + index += 1 + } + } + return bytes.toByteArray().decodeToString() + } private fun normalizedRoot(path: String): String = path.trim().let { it.trimEnd('/').ifEmpty { it } } } diff --git a/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt b/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt index c23dc2e1ca..b2689856e0 100644 --- a/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt +++ b/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt @@ -54,6 +54,18 @@ class LegacyWorkspaceCompatibilityTest { LegacyWorkspaceCompatibility.resolveReference(RemoteWorkspaceIdentity("/repo", " ", ""), catalog)) } + @Test + fun connectionlessLegacyReferenceNeverSelectsAPortScopedSshWorkspace() { + val legacy = RemoteWorkspaceIdentity("/srv/app", "ssh-root@cluster", "cluster", "legacy-id") + val node = RemoteWorkspaceIdentity("/srv/app", "ssh-root@cluster#2201", "cluster", "node-id") + val nodes = listOf(legacy, node) + assertEquals(legacy, LegacyWorkspaceCompatibility.resolve(RemoteWorkspaceIdentity("/srv/app", null, "cluster"), nodes)) + assertEquals(node, LegacyWorkspaceCompatibility.resolve(RemoteWorkspaceIdentity("/srv/app", "ssh-root@cluster#2201", "cluster"), nodes)) + assertTrue(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("workspace-host-ssh-root%40cluster%232201-container-web")) + assertFalse(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("ssh-root@cluster:2201")) + assertFalse(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("workspace-host-%ZZ")) + } + @Test fun bareLocalhostHostIsIgnoredOnlyWithoutAConnectionId() { // 1.0.0 stamped `localhost` on local workspaces: without a connection it says nothing. diff --git a/src/crates/assembly/core/src/agentic/session/session_store_port.rs b/src/crates/assembly/core/src/agentic/session/session_store_port.rs index fb0f4d8c16..2368c21ae8 100644 --- a/src/crates/assembly/core/src/agentic/session/session_store_port.rs +++ b/src/crates/assembly/core/src/agentic/session/session_store_port.rs @@ -268,6 +268,7 @@ impl SessionStorePort for CoreSessionStorePort { &openbitfun_services_core::workspace_identity::ssh_workspace_identity_host( host, Some(connection_id), + &workspace.root_path.to_string_lossy(), ), &workspace.root_path.to_string_lossy(), ) diff --git a/src/crates/assembly/core/src/service/remote_ssh/workspace_state.rs b/src/crates/assembly/core/src/service/remote_ssh/workspace_state.rs index b39bf0a38d..5e71fb892d 100644 --- a/src/crates/assembly/core/src/service/remote_ssh/workspace_state.rs +++ b/src/crates/assembly/core/src/service/remote_ssh/workspace_state.rs @@ -321,7 +321,7 @@ impl RemoteWorkspaceStateManager { if let Some(host) = remote_ssh_host.map(str::trim).filter(|s| !s.is_empty()) { return runtime_service .context_for_remote_workspace( - &ssh_workspace_identity_host(host, remote_id), + &ssh_workspace_identity_host(host, remote_id, &path_norm), &path_norm, ) .sessions_dir; @@ -330,7 +330,11 @@ impl RemoteWorkspaceStateManager { if !entry.ssh_host.trim().is_empty() { return runtime_service .context_for_remote_workspace( - &ssh_workspace_identity_host(&entry.ssh_host, Some(&entry.connection_id)), + &ssh_workspace_identity_host( + &entry.ssh_host, + Some(&entry.connection_id), + &entry.remote_root, + ), &entry.remote_root, ) .sessions_dir; diff --git a/src/crates/assembly/core/src/service/workspace/legacy_compat.rs b/src/crates/assembly/core/src/service/workspace/legacy_compat.rs index f364ac4c6e..20d79c0d6b 100644 --- a/src/crates/assembly/core/src/service/workspace/legacy_compat.rs +++ b/src/crates/assembly/core/src/service/workspace/legacy_compat.rs @@ -50,6 +50,20 @@ pub(crate) fn resolve_legacy_workspace_reference( }); } let mut candidates: Vec<_> = records.iter().filter(path_matches).collect(); + if connection_id.is_none() { + // A reference without a connection id predates port-scoped SSH + // connections, so it can never name one. Keeping them would make a + // legacy (sshHost, root) reference ambiguous as soon as another port + // of the same host opens the same root. + candidates.retain(|workspace| { + workspace + .remote_ssh_connection_id() + .and_then( + openbitfun_services_core::workspace_identity::ssh_connection_id_port_scope, + ) + .is_none() + }); + } if let Some(id) = connection_id.as_deref() { candidates.retain(|workspace| { workspace.workspace_kind == WorkspaceKind::Remote @@ -74,6 +88,34 @@ pub(crate) fn resolve_legacy_workspace_reference( } } +/// Upgrade-only: keep the host-only identity for port-scoped SSH connections +/// whose persisted records an older host (one that did not understand port +/// scopes) wrote under `remote_workspace_stable_id(host, root)`, so their +/// sessions and runtime data stay where they are after the upgrade. +pub(crate) fn pin_legacy_port_scoped_identities<'a>( + records: impl IntoIterator, +) { + use openbitfun_services_core::workspace_identity as wi; + for record in records { + if record.workspace_kind != WorkspaceKind::Remote { + continue; + } + let (Some(connection_id), Some(host)) = ( + record.remote_ssh_connection_id(), + record + .metadata + .get("sshHost") + .and_then(|value| value.as_str()), + ) else { + continue; + }; + let root = wi::normalize_remote_workspace_path(&record.root_path.to_string_lossy()); + if wi::remote_record_uses_legacy_identity(&record.id, host, connection_id, &root) { + wi::pin_legacy_ssh_workspace_identity(connection_id, &root); + } + } +} + impl WorkspaceService { pub async fn resolve_legacy_workspace_reference( &self, @@ -729,6 +771,80 @@ mod tests { .is_err()); } + #[tokio::test] + async fn record_from_a_host_without_port_scopes_keeps_its_identity() { + use openbitfun_services_core::workspace_identity as wi; + // Old-host payload: a port-scoped id persisted with the host-only stable id. + let connection = "ssh-root@old-host.example#2201"; + let root = "/srv/old-host-payload"; + let legacy_id = wi::remote_workspace_stable_id("old-host.example", root); + assert_eq!( + wi::ssh_workspace_identity_host("old-host.example", Some(connection), root), + "old-host.example#2201" + ); + // Importing the record (the same path as loading persisted data) pins it. + let record = + register_remote_fixture_with_id(root, connection, "old-host.example", Some(&legacy_id)) + .await; + assert_eq!(record.id, legacy_id); + assert_eq!( + wi::ssh_workspace_identity_host("old-host.example", Some(connection), root), + "old-host.example" + ); + assert_eq!( + wi::remote_workspace_stable_id_for_connection( + "old-host.example", + Some(connection), + root + ), + record.id + ); + // Round trip through the persisted shape keeps the same identity. + let round_trip: WorkspaceInfo = + serde_json::from_value(serde_json::to_value(&record).unwrap()).unwrap(); + pin_legacy_port_scoped_identities([&round_trip]); + assert_eq!(round_trip.id, legacy_id); + } + + #[tokio::test] + async fn connectionless_legacy_reference_ignores_port_scoped_records() { + let legacy = + register_remote_fixture("/srv/port-legacy", "ssh-root@cluster", "cluster").await; + let node = + register_remote_fixture("/srv/port-legacy", "ssh-root@cluster#2201", "cluster").await; + assert_ne!(legacy.id, node.id); + let records = [legacy.clone(), node.clone()]; + + // Old session payload: (sshHost, root) with no connection id or workspace id. + let mut json = serde_json::to_value(SessionConfig::default()).unwrap(); + json["workspace_path"] = serde_json::json!("/srv/port-legacy"); + json["remote_ssh_host"] = serde_json::json!("cluster"); + json.as_object_mut().unwrap().remove("remote_connection_id"); + let old: SessionConfig = serde_json::from_value(json).unwrap(); + let resolved = resolve_legacy_workspace_reference( + &records, + None, + old.workspace_path.as_deref().unwrap(), + old.remote_connection_id.as_deref(), + old.remote_ssh_host.as_deref(), + ) + .unwrap() + .unwrap(); + assert_eq!(resolved.id, legacy.id); + + // An explicit port-scoped connection still selects its own record. + let resolved = resolve_legacy_workspace_reference( + &records, + None, + "/srv/port-legacy", + Some("ssh-root@cluster#2201"), + Some("cluster"), + ) + .unwrap() + .unwrap(); + assert_eq!(resolved.id, node.id); + } + #[tokio::test] async fn workspace_kind_controls_legacy_identity_and_path_resolution() { let root = tempfile::tempdir().unwrap(); diff --git a/src/crates/assembly/core/src/service/workspace/service.rs b/src/crates/assembly/core/src/service/workspace/service.rs index 5564d5e868..03deea13c4 100644 --- a/src/crates/assembly/core/src/service/workspace/service.rs +++ b/src/crates/assembly/core/src/service/workspace/service.rs @@ -238,6 +238,7 @@ impl WorkspaceService { openbitfun_services_core::workspace_identity::ssh_workspace_identity_host( ssh_host, workspace.remote_ssh_connection_id(), + &workspace.root_path.to_string_lossy(), ); self.runtime_service .ensure_remote_workspace_runtime( @@ -1931,6 +1932,7 @@ impl WorkspaceService { warnings: Vec::new(), }; + super::legacy_compat::pin_legacy_port_scoped_identities(&export.workspaces); let mut manager = self.manager.write().await; for workspace in export.workspaces { @@ -2068,6 +2070,7 @@ impl WorkspaceService { || !self.is_miniapp_owned_path(&workspace.root_path) }); + super::legacy_compat::pin_legacy_port_scoped_identities(data.workspaces.values()); let mut manager = self.manager.write().await; *manager.get_workspaces_mut() = data.workspaces; manager.restore_assistant_name_sequence(data.assistant_name_sequence); diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index fa268d4b0c..3e852ddd9f 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:ee62faff5c97f12a", + "digest": "fnv1a64:96f7c9d0efb48c2a", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -33,6 +33,7 @@ "miniapp_agent_context_files_v1", "miniapp_agent_images_v1", "wsl_workspaces_v1", + "ssh_port_scoped_identity_v1", "computer_use_sharing_v1", "product_control_v1", "remote_connect_control_v1", @@ -75,6 +76,7 @@ "miniapp_agent_context_files_v1", "miniapp_agent_images_v1", "wsl_workspaces_v1", + "ssh_port_scoped_identity_v1", "computer_use_sharing_v1", "product_control_v1", "remote_connect_control_v1", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 038a3dd378..b1fbfaf031 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -69,6 +69,10 @@ pub enum PeerHostCapability { MiniappAgentImagesV1, /// WSL profiles and discovery are understood; availability is probed on the host. WslWorkspacesV1, + /// SSH profiles on the same host that differ only by port are distinct: + /// `ssh-user@host#port` connection ids get their own saved profile, + /// workspace identity, and session store. + SshPortScopedIdentityV1, /// User-selected native window sharing and explicit permission receipts. ComputerUseSharingV1, /// `product_control_invoke` is implemented (shared config contract). @@ -129,6 +133,7 @@ impl PeerHostCapability { Self::MiniappAgentContextFilesV1, Self::MiniappAgentImagesV1, Self::WslWorkspacesV1, + Self::SshPortScopedIdentityV1, Self::ComputerUseSharingV1, Self::ProductControlV1, Self::RemoteConnectControlV1, @@ -174,6 +179,7 @@ impl PeerHostCapability { Self::MiniappAgentContextFilesV1 => "miniapp_agent_context_files_v1", Self::MiniappAgentImagesV1 => "miniapp_agent_images_v1", Self::WslWorkspacesV1 => "wsl_workspaces_v1", + Self::SshPortScopedIdentityV1 => "ssh_port_scoped_identity_v1", Self::ComputerUseSharingV1 => "computer_use_sharing_v1", Self::ProductControlV1 => "product_control_v1", Self::RemoteConnectControlV1 => "remote_connect_control_v1", @@ -201,8 +207,8 @@ impl PeerHostCapability { const DESKTOP_CAPABILITIES: &[PeerHostCapability] = PeerHostCapability::ALL; -/// The CLI peer host has no MiniApp runtime, WSL connection setup, host-native -/// ProductControl providers, or presentation surface. +/// The CLI peer host has no MiniApp runtime, WSL or SSH connection setup, +/// host-native ProductControl providers, or presentation surface. const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::ModelRoutingV1, PeerHostCapability::ModelPoolSelectionV1, @@ -315,6 +321,11 @@ mod tests { true ); assert!(!cli.contains_key("product_control_native_v1")); + assert!(!cli.contains_key("ssh_port_scoped_identity_v1")); + assert_eq!( + capability_map(PeerHostKind::Desktop).get("ssh_port_scoped_identity_v1"), + Some(&Value::Bool(true)) + ); assert!(!cli.contains_key("product_control_presentation_v1")); assert!(!cli.contains_key("whole_session_copy_v1")); assert!(!cli.contains_key("review_platform_v1")); diff --git a/src/crates/services/services-core/src/session_recovery/identity.rs b/src/crates/services/services-core/src/session_recovery/identity.rs index 2468bcb66f..1e65c9caa8 100644 --- a/src/crates/services/services-core/src/session_recovery/identity.rs +++ b/src/crates/services/services-core/src/session_recovery/identity.rs @@ -85,10 +85,20 @@ fn host(record: &Value) -> Result { pub(super) fn runtime_key(record: &Value) -> Result { let root = record_root(record)?; if string(record, "workspaceKind") == Some("remote") { - let identity_host = wi::ssh_workspace_identity_host( - &host(record)?, - string(&record["metadata"], "connectionId"), - ); + let host = host(record)?; + let connection_id = string(&record["metadata"], "connectionId"); + let root_norm = remote_path(&root)?; + // A record an older host wrote keeps the host-only identity it was stored under. + let legacy_record = connection_id.is_some_and(|connection_id| { + string(record, "id").is_some_and(|id| { + wi::remote_record_uses_legacy_identity(id, &host, connection_id, &root_norm) + }) + }); + let identity_host = if legacy_record { + host.clone() + } else { + wi::ssh_workspace_identity_host(&host, connection_id, &root_norm) + }; Ok(wi::remote_workspace_runtime_key( &identity_host, &remote_path(&root)?, diff --git a/src/crates/services/services-core/src/workspace_identity.rs b/src/crates/services/services-core/src/workspace_identity.rs index be0ce150b0..d18b1c62d1 100644 --- a/src/crates/services/services-core/src/workspace_identity.rs +++ b/src/crates/services/services-core/src/workspace_identity.rs @@ -1,7 +1,9 @@ //! Remote SSH workspace path and identity helpers. use sha2::{Digest, Sha256}; +use std::collections::HashSet; use std::path::{Path, PathBuf}; +use std::sync::{OnceLock, RwLock}; /// SSH host label for local disk workspaces (`Normal` / `Assistant`). pub const LOCAL_WORKSPACE_SSH_HOST: &str = "localhost"; @@ -27,7 +29,11 @@ impl WorkspaceSessionIdentity { /// Host string for runtime and session paths; see [`ssh_workspace_identity_host`]. pub fn identity_host(&self) -> String { - ssh_workspace_identity_host(&self.hostname, self.remote_connection_id.as_deref()) + ssh_workspace_identity_host( + &self.hostname, + self.remote_connection_id.as_deref(), + &self.logical_workspace_path, + ) } } @@ -88,14 +94,30 @@ pub fn ssh_connection_id_for_endpoint(username: &str, host: &str, port: u16) -> } } +/// Prefix of the synthetic host profile the Web UI wraps around a saved SSH +/// connection when it discovers Docker containers on it +/// (`workspace-host-{percent-encoded id}`); container profiles derived from it +/// append `-container-{name}`. +const WORKSPACE_HOST_PREFIX: &str = "workspace-host-"; + /// Port scope carried by a port-scoped SSH connection id. /// /// Returns the text after `#` (a port, optionally followed by a `~{n}` -/// disambiguator) for ids shaped `ssh-{user}@{host}#{scope}` and for container -/// ids derived from them (`...#{scope}-container-{name}`). Legacy ids, including -/// pre-#710 `ssh-{user}@{host}:{port}` ids, return `None`. -pub fn ssh_connection_id_port_scope(connection_id: &str) -> Option<&str> { - let rest = connection_id.trim().strip_prefix("ssh-")?; +/// disambiguator) for ids shaped `ssh-{user}@{host}#{scope}`, for container +/// ids derived from them (`...#{scope}-container-{name}`), and for synthetic +/// container-host wrappers around them (`workspace-host-{encoded id}...`). +/// Legacy ids, including pre-#710 `ssh-{user}@{host}:{port}` ids and wrappers +/// around them, return `None`. +pub fn ssh_connection_id_port_scope(connection_id: &str) -> Option { + let id = connection_id.trim(); + if let Some(wrapped) = id.strip_prefix(WORKSPACE_HOST_PREFIX) { + return direct_port_scope(&percent_decode(wrapped)?).map(str::to_string); + } + direct_port_scope(id).map(str::to_string) +} + +fn direct_port_scope(id: &str) -> Option<&str> { + let rest = id.strip_prefix("ssh-")?; let at = rest.find('@')?; let after_at = &rest[at + 1..]; let separator = after_at.find(SSH_CONNECTION_ID_PORT_SEPARATOR)?; @@ -117,6 +139,74 @@ pub fn ssh_connection_id_port_scope(connection_id: &str) -> Option<&str> { Some(scope) } +/// `decodeURIComponent` for the ids the Web UI encodes; `None` on malformed input. +fn percent_decode(value: &str) -> Option { + let bytes = value.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'%' { + let hex = value.get(index + 1..index + 3)?; + out.push(u8::from_str_radix(hex, 16).ok()?); + index += 3; + } else { + out.push(bytes[index]); + index += 1; + } + } + String::from_utf8(out).ok() +} + +/// `(connection id, normalized remote root)` pairs pinned to the legacy identity. +fn legacy_identity_records() -> &'static RwLock> { + static PINNED: OnceLock>> = OnceLock::new(); + PINNED.get_or_init(|| RwLock::new(HashSet::new())) +} + +fn legacy_identity_key(connection_id: &str, remote_root: &str) -> (String, String) { + ( + connection_id.trim().to_string(), + normalize_remote_workspace_path(remote_root), + ) +} + +/// Whether a persisted remote workspace record proves that its port-scoped +/// connection was registered with the legacy host-only identity: a host that +/// did not understand port scopes stored it under +/// `remote_workspace_stable_id(host, root)`. +pub fn remote_record_uses_legacy_identity( + record_id: &str, + ssh_host: &str, + connection_id: &str, + remote_root_norm: &str, +) -> bool { + ssh_connection_id_port_scope(connection_id).is_some() + && record_id.trim() == remote_workspace_stable_id(ssh_host, remote_root_norm) +} + +/// Keep the host-only identity for one persisted `(connection, root)` record +/// of a port-scoped connection in this process. +/// +/// Called when persisted workspace records are loaded, so data an older host +/// wrote under the legacy identity stays where it is after an upgrade. The pin +/// is per root: other workspaces of the same connection keep their port-scoped +/// identity. +pub fn pin_legacy_ssh_workspace_identity(connection_id: &str, remote_root: &str) { + if connection_id.trim().is_empty() || ssh_connection_id_port_scope(connection_id).is_none() { + return; + } + if let Ok(mut pinned) = legacy_identity_records().write() { + pinned.insert(legacy_identity_key(connection_id, remote_root)); + } +} + +fn legacy_identity_pinned(connection_id: &str, remote_root: &str) -> bool { + legacy_identity_records() + .read() + .map(|pinned| pinned.contains(&legacy_identity_key(connection_id, remote_root))) + .unwrap_or(false) +} + /// SSH host string used for workspace identity (stable id, runtime key, and /// session mirror path). /// @@ -125,9 +215,19 @@ pub fn ssh_connection_id_port_scope(connection_id: &str) -> Option<&str> { /// so their workspace identity and on-disk layout stay byte-for-byte the same. /// Port-scoped connections return `{ssh_host}#{scope}`; `#` never appears in a /// real SSH host, so these identities cannot collide with legacy ones and are -/// a safe path component on every client OS. -pub fn ssh_workspace_identity_host(ssh_host: &str, connection_id: Option<&str>) -> String { - match connection_id.and_then(ssh_connection_id_port_scope) { +/// a safe path component on every client OS. A root of a port-scoped +/// connection whose record was written with the legacy identity (see +/// [`pin_legacy_ssh_workspace_identity`]) keeps `ssh_host`. +pub fn ssh_workspace_identity_host( + ssh_host: &str, + connection_id: Option<&str>, + remote_root: &str, +) -> String { + let Some(connection_id) = connection_id else { + return ssh_host.to_string(); + }; + match ssh_connection_id_port_scope(connection_id) { + Some(_) if legacy_identity_pinned(connection_id, remote_root) => ssh_host.to_string(), Some(scope) => format!( "{}{SSH_CONNECTION_ID_PORT_SEPARATOR}{scope}", ssh_host.trim() @@ -143,7 +243,7 @@ pub fn remote_workspace_stable_id_for_connection( remote_root_norm: &str, ) -> String { remote_workspace_stable_id( - &ssh_workspace_identity_host(ssh_host, connection_id), + &ssh_workspace_identity_host(ssh_host, connection_id, remote_root_norm), remote_root_norm, ) } @@ -488,7 +588,8 @@ pub fn build_project_runtime_slug(canonical: &str) -> String { #[cfg(test)] mod tests { use super::{ - canonical_ssh_connection_id, remote_workspace_runtime_key, + canonical_ssh_connection_id, pin_legacy_ssh_workspace_identity, + remote_record_uses_legacy_identity, remote_workspace_runtime_key, remote_workspace_session_mirror_dir, remote_workspace_stable_id, remote_workspace_stable_id_for_connection, ssh_connection_id_for_endpoint, ssh_connection_id_port_scope, ssh_workspace_identity_host, @@ -511,19 +612,19 @@ mod tests { fn port_scope_is_parsed_only_from_port_scoped_ids() { assert_eq!( ssh_connection_id_port_scope("ssh-root@example.com#2222"), - Some("2222") + Some("2222".to_string()) ); assert_eq!( ssh_connection_id_port_scope("ssh-root@example.com#2222~2"), - Some("2222~2") + Some("2222~2".to_string()) ); assert_eq!( ssh_connection_id_port_scope("ssh-root@example.com#2222-container-web"), - Some("2222") + Some("2222".to_string()) ); assert_eq!( ssh_connection_id_port_scope("ssh-root@fe80::1#2201"), - Some("2201") + Some("2201".to_string()) ); // Every id shape written by released builds stays legacy. for legacy in [ @@ -553,7 +654,7 @@ mod tests { Some("ssh-root@example.com-container-web"), ] { assert_eq!( - ssh_workspace_identity_host("example.com", connection_id), + ssh_workspace_identity_host("example.com", connection_id, "/home/user/repo"), "example.com" ); assert_eq!( @@ -581,7 +682,11 @@ mod tests { assert_ne!(port_b, legacy); assert_ne!(port_a, port_b); assert_eq!( - ssh_workspace_identity_host(" Example.com ", Some("ssh-u@example.com#2201")), + ssh_workspace_identity_host( + " Example.com ", + Some("ssh-u@example.com#2201"), + "/home/user/repo" + ), "Example.com#2201" ); assert_ne!( @@ -590,7 +695,11 @@ mod tests { ); let mirror = remote_workspace_session_mirror_dir( Path::new("/mirror"), - &ssh_workspace_identity_host("example.com", Some("ssh-u@example.com#2201")), + &ssh_workspace_identity_host( + "example.com", + Some("ssh-u@example.com#2201"), + "/home/user/repo", + ), root, ); assert_eq!( @@ -604,6 +713,114 @@ mod tests { ); } + #[test] + fn synthetic_container_host_wrappers_keep_the_wrapped_port_scope() { + assert_eq!( + ssh_connection_id_port_scope("workspace-host-ssh-root%40cluster%232201-container-web"), + Some("2201".to_string()) + ); + assert_eq!( + ssh_connection_id_port_scope("workspace-host-ssh-root%40cluster%232201"), + Some("2201".to_string()) + ); + // Wrappers around legacy ids written by released builds stay legacy. + for legacy in [ + "workspace-host-ssh-root%40cluster-container-web", + "workspace-host-ssh-root%40cluster%3A2201-container-web", + "workspace-host-%ZZ", + ] { + assert_eq!(ssh_connection_id_port_scope(legacy), None, "{legacy}"); + } + assert_ne!( + ssh_workspace_identity_host( + "cluster", + Some("workspace-host-ssh-root%40cluster%232201-container-web"), + "/home/user/repo" + ), + ssh_workspace_identity_host( + "cluster", + Some("workspace-host-ssh-root%40cluster%232202-container-web"), + "/home/user/repo" + ) + ); + } + + #[test] + fn records_written_with_the_legacy_identity_pin_their_connection() { + let root = "/srv/pinned"; + let connection = "ssh-root@pinned.example#2201"; + let legacy_id = remote_workspace_stable_id("pinned.example", root); + assert!(remote_record_uses_legacy_identity( + &legacy_id, + "pinned.example", + connection, + root + )); + assert!(!remote_record_uses_legacy_identity( + &remote_workspace_stable_id_for_connection("pinned.example", Some(connection), root), + "pinned.example", + connection, + root + )); + assert!(!remote_record_uses_legacy_identity( + &legacy_id, + "pinned.example", + "ssh-root@pinned.example", + root + )); + + assert_eq!( + ssh_workspace_identity_host("pinned.example", Some(connection), root), + "pinned.example#2201" + ); + pin_legacy_ssh_workspace_identity(connection, root); + assert_eq!( + ssh_workspace_identity_host("pinned.example", Some(connection), root), + "pinned.example" + ); + assert_eq!( + remote_workspace_stable_id_for_connection("pinned.example", Some(connection), root), + legacy_id + ); + // Other ports of the same host are unaffected. + assert_eq!( + ssh_workspace_identity_host( + "pinned.example", + Some("ssh-root@pinned.example#2202"), + root + ), + "pinned.example#2202" + ); + } + + #[test] + fn loading_one_legacy_root_does_not_reidentify_another_root_on_the_same_connection() { + let host = "mixed-records.example"; + let connection = "ssh-root@mixed-records.example#2201"; + let legacy_root = "/srv/legacy"; + let scoped_root = "/srv/scoped"; + let legacy_id = remote_workspace_stable_id(host, legacy_root); + assert!(remote_record_uses_legacy_identity( + &legacy_id, + host, + connection, + legacy_root + )); + let scoped_id = + remote_workspace_stable_id_for_connection(host, Some(connection), scoped_root); + pin_legacy_ssh_workspace_identity(connection, legacy_root); + assert_eq!( + remote_workspace_stable_id_for_connection(host, Some(connection), legacy_root), + legacy_id, + "the pinned record keeps its legacy identity" + ); + assert_eq!( + remote_workspace_stable_id_for_connection(host, Some(connection), scoped_root), + scoped_id, + "loading a different legacy record must not move an existing workspace's identity" + ); + } + #[test] fn canonical_ssh_connection_id_never_collapses_port_scoped_ids() { assert_eq!( diff --git a/src/mobile-web/src/services/workspaceIdentity.ts b/src/mobile-web/src/services/workspaceIdentity.ts index b4f6b649eb..9f8e039a5d 100644 --- a/src/mobile-web/src/services/workspaceIdentity.ts +++ b/src/mobile-web/src/services/workspaceIdentity.ts @@ -62,6 +62,24 @@ export interface WorkspaceReference { remote_ssh_host?: string; } +/** + * Port-scoped SSH connection ids (`ssh-user@host#port`, also wrapped as + * `workspace-host-...`) name a distinct connection per port. + * Mirrors `ssh_connection_id_port_scope` in the Rust workspace identity owner. + */ +export function isPortScopedSshConnectionId(connectionId: string | null | undefined): boolean { + let id = (connectionId ?? '').trim(); + if (id.startsWith('workspace-host-')) { + try { + id = decodeURIComponent(id.slice('workspace-host-'.length)); + } catch { + return false; + } + } + const match = /^ssh-[^@]*@[^#]*#(\d+)(?:~\d+)?(?:-.*)?$/.exec(id); + return match !== null && Number(match[1]) <= 65535; +} + function trimmedText(value: string | null | undefined): string | undefined { const text = value?.trim(); return text ? text : undefined; @@ -123,6 +141,8 @@ export function resolveLegacyWorkspaceReference( const connection = trimmedText(reference.remote_connection_id); const host = trimmedText(reference.remote_ssh_host); const matches = catalog.filter((candidate) => normalizedLegacyRoot(candidate.path) === root + // A reference without a connection id predates port-scoped SSH profiles. + && (connection || !isPortScopedSshConnectionId(candidate.remote_connection_id)) && (!connection || candidate.remote_connection_id === connection) && (!host || (!connection && host === 'localhost') diff --git a/src/mobile-web/tests/workspace-identity.test.mjs b/src/mobile-web/tests/workspace-identity.test.mjs index 77d1fd9634..a83badae0f 100644 --- a/src/mobile-web/tests/workspace-identity.test.mjs +++ b/src/mobile-web/tests/workspace-identity.test.mjs @@ -432,3 +432,12 @@ test('workspace icons reject future formats and external image URLs without loca assert.equal(calls, 1); } }); + +test('connection-less legacy references never resolve to port-scoped SSH workspaces', () => { + const legacy = { workspace_id: 'ws-legacy', path: '/srv/app', remote_connection_id: 'ssh-root@cluster', remote_ssh_host: 'cluster' }; + const node = { workspace_id: 'ws-node', path: '/srv/app', remote_connection_id: 'ssh-root@cluster#2201', remote_ssh_host: 'cluster' }; + // Old cached reference: host and root without a connection id. + assert.equal(resolveLegacyWorkspaceReference({ path: '/srv/app', remote_ssh_host: 'cluster' }, [legacy, node]), legacy); + assert.equal(resolveLegacyWorkspaceReference( + { path: '/srv/app', remote_connection_id: 'ssh-root@cluster#2201', remote_ssh_host: 'cluster' }, [legacy, node]), node); +}); diff --git a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx index 47fa42fd8e..5702f4e6c6 100644 --- a/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx +++ b/src/web-ui/src/features/ssh-remote/SSHConnectionDialog.tsx @@ -54,7 +54,7 @@ import { workspaceSourceErrorKey, isSshAuthenticationError } from './workspaceSo import { savedConnectionConfig } from './savedConnectionConfig'; import type { WorkspaceConnectionPreset } from './useWorkspaceSourceOptions'; import { sameWorkspaceSource, savedConnectionTarget } from './workspaceSource'; -import { sshConnectionIdForEndpoint } from './sshConnectionId'; +import { resolveNewSshConnectionId } from './resolveSshConnectionId'; import { pickSshCertificatePath, pickSshPrivateKeyPath, @@ -390,6 +390,7 @@ export const SSHConnectionDialog: React.FC = ({ const buildConnectionConfig = async ( requireContainer: boolean, + persistsProfile = true, ): Promise => { if (formData.targetType === 'wsl') { if (!editOnly && !wslDistributions?.supported) { @@ -513,20 +514,27 @@ export const SSHConnectionDialog: React.FC = ({ const containerName = formData.containerName.trim() || (formData.targetType === 'containerSshd' ? connectHost : 'discovery'); // Editing keeps the saved id (so a port change never moves sessions); // new profiles get a port-aware id that cannot overwrite another endpoint. - const knownConnections = editingProfile || isLocalDocker - ? savedConnections - : await sshApi.listSavedConnections().catch(() => savedConnections); - const id = isLocalDocker - ? `docker-local-${containerName}` - : sshConnectionIdForEndpoint( + let id = editingProfile?.id ?? `docker-local-${containerName}`; + if (!editingProfile && !isLocalDocker) { + const resolved = await resolveNewSshConnectionId( { host: connectHost, port, username, suffix: usesContainer ? `-container-${containerName}` : '' }, - knownConnections, connection => !connection.wsl && (usesContainer ? !connection.container?.local && connection.container?.name === containerName : !connection.container), ); + if (!('error' in resolved)) { + id = resolved.id; + } else if (!persistsProfile) { + id = resolved.transientId; + } else { + setLocalError(resolved.error === 'portScopedIdentityUnsupported' + ? t('ssh.remote.portScopedIdentityUnsupported', { connection: resolved.conflict.name || resolved.conflict.id }) + : t('workspaceSource.hostDiscoveryFailed')); + return null; + } + } return { - id: editingProfile?.id ?? id, + id, name: formData.name || (isLocalDocker ? containerName : `${username}@${hostInput}`), host: connectHost, port, @@ -599,7 +607,7 @@ export const SSHConnectionDialog: React.FC = ({ setConnectionTest(null); setLocalError(null); try { - const config = await buildConnectionConfig(true); + const config = await buildConnectionConfig(true, false); if (!config) return; setConnectionTest(await sshApi.testConnection(config)); } catch (_error) { @@ -614,7 +622,7 @@ export const SSHConnectionDialog: React.FC = ({ setIsListingContainers(true); setLocalError(null); try { - const config = await buildConnectionConfig(false); + const config = await buildConnectionConfig(false, false); if (!config || requestId !== containerRequestId.current || !scope.isCurrent()) return; const containers = await sshApi.listDockerContainers(config); if (requestId !== containerRequestId.current || !scope.isCurrent()) return; diff --git a/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts b/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts new file mode 100644 index 0000000000..b005dd5bc7 --- /dev/null +++ b/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts @@ -0,0 +1,80 @@ +import { getActiveSurfaceScope, isLocalSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { globalAPI } from '@/infrastructure/api/service-api/GlobalAPI'; +import { createLogger } from '@/shared/utils/logger'; +import { sshApi } from './sshApi'; +import { + DEFAULT_SSH_PORT, + legacySshEndpointConflict, + sshConnectionIdForEndpoint, + type SshEndpoint, +} from './sshConnectionId'; +import type { SavedConnection } from './types'; + +const log = createLogger('ResolveSshConnectionId'); + +/** + * Failures carry `transientId`, an id the host accepts for requests that do + * not persist a profile (connection tests, container discovery). + */ +export type NewSshConnectionId = + | { id: string } + /** The saved profiles are unknown, so any id could overwrite one of them. */ + | { error: 'savedConnectionsUnavailable'; transientId: string } + /** The host predates port-scoped ids and would replace another port's profile. */ + | { error: 'portScopedIdentityUnsupported'; conflict: SavedConnection; transientId: string }; + +/** + * Whether the active host understands port-scoped SSH ids + * (`ssh-user@host#port`). Peer hosts must advertise `ssh_port_scoped_identity_v1`; + * older hosts would treat such an id as a different, unscoped connection. + */ +export async function activeHostSupportsPortScopedSshIds(): Promise { + const scope = getActiveSurfaceScope(); + if (isLocalSurface(scope.surfaceId)) return true; + const { peerConnectionManager } = await import('@/infrastructure/peer-device/PeerConnectionManager'); + scope.assertCurrent('negotiate SSH connection identity'); + return peerConnectionManager.get(scope.surfaceId)?.getState().capabilities.sshPortScopedIdentityV1 === true; +} + +async function referencedRemoteConnectionIds(): Promise { + try { + const [opened, recent] = await Promise.all([globalAPI.getOpenedWorkspaces(), globalAPI.getRecentWorkspaces()]); + return [...opened, ...recent].flatMap(workspace => + workspace.workspaceKind === 'remote' && workspace.connectionId ? [workspace.connectionId] : []); + } catch (error) { + // Only the reuse of an orphaned legacy id depends on this list. + log.warn('Failed to list workspace records for SSH connection id reuse', { error }); + return []; + } +} + +/** + * Id for a new SSH profile on the active host, resolved against the profiles + * it already saved. Pass `saved` when the caller already listed them. + */ +export async function resolveNewSshConnectionId( + endpoint: SshEndpoint, + isSameTarget: (connection: SavedConnection) => boolean, + saved?: readonly SavedConnection[], +): Promise { + const portScopedIds = await activeHostSupportsPortScopedSshIds(); + let connections = saved; + if (!connections) { + try { + connections = await sshApi.listSavedConnections(); + } catch (error) { + log.warn('Failed to list saved SSH connections for a new profile id', { error }); + return { + error: 'savedConnectionsUnavailable', + transientId: sshConnectionIdForEndpoint(endpoint, [], isSameTarget, { portScopedIds }), + }; + } + } + if (!portScopedIds) { + const id = sshConnectionIdForEndpoint(endpoint, connections, isSameTarget, { portScopedIds }); + const conflict = legacySshEndpointConflict(endpoint, connections, isSameTarget); + return conflict ? { error: 'portScopedIdentityUnsupported', conflict, transientId: id } : { id }; + } + const referencedIds = endpoint.port === DEFAULT_SSH_PORT ? [] : await referencedRemoteConnectionIds(); + return { id: sshConnectionIdForEndpoint(endpoint, connections, isSameTarget, { referencedIds }) }; +} diff --git a/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts b/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts index 7cda2bd0c3..3368411c45 100644 --- a/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts +++ b/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts @@ -1,11 +1,41 @@ -import { describe, expect, it } from 'vitest'; -import { sshConnectionIdForEndpoint } from './sshConnectionId'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { legacySshEndpointConflict, sshConnectionIdForEndpoint } from './sshConnectionId'; import type { SavedConnection } from './types'; +import { canonicalSshConnectionId, sshConnectionIdPortScope } from '@/shared/utils/sshConnectionIdentity'; + +const api = vi.hoisted(() => ({ listSavedConnections: vi.fn() })); +const workspaces = vi.hoisted(() => ({ opened: vi.fn(), recent: vi.fn() })); +const surface = vi.hoisted(() => ({ local: true, portScoped: false })); +vi.mock('./sshApi', () => ({ sshApi: api })); +vi.mock('@/infrastructure/api/service-api/GlobalAPI', () => ({ + globalAPI: { getOpenedWorkspaces: workspaces.opened, getRecentWorkspaces: workspaces.recent }, +})); +vi.mock('@/infrastructure/peer-device/deviceSurface', async importOriginal => ({ + ...await importOriginal(), + getActiveSurfaceScope: () => ({ surfaceId: surface.local ? 'local' : 'peer-1', assertCurrent: () => undefined }), + isLocalSurface: (id: string) => id === 'local', +})); +vi.mock('@/infrastructure/peer-device/PeerConnectionManager', () => ({ + peerConnectionManager: { get: () => ({ getState: () => ({ capabilities: { sshPortScopedIdentityV1: surface.portScoped } }) }) }, +})); const saved = (id: string, host: string, port: number, username = 'root', extra: Partial = {}): SavedConnection => ({ id, name: id, host, port, username, authType: { type: 'Agent' }, ...extra, }); +describe('ssh connection id grammar', () => { + it('parses port scopes, including synthetic container hosts, and never legacy ids', () => { + expect(sshConnectionIdPortScope('ssh-root@cluster#2201')).toBe('2201'); + expect(sshConnectionIdPortScope('ssh-root@cluster#2201~2-container-web')).toBe('2201~2'); + expect(sshConnectionIdPortScope(`workspace-host-${encodeURIComponent('ssh-root@cluster#2201')}-container-web`)).toBe('2201'); + for (const legacy of ['ssh-root@cluster', 'ssh-root@cluster:2201', `workspace-host-${encodeURIComponent('ssh-root@cluster:2201')}-container-web`, 'workspace-host-%ZZ']) { + expect(sshConnectionIdPortScope(legacy)).toBeUndefined(); + } + expect(canonicalSshConnectionId('ssh-root@cluster:2222')).toBe('ssh-root@cluster'); + expect(canonicalSshConnectionId('ssh-root@cluster#2222')).toBe('ssh-root@cluster#2222'); + }); +}); + describe('sshConnectionIdForEndpoint', () => { it('keeps the legacy id for the default port', () => { expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' })).toBe('ssh-root@cluster'); @@ -29,6 +59,24 @@ describe('sshConnectionIdForEndpoint', () => { expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2202, username: 'root' }, connections)).toBe('ssh-root@cluster#2202~2'); }); + it('treats a pre-#710 `:port` alias on another port as taken', () => { + // Old saved payload: id written with the port, which workspace records treat as `ssh-root@cluster`. + const connections = [saved('ssh-root@cluster:2222', 'cluster', 2222)]; + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, connections)).toBe('ssh-root@cluster#22'); + }); + + it('reuses an orphaned legacy id that workspace records still reference', () => { + const context = { referencedIds: ['ssh-root@cluster'] }; + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, [], undefined, context)).toBe('ssh-root@cluster'); + // A `:port` alias only reattaches to its own port. + const alias = { referencedIds: ['ssh-root@cluster:2201'] }; + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, [], undefined, alias)).toBe('ssh-root@cluster:2201'); + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2202, username: 'root' }, [], undefined, alias)).toBe('ssh-root@cluster#2202'); + // Owned ids are never reused for another port. + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, + [saved('ssh-root@cluster', 'cluster', 22)], undefined, context)).toBe('ssh-root@cluster#2201'); + }); + it('only reuses profiles of the same target kind', () => { const connections = [saved('ssh-root@cluster', 'cluster', 22, 'root', { container: { name: 'web', local: false, access: 'auto', dockerPath: 'docker', shell: '/bin/sh', interactive: true }, @@ -36,4 +84,48 @@ describe('sshConnectionIdForEndpoint', () => { expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, connections, connection => !connection.container)) .toBe('ssh-root@cluster#22'); }); + + it('keeps legacy ids for hosts without port-scoped identity and reports the profile they would replace', () => { + const connections = [saved('ssh-root@cluster', 'cluster', 2201)]; + const endpoint = { host: 'cluster', port: 2202, username: 'root' }; + expect(sshConnectionIdForEndpoint(endpoint, connections, undefined, { portScopedIds: false })).toBe('ssh-root@cluster'); + expect(legacySshEndpointConflict(endpoint, connections)?.id).toBe('ssh-root@cluster'); + expect(legacySshEndpointConflict({ ...endpoint, port: 2201 }, connections)).toBeUndefined(); + expect(legacySshEndpointConflict({ ...endpoint, host: 'other' }, connections)).toBeUndefined(); + }); +}); + +describe('resolveNewSshConnectionId', () => { + beforeEach(() => { + surface.local = true; + surface.portScoped = false; + api.listSavedConnections.mockReset(); + workspaces.opened.mockResolvedValue([]); + workspaces.recent.mockResolvedValue([]); + }); + + it('resolves against the saved profiles of the active host', async () => { + const { resolveNewSshConnectionId } = await import('./resolveSshConnectionId'); + api.listSavedConnections.mockResolvedValue([saved('ssh-root@cluster', 'cluster', 2201)]); + await expect(resolveNewSshConnectionId({ host: 'cluster', port: 22, username: 'root' }, () => true)) + .resolves.toEqual({ id: 'ssh-root@cluster#22' }); + }); + + it('refuses to pick an id when the saved profiles are unknown', async () => { + const { resolveNewSshConnectionId } = await import('./resolveSshConnectionId'); + api.listSavedConnections.mockRejectedValue(new Error('offline')); + const resolved = await resolveNewSshConnectionId({ host: 'cluster', port: 22, username: 'root' }, () => true); + expect(resolved).toMatchObject({ error: 'savedConnectionsUnavailable' }); + }); + + it('blocks a second port on an older peer host and keeps the legacy id', async () => { + const { resolveNewSshConnectionId } = await import('./resolveSshConnectionId'); + surface.local = false; + const connections = [saved('ssh-root@cluster', 'cluster', 2201)]; + const resolved = await resolveNewSshConnectionId({ host: 'cluster', port: 2202, username: 'root' }, () => true, connections); + expect(resolved).toMatchObject({ error: 'portScopedIdentityUnsupported', transientId: 'ssh-root@cluster' }); + surface.portScoped = true; + await expect(resolveNewSshConnectionId({ host: 'cluster', port: 2202, username: 'root' }, () => true, connections)) + .resolves.toEqual({ id: 'ssh-root@cluster#2202' }); + }); }); diff --git a/src/web-ui/src/features/ssh-remote/sshConnectionId.ts b/src/web-ui/src/features/ssh-remote/sshConnectionId.ts index dc81ed1ec5..d4ca7422ff 100644 --- a/src/web-ui/src/features/ssh-remote/sshConnectionId.ts +++ b/src/web-ui/src/features/ssh-remote/sshConnectionId.ts @@ -1,4 +1,5 @@ import type { SavedConnection } from './types'; +import { canonicalSshConnectionId, sshConnectionIdAliasPort } from '@/shared/utils/sshConnectionIdentity'; export const DEFAULT_SSH_PORT = 22; @@ -10,7 +11,7 @@ export const DEFAULT_SSH_PORT = 22; */ const PORT_SEPARATOR = '#'; -interface SshEndpoint { +export interface SshEndpoint { host: string; port: number; username: string; @@ -18,11 +19,27 @@ interface SshEndpoint { suffix?: string; } +export interface SshConnectionIdContext { + /** + * Connection ids referenced by workspace records on the target host. A + * legacy port-less id that no saved profile owns any more is reused for a + * non-default port, so re-adding a deleted legacy profile finds its sessions. + */ + referencedIds?: readonly string[]; + /** + * False when the target host predates port-scoped ids (it does not advertise + * `ssh_port_scoped_identity_v1`); new profiles then keep the legacy id. + */ + portScopedIds?: boolean; +} + const sameEndpoint = (connection: SavedConnection, endpoint: SshEndpoint) => connection.host === endpoint.host && connection.port === endpoint.port && connection.username === endpoint.username; +const legacyIdFor = (endpoint: SshEndpoint) => `ssh-${endpoint.username}@${endpoint.host}${endpoint.suffix ?? ''}`; + /** * Connection id for a new SSH profile. * @@ -31,24 +48,50 @@ const sameEndpoint = (connection: SavedConnection, endpoint: SshEndpoint) => * differ only by port stay distinct connections and workspaces. * - A saved profile for the same endpoint keeps its existing id, so legacy * port-less ids for non-default ports are reused instead of replaced. - * - An id already owned by a profile for another endpoint is never reused; - * the port-scoped form (with a `~n` disambiguator when needed) is used. + * - An id already owned by a profile for another endpoint, directly or through + * a pre-#710 `ssh-user@host:port` alias, is never reused; the port-scoped + * form (with a `~n` disambiguator when needed) is used. */ export function sshConnectionIdForEndpoint( endpoint: SshEndpoint, saved: readonly SavedConnection[] = [], isSameTarget: (connection: SavedConnection) => boolean = () => true, + context: SshConnectionIdContext = {}, ): string { const suffix = endpoint.suffix ?? ''; const existing = saved.find(connection => sameEndpoint(connection, endpoint) && isSameTarget(connection)); if (existing) return existing.id; - const taken = (id: string) => saved.some(connection => connection.id === id); - const portLess = `ssh-${endpoint.username}@${endpoint.host}`; - const scoped = `${portLess}${PORT_SEPARATOR}${endpoint.port}`; - const preferred = endpoint.port === DEFAULT_SSH_PORT ? `${portLess}${suffix}` : `${scoped}${suffix}`; + const legacy = legacyIdFor(endpoint); + if (context.portScopedIds === false) return legacy; + + const taken = (id: string) => saved.some(connection => canonicalSshConnectionId(connection.id) === id); + if (endpoint.port !== DEFAULT_SSH_PORT && !taken(legacy)) { + const orphan = context.referencedIds?.find(id => canonicalSshConnectionId(id) === legacy + && (sshConnectionIdAliasPort(id) ?? endpoint.port) === endpoint.port); + if (orphan) return orphan; + } + + const scoped = `ssh-${endpoint.username}@${endpoint.host}${PORT_SEPARATOR}${endpoint.port}`; + const preferred = endpoint.port === DEFAULT_SSH_PORT ? legacy : `${scoped}${suffix}`; if (!taken(preferred)) return preferred; let candidate = `${scoped}${suffix}`; for (let n = 2; taken(candidate); n += 1) candidate = `${scoped}~${n}${suffix}`; return candidate; } + +/** + * Saved profile that a host without port-scoped ids would overwrite when it + * saves `endpoint` under the legacy id: it replaces the same id, its `:port` + * aliases, and any profile for the same host and user regardless of port. + */ +export function legacySshEndpointConflict( + endpoint: SshEndpoint, + saved: readonly SavedConnection[], + isSameTarget: (connection: SavedConnection) => boolean = () => true, +): SavedConnection | undefined { + if (saved.some(connection => sameEndpoint(connection, endpoint) && isSameTarget(connection))) return undefined; + const legacy = legacyIdFor(endpoint); + return saved.find(connection => canonicalSshConnectionId(connection.id) === legacy + || (connection.host === endpoint.host && connection.username === endpoint.username && isSameTarget(connection))); +} diff --git a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx index fc19ed06f5..35c97dbd1f 100644 --- a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx +++ b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx @@ -2,7 +2,7 @@ import React, { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; -import { useWorkspaceSourceOptions, type WorkspaceConnectionPreset } from './useWorkspaceSourceOptions'; +import { useWorkspaceSourceOptions, workspacePresetHost, type WorkspaceConnectionPreset } from './useWorkspaceSourceOptions'; import type { WorkspaceSource } from './workspaceSource'; import { activateSurface, resetDeviceSurfaceForTest, surfaceIdForDevice } from '@/infrastructure/peer-device/deviceSurface'; @@ -115,3 +115,26 @@ it('discards late discovery after a device switch', async () => { await act(async () => resolveOld({ supported: true, distributions: ['Old machine'] })); expect(result.options.map(option => option.label)).toEqual(['Ubuntu']); }); + +it('resolves ~/.ssh/config ids against saved profiles so another port is never overwritten', async () => { + // Saved profile on port 2201 under the port-less legacy id; config entry for port 22. + api.listSavedConnections.mockResolvedValue([{ + id: 'ssh-root@cluster', name: 'Node 1', host: 'cluster', port: 2201, username: 'root', authType: { type: 'Agent' }, + }]); + api.listSSHConfigHosts.mockResolvedValue([{ host: 'cluster-main', hostname: 'cluster', port: 22, user: 'root', agent: true }]); + await render('ssh'); + const preset = result.options.find(option => option.id === 'ssh-config:cluster-main')?.preset; + expect(preset).toMatchObject({ kind: 'sshConfig', connectionId: 'ssh-root@cluster#22' }); + expect(workspacePresetHost(preset)?.id).toBe('ssh-root@cluster#22'); +}); + +it('routes ~/.ssh/config entries to the dialog when saved profiles cannot be listed', async () => { + api.listSavedConnections.mockRejectedValue(new Error('offline')); + api.listSSHConfigHosts.mockResolvedValue([{ host: 'cluster-main', hostname: 'cluster', port: 22, user: 'root', agent: true }]); + await render('ssh'); + const preset = result.options.find(option => option.id === 'ssh-config:cluster-main')?.preset; + expect(preset).toMatchObject({ kind: 'sshConfig' }); + expect(preset && 'connectionId' in preset ? preset.connectionId : undefined).toBeUndefined(); + // No connectable profile: the caller opens the connection dialog instead of a one-click connect. + expect(workspacePresetHost(preset)).toBeUndefined(); +}); diff --git a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts index 5043ee7392..d989a6493d 100644 --- a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts +++ b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts @@ -7,12 +7,14 @@ import { createLogger } from '@/shared/utils/logger'; const log = createLogger('WorkspaceSourceOptions'); import { sameWorkspaceSource, savedConnectionTarget, type WorkspaceSource } from './workspaceSource'; import type { SavedConnection, SSHConfigEntry, SSHConnectionConfig } from './types'; -import { DEFAULT_SSH_PORT, sshConnectionIdForEndpoint } from './sshConnectionId'; +import { DEFAULT_SSH_PORT, type SshEndpoint } from './sshConnectionId'; +import { resolveNewSshConnectionId } from './resolveSshConnectionId'; export type WorkspaceConnectionPreset = ( | { kind: 'new'; host?: SavedConnection } | { kind: 'saved'; connection: SavedConnection } - | { kind: 'sshConfig'; entry: SSHConfigEntry }) & { edit?: boolean; authenticate?: boolean; credentialConnectionId?: string }; + /** `connectionId` is resolved against the host's saved profiles; without it the dialog decides. */ + | { kind: 'sshConfig'; entry: SSHConfigEntry; connectionId?: string }) & { edit?: boolean; authenticate?: boolean; credentialConnectionId?: string }; export interface WorkspaceSourceOption { id: string; @@ -21,19 +23,28 @@ export interface WorkspaceSourceOption { preset: WorkspaceConnectionPreset; } +const sshConfigEndpoint = (entry: SSHConfigEntry): SshEndpoint => ({ + host: entry.hostname || entry.host, port: entry.port || DEFAULT_SSH_PORT, username: entry.user || '', +}); + +/** Connectable profile of a preset; an `sshConfig` entry whose id is unresolved has none. */ export function workspacePresetHost(preset?: WorkspaceConnectionPreset): SavedConnection | undefined { if (preset?.kind === 'saved') return preset.connection; - if (preset?.kind !== 'sshConfig') return undefined; + if (preset?.kind !== 'sshConfig' || !preset.connectionId) return undefined; const { entry } = preset; return { - id: sshConnectionIdForEndpoint({ host: entry.hostname || entry.host, port: entry.port || DEFAULT_SSH_PORT, username: entry.user || '' }), - name: entry.host, host: entry.hostname || entry.host, port: entry.port || 22, username: entry.user || '', + ...sshConfigEndpoint(entry), id: preset.connectionId, name: entry.host, authType: entry.identityFile ? { type: 'PrivateKey', keyPath: entry.identityFile, certificatePath: entry.certificateFile } : entry.agent ? { type: 'Agent' } : { type: 'Password' }, proxyJump: entry.proxyJump, }; } +function presetEndpoint(preset: WorkspaceConnectionPreset) { + if (preset.kind === 'saved') return preset.connection; + return preset.kind === 'sshConfig' ? { ...sshConfigEndpoint(preset.entry), proxyJump: preset.entry.proxyJump } : undefined; +} + function hostDiscoveryConfig(host: SavedConnection, credentialConnectionId?: string): SSHConnectionConfig { const { authType, ...config } = host; return { ...config, id: credentialConnectionId || config.id, container: { name: 'discovery', local: false, access: 'auto', dockerPath: 'docker', shell: '/bin/sh', interactive: true }, @@ -67,7 +78,7 @@ export function useWorkspaceSourceOptions(source: WorkspaceSource, enabled: bool }) : source === 'remoteDocker' && host ? sshApi.listDockerContainers(hostDiscoveryConfig(host, hostPreset?.credentialConnectionId)) : source === 'ssh' ? sshApi.listSSHConfigHosts() : Promise.resolve(null); - void Promise.allSettled([sshApi.listSavedConnections(), discovery]).then(([saved, detected]) => { + void Promise.allSettled([sshApi.listSavedConnections(), discovery]).then(async ([saved, detected]) => { if (cancelled || !scope.isCurrent()) return; const connections = saved.status === 'fulfilled' ? saved.value.filter(connection => sameWorkspaceSource(savedConnectionTarget(connection), source) && (source !== 'remoteDocker' || (host && connection.host === host.host && connection.port === host.port && connection.username === host.username))) : []; @@ -80,7 +91,7 @@ export function useWorkspaceSourceOptions(source: WorkspaceSource, enabled: bool for (const connection of saved.value) { if (!connection.container || connection.container.local || connection.wsl) continue; if (result.some(option => { - const host = workspacePresetHost(option.preset); + const host = presetEndpoint(option.preset); return host?.host === connection.host && host.port === connection.port && host.username === connection.username && host.proxyJump === connection.proxyJump; })) continue; const id = `workspace-host-${encodeURIComponent(connection.id)}`; @@ -119,10 +130,16 @@ export function useWorkspaceSourceOptions(source: WorkspaceSource, enabled: bool } } else if (source === 'ssh') { for (const entry of detected.value as SSHConfigEntry[]) { - if (connections.some(connection => connection.host === (entry.hostname || entry.host) && connection.port === (entry.port || 22) && connection.username === (entry.user || ''))) continue; + const endpoint = sshConfigEndpoint(entry); + if (connections.some(connection => connection.host === endpoint.host && connection.port === endpoint.port && connection.username === endpoint.username)) continue; + // Without the saved profiles any id could overwrite one, so the dialog resolves it on connect. + const resolved = saved.status === 'fulfilled' + ? await resolveNewSshConnectionId(endpoint, connection => !connection.container && !connection.wsl, saved.value) + : undefined; + if (cancelled || !scope.isCurrent()) return; result.push({ id: `ssh-config:${entry.host}`, label: entry.host, - description: `${entry.user || ''}@${entry.hostname || entry.host}:${entry.port || 22}`, - preset: { kind: 'sshConfig', entry } }); + description: `${endpoint.username}@${endpoint.host}:${endpoint.port}`, + preset: { kind: 'sshConfig', entry, ...(resolved && 'id' in resolved ? { connectionId: resolved.id } : {}) } }); } } } diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts index 0f6290ce2c..175a5ca19a 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts @@ -656,6 +656,27 @@ describe('PeerDeviceTransportAdapter queue', () => { }, ); + it.each(['ssh_connect', 'ssh_save_connection', 'ssh_test_connection'])( + 'rejects %s with a port-scoped id before an older peer can treat it as unscoped', async (command) => { + const deviceRpc = vi.fn(); + const adapter = new PeerDeviceTransportAdapter('peer-1', deviceRpc); + await expect(adapter.request(command, { config: { id: 'ssh-root@cluster#2201', host: 'cluster', port: 2201 } })) + .rejects.toThrow('ssh_port_scoped_identity_v1_unsupported'); + expect(deviceRpc).not.toHaveBeenCalled(); + }, + ); + + it('forwards legacy ids to any peer and port-scoped ids to a negotiated peer', async () => { + const ok = JSON.stringify({ resp: 'host_invoke_result', ok: true, value: { success: true } }); + const legacyRpc = vi.fn().mockResolvedValue(ok); + await expect(new PeerDeviceTransportAdapter('peer-1', legacyRpc) + .request('ssh_connect', { config: { id: 'ssh-root@cluster', host: 'cluster', port: 2201 } })).resolves.toEqual({ success: true }); + const scopedRpc = vi.fn().mockResolvedValue(ok); + await expect(new PeerDeviceTransportAdapter('peer-1', scopedRpc, { supportsSshPortScopedIdentityV1: true }) + .request('ssh_connect', { config: { id: 'ssh-root@cluster#2201', host: 'cluster', port: 2201 } })).resolves.toEqual({ success: true }); + expect(JSON.stringify(scopedRpc.mock.calls[0])).toContain('ssh-root@cluster#2201'); + }); + it('forwards a WSL profile to the negotiated host with its target intact', async () => { const deviceRpc = vi.fn().mockResolvedValue(JSON.stringify({ resp: 'host_invoke_result', ok: true, value: { success: true } })); const adapter = new PeerDeviceTransportAdapter('peer-1', deviceRpc, { supportsWslWorkspacesV1: true }); diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts index 05c093326e..e643fdf832 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts @@ -11,6 +11,7 @@ import { } from '@/infrastructure/peer-device/deviceSurface'; import { PEER_CONTROLLER_LOCAL_COMMANDS } from '@/infrastructure/api/generated/remoteSurface'; import { createLogger } from '@/shared/utils/logger'; +import { sshConnectionIdPortScope } from '@/shared/utils/sshConnectionIdentity'; import { elapsedMs, nowMs } from '@/shared/utils/timing'; const log = createLogger('PeerDeviceTransport'); @@ -303,6 +304,7 @@ export interface PeerDeviceTransportHooks { /** Enables MiniApp Agent turns carrying inline image attachments. */ supportsMiniAppAgentImagesV1?: boolean; supportsWslWorkspacesV1?: boolean; + supportsSshPortScopedIdentityV1?: boolean; supportsWholeSessionCopyV1?: boolean; supportsModelRoutingV1?: boolean; supportsModelPoolSelectionV1?: boolean; @@ -445,6 +447,7 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { | 'supportsMiniAppAgentContextFilesV1' | 'supportsMiniAppAgentImagesV1' | 'supportsWslWorkspacesV1' + | 'supportsSshPortScopedIdentityV1' | 'supportsWholeSessionCopyV1' | 'supportsModelRoutingV1' | 'supportsModelPoolSelectionV1' @@ -570,6 +573,18 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { ); } + const sshConfigId = (params as { config?: { id?: unknown } } | undefined)?.config?.id; + if ( + action.startsWith('ssh_') && + typeof sshConfigId === 'string' && + sshConnectionIdPortScope(sshConfigId) !== undefined && + this.hooks.supportsSshPortScopedIdentityV1 !== true + ) { + throw new PeerProductCommandError( + 'ssh_port_scoped_identity_v1_unsupported: The connected Peer host does not keep SSH profiles that differ only by port separate; update the executing Desktop host', + ); + } + if ( action === 'miniapp_agent_run' && hasMiniAppAgentPayload(params, ['imageContexts', 'image_contexts']) && diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index 8d9d4fe2a2..2d0d95f2ef 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:ee62faff5c97f12a" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:96f7c9d0efb48c2a" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -194,6 +194,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "miniapp_agent_context_files_v1", "miniapp_agent_images_v1", "wsl_workspaces_v1", + "ssh_port_scoped_identity_v1", "computer_use_sharing_v1", "product_control_v1", "remote_connect_control_v1", @@ -243,6 +244,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "miniapp_agent_context_files_v1", "miniapp_agent_images_v1", "wsl_workspaces_v1", + "ssh_port_scoped_identity_v1", "computer_use_sharing_v1", "product_control_v1", "remote_connect_control_v1", diff --git a/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.test.ts b/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.test.ts index 830b4bf233..6cf03aa123 100644 --- a/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.test.ts +++ b/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.test.ts @@ -25,6 +25,14 @@ describe('legacy session workspace identity', () => { expect(resolveLegacySessionWorkspace({ workspacePath: '/repo', remoteSshHost: 'server-2' }, records)).toBe(otherHost); }); + it('never resolves a connection-less legacy reference to a port-scoped SSH record', () => { + const legacy = { ...parent, id: 'legacy-id', workspaceKind: 'remote', connectionId: 'ssh-root@cluster', sshHost: 'cluster' }; + const node = { ...legacy, id: 'node-id', connectionId: 'ssh-root@cluster#2201' }; + // Old session projection: sshHost and root, no connection id. + expect(resolveLegacySessionWorkspace({ workspacePath: '/repo', remoteSshHost: 'cluster' }, [legacy, node])).toBe(legacy); + expect(resolveLegacySessionWorkspace({ workspacePath: '/repo', remoteConnectionId: 'ssh-root@cluster#2201', remoteSshHost: 'cluster' }, [legacy, node])).toBe(node); + }); + it('does not substitute a worktree project for its missing execution workspace', () => { const old = { workspacePath: '/repo/tree', projectWorkspacePath: '/repo' }; expect(resolveLegacySessionWorkspace(old, [parent])).toBeUndefined(); diff --git a/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.ts b/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.ts index 3d47681a6a..5d9ef32c4b 100644 --- a/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.ts +++ b/src/web-ui/src/infrastructure/api/service-api/legacyWorkspaceCompatibility.ts @@ -6,6 +6,7 @@ */ import { normalizePath, normalizeRemoteWorkspacePath } from '@/shared/utils/pathUtils'; import { getActiveSurfaceScope, isLocalSurface } from '@/infrastructure/peer-device/deviceSurface'; +import { sshConnectionIdPortScope } from '@/shared/utils/sshConnectionIdentity'; export async function legacyWorkspacePayload(workspaceId: string, assertCurrent: () => void) { const { api } = await import('./ApiClient'); @@ -43,6 +44,10 @@ export function resolveLegacySessionWorkspace [record.id, record])).values()]; const candidates = uniqueRecords.filter(record => { + // A reference without a connection id predates port-scoped SSH profiles and + // can never name one; keeping them would make old (sshHost, root) references + // ambiguous once another port of the same host opens the same root. + if (!session.remoteConnectionId && sshConnectionIdPortScope(record.connectionId) !== undefined) return false; const normalize = record.workspaceKind === 'remote' ? normalizeRemoteWorkspacePath : normalizePath; const matchesPath = normalize(root).replace(/\/$/, '') === normalize(record.rootPath).replace(/\/$/, ''); return matchesPath diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 7080bd59d7..7a081402d0 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -53,6 +53,8 @@ export interface PeerHostCapabilities { readonly miniAppAgentContextFilesV1: boolean; readonly miniAppAgentImagesV1: boolean; readonly wslWorkspacesV1?: boolean; + /** Host keeps `ssh-user@host#port` profiles distinct; older hosts get legacy ids only. */ + readonly sshPortScopedIdentityV1?: boolean; /** Host stores ordered subscription account pools on model configs. */ readonly subscriptionAccountPoolsV1?: boolean; /** Host-owned read-only subscription allowance query. */ @@ -197,6 +199,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { miniAppAgentContextFilesV1: false, miniAppAgentImagesV1: false, wslWorkspacesV1: false, + sshPortScopedIdentityV1: false, subscriptionAccountPoolsV1: false, subscriptionQuotaV1: false, grokQuotaV1: false, @@ -464,6 +467,7 @@ export class PeerConnectionManager { supportsMiniAppAgentContextFilesV1: entry.capabilities.miniAppAgentContextFilesV1, supportsMiniAppAgentImagesV1: entry.capabilities.miniAppAgentImagesV1, supportsWslWorkspacesV1: entry.capabilities.wslWorkspacesV1, + supportsSshPortScopedIdentityV1: entry.capabilities.sshPortScopedIdentityV1, supportsWholeSessionCopyV1: entry.capabilities.wholeSessionCopyV1, supportsModelRoutingV1: entry.capabilities.modelRoutingV1, supportsModelPoolSelectionV1: entry.capabilities.modelPoolSelectionV1, @@ -558,6 +562,7 @@ export class PeerConnectionManager { miniAppAgentContextFilesV1: caps?.miniapp_agent_context_files_v1 === true, miniAppAgentImagesV1: caps?.miniapp_agent_images_v1 === true, wslWorkspacesV1: caps?.wsl_workspaces_v1 === true, + sshPortScopedIdentityV1: caps?.ssh_port_scoped_identity_v1 === true, subscriptionAccountPoolsV1: caps?.subscription_account_pools_v1 === true, subscriptionQuotaV1: caps?.subscription_quota_v1 === true, grokQuotaV1: caps?.grok_quota_v1 === true, @@ -667,6 +672,7 @@ export class PeerConnectionManager { supportsMiniAppAgentContextFilesV1: capabilities.miniAppAgentContextFilesV1, supportsMiniAppAgentImagesV1: capabilities.miniAppAgentImagesV1, supportsWslWorkspacesV1: capabilities.wslWorkspacesV1, + supportsSshPortScopedIdentityV1: capabilities.sshPortScopedIdentityV1, supportsWholeSessionCopyV1: capabilities.wholeSessionCopyV1, supportsModelRoutingV1: capabilities.modelRoutingV1, supportsModelPoolSelectionV1: capabilities.modelPoolSelectionV1, @@ -819,6 +825,7 @@ function capabilitiesEqual( a.miniAppAgentContextFilesV1 === b.miniAppAgentContextFilesV1 && a.miniAppAgentImagesV1 === b.miniAppAgentImagesV1 && a.wslWorkspacesV1 === b.wslWorkspacesV1 && + a.sshPortScopedIdentityV1 === b.sshPortScopedIdentityV1 && a.subscriptionAccountPoolsV1 === b.subscriptionAccountPoolsV1 && a.subscriptionQuotaV1 === b.subscriptionQuotaV1 && a.grokQuotaV1 === b.grokQuotaV1 && diff --git a/src/web-ui/src/locales/en-US/common.json b/src/web-ui/src/locales/en-US/common.json index 788c74fb83..5f69f7c7f3 100644 --- a/src/web-ui/src/locales/en-US/common.json +++ b/src/web-ui/src/locales/en-US/common.json @@ -2038,6 +2038,7 @@ "hostRequired": "Host is required", "usernameRequired": "Username is required", "portInvalid": "Port must be a number between 1 and 65535", + "portScopedIdentityUnsupported": "The connected device cannot keep separate profiles for SSH ports on the same host and user, so saving would replace \"{{connection}}\". Update OpenBitFun on that device, or edit the existing profile instead.", "passwordRequired": "Password is required", "keyPathRequired": "Private key path is required", "enterPassword": "Enter Password", diff --git a/src/web-ui/src/locales/zh-CN/common.json b/src/web-ui/src/locales/zh-CN/common.json index 6d98f5594b..7193516c80 100644 --- a/src/web-ui/src/locales/zh-CN/common.json +++ b/src/web-ui/src/locales/zh-CN/common.json @@ -2038,6 +2038,7 @@ "hostRequired": "主机地址不能为空", "usernameRequired": "用户名不能为空", "portInvalid": "端口必须是 1-65535 之间的数字", + "portScopedIdentityUnsupported": "所连接的设备无法为同一主机和用户的不同 SSH 端口保存独立配置,继续保存会替换“{{connection}}”。请在该设备上更新 OpenBitFun,或改为编辑已有配置。", "passwordRequired": "密码不能为空", "keyPathRequired": "私钥路径不能为空", "enterPassword": "请输入密码", diff --git a/src/web-ui/src/locales/zh-TW/common.json b/src/web-ui/src/locales/zh-TW/common.json index efdd80cd52..0a52248b02 100644 --- a/src/web-ui/src/locales/zh-TW/common.json +++ b/src/web-ui/src/locales/zh-TW/common.json @@ -2038,6 +2038,7 @@ "hostRequired": "主機地址不能為空", "usernameRequired": "用戶名不能為空", "portInvalid": "端口必須是 1-65535 之間的數字", + "portScopedIdentityUnsupported": "所連接的裝置無法為同一主機和使用者的不同 SSH 連接埠保存獨立設定,繼續保存會取代「{{connection}}」。請在該裝置上更新 OpenBitFun,或改為編輯現有設定。", "passwordRequired": "密碼不能為空", "keyPathRequired": "私鑰路徑不能為空", "enterPassword": "請輸入密碼", diff --git a/src/web-ui/src/shared/utils/sshConnectionIdentity.ts b/src/web-ui/src/shared/utils/sshConnectionIdentity.ts new file mode 100644 index 0000000000..97bf996bee --- /dev/null +++ b/src/web-ui/src/shared/utils/sshConnectionIdentity.ts @@ -0,0 +1,45 @@ +/** + * SSH connection id grammar shared with the Rust owner + * (`openbitfun_services_core::workspace_identity`). + * + * - `ssh-user@host`: default-port and legacy profiles. + * - `ssh-user@host:port`: pre-#710 alias of `ssh-user@host`. + * - `ssh-user@host#port[~n]`: port-scoped profile (a distinct connection). + * - `workspace-host--container-`: container on a synthetic + * host wrapper; the wrapped id keeps its port scope. + */ +const PORT_SCOPE = /^ssh-[^@]*@[^#]*#(\d+(?:~\d+)?)(?:-.*)?$/; +const WORKSPACE_HOST_PREFIX = 'workspace-host-'; + +function unwrapWorkspaceHost(id: string): string { + if (!id.startsWith(WORKSPACE_HOST_PREFIX)) return id; + try { + return decodeURIComponent(id.slice(WORKSPACE_HOST_PREFIX.length)); + } catch { + return id; + } +} + +/** Port scope of a port-scoped SSH connection id, or undefined for every legacy id. */ +export function sshConnectionIdPortScope(connectionId: string | null | undefined): string | undefined { + const match = PORT_SCOPE.exec(unwrapWorkspaceHost((connectionId ?? '').trim())); + if (!match) return undefined; + return Number(match[1].split('~')[0]) <= 65535 ? match[1] : undefined; +} + +/** Port named by a pre-#710 `ssh-user@host:port` alias; undefined for every other id. */ +export function sshConnectionIdAliasPort(connectionId: string): number | undefined { + if (!connectionId.startsWith('ssh-')) return undefined; + const rest = connectionId.slice(4); + const at = rest.indexOf('@'); + const colon = rest.lastIndexOf(':'); + const port = rest.slice(colon + 1); + if (at < 0 || colon <= at || !/^\d+$/.test(port) || Number(port) > 65535) return undefined; + return Number(port); +} + +/** Pre-#710 `ssh-user@host:port` ids collapse to `ssh-user@host`; other ids are unchanged. */ +export function canonicalSshConnectionId(connectionId: string): string { + if (sshConnectionIdAliasPort(connectionId) === undefined) return connectionId; + return connectionId.slice(0, connectionId.lastIndexOf(':')); +} From 5ffae4010eca5e7471d9f8de9cc3542c41db9d8c Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 13:14:06 +0800 Subject: [PATCH 3/4] fix(remote-ssh): tighten orphan id reuse and percent decoding - Reuse an orphaned legacy id only through an exact ssh-user@host:port alias; a port-less orphan never moves to a non-default port. - List workspace records once per ~/.ssh/config discovery pass. - Reject malformed percent escapes (sign, short, invalid UTF-8) in the Rust and Kotlin workspace-host decoders, matching decodeURIComponent. --- .../domain/LegacyWorkspaceCompatibility.kt | 11 ++++++++-- .../LegacyWorkspaceCompatibilityTest.kt | 2 ++ .../services-core/src/workspace_identity.rs | 20 +++++++++++++++++++ .../ssh-remote/resolveSshConnectionId.ts | 8 ++++++-- .../ssh-remote/sshConnectionId.test.ts | 8 ++++++-- .../features/ssh-remote/sshConnectionId.ts | 11 ++++++---- .../useWorkspaceSourceOptions.test.tsx | 20 +++++++++++++++++++ .../ssh-remote/useWorkspaceSourceOptions.ts | 12 ++++++++--- 8 files changed, 79 insertions(+), 13 deletions(-) diff --git a/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibility.kt b/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibility.kt index c61708b007..34f0e1ddd6 100644 --- a/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibility.kt +++ b/src/apps/mobile/shared/core-domain/src/commonMain/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibility.kt @@ -113,7 +113,10 @@ public object LegacyWorkspaceCompatibility { while (index < value.length) { if (value[index] == '%') { if (index + 2 >= value.length) return null - val hex = value.substring(index + 1, index + 3).toIntOrNull(16) ?: return null + // Like `decodeURIComponent`: exactly two hex digits (no sign). + val digits = value.substring(index + 1, index + 3) + if (!digits.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }) return null + val hex = digits.toInt(16) bytes.add(hex.toByte()) index += 3 } else { @@ -121,7 +124,11 @@ public object LegacyWorkspaceCompatibility { index += 1 } } - return bytes.toByteArray().decodeToString() + return try { + bytes.toByteArray().decodeToString(throwOnInvalidSequence = true) + } catch (_: CharacterCodingException) { + null + } } private fun normalizedRoot(path: String): String = path.trim().let { it.trimEnd('/').ifEmpty { it } } diff --git a/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt b/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt index b2689856e0..5e176af37c 100644 --- a/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt +++ b/src/apps/mobile/shared/core-domain/src/commonTest/kotlin/com/openbitfun/mobile/core/domain/LegacyWorkspaceCompatibilityTest.kt @@ -64,6 +64,8 @@ class LegacyWorkspaceCompatibilityTest { assertTrue(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("workspace-host-ssh-root%40cluster%232201-container-web")) assertFalse(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("ssh-root@cluster:2201")) assertFalse(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("workspace-host-%ZZ")) + assertFalse(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("workspace-host-ssh-root%40cluster%+12201")) + assertFalse(LegacyWorkspaceCompatibility.isPortScopedSshConnectionId("workspace-host-ssh-root%40cluster%232201%C3")) } @Test diff --git a/src/crates/services/services-core/src/workspace_identity.rs b/src/crates/services/services-core/src/workspace_identity.rs index d18b1c62d1..b76482bcee 100644 --- a/src/crates/services/services-core/src/workspace_identity.rs +++ b/src/crates/services/services-core/src/workspace_identity.rs @@ -146,7 +146,11 @@ fn percent_decode(value: &str) -> Option { let mut index = 0; while index < bytes.len() { if bytes[index] == b'%' { + // Like `decodeURIComponent`: exactly two hex digits (no sign). let hex = value.get(index + 1..index + 3)?; + if !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } out.push(u8::from_str_radix(hex, 16).ok()?); index += 3; } else { @@ -728,6 +732,9 @@ mod tests { "workspace-host-ssh-root%40cluster-container-web", "workspace-host-ssh-root%40cluster%3A2201-container-web", "workspace-host-%ZZ", + "workspace-host-ssh-root%40cluster%+12201", + "workspace-host-ssh-root%40cluster%232201%", + "workspace-host-ssh-root%40cluster%232201%C3", ] { assert_eq!(ssh_connection_id_port_scope(legacy), None, "{legacy}"); } @@ -821,6 +828,19 @@ mod tests { ); } + #[test] + fn percent_decoding_rejects_what_decode_uri_component_rejects() { + use super::percent_decode; + assert_eq!( + percent_decode("ssh-u%40h%232201").as_deref(), + Some("ssh-u@h#2201") + ); + assert_eq!(percent_decode("%C3%A9").as_deref(), Some("\u{e9}")); + for malformed in ["%+1", "%-1", "%1", "%", "%G1", "%C3", "%FF"] { + assert_eq!(percent_decode(malformed), None, "{malformed}"); + } + } + #[test] fn canonical_ssh_connection_id_never_collapses_port_scoped_ids() { assert_eq!( diff --git a/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts b/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts index b005dd5bc7..e062f3382a 100644 --- a/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts +++ b/src/web-ui/src/features/ssh-remote/resolveSshConnectionId.ts @@ -36,7 +36,8 @@ export async function activeHostSupportsPortScopedSshIds(): Promise { return peerConnectionManager.get(scope.surfaceId)?.getState().capabilities.sshPortScopedIdentityV1 === true; } -async function referencedRemoteConnectionIds(): Promise { +/** Connection ids referenced by workspace records on the active host; fetch once per pass. */ +export async function referencedRemoteConnectionIds(): Promise { try { const [opened, recent] = await Promise.all([globalAPI.getOpenedWorkspaces(), globalAPI.getRecentWorkspaces()]); return [...opened, ...recent].flatMap(workspace => @@ -56,6 +57,7 @@ export async function resolveNewSshConnectionId( endpoint: SshEndpoint, isSameTarget: (connection: SavedConnection) => boolean, saved?: readonly SavedConnection[], + referenced?: readonly string[], ): Promise { const portScopedIds = await activeHostSupportsPortScopedSshIds(); let connections = saved; @@ -75,6 +77,8 @@ export async function resolveNewSshConnectionId( const conflict = legacySshEndpointConflict(endpoint, connections, isSameTarget); return conflict ? { error: 'portScopedIdentityUnsupported', conflict, transientId: id } : { id }; } - const referencedIds = endpoint.port === DEFAULT_SSH_PORT ? [] : await referencedRemoteConnectionIds(); + // Port 22 already gets the port-less id, which workspace records treat as + // equal to its `:22` alias, so only other ports need the record listing. + const referencedIds = endpoint.port === DEFAULT_SSH_PORT ? [] : referenced ?? await referencedRemoteConnectionIds(); return { id: sshConnectionIdForEndpoint(endpoint, connections, isSameTarget, { referencedIds }) }; } diff --git a/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts b/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts index 3368411c45..1c24e27e0b 100644 --- a/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts +++ b/src/web-ui/src/features/ssh-remote/sshConnectionId.test.ts @@ -65,9 +65,13 @@ describe('sshConnectionIdForEndpoint', () => { expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, connections)).toBe('ssh-root@cluster#22'); }); - it('reuses an orphaned legacy id that workspace records still reference', () => { + it('reuses an orphaned legacy id only when it names the same port', () => { const context = { referencedIds: ['ssh-root@cluster'] }; - expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, [], undefined, context)).toBe('ssh-root@cluster'); + // A port-less orphan most likely belonged to a port-22 server: never hand its history to another port. + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, [], undefined, context)).toBe('ssh-root@cluster#2201'); + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, [], undefined, context)).toBe('ssh-root@cluster'); + expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 22, username: 'root' }, [], undefined, { referencedIds: ['ssh-root@cluster:22'] })) + .toBe('ssh-root@cluster:22'); // A `:port` alias only reattaches to its own port. const alias = { referencedIds: ['ssh-root@cluster:2201'] }; expect(sshConnectionIdForEndpoint({ host: 'cluster', port: 2201, username: 'root' }, [], undefined, alias)).toBe('ssh-root@cluster:2201'); diff --git a/src/web-ui/src/features/ssh-remote/sshConnectionId.ts b/src/web-ui/src/features/ssh-remote/sshConnectionId.ts index d4ca7422ff..2d500ba30b 100644 --- a/src/web-ui/src/features/ssh-remote/sshConnectionId.ts +++ b/src/web-ui/src/features/ssh-remote/sshConnectionId.ts @@ -22,8 +22,11 @@ export interface SshEndpoint { export interface SshConnectionIdContext { /** * Connection ids referenced by workspace records on the target host. A - * legacy port-less id that no saved profile owns any more is reused for a - * non-default port, so re-adding a deleted legacy profile finds its sessions. + * pre-#710 `ssh-user@host:port` alias that no saved profile owns any more is + * reused for exactly that port, so re-adding a deleted legacy profile finds + * its sessions. A port-less orphan only says nothing about its port (most + * belonged to port 22), so it is reused only for port 22, where it is the + * default id anyway, and never for another port. */ referencedIds?: readonly string[]; /** @@ -66,9 +69,9 @@ export function sshConnectionIdForEndpoint( if (context.portScopedIds === false) return legacy; const taken = (id: string) => saved.some(connection => canonicalSshConnectionId(connection.id) === id); - if (endpoint.port !== DEFAULT_SSH_PORT && !taken(legacy)) { + if (!taken(legacy)) { const orphan = context.referencedIds?.find(id => canonicalSshConnectionId(id) === legacy - && (sshConnectionIdAliasPort(id) ?? endpoint.port) === endpoint.port); + && sshConnectionIdAliasPort(id) === endpoint.port); if (orphan) return orphan; } diff --git a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx index 35c97dbd1f..60357e7460 100644 --- a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx +++ b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.test.tsx @@ -9,6 +9,10 @@ import { activateSurface, resetDeviceSurfaceForTest, surfaceIdForDevice } from ' globalThis.IS_REACT_ACT_ENVIRONMENT = true; const api = vi.hoisted(() => ({ listSavedConnections: vi.fn(), listSSHConfigHosts: vi.fn(), listWslDistributions: vi.fn(), listDockerContainers: vi.fn() })); vi.mock('./sshApi', () => ({ sshApi: api })); +const workspaceRecords = vi.hoisted(() => ({ opened: vi.fn(), recent: vi.fn() })); +vi.mock('@/infrastructure/api/service-api/GlobalAPI', () => ({ + globalAPI: { getOpenedWorkspaces: workspaceRecords.opened, getRecentWorkspaces: workspaceRecords.recent }, +})); vi.mock('@/infrastructure/i18n', () => { const t = (key: string) => key; return { useI18n: () => ({ t }) }; @@ -25,6 +29,8 @@ beforeEach(() => { vi.resetAllMocks(); resetDeviceSurfaceForTest(); api.listSavedConnections.mockResolvedValue([]); api.listSSHConfigHosts.mockResolvedValue([]); + workspaceRecords.opened.mockResolvedValue([]); + workspaceRecords.recent.mockResolvedValue([]); api.listWslDistributions.mockResolvedValue({ supported: true, distributions: ['Ubuntu'] }); api.listDockerContainers.mockResolvedValue([{ id: 'dev-id', name: 'dev', image: 'ubuntu', state: 'running' }]); host = document.createElement('div'); document.body.append(host); root = createRoot(host); @@ -138,3 +144,17 @@ it('routes ~/.ssh/config entries to the dialog when saved profiles cannot be lis // No connectable profile: the caller opens the connection dialog instead of a one-click connect. expect(workspacePresetHost(preset)).toBeUndefined(); }); + +it('lists workspace records once per discovery pass, not once per ~/.ssh/config entry', async () => { + api.listSSHConfigHosts.mockResolvedValue([ + { host: 'node-1', hostname: 'cluster', port: 2201, user: 'root', agent: true }, + { host: 'node-2', hostname: 'cluster', port: 2202, user: 'root', agent: true }, + { host: 'node-3', hostname: 'cluster', port: 2203, user: 'root', agent: true }, + ]); + await render('ssh'); + expect(result.options.map(option => option.preset).filter(preset => preset.kind === 'sshConfig') + .map(preset => 'connectionId' in preset ? preset.connectionId : undefined)) + .toEqual(['ssh-root@cluster#2201', 'ssh-root@cluster#2202', 'ssh-root@cluster#2203']); + expect(workspaceRecords.opened).toHaveBeenCalledTimes(1); + expect(workspaceRecords.recent).toHaveBeenCalledTimes(1); +}); diff --git a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts index d989a6493d..d8cca837c2 100644 --- a/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts +++ b/src/web-ui/src/features/ssh-remote/useWorkspaceSourceOptions.ts @@ -8,7 +8,7 @@ const log = createLogger('WorkspaceSourceOptions'); import { sameWorkspaceSource, savedConnectionTarget, type WorkspaceSource } from './workspaceSource'; import type { SavedConnection, SSHConfigEntry, SSHConnectionConfig } from './types'; import { DEFAULT_SSH_PORT, type SshEndpoint } from './sshConnectionId'; -import { resolveNewSshConnectionId } from './resolveSshConnectionId'; +import { referencedRemoteConnectionIds, resolveNewSshConnectionId } from './resolveSshConnectionId'; export type WorkspaceConnectionPreset = ( | { kind: 'new'; host?: SavedConnection } @@ -129,12 +129,18 @@ export function useWorkspaceSourceOptions(source: WorkspaceSource, enabled: bool } } }); } } else if (source === 'ssh') { - for (const entry of detected.value as SSHConfigEntry[]) { + const entries = detected.value as SSHConfigEntry[]; + // One workspace-record listing per discovery pass, shared by every entry. + const referenced = saved.status === 'fulfilled' && entries.length > 0 + ? await referencedRemoteConnectionIds() + : []; + if (cancelled || !scope.isCurrent()) return; + for (const entry of entries) { const endpoint = sshConfigEndpoint(entry); if (connections.some(connection => connection.host === endpoint.host && connection.port === endpoint.port && connection.username === endpoint.username)) continue; // Without the saved profiles any id could overwrite one, so the dialog resolves it on connect. const resolved = saved.status === 'fulfilled' - ? await resolveNewSshConnectionId(endpoint, connection => !connection.container && !connection.wsl, saved.value) + ? await resolveNewSshConnectionId(endpoint, connection => !connection.container && !connection.wsl, saved.value, referenced) : undefined; if (cancelled || !scope.isCurrent()) return; result.push({ id: `ssh-config:${entry.host}`, label: entry.host, From ee914338b774c0ac7f8b38abc70a66ebfa9db47a Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Mon, 2 Nov 2026 14:44:30 +0800 Subject: [PATCH 4/4] test(remote-ssh): set proxy_command in port-identity profile fixture --- .../services/services-integrations/src/remote_ssh/manager.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/crates/services/services-integrations/src/remote_ssh/manager.rs b/src/crates/services/services-integrations/src/remote_ssh/manager.rs index 06d3b296de..97cce2022d 100644 --- a/src/crates/services/services-integrations/src/remote_ssh/manager.rs +++ b/src/crates/services/services-integrations/src/remote_ssh/manager.rs @@ -9841,6 +9841,7 @@ Host * }, default_workspace: None, proxy_jump: None, + proxy_command: None, container: None, wsl: None, options: Default::default(),