aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / tests / gateway_auth_tests.rs
| 1 | //! Gateway hardening: operator token on every non-public route, loopback bind |
| 2 | //! by default, allowlist dispatch. Each test is a bypass attempt or a |
| 3 | //! realistic fault the rule must catch. |
| 4 | |
| 5 | use aegis::{ |
| 6 | create_router, AgentEngine, Database, GatewayState, HeartbeatEngine, HttpInferenceBackend, |
| 7 | OperatorAuth, SkillRegistry, WorkspaceCapability, |
| 8 | }; |
| 9 | use axum::{ |
| 10 | body::Body, |
| 11 | http::{Request, StatusCode}, |
| 12 | }; |
| 13 | use serde_json::{json, Value}; |
| 14 | use std::sync::Arc; |
| 15 | use std::time::Instant; |
| 16 | use tower::util::ServiceExt; |
| 17 | |
| 18 | const TOKEN: &str = "auth-test-operator-token-0123456789abcdef"; |
| 19 | |
| 20 | fn state_with(auth: OperatorAuth, workspace: &std::path::Path) -> GatewayState { |
| 21 | let db = Arc::new(Database::open_in_memory().unwrap()); |
| 22 | // Unreachable inference: no route here should need a model to answer. |
| 23 | let inference = Arc::new(HttpInferenceBackend::new( |
| 24 | Some("http://127.0.0.1:9/v1/chat/completions".to_string()), |
| 25 | None, |
| 26 | )); |
| 27 | let heartbeat = Arc::new(HeartbeatEngine::new(60, db.clone())); |
| 28 | let skills = Arc::new(SkillRegistry::with_workspace( |
| 29 | WorkspaceCapability::new(workspace).unwrap(), |
| 30 | )); |
| 31 | let agent = Arc::new(AgentEngine::new( |
| 32 | inference.clone(), |
| 33 | skills.clone(), |
| 34 | Some(db.clone()), |
| 35 | )); |
| 36 | GatewayState { |
| 37 | start_time: Instant::now(), |
| 38 | db, |
| 39 | inference, |
| 40 | heartbeat, |
| 41 | skills, |
| 42 | agent, |
| 43 | operator: auth, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn authed() -> OperatorAuth { |
| 48 | OperatorAuth::with_token(TOKEN).unwrap() |
| 49 | } |
| 50 | |
| 51 | async fn send( |
| 52 | state: &GatewayState, |
| 53 | method: &str, |
| 54 | uri: &str, |
| 55 | headers: &[(&str, String)], |
| 56 | body: Value, |
| 57 | ) -> (StatusCode, Value) { |
| 58 | let mut b = Request::builder() |
| 59 | .method(method) |
| 60 | .uri(uri) |
| 61 | .header("content-type", "application/json"); |
| 62 | for (k, v) in headers { |
| 63 | b = b.header(*k, v); |
| 64 | } |
| 65 | let res = create_router(state.clone()) |
| 66 | .oneshot(b.body(Body::from(body.to_string())).unwrap()) |
| 67 | .await |
| 68 | .unwrap(); |
| 69 | let status = res.status(); |
| 70 | let bytes = axum::body::to_bytes(res.into_body(), usize::MAX) |
| 71 | .await |
| 72 | .unwrap(); |
| 73 | ( |
| 74 | status, |
| 75 | serde_json::from_slice(&bytes).unwrap_or(Value::Null), |
| 76 | ) |
| 77 | } |
| 78 | |
| 79 | fn bearer(t: &str) -> Vec<(&'static str, String)> { |
| 80 | vec![("authorization", format!("Bearer {}", t))] |
| 81 | } |
| 82 | |
| 83 | /// Every mutating or effectful route, with a body that would act if admitted. |
| 84 | fn protected_routes() -> Vec<(&'static str, &'static str, Value)> { |
| 85 | vec![ |
| 86 | ("POST", "/api/v1/shell", json!({"command": "ls"})), |
| 87 | ( |
| 88 | "POST", |
| 89 | "/api/v1/skills/execute", |
| 90 | json!({"skill_name": "write_file", "arguments": {"path": "pwned.txt", "content": "x"}}), |
| 91 | ), |
| 92 | ( |
| 93 | "POST", |
| 94 | "/api/v1/tasks", |
| 95 | json!({"task_type": "shell_exec", "payload": "ls"}), |
| 96 | ), |
| 97 | ( |
| 98 | "POST", |
| 99 | "/api/v1/agent/run", |
| 100 | json!({"prompt": "hi", "max_turns": 1}), |
| 101 | ), |
| 102 | ("POST", "/api/v1/chat", json!({"prompt": "hi"})), |
| 103 | ("POST", "/api/v1/heartbeat/tick", json!({})), |
| 104 | ( |
| 105 | "POST", |
| 106 | "/api/v1/discord/relay", |
| 107 | json!({"channel_id": "c", "author": "a", "content": "hi"}), |
| 108 | ), |
| 109 | ( |
| 110 | "POST", |
| 111 | "/v1/chat/completions", |
| 112 | json!({"messages": [{"role": "user", "content": "hi"}]}), |
| 113 | ), |
| 114 | ("POST", "/v1/probe", json!({"state": {}, "probes": {}})), |
| 115 | ("GET", "/ws", json!({})), |
| 116 | ("GET", "/api/v1/ws", json!({})), |
| 117 | ] |
| 118 | } |
| 119 | |
| 120 | #[tokio::test] |
| 121 | async fn protected_routes_refuse_missing_or_wrong_tokens() { |
| 122 | let ws = tempfile::tempdir().unwrap(); |
| 123 | let state = state_with(authed(), ws.path()); |
| 124 | let attempts: Vec<Vec<(&str, String)>> = vec![ |
| 125 | vec![], |
| 126 | bearer("wrong-token-wrong-token-wrong-token-xx"), |
| 127 | bearer(&TOKEN[..TOKEN.len() - 1]), |
| 128 | bearer(&format!("{}x", TOKEN)), |
| 129 | bearer(""), |
| 130 | vec![("authorization", format!("bearer {}", TOKEN))], |
| 131 | vec![("authorization", format!("Basic {}", TOKEN))], |
| 132 | vec![("authorization", TOKEN.to_string())], |
| 133 | vec![("x-forwarded-for", "127.0.0.1".to_string())], |
| 134 | vec![("x-aegis-operator-token", "nope".to_string())], |
| 135 | ]; |
| 136 | for (method, uri, body) in protected_routes() { |
| 137 | for headers in &attempts { |
| 138 | let (status, _) = send(&state, method, uri, headers, body.clone()).await; |
| 139 | assert_eq!( |
| 140 | status, |
| 141 | StatusCode::UNAUTHORIZED, |
| 142 | "{} {} admitted with headers {:?}", |
| 143 | method, |
| 144 | uri, |
| 145 | headers |
| 146 | ); |
| 147 | } |
| 148 | // Token in the query string is never read. |
| 149 | let q = format!("{}?token={}&operator_token={}", uri, TOKEN, TOKEN); |
| 150 | let (status, _) = send(&state, method, &q, &[], body.clone()).await; |
| 151 | assert_eq!(status, StatusCode::UNAUTHORIZED, "{} via query", uri); |
| 152 | } |
| 153 | // The refused write never happened. |
| 154 | assert!(!ws.path().join("pwned.txt").exists()); |
| 155 | assert!(state.db.list_pending_tasks().unwrap().is_empty()); |
| 156 | } |
| 157 | |
| 158 | #[tokio::test] |
| 159 | async fn path_tricks_do_not_reach_public_list() { |
| 160 | let ws = tempfile::tempdir().unwrap(); |
| 161 | let state = state_with(authed(), ws.path()); |
| 162 | for uri in [ |
| 163 | "/health/../api/v1/shell", |
| 164 | "/api/v1/health/../shell", |
| 165 | "//api/v1/shell", |
| 166 | "/api/v1/shell/", |
| 167 | "/API/V1/SHELL", |
| 168 | ] { |
| 169 | let (status, _) = send(&state, "POST", uri, &[], json!({"command": "ls"})).await; |
| 170 | assert!( |
| 171 | status == StatusCode::UNAUTHORIZED || status == StatusCode::NOT_FOUND, |
| 172 | "{} gave {}", |
| 173 | uri, |
| 174 | status |
| 175 | ); |
| 176 | assert_ne!(status, StatusCode::OK, "{}", uri); |
| 177 | } |
| 178 | // A POST to a public read path is not public. |
| 179 | let (status, _) = send(&state, "POST", "/api/v1/tasks", &[], json!({})).await; |
| 180 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 181 | } |
| 182 | |
| 183 | #[tokio::test] |
| 184 | async fn no_configured_token_means_protected_routes_are_closed() { |
| 185 | let ws = tempfile::tempdir().unwrap(); |
| 186 | let state = state_with(OperatorAuth::disabled(), ws.path()); |
| 187 | for (method, uri, body) in protected_routes() { |
| 188 | for headers in [vec![], bearer(""), bearer(TOKEN)] { |
| 189 | let (status, _) = send(&state, method, uri, &headers, body.clone()).await; |
| 190 | assert_eq!( |
| 191 | status, |
| 192 | StatusCode::SERVICE_UNAVAILABLE, |
| 193 | "{} {}", |
| 194 | method, |
| 195 | uri |
| 196 | ); |
| 197 | } |
| 198 | } |
| 199 | let (status, _) = send(&state, "GET", "/health", &[], json!({})).await; |
| 200 | assert_eq!(status, StatusCode::OK); |
| 201 | } |
| 202 | |
| 203 | #[tokio::test] |
| 204 | async fn public_reads_stay_open() { |
| 205 | let ws = tempfile::tempdir().unwrap(); |
| 206 | let state = state_with(authed(), ws.path()); |
| 207 | for uri in ["/health", "/api/v1/health", "/api/v1/skills"] { |
| 208 | let (status, _) = send(&state, "GET", uri, &[], json!({})).await; |
| 209 | assert_eq!(status, StatusCode::OK, "{}", uri); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[tokio::test] |
| 214 | async fn correct_token_admits_catalogued_shell_only() { |
| 215 | let ws = tempfile::tempdir().unwrap(); |
| 216 | let state = state_with(authed(), ws.path()); |
| 217 | let (status, body) = send( |
| 218 | &state, |
| 219 | "POST", |
| 220 | "/api/v1/shell", |
| 221 | &bearer(TOKEN), |
| 222 | json!({"command": "ls"}), |
| 223 | ) |
| 224 | .await; |
| 225 | assert_eq!(status, StatusCode::OK); |
| 226 | // Either success or a probe refusal; never an allowlist refusal. |
| 227 | if body["success"] != true { |
| 228 | assert!( |
| 229 | body["stderr"].as_str().unwrap_or("").contains("probe"), |
| 230 | "{}", |
| 231 | body |
| 232 | ); |
| 233 | } |
| 234 | let alt = vec![("x-aegis-operator-token", TOKEN.to_string())]; |
| 235 | for cmd in [ |
| 236 | "rm -r -f /", |
| 237 | "find . -delete", |
| 238 | "curl http://example.invalid", |
| 239 | "ls; id", |
| 240 | "ls $(id)", |
| 241 | "git push", |
| 242 | "ls -la /", |
| 243 | ] { |
| 244 | let (status, body) = send( |
| 245 | &state, |
| 246 | "POST", |
| 247 | "/api/v1/shell", |
| 248 | &alt, |
| 249 | json!({ "command": cmd }), |
| 250 | ) |
| 251 | .await; |
| 252 | assert_eq!(status, StatusCode::OK); |
| 253 | assert_eq!(body["success"], false, "{:?} ran", cmd); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | #[tokio::test] |
| 258 | async fn skill_allowlist_holds_behind_the_token() { |
| 259 | let ws = tempfile::tempdir().unwrap(); |
| 260 | let state = state_with(authed(), ws.path()); |
| 261 | for name in ["exec", "shell", "Bash_eval", "bash_eval ", "spawn_process"] { |
| 262 | let (status, body) = send( |
| 263 | &state, |
| 264 | "POST", |
| 265 | "/api/v1/skills/execute", |
| 266 | &bearer(TOKEN), |
| 267 | json!({"skill_name": name, "arguments": {"command": "ls"}}), |
| 268 | ) |
| 269 | .await; |
| 270 | assert_eq!(status, StatusCode::OK); |
| 271 | assert_eq!(body["success"], false, "{:?} dispatched", name); |
| 272 | assert!( |
| 273 | body["error"].as_str().unwrap().contains("allowlist"), |
| 274 | "{}", |
| 275 | body |
| 276 | ); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | #[tokio::test] |
| 281 | async fn websocket_handshake_needs_the_token() { |
| 282 | let ws = tempfile::tempdir().unwrap(); |
| 283 | let state = state_with(authed(), ws.path()); |
| 284 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 285 | let port = listener.local_addr().unwrap().port(); |
| 286 | let app = create_router(state); |
| 287 | tokio::spawn(async move { |
| 288 | axum::serve(listener, app).await.unwrap(); |
| 289 | }); |
| 290 | let url = format!("ws://127.0.0.1:{}/ws", port); |
| 291 | let refused = tokio_tungstenite::connect_async(url.clone()).await; |
| 292 | assert!(refused.is_err(), "unauthenticated WebSocket was accepted"); |
| 293 | |
| 294 | use tokio_tungstenite::tungstenite::client::IntoClientRequest; |
| 295 | let mut req = url.into_client_request().unwrap(); |
| 296 | req.headers_mut().insert( |
| 297 | "authorization", |
| 298 | format!("Bearer {}", TOKEN).parse().unwrap(), |
| 299 | ); |
| 300 | assert!(tokio_tungstenite::connect_async(req).await.is_ok()); |
| 301 | } |
| 302 | |
| 303 | /// Runs `aegis serve ...` and expects it to exit on its own (refusal). |
| 304 | /// If it starts listening instead, it is killed and the test fails. |
| 305 | fn serve_must_refuse(args: &[&str], token: Option<&str>) -> String { |
| 306 | let dir = tempfile::tempdir().unwrap(); |
| 307 | let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_aegis")); |
| 308 | cmd.arg("serve") |
| 309 | .args(args) |
| 310 | .args(["--port", "0", "--inference", "http"]) |
| 311 | .current_dir(dir.path()) |
| 312 | .stdout(std::process::Stdio::piped()) |
| 313 | .stderr(std::process::Stdio::piped()); |
| 314 | match token { |
| 315 | Some(t) => cmd.env("AEGIS_OPERATOR_TOKEN", t), |
| 316 | None => cmd.env_remove("AEGIS_OPERATOR_TOKEN"), |
| 317 | }; |
| 318 | let mut child = cmd.spawn().unwrap(); |
| 319 | let deadline = Instant::now() + std::time::Duration::from_secs(30); |
| 320 | let status = loop { |
| 321 | if let Some(s) = child.try_wait().unwrap() { |
| 322 | break s; |
| 323 | } |
| 324 | if Instant::now() > deadline { |
| 325 | let _ = child.kill(); |
| 326 | panic!("aegis serve {:?} started instead of refusing", args); |
| 327 | } |
| 328 | std::thread::sleep(std::time::Duration::from_millis(50)); |
| 329 | }; |
| 330 | assert!(!status.success()); |
| 331 | let out = child.wait_with_output().unwrap(); |
| 332 | format!( |
| 333 | "{}{}", |
| 334 | String::from_utf8_lossy(&out.stdout), |
| 335 | String::from_utf8_lossy(&out.stderr) |
| 336 | ) |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn serve_refuses_non_loopback_bind_without_opt_in() { |
| 341 | for addr in ["0.0.0.0", "::", "192.0.2.10"] { |
| 342 | let text = serve_must_refuse(&["--bind", addr], None); |
| 343 | assert!(text.contains("non-loopback"), "{}: {}", addr, text); |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn serve_refuses_a_short_operator_token() { |
| 349 | let text = serve_must_refuse(&[], Some("short")); |
| 350 | assert!(text.contains("at least"), "{}", text); |
| 351 | } |
| 352 | |
| 353 | #[tokio::test] |
| 354 | async fn task_list_needs_the_operator_token() { |
| 355 | let ws = tempfile::tempdir().unwrap(); |
| 356 | let state = state_with(authed(), ws.path()); |
| 357 | let (status, _) = send(&state, "GET", "/api/v1/tasks", &[], json!({})).await; |
| 358 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 359 | let (status, _) = send( |
| 360 | &state, |
| 361 | "GET", |
| 362 | "/api/v1/tasks", |
| 363 | &bearer("wrong-token"), |
| 364 | json!({}), |
| 365 | ) |
| 366 | .await; |
| 367 | assert_eq!(status, StatusCode::UNAUTHORIZED); |
| 368 | let (status, _) = send(&state, "GET", "/api/v1/tasks", &bearer(TOKEN), json!({})).await; |
| 369 | assert_eq!(status, StatusCode::OK); |
| 370 | } |