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 / src / auth.rs
| 1 | //! Operator authentication and listen-address policy for the gateway. |
| 2 | //! |
| 3 | //! - The gateway listens on 127.0.0.1 unless the operator passes an explicit |
| 4 | //! opt-in flag for any other address. |
| 5 | //! - Every route is protected by default. Only a short list of read-only |
| 6 | //! `GET`/`HEAD` routes is public. Everything else (all `POST` routes and the |
| 7 | //! WebSocket, which can run shell and skills) needs the operator token in |
| 8 | //! `Authorization: Bearer <token>` or `X-Aegis-Operator-Token: <token>`. |
| 9 | //! - With no token configured, protected routes refuse every request. |
| 10 | //! - There is no bypass: no loopback exemption, no debug flag, no query param. |
| 11 | |
| 12 | use axum::{ |
| 13 | extract::{Request, State}, |
| 14 | http::{header, HeaderMap, Method, StatusCode}, |
| 15 | middleware::Next, |
| 16 | response::{IntoResponse, Response}, |
| 17 | Json, |
| 18 | }; |
| 19 | use std::net::{IpAddr, SocketAddr}; |
| 20 | use std::path::Path; |
| 21 | use std::sync::Arc; |
| 22 | |
| 23 | /// Environment variable holding the operator token. |
| 24 | pub const OPERATOR_TOKEN_ENV: &str = "AEGIS_OPERATOR_TOKEN"; |
| 25 | /// Alternate header carrying the operator token. |
| 26 | pub const OPERATOR_TOKEN_HEADER: &str = "x-aegis-operator-token"; |
| 27 | /// Shortest token accepted. |
| 28 | pub const MIN_TOKEN_LEN: usize = 32; |
| 29 | |
| 30 | /// Read-only routes that stay open without a token (GET/HEAD only). |
| 31 | pub const PUBLIC_READ_PATHS: &[&str] = &[ |
| 32 | "/health", |
| 33 | "/api/v1/health", |
| 34 | "/v1/models", |
| 35 | "/api/v1/skills", |
| 36 | "/api/v1/events", |
| 37 | "/events", |
| 38 | ]; |
| 39 | |
| 40 | #[derive(Clone, Default)] |
| 41 | pub struct OperatorAuth { |
| 42 | token: Option<Arc<str>>, |
| 43 | } |
| 44 | |
| 45 | impl std::fmt::Debug for OperatorAuth { |
| 46 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 47 | f.debug_struct("OperatorAuth") |
| 48 | .field("configured", &self.token.is_some()) |
| 49 | .finish() |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | impl OperatorAuth { |
| 54 | /// No token: every protected route is refused. |
| 55 | pub fn disabled() -> Self { |
| 56 | Self { token: None } |
| 57 | } |
| 58 | |
| 59 | pub fn with_token(token: &str) -> Result<Self, String> { |
| 60 | let t = token.trim(); |
| 61 | if t.len() < MIN_TOKEN_LEN { |
| 62 | return Err(format!( |
| 63 | "operator token must be at least {} characters", |
| 64 | MIN_TOKEN_LEN |
| 65 | )); |
| 66 | } |
| 67 | if !t.chars().all(|c| c.is_ascii_graphic()) { |
| 68 | return Err("operator token must be printable ASCII without spaces".to_string()); |
| 69 | } |
| 70 | Ok(Self { |
| 71 | token: Some(Arc::from(t)), |
| 72 | }) |
| 73 | } |
| 74 | |
| 75 | /// Token from a file (if given) or from `AEGIS_OPERATOR_TOKEN`. |
| 76 | pub fn load(token_file: Option<&Path>) -> Result<Self, String> { |
| 77 | if let Some(p) = token_file { |
| 78 | let raw = std::fs::read_to_string(p) |
| 79 | .map_err(|e| format!("cannot read operator token file {}: {}", p.display(), e))?; |
| 80 | return Self::with_token(&raw); |
| 81 | } |
| 82 | match std::env::var(OPERATOR_TOKEN_ENV) { |
| 83 | Ok(v) if !v.trim().is_empty() => Self::with_token(&v), |
| 84 | _ => Ok(Self::disabled()), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub fn is_configured(&self) -> bool { |
| 89 | self.token.is_some() |
| 90 | } |
| 91 | |
| 92 | /// True only when a token is configured and the presented one matches. |
| 93 | pub fn verify(&self, presented: Option<&str>) -> bool { |
| 94 | match (&self.token, presented) { |
| 95 | (Some(expected), Some(got)) => constant_time_eq(expected.as_bytes(), got.as_bytes()), |
| 96 | _ => false, |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Comparison whose time does not depend on where the first mismatch is. |
| 102 | /// (Only the length is observable, and the length is not secret.) |
| 103 | pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { |
| 104 | if a.len() != b.len() { |
| 105 | return false; |
| 106 | } |
| 107 | a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 |
| 108 | } |
| 109 | |
| 110 | /// The token a request presents, if any. |
| 111 | pub fn presented_token(headers: &HeaderMap) -> Option<&str> { |
| 112 | if let Some(v) = headers |
| 113 | .get(header::AUTHORIZATION) |
| 114 | .and_then(|v| v.to_str().ok()) |
| 115 | { |
| 116 | if let Some(rest) = v.strip_prefix("Bearer ") { |
| 117 | return Some(rest.trim()); |
| 118 | } |
| 119 | } |
| 120 | headers |
| 121 | .get(OPERATOR_TOKEN_HEADER) |
| 122 | .and_then(|v| v.to_str().ok()) |
| 123 | .map(str::trim) |
| 124 | } |
| 125 | |
| 126 | /// Public means: read-only method AND an exact path on the public list. |
| 127 | pub fn is_public(method: &Method, path: &str) -> bool { |
| 128 | (*method == Method::GET || *method == Method::HEAD) && PUBLIC_READ_PATHS.contains(&path) |
| 129 | } |
| 130 | |
| 131 | /// Middleware: deny by default, allow the public list, else require the token. |
| 132 | pub async fn require_operator( |
| 133 | State(auth): State<OperatorAuth>, |
| 134 | req: Request, |
| 135 | next: Next, |
| 136 | ) -> Response { |
| 137 | if is_public(req.method(), req.uri().path()) { |
| 138 | return next.run(req).await; |
| 139 | } |
| 140 | if !auth.is_configured() { |
| 141 | return ( |
| 142 | StatusCode::SERVICE_UNAVAILABLE, |
| 143 | Json(serde_json::json!({ |
| 144 | "error": "operator token not configured; protected routes are disabled", |
| 145 | })), |
| 146 | ) |
| 147 | .into_response(); |
| 148 | } |
| 149 | if auth.verify(presented_token(req.headers())) { |
| 150 | return next.run(req).await; |
| 151 | } |
| 152 | ( |
| 153 | StatusCode::UNAUTHORIZED, |
| 154 | [(header::WWW_AUTHENTICATE, "Bearer")], |
| 155 | Json(serde_json::json!({ "error": "operator token required" })), |
| 156 | ) |
| 157 | .into_response() |
| 158 | } |
| 159 | |
| 160 | /// Listen address. Loopback unless the operator explicitly opts in. |
| 161 | pub fn resolve_bind_addr( |
| 162 | host: &str, |
| 163 | port: u16, |
| 164 | allow_non_loopback: bool, |
| 165 | ) -> Result<SocketAddr, String> { |
| 166 | let ip: IpAddr = host |
| 167 | .trim() |
| 168 | .parse() |
| 169 | .map_err(|_| format!("bind address {:?} is not an IP address", host))?; |
| 170 | if !ip.is_loopback() && !allow_non_loopback { |
| 171 | return Err(format!( |
| 172 | "refusing to listen on non-loopback address {}; pass --allow-non-loopback-bind to opt in", |
| 173 | ip |
| 174 | )); |
| 175 | } |
| 176 | Ok(SocketAddr::new(ip, port)) |
| 177 | } |
| 178 | |
| 179 | #[cfg(test)] |
| 180 | mod tests { |
| 181 | use super::*; |
| 182 | |
| 183 | const TOKEN: &str = "0123456789abcdef0123456789abcdef"; |
| 184 | |
| 185 | #[test] |
| 186 | fn bind_defaults_to_loopback_only() { |
| 187 | assert!(resolve_bind_addr("127.0.0.1", 1, false).is_ok()); |
| 188 | assert!(resolve_bind_addr("::1", 1, false).is_ok()); |
| 189 | assert!(resolve_bind_addr("0.0.0.0", 1, false).is_err()); |
| 190 | assert!(resolve_bind_addr("::", 1, false).is_err()); |
| 191 | assert!(resolve_bind_addr("192.0.2.10", 1, false).is_err()); |
| 192 | assert!(resolve_bind_addr("localhost", 1, false).is_err()); |
| 193 | assert!(resolve_bind_addr("0.0.0.0", 1, true).is_ok()); |
| 194 | } |
| 195 | |
| 196 | #[test] |
| 197 | fn token_rules() { |
| 198 | assert!(OperatorAuth::with_token("short").is_err()); |
| 199 | assert!(OperatorAuth::with_token(&format!("{} x", TOKEN)).is_err()); |
| 200 | let a = OperatorAuth::with_token(TOKEN).unwrap(); |
| 201 | assert!(a.verify(Some(TOKEN))); |
| 202 | assert!(!a.verify(None)); |
| 203 | assert!(!a.verify(Some(""))); |
| 204 | assert!(!a.verify(Some(&TOKEN[..31]))); |
| 205 | assert!(!a.verify(Some(&format!("{}0", TOKEN)))); |
| 206 | assert!(!a.verify(Some(&TOKEN.to_uppercase()))); |
| 207 | assert!(!OperatorAuth::disabled().verify(Some(TOKEN))); |
| 208 | assert!(!OperatorAuth::disabled().verify(Some(""))); |
| 209 | } |
| 210 | |
| 211 | #[test] |
| 212 | fn only_listed_reads_are_public() { |
| 213 | assert!(is_public(&Method::GET, "/health")); |
| 214 | assert!(!is_public(&Method::POST, "/health")); |
| 215 | assert!(!is_public(&Method::POST, "/api/v1/tasks")); |
| 216 | // Task records carry payloads and results (command text and output). |
| 217 | assert!(!is_public(&Method::GET, "/api/v1/tasks")); |
| 218 | assert!(!is_public(&Method::GET, "/ws")); |
| 219 | assert!(!is_public(&Method::GET, "/api/v1/ws")); |
| 220 | assert!(!is_public(&Method::GET, "/health/")); |
| 221 | assert!(!is_public(&Method::GET, "/HEALTH")); |
| 222 | assert!(!is_public(&Method::OPTIONS, "/api/v1/shell")); |
| 223 | } |
| 224 | } |