BlueGit

ict rusty-teams

Files

rusty-teams / crates / agents / src / inbox.rs

inbox.rs

inbox.rs 9.3 KiB Download Raw
1use std::fmt;
2use std::io::Write;
3use std::path::Path;
4use std::process::{Command, Stdio};
5use std::time::Duration;
6
7use serde::Serialize;
8
9use crate::profile::Environment;
10use crate::sessions::RunningSession;
11
12const SENDER: &str = "rusty-teams";
13const SOCKET_TIMEOUT: Duration = Duration::from_secs(5);
14const WSL_PROGRAM: &str = "wsl.exe";
15const SOCKET_RELAY_SCRIPT: &str = "import socket,sys;s=socket.socket(socket.AF_UNIX);s.settimeout(5);s.connect(sys.argv[1]);s.sendall(sys.stdin.buffer.read());s.close()";
16#[cfg(windows)]
17const CREATE_NO_WINDOW: u32 = 0x0800_0000;
18
19#[derive(Debug, PartialEq, Eq)]
20pub enum DeliveryError {
21 SessionGone,
22 Failed(String),
23}
24
25impl fmt::Display for DeliveryError {
26 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
27 match self {
28 DeliveryError::SessionGone => formatter.write_str("the session is no longer running"),
29 DeliveryError::Failed(message) => formatter.write_str(message),
30 }
31 }
32}
33
34impl std::error::Error for DeliveryError {}
35
36struct PeerToken(String);
37
38impl fmt::Debug for PeerToken {
39 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
40 formatter.write_str("PeerToken(..)")
41 }
42}
43
44#[derive(Serialize)]
45struct AuthFrame<'a> {
46 #[serde(rename = "type")]
47 kind: &'a str,
48 token: &'a str,
49}
50
51#[derive(Serialize)]
52struct UserFrame<'a> {
53 #[serde(rename = "type")]
54 kind: &'a str,
55 message: UserMessage<'a>,
56 from: &'a str,
57 msg_id: &'a str,
58}
59
60#[derive(Serialize)]
61struct UserMessage<'a> {
62 content: &'a str,
63}
64
65pub fn inbox_frame(token: &str, content: &str, message_id: &str) -> String {
66 let auth = AuthFrame {
67 kind: "auth",
68 token,
69 };
70 let user = UserFrame {
71 kind: "user",
72 message: UserMessage { content },
73 from: SENDER,
74 msg_id: message_id,
75 };
76 format!(
77 "{}\n{}\n",
78 serde_json::to_string(&auth).unwrap_or_default(),
79 serde_json::to_string(&user).unwrap_or_default()
80 )
81}
82
83fn read_peer_token(sessions_dir: &Path, process_id: u32) -> Option<PeerToken> {
84 let prefix = format!("{process_id}.");
85 std::fs::read_dir(sessions_dir)
86 .ok()?
87 .flatten()
88 .filter(|entry| {
89 let name = entry.file_name();
90 let name = name.to_string_lossy();
91 name.starts_with(&prefix) && name.ends_with(".key")
92 })
93 .find_map(|entry| {
94 let value: serde_json::Value =
95 serde_json::from_str(&std::fs::read_to_string(entry.path()).ok()?).ok()?;
96 value["peerToken"]
97 .as_str()
98 .map(|token| PeerToken(token.to_owned()))
99 })
100}
101
102pub fn deliver(
103 environment: &Environment,
104 sessions_dir: &Path,
105 session: &RunningSession,
106 content: &str,
107) -> Result<(), DeliveryError> {
108 let socket_path = session
109 .socket_path
110 .as_deref()
111 .ok_or_else(|| DeliveryError::Failed("the session does not accept messages".to_owned()))?;
112 let token = read_peer_token(sessions_dir, session.process_id).ok_or_else(|| {
113 DeliveryError::Failed("the session's message key is not readable".to_owned())
114 })?;
115 let frame = inbox_frame(&token.0, content, &uuid::Uuid::new_v4().to_string());
116 match environment {
117 Environment::Wsl { distro } => send_through_wsl(distro.as_deref(), socket_path, &frame),
118 Environment::Host => send_on_host(socket_path, &frame),
119 }
120}
121
122#[cfg(unix)]
123fn send_on_host(socket_path: &str, frame: &str) -> Result<(), DeliveryError> {
124 use std::os::unix::net::UnixStream;
125
126 let mut stream = UnixStream::connect(socket_path).map_err(|error| match error.kind() {
127 std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused => {
128 DeliveryError::SessionGone
129 }
130 _ => DeliveryError::Failed(format!("cannot connect to the session: {error}")),
131 })?;
132 let failed = |error: std::io::Error| DeliveryError::Failed(format!("send failed: {error}"));
133 stream
134 .set_write_timeout(Some(SOCKET_TIMEOUT))
135 .map_err(failed)?;
136 stream.write_all(frame.as_bytes()).map_err(failed)
137}
138
139#[cfg(not(unix))]
140fn send_on_host(_socket_path: &str, _frame: &str) -> Result<(), DeliveryError> {
141 Err(DeliveryError::Failed(
142 "delivery to Windows-native sessions is not supported".to_owned(),
143 ))
144}
145
146fn send_through_wsl(
147 distro: Option<&str>,
148 socket_path: &str,
149 frame: &str,
150) -> Result<(), DeliveryError> {
151 let mut command = Command::new(WSL_PROGRAM);
152 if let Some(distro) = distro {
153 command.args(["-d", distro]);
154 }
155 command
156 .args(["-e", "python3", "-c", SOCKET_RELAY_SCRIPT, socket_path])
157 .stdin(Stdio::piped())
158 .stdout(Stdio::null())
159 .stderr(Stdio::piped());
160 #[cfg(windows)]
161 {
162 use std::os::windows::process::CommandExt;
163 command.creation_flags(CREATE_NO_WINDOW);
164 }
165 let mut child = command
166 .spawn()
167 .map_err(|error| DeliveryError::Failed(format!("cannot start {WSL_PROGRAM}: {error}")))?;
168 let written = child
169 .stdin
170 .take()
171 .map(|mut stdin| stdin.write_all(frame.as_bytes()));
172 let output = child
173 .wait_with_output()
174 .map_err(|error| DeliveryError::Failed(format!("send failed: {error}")))?;
175 if output.status.success() {
176 return Ok(());
177 }
178 let stderr = String::from_utf8_lossy(&output.stderr);
179 if stderr.contains("ConnectionRefusedError") || stderr.contains("FileNotFoundError") {
180 return Err(DeliveryError::SessionGone);
181 }
182 let detail = stderr.lines().last().unwrap_or_default().trim();
183 let write_note = match written {
184 Some(Err(error)) => format!(" ({error})"),
185 _ => String::new(),
186 };
187 Err(DeliveryError::Failed(format!(
188 "delivery failed: {detail}{write_note}"
189 )))
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[test]
197 fn the_frame_is_an_auth_line_then_a_user_line() {
198 assert_eq!(
199 inbox_frame("tok", "Hi \"you\"\nbye", "id-1"),
200 "{\"type\":\"auth\",\"token\":\"tok\"}\n{\"type\":\"user\",\"message\":{\"content\":\"Hi \\\"you\\\"\\nbye\"},\"from\":\"rusty-teams\",\"msg_id\":\"id-1\"}\n"
201 );
202 }
203
204 #[test]
205 fn errors_and_the_token_wrapper_never_show_the_token() {
206 let token = PeerToken("s3cret".to_owned());
207 assert!(!format!("{token:?}").contains("s3cret"));
208 for error in [
209 DeliveryError::SessionGone,
210 DeliveryError::Failed("delivery failed: boom".to_owned()),
211 ] {
212 assert!(!format!("{error:?} {error}").contains("s3cret"));
213 }
214 }
215
216 #[test]
217 fn a_session_without_a_socket_cannot_be_delivered_to() {
218 let directory = tempfile::tempdir().unwrap();
219 let session = RunningSession {
220 session_id: "abc".to_owned(),
221 name: None,
222 working_dir: String::new(),
223 socket_path: None,
224 process_id: 1,
225 };
226 assert!(matches!(
227 deliver(&Environment::Host, directory.path(), &session, "hi"),
228 Err(DeliveryError::Failed(_))
229 ));
230 }
231
232 #[cfg(unix)]
233 mod unix {
234 use std::io::Read;
235 use std::os::unix::net::UnixListener;
236
237 use super::*;
238
239 fn session(socket_path: &Path, process_id: u32) -> RunningSession {
240 RunningSession {
241 session_id: "abc".to_owned(),
242 name: None,
243 working_dir: String::new(),
244 socket_path: Some(socket_path.to_string_lossy().into_owned()),
245 process_id,
246 }
247 }
248
249 #[test]
250 fn a_host_delivery_writes_both_lines_to_the_socket() {
251 let directory = tempfile::tempdir().unwrap();
252 let socket_path = directory.path().join("s.sock");
253 let listener = UnixListener::bind(&socket_path).unwrap();
254 std::fs::write(
255 directory.path().join("42.ab12.key"),
256 r#"{"peerToken":"tok"}"#,
257 )
258 .unwrap();
259 let reader = std::thread::spawn(move || {
260 let (mut stream, _) = listener.accept().unwrap();
261 let mut received = String::new();
262 stream.read_to_string(&mut received).unwrap();
263 received
264 });
265 deliver(
266 &Environment::Host,
267 directory.path(),
268 &session(&socket_path, 42),
269 "hello",
270 )
271 .unwrap();
272 let received = reader.join().unwrap();
273 let lines: Vec<&str> = received.lines().collect();
274 assert_eq!(lines.len(), 2);
275 assert_eq!(lines[0], r#"{"type":"auth","token":"tok"}"#);
276 assert!(lines[1].starts_with(
277 r#"{"type":"user","message":{"content":"hello"},"from":"rusty-teams","msg_id":""#
278 ));
279 }
280
281 #[test]
282 fn a_missing_socket_means_the_session_is_gone() {
283 let directory = tempfile::tempdir().unwrap();
284 std::fs::write(
285 directory.path().join("42.ab12.key"),
286 r#"{"peerToken":"tok"}"#,
287 )
288 .unwrap();
289 let result = deliver(
290 &Environment::Host,
291 directory.path(),
292 &session(&directory.path().join("none.sock"), 42),
293 "hello",
294 );
295 assert_eq!(result, Err(DeliveryError::SessionGone));
296 }
297 }
298}