| 1 | //! `/v1/computer/*` — the Engine's view of the computer it runs on. |
| 2 | //! |
| 3 | //! ARCHITECTURE §3.3 (research/computer): TigerVNC `Xvnc` serves RFB on a |
| 4 | //! Unix socket only (`/run/cw/vnc.sock`, group `cw-display`). This module is |
| 5 | //! the single external path to it: |
| 6 | //! |
| 7 | //! - `GET /v1/computer/display` upgrades to a WebSocket that carries raw RFB |
| 8 | //! 3.8 bytes as binary frames. The Engine completes the upstream handshake |
| 9 | //! itself (security None on the socket) and offers only None downstream, |
| 10 | //! because the WebSocket is already authenticated. |
| 11 | //! - Server-to-client bytes pass through verbatim. |
| 12 | //! - Client-to-server bytes go through [`ClientParser`], a length-tracked, |
| 13 | //! fail-closed parser that runs in its **own task**, so a panic in it ends |
| 14 | //! one display connection and never a turn. Only message types 0, 2, 3, 4, |
| 15 | //! 5, 6, 150 and 251 are allowed; any other type closes the stream. |
| 16 | //! Input (4 key, 5 pointer, 6 clipboard, 251 resize) is dropped unless the |
| 17 | //! connection's principal holds the control lease. |
| 18 | //! - The lease is human-only and lives here, in the Engine. Agents read it |
| 19 | //! (`GET /v1/computer`) to refuse input tools while a human drives. |
| 20 | //! |
| 21 | //! Auth: every route here authenticates itself (it is merged outside the |
| 22 | //! `/v1` route layer) because the display WebSocket also accepts a |
| 23 | //! single-use `?ticket=` for browser clients that cannot set headers. Tickets |
| 24 | //! are redacted by [`redact_query_secrets`] wherever a URI is logged. The |
| 25 | //! Engine never trusts the peer address (S0 Q3: `/proxy` peers arrive as |
| 26 | //! `10.0.0.2`, not loopback) — only a token. |
| 27 | //! |
| 28 | //! Human keystrokes are never logged or put in events: events carry time |
| 29 | //! spans and counts only. Frames are never events. |
| 30 | |
| 31 | use codewhale_core::secret_eq::constant_time_eq; |
| 32 | use std::collections::{HashMap, VecDeque}; |
| 33 | use std::path::PathBuf; |
| 34 | use std::sync::Arc; |
| 35 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 36 | use std::time::{Duration, Instant}; |
| 37 | |
| 38 | use axum::extract::ws::{ |
| 39 | CloseFrame, Message, WebSocket, WebSocketUpgrade, rejection::WebSocketUpgradeRejection, |
| 40 | }; |
| 41 | use axum::extract::{Path, Query, State}; |
| 42 | use axum::http::{HeaderMap, StatusCode, Uri, header}; |
| 43 | use axum::response::{IntoResponse, Response}; |
| 44 | use axum::routing::{delete, get, post}; |
| 45 | use axum::{Json, Router}; |
| 46 | use chrono::{DateTime, Utc}; |
| 47 | use futures_util::{SinkExt, StreamExt}; |
| 48 | use serde::{Deserialize, Serialize}; |
| 49 | use serde_json::{Value, json}; |
| 50 | use sha2::{Digest, Sha256}; |
| 51 | use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; |
| 52 | |
| 53 | const DISPLAY_SOCKET_ENV: &str = "CODEWHALE_COMPUTER_DISPLAY_SOCKET"; |
| 54 | const DISPLAY_IDLE_ENV: &str = "CODEWHALE_COMPUTER_DISPLAY_IDLE_SECS"; |
| 55 | const DEFAULT_DISPLAY_SOCKET: &str = "/run/cw/vnc.sock"; |
| 56 | /// §5: the Engine closes idle displays after 10 minutes. |
| 57 | const DEFAULT_IDLE: Duration = Duration::from_secs(600); |
| 58 | /// A lease with no human input for this long expires. |
| 59 | const LEASE_IDLE_TTL: Duration = Duration::from_secs(300); |
| 60 | /// §2.3: client tokens last at most one hour. |
| 61 | const CLIENT_TOKEN_MAX_TTL_SECS: u64 = 3600; |
| 62 | const CLIENT_TOKEN_MIN_TTL_SECS: u64 = 60; |
| 63 | const CLIENT_TOKEN_MAX_ACTIVE: usize = 64; |
| 64 | const DISPLAY_TICKET_TTL: Duration = Duration::from_secs(30); |
| 65 | const DISPLAY_TICKET_MAX_ACTIVE: usize = 64; |
| 66 | const EVENT_LOG_CAP: usize = 512; |
| 67 | const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); |
| 68 | const SUPERVISOR_TICK: Duration = Duration::from_secs(5); |
| 69 | const RFB_VERSION_38: &[u8; 12] = b"RFB 003.008\n"; |
| 70 | const DEVICE_ID_MAX_BYTES: usize = 128; |
| 71 | |
| 72 | /// Query keys whose values are secrets and must never reach a log line. |
| 73 | const SECRET_QUERY_KEYS: &[&str] = &[ |
| 74 | "ticket", |
| 75 | super::mobile::MOBILE_STREAM_TICKET_QUERY, |
| 76 | "token", |
| 77 | "access_token", |
| 78 | ]; |
| 79 | |
| 80 | // --------------------------------------------------------------------------- |
| 81 | // State |
| 82 | // --------------------------------------------------------------------------- |
| 83 | |
| 84 | /// Immutable authority minted into a device token; a label is never a grant. |
| 85 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] |
| 86 | #[serde(rename_all = "snake_case")] |
| 87 | pub(super) enum ClientTokenIntent { |
| 88 | #[default] |
| 89 | Watch, |
| 90 | Drive, |
| 91 | } |
| 92 | |
| 93 | /// `Owner` is the master Runtime token; a device token retains its mint intent. |
| 94 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 95 | pub(super) enum Principal { |
| 96 | Owner, |
| 97 | Client { |
| 98 | token_id: String, |
| 99 | device_id: String, |
| 100 | intent: ClientTokenIntent, |
| 101 | }, |
| 102 | } |
| 103 | |
| 104 | impl Principal { |
| 105 | pub(super) fn can_drive(&self) -> bool { |
| 106 | matches!( |
| 107 | self, |
| 108 | Principal::Owner |
| 109 | | Principal::Client { |
| 110 | intent: ClientTokenIntent::Drive, |
| 111 | .. |
| 112 | } |
| 113 | ) |
| 114 | } |
| 115 | |
| 116 | fn holder(&self) -> String { |
| 117 | match self { |
| 118 | Principal::Owner => "owner".to_string(), |
| 119 | Principal::Client { device_id, .. } => format!("device:{device_id}"), |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | fn device_id(&self) -> Option<&str> { |
| 124 | match self { |
| 125 | Principal::Owner => None, |
| 126 | Principal::Client { device_id, .. } => Some(device_id), |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | struct ClientToken { |
| 132 | id: String, |
| 133 | device_id: String, |
| 134 | intent: ClientTokenIntent, |
| 135 | label: Option<String>, |
| 136 | created_at: DateTime<Utc>, |
| 137 | expires_at: DateTime<Utc>, |
| 138 | } |
| 139 | |
| 140 | struct DisplayTicket { |
| 141 | principal: Principal, |
| 142 | expires: Instant, |
| 143 | } |
| 144 | |
| 145 | struct Lease { |
| 146 | principal: Principal, |
| 147 | acquired_at: DateTime<Utc>, |
| 148 | acquired_instant: Instant, |
| 149 | last_activity: Instant, |
| 150 | input_events: u64, |
| 151 | } |
| 152 | |
| 153 | #[derive(Debug, Clone, Serialize)] |
| 154 | pub(super) struct ComputerEvent { |
| 155 | pub seq: u64, |
| 156 | #[serde(rename = "type")] |
| 157 | pub kind: String, |
| 158 | pub at: DateTime<Utc>, |
| 159 | pub data: Value, |
| 160 | } |
| 161 | |
| 162 | struct Inner { |
| 163 | // Only the Unix display socket is dialed; other platforms report it absent. |
| 164 | #[cfg_attr(not(unix), allow(dead_code))] |
| 165 | socket_path: PathBuf, |
| 166 | idle_close: Duration, |
| 167 | lease_ttl: Duration, |
| 168 | lease: parking_lot::Mutex<Option<Lease>>, |
| 169 | client_tokens: parking_lot::Mutex<HashMap<[u8; 32], ClientToken>>, |
| 170 | tickets: parking_lot::Mutex<HashMap<[u8; 32], DisplayTicket>>, |
| 171 | events: parking_lot::Mutex<VecDeque<ComputerEvent>>, |
| 172 | next_seq: AtomicU64, |
| 173 | next_connection: AtomicU64, |
| 174 | attached: AtomicU64, |
| 175 | } |
| 176 | |
| 177 | /// Engine-side computer state: display socket, control lease, client tokens, |
| 178 | /// display tickets and the `computer.*` event log. |
| 179 | #[derive(Clone)] |
| 180 | pub(crate) struct ComputerState { |
| 181 | inner: Arc<Inner>, |
| 182 | } |
| 183 | |
| 184 | /// Accept a display socket path only if it is absolute and made of plain |
| 185 | /// components: no `.`/`..`, no NUL. The configured value cannot walk the |
| 186 | /// Engine out of the directory it names, and the socket-type check at use |
| 187 | /// (`display_socket_present`) refuses anything that is not a Unix socket. |
| 188 | fn validated_socket_path(raw: &str) -> Option<PathBuf> { |
| 189 | let raw = raw.trim(); |
| 190 | // This is a Unix socket setting even on hosts without Unix transport. |
| 191 | // Host-native Path parsing would reject /run/... on Windows, or normalize |
| 192 | // away the dot/repeated-separator components this contract must refuse. |
| 193 | let relative = raw.strip_prefix('/')?; |
| 194 | if raw.contains(['\0', '\\']) |
| 195 | || relative |
| 196 | .split('/') |
| 197 | .any(|part| part.is_empty() || matches!(part, "." | "..")) |
| 198 | { |
| 199 | return None; |
| 200 | } |
| 201 | Some(PathBuf::from(raw)) |
| 202 | } |
| 203 | |
| 204 | impl ComputerState { |
| 205 | pub(crate) fn new(socket_path: PathBuf, idle_close: Duration) -> Self { |
| 206 | Self { |
| 207 | inner: Arc::new(Inner { |
| 208 | socket_path, |
| 209 | idle_close, |
| 210 | lease_ttl: LEASE_IDLE_TTL, |
| 211 | lease: parking_lot::Mutex::new(None), |
| 212 | client_tokens: parking_lot::Mutex::new(HashMap::new()), |
| 213 | tickets: parking_lot::Mutex::new(HashMap::new()), |
| 214 | events: parking_lot::Mutex::new(VecDeque::new()), |
| 215 | next_seq: AtomicU64::new(1), |
| 216 | next_connection: AtomicU64::new(1), |
| 217 | attached: AtomicU64::new(0), |
| 218 | }), |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | pub(crate) fn from_env() -> Self { |
| 223 | let socket = std::env::var(DISPLAY_SOCKET_ENV) |
| 224 | .ok() |
| 225 | .and_then(|raw| { |
| 226 | let checked = validated_socket_path(&raw); |
| 227 | if checked.is_none() && !raw.trim().is_empty() { |
| 228 | tracing::warn!( |
| 229 | target: "codewhale::computer", |
| 230 | "{DISPLAY_SOCKET_ENV} must be an absolute path with no `.`/`..` \ |
| 231 | components; using {DEFAULT_DISPLAY_SOCKET}" |
| 232 | ); |
| 233 | } |
| 234 | checked |
| 235 | }) |
| 236 | .unwrap_or_else(|| PathBuf::from(DEFAULT_DISPLAY_SOCKET)); |
| 237 | let idle = std::env::var(DISPLAY_IDLE_ENV) |
| 238 | .ok() |
| 239 | .and_then(|v| v.trim().parse::<u64>().ok()) |
| 240 | .filter(|secs| *secs > 0) |
| 241 | .map(Duration::from_secs) |
| 242 | .unwrap_or(DEFAULT_IDLE); |
| 243 | Self::new(socket, idle) |
| 244 | } |
| 245 | |
| 246 | fn emit(&self, kind: &str, data: Value) { |
| 247 | let mut events = self.inner.events.lock(); |
| 248 | let seq = self.inner.next_seq.fetch_add(1, Ordering::Relaxed); |
| 249 | let event = ComputerEvent { |
| 250 | seq, |
| 251 | kind: kind.to_string(), |
| 252 | at: Utc::now(), |
| 253 | data, |
| 254 | }; |
| 255 | tracing::info!(target: "codewhale::computer", seq, kind, "computer event"); |
| 256 | if events.len() >= EVENT_LOG_CAP { |
| 257 | events.pop_front(); |
| 258 | } |
| 259 | events.push_back(event); |
| 260 | } |
| 261 | |
| 262 | pub(super) fn events_since(&self, since: u64) -> (Vec<ComputerEvent>, u64) { |
| 263 | let events = self.inner.events.lock(); |
| 264 | let list: Vec<_> = events.iter().filter(|e| e.seq > since).cloned().collect(); |
| 265 | let next = self |
| 266 | .inner |
| 267 | .next_seq |
| 268 | .load(Ordering::Relaxed) |
| 269 | .saturating_sub(1); |
| 270 | (list, next) |
| 271 | } |
| 272 | |
| 273 | // -- tokens -------------------------------------------------------------- |
| 274 | |
| 275 | /// Whether `bearer` is a live (unexpired, unrevoked) client token. |
| 276 | pub(super) fn client_principal(&self, bearer: &str) -> Option<Principal> { |
| 277 | let key = hash(bearer); |
| 278 | let now = Utc::now(); |
| 279 | let tokens = self.inner.client_tokens.lock(); |
| 280 | let token = tokens.get(&key)?; |
| 281 | (token.expires_at > now).then(|| Principal::Client { |
| 282 | token_id: token.id.clone(), |
| 283 | device_id: token.device_id.clone(), |
| 284 | intent: token.intent, |
| 285 | }) |
| 286 | } |
| 287 | |
| 288 | fn principal_is_live(&self, principal: &Principal) -> bool { |
| 289 | match principal { |
| 290 | Principal::Owner => true, |
| 291 | Principal::Client { token_id, .. } => { |
| 292 | let now = Utc::now(); |
| 293 | self.inner |
| 294 | .client_tokens |
| 295 | .lock() |
| 296 | .values() |
| 297 | .any(|t| &t.id == token_id && t.expires_at > now) |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | fn mint_client_token( |
| 303 | &self, |
| 304 | device_id: String, |
| 305 | ttl_secs: u64, |
| 306 | label: Option<String>, |
| 307 | intent: ClientTokenIntent, |
| 308 | ) -> Result<(String, ClientTokenView), ApiErr> { |
| 309 | let now = Utc::now(); |
| 310 | let mut tokens = self.inner.client_tokens.lock(); |
| 311 | tokens.retain(|_, t| t.expires_at > now); |
| 312 | if tokens.len() >= CLIENT_TOKEN_MAX_ACTIVE { |
| 313 | return Err(ApiErr::new( |
| 314 | StatusCode::TOO_MANY_REQUESTS, |
| 315 | "too many active client tokens; revoke one first", |
| 316 | )); |
| 317 | } |
| 318 | let secret = format!( |
| 319 | "cwct_{}{}", |
| 320 | uuid::Uuid::new_v4().simple(), |
| 321 | uuid::Uuid::new_v4().simple() |
| 322 | ); |
| 323 | let id = format!("ct_{}", uuid::Uuid::new_v4().simple()); |
| 324 | let token = ClientToken { |
| 325 | id, |
| 326 | device_id, |
| 327 | intent, |
| 328 | label, |
| 329 | created_at: now, |
| 330 | expires_at: now + chrono::Duration::seconds(ttl_secs as i64), |
| 331 | }; |
| 332 | let view = ClientTokenView::from(&token); |
| 333 | tokens.insert(hash(&secret), token); |
| 334 | Ok((secret, view)) |
| 335 | } |
| 336 | |
| 337 | fn revoke_client_token(&self, id: &str) -> bool { |
| 338 | let mut tokens = self.inner.client_tokens.lock(); |
| 339 | let before = tokens.len(); |
| 340 | tokens.retain(|_, t| t.id != id); |
| 341 | before != tokens.len() |
| 342 | } |
| 343 | |
| 344 | fn list_client_tokens(&self) -> Vec<ClientTokenView> { |
| 345 | let now = Utc::now(); |
| 346 | let mut tokens = self.inner.client_tokens.lock(); |
| 347 | tokens.retain(|_, t| t.expires_at > now); |
| 348 | let mut list: Vec<_> = tokens.values().map(ClientTokenView::from).collect(); |
| 349 | list.sort_by_key(|a| a.created_at); |
| 350 | list |
| 351 | } |
| 352 | |
| 353 | // -- display tickets ----------------------------------------------------- |
| 354 | |
| 355 | fn mint_ticket(&self, principal: Principal) -> Result<String, ApiErr> { |
| 356 | let now = Instant::now(); |
| 357 | let mut tickets = self.inner.tickets.lock(); |
| 358 | tickets.retain(|_, t| t.expires > now); |
| 359 | if tickets.len() >= DISPLAY_TICKET_MAX_ACTIVE { |
| 360 | return Err(ApiErr::new( |
| 361 | StatusCode::TOO_MANY_REQUESTS, |
| 362 | "too many outstanding display tickets", |
| 363 | )); |
| 364 | } |
| 365 | let secret = format!("cwdt_{}", uuid::Uuid::new_v4().simple()); |
| 366 | tickets.insert( |
| 367 | hash(&secret), |
| 368 | DisplayTicket { |
| 369 | principal, |
| 370 | expires: now + DISPLAY_TICKET_TTL, |
| 371 | }, |
| 372 | ); |
| 373 | Ok(secret) |
| 374 | } |
| 375 | |
| 376 | /// Single use: a ticket is removed on the first redemption attempt, |
| 377 | /// whether or not it had expired. |
| 378 | fn redeem_ticket(&self, ticket: &str) -> Option<Principal> { |
| 379 | let entry = self.inner.tickets.lock().remove(&hash(ticket))?; |
| 380 | (entry.expires > Instant::now() && self.principal_is_live(&entry.principal)) |
| 381 | .then_some(entry.principal) |
| 382 | } |
| 383 | |
| 384 | // -- lease --------------------------------------------------------------- |
| 385 | |
| 386 | /// Expire a stale lease (emitting `computer.control.expired`) and return |
| 387 | /// a snapshot of whatever lease remains. |
| 388 | fn sweep_lease(&self) -> Option<LeaseView> { |
| 389 | let mut guard = self.inner.lease.lock(); |
| 390 | let expired = guard.as_ref().is_some_and(|lease| { |
| 391 | lease.last_activity.elapsed() >= self.inner.lease_ttl |
| 392 | || !self.principal_is_live(&lease.principal) |
| 393 | }); |
| 394 | if expired { |
| 395 | let lease = guard.take().expect("checked above"); |
| 396 | drop(guard); |
| 397 | self.emit( |
| 398 | "computer.control.expired", |
| 399 | lease_span_data(&lease, "expired"), |
| 400 | ); |
| 401 | return None; |
| 402 | } |
| 403 | guard.as_ref().map(|lease| self.lease_view(lease)) |
| 404 | } |
| 405 | |
| 406 | fn lease_view(&self, lease: &Lease) -> LeaseView { |
| 407 | let remaining = self |
| 408 | .inner |
| 409 | .lease_ttl |
| 410 | .saturating_sub(lease.last_activity.elapsed()); |
| 411 | LeaseView { |
| 412 | holder: lease.principal.holder(), |
| 413 | device_id: lease.principal.device_id().map(str::to_string), |
| 414 | acquired_at: lease.acquired_at, |
| 415 | expires_at: Utc::now() + chrono::Duration::from_std(remaining).unwrap_or_default(), |
| 416 | input_events: lease.input_events, |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | fn acquire(&self, principal: &Principal, force: bool) -> Result<LeaseView, LeaseView> { |
| 421 | self.sweep_lease(); |
| 422 | let mut guard = self.inner.lease.lock(); |
| 423 | if let Some(current) = guard.as_mut() { |
| 424 | if current.principal == *principal { |
| 425 | current.last_activity = Instant::now(); |
| 426 | return Ok(self.lease_view(current)); |
| 427 | } |
| 428 | if !force { |
| 429 | return Err(self.lease_view(current)); |
| 430 | } |
| 431 | let previous = guard.take().expect("checked above"); |
| 432 | self.emit( |
| 433 | "computer.control.released", |
| 434 | lease_span_data(&previous, "taken_over"), |
| 435 | ); |
| 436 | } |
| 437 | let now = Instant::now(); |
| 438 | let lease = Lease { |
| 439 | principal: principal.clone(), |
| 440 | acquired_at: Utc::now(), |
| 441 | acquired_instant: now, |
| 442 | last_activity: now, |
| 443 | input_events: 0, |
| 444 | }; |
| 445 | let view = self.lease_view(&lease); |
| 446 | *guard = Some(lease); |
| 447 | drop(guard); |
| 448 | self.emit( |
| 449 | "computer.control.acquired", |
| 450 | json!({ "holder": view.holder, "device_id": view.device_id }), |
| 451 | ); |
| 452 | Ok(view) |
| 453 | } |
| 454 | |
| 455 | fn release(&self, principal: &Principal) -> bool { |
| 456 | let mut guard = self.inner.lease.lock(); |
| 457 | if guard |
| 458 | .as_ref() |
| 459 | .is_some_and(|lease| lease.principal == *principal) |
| 460 | { |
| 461 | let lease = guard.take().expect("checked above"); |
| 462 | drop(guard); |
| 463 | self.emit( |
| 464 | "computer.control.released", |
| 465 | lease_span_data(&lease, "hand_back"), |
| 466 | ); |
| 467 | true |
| 468 | } else { |
| 469 | false |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | fn holds_lease(&self, principal: &Principal) -> bool { |
| 474 | principal.can_drive() |
| 475 | && self.principal_is_live(principal) |
| 476 | && self.inner.lease.lock().as_ref().is_some_and(|lease| { |
| 477 | lease.principal == *principal |
| 478 | && lease.last_activity.elapsed() < self.inner.lease_ttl |
| 479 | }) |
| 480 | } |
| 481 | |
| 482 | fn note_input(&self, principal: &Principal, count: u64) { |
| 483 | if let Some(lease) = self.inner.lease.lock().as_mut() |
| 484 | && lease.principal == *principal |
| 485 | { |
| 486 | lease.last_activity = Instant::now(); |
| 487 | lease.input_events += count; |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | fn lease_span_data(lease: &Lease, reason: &str) -> Value { |
| 493 | json!({ |
| 494 | "holder": lease.principal.holder(), |
| 495 | "device_id": lease.principal.device_id(), |
| 496 | "reason": reason, |
| 497 | "held_ms": lease.acquired_instant.elapsed().as_millis() as u64, |
| 498 | "input_events": lease.input_events, |
| 499 | }) |
| 500 | } |
| 501 | |
| 502 | fn hash(secret: &str) -> [u8; 32] { |
| 503 | Sha256::digest(secret.as_bytes()).into() |
| 504 | } |
| 505 | |
| 506 | #[derive(Debug, Clone, Serialize)] |
| 507 | struct LeaseView { |
| 508 | holder: String, |
| 509 | device_id: Option<String>, |
| 510 | acquired_at: DateTime<Utc>, |
| 511 | expires_at: DateTime<Utc>, |
| 512 | input_events: u64, |
| 513 | } |
| 514 | |
| 515 | #[derive(Debug, Clone, Serialize)] |
| 516 | struct ClientTokenView { |
| 517 | id: String, |
| 518 | device_id: String, |
| 519 | intent: ClientTokenIntent, |
| 520 | label: Option<String>, |
| 521 | created_at: DateTime<Utc>, |
| 522 | expires_at: DateTime<Utc>, |
| 523 | } |
| 524 | |
| 525 | impl From<&ClientToken> for ClientTokenView { |
| 526 | fn from(t: &ClientToken) -> Self { |
| 527 | Self { |
| 528 | id: t.id.clone(), |
| 529 | device_id: t.device_id.clone(), |
| 530 | intent: t.intent, |
| 531 | label: t.label.clone(), |
| 532 | created_at: t.created_at, |
| 533 | expires_at: t.expires_at, |
| 534 | } |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | // --------------------------------------------------------------------------- |
| 539 | // Redaction |
| 540 | // --------------------------------------------------------------------------- |
| 541 | |
| 542 | /// Replace the value of every secret-bearing query parameter |
| 543 | /// (`ticket`, `mobile_stream_ticket`, `token`, `access_token`) with |
| 544 | /// `redacted`. Use on any URI before it reaches a log line or a proxy. |
| 545 | pub(crate) fn redact_query_secrets(uri: &str) -> String { |
| 546 | let Some((path, query)) = uri.split_once('?') else { |
| 547 | return uri.to_string(); |
| 548 | }; |
| 549 | let (query, fragment) = match query.split_once('#') { |
| 550 | Some((q, f)) => (q, Some(f)), |
| 551 | None => (query, None), |
| 552 | }; |
| 553 | let redacted: Vec<String> = query |
| 554 | .split('&') |
| 555 | .map(|pair| match pair.split_once('=') { |
| 556 | Some((key, _)) |
| 557 | if SECRET_QUERY_KEYS |
| 558 | .iter() |
| 559 | .any(|k| k.eq_ignore_ascii_case(key)) => |
| 560 | { |
| 561 | format!("{key}=redacted") |
| 562 | } |
| 563 | _ => pair.to_string(), |
| 564 | }) |
| 565 | .collect(); |
| 566 | let mut out = format!("{path}?{}", redacted.join("&")); |
| 567 | if fragment.is_some() { |
| 568 | // Fragments never reach a server, but a logged client URL could carry |
| 569 | // one (the mobile bootstrap redirect does); drop it wholesale. |
| 570 | out.push_str("#redacted"); |
| 571 | } |
| 572 | out |
| 573 | } |
| 574 | |
| 575 | // --------------------------------------------------------------------------- |
| 576 | // Client-to-server RFB parser |
| 577 | // --------------------------------------------------------------------------- |
| 578 | |
| 579 | const MAX_ENCODINGS: usize = 64; |
| 580 | const MAX_CUT_TEXT: usize = 256 * 1024; |
| 581 | const MAX_SCREENS: usize = 16; |
| 582 | |
| 583 | /// Encodings a client may ask Xvnc for. Anything else is stripped from |
| 584 | /// `SetEncodings` so the server never starts a sub-protocol (Fence, xvp, |
| 585 | /// QEMU keys, extended clipboard) whose client replies this parser would |
| 586 | /// refuse. |
| 587 | fn encoding_allowed(encoding: i32) -> bool { |
| 588 | matches!( |
| 589 | encoding, |
| 590 | 0 | 1 | 2 | 5 | 7 | 16 // Raw, CopyRect, RRE, Hextile, Tight, ZRLE |
| 591 | | -223 // DesktopSize |
| 592 | | -224 // LastRect |
| 593 | | -239 // Cursor |
| 594 | | -307 // DesktopName |
| 595 | | -308 // ExtendedDesktopSize |
| 596 | | -313 // ContinuousUpdates |
| 597 | | -32..=-23 // JPEG quality |
| 598 | | -256..=-247 // compression level |
| 599 | ) |
| 600 | } |
| 601 | |
| 602 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 603 | pub(crate) enum ParseError { |
| 604 | UnknownType(u8), |
| 605 | TooLarge { message_type: u8, len: usize }, |
| 606 | } |
| 607 | |
| 608 | impl std::fmt::Display for ParseError { |
| 609 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 610 | match self { |
| 611 | ParseError::UnknownType(t) => write!(f, "unknown client message type {t}"), |
| 612 | ParseError::TooLarge { message_type, len } => { |
| 613 | write!(f, "client message type {message_type} too large ({len})") |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] |
| 620 | pub(crate) struct FeedStats { |
| 621 | pub input_forwarded: u64, |
| 622 | pub input_dropped: u64, |
| 623 | } |
| 624 | |
| 625 | /// Length-tracked parser for RFB client messages after `ClientInit`. |
| 626 | /// Holds partial messages across WebSocket frames. |
| 627 | #[derive(Default)] |
| 628 | pub(crate) struct ClientParser { |
| 629 | buf: Vec<u8>, |
| 630 | } |
| 631 | |
| 632 | impl ClientParser { |
| 633 | /// Feed client bytes. Complete, allowed messages are appended to `out`; |
| 634 | /// input messages are appended only when `input_allowed`. Returns an |
| 635 | /// error (and the stream must close) on any unknown or oversized message. |
| 636 | pub(crate) fn feed( |
| 637 | &mut self, |
| 638 | data: &[u8], |
| 639 | input_allowed: bool, |
| 640 | out: &mut Vec<u8>, |
| 641 | ) -> Result<FeedStats, ParseError> { |
| 642 | self.buf.extend_from_slice(data); |
| 643 | let mut stats = FeedStats::default(); |
| 644 | let mut offset = 0; |
| 645 | loop { |
| 646 | let rest = &self.buf[offset..]; |
| 647 | let Some(&message_type) = rest.first() else { |
| 648 | break; |
| 649 | }; |
| 650 | let need = match message_type { |
| 651 | 0 => Some(20), |
| 652 | 2 => (rest.len() >= 4) |
| 653 | .then(|| { |
| 654 | let n = u16::from_be_bytes([rest[2], rest[3]]) as usize; |
| 655 | (n, 4 + 4 * n) |
| 656 | }) |
| 657 | .map(|(n, len)| if n > MAX_ENCODINGS { usize::MAX } else { len }), |
| 658 | 3 => Some(10), |
| 659 | 4 => Some(8), |
| 660 | 5 => Some(6), |
| 661 | 6 => (rest.len() >= 8).then(|| { |
| 662 | let n = u32::from_be_bytes([rest[4], rest[5], rest[6], rest[7]]) as usize; |
| 663 | if n > MAX_CUT_TEXT { usize::MAX } else { 8 + n } |
| 664 | }), |
| 665 | 150 => Some(10), |
| 666 | 251 => (rest.len() >= 8).then(|| { |
| 667 | let n = rest[6] as usize; |
| 668 | if n > MAX_SCREENS { |
| 669 | usize::MAX |
| 670 | } else { |
| 671 | 8 + 16 * n |
| 672 | } |
| 673 | }), |
| 674 | other => return Err(ParseError::UnknownType(other)), |
| 675 | }; |
| 676 | let Some(need) = need else { break }; |
| 677 | if need == usize::MAX { |
| 678 | return Err(ParseError::TooLarge { |
| 679 | message_type, |
| 680 | len: rest.len(), |
| 681 | }); |
| 682 | } |
| 683 | if rest.len() < need { |
| 684 | break; |
| 685 | } |
| 686 | let message = &rest[..need]; |
| 687 | match message_type { |
| 688 | 2 => { |
| 689 | let kept: Vec<[u8; 4]> = message[4..] |
| 690 | .as_chunks::<4>() |
| 691 | .0 |
| 692 | .iter() |
| 693 | .copied() |
| 694 | .filter(|c| encoding_allowed(i32::from_be_bytes(*c))) |
| 695 | .collect(); |
| 696 | out.extend_from_slice(&[2, 0]); |
| 697 | out.extend_from_slice(&(kept.len() as u16).to_be_bytes()); |
| 698 | for c in &kept { |
| 699 | out.extend_from_slice(c); |
| 700 | } |
| 701 | } |
| 702 | 4 | 5 | 6 | 251 => { |
| 703 | if input_allowed { |
| 704 | out.extend_from_slice(message); |
| 705 | stats.input_forwarded += 1; |
| 706 | } else { |
| 707 | stats.input_dropped += 1; |
| 708 | } |
| 709 | } |
| 710 | _ => out.extend_from_slice(message), |
| 711 | } |
| 712 | offset += need; |
| 713 | } |
| 714 | self.buf.drain(..offset); |
| 715 | Ok(stats) |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | // --------------------------------------------------------------------------- |
| 720 | // Handshakes |
| 721 | // --------------------------------------------------------------------------- |
| 722 | |
| 723 | #[cfg(unix)] |
| 724 | async fn read_reason<S: AsyncRead + Unpin>(s: &mut S) -> String { |
| 725 | let Ok(len) = s.read_u32().await else { |
| 726 | return String::new(); |
| 727 | }; |
| 728 | let mut reason = vec![0u8; (len as usize).min(1024)]; |
| 729 | let _ = s.read_exact(&mut reason).await; |
| 730 | String::from_utf8_lossy(&reason).into_owned() |
| 731 | } |
| 732 | |
| 733 | /// Complete the RFB 3.8 handshake with Xvnc as a client (security None) and |
| 734 | /// send a shared `ClientInit`, so each viewer gets its own connection without |
| 735 | /// disconnecting the others. After this returns, the next upstream bytes are |
| 736 | /// `ServerInit`. |
| 737 | #[cfg(unix)] |
| 738 | pub(crate) async fn upstream_handshake<S: AsyncRead + AsyncWrite + Unpin>( |
| 739 | s: &mut S, |
| 740 | ) -> Result<(), String> { |
| 741 | let mut version = [0u8; 12]; |
| 742 | s.read_exact(&mut version) |
| 743 | .await |
| 744 | .map_err(|e| format!("read server version: {e}"))?; |
| 745 | if !version.starts_with(b"RFB 003.") { |
| 746 | return Err("upstream is not an RFB server".to_string()); |
| 747 | } |
| 748 | s.write_all(RFB_VERSION_38) |
| 749 | .await |
| 750 | .map_err(|e| format!("write version: {e}"))?; |
| 751 | let count = s |
| 752 | .read_u8() |
| 753 | .await |
| 754 | .map_err(|e| format!("read security: {e}"))?; |
| 755 | if count == 0 { |
| 756 | return Err(format!("upstream refused: {}", read_reason(s).await)); |
| 757 | } |
| 758 | let mut types = vec![0u8; count as usize]; |
| 759 | s.read_exact(&mut types) |
| 760 | .await |
| 761 | .map_err(|e| format!("read security types: {e}"))?; |
| 762 | if !types.contains(&1) { |
| 763 | return Err("upstream does not offer security type None".to_string()); |
| 764 | } |
| 765 | s.write_all(&[1]) |
| 766 | .await |
| 767 | .map_err(|e| format!("write security: {e}"))?; |
| 768 | let result = s |
| 769 | .read_u32() |
| 770 | .await |
| 771 | .map_err(|e| format!("read security result: {e}"))?; |
| 772 | if result != 0 { |
| 773 | return Err(format!( |
| 774 | "upstream security failed: {}", |
| 775 | read_reason(s).await |
| 776 | )); |
| 777 | } |
| 778 | s.write_all(&[1]) |
| 779 | .await |
| 780 | .map_err(|e| format!("write ClientInit: {e}"))?; |
| 781 | Ok(()) |
| 782 | } |
| 783 | |
| 784 | /// Buffered reader over the client half of the WebSocket. |
| 785 | struct WsIn<R> { |
| 786 | stream: R, |
| 787 | pending: Vec<u8>, |
| 788 | } |
| 789 | |
| 790 | impl<R> WsIn<R> |
| 791 | where |
| 792 | R: futures_util::Stream<Item = Result<Message, axum::Error>> + Unpin, |
| 793 | { |
| 794 | /// Next chunk of client bytes. `Ok(None)` is a clean close; text frames |
| 795 | /// are a protocol violation (RFB is binary). |
| 796 | async fn next_chunk(&mut self) -> Result<Option<Vec<u8>>, String> { |
| 797 | if !self.pending.is_empty() { |
| 798 | return Ok(Some(std::mem::take(&mut self.pending))); |
| 799 | } |
| 800 | loop { |
| 801 | match self.stream.next().await { |
| 802 | None | Some(Ok(Message::Close(_))) => return Ok(None), |
| 803 | Some(Ok(Message::Binary(bytes))) => return Ok(Some(bytes.to_vec())), |
| 804 | Some(Ok(Message::Ping(_) | Message::Pong(_))) => continue, |
| 805 | Some(Ok(Message::Text(_))) => return Err("text frame on RFB stream".to_string()), |
| 806 | Some(Err(err)) => return Err(format!("websocket: {err}")), |
| 807 | } |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | async fn read_exact(&mut self, n: usize) -> Result<Vec<u8>, String> { |
| 812 | let mut acc = Vec::with_capacity(n); |
| 813 | while acc.len() < n { |
| 814 | let Some(chunk) = self.next_chunk().await? else { |
| 815 | return Err("client closed during handshake".to_string()); |
| 816 | }; |
| 817 | acc.extend_from_slice(&chunk); |
| 818 | } |
| 819 | self.pending = acc.split_off(n); |
| 820 | Ok(acc) |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | // --------------------------------------------------------------------------- |
| 825 | // Session |
| 826 | // --------------------------------------------------------------------------- |
| 827 | |
| 828 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 829 | enum ExitReason { |
| 830 | ClientClosed, |
| 831 | UpstreamClosed, |
| 832 | ProtocolViolation(String), |
| 833 | ParserPanic, |
| 834 | IdleClosed, |
| 835 | Revoked, |
| 836 | Error(String), |
| 837 | } |
| 838 | |
| 839 | impl ExitReason { |
| 840 | fn label(&self) -> String { |
| 841 | match self { |
| 842 | ExitReason::ClientClosed => "client_closed".into(), |
| 843 | ExitReason::UpstreamClosed => "upstream_closed".into(), |
| 844 | ExitReason::ProtocolViolation(detail) => format!("protocol_violation: {detail}"), |
| 845 | ExitReason::ParserPanic => "parser_panic".into(), |
| 846 | ExitReason::IdleClosed => "idle_closed".into(), |
| 847 | ExitReason::Revoked => "revoked".into(), |
| 848 | ExitReason::Error(detail) => format!("error: {detail}"), |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | fn close_code(&self) -> u16 { |
| 853 | match self { |
| 854 | ExitReason::ClientClosed | ExitReason::UpstreamClosed | ExitReason::IdleClosed => 1000, |
| 855 | ExitReason::ProtocolViolation(_) => 1008, |
| 856 | ExitReason::Revoked => 4401, |
| 857 | ExitReason::ParserPanic | ExitReason::Error(_) => 1011, |
| 858 | } |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | struct SessionCounters { |
| 863 | last_human_input: parking_lot::Mutex<Instant>, |
| 864 | last_screen_bytes: parking_lot::Mutex<Instant>, |
| 865 | input_forwarded: AtomicU64, |
| 866 | input_dropped: AtomicU64, |
| 867 | } |
| 868 | |
| 869 | /// Parser task body: client bytes → [`ClientParser`] → upstream writer. |
| 870 | async fn parser_loop<R, W>( |
| 871 | mut ws_in: WsIn<R>, |
| 872 | mut upstream: W, |
| 873 | computer: ComputerState, |
| 874 | principal: Principal, |
| 875 | counters: Arc<SessionCounters>, |
| 876 | ) -> ExitReason |
| 877 | where |
| 878 | R: futures_util::Stream<Item = Result<Message, axum::Error>> + Unpin, |
| 879 | W: AsyncWrite + Unpin, |
| 880 | { |
| 881 | let mut parser = ClientParser::default(); |
| 882 | let mut out = Vec::with_capacity(4096); |
| 883 | loop { |
| 884 | let chunk = match ws_in.next_chunk().await { |
| 885 | Ok(Some(chunk)) => chunk, |
| 886 | Ok(None) => return ExitReason::ClientClosed, |
| 887 | Err(detail) => return ExitReason::ProtocolViolation(detail), |
| 888 | }; |
| 889 | out.clear(); |
| 890 | let allowed = computer.holds_lease(&principal); |
| 891 | let stats = match parser.feed(&chunk, allowed, &mut out) { |
| 892 | Ok(stats) => stats, |
| 893 | Err(err) => return ExitReason::ProtocolViolation(err.to_string()), |
| 894 | }; |
| 895 | if stats.input_forwarded > 0 { |
| 896 | computer.note_input(&principal, stats.input_forwarded); |
| 897 | *counters.last_human_input.lock() = Instant::now(); |
| 898 | counters |
| 899 | .input_forwarded |
| 900 | .fetch_add(stats.input_forwarded, Ordering::Relaxed); |
| 901 | } |
| 902 | if stats.input_dropped > 0 { |
| 903 | counters |
| 904 | .input_dropped |
| 905 | .fetch_add(stats.input_dropped, Ordering::Relaxed); |
| 906 | } |
| 907 | if !out.is_empty() && upstream.write_all(&out).await.is_err() { |
| 908 | return ExitReason::UpstreamClosed; |
| 909 | } |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | /// Map a parser task's join result to an exit reason. A panic inside the |
| 914 | /// parser is contained here: it ends this display connection only. |
| 915 | fn parser_exit(result: Result<ExitReason, tokio::task::JoinError>) -> ExitReason { |
| 916 | match result { |
| 917 | Ok(reason) => reason, |
| 918 | Err(err) if err.is_panic() => ExitReason::ParserPanic, |
| 919 | Err(err) => ExitReason::Error(err.to_string()), |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | async fn run_session<U>( |
| 924 | socket: WebSocket, |
| 925 | upstream: U, |
| 926 | computer: ComputerState, |
| 927 | principal: Principal, |
| 928 | ) where |
| 929 | U: AsyncRead + AsyncWrite + Unpin + Send + 'static, |
| 930 | { |
| 931 | let connection_id = computer |
| 932 | .inner |
| 933 | .next_connection |
| 934 | .fetch_add(1, Ordering::Relaxed); |
| 935 | let started = Instant::now(); |
| 936 | let (mut ws_tx, ws_rx) = socket.split(); |
| 937 | let mut ws_in = WsIn { |
| 938 | stream: ws_rx, |
| 939 | pending: Vec::new(), |
| 940 | }; |
| 941 | |
| 942 | // Downstream handshake: offer RFB 3.8 with security None only. |
| 943 | let handshake = async { |
| 944 | ws_tx |
| 945 | .send(Message::Binary(RFB_VERSION_38.to_vec().into())) |
| 946 | .await |
| 947 | .map_err(|e| e.to_string())?; |
| 948 | let version = ws_in.read_exact(12).await?; |
| 949 | if version != RFB_VERSION_38 { |
| 950 | return Err("client must speak RFB 003.008".to_string()); |
| 951 | } |
| 952 | ws_tx |
| 953 | .send(Message::Binary(vec![1u8, 1].into())) |
| 954 | .await |
| 955 | .map_err(|e| e.to_string())?; |
| 956 | let choice = ws_in.read_exact(1).await?; |
| 957 | if choice != [1] { |
| 958 | return Err("client chose an unsupported security type".to_string()); |
| 959 | } |
| 960 | ws_tx |
| 961 | .send(Message::Binary(vec![0u8, 0, 0, 0].into())) |
| 962 | .await |
| 963 | .map_err(|e| e.to_string())?; |
| 964 | // ClientInit: its shared flag is ignored; upstream is always shared. |
| 965 | ws_in.read_exact(1).await?; |
| 966 | Ok::<(), String>(()) |
| 967 | }; |
| 968 | if let Err(detail) = tokio::time::timeout(HANDSHAKE_TIMEOUT, handshake) |
| 969 | .await |
| 970 | .unwrap_or_else(|_| Err("handshake timed out".to_string())) |
| 971 | { |
| 972 | let _ = ws_tx |
| 973 | .send(Message::Close(Some(CloseFrame { |
| 974 | code: 1008, |
| 975 | reason: "rfb handshake failed".into(), |
| 976 | }))) |
| 977 | .await; |
| 978 | tracing::info!(target: "codewhale::computer", %detail, "display handshake failed"); |
| 979 | return; |
| 980 | } |
| 981 | |
| 982 | computer.inner.attached.fetch_add(1, Ordering::Relaxed); |
| 983 | computer.emit( |
| 984 | "computer.display.attached", |
| 985 | json!({ |
| 986 | "connection_id": connection_id, |
| 987 | "holder": principal.holder(), |
| 988 | "device_id": principal.device_id(), |
| 989 | }), |
| 990 | ); |
| 991 | |
| 992 | let counters = Arc::new(SessionCounters { |
| 993 | last_human_input: parking_lot::Mutex::new(Instant::now()), |
| 994 | last_screen_bytes: parking_lot::Mutex::new(Instant::now()), |
| 995 | input_forwarded: AtomicU64::new(0), |
| 996 | input_dropped: AtomicU64::new(0), |
| 997 | }); |
| 998 | let (mut up_r, up_w) = tokio::io::split(upstream); |
| 999 | |
| 1000 | // Parser in its own task (§3.3): a panic here must not reach a turn. |
| 1001 | let mut parser = tokio::spawn(parser_loop( |
| 1002 | ws_in, |
| 1003 | up_w, |
| 1004 | computer.clone(), |
| 1005 | principal.clone(), |
| 1006 | counters.clone(), |
| 1007 | )); |
| 1008 | |
| 1009 | let mut tick = tokio::time::interval(SUPERVISOR_TICK); |
| 1010 | tick.tick().await; |
| 1011 | let mut buf = vec![0u8; 64 * 1024]; |
| 1012 | let reason = loop { |
| 1013 | tokio::select! { |
| 1014 | joined = &mut parser => break parser_exit(joined), |
| 1015 | read = up_r.read(&mut buf) => match read { |
| 1016 | Ok(0) | Err(_) => break ExitReason::UpstreamClosed, |
| 1017 | Ok(n) => { |
| 1018 | *counters.last_screen_bytes.lock() = Instant::now(); |
| 1019 | if ws_tx.send(Message::Binary(buf[..n].to_vec().into())).await.is_err() { |
| 1020 | break ExitReason::ClientClosed; |
| 1021 | } |
| 1022 | } |
| 1023 | }, |
| 1024 | _ = tick.tick() => { |
| 1025 | computer.sweep_lease(); |
| 1026 | if !computer.principal_is_live(&principal) { |
| 1027 | break ExitReason::Revoked; |
| 1028 | } |
| 1029 | let idle = computer.inner.idle_close; |
| 1030 | let human_idle = counters.last_human_input.lock().elapsed() >= idle; |
| 1031 | let screen_idle = counters.last_screen_bytes.lock().elapsed() >= idle; |
| 1032 | if human_idle && screen_idle { |
| 1033 | break ExitReason::IdleClosed; |
| 1034 | } |
| 1035 | } |
| 1036 | } |
| 1037 | }; |
| 1038 | parser.abort(); |
| 1039 | |
| 1040 | let _ = ws_tx |
| 1041 | .send(Message::Close(Some(CloseFrame { |
| 1042 | code: reason.close_code(), |
| 1043 | reason: reason.label().into(), |
| 1044 | }))) |
| 1045 | .await; |
| 1046 | computer.inner.attached.fetch_sub(1, Ordering::Relaxed); |
| 1047 | let span = json!({ |
| 1048 | "connection_id": connection_id, |
| 1049 | "holder": principal.holder(), |
| 1050 | "reason": reason.label(), |
| 1051 | "attached_ms": started.elapsed().as_millis() as u64, |
| 1052 | "input_forwarded": counters.input_forwarded.load(Ordering::Relaxed), |
| 1053 | "input_dropped": counters.input_dropped.load(Ordering::Relaxed), |
| 1054 | }); |
| 1055 | if reason == ExitReason::IdleClosed { |
| 1056 | computer.emit("computer.display.idle_closed", span.clone()); |
| 1057 | } |
| 1058 | computer.emit("computer.display.detached", span); |
| 1059 | } |
| 1060 | |
| 1061 | // --------------------------------------------------------------------------- |
| 1062 | // HTTP |
| 1063 | // --------------------------------------------------------------------------- |
| 1064 | |
| 1065 | #[derive(Clone)] |
| 1066 | struct RouteState { |
| 1067 | computer: ComputerState, |
| 1068 | runtime_token: Option<String>, |
| 1069 | } |
| 1070 | |
| 1071 | struct ApiErr { |
| 1072 | status: StatusCode, |
| 1073 | message: String, |
| 1074 | extra: Option<Value>, |
| 1075 | } |
| 1076 | |
| 1077 | impl ApiErr { |
| 1078 | fn new(status: StatusCode, message: impl Into<String>) -> Self { |
| 1079 | Self { |
| 1080 | status, |
| 1081 | message: message.into(), |
| 1082 | extra: None, |
| 1083 | } |
| 1084 | } |
| 1085 | fn unauthorized() -> Self { |
| 1086 | Self::new( |
| 1087 | StatusCode::UNAUTHORIZED, |
| 1088 | "runtime API bearer token required", |
| 1089 | ) |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | impl IntoResponse for ApiErr { |
| 1094 | fn into_response(self) -> Response { |
| 1095 | let mut body = json!({ |
| 1096 | "error": { "message": self.message, "status": self.status.as_u16() } |
| 1097 | }); |
| 1098 | if let Some(extra) = self.extra { |
| 1099 | body["error"]["detail"] = extra; |
| 1100 | } |
| 1101 | (self.status, Json(body)).into_response() |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | fn bearer(headers: &HeaderMap) -> Option<&str> { |
| 1106 | headers |
| 1107 | .get(header::AUTHORIZATION) |
| 1108 | .and_then(|v| v.to_str().ok()) |
| 1109 | .and_then(|raw| raw.strip_prefix("Bearer ")) |
| 1110 | .or_else(|| { |
| 1111 | headers |
| 1112 | .get("x-codewhale-runtime-token") |
| 1113 | .and_then(|v| v.to_str().ok()) |
| 1114 | }) |
| 1115 | } |
| 1116 | |
| 1117 | fn principal_from_headers(state: &RouteState, headers: &HeaderMap) -> Option<Principal> { |
| 1118 | let Some(expected) = state.runtime_token.as_deref() else { |
| 1119 | return Some(Principal::Owner); |
| 1120 | }; |
| 1121 | let presented = bearer(headers)?; |
| 1122 | if constant_time_eq(presented.as_bytes(), expected.as_bytes()) { |
| 1123 | return Some(Principal::Owner); |
| 1124 | } |
| 1125 | state.computer.client_principal(presented) |
| 1126 | } |
| 1127 | |
| 1128 | fn require_principal(state: &RouteState, headers: &HeaderMap) -> Result<Principal, ApiErr> { |
| 1129 | principal_from_headers(state, headers).ok_or_else(ApiErr::unauthorized) |
| 1130 | } |
| 1131 | |
| 1132 | fn require_driver(state: &RouteState, headers: &HeaderMap) -> Result<Principal, ApiErr> { |
| 1133 | let principal = require_principal(state, headers)?; |
| 1134 | if !principal.can_drive() { |
| 1135 | return Err(ApiErr::new( |
| 1136 | StatusCode::FORBIDDEN, |
| 1137 | "watch client tokens cannot control this Computer", |
| 1138 | )); |
| 1139 | } |
| 1140 | Ok(principal) |
| 1141 | } |
| 1142 | |
| 1143 | /// Routes for the computer surface, merged into the Runtime API router |
| 1144 | /// outside the `/v1` auth layer (each handler authenticates itself). |
| 1145 | pub(super) fn router<S>(computer: ComputerState, runtime_token: Option<String>) -> Router<S> |
| 1146 | where |
| 1147 | S: Clone + Send + Sync + 'static, |
| 1148 | { |
| 1149 | Router::new() |
| 1150 | .route("/v1/computer", get(computer_status)) |
| 1151 | .route("/v1/computer/events", get(computer_events)) |
| 1152 | .route("/v1/computer/control/acquire", post(control_acquire)) |
| 1153 | .route("/v1/computer/control/release", post(control_release)) |
| 1154 | .route("/v1/computer/display/tickets", post(display_ticket)) |
| 1155 | .route("/v1/computer/display", get(display_ws)) |
| 1156 | .route( |
| 1157 | "/v1/auth/client-tokens", |
| 1158 | get(list_client_tokens).post(create_client_token), |
| 1159 | ) |
| 1160 | .route("/v1/auth/client-tokens/{id}", delete(revoke_client_token)) |
| 1161 | .with_state(RouteState { |
| 1162 | computer, |
| 1163 | runtime_token, |
| 1164 | }) |
| 1165 | } |
| 1166 | |
| 1167 | async fn computer_status(State(state): State<RouteState>, headers: HeaderMap) -> Response { |
| 1168 | let principal = match require_principal(&state, &headers) { |
| 1169 | Ok(p) => p, |
| 1170 | Err(e) => return e.into_response(), |
| 1171 | }; |
| 1172 | let lease = state.computer.sweep_lease(); |
| 1173 | let you_hold = state.computer.holds_lease(&principal); |
| 1174 | let (_, seq) = state.computer.events_since(u64::MAX); |
| 1175 | Json(json!({ |
| 1176 | "display": { |
| 1177 | "available": display_socket_present(&state.computer).await, |
| 1178 | "attached": state.computer.inner.attached.load(Ordering::Relaxed), |
| 1179 | "idle_close_seconds": state.computer.inner.idle_close.as_secs(), |
| 1180 | }, |
| 1181 | "control": { |
| 1182 | "lease": lease, |
| 1183 | "you_hold_lease": you_hold, |
| 1184 | "human_driving": lease.is_some(), |
| 1185 | "lease_idle_ttl_seconds": state.computer.inner.lease_ttl.as_secs(), |
| 1186 | }, |
| 1187 | "events_seq": seq, |
| 1188 | })) |
| 1189 | .into_response() |
| 1190 | } |
| 1191 | |
| 1192 | async fn display_socket_present(computer: &ComputerState) -> bool { |
| 1193 | #[cfg(unix)] |
| 1194 | { |
| 1195 | use std::os::unix::fs::FileTypeExt; |
| 1196 | tokio::fs::metadata(&computer.inner.socket_path) |
| 1197 | .await |
| 1198 | .map(|m| m.file_type().is_socket()) |
| 1199 | .unwrap_or(false) |
| 1200 | } |
| 1201 | #[cfg(not(unix))] |
| 1202 | { |
| 1203 | let _ = computer; |
| 1204 | false |
| 1205 | } |
| 1206 | } |
| 1207 | |
| 1208 | #[derive(Deserialize)] |
| 1209 | struct EventsQuery { |
| 1210 | since: Option<u64>, |
| 1211 | } |
| 1212 | |
| 1213 | async fn computer_events( |
| 1214 | State(state): State<RouteState>, |
| 1215 | headers: HeaderMap, |
| 1216 | Query(query): Query<EventsQuery>, |
| 1217 | ) -> Response { |
| 1218 | if let Err(e) = require_principal(&state, &headers) { |
| 1219 | return e.into_response(); |
| 1220 | } |
| 1221 | state.computer.sweep_lease(); |
| 1222 | let (events, next) = state.computer.events_since(query.since.unwrap_or(0)); |
| 1223 | Json(json!({ "events": events, "next_since": next })).into_response() |
| 1224 | } |
| 1225 | |
| 1226 | #[derive(Deserialize, Default)] |
| 1227 | struct AcquireBody { |
| 1228 | #[serde(default)] |
| 1229 | force: bool, |
| 1230 | } |
| 1231 | |
| 1232 | async fn control_acquire( |
| 1233 | State(state): State<RouteState>, |
| 1234 | headers: HeaderMap, |
| 1235 | body: Option<Json<AcquireBody>>, |
| 1236 | ) -> Response { |
| 1237 | let principal = match require_driver(&state, &headers) { |
| 1238 | Ok(p) => p, |
| 1239 | Err(e) => return e.into_response(), |
| 1240 | }; |
| 1241 | let force = body.map(|Json(b)| b.force).unwrap_or(false); |
| 1242 | match state.computer.acquire(&principal, force) { |
| 1243 | Ok(lease) => Json(json!({ "lease": lease })).into_response(), |
| 1244 | Err(current) => ApiErr { |
| 1245 | status: StatusCode::CONFLICT, |
| 1246 | message: "another client holds the control lease".to_string(), |
| 1247 | extra: Some(json!({ "lease": current })), |
| 1248 | } |
| 1249 | .into_response(), |
| 1250 | } |
| 1251 | } |
| 1252 | |
| 1253 | async fn control_release(State(state): State<RouteState>, headers: HeaderMap) -> Response { |
| 1254 | let principal = match require_driver(&state, &headers) { |
| 1255 | Ok(p) => p, |
| 1256 | Err(e) => return e.into_response(), |
| 1257 | }; |
| 1258 | if state.computer.release(&principal) { |
| 1259 | Json(json!({ "released": true })).into_response() |
| 1260 | } else { |
| 1261 | ApiErr::new( |
| 1262 | StatusCode::CONFLICT, |
| 1263 | "this client does not hold the control lease", |
| 1264 | ) |
| 1265 | .into_response() |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | async fn display_ticket(State(state): State<RouteState>, headers: HeaderMap) -> Response { |
| 1270 | let principal = match require_principal(&state, &headers) { |
| 1271 | Ok(p) => p, |
| 1272 | Err(e) => return e.into_response(), |
| 1273 | }; |
| 1274 | match state.computer.mint_ticket(principal) { |
| 1275 | Ok(ticket) => ( |
| 1276 | StatusCode::CREATED, |
| 1277 | Json(json!({ |
| 1278 | "ticket": ticket, |
| 1279 | "expires_in_seconds": DISPLAY_TICKET_TTL.as_secs(), |
| 1280 | })), |
| 1281 | ) |
| 1282 | .into_response(), |
| 1283 | Err(e) => e.into_response(), |
| 1284 | } |
| 1285 | } |
| 1286 | |
| 1287 | #[derive(Deserialize)] |
| 1288 | struct DisplayQuery { |
| 1289 | ticket: Option<String>, |
| 1290 | } |
| 1291 | |
| 1292 | async fn display_ws( |
| 1293 | State(state): State<RouteState>, |
| 1294 | headers: HeaderMap, |
| 1295 | uri: Uri, |
| 1296 | Query(query): Query<DisplayQuery>, |
| 1297 | ws: Result<WebSocketUpgrade, WebSocketUpgradeRejection>, |
| 1298 | ) -> Response { |
| 1299 | let principal = match principal_from_headers(&state, &headers) { |
| 1300 | Some(p) => p, |
| 1301 | None => match query |
| 1302 | .ticket |
| 1303 | .as_deref() |
| 1304 | .and_then(|ticket| state.computer.redeem_ticket(ticket)) |
| 1305 | { |
| 1306 | Some(p) => p, |
| 1307 | None => return ApiErr::unauthorized().into_response(), |
| 1308 | }, |
| 1309 | }; |
| 1310 | tracing::info!( |
| 1311 | target: "codewhale::computer", |
| 1312 | uri = %redact_query_secrets(&uri.to_string()), |
| 1313 | holder = %principal.holder(), |
| 1314 | "computer display attach" |
| 1315 | ); |
| 1316 | let ws = match ws { |
| 1317 | Ok(ws) => ws, |
| 1318 | Err(rejection) => return rejection.into_response(), |
| 1319 | }; |
| 1320 | let upstream = match connect_upstream(&state.computer).await { |
| 1321 | Ok(upstream) => upstream, |
| 1322 | Err(detail) => { |
| 1323 | tracing::warn!(target: "codewhale::computer", %detail, "computer display unavailable"); |
| 1324 | return ApiErr::new( |
| 1325 | StatusCode::SERVICE_UNAVAILABLE, |
| 1326 | "computer display unavailable", |
| 1327 | ) |
| 1328 | .into_response(); |
| 1329 | } |
| 1330 | }; |
| 1331 | let computer = state.computer.clone(); |
| 1332 | ws.on_upgrade(move |socket| run_session(socket, upstream, computer, principal)) |
| 1333 | } |
| 1334 | |
| 1335 | #[cfg(unix)] |
| 1336 | async fn connect_upstream(computer: &ComputerState) -> Result<tokio::net::UnixStream, String> { |
| 1337 | let connect = async { |
| 1338 | let mut stream = tokio::net::UnixStream::connect(&computer.inner.socket_path) |
| 1339 | .await |
| 1340 | .map_err(|e| format!("connect display socket: {e}"))?; |
| 1341 | upstream_handshake(&mut stream).await?; |
| 1342 | Ok::<_, String>(stream) |
| 1343 | }; |
| 1344 | tokio::time::timeout(HANDSHAKE_TIMEOUT, connect) |
| 1345 | .await |
| 1346 | .unwrap_or_else(|_| Err("display handshake timed out".to_string())) |
| 1347 | } |
| 1348 | |
| 1349 | #[cfg(not(unix))] |
| 1350 | async fn connect_upstream(_computer: &ComputerState) -> Result<tokio::io::DuplexStream, String> { |
| 1351 | Err("the computer display is Unix-only".to_string()) |
| 1352 | } |
| 1353 | |
| 1354 | #[derive(Deserialize)] |
| 1355 | #[serde(deny_unknown_fields)] |
| 1356 | struct CreateClientTokenBody { |
| 1357 | device_id: String, |
| 1358 | ttl_seconds: Option<u64>, |
| 1359 | label: Option<String>, |
| 1360 | #[serde(default)] |
| 1361 | intent: ClientTokenIntent, |
| 1362 | } |
| 1363 | |
| 1364 | fn valid_device_id(id: &str) -> bool { |
| 1365 | !id.is_empty() |
| 1366 | && id.len() <= DEVICE_ID_MAX_BYTES |
| 1367 | && id |
| 1368 | .bytes() |
| 1369 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':')) |
| 1370 | } |
| 1371 | |
| 1372 | /// Minting is master-token only: a client token can never mint another. |
| 1373 | fn require_owner(state: &RouteState, headers: &HeaderMap) -> Result<(), ApiErr> { |
| 1374 | let Some(expected) = state.runtime_token.as_deref() else { |
| 1375 | return Err(ApiErr::new( |
| 1376 | StatusCode::CONFLICT, |
| 1377 | "client tokens need Runtime API auth; this Engine runs without a token", |
| 1378 | )); |
| 1379 | }; |
| 1380 | match bearer(headers) { |
| 1381 | Some(presented) if constant_time_eq(presented.as_bytes(), expected.as_bytes()) => Ok(()), |
| 1382 | Some(presented) if state.computer.client_principal(presented).is_some() => { |
| 1383 | Err(ApiErr::new( |
| 1384 | StatusCode::FORBIDDEN, |
| 1385 | "client tokens cannot manage client tokens", |
| 1386 | )) |
| 1387 | } |
| 1388 | _ => Err(ApiErr::unauthorized()), |
| 1389 | } |
| 1390 | } |
| 1391 | |
| 1392 | async fn create_client_token( |
| 1393 | State(state): State<RouteState>, |
| 1394 | headers: HeaderMap, |
| 1395 | Json(body): Json<CreateClientTokenBody>, |
| 1396 | ) -> Response { |
| 1397 | if let Err(e) = require_owner(&state, &headers) { |
| 1398 | return e.into_response(); |
| 1399 | } |
| 1400 | let device_id = body.device_id.trim().to_string(); |
| 1401 | if !valid_device_id(&device_id) { |
| 1402 | return ApiErr::new( |
| 1403 | StatusCode::BAD_REQUEST, |
| 1404 | "device_id must be 1-128 of [A-Za-z0-9._:-]", |
| 1405 | ) |
| 1406 | .into_response(); |
| 1407 | } |
| 1408 | let ttl = body |
| 1409 | .ttl_seconds |
| 1410 | .unwrap_or(CLIENT_TOKEN_MAX_TTL_SECS) |
| 1411 | .clamp(CLIENT_TOKEN_MIN_TTL_SECS, CLIENT_TOKEN_MAX_TTL_SECS); |
| 1412 | let label = body |
| 1413 | .label |
| 1414 | .map(|l| l.chars().take(128).collect::<String>()) |
| 1415 | .filter(|l| !l.trim().is_empty()); |
| 1416 | match state |
| 1417 | .computer |
| 1418 | .mint_client_token(device_id, ttl, label, body.intent) |
| 1419 | { |
| 1420 | Ok((token, view)) => ( |
| 1421 | StatusCode::CREATED, |
| 1422 | Json(json!({ |
| 1423 | "token": token, |
| 1424 | "id": view.id, |
| 1425 | "device_id": view.device_id, |
| 1426 | "intent": view.intent, |
| 1427 | "label": view.label, |
| 1428 | "created_at": view.created_at, |
| 1429 | "expires_at": view.expires_at, |
| 1430 | })), |
| 1431 | ) |
| 1432 | .into_response(), |
| 1433 | Err(e) => e.into_response(), |
| 1434 | } |
| 1435 | } |
| 1436 | |
| 1437 | async fn list_client_tokens(State(state): State<RouteState>, headers: HeaderMap) -> Response { |
| 1438 | if let Err(e) = require_owner(&state, &headers) { |
| 1439 | return e.into_response(); |
| 1440 | } |
| 1441 | Json(json!({ "tokens": state.computer.list_client_tokens() })).into_response() |
| 1442 | } |
| 1443 | |
| 1444 | async fn revoke_client_token( |
| 1445 | State(state): State<RouteState>, |
| 1446 | headers: HeaderMap, |
| 1447 | Path(id): Path<String>, |
| 1448 | ) -> Response { |
| 1449 | if let Err(e) = require_owner(&state, &headers) { |
| 1450 | return e.into_response(); |
| 1451 | } |
| 1452 | if state.computer.revoke_client_token(&id) { |
| 1453 | state.computer.sweep_lease(); |
| 1454 | StatusCode::NO_CONTENT.into_response() |
| 1455 | } else { |
| 1456 | ApiErr::new(StatusCode::NOT_FOUND, "no such client token").into_response() |
| 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | #[cfg(test)] |
| 1461 | #[path = "computer_display_tests.rs"] |
| 1462 | mod tests; |
| 1463 |