Skip to main content

shell_tunnel/api/
handlers.rs

1//! REST API handlers.
2
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use axum::{
7    extract::{Path, State},
8    http::StatusCode,
9    Json,
10};
11
12use super::types::{
13    CreateSessionRequest, CreateSessionResponse, ErrorResponse, ExecuteCommandRequest,
14    ExecuteCommandResponse, ListSessionsResponse, SessionStatusResponse, SessionSummary,
15};
16use crate::execution::{Command, CommandExecutor};
17use crate::session::{SessionConfig, SessionId, SessionState, SessionStore};
18
19/// Shared application state.
20#[derive(Clone)]
21pub struct AppState {
22    pub store: Arc<SessionStore>,
23    pub executor: Arc<CommandExecutor>,
24    /// Where execution events are recorded; disabled unless configured.
25    pub audit: Arc<crate::audit::AuditSink>,
26    /// The directory the filesystem API may touch.
27    ///
28    /// `None` means the API is off. Since 0.12.0 the shipped binary no longer
29    /// defaults to this: it always installs `FsRoot::machine_wide()` unless
30    /// `--fs-root` narrows it, on the reasoning that a token holding `fs.*`
31    /// already needs `exec` to matter, and `exec` can already reach anything
32    /// this process can (`src/main.rs`). `None` now only occurs when a
33    /// library consumer builds an `AppState` directly instead of going
34    /// through the binary's startup path.
35    pub fs: Option<Arc<crate::fs::FsRoot>>,
36    /// In-flight uploads. Always present; useless until `fs` is set.
37    pub uploads: Arc<crate::fs::UploadStore>,
38}
39
40impl AppState {
41    pub fn new() -> Self {
42        let store = Arc::new(SessionStore::new());
43        let executor = Arc::new(CommandExecutor::new(Arc::clone(&store)));
44        Self {
45            store,
46            executor,
47            audit: Arc::new(crate::audit::AuditSink::Disabled),
48            fs: None,
49            uploads: Arc::new(crate::fs::UploadStore::new(crate::fs::DEFAULT_CHUNK_SIZE)),
50        }
51    }
52
53    /// Record execution events to `sink`.
54    pub fn with_audit(mut self, sink: Arc<crate::audit::AuditSink>) -> Self {
55        self.audit = sink;
56        self
57    }
58
59    /// Enable the filesystem API, confined to `root`.
60    pub fn with_fs_root(mut self, root: crate::fs::FsRoot) -> Self {
61        self.fs = Some(Arc::new(root));
62        self
63    }
64
65    /// Advertise a different chunk size to upload clients.
66    pub fn with_chunk_size(mut self, chunk_size: usize) -> Self {
67        self.uploads = Arc::new(crate::fs::UploadStore::new(chunk_size));
68        self
69    }
70}
71
72/// Build the execution event for a finished command.
73///
74/// Written from the handler rather than from middleware because only here are
75/// the command and its outcome both in hand — an entry saying a request reached
76/// `/execute` would say almost nothing about what ran.
77fn execution_event(
78    identity: Option<crate::audit::Identity>,
79    route: &str,
80    command: &str,
81    session_id: Option<u64>,
82    result: &crate::execution::ExecutionResult,
83) -> crate::audit::AuditEvent {
84    let mut event = crate::audit::AuditEvent::new("execute")
85        .with_identity(identity)
86        .with_route(route)
87        .with_command(command)
88        .with_outcome(
89            result.exit_code,
90            result.timed_out,
91            result.duration.as_millis() as u64,
92        )
93        .with_truncated_output(result.truncated, result.total_bytes);
94    if let Some(id) = session_id {
95        event = event.with_session(id);
96    }
97    event
98}
99
100impl Default for AppState {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106/// Health check endpoint.
107pub async fn health() -> &'static str {
108    "OK"
109}
110
111/// API information endpoint.
112pub async fn api_info() -> Json<serde_json::Value> {
113    Json(serde_json::json!({
114        "name": "shell-tunnel",
115        "version": env!("CARGO_PKG_VERSION"),
116        "status": "running"
117    }))
118}
119
120/// List all sessions.
121pub async fn list_sessions(
122    State(state): State<AppState>,
123) -> Result<Json<ListSessionsResponse>, (StatusCode, Json<ErrorResponse>)> {
124    let ids = state.store.list_ids().map_err(|e| {
125        (
126            StatusCode::INTERNAL_SERVER_ERROR,
127            Json(ErrorResponse::internal_error(e.to_string())),
128        )
129    })?;
130
131    let mut sessions = Vec::with_capacity(ids.len());
132    for id in ids {
133        if let Ok(Some(session)) = state.store.get(&id) {
134            sessions.push(SessionSummary {
135                session_id: session.id.as_u64(),
136                state: format!("{:?}", session.state),
137                idle_seconds: session.idle_duration().as_secs_f64(),
138            });
139        }
140    }
141
142    Ok(Json(ListSessionsResponse {
143        count: sessions.len(),
144        sessions,
145    }))
146}
147
148/// Create a new session.
149pub async fn create_session(
150    State(state): State<AppState>,
151    Json(req): Json<CreateSessionRequest>,
152) -> Result<(StatusCode, Json<CreateSessionResponse>), (StatusCode, Json<ErrorResponse>)> {
153    let config = SessionConfig {
154        shell: req.shell,
155        working_dir: req.working_dir,
156        env: req.env,
157    };
158
159    let session_id = state.store.create(config).map_err(|e| {
160        (
161            StatusCode::INTERNAL_SERVER_ERROR,
162            Json(ErrorResponse::internal_error(e.to_string())),
163        )
164    })?;
165
166    // Transition to Idle state (ready for commands)
167    state
168        .store
169        .update(&session_id, |s| {
170            let _ = s.state.transition_to(SessionState::Idle);
171        })
172        .ok();
173
174    Ok((
175        StatusCode::CREATED,
176        Json(CreateSessionResponse::new(session_id)),
177    ))
178}
179
180/// Get session status.
181pub async fn get_session(
182    State(state): State<AppState>,
183    Path(session_id): Path<u64>,
184) -> Result<Json<SessionStatusResponse>, (StatusCode, Json<ErrorResponse>)> {
185    let id = SessionId::from_raw(session_id);
186
187    let session = state
188        .store
189        .get(&id)
190        .map_err(|e| {
191            (
192                StatusCode::INTERNAL_SERVER_ERROR,
193                Json(ErrorResponse::internal_error(e.to_string())),
194            )
195        })?
196        .ok_or_else(|| {
197            (
198                StatusCode::NOT_FOUND,
199                Json(ErrorResponse::session_not_found(&session_id.to_string())),
200            )
201        })?;
202
203    Ok(Json(SessionStatusResponse::from_session(&session)))
204}
205
206/// Delete a session.
207pub async fn delete_session(
208    State(state): State<AppState>,
209    Path(session_id): Path<u64>,
210) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
211    let id = SessionId::from_raw(session_id);
212
213    // First mark as terminated
214    state
215        .store
216        .update(&id, |s| {
217            let _ = s.state.transition_to(SessionState::Terminated);
218        })
219        .map_err(|_| {
220            (
221                StatusCode::NOT_FOUND,
222                Json(ErrorResponse::session_not_found(&session_id.to_string())),
223            )
224        })?;
225
226    // Then remove from store
227    state.store.remove(&id).map_err(|e| {
228        (
229            StatusCode::INTERNAL_SERVER_ERROR,
230            Json(ErrorResponse::internal_error(e.to_string())),
231        )
232    })?;
233
234    Ok(StatusCode::NO_CONTENT)
235}
236
237/// Execute a command in a session.
238pub async fn execute_command(
239    State(state): State<AppState>,
240    Path(session_id): Path<u64>,
241    identity: Option<axum::Extension<crate::audit::Identity>>,
242    Json(req): Json<ExecuteCommandRequest>,
243) -> Result<Json<ExecuteCommandResponse>, (StatusCode, Json<ErrorResponse>)> {
244    let id = SessionId::from_raw(session_id);
245
246    // Verify session exists and is in valid state
247    let session = state
248        .store
249        .get(&id)
250        .map_err(|e| {
251            (
252                StatusCode::INTERNAL_SERVER_ERROR,
253                Json(ErrorResponse::internal_error(e.to_string())),
254            )
255        })?
256        .ok_or_else(|| {
257            (
258                StatusCode::NOT_FOUND,
259                Json(ErrorResponse::session_not_found(&session_id.to_string())),
260            )
261        })?;
262
263    if !session.state.can_execute() {
264        return Err((
265            StatusCode::CONFLICT,
266            Json(ErrorResponse::invalid_state(session.state)),
267        ));
268    }
269
270    // Build command
271    let mut cmd = Command::new(&req.command);
272    if let Some(dir) = &req.working_dir {
273        cmd = cmd.working_dir(PathBuf::from(dir));
274    }
275    if let Some(timeout) = req.timeout() {
276        cmd = cmd.timeout(timeout);
277    }
278    if let Some(bytes) = req.max_output_bytes {
279        cmd = cmd.max_output_bytes(bytes);
280    }
281    for (key, value) in &req.env {
282        cmd = cmd.env(key, value);
283    }
284
285    // Execute
286    let result = state
287        .executor
288        .execute_in_session(&id, &cmd)
289        .await
290        .map_err(|e| {
291            (
292                StatusCode::INTERNAL_SERVER_ERROR,
293                Json(ErrorResponse::internal_error(e.to_string())),
294            )
295        })?;
296
297    state.audit.record(execution_event(
298        identity.map(|axum::Extension(id)| id),
299        "POST /api/v1/sessions/{id}/execute",
300        &req.command,
301        Some(session_id),
302        &result,
303    ));
304
305    // Update session context
306    state
307        .store
308        .update(&id, |s| {
309            s.context.record_execution(&req.command, result.exit_code);
310        })
311        .ok();
312
313    Ok(Json(ExecuteCommandResponse::from_result(&result)))
314}
315
316/// Execute a command without session (one-shot).
317pub async fn execute_oneshot(
318    State(state): State<AppState>,
319    identity: Option<axum::Extension<crate::audit::Identity>>,
320    Json(req): Json<ExecuteCommandRequest>,
321) -> Result<Json<ExecuteCommandResponse>, (StatusCode, Json<ErrorResponse>)> {
322    // Build command
323    let mut cmd = Command::new(&req.command);
324    if let Some(dir) = &req.working_dir {
325        cmd = cmd.working_dir(PathBuf::from(dir));
326    }
327    if let Some(timeout) = req.timeout() {
328        cmd = cmd.timeout(timeout);
329    }
330    if let Some(bytes) = req.max_output_bytes {
331        cmd = cmd.max_output_bytes(bytes);
332    }
333    for (key, value) in &req.env {
334        cmd = cmd.env(key, value);
335    }
336
337    // Execute directly without session (off the async runtime workers)
338    let result = state.executor.execute(&cmd).await.map_err(|e| {
339        (
340            StatusCode::INTERNAL_SERVER_ERROR,
341            Json(ErrorResponse::internal_error(e.to_string())),
342        )
343    })?;
344
345    state.audit.record(execution_event(
346        identity.map(|axum::Extension(id)| id),
347        "POST /api/v1/execute",
348        &req.command,
349        None,
350        &result,
351    ));
352
353    Ok(Json(ExecuteCommandResponse::from_result(&result)))
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[test]
361    fn test_app_state_new() {
362        let state = AppState::new();
363        assert_eq!(state.store.count(), 0);
364    }
365
366    #[tokio::test]
367    async fn test_health_endpoint() {
368        let response = health().await;
369        assert_eq!(response, "OK");
370    }
371
372    #[tokio::test]
373    async fn test_api_info_endpoint() {
374        let response = api_info().await;
375        let json = response.0;
376        assert_eq!(json["name"], "shell-tunnel");
377        assert_eq!(json["status"], "running");
378    }
379}