1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//! WebSocket handler for real-time command streaming.
use std::time::Duration;
use axum::{
extract::{
ws::{Message, WebSocket, WebSocketUpgrade},
Path, State,
},
response::IntoResponse,
};
use futures_util::{SinkExt, StreamExt};
use super::handlers::AppState;
use super::types::WsMessage;
use crate::execution::Command;
use crate::session::SessionId;
/// WebSocket upgrade handler.
pub async fn ws_handler(
ws: WebSocketUpgrade,
State(state): State<AppState>,
Path(session_id): Path<u64>,
identity: Option<axum::Extension<crate::audit::Identity>>,
) -> impl IntoResponse {
// Taken here because extensions belong to the upgrade request, not to the
// socket that outlives it.
let identity = identity.map(|axum::Extension(id)| id);
ws.on_upgrade(move |socket| handle_socket(socket, state, session_id, identity))
}
/// Handle WebSocket connection.
async fn handle_socket(
socket: WebSocket,
state: AppState,
session_id: u64,
identity: Option<crate::audit::Identity>,
) {
let id = SessionId::from_raw(session_id);
// Verify session exists
if state.store.get(&id).ok().flatten().is_none() {
let (mut sink, _) = socket.split();
let err = WsMessage::Error {
code: "SESSION_NOT_FOUND".to_string(),
message: format!("Session {} not found", session_id),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
return;
}
let (mut sink, mut stream) = socket.split();
// Process incoming messages
while let Some(msg) = stream.next().await {
let msg = match msg {
Ok(Message::Text(text)) => text.to_string(),
Ok(Message::Close(_)) => break,
Ok(Message::Ping(data)) => {
let _ = sink.send(Message::Pong(data)).await;
continue;
}
Ok(_) => continue,
Err(_) => break,
};
// Parse WebSocket message
let ws_msg: WsMessage = match serde_json::from_str(&msg) {
Ok(m) => m,
Err(e) => {
let err = WsMessage::Error {
code: "PARSE_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
continue;
}
};
match ws_msg {
WsMessage::Execute {
command,
timeout_secs,
} => {
// Build command
let mut cmd = Command::new(&command);
if let Some(secs) = timeout_secs {
cmd = cmd.timeout(Duration::from_secs(secs));
}
// Execute with streaming
match state.executor.execute_async(&cmd).await {
Ok((mut rx, handle)) => {
// Stream output chunks
while let Some(chunk) = rx.recv().await {
let output = WsMessage::Output {
data: String::from_utf8_lossy(&chunk.raw).to_string(),
is_final: false,
};
if let Ok(json) = serde_json::to_string(&output) {
if sink.send(Message::Text(json.into())).await.is_err() {
break;
}
}
}
// Wait for completion and send result
match handle.await {
Ok(Ok(result)) => {
state.audit.record(
crate::audit::AuditEvent::new("execute")
.with_identity(identity.clone())
.with_route("WS /api/v1/sessions/{id}/ws")
.with_command(&command)
.with_session(session_id)
.with_outcome(
result.exit_code,
result.timed_out,
result.duration.as_millis() as u64,
),
);
// Update session context
state
.store
.update(&id, |s| {
s.context.record_execution(&command, result.exit_code);
})
.ok();
let result_msg = WsMessage::Result {
success: result.exit_code.map(|c| c == 0).unwrap_or(false)
&& !result.timed_out,
exit_code: result.exit_code,
duration_ms: result.duration.as_millis() as u64,
timed_out: result.timed_out,
};
if let Ok(json) = serde_json::to_string(&result_msg) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
Ok(Err(e)) => {
let err = WsMessage::Error {
code: "EXECUTION_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
Err(e) => {
let err = WsMessage::Error {
code: "TASK_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
}
}
Err(e) => {
let err = WsMessage::Error {
code: "EXECUTION_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
}
}
WsMessage::Ping => {
let pong = WsMessage::Pong;
if let Ok(json) = serde_json::to_string(&pong) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
_ => {
// Ignore other message types from client
}
}
}
}
/// One-shot WebSocket execution (no session required).
pub async fn ws_oneshot_handler(
ws: WebSocketUpgrade,
State(state): State<AppState>,
identity: Option<axum::Extension<crate::audit::Identity>>,
) -> impl IntoResponse {
let identity = identity.map(|axum::Extension(id)| id);
ws.on_upgrade(move |socket| handle_oneshot_socket(socket, state, identity))
}
/// Handle one-shot WebSocket connection.
async fn handle_oneshot_socket(
socket: WebSocket,
state: AppState,
identity: Option<crate::audit::Identity>,
) {
let (mut sink, mut stream) = socket.split();
while let Some(msg) = stream.next().await {
let msg = match msg {
Ok(Message::Text(text)) => text.to_string(),
Ok(Message::Close(_)) => break,
Ok(Message::Ping(data)) => {
let _ = sink.send(Message::Pong(data)).await;
continue;
}
Ok(_) => continue,
Err(_) => break,
};
let ws_msg: WsMessage = match serde_json::from_str(&msg) {
Ok(m) => m,
Err(e) => {
let err = WsMessage::Error {
code: "PARSE_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
continue;
}
};
match ws_msg {
WsMessage::Execute {
command,
timeout_secs,
} => {
let mut cmd = Command::new(&command);
if let Some(secs) = timeout_secs {
cmd = cmd.timeout(Duration::from_secs(secs));
}
match state.executor.execute_async(&cmd).await {
Ok((mut rx, handle)) => {
while let Some(chunk) = rx.recv().await {
let output = WsMessage::Output {
data: String::from_utf8_lossy(&chunk.raw).to_string(),
is_final: false,
};
if let Ok(json) = serde_json::to_string(&output) {
if sink.send(Message::Text(json.into())).await.is_err() {
break;
}
}
}
match handle.await {
Ok(Ok(result)) => {
state.audit.record(
crate::audit::AuditEvent::new("execute")
.with_identity(identity.clone())
.with_route("WS /api/v1/ws")
.with_command(&command)
.with_outcome(
result.exit_code,
result.timed_out,
result.duration.as_millis() as u64,
),
);
let result_msg = WsMessage::Result {
success: result.exit_code.map(|c| c == 0).unwrap_or(false)
&& !result.timed_out,
exit_code: result.exit_code,
duration_ms: result.duration.as_millis() as u64,
timed_out: result.timed_out,
};
if let Ok(json) = serde_json::to_string(&result_msg) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
Ok(Err(e)) => {
let err = WsMessage::Error {
code: "EXECUTION_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
Err(e) => {
let err = WsMessage::Error {
code: "TASK_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
}
}
Err(e) => {
let err = WsMessage::Error {
code: "EXECUTION_ERROR".to_string(),
message: e.to_string(),
};
if let Ok(json) = serde_json::to_string(&err) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
}
}
WsMessage::Ping => {
let pong = WsMessage::Pong;
if let Ok(json) = serde_json::to_string(&pong) {
let _ = sink.send(Message::Text(json.into())).await;
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ws_message_execute_parse() {
let json = r#"{"type": "execute", "command": "echo hello"}"#;
let msg: WsMessage = serde_json::from_str(json).unwrap();
match msg {
WsMessage::Execute { command, .. } => assert_eq!(command, "echo hello"),
_ => panic!("Expected Execute message"),
}
}
#[test]
fn test_ws_message_ping_parse() {
let json = r#"{"type": "ping"}"#;
let msg: WsMessage = serde_json::from_str(json).unwrap();
assert!(matches!(msg, WsMessage::Ping));
}
}