1use std::path::{Path, PathBuf};
15
16use agentmux_common::api_types::FileRenameRequest;
17
18use super::*;
19use crate::backend::remote::ConnTarget;
20use crate::backend::rpc_types::FsRenameReq;
21
22const NO_REMOTE_FOR_CONTAINERS: &str = "A container agent can't rename a file on another machine: an SSH host is reached as the user. \
24 Rename it from a shell you have on that machine, or ask a native agent or your leader.";
25const NO_WSL: &str = "Pane rename takes an SSH host as its connection. For a file in a WSL distribution, \
27 give its Windows path (\\\\wsl.localhost\\<distribution>\\...) and no connection.";
28const NO_WORKSPACE: &str = "This agent's workspace folder isn't known to AgentMux, so nothing in it can be renamed here. \
30 Rename the file in your own shell.";
31
32type Refusal = (StatusCode, String);
34
35fn forbidden(why: String) -> Refusal {
36 (StatusCode::FORBIDDEN, why)
37}
38
39fn not_done(why: String) -> Refusal {
41 (StatusCode::UNPROCESSABLE_ENTITY, why)
42}
43
44pub(super) async fn handle_file_rename(
46 State(state): State<AppState>,
47 grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
48 Json(req): Json<FileRenameRequest>,
49) -> impl IntoResponse {
50 let container = grant.map(|g| g.0.block_id);
51 match rename_file(&state, container.as_deref(), req).await {
52 Ok(new_path) => (StatusCode::OK, Json(json!({ "success": true, "new_path": new_path }))).into_response(),
53 Err((status, why)) => (status, Json(json!({ "error": why }))).into_response(),
54 }
55}
56
57pub(crate) async fn rename_file(state: &AppState, container: Option<&str>, req: FileRenameRequest) -> Result<String, Refusal> {
60 let path = req.path.trim().to_string();
61 if path.is_empty() {
62 return Err((StatusCode::BAD_REQUEST, "path must not be empty".to_string()));
63 }
64 if req.name.trim().is_empty() {
65 return Err((StatusCode::BAD_REQUEST, "name must not be empty".to_string()));
66 }
67 let ssh = ssh_host(req.connection.as_deref()).map_err(|why| (StatusCode::BAD_REQUEST, why))?;
68 if let Some(block) = container {
69 if ssh.is_some() {
70 return Err(forbidden(NO_REMOTE_FOR_CONTAINERS.to_string()));
71 }
72 let workspace = super::container_workspace::workspace_of(state, block).ok_or_else(|| forbidden(NO_WORKSPACE.to_string()))?;
73 return rename_in_workspace(state, workspace, path, req.name).await;
74 }
75 let mut block_id = None;
76 if let Some(conn) = &ssh {
77 let block = req.block_id.clone().unwrap_or_default();
78 let agent = app_api::connections::verified_agent(state, &block, req.auth.as_ref()).map_err(forbidden)?;
79 let what = format!("rename {path} to {}", req.name);
80 app_api::connections::consent_for_ssh(state, &block, &agent, conn, &what).await.map_err(forbidden)?;
81 block_id = Some(block);
82 }
83 let cmd = FsRenameReq { path, new_name: req.name, connection: ssh, block_id };
84 super::fs_handlers::fs_rename(state, cmd).await.map(|done| done.new_path).map_err(not_done)
85}
86
87async fn rename_in_workspace(state: &AppState, workspace: PathBuf, raw: String, name: String) -> Result<String, Refusal> {
90 let found = tokio::task::spawn_blocking(move || super::container_workspace::entry_inside(&workspace, &raw))
92 .await
93 .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("the path couldn't be checked: {e}")))?;
94 let (entry, folder) = found.map_err(forbidden)?;
95 let cmd = FsRenameReq { path: entry.to_string_lossy().into_owned(), new_name: name.clone(), connection: None, block_id: None };
96 let done = super::fs_handlers::fs_rename(state, cmd).await.map_err(not_done)?;
97 let new_name = Path::new(&done.new_path).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or(name);
98 Ok(format!("{}/{new_name}", folder.trim_end_matches('/')))
99}
100
101fn ssh_host(connection: Option<&str>) -> Result<Option<String>, String> {
104 let Some(name) = connection.map(str::trim).filter(|c| !c.is_empty()) else {
105 return Ok(None);
106 };
107 match ConnTarget::parse(name) {
108 Ok(ConnTarget::Local) => Ok(None),
109 Ok(target @ ConnTarget::Ssh(_)) => Ok(Some(target.name())),
110 Ok(ConnTarget::Wsl(_)) => Err(NO_WSL.to_string()),
111 Err(why) => Err(format!("connection {name:?} is not an SSH host: {why}")),
112 }
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118
119 fn req(path: impl Into<String>, name: &str) -> FileRenameRequest {
120 FileRenameRequest { path: path.into(), name: name.to_string(), connection: None, block_id: None, auth: None }
121 }
122
123 fn renames_seen(state: &AppState) -> std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>> {
125 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
126 let sink = seen.clone();
127 state.broker.add_observer(std::sync::Arc::new(move |e: &crate::backend::mps::MuxEvent| {
128 if e.event == "fs:renamed" {
129 sink.lock().unwrap().push(e.data.clone().unwrap_or_default());
130 }
131 }));
132 seen
133 }
134
135 #[tokio::test]
137 async fn a_rename_on_the_host_answers_the_new_path_and_tells_the_windows_once() {
138 let state = crate::server::tests::test_state();
139 let seen = renames_seen(&state);
140 let dir = tempfile::tempdir().unwrap();
141 let old = dir.path().join("a.txt");
142 std::fs::write(&old, "a").unwrap();
143
144 let new_path = rename_file(&state, None, req(old.to_string_lossy(), "b.txt")).await.unwrap();
145 assert!(dir.path().join("b.txt").exists() && !old.exists());
146 assert!(new_path.ends_with("b.txt"), "{new_path}");
147 let events = seen.lock().unwrap();
148 assert_eq!(events.len(), 1);
149 assert_eq!(events[0]["new_path"], new_path);
150 }
151
152 #[tokio::test]
154 async fn a_refusal_is_a_sentence_and_renames_nothing() {
155 let state = crate::server::tests::test_state();
156 let seen = renames_seen(&state);
157 let dir = tempfile::tempdir().unwrap();
158 let old = dir.path().join("a.txt");
159 std::fs::write(&old, "a").unwrap();
160 std::fs::write(dir.path().join("taken.txt"), "t").unwrap();
161 let path = old.to_string_lossy().into_owned();
162
163 let (status, why) = rename_file(&state, None, req(&path, "taken.txt")).await.unwrap_err();
164 assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
165 assert!(why.contains("already exists"), "{why}");
166 let (status, _) = rename_file(&state, None, req(&path, "sub/b.txt")).await.unwrap_err();
168 assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
169 let gone = dir.path().join("gone.txt").to_string_lossy().into_owned();
170 let (status, _) = rename_file(&state, None, req(gone, "b.txt")).await.unwrap_err();
171 assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
172
173 assert_eq!(rename_file(&state, None, req(" ", "b.txt")).await.unwrap_err(), (StatusCode::BAD_REQUEST, "path must not be empty".to_string()));
174 assert_eq!(rename_file(&state, None, req(&path, " ")).await.unwrap_err(), (StatusCode::BAD_REQUEST, "name must not be empty".to_string()));
175 let mut wsl = req(&path, "b.txt");
176 wsl.connection = Some("wsl://Ubuntu".to_string());
177 assert_eq!(rename_file(&state, None, wsl).await.unwrap_err(), (StatusCode::BAD_REQUEST, NO_WSL.to_string()));
178
179 assert!(old.exists(), "nothing was renamed");
180 assert!(seen.lock().unwrap().is_empty());
181 }
182
183 #[tokio::test]
185 async fn an_ssh_host_without_the_agents_identity_is_refused() {
186 let state = crate::server::tests::test_state();
187 let mut remote = req("~/a.txt", "b.txt");
188 remote.connection = Some("devbox".to_string());
189 remote.block_id = Some("blk".to_string());
190 let (status, why) = rename_file(&state, None, remote).await.unwrap_err();
191 assert_eq!(status, StatusCode::FORBIDDEN);
192 assert!(why.contains("signed identity"), "{why}");
193 }
194
195 #[test]
196 fn a_connection_is_an_ssh_host_or_this_computer() {
197 assert_eq!(ssh_host(None), Ok(None));
198 assert_eq!(ssh_host(Some(" ")), Ok(None));
199 assert_eq!(ssh_host(Some("local")), Ok(None));
200 assert_eq!(ssh_host(Some(" me@devbox:2222 ")), Ok(Some("me@devbox:2222".to_string())));
201 assert_eq!(ssh_host(Some("wsl://Ubuntu")), Err(NO_WSL.to_string()));
202 assert!(ssh_host(Some("dev box")).unwrap_err().contains("is not an SSH host"));
203 }
204
205 #[tokio::test]
207 async fn a_container_agent_renames_inside_its_workspace_and_is_answered_in_its_own_names() {
208 let state = crate::server::tests::test_state();
209 let seen = renames_seen(&state);
210 let root = tempfile::tempdir().unwrap();
211 let ws = root.path().join("ws");
212 std::fs::create_dir_all(ws.join("src")).unwrap();
213 std::fs::write(ws.join("src/a.rs"), "a").unwrap();
214 std::fs::write(ws.join("top.txt"), "t").unwrap();
215
216 let new_path = rename_in_workspace(&state, ws.clone(), "/workspace/src/a.rs".to_string(), "b.rs".to_string()).await.unwrap();
217 assert_eq!(new_path, "/workspace/src/b.rs");
218 assert!(ws.join("src/b.rs").exists() && !ws.join("src/a.rs").exists());
219 let new_path = rename_in_workspace(&state, ws.clone(), "top.txt".to_string(), "first.txt".to_string()).await.unwrap();
221 assert_eq!(new_path, "/workspace/first.txt");
222 assert!(ws.join("first.txt").exists());
223 assert_eq!(seen.lock().unwrap().len(), 2, "the windows hear of each, by its host path");
224 }
225
226 #[tokio::test]
228 async fn a_container_agent_is_refused_outside_its_workspace() {
229 let state = crate::server::tests::test_state();
230 let seen = renames_seen(&state);
231 let root = tempfile::tempdir().unwrap();
232 let ws = root.path().join("ws");
233 std::fs::create_dir_all(&ws).unwrap();
234 let outside = root.path().join("secret.txt");
235 std::fs::write(&outside, "s").unwrap();
236
237 for given in ["/workspace/../secret.txt".to_string(), "../secret.txt".to_string(), outside.to_string_lossy().into_owned()] {
238 let (status, why) = rename_in_workspace(&state, ws.clone(), given.clone(), "mine.txt".to_string()).await.unwrap_err();
239 assert_eq!(status, StatusCode::FORBIDDEN, "{given}");
240 assert!(why.contains("outside this agent's workspace") && why.contains("/workspace"), "{given}: {why}");
241 }
242 let (status, _) = rename_in_workspace(&state, ws.clone(), "/workspace".to_string(), "other".to_string()).await.unwrap_err();
244 assert_eq!(status, StatusCode::FORBIDDEN);
245 assert!(outside.exists() && ws.exists());
246 assert!(seen.lock().unwrap().is_empty());
247
248 let mut remote = req("/workspace/a.txt", "b.txt");
250 remote.connection = Some("devbox".to_string());
251 assert_eq!(rename_file(&state, Some("blk"), remote).await.unwrap_err(), (StatusCode::FORBIDDEN, NO_REMOTE_FOR_CONTAINERS.to_string()));
252 assert_eq!(
253 rename_file(&state, Some("no-such-pane"), req("/workspace/a.txt", "b.txt")).await.unwrap_err(),
254 (StatusCode::FORBIDDEN, NO_WORKSPACE.to_string())
255 );
256 }
257
258 #[cfg(unix)]
260 #[tokio::test]
261 async fn a_container_agents_link_is_renamed_itself_not_its_target() {
262 let state = crate::server::tests::test_state();
263 let root = tempfile::tempdir().unwrap();
264 let ws = root.path().join("ws");
265 std::fs::create_dir_all(&ws).unwrap();
266 let outside = root.path().join("secret.txt");
267 std::fs::write(&outside, "s").unwrap();
268 std::os::unix::fs::symlink(&outside, ws.join("link.txt")).unwrap();
269 std::os::unix::fs::symlink(root.path(), ws.join("out")).unwrap();
270
271 let new_path = rename_in_workspace(&state, ws.clone(), "/workspace/link.txt".to_string(), "moved.txt".to_string()).await.unwrap();
272 assert_eq!(new_path, "/workspace/moved.txt");
273 assert!(ws.join("moved.txt").symlink_metadata().unwrap().file_type().is_symlink());
274 assert!(outside.exists(), "the target keeps its name");
275 let (status, why) = rename_in_workspace(&state, ws.clone(), "/workspace/out/secret.txt".to_string(), "x".to_string()).await.unwrap_err();
277 assert_eq!(status, StatusCode::FORBIDDEN);
278 assert!(why.contains("outside this agent's workspace"), "{why}");
279 }
280}