//! 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::WebSocketUpgrade; use axum::extract::{Path, Query, State}; use axum::http::HeaderMap; use axum::response::Response; use rhema_sandbox::Sandbox; use rhema_sandbox::exec_util::shquote; use serde::Deserialize; use serde_json::{Value, json}; use crate::auth::AuthUser; use crate::error::{AppError, AppResult}; use crate::models::FileEntry; use crate::room::agent; use crate::state::Shared; 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 { let trimmed = path.trim(); if trimmed.starts_with('/') { return Err(AppError::bad_request( "path must be relative to the workspace", )); } let normalized = trimmed.trim_matches('/'); if normalized.split('/').any(|part| part == "..") { return Err(AppError::bad_request("path escapes the workspace")); } Ok(if normalized.is_empty() { ".".to_owned() } else { normalized.to_owned() }) } 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 ssh connection is opened only after /// the socket is accepted, with the same target and key as the agent. pub async fn terminal( user: AuthUser, State(state): State, Path(room): Path, headers: HeaderMap, ws: WebSocketUpgrade, ) -> AppResult { if !super::websocket_origin_ok(&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 account = user.user.id.clone(); Ok(ws.on_upgrade(move |socket| { crate::ssh::terminal(socket, state, room, account, workspace, target) })) }