| 1 | //! Remote / cloud attach surface for native clients (APPS-50). |
| 2 | //! |
| 3 | //! A "target" is a Codewhale runtime a client talks to. This server is always |
| 4 | //! the local target; remote targets are other `codewhale serve --http` |
| 5 | //! endpoints, and the *client* owns that registry — a runtime never persists |
| 6 | //! peer endpoints, relays sessions, or mints a second process owner. SSH |
| 7 | //! workspaces and hosted cloud computers are control-plane features, so those |
| 8 | //! routes answer honestly (`supported: false`) and refuse writes with 501 |
| 9 | //! instead of 404 — a client can render real disabled states with reasons. |
| 10 | //! |
| 11 | //! Routes: |
| 12 | //! GET /v1/targets — this runtime's target record |
| 13 | //! POST /v1/targets — 501: target registry is client-owned |
| 14 | //! POST /v1/targets/switch — 501: client-owned; never mid-turn server-side |
| 15 | //! GET /v1/remote — this runtime's reachability posture |
| 16 | //! POST /v1/remote/connect — probe a candidate remote runtime endpoint |
| 17 | //! GET /v1/ssh — SSH workspaces: control-plane owned |
| 18 | //! POST /v1/ssh/connect — 501 |
| 19 | //! GET /v1/cloud — hosted computers: control-plane owned |
| 20 | //! POST /v1/cloud/attach — 501 |
| 21 | |
| 22 | use std::net::{IpAddr, SocketAddr}; |
| 23 | use std::time::Duration; |
| 24 | |
| 25 | use axum::Json; |
| 26 | use axum::extract::State; |
| 27 | use serde::Deserialize; |
| 28 | use serde_json::{Value, json}; |
| 29 | |
| 30 | use super::{ApiError, RuntimeApiState}; |
| 31 | |
| 32 | const PROBE_TIMEOUT: Duration = Duration::from_secs(5); |
| 33 | const PROBE_MAX_BYTES: usize = 64 * 1024; |
| 34 | const CONTROL_PLANE_OWNER: &str = "codewhale-control-plane"; |
| 35 | |
| 36 | fn self_target(state: &RuntimeApiState) -> Value { |
| 37 | json!({ |
| 38 | "id": "local", |
| 39 | "kind": "local", |
| 40 | "current": true, |
| 41 | "endpoint": format!("http://{}:{}", display_host(&state.bind_host), state.bind_port), |
| 42 | "auth_required": state.auth_required, |
| 43 | "service": "codewhale-runtime-api", |
| 44 | "codewhale_version": env!("CARGO_PKG_VERSION"), |
| 45 | "state": "ready", |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | fn display_host(host: &str) -> String { |
| 50 | if host.parse::<IpAddr>().is_ok_and(|ip| ip.is_ipv6()) { |
| 51 | format!("[{host}]") |
| 52 | } else { |
| 53 | host.to_string() |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | fn unsupported_surface(feature: &str) -> Value { |
| 58 | json!({ |
| 59 | "supported": false, |
| 60 | "owner": CONTROL_PLANE_OWNER, |
| 61 | "reason": format!( |
| 62 | "{feature} is owned by the Codewhale control plane (managed apps); this runtime does not broker it" |
| 63 | ), |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | pub(super) async fn list_targets(State(state): State<RuntimeApiState>) -> Json<Value> { |
| 68 | Json(json!({ |
| 69 | "targets": [self_target(&state)], |
| 70 | // Remote attach means the client points at another runtime's /v1 API; |
| 71 | // nothing server-side needs to (or may) switch. |
| 72 | "remote": { |
| 73 | "supported": true, |
| 74 | "attach": "client", |
| 75 | "probe": "POST /v1/remote/connect", |
| 76 | }, |
| 77 | "ssh": unsupported_surface("SSH remote workspaces"), |
| 78 | "cloud": unsupported_surface("Hosted cloud computers"), |
| 79 | "tailnet": { |
| 80 | "supported": true, |
| 81 | "inventory": "/v1/tailnet", |
| 82 | "enrollment": "external", |
| 83 | "execution": "explicit_fleet_workers", |
| 84 | }, |
| 85 | "placement": { "version": 1, "preview": "POST /v1/fleet/placement", "dispatch": "operator_fleet_cli" }, |
| 86 | })) |
| 87 | } |
| 88 | |
| 89 | pub(super) async fn create_target(State(_state): State<RuntimeApiState>) -> ApiError { |
| 90 | ApiError::not_implemented( |
| 91 | "target registry is client-owned; attach by pointing the client at a runtime endpoint", |
| 92 | ) |
| 93 | } |
| 94 | |
| 95 | pub(super) async fn switch_target(State(_state): State<RuntimeApiState>) -> ApiError { |
| 96 | ApiError::not_implemented( |
| 97 | "target switching is client-owned; a switch must never move a running task or replay input", |
| 98 | ) |
| 99 | } |
| 100 | |
| 101 | pub(super) async fn remote_status(State(state): State<RuntimeApiState>) -> Json<Value> { |
| 102 | let loopback_only = super::is_loopback_bind_host(&state.bind_host); |
| 103 | Json(json!({ |
| 104 | "bind_host": state.bind_host, |
| 105 | "port": state.bind_port, |
| 106 | "loopback_only": loopback_only, |
| 107 | "reachable_from_lan": !loopback_only, |
| 108 | "auth_required": state.auth_required, |
| 109 | "mobile": state.mobile_enabled, |
| 110 | // The runtime API has no TLS terminator; non-loopback reachability |
| 111 | // assumes a verified overlay (VPN/mesh), never plain LAN trust. |
| 112 | "tls": false, |
| 113 | })) |
| 114 | } |
| 115 | |
| 116 | #[derive(Deserialize)] |
| 117 | #[serde(deny_unknown_fields)] |
| 118 | pub(super) struct RemoteConnectRequest { |
| 119 | /// Base URL of the candidate runtime, e.g. `http://192.168.1.5:7878`. |
| 120 | /// Credentials in the URL are refused — runtime tokens never travel |
| 121 | /// through this server. |
| 122 | endpoint: String, |
| 123 | } |
| 124 | |
| 125 | fn is_blocked_remote_probe_ip(ip: &IpAddr) -> bool { |
| 126 | if codewhale_net::guard::is_cloud_metadata_ip(ip) { |
| 127 | return true; |
| 128 | } |
| 129 | match ip { |
| 130 | IpAddr::V4(v4) => { |
| 131 | v4.is_loopback() |
| 132 | || v4.is_link_local() |
| 133 | || v4.is_unspecified() |
| 134 | || v4.octets()[0] == 0 |
| 135 | || v4.is_multicast() |
| 136 | || v4.is_broadcast() |
| 137 | } |
| 138 | IpAddr::V6(v6) => { |
| 139 | if codewhale_net::guard::embedded_ipv4_addrs(*v6) |
| 140 | .iter() |
| 141 | .any(|v4| is_blocked_remote_probe_ip(&IpAddr::V4(*v4))) |
| 142 | { |
| 143 | return true; |
| 144 | } |
| 145 | v6.is_loopback() |
| 146 | || v6.is_unspecified() |
| 147 | || v6.is_multicast() |
| 148 | || matches!(v6.segments(), [0xfe80..=0xfebf, ..]) |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | fn is_loopback_hostname(host: &str) -> bool { |
| 154 | let bare = host.trim().trim_end_matches('.').to_ascii_lowercase(); |
| 155 | bare == "localhost" || bare == "localhost.localdomain" || bare.ends_with(".localhost") |
| 156 | } |
| 157 | |
| 158 | fn parse_literal_ip(host: &str) -> Option<IpAddr> { |
| 159 | host.strip_prefix('[') |
| 160 | .and_then(|rest| rest.strip_suffix(']')) |
| 161 | .unwrap_or(host) |
| 162 | .parse() |
| 163 | .ok() |
| 164 | } |
| 165 | |
| 166 | enum ProbeTargetResolution { |
| 167 | Pinned(Option<(String, IpAddr)>), |
| 168 | Unreachable(String), |
| 169 | } |
| 170 | |
| 171 | async fn validate_and_resolve_probe_target( |
| 172 | host: &str, |
| 173 | port: u16, |
| 174 | ) -> Result<ProbeTargetResolution, ApiError> { |
| 175 | const BLOCKED_MSG: &str = |
| 176 | "remote probe refuses loopback, link-local, metadata, unspecified, and multicast targets"; |
| 177 | |
| 178 | if is_loopback_hostname(host) { |
| 179 | return Err(ApiError::bad_request(BLOCKED_MSG)); |
| 180 | } |
| 181 | if let Some(ip) = parse_literal_ip(host) { |
| 182 | if is_blocked_remote_probe_ip(&ip) { |
| 183 | return Err(ApiError::bad_request(BLOCKED_MSG)); |
| 184 | } |
| 185 | return Ok(ProbeTargetResolution::Pinned(None)); |
| 186 | } |
| 187 | let resolved = |
| 188 | match tokio::time::timeout(PROBE_TIMEOUT, tokio::net::lookup_host((host, port))).await { |
| 189 | Ok(Ok(addrs)) => addrs.collect::<Vec<SocketAddr>>(), |
| 190 | Ok(Err(error)) => return Ok(ProbeTargetResolution::Unreachable(error.to_string())), |
| 191 | Err(_) => { |
| 192 | return Ok(ProbeTargetResolution::Unreachable( |
| 193 | "timed out resolving endpoint host".to_string(), |
| 194 | )); |
| 195 | } |
| 196 | }; |
| 197 | if resolved.is_empty() { |
| 198 | return Ok(ProbeTargetResolution::Unreachable( |
| 199 | "endpoint host resolved to no addresses".to_string(), |
| 200 | )); |
| 201 | } |
| 202 | for addr in &resolved { |
| 203 | if is_blocked_remote_probe_ip(&addr.ip()) { |
| 204 | return Err(ApiError::bad_request(BLOCKED_MSG)); |
| 205 | } |
| 206 | } |
| 207 | Ok(ProbeTargetResolution::Pinned(Some(( |
| 208 | host.to_string(), |
| 209 | resolved[0].ip(), |
| 210 | )))) |
| 211 | } |
| 212 | |
| 213 | /// Probe a candidate remote endpoint's `/v1/runtime/info`. The probe is |
| 214 | /// unauthenticated against the remote on purpose: this route must never be a |
| 215 | /// bearer-token forwarding primitive, and `runtime/info` answers signed-out |
| 216 | /// identity + `auth_required` without one. A negative reachability verdict is |
| 217 | /// data (`ok: false`), not a server error — the probe itself succeeded. |
| 218 | pub(super) async fn remote_connect( |
| 219 | State(_state): State<RuntimeApiState>, |
| 220 | Json(req): Json<RemoteConnectRequest>, |
| 221 | ) -> Result<Json<Value>, ApiError> { |
| 222 | let url = reqwest::Url::parse(req.endpoint.trim()) |
| 223 | .map_err(|_| ApiError::bad_request("endpoint must be an http(s) URL"))?; |
| 224 | if !matches!(url.scheme(), "http" | "https") { |
| 225 | return Err(ApiError::bad_request( |
| 226 | "endpoint scheme must be http or https", |
| 227 | )); |
| 228 | } |
| 229 | if !url.username().is_empty() || url.password().is_some() { |
| 230 | return Err(ApiError::bad_request( |
| 231 | "credentials in endpoints are refused; send the remote's runtime token from the client", |
| 232 | )); |
| 233 | } |
| 234 | let host = url |
| 235 | .host_str() |
| 236 | .ok_or_else(|| ApiError::bad_request("endpoint must name a host"))?; |
| 237 | let port = url |
| 238 | .port_or_known_default() |
| 239 | .ok_or_else(|| ApiError::bad_request("endpoint must specify a valid port"))?; |
| 240 | // Origin only — the runtime API always serves at /v1 regardless of the |
| 241 | // path a user pasted. |
| 242 | let origin = match url.port() { |
| 243 | Some(port) => format!("{}://{host}:{port}", url.scheme()), |
| 244 | None => format!("{}://{host}", url.scheme()), |
| 245 | }; |
| 246 | let dns_pin = match validate_and_resolve_probe_target(host, port).await? { |
| 247 | ProbeTargetResolution::Pinned(pin) => pin, |
| 248 | ProbeTargetResolution::Unreachable(detail) => { |
| 249 | return Ok(Json(json!({ |
| 250 | "ok": false, |
| 251 | "endpoint": origin, |
| 252 | "reason": "unreachable", |
| 253 | "detail": detail, |
| 254 | }))); |
| 255 | } |
| 256 | }; |
| 257 | let probe_url = format!("{origin}/v1/runtime/info"); |
| 258 | |
| 259 | let mut builder = codewhale_net::guard::guarded_reqwest_client_builder() |
| 260 | .redirect(reqwest::redirect::Policy::none()) |
| 261 | .timeout(PROBE_TIMEOUT); |
| 262 | if let Some((pin_host, pin_ip)) = dns_pin { |
| 263 | builder = builder.resolve(&pin_host, SocketAddr::new(pin_ip, port)); |
| 264 | } |
| 265 | let client = builder |
| 266 | .build() |
| 267 | .map_err(|error| ApiError::internal(format!("probe client unavailable: {error}")))?; |
| 268 | let mut response = match client.get(&probe_url).send().await { |
| 269 | Ok(response) => response, |
| 270 | Err(error) => { |
| 271 | return Ok(Json(json!({ |
| 272 | "ok": false, |
| 273 | "endpoint": origin, |
| 274 | "reason": "unreachable", |
| 275 | "detail": error.to_string(), |
| 276 | }))); |
| 277 | } |
| 278 | }; |
| 279 | let status = response.status(); |
| 280 | let mut bytes = Vec::new(); |
| 281 | let mut too_large = false; |
| 282 | while let Ok(Some(chunk)) = response.chunk().await { |
| 283 | if bytes.len() + chunk.len() > PROBE_MAX_BYTES { |
| 284 | too_large = true; |
| 285 | break; |
| 286 | } |
| 287 | bytes.extend_from_slice(&chunk); |
| 288 | } |
| 289 | if too_large { |
| 290 | return Ok(Json(json!({ |
| 291 | "ok": false, |
| 292 | "endpoint": origin, |
| 293 | "reason": "response too large to be a runtime identity", |
| 294 | }))); |
| 295 | } |
| 296 | let body: Value = match serde_json::from_slice(&bytes) { |
| 297 | Ok(body) => body, |
| 298 | Err(_) => { |
| 299 | return Ok(Json(json!({ |
| 300 | "ok": false, |
| 301 | "endpoint": origin, |
| 302 | "status": status.as_u16(), |
| 303 | "reason": "not a Codewhale runtime", |
| 304 | }))); |
| 305 | } |
| 306 | }; |
| 307 | if body.get("service").and_then(Value::as_str) != Some("codewhale-runtime-api") { |
| 308 | return Ok(Json(json!({ |
| 309 | "ok": false, |
| 310 | "endpoint": origin, |
| 311 | "status": status.as_u16(), |
| 312 | "reason": "not a Codewhale runtime", |
| 313 | }))); |
| 314 | } |
| 315 | Ok(Json(json!({ |
| 316 | "ok": true, |
| 317 | "endpoint": origin, |
| 318 | "remote": { |
| 319 | "kind": "remote", |
| 320 | "endpoint": origin, |
| 321 | "service": "codewhale-runtime-api", |
| 322 | "runtime_api_version": body.get("runtime_api_version").cloned().unwrap_or(Value::Null), |
| 323 | "codewhale_version": body.get("codewhale_version").cloned().unwrap_or(Value::Null), |
| 324 | "auth_required": body.get("auth_required").cloned().unwrap_or(Value::Null), |
| 325 | "bind_host": body.get("bind_host").cloned().unwrap_or(Value::Null), |
| 326 | "port": body.get("port").cloned().unwrap_or(Value::Null), |
| 327 | }, |
| 328 | // The verdict is all this server knows: attaching means the client |
| 329 | // re-targets its own transport at `endpoint` with that runtime's token. |
| 330 | "attach": "client", |
| 331 | }))) |
| 332 | } |
| 333 | |
| 334 | pub(super) async fn ssh_status(State(_state): State<RuntimeApiState>) -> Json<Value> { |
| 335 | Json(unsupported_surface("SSH remote workspaces")) |
| 336 | } |
| 337 | |
| 338 | pub(super) async fn ssh_connect(State(_state): State<RuntimeApiState>) -> ApiError { |
| 339 | ApiError::not_implemented( |
| 340 | "SSH remote workspaces are owned by the Codewhale control plane; this runtime does not open SSH transports", |
| 341 | ) |
| 342 | } |
| 343 | |
| 344 | pub(super) async fn cloud_status(State(_state): State<RuntimeApiState>) -> Json<Value> { |
| 345 | Json(unsupported_surface("Hosted cloud computers")) |
| 346 | } |
| 347 | |
| 348 | pub(super) async fn cloud_attach(State(_state): State<RuntimeApiState>) -> ApiError { |
| 349 | ApiError::not_implemented( |
| 350 | "hosted cloud computers are owned by the Codewhale control plane; this runtime does not provision them", |
| 351 | ) |
| 352 | } |
| 353 | |
| 354 | pub(super) async fn tailnet_inventory( |
| 355 | State(_state): State<RuntimeApiState>, |
| 356 | ) -> Result<Json<Value>, ApiError> { |
| 357 | let result = tokio::task::spawn_blocking(codewhale_engine::fleet::tailnet::inventory) |
| 358 | .await |
| 359 | .map_err(|error| ApiError::internal(format!("Tailnet inventory task failed: {error}")))?; |
| 360 | Ok(Json(match result { |
| 361 | Ok(nodes) => json!({ "available": true, "nodes": nodes, "grants_execution": false }), |
| 362 | Err(error) => { |
| 363 | json!({ "available": false, "nodes": [], "code": "tailnet_unavailable", "reason": error.to_string(), "grants_execution": false }) |
| 364 | } |
| 365 | })) |
| 366 | } |
| 367 | |
| 368 | pub(super) async fn placement_preview( |
| 369 | State(_state): State<RuntimeApiState>, |
| 370 | Json(mut document): Json<codewhale_engine::fleet::task_spec::FleetTaskSpecDocument>, |
| 371 | ) -> Result<Json<Value>, ApiError> { |
| 372 | if document.tasks.len() > 64 { |
| 373 | return Err(ApiError::bad_request( |
| 374 | "Placement previews support up to 64 tasks", |
| 375 | )); |
| 376 | } |
| 377 | codewhale_engine::fleet::task_spec::validate_task_spec_document(&document) |
| 378 | .map_err(|error| ApiError::bad_request(error.to_string()))?; |
| 379 | if document.workers.is_empty() { |
| 380 | document.workers.push(serde_json::from_value(json!({ |
| 381 | "id": "local", "name": "This computer", "host": { "kind": "local" }, "capabilities": ["local"], |
| 382 | })).map_err(|error| ApiError::internal(error.to_string()))?); |
| 383 | } |
| 384 | let unavailable = std::collections::BTreeSet::new(); |
| 385 | let decisions: Vec<_> = document |
| 386 | .tasks |
| 387 | .iter() |
| 388 | .map(|task| { |
| 389 | codewhale_engine::fleet::placement::decide(task, &document.workers, &unavailable) |
| 390 | }) |
| 391 | .collect(); |
| 392 | Ok(Json( |
| 393 | json!({ "execution": "preview", "evidence": "operator_declared", "grants_execution": false, "decisions": decisions }), |
| 394 | )) |
| 395 | } |
| 396 | |
| 397 | #[cfg(test)] |
| 398 | mod tests { |
| 399 | use super::*; |
| 400 | |
| 401 | #[test] |
| 402 | fn remote_probe_blocks_loopback_metadata_unspecified_and_multicast_ips() { |
| 403 | for blocked in [ |
| 404 | "127.0.0.1", |
| 405 | "127.255.255.254", |
| 406 | "169.254.169.254", |
| 407 | "169.254.0.1", |
| 408 | "100.100.100.200", |
| 409 | "0.0.0.0", |
| 410 | "0.1.2.3", |
| 411 | "224.0.0.1", |
| 412 | "255.255.255.255", |
| 413 | "::1", |
| 414 | "::", |
| 415 | "fe80::1", |
| 416 | "ff02::1", |
| 417 | "::ffff:127.0.0.1", |
| 418 | "::ffff:169.254.169.254", |
| 419 | "::ffff:0.0.0.0", |
| 420 | "::ffff:0:127.0.0.1", |
| 421 | "64:ff9b::127.0.0.1", |
| 422 | "64:ff9b::0.0.0.0", |
| 423 | "64:ff9b:1::127.0.0.1", |
| 424 | "2002:7f00:1::", |
| 425 | "2001:0:7f00:1::", |
| 426 | ] { |
| 427 | let ip: IpAddr = blocked.parse().unwrap(); |
| 428 | assert!( |
| 429 | is_blocked_remote_probe_ip(&ip), |
| 430 | "{blocked} should be blocked" |
| 431 | ); |
| 432 | } |
| 433 | for allowed in [ |
| 434 | "192.168.1.5", |
| 435 | "10.0.0.12", |
| 436 | "100.64.0.1", |
| 437 | "93.184.216.34", |
| 438 | "fd7a:115c:a1e0::1", |
| 439 | "2606:2800:220:1:248:1893:25c8:1946", |
| 440 | ] { |
| 441 | let ip: IpAddr = allowed.parse().unwrap(); |
| 442 | assert!( |
| 443 | !is_blocked_remote_probe_ip(&ip), |
| 444 | "{allowed} should be allowed for remote runtime probes" |
| 445 | ); |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | #[tokio::test] |
| 450 | async fn validate_and_resolve_probe_target_blocks_localhost_and_metadata() { |
| 451 | for host in [ |
| 452 | "localhost", |
| 453 | "sub.localhost", |
| 454 | "localhost.localdomain", |
| 455 | "127.0.0.1", |
| 456 | "[::1]", |
| 457 | "169.254.169.254", |
| 458 | "[fe80::1]", |
| 459 | "0.0.0.0", |
| 460 | "[::]", |
| 461 | "224.0.0.1", |
| 462 | ] { |
| 463 | assert!( |
| 464 | validate_and_resolve_probe_target(host, 7878).await.is_err(), |
| 465 | "{host} should be rejected" |
| 466 | ); |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 |