1use super::*;
14use crate::backend::mps::Broker;
15use crate::backend::remote::remotes;
16use crate::backend::remote::sessions;
17use crate::backend::remote::status::{self, state};
18use crate::backend::remote::ConnTarget;
19
20pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
21 engine.register_typed(COMMAND_CONN_LIST, |_data: serde_json::Value, _ctx| async move { Ok(conn_list().await) });
30 engine.register_typed(COMMAND_CONN_LIST_AWS, |_data: serde_json::Value, _ctx| async move {
31 Ok(Vec::<String>::new())
32 });
33 engine.register_typed(COMMAND_WSL_LIST, |_data: serde_json::Value, _ctx| async move {
35 Ok(crate::backend::remote::wsl::list().await)
36 });
37
38 let broker = state.broker.clone();
39 engine.register_typed(COMMAND_CONN_ENSURE, move |data: serde_json::Value, _ctx| {
40 let broker = broker.clone();
41 async move { ensure(&broker, &str_field(&data, "connname")).await }
43 });
44
45 let app = state.clone();
46 engine.register_typed(COMMAND_CONN_CONNECT, move |data: serde_json::Value, _ctx| {
47 let app = app.clone();
48 async move { connect(&app, &str_field(&data, "host"), &str_field(&data, "logblockid")).await }
50 });
51
52 let broker = state.broker.clone();
53 engine.register_typed(COMMAND_CONN_DISCONNECT, move |data: serde_json::Value, _ctx| {
54 let broker = broker.clone();
55 async move { conn_disconnect(&broker, &data).await }
56 });
57
58 let app = state.clone();
59 engine.register_typed(COMMAND_CONN_SESSIONS, move |data: serde_json::Value, _ctx| {
60 let app = app.clone();
61 async move { conn_sessions(&app, &data).await }
62 });
63 let app = state.clone();
64 engine.register_typed(COMMAND_CONN_SESSION_END, move |data: serde_json::Value, _ctx| {
65 let app = app.clone();
66 async move { conn_session_end(&app, &data).await }
67 });
68
69 let config = state.config_watcher.clone();
72 engine.register_typed(COMMAND_REMOTES_LIST, move |_cmd: CommandRemotesListData, _ctx| {
73 let config = config.clone();
74 async move { Ok(remotes::list(config.get_full_config().connections.clone()).await) }
75 });
76 let app = state.clone();
77 engine.register_typed(COMMAND_REMOTE_SET_CONFIG, move |cmd: CommandRemoteSetConfigData, _ctx| {
78 let app = app.clone();
79 async move { remote_set_config(&app, cmd) }
80 });
81 let app = state.clone();
82 engine.register_typed(COMMAND_REMOTE_FORGET, move |cmd: CommandRemoteForgetData, _ctx| {
83 let app = app.clone();
84 async move { remote_forget(&app, cmd) }
85 });
86 let app = state.clone();
89 engine.register_typed(COMMAND_REMOTE_HELPER_REMOVE, move |cmd: CommandRemoteHelperRemoveData, _ctx| {
90 let app = app.clone();
91 async move { remove_helper(&app, &cmd.connection, &cmd.blockid).await }
92 });
93 let app = state.clone();
98 engine.register_typed(COMMAND_REMOTE_ADD, move |cmd: CommandRemoteAddData, _ctx| {
99 let app = app.clone();
100 async move { add_remote(&app, cmd).await }
101 });
102 let app = state.clone();
106 engine.register_typed(COMMAND_REMOTE_TEST, move |cmd: CommandRemoteTestData, _ctx| {
107 let app = app.clone();
108 async move { test_remote(&app, &cmd.connection, &cmd.blockid).await }
109 });
110 let app = state.clone();
111 engine.register_typed(COMMAND_REMOTE_AGENT_REVOKE, move |cmd: CommandRemoteAgentRevokeData, _ctx| {
112 let app = app.clone();
113 async move { remote_agent_revoke(&app, cmd) }
114 });
115 engine.register_typed(COMMAND_REMOTE_SSH_LOCATE, move |cmd: CommandRemoteSshLocateData, _ctx| async move {
116 remote_ssh_locate(cmd).await
117 });
118}
119
120pub(crate) async fn conn_list() -> Vec<String> {
124 let hosts = tokio::task::spawn_blocking(crate::backend::remote::ssh_config::hosts)
125 .await
126 .unwrap_or_default();
127 remote_names(&hosts, &status::all())
128}
129
130pub(crate) async fn conn_disconnect(broker: &Broker, data: &serde_json::Value) -> Result<(), String> {
132 let name = data.as_str().unwrap_or_default().to_string();
133 match ConnTarget::parse(&name) {
134 Ok(ConnTarget::Ssh(_)) => crate::backend::remote::link::disconnect(&name).await,
137 Ok(ConnTarget::Wsl(_)) => {
138 status::set(Some(broker), &name, state::DISCONNECTED, None);
139 }
140 _ => {}
141 }
142 Ok(())
143}
144
145pub(crate) async fn conn_sessions(state: &AppState, data: &serde_json::Value) -> Result<Vec<sessions::HostSession>, String> {
152 let (conn, block) = (str_field(data, "connname"), str_field(data, "blockid"));
153 let ask = (!block.is_empty()).then_some(sessions::AskIn {
154 block_id: &block,
155 auth_key: &state.auth_key,
156 });
157 let list = sessions::list(&state.mstore, &conn, ask).await?;
158 remotes::note_sessions(&conn, list.len());
160 Ok(list)
161}
162
163pub(crate) async fn conn_session_end(state: &AppState, data: &serde_json::Value) -> Result<bool, String> {
165 let (conn, id, block) = (
166 str_field(data, "connname"),
167 str_field(data, "sessionid"),
168 str_field(data, "blockid"),
169 );
170 if block.is_empty() {
171 return Err("ending a session needs the pane asking, to ask the user in".into());
172 }
173 if !crate::backend::blockcontroller::durable_ssh::valid_session_id(&id) {
174 return Err(format!("{:?} is not a session id", one_line(&id, 80)));
175 }
176 confirm_session_end(state, &block, &conn, &id).await?;
177 let ask = sessions::AskIn {
178 block_id: &block,
179 auth_key: &state.auth_key,
180 };
181 sessions::end(&conn, &id, Some(ask)).await
182}
183
184pub(crate) fn remote_set_config(state: &AppState, cmd: CommandRemoteSetConfigData) -> Result<(), String> {
186 let name = remote_name(&cmd.connection)?;
187 crate::backend::config_watcher_fs::set_connection_values(&state.config_watcher, &state.event_bus, &name, &cmd.values)?;
188 remotes::publish_change(&state.broker);
189 Ok(())
190}
191
192pub(crate) fn remote_forget(state: &AppState, cmd: CommandRemoteForgetData) -> Result<(), String> {
194 let name = remote_name(&cmd.connection)?;
195 if remotes::forget_recent(&name).map_err(|e| format!("could not forget {name}: {e}"))? {
196 remotes::publish_change(&state.broker);
197 }
198 Ok(())
199}
200
201pub(crate) fn remote_agent_revoke(state: &AppState, cmd: CommandRemoteAgentRevokeData) -> Result<(), String> {
204 let name = ssh_host(&cmd.connection, NOT_SSH)?;
205 let revoked = crate::backend::remote::agent_access::revoke(&cmd.agent, &name)
206 .map_err(|e| format!("could not revoke {}'s access to {name}: {e}", one_line(&cmd.agent, 60)))?;
207 if revoked {
208 tracing::info!(agent = %one_line(&cmd.agent, 60), connection = %name, "agent ssh access: revoked");
209 remotes::publish_change(&state.broker);
210 }
211 Ok(())
212}
213
214pub(crate) async fn remote_ssh_locate(cmd: CommandRemoteSshLocateData) -> Result<Option<RemoteSshLocation>, String> {
216 let found = tokio::task::spawn_blocking(move || {
217 let (config, ssh_dir) = crate::backend::remote::ssh_config_edit::user_paths()?;
218 crate::backend::remote::ssh_config_edit::locate_in(&config, &ssh_dir, &cmd.connection)
219 })
220 .await
221 .map_err(|e| e.to_string())?;
222 Ok(found.map(|(path, line)| RemoteSshLocation {
223 path: path.to_string_lossy().into_owned(),
224 line: line as u32,
225 }))
226}
227
228async fn add_remote(state: &AppState, cmd: CommandRemoteAddData) -> Result<(), String> {
231 use crate::backend::remote::ssh_config_edit::{self, NewHost};
232 if cmd.blockid.is_empty() {
233 return Err("adding a remote needs the pane asking, to ask the user in".into());
234 }
235 let host = NewHost {
236 alias: cmd.alias,
237 hostname: cmd.hostname,
238 user: cmd.user,
239 port: cmd.port,
240 identity_file: cmd.identityfile,
241 proxy_jump: cmd.proxyjump,
242 };
243 let block = ssh_config_edit::host_block(&host)?;
244 let (config, ssh_dir) =
245 ssh_config_edit::user_paths().ok_or_else(|| "there is no home folder for an ssh config".to_string())?;
246 let question = serde_json::json!({
247 "kind": "consent",
248 "title": format!("Add {} to your ssh config", one_line(&host.alias, 80)),
249 "message": format!(
250 "Add this to the end of {}?\n\n{}\nEvery ssh on this computer will use it.",
251 config.display(),
252 block
253 ),
254 "ok_label": "Add",
255 "cancel_label": "Cancel",
256 });
257 let answer = ask_in_pane(state, &cmd.blockid, question).await?;
258 if !(answer.answered && answer.approve) {
259 return Err("kept: the user chose not to add it".into());
260 }
261 tokio::task::spawn_blocking(move || ssh_config_edit::add_host_in(&config, &ssh_dir, &host))
262 .await
263 .map_err(|e| e.to_string())??;
264 remotes::publish_change(&state.broker);
265 Ok(())
266}
267
268const NOT_SSH: &str = "is not an SSH host";
269
270fn ssh_host(connection: &str, otherwise: &str) -> Result<String, String> {
273 match ConnTarget::parse(connection)? {
274 t @ ConnTarget::Ssh(_) => Ok(t.name()),
275 _ => Err(format!("{} {otherwise}", one_line(connection, 80))),
276 }
277}
278
279async fn known_ssh_host(state: &AppState, connection: &str) -> Result<String, String> {
284 let name = ssh_host(connection, NOT_SSH)?;
285 let known = remotes::list(state.config_watcher.get_full_config().connections.clone())
286 .await
287 .iter()
288 .any(|r| r.kind == "ssh" && r.name == name);
289 if !known {
290 return Err(format!("{} isn't one of your remotes", one_line(&name, 80)));
291 }
292 Ok(name)
293}
294
295async fn log_in(state: &AppState, name: &str, block: &str) -> Result<(), String> {
300 use crate::backend::remote::{host::HostSsh, link};
301 let mut host = HostSsh::for_connection(name)?;
302 let _grant = (!block.is_empty()).then(|| host.ask_user_in(block, name, &state.auth_key)).flatten();
303 link::login(name, async {
304 host.run("true", None, SSH_WITH_PROMPTS).await.and_then(|o| o.ok()).map(|_| ())
305 })
306 .await
307}
308
309async fn connect(state: &AppState, connection: &str, block: &str) -> Result<(), String> {
312 ensure(&state.broker, connection).await?;
313 if !matches!(ConnTarget::parse(connection)?, ConnTarget::Ssh(_)) {
314 return Ok(());
315 }
316 let name = known_ssh_host(state, connection).await?;
317 log_in(state, &name, block).await
318}
319
320async fn test_remote(state: &AppState, connection: &str, block: &str) -> Result<RemoteTestResult, String> {
322 let name = known_ssh_host(state, connection).await?;
323 Ok(match log_in(state, &name, block).await {
324 Ok(()) => RemoteTestResult { ok: true, message: String::new() },
325 Err(message) => RemoteTestResult { ok: false, message },
326 })
327}
328
329async fn remove_helper(state: &AppState, connection: &str, block: &str) -> Result<(), String> {
333 use crate::backend::remote::{files, helper_hosts, helper_install, host::HostSsh};
334 let name = ssh_host(connection, "has no AgentMux helper to remove")?;
335 if block.is_empty() {
336 return Err("removing the helper needs the pane asking, to ask the user in".into());
337 }
338 let ask = sessions::AskIn { block_id: block, auth_key: &state.auth_key };
339 let running = sessions::list(&state.mstore, &name, Some(ask)).await?;
340 let ends = match running.len() {
341 0 => "No sessions are running there.".to_string(),
342 1 => "The 1 session running there ends, with everything running in it.".to_string(),
343 n => format!("The {n} sessions running there end, with everything running in them."),
344 };
345 let question = serde_json::json!({
346 "kind": "consent",
347 "title": format!("Remove AgentMux's helper from {}", one_line(&name, 80)),
348 "message": format!(
349 "Remove AgentMux's helper from {}?\n\n{ends} It deletes ~/.agentmux-remote there; file browsing and terminals that survive disconnects need it installed again.",
350 one_line(&name, 80)
351 ),
352 "ok_label": "Remove",
353 "cancel_label": "Keep It",
354 "destructive": true,
357 });
358 let answer = ask_in_pane(state, block, question).await?;
359 if !(answer.answered && answer.approve) {
360 return Err("kept: the user chose not to remove it".into());
361 }
362 let mut host = HostSsh::for_connection(&name)?;
363 let _grant = host.ask_user_in(block, &name, &state.auth_key);
364 let out = host
365 .run(&helper_install::remove_command(), None, SSH_WITH_PROMPTS)
366 .await?
367 .ok()?;
368 if out.trim() != "ok" {
369 return Err(format!("removing the helper from {name} did not finish ({})", one_line(&out, 200)));
370 }
371 files::close(&name).await;
372 if let Err(e) = helper_hosts::forget_helper_on_machine(&name).await {
374 tracing::warn!(connection = %name, error = %e, "could not forget the removed helper");
375 }
376 crate::backend::remote::helper_consent::forget_answers(&name);
378 remotes::note_sessions(&name, 0);
379 remotes::publish_change(&state.broker);
380 tracing::info!(connection = %name, sessions = running.len(), "removed the helper");
381 Ok(())
382}
383
384pub fn install_helper_consent(state: &AppState) {
387 use crate::backend::remote::helper_consent;
388 let app = state.clone();
389 let config = state.config_watcher.clone();
390 let (writer, event_bus, broker) = (state.config_watcher.clone(), state.event_bus.clone(), state.broker.clone());
391 helper_consent::install(helper_consent::Deps {
392 ask: Box::new(move |block, question| {
393 let app = app.clone();
394 Box::pin(async move {
395 let a = ask_in_pane(&app, &block, question).await?;
396 Ok(helper_consent::Answer { answered: a.answered, approve: a.approve, remember: a.checkbox })
397 })
398 }),
399 settings: Box::new(move |connection| {
400 let full = config.get_full_config();
401 let host = full
402 .connections
403 .iter()
404 .find(|(name, _)| crate::backend::remote::conn::same_connection(name, connection))
405 .map(|(_, k)| k.conn_helper.clone())
406 .unwrap_or_default();
407 (host, full.settings.conn_helper.clone())
408 }),
409 remember: Box::new(move |connection, value| {
410 let mut values = serde_json::Map::new();
411 values.insert("conn:helper".into(), serde_json::json!(value));
412 crate::backend::config_watcher_fs::set_connection_values(&writer, &event_bus, connection, &values)?;
413 remotes::publish_change(&broker);
414 Ok(())
415 }),
416 });
417}
418
419fn remote_name(connection: &str) -> Result<String, String> {
422 match ConnTarget::parse(connection)? {
423 ConnTarget::Local => Err("local is not a remote".to_string()),
424 _ => Ok(connection.trim().to_string()),
425 }
426}
427
428async fn confirm_session_end(
431 state: &AppState,
432 block: &str,
433 conn: &str,
434 id: &str,
435) -> Result<(), String> {
436 let question = serde_json::json!({
438 "kind": "consent",
439 "title": format!("End a session on {}", one_line(conn, 80)),
440 "message": format!(
441 "End the durable session {id} on {}?\n\nIts shell, and everything running in it, stops. This cannot be undone.",
442 one_line(conn, 80)
443 ),
444 "ok_label": "End Session",
445 "cancel_label": "Keep It",
446 "destructive": true,
447 });
448 let answer = ask_in_pane(state, block, question).await?;
449 if answer.answered && answer.approve {
450 Ok(())
451 } else {
452 Err("kept: the user chose not to end it".to_string())
453 }
454}
455
456fn str_field(data: &serde_json::Value, key: &str) -> String {
457 data.get(key)
458 .and_then(|v| v.as_str())
459 .unwrap_or_default()
460 .to_string()
461}
462
463pub(crate) async fn ensure(broker: &Broker, name: &str) -> Result<(), String> {
469 let (installed, ssh_found) = match ConnTarget::parse(name)? {
470 ConnTarget::Wsl(_) => (crate::backend::remote::wsl::list().await, false),
471 ConnTarget::Ssh(_) => (Vec::new(), crate::backend::remote::ssh::binary().is_some()),
472 ConnTarget::Local => (Vec::new(), false),
473 };
474 ensure_with(broker, name, &installed, cfg!(windows), ssh_found)
475}
476
477pub(crate) fn ensure_with(
480 broker: &Broker,
481 name: &str,
482 wsl_installed: &[String],
483 on_windows: bool,
484 ssh_found: bool,
485) -> Result<(), String> {
486 let target = ConnTarget::parse(name)?;
487 let message = match &target {
488 ConnTarget::Local => return Ok(()),
489 ConnTarget::Wsl(_) if !on_windows => "WSL is only available on Windows".to_string(),
490 ConnTarget::Wsl(distro) if wsl_installed.iter().any(|d| d.eq_ignore_ascii_case(distro)) => {
491 status::set(Some(broker), name, state::CONNECTED, None);
492 return Ok(());
493 }
494 ConnTarget::Wsl(distro) => {
495 format!("WSL distribution '{distro}' is not installed (wsl.exe --list shows what is)")
496 }
497 ConnTarget::Ssh(_) if ssh_found => return Ok(()),
498 ConnTarget::Ssh(_) => crate::backend::remote::ssh::missing_binary_message(),
499 };
500 status::set(Some(broker), name, state::ERROR, Some(&message));
504 Err(message)
505}
506
507#[derive(Debug, Clone, PartialEq, Eq)]
509pub(crate) enum AgentTarget {
510 Local,
511 Wsl(String),
513 Ssh(crate::backend::remote::conn::SshDest),
517}
518
519pub(crate) async fn for_agent(broker: &Broker, name: Option<&str>) -> Result<AgentTarget, String> {
522 let name = name.unwrap_or_default();
523 ensure(broker, name).await?;
524 Ok(match ConnTarget::parse(name)? {
525 ConnTarget::Local => AgentTarget::Local,
526 ConnTarget::Wsl(distro) => AgentTarget::Wsl(distro),
527 ConnTarget::Ssh(dest) => AgentTarget::Ssh(dest),
528 })
529}
530
531pub(crate) fn agent_label(agent: Option<&str>) -> String {
533 agent
534 .map(|a| one_line(a, 60))
535 .unwrap_or_else(|| "An agent with no AgentMux id".to_string())
536}
537
538pub(crate) fn one_line(text: &str, max: usize) -> String {
541 let flat: String = text
542 .chars()
543 .map(|c| if c.is_control() { ' ' } else { c })
544 .collect();
545 let flat = flat.split_whitespace().collect::<Vec<_>>().join(" ");
546 if flat.chars().count() <= max {
547 flat
548 } else {
549 format!("{}…", flat.chars().take(max).collect::<String>())
550 }
551}
552
553const DIALOG_TIMEOUT_MS: u64 = 120_000;
555
556const SSH_WITH_PROMPTS: std::time::Duration = std::time::Duration::from_millis(DIALOG_TIMEOUT_MS + 30_000);
559
560#[derive(Debug, Default, Clone, serde::Deserialize)]
563pub(crate) struct UserAnswer {
564 #[serde(default)]
565 pub answered: bool,
566 #[serde(default)]
567 pub approve: bool,
568 #[serde(default)]
570 pub text: String,
571 #[serde(default)]
572 pub checkbox: bool,
573}
574
575pub(crate) async fn host_to_ask_user(state: &AppState) -> Result<crate::server::HostIpc, String> {
580 state
581 .host_ipc
582 .lock()
583 .await
584 .clone()
585 .ok_or_else(|| "no AgentMux window is connected to ask the user in".to_string())
586}
587
588pub(crate) async fn ask_user(
599 state: &AppState,
600 agent_block_id: &str,
601 question: serde_json::Value,
602) -> Result<UserAnswer, String> {
603 let host = host_to_ask_user(state).await?;
604 let title = question.get("title").and_then(|t| t.as_str()).unwrap_or("An agent needs your answer").to_string();
607 let _asking = crate::backend::user_attention::Asking::start(&state.broker, &state.mstore, agent_block_id, "consent", &title);
608 let mut body = question;
609 body["block_id"] = serde_json::json!(agent_block_id);
610 body["timeout_ms"] = serde_json::json!(DIALOG_TIMEOUT_MS);
611 let url = format!("http://127.0.0.1:{}/agentmux/approval/ask", host.port);
612 let resp = state
613 .http_client
614 .post(&url)
615 .header("Authorization", format!("Bearer {}", host.token))
616 .timeout(std::time::Duration::from_millis(DIALOG_TIMEOUT_MS + 15_000))
617 .json(&body)
618 .send()
619 .await
620 .map_err(|e| format!("could not ask the user: {e}"))?;
621 if !resp.status().is_success() {
622 return Err(format!(
623 "could not ask the user: the window host answered HTTP {}",
624 resp.status()
625 ));
626 }
627 let v: serde_json::Value = resp
628 .json()
629 .await
630 .map_err(|e| format!("could not ask the user: {e}"))?;
631 if v.get("ok").and_then(|o| o.as_bool()) != Some(true) {
632 let e = v
633 .get("error")
634 .and_then(|e| e.as_str())
635 .unwrap_or("no answer");
636 return Err(format!("could not ask the user: {e}"));
637 }
638 serde_json::from_value(v.get("data").cloned().unwrap_or_default())
639 .map_err(|e| format!("could not ask the user: {e}"))
640}
641
642pub(crate) async fn ask_in_pane(
648 state: &AppState,
649 block_id: &str,
650 question: serde_json::Value,
651) -> Result<UserAnswer, String> {
652 use crate::sagas::pane_confirm;
653 if block_id.is_empty() {
654 return ask_user(state, block_id, question).await;
655 }
656 let a = pane_confirm::ask(state, block_id, pane_confirm::Question::from_json(&question)).await?;
657 Ok(UserAnswer { answered: a.answered, approve: a.approve, text: String::new(), checkbox: a.checkbox })
658}
659
660pub(crate) fn verified_agent(
667 state: &AppState,
668 agent_block_id: &str,
669 auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
670) -> Result<String, String> {
671 verified_agent_as(state, None, agent_block_id, auth)
672}
673
674pub(crate) fn verified_agent_as(
678 state: &AppState,
679 caller: Option<&crate::server::caller::Caller>,
680 agent_block_id: &str,
681 auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
682) -> Result<String, String> {
683 let auth = auth.ok_or_else(|| {
684 "an SSH connection needs the agent's signed identity, which this call did not carry (respawn the agent to give it a signing key)".to_string()
685 })?;
686 let pane = crate::server::ui_handlers::verified_block_id(state, caller, auth)
687 .map_err(|e| format!("could not verify which agent is asking: {e}"))?;
688 if pane != agent_block_id {
689 return Err("this request names another agent's pane".to_string());
690 }
691 Ok(auth.agent_id.clone())
692}
693
694pub(crate) async fn consent_for_ssh(
703 state: &AppState,
704 agent_block_id: &str,
705 agent_id: &str,
706 connection: &str,
707 what: &str,
708) -> Result<(), String> {
709 use crate::sagas::agent_notice::{self, Kind, Notice, Outcome};
710 let agent_id = Some(agent_id.to_string()).filter(|a| !a.trim().is_empty());
711 let agent = agent_label(agent_id.as_deref());
712 let connection = connection.trim();
713 let notice = Notice {
714 kind: Kind::SshAccess,
715 block_id: agent_block_id.to_string(),
716 agent_id: agent_id.clone().unwrap_or_default(),
717 agent: agent.clone(),
718 connection: connection.to_string(),
719 headline: format!("{} is using {}", one_line(&agent, 60), one_line(connection, 80)),
720 body: format!("It will run this on {}, as you, with your SSH keys.", one_line(connection, 80)),
721 quote: one_line(what, 400),
722 always_label: format!("Always allow {} on {}", one_line(&agent, 40), one_line(connection, 80)),
723 waived: None,
724 };
725 let outcome = agent_notice::announce(state, notice, || super::agent_spawn::requester_here(state, agent_block_id)).await;
726 tracing::info!(agent = %agent, connection = %connection, what = %one_line(what, 200), outcome = ?outcome, "agent ssh access");
727 match outcome {
728 Outcome::Go(_) => Ok(()),
729 Outcome::Stopped => Err(format!("the user stopped {agent} using {connection}")),
730 Outcome::Gone => Err(format!("{agent}'s pane was closed before it could use {connection}")),
731 }
732}
733
734pub(crate) fn remember_always_in(
737 broker: &Broker,
738 config_home: &std::path::Path,
739 agent: &str,
740 connection: &str,
741) -> std::io::Result<()> {
742 crate::backend::remote::agent_access::remember_in(config_home, agent, connection)?;
743 remotes::publish_change(broker);
744 Ok(())
745}
746
747#[derive(Debug, serde::Deserialize)]
749pub(crate) struct AskpassRequest {
750 secret: String,
751 prompt: String,
752 #[serde(default)]
754 hint: String,
755}
756
757pub(crate) async fn handle_askpass(
762 axum::extract::State(state): axum::extract::State<AppState>,
763 axum::Json(req): axum::Json<AskpassRequest>,
764) -> axum::response::Response {
765 use crate::backend::remote::askpass::{self, PromptKind};
766 use axum::http::StatusCode;
767 use axum::response::IntoResponse;
768 let refuse = |code: StatusCode, error: String| {
769 (code, axum::Json(serde_json::json!({ "error": error }))).into_response()
770 };
771 let Some(grant) = askpass::lookup(&req.secret) else {
772 return refuse(StatusCode::FORBIDDEN, "no such ssh prompt".to_string());
773 };
774 let kind = askpass::classify(&req.prompt, &req.hint);
775 let question = serde_json::json!({
778 "kind": match kind {
779 PromptKind::YesNo => "yesno",
780 PromptKind::Info => "info",
781 PromptKind::Secret => "secret",
782 },
783 "title": format!("SSH: {}", one_line(&grant.connection, 80)),
784 "message": format!(
785 "ssh, connecting to {} for {}, {}:\n\n{}",
786 one_line(&grant.connection, 80),
787 if grant.user_pane {
788 "your terminal".to_string()
789 } else {
790 agent_label(Some(grant.agent.as_str()).filter(|a| !a.is_empty()))
791 },
792 if kind == PromptKind::Info { "says" } else { "asks" },
793 req.prompt.trim().chars().take(2000).collect::<String>()
794 ),
795 "ok_label": match kind {
796 PromptKind::YesNo => "Yes",
797 PromptKind::Info => "OK",
798 PromptKind::Secret => "OK",
799 },
800 "cancel_label": if kind == PromptKind::YesNo { "No" } else { "Cancel" },
801 });
802 match ask_user(&state, &grant.agent_block_id, question).await {
807 Ok(answer) if answer.answered => {
808 let text = match kind {
810 PromptKind::YesNo if answer.approve => "yes".to_string(),
811 PromptKind::YesNo => "no".to_string(),
812 PromptKind::Secret if answer.approve => answer.text,
813 PromptKind::Secret => {
814 return refuse(StatusCode::GONE, "cancelled".to_string());
815 }
816 PromptKind::Info => String::new(),
817 };
818 axum::Json(serde_json::json!({ "answer": text })).into_response()
819 }
820 Ok(_) => refuse(StatusCode::GONE, "not answered".to_string()),
821 Err(e) => refuse(StatusCode::CONFLICT, e),
822 }
823}
824
825#[derive(Debug, Clone, PartialEq, serde::Serialize)]
827pub(crate) struct ConnEntry {
828 pub connection: String,
829 pub kind: &'static str,
831 pub status: String,
834 #[serde(skip_serializing_if = "String::is_empty")]
835 pub error: String,
836 pub agent_can_use: bool,
840}
841
842pub(crate) fn remote_names(ssh_hosts: &[String], known: &[ConnStatus]) -> Vec<String> {
845 use crate::backend::remote::conn::same_connection;
846 let mut out: Vec<String> = ssh_hosts.to_vec();
847 for s in known {
848 let is_ssh = matches!(ConnTarget::parse(&s.connection), Ok(ConnTarget::Ssh(_)));
849 if is_ssh && !out.iter().any(|n| same_connection(n, &s.connection)) {
850 out.push(s.connection.clone());
851 }
852 }
853 out
854}
855
856pub(crate) fn list(
860 wsl_installed: &[String],
861 ssh_hosts: &[String],
862 known: &[ConnStatus],
863) -> Vec<ConnEntry> {
864 use crate::backend::remote::conn::same_connection;
865 let status_of = |name: &str| known.iter().find(|s| same_connection(&s.connection, name));
866 let mut out = vec![ConnEntry {
867 connection: "local".to_string(),
868 kind: "local",
869 status: state::CONNECTED.to_string(),
870 error: String::new(),
871 agent_can_use: true,
872 }];
873 for distro in wsl_installed {
874 let name = ConnTarget::Wsl(distro.clone()).name();
875 let (status, error) = match status_of(&name) {
876 Some(s) => (s.status.clone(), s.error.clone()),
877 None => ("available".to_string(), String::new()),
878 };
879 out.push(ConnEntry {
880 connection: name,
881 kind: "wsl",
882 status,
883 error,
884 agent_can_use: true,
885 });
886 }
887 for host in ssh_hosts {
888 let (status, error) = match status_of(host) {
889 Some(s) => (s.status.clone(), s.error.clone()),
890 None => ("available".to_string(), String::new()),
891 };
892 out.push(ConnEntry {
893 connection: host.clone(),
894 kind: "ssh",
895 status,
896 error,
897 agent_can_use: true,
898 });
899 }
900 for s in known {
901 if out
902 .iter()
903 .any(|e| same_connection(&e.connection, &s.connection))
904 {
905 continue;
906 }
907 let kind = match ConnTarget::parse(&s.connection) {
908 Ok(ConnTarget::Wsl(_)) => "wsl",
909 Ok(ConnTarget::Ssh(_)) => "ssh",
910 _ => continue,
911 };
912 out.push(ConnEntry {
913 connection: s.connection.clone(),
914 kind,
915 status: s.status.clone(),
916 error: s.error.clone(),
917 agent_can_use: true,
918 });
919 }
920 out
921}
922
923pub(crate) async fn handle_conn_list() -> axum::Json<Vec<ConnEntry>> {
925 let installed = crate::backend::remote::wsl::list().await;
926 let hosts = tokio::task::spawn_blocking(crate::backend::remote::ssh_config::hosts)
927 .await
928 .unwrap_or_default();
929 axum::Json(list(&installed, &hosts, &status::all()))
930}
931
932#[cfg(test)]
933mod tests {
934 use super::*;
935
936 #[test]
937 fn local_is_accepted_and_remote_is_refused_with_a_status() {
938 let broker = Broker::new();
939 let none: &[String] = &[];
940 let ensure = |name: &str| ensure_with(&broker, name, none, true, false);
941 assert_eq!(ensure("local"), Ok(()));
942 assert_eq!(ensure(""), Ok(()));
943
944 let err = ensure("test-ensure-host").unwrap_err();
945 assert!(err.contains("need the ssh command"), "{err}");
946 assert_eq!(
950 ensure_with(&broker, "test-ensure-ssh-ok", none, true, true),
951 Ok(())
952 );
953 assert!(!status::all()
954 .iter()
955 .any(|s| s.connection == "test-ensure-ssh-ok" && s.connected));
956 let st = status::all()
957 .into_iter()
958 .find(|s| s.connection == "test-ensure-host")
959 .unwrap();
960 assert_eq!(
961 (st.status.as_str(), st.error.as_str()),
962 (state::ERROR, err.as_str())
963 );
964
965 assert!(ensure("-oProxyCommand=calc")
967 .unwrap_err()
968 .contains("cannot start with '-'"));
969 assert!(!status::all().iter().any(|s| s.connection.starts_with('-')));
970 }
971
972 #[test]
973 fn an_installed_wsl_distro_connects_and_a_missing_one_says_so() {
974 let broker = Broker::new();
975 let installed = vec!["Ubuntu".to_string(), "Debian".to_string()];
976 assert_eq!(
977 ensure_with(&broker, "wsl://ubuntu", &installed, true, false),
978 Ok(())
979 );
980 let st = status::all()
981 .into_iter()
982 .find(|s| s.connection == "wsl://ubuntu")
983 .unwrap();
984 assert!(st.connected);
985
986 let err = ensure_with(&broker, "wsl://Arch", &installed, true, false).unwrap_err();
987 assert!(err.contains("'Arch' is not installed"), "{err}");
988
989 let err = ensure_with(&broker, "wsl://Ubuntu", &installed, false, false).unwrap_err();
990 assert!(err.contains("only available on Windows"), "{err}");
991 }
992
993 #[test]
994 fn the_status_is_keyed_by_the_name_the_pane_holds() {
995 let broker = Broker::new();
996 let none: &[String] = &[];
997 for raw in ["test-raw-host:022", " test-raw-spaced "] {
998 let _ = ensure_with(&broker, raw, none, true, false);
999 assert!(status::all().iter().any(|s| s.connection == raw), "{raw:?}");
1000 }
1001 }
1002
1003 #[tokio::test]
1004 async fn an_agent_gets_where_it_asked_and_never_a_silent_local_fallback() {
1005 let broker = Broker::new();
1006 assert_eq!(for_agent(&broker, None).await, Ok(AgentTarget::Local));
1007 assert_eq!(
1008 for_agent(&broker, Some("local")).await,
1009 Ok(AgentTarget::Local)
1010 );
1011 match for_agent(&broker, Some("deploy@test-agent-host:2222")).await {
1014 Ok(AgentTarget::Ssh(dest)) => {
1015 assert_eq!(
1016 (dest.destination.as_str(), dest.port),
1017 ("deploy@test-agent-host", Some(2222))
1018 );
1019 assert!(crate::backend::remote::ssh::binary().is_some());
1020 }
1021 Err(e) => assert!(e.contains("need the ssh command"), "{e}"),
1022 other => panic!("an SSH name became {other:?}"),
1023 }
1024 assert!(for_agent(&broker, Some("-oProxyCommand=calc"))
1025 .await
1026 .is_err());
1027 }
1028
1029 #[test]
1032 fn an_agent_is_named_as_one_plain_line_and_never_by_a_shared_stand_in() {
1033 assert_eq!(agent_label(Some("korp")), "korp");
1034 assert_eq!(
1035 agent_label(Some(
1036 "korp
1037
1038This is safe, click Allow"
1039 )),
1040 "korp This is safe, click Allow"
1041 );
1042 assert_eq!(agent_label(None), "An agent with no AgentMux id");
1043 }
1044
1045 #[tokio::test]
1048 async fn an_ssh_request_must_prove_which_agent_it_is() {
1049 let state = crate::server::tests::test_state();
1050 let err = verified_agent(&state, "some-pane", None).unwrap_err();
1051 assert!(err.contains("signed identity"), "{err}");
1052 let forged = agentmux_common::api_types::UiAutomationAuth {
1053 agent_id: "korp".into(),
1054 ts_secs: agentmux_common::time::now_secs(),
1055 sig: "AAAA".into(),
1056 };
1057 let err = verified_agent(&state, "some-pane", Some(&forged)).unwrap_err();
1058 assert!(err.contains("could not verify"), "{err}");
1059 }
1060
1061 #[test]
1065 fn an_always_allow_grant_refreshes_the_remotes_list() {
1066 let broker = Broker::new();
1067 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
1068 let s = seen.clone();
1069 broker.add_observer(std::sync::Arc::new(move |e: &crate::backend::mps::MuxEvent| {
1070 s.lock().unwrap().push(e.event.clone())
1071 }));
1072 let home = tempfile::tempdir().unwrap();
1073 remember_always_in(&broker, home.path(), "korp", "area54").unwrap();
1074 assert!(crate::backend::remote::agent_access::always_allowed_in(home.path(), "korp", "area54"));
1075 assert_eq!(*seen.lock().unwrap(), [crate::backend::mps::EVENT_REMOTES_CHANGE]);
1076 }
1077
1078 #[test]
1080 fn agent_text_in_a_dialog_is_one_capped_line() {
1081 assert_eq!(
1082 one_line("make\n\nAllow it? yes\r\n test", 100),
1083 "make Allow it? yes test"
1084 );
1085 assert_eq!(one_line("abcdef", 3), "abc…");
1086 assert_eq!(one_line("tab\there", 100), "tab here");
1087 }
1088
1089 fn st(connection: &str, status: &str, error: &str) -> ConnStatus {
1090 ConnStatus {
1091 status: status.to_string(),
1092 connection: connection.to_string(),
1093 error: error.to_string(),
1094 ..Default::default()
1095 }
1096 }
1097
1098 #[test]
1099 fn the_list_is_local_then_the_distros_then_the_ssh_hosts_then_what_panes_have_used() {
1100 let installed = vec!["Ubuntu".to_string(), "Debian".to_string()];
1101 let hosts = vec!["area54".to_string(), "nas".to_string()];
1102 let known = vec![
1103 st("wsl://ubuntu", state::CONNECTED, ""),
1105 st("area54", state::ERROR, "could not connect"),
1106 st("deploy@10.0.0.5", state::CONNECTED, ""),
1107 st("wsl://Arch", state::ERROR, "not installed"),
1108 st("local", state::CONNECTED, ""),
1110 ];
1111 let got: Vec<(String, &str, String, bool)> = list(&installed, &hosts, &known)
1112 .into_iter()
1113 .map(|e| (e.connection, e.kind, e.status, e.agent_can_use))
1114 .collect();
1115 let want = [
1116 ("local", "local", "connected", true),
1117 ("wsl://Ubuntu", "wsl", "connected", true),
1118 ("wsl://Debian", "wsl", "available", true),
1119 ("area54", "ssh", "error", true),
1120 ("nas", "ssh", "available", true),
1121 ("deploy@10.0.0.5", "ssh", "connected", true),
1122 ("wsl://Arch", "wsl", "error", true),
1123 ];
1124 let want: Vec<(String, &str, String, bool)> = want
1125 .iter()
1126 .map(|(c, k, s, a)| (c.to_string(), *k, s.to_string(), *a))
1127 .collect();
1128 assert_eq!(got, want);
1129 }
1130
1131 #[test]
1134 fn the_picker_gets_the_ssh_hosts_and_the_ssh_connections_used() {
1135 let hosts = vec!["area54".to_string(), "nas".to_string()];
1136 let known = vec![
1137 st("area54", state::CONNECTED, ""),
1138 st("deploy@10.0.0.5:2222", state::DISCONNECTED, ""),
1139 st("wsl://Ubuntu", state::CONNECTED, ""),
1140 st("local", state::CONNECTED, ""),
1141 ];
1142 assert_eq!(
1143 remote_names(&hosts, &known),
1144 ["area54", "nas", "deploy@10.0.0.5:2222"]
1145 );
1146 }
1147
1148 fn state() -> AppState {
1149 crate::server::tests::test_state()
1150 }
1151
1152 #[tokio::test]
1153 async fn ending_a_session_needs_the_pane_asking_and_a_real_session_id() {
1154 let state = state();
1155 let end = |block: &str, id: &str| serde_json::json!({ "connname": "host", "sessionid": id, "blockid": block });
1156 let err = conn_session_end(&state, &end("", "s-1")).await.unwrap_err();
1157 assert_eq!(err, "ending a session needs the pane asking, to ask the user in");
1158 let err = conn_session_end(&state, &end("blk", "../x")).await.unwrap_err();
1159 assert!(err.contains("is not a session id"), "{err}");
1160 }
1161
1162 #[tokio::test]
1163 async fn disconnecting_a_wsl_distro_marks_it_disconnected() {
1164 let broker = Broker::new();
1165 conn_disconnect(&broker, &serde_json::json!("wsl://test-disconnect-distro")).await.unwrap();
1166 let st = status::all().into_iter().find(|s| s.connection == "wsl://test-disconnect-distro").expect("a status was recorded");
1167 assert_eq!(st.status, state::DISCONNECTED);
1168 conn_disconnect(&broker, &serde_json::json!(null)).await.unwrap();
1170 }
1171
1172 #[tokio::test]
1173 async fn the_remotes_commands_refuse_local_and_revoke_refuses_a_non_ssh_host() {
1174 let state = state();
1175 let err = remote_forget(&state, CommandRemoteForgetData { connection: "local".into() }).unwrap_err();
1176 assert_eq!(err, "local is not a remote");
1177 let cfg = CommandRemoteSetConfigData { connection: "local".into(), values: Default::default() };
1178 assert_eq!(remote_set_config(&state, cfg).unwrap_err(), "local is not a remote");
1179 let revoke = CommandRemoteAgentRevokeData { agent: "a".into(), connection: "wsl://Ubuntu".into() };
1180 assert!(remote_agent_revoke(&state, revoke).unwrap_err().ends_with(NOT_SSH));
1181 }
1182}