//! Read-only file browsing, a git summary, and the web terminal. use std::sync::atomic::AtomicBool; use std::time::Duration; use axum::Json; use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade}; use axum::extract::{Path, Query, State}; use axum::http::{HeaderMap, HeaderValue}; use axum::response::Response; use futures::{SinkExt, StreamExt}; use rhema_sandbox::Sandbox; use rhema_sandbox::exec_util::shquote; use serde::Deserialize; use serde_json::{Value, json}; use tokio_tungstenite::tungstenite::Message as TMessage; use tokio_tungstenite::tungstenite::client::IntoClientRequest; use crate::auth::AuthUser; use crate::error::{AppError, AppResult}; use crate::models::FileEntry; use crate::room::agent; use crate::state::Shared; use crate::util::safe_rel_path; use super::rooms::member_of; #[derive(Deserialize)] pub struct PathQuery { #[serde(default)] pub path: String, } /// The workspace and target of a room, without needing a provider. fn room_workspace(state: &Shared, room: &str) -> AppResult<(String, agent::TargetRow)> { let (workspace, target) = agent::load_room_target(state, room)?; Ok((workspace, target)) } /// Validates a workspace-relative path. fn safe_rel(path: &str) -> AppResult { safe_rel_path(path).map_err(AppError::bad_request) } async fn run( state: &Shared, workspace: &str, target: &agent::TargetRow, command: String, timeout: Duration, ) -> AppResult { let sandbox = agent::sandbox_for(state, workspace, target)?; let cancelled = AtomicBool::new(false); let mut progress = rhema_sandbox::OutputOnly(|_| {}); sandbox .run( rhema_sandbox::RunRequest { command, cwd: workspace.into(), timeout, env: Default::default(), }, &cancelled, &mut progress, ) .await .map_err(|err| AppError::new(axum::http::StatusCode::BAD_GATEWAY, err.to_string())) } /// One directory. pub async fn list( user: AuthUser, State(state): State, Path(room): Path, Query(query): Query, ) -> AppResult> { member_of(&state, &room, &user.user.id)?; let (workspace, target) = room_workspace(&state, &room)?; let rel = safe_rel(&query.path)?; let abs = if rel == "." { workspace.clone() } else { format!("{}/{rel}", workspace.trim_end_matches('/')) }; let command = format!( "find {} -mindepth 1 -maxdepth 1 -printf '%y\\t%s\\t%f\\0' 2>/dev/null | head -c 400000", shquote(&abs) ); let outcome = run( &state, &workspace, &target, command, Duration::from_secs(15), ) .await?; let mut entries = Vec::new(); for record in outcome.stdout.split(|byte| *byte == 0) { if record.is_empty() { continue; } let text = String::from_utf8_lossy(record); let mut parts = text.splitn(3, '\t'); let kind = parts.next().unwrap_or("f"); let size = parts .next() .and_then(|value| value.parse::().ok()) .unwrap_or(0); let name = parts.next().unwrap_or(""); if name.is_empty() || name == ".git" { continue; } let child = if rel == "." { name.to_owned() } else { format!("{rel}/{name}") }; let kind = match kind { "d" => "dir", "l" => "link", _ => "file", }; entries.push(FileEntry { name: name.to_owned(), path: child, kind: kind.into(), size, }); } entries.sort_by(|a, b| { (a.kind != "dir") .cmp(&(b.kind != "dir")) .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) }); Ok(Json(json!({ "path": rel, "entries": entries }))) } /// One file, capped at 400 KB. pub async fn read( user: AuthUser, State(state): State, Path(room): Path, Query(query): Query, ) -> AppResult> { member_of(&state, &room, &user.user.id)?; let (workspace, target) = room_workspace(&state, &room)?; let rel = safe_rel(&query.path)?; if rel == "." { return Err(AppError::bad_request("path names a directory")); } let abs = format!("{}/{rel}", workspace.trim_end_matches('/')); let size_command = format!("stat -c %s -- {} 2>/dev/null", shquote(&abs)); let size_out = run( &state, &workspace, &target, size_command, Duration::from_secs(10), ) .await?; let size = String::from_utf8_lossy(&size_out.stdout) .trim() .parse::() .unwrap_or(0); if size == 0 && size_out.code != Some(0) { return Err(AppError::not_found("file not found")); } let read_command = format!("head -c 400000 -- {} 2>/dev/null", shquote(&abs)); let outcome = run( &state, &workspace, &target, read_command, Duration::from_secs(20), ) .await?; let binary = outcome.stdout.iter().take(8000).any(|byte| *byte == 0); let content = if binary { String::new() } else { String::from_utf8_lossy(&outcome.stdout).into_owned() }; Ok(Json(json!({ "path": rel, "content": content, "binary": binary, "size": size, "truncated": size > outcome.stdout.len() as i64, }))) } /// Branch, short status, and the diff stat. pub async fn git( user: AuthUser, State(state): State, Path(room): Path, ) -> AppResult> { member_of(&state, &room, &user.user.id)?; let (workspace, target) = room_workspace(&state, &room)?; let command = format!( "cd {} 2>/dev/null || {{ echo 'workspace not created yet'; exit 0; }}; \ git rev-parse --is-inside-work-tree >/dev/null 2>&1 || {{ echo 'not a git checkout'; exit 0; }}; \ git status --short --branch 2>&1 | head -80; echo '---'; \ git diff --stat 2>&1 | tail -40", shquote(&workspace) ); let outcome = run( &state, &workspace, &target, command, Duration::from_secs(20), ) .await?; Ok(Json(json!({ "text": String::from_utf8_lossy(&outcome.stdout), "code": outcome.code, }))) } /// The web terminal upgrade. The control plane only proxies bytes: the /// room's worker owns the ssh connection and the pty. pub async fn terminal( user: AuthUser, State(state): State, Path(room): Path, headers: HeaderMap, ws: WebSocketUpgrade, ) -> AppResult { if !super::websocket_origin_ok(&state.config, &headers) { return Err(AppError::forbidden("websocket origin does not match")); } member_of(&state, &room, &user.user.id)?; let (workspace, target) = room_workspace(&state, &room)?; let worker = crate::worker::client_for(&state, &workspace, &target) .await .map_err(|err| AppError::new(axum::http::StatusCode::BAD_GATEWAY, err))?; let account = user.user.id.clone(); Ok(ws.on_upgrade(move |socket| async move { proxy_terminal(socket, worker, state, room, account).await; })) } async fn proxy_terminal( socket: WebSocket, worker: crate::worker::WorkerClient, state: Shared, room: String, account: String, ) { let url = format!("ws://127.0.0.1:{}/pty?cols=100&rows=30", worker.http_port); let Ok(mut request) = url.into_client_request() else { return; }; let Ok(token) = HeaderValue::from_str(&worker.token) else { return; }; request.headers_mut().insert("x-rhema-token", token); let (worker_socket, _) = match tokio_tungstenite::connect_async(request).await { Ok(pair) => pair, Err(err) => { let (mut sink, _) = socket.split(); let _ = sink .send(WsMessage::Text( json!({ "type": "error", "message": format!("the sandbox worker did not answer: {err}") }) .to_string() .into(), )) .await; return; } }; let (mut browser_sink, mut browser_source) = socket.split(); let (mut worker_sink, mut worker_source) = worker_socket.split(); let mut access = tokio::time::interval(std::time::Duration::from_secs(2)); loop { tokio::select! { _ = access.tick() => { if member_of(&state, &room, &account).is_err() { break; } } message = worker_source.next() => { match message { Some(Ok(message)) => { if let Some(message) = from_worker(message) && browser_sink.send(message).await.is_err() { break; } } _ => break, } } message = browser_source.next() => { match message { Some(Ok(message)) => { if let Some(message) = to_worker(message) && worker_sink.send(message).await.is_err() { break; } } _ => break, } } } } let _ = worker_sink.close().await; } fn from_worker(message: TMessage) -> Option { match message { TMessage::Text(text) => Some(WsMessage::Text(text.as_str().into())), TMessage::Binary(data) => Some(WsMessage::Binary(data)), TMessage::Ping(data) => Some(WsMessage::Ping(data)), TMessage::Pong(data) => Some(WsMessage::Pong(data)), TMessage::Close(frame) => Some(WsMessage::Close(frame.map(|frame| { axum::extract::ws::CloseFrame { code: frame.code.into(), reason: frame.reason.as_str().into(), } }))), TMessage::Frame(_) => None, } } fn to_worker(message: WsMessage) -> Option { match message { WsMessage::Text(text) => Some(TMessage::Text(text.as_str().into())), WsMessage::Binary(data) => Some(TMessage::Binary(data)), WsMessage::Ping(data) => Some(TMessage::Ping(data)), WsMessage::Pong(data) => Some(TMessage::Pong(data)), WsMessage::Close(frame) => Some(TMessage::Close(frame.map(|frame| { tokio_tungstenite::tungstenite::protocol::CloseFrame { code: frame.code.into(), reason: frame.reason.as_str().into(), } }))), } }