aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-cockpit-rs / src / access.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Operator access boundary. Browser sessions never put credentials in URLs. |
| 17 | use axum::{ |
| 18 | extract::{Form, Request, State}, |
| 19 | http::{HeaderMap, StatusCode, header}, |
| 20 | middleware::Next, |
| 21 | response::{Html, IntoResponse, Response}, |
| 22 | }; |
| 23 | use serde::Deserialize; |
| 24 | use std::{ |
| 25 | collections::HashMap, |
| 26 | net::SocketAddr, |
| 27 | sync::{Arc, Mutex}, |
| 28 | time::{Duration, Instant}, |
| 29 | }; |
| 30 | |
| 31 | const COOKIE: &str = "aien_cockpit_session"; |
| 32 | const LOGIN: &str = r#"<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>AIEN sign in</title><h1>Sign in to AIEN</h1><form method="post" action="/auth/session"><label>Operator access token <input type="password" name="token" autocomplete="off" required></label><button>Sign in</button></form></html>"#; |
| 33 | |
| 34 | pub struct Access { |
| 35 | token: String, |
| 36 | origins: Vec<String>, |
| 37 | sessions: Mutex<HashMap<String, Instant>>, |
| 38 | } |
| 39 | |
| 40 | impl Access { |
| 41 | pub fn new(token: String, origins: Vec<String>) -> Result<Self, String> { |
| 42 | if token.len() < 32 |
| 43 | || token.len() > 256 |
| 44 | || !token |
| 45 | .bytes() |
| 46 | .all(|b| b.is_ascii_alphanumeric() || b"-_+=/.".contains(&b)) |
| 47 | { |
| 48 | return Err("Cockpit token must contain 32 to 256 cookie-safe ASCII characters".into()); |
| 49 | } |
| 50 | if origins.is_empty() |
| 51 | || origins.iter().any(|o| { |
| 52 | o.parse::<axum::http::Uri>().map_or(true, |uri| { |
| 53 | uri.authority().is_none() || uri.path() != "/" || uri.query().is_some() |
| 54 | }) || !(o.starts_with("http://") || o.starts_with("https://")) |
| 55 | || o.ends_with('/') |
| 56 | }) |
| 57 | { |
| 58 | return Err( |
| 59 | "Cockpit origins must be explicit HTTP(S) origins without a trailing slash".into(), |
| 60 | ); |
| 61 | } |
| 62 | Ok(Self { |
| 63 | token, |
| 64 | origins, |
| 65 | sessions: Mutex::new(HashMap::new()), |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | pub fn from_environment() -> Result<Self, String> { |
| 70 | let from_env = std::env::var("AIEN_COCKPIT_TOKEN") |
| 71 | .ok() |
| 72 | .filter(|t| !t.trim().is_empty()); |
| 73 | let token = from_env |
| 74 | .or_else(|| { |
| 75 | let result = std::process::Command::new("atlas-vault") |
| 76 | .args(["get", "AIEN_COCKPIT_TOKEN"]) |
| 77 | .output() |
| 78 | .ok()?; |
| 79 | result |
| 80 | .status |
| 81 | .success() |
| 82 | .then(|| String::from_utf8(result.stdout).ok()) |
| 83 | .flatten() |
| 84 | }) |
| 85 | .ok_or("AIEN_COCKPIT_TOKEN is unavailable from memory or atlas-vault")?; |
| 86 | let origins = std::env::var("AIEN_COCKPIT_ORIGINS") |
| 87 | .unwrap_or_else(|_| "http://127.0.0.1:18095,http://localhost:18095".into()); |
| 88 | Self::new( |
| 89 | token.trim().to_owned(), |
| 90 | origins.split(',').map(|o| o.trim().to_owned()).collect(), |
| 91 | ) |
| 92 | } |
| 93 | |
| 94 | fn matches(&self, supplied: &str) -> bool { |
| 95 | if supplied.len() != self.token.len() { |
| 96 | return false; |
| 97 | } |
| 98 | self.token |
| 99 | .bytes() |
| 100 | .zip(supplied.bytes()) |
| 101 | .fold(0u8, |diff, (a, b)| diff | (a ^ b)) |
| 102 | == 0 |
| 103 | } |
| 104 | |
| 105 | fn create_session(&self) -> Option<String> { |
| 106 | let mut sessions = self.sessions.lock().ok()?; |
| 107 | sessions.retain(|_, expires| *expires > Instant::now()); |
| 108 | if sessions.len() >= 1024 { |
| 109 | return None; |
| 110 | } |
| 111 | let id = format!( |
| 112 | "{}{}", |
| 113 | uuid::Uuid::new_v4().simple(), |
| 114 | uuid::Uuid::new_v4().simple() |
| 115 | ); |
| 116 | sessions.insert(id.clone(), Instant::now() + Duration::from_secs(3600)); |
| 117 | Some(id) |
| 118 | } |
| 119 | |
| 120 | fn session_valid(&self, id: &str) -> bool { |
| 121 | self.sessions.lock().ok().is_some_and(|sessions| { |
| 122 | sessions |
| 123 | .get(id) |
| 124 | .is_some_and(|expires| *expires > Instant::now()) |
| 125 | }) |
| 126 | } |
| 127 | |
| 128 | fn origin_allowed(&self, headers: &HeaderMap) -> bool { |
| 129 | headers |
| 130 | .get(header::ORIGIN) |
| 131 | .and_then(|v| v.to_str().ok()) |
| 132 | .is_some_and(|origin| self.origins.iter().any(|o| o == origin)) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// Read-only health routes that local monitors (aien-cli, spark-debugger, |
| 137 | /// spark-supervisor) poll without credentials. GET/HEAD |
| 138 | /// only, and only when the Host header names the loopback listener, so a |
| 139 | /// DNS-rebinding page cannot read them through a foreign hostname. |
| 140 | const PUBLIC_READ_ROUTES: &[&str] = &["/api/pulse", "/api/status"]; |
| 141 | |
| 142 | fn loopback_host(headers: &HeaderMap) -> bool { |
| 143 | headers |
| 144 | .get(header::HOST) |
| 145 | .and_then(|v| v.to_str().ok()) |
| 146 | .and_then(|host| host.parse::<axum::http::uri::Authority>().ok()) |
| 147 | .is_some_and(|authority| matches!(authority.host(), "127.0.0.1" | "localhost" | "[::1]")) |
| 148 | } |
| 149 | |
| 150 | pub fn bind_address() -> Result<SocketAddr, String> { |
| 151 | std::env::var("AIEN_COCKPIT_ADDR") |
| 152 | .unwrap_or_else(|_| "127.0.0.1:18095".into()) |
| 153 | .parse() |
| 154 | .map_err(|_| "AIEN_COCKPIT_ADDR must be a socket address".into()) |
| 155 | } |
| 156 | |
| 157 | pub async fn login() -> Response { |
| 158 | let mut response = Html(LOGIN).into_response(); |
| 159 | response |
| 160 | .headers_mut() |
| 161 | .insert(header::CACHE_CONTROL, "no-store".parse().unwrap()); |
| 162 | response.headers_mut().insert( |
| 163 | header::CONTENT_SECURITY_POLICY, |
| 164 | "default-src 'none'; form-action 'self'; frame-ancestors 'none'" |
| 165 | .parse() |
| 166 | .unwrap(), |
| 167 | ); |
| 168 | response |
| 169 | } |
| 170 | |
| 171 | #[derive(Deserialize)] |
| 172 | pub struct LoginForm { |
| 173 | token: String, |
| 174 | } |
| 175 | |
| 176 | pub async fn session( |
| 177 | State(access): State<Arc<Access>>, |
| 178 | headers: HeaderMap, |
| 179 | Form(form): Form<LoginForm>, |
| 180 | ) -> Response { |
| 181 | if !access.origin_allowed(&headers) { |
| 182 | return StatusCode::FORBIDDEN.into_response(); |
| 183 | } |
| 184 | if !access.matches(&form.token) { |
| 185 | return StatusCode::UNAUTHORIZED.into_response(); |
| 186 | } |
| 187 | let secure = headers |
| 188 | .get(header::ORIGIN) |
| 189 | .and_then(|v| v.to_str().ok()) |
| 190 | .is_some_and(|v| v.starts_with("https://")); |
| 191 | let Some(id) = access.create_session() else { |
| 192 | return StatusCode::SERVICE_UNAVAILABLE.into_response(); |
| 193 | }; |
| 194 | let cookie = format!( |
| 195 | "{COOKIE}={}; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600{}", |
| 196 | id, |
| 197 | if secure { "; Secure" } else { "" } |
| 198 | ); |
| 199 | let mut response = StatusCode::SEE_OTHER.into_response(); |
| 200 | response |
| 201 | .headers_mut() |
| 202 | .insert(header::LOCATION, "/".parse().unwrap()); |
| 203 | response |
| 204 | .headers_mut() |
| 205 | .insert(header::SET_COOKIE, cookie.parse().unwrap()); |
| 206 | response |
| 207 | .headers_mut() |
| 208 | .insert(header::CACHE_CONTROL, "no-store".parse().unwrap()); |
| 209 | response |
| 210 | } |
| 211 | |
| 212 | pub async fn require_access( |
| 213 | State(access): State<Arc<Access>>, |
| 214 | request: Request, |
| 215 | next: Next, |
| 216 | ) -> Response { |
| 217 | let headers = request.headers(); |
| 218 | let origin_present = headers.contains_key(header::ORIGIN); |
| 219 | let websocket = headers |
| 220 | .get(header::UPGRADE) |
| 221 | .and_then(|v| v.to_str().ok()) |
| 222 | .is_some_and(|v| v.eq_ignore_ascii_case("websocket")); |
| 223 | if (origin_present && !access.origin_allowed(headers)) |
| 224 | || (websocket && !access.origin_allowed(headers)) |
| 225 | { |
| 226 | return StatusCode::FORBIDDEN.into_response(); |
| 227 | } |
| 228 | let read_only = |
| 229 | request.method() == axum::http::Method::GET || request.method() == axum::http::Method::HEAD; |
| 230 | if read_only |
| 231 | && !websocket |
| 232 | && PUBLIC_READ_ROUTES.contains(&request.uri().path()) |
| 233 | && loopback_host(headers) |
| 234 | { |
| 235 | return next.run(request).await; |
| 236 | } |
| 237 | let bearer = headers |
| 238 | .get(header::AUTHORIZATION) |
| 239 | .and_then(|v| v.to_str().ok()) |
| 240 | .and_then(|v| v.strip_prefix("Bearer ")) |
| 241 | .is_some_and(|t| access.matches(t)); |
| 242 | let cookie = headers |
| 243 | .get(header::COOKIE) |
| 244 | .and_then(|v| v.to_str().ok()) |
| 245 | .is_some_and(|cookies| { |
| 246 | cookies.split(';').any(|v| { |
| 247 | v.trim() |
| 248 | .strip_prefix(&format!("{COOKIE}=")) |
| 249 | .is_some_and(|t| access.session_valid(t)) |
| 250 | }) |
| 251 | }); |
| 252 | // Cookie credentials require an allowed browser Origin for every mutation. |
| 253 | let safe = |
| 254 | request.method() == axum::http::Method::GET || request.method() == axum::http::Method::HEAD; |
| 255 | if !bearer && (!cookie || (!safe && !access.origin_allowed(headers))) { |
| 256 | if safe |
| 257 | && headers |
| 258 | .get(header::ACCEPT) |
| 259 | .and_then(|v| v.to_str().ok()) |
| 260 | .is_some_and(|v| v.contains("text/html")) |
| 261 | { |
| 262 | return axum::response::Redirect::to("/login").into_response(); |
| 263 | } |
| 264 | return StatusCode::UNAUTHORIZED.into_response(); |
| 265 | } |
| 266 | let mut response = next.run(request).await; |
| 267 | response |
| 268 | .headers_mut() |
| 269 | .insert(header::CACHE_CONTROL, "no-store".parse().unwrap()); |
| 270 | response |
| 271 | } |
| 272 | |
| 273 | #[cfg(test)] |
| 274 | mod tests { |
| 275 | use super::*; |
| 276 | use axum::{ |
| 277 | Router, middleware, |
| 278 | routing::{get, post}, |
| 279 | }; |
| 280 | |
| 281 | #[tokio::test] |
| 282 | async fn boundary_rejects_missing_tokens_and_cross_origin_sessions() { |
| 283 | let access = |
| 284 | Arc::new(Access::new("a".repeat(64), vec!["http://localhost:18095".into()]).unwrap()); |
| 285 | let app = Router::new() |
| 286 | .route( |
| 287 | "/private", |
| 288 | get(|| async { "private" }).post(|| async { "changed" }), |
| 289 | ) |
| 290 | .route("/ws/terminal", get(|| async { "terminal" })) |
| 291 | .layer(middleware::from_fn_with_state( |
| 292 | Arc::clone(&access), |
| 293 | require_access, |
| 294 | )) |
| 295 | .merge( |
| 296 | Router::new() |
| 297 | .route("/auth/session", post(session)) |
| 298 | .with_state(Arc::clone(&access)), |
| 299 | ); |
| 300 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 301 | let url = format!("http://{}", listener.local_addr().unwrap()); |
| 302 | let server = tokio::spawn(async move { |
| 303 | axum::serve(listener, app).await.unwrap(); |
| 304 | }); |
| 305 | let client = reqwest::Client::builder() |
| 306 | .redirect(reqwest::redirect::Policy::none()) |
| 307 | .build() |
| 308 | .unwrap(); |
| 309 | for path in ["/private", "/ws/terminal"] { |
| 310 | assert_eq!( |
| 311 | client |
| 312 | .get(format!("{url}{path}")) |
| 313 | .send() |
| 314 | .await |
| 315 | .unwrap() |
| 316 | .status(), |
| 317 | 401 |
| 318 | ); |
| 319 | } |
| 320 | assert_eq!( |
| 321 | client |
| 322 | .get(format!("{url}/private")) |
| 323 | .bearer_auth("wrong") |
| 324 | .send() |
| 325 | .await |
| 326 | .unwrap() |
| 327 | .status(), |
| 328 | 401 |
| 329 | ); |
| 330 | assert_eq!( |
| 331 | client |
| 332 | .get(format!("{url}/private")) |
| 333 | .bearer_auth("a".repeat(64)) |
| 334 | .send() |
| 335 | .await |
| 336 | .unwrap() |
| 337 | .status(), |
| 338 | 200 |
| 339 | ); |
| 340 | let form = format!("token={}", "a".repeat(64)); |
| 341 | assert_eq!( |
| 342 | client |
| 343 | .post(format!("{url}/auth/session")) |
| 344 | .header("Origin", "http://evil.example") |
| 345 | .header("Content-Type", "application/x-www-form-urlencoded") |
| 346 | .body(form.clone()) |
| 347 | .send() |
| 348 | .await |
| 349 | .unwrap() |
| 350 | .status(), |
| 351 | 403 |
| 352 | ); |
| 353 | let login = client |
| 354 | .post(format!("{url}/auth/session")) |
| 355 | .header("Origin", "http://localhost:18095") |
| 356 | .header("Content-Type", "application/x-www-form-urlencoded") |
| 357 | .body(form) |
| 358 | .send() |
| 359 | .await |
| 360 | .unwrap(); |
| 361 | assert_eq!(login.status(), 303); |
| 362 | let cookie = login |
| 363 | .headers() |
| 364 | .get("set-cookie") |
| 365 | .unwrap() |
| 366 | .to_str() |
| 367 | .unwrap() |
| 368 | .split(';') |
| 369 | .next() |
| 370 | .unwrap() |
| 371 | .to_owned(); |
| 372 | assert!(!cookie.contains(&"a".repeat(64))); |
| 373 | assert_eq!( |
| 374 | client |
| 375 | .get(format!("{url}/private")) |
| 376 | .header("Cookie", &cookie) |
| 377 | .send() |
| 378 | .await |
| 379 | .unwrap() |
| 380 | .status(), |
| 381 | 200 |
| 382 | ); |
| 383 | assert_eq!( |
| 384 | client |
| 385 | .post(format!("{url}/private")) |
| 386 | .header("Cookie", &cookie) |
| 387 | .send() |
| 388 | .await |
| 389 | .unwrap() |
| 390 | .status(), |
| 391 | 401 |
| 392 | ); |
| 393 | assert_eq!( |
| 394 | client |
| 395 | .post(format!("{url}/private")) |
| 396 | .header("Cookie", &cookie) |
| 397 | .header("Origin", "http://evil.example") |
| 398 | .send() |
| 399 | .await |
| 400 | .unwrap() |
| 401 | .status(), |
| 402 | 403 |
| 403 | ); |
| 404 | assert_eq!( |
| 405 | client |
| 406 | .post(format!("{url}/private")) |
| 407 | .header("Cookie", &cookie) |
| 408 | .header("Origin", "http://localhost:18095") |
| 409 | .send() |
| 410 | .await |
| 411 | .unwrap() |
| 412 | .status(), |
| 413 | 200 |
| 414 | ); |
| 415 | for expires in access.sessions.lock().unwrap().values_mut() { |
| 416 | *expires = Instant::now() - Duration::from_secs(1); |
| 417 | } |
| 418 | assert_eq!( |
| 419 | client |
| 420 | .get(format!("{url}/private")) |
| 421 | .header("Cookie", &cookie) |
| 422 | .send() |
| 423 | .await |
| 424 | .unwrap() |
| 425 | .status(), |
| 426 | 401 |
| 427 | ); |
| 428 | server.abort(); |
| 429 | } |
| 430 | |
| 431 | #[test] |
| 432 | fn refuses_empty_credentials_and_invalid_origins() { |
| 433 | assert!(Access::new(String::new(), vec!["http://localhost:18095".into()]).is_err()); |
| 434 | assert!(Access::new("a".repeat(64), vec!["http://localhost:18095/path".into()]).is_err()); |
| 435 | } |
| 436 | |
| 437 | #[tokio::test] |
| 438 | async fn health_reads_stay_open_on_loopback_only() { |
| 439 | let access = |
| 440 | Arc::new(Access::new("a".repeat(64), vec!["http://localhost:18095".into()]).unwrap()); |
| 441 | let app = Router::new() |
| 442 | .route("/api/pulse", get(|| async { "pulse" })) |
| 443 | .route("/api/status", get(|| async { "status" })) |
| 444 | .route("/api/goals", get(|| async { "goals" })) |
| 445 | .layer(middleware::from_fn_with_state( |
| 446 | Arc::clone(&access), |
| 447 | require_access, |
| 448 | )); |
| 449 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 450 | let url = format!("http://{}", listener.local_addr().unwrap()); |
| 451 | let server = tokio::spawn(async move { |
| 452 | axum::serve(listener, app).await.unwrap(); |
| 453 | }); |
| 454 | let client = reqwest::Client::new(); |
| 455 | for path in ["/api/pulse", "/api/status"] { |
| 456 | let status = client |
| 457 | .get(format!("{url}{path}")) |
| 458 | .send() |
| 459 | .await |
| 460 | .unwrap() |
| 461 | .status(); |
| 462 | assert_eq!(status, 200, "{path} must stay readable for local monitors"); |
| 463 | } |
| 464 | let not_public = client |
| 465 | .get(format!("{url}/api/goals")) |
| 466 | .send() |
| 467 | .await |
| 468 | .unwrap() |
| 469 | .status(); |
| 470 | assert_eq!(not_public, 401); |
| 471 | let mutation = client |
| 472 | .post(format!("{url}/api/pulse")) |
| 473 | .send() |
| 474 | .await |
| 475 | .unwrap() |
| 476 | .status(); |
| 477 | assert_eq!(mutation, 401); |
| 478 | let rebound = client |
| 479 | .get(format!("{url}/api/pulse")) |
| 480 | .header("Host", "evil.example:18095") |
| 481 | .send() |
| 482 | .await |
| 483 | .unwrap() |
| 484 | .status(); |
| 485 | assert_eq!(rebound, 401); |
| 486 | let foreign_origin = client |
| 487 | .get(format!("{url}/api/pulse")) |
| 488 | .header("Origin", "http://evil.example") |
| 489 | .send() |
| 490 | .await |
| 491 | .unwrap() |
| 492 | .status(); |
| 493 | assert_eq!(foreign_origin, 403); |
| 494 | server.abort(); |
| 495 | } |
| 496 | } |