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 / aien-serve-http / tests / bind_loopback.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 | //! The engine binary listens on 127.0.0.1 only (DRA-47). |
| 17 | //! |
| 18 | //! `tests/loopback.rs` checks `serve` in process. This file runs the real binary the way the |
| 19 | //! AienOS installer starts it (no `--bind`), with the stub engine and an empty model directory, |
| 20 | //! so no model is loaded and no GPU device is opened. It then checks the listening socket in the |
| 21 | //! kernel's own table, not only the address the binary prints. |
| 22 | //! |
| 23 | //! `AIEN_SERVE_HTTP_BIN` points the test at another build of the binary, for example the engine a |
| 24 | //! release ships; unset, it runs the binary cargo built for this test. |
| 25 | //! |
| 26 | //! Linux only: the listener and descriptor checks read `/proc`. |
| 27 | |
| 28 | #![cfg(target_os = "linux")] |
| 29 | |
| 30 | use std::collections::HashSet; |
| 31 | use std::io::{BufRead, BufReader}; |
| 32 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, TcpStream, UdpSocket}; |
| 33 | use std::path::PathBuf; |
| 34 | use std::process::{Child, Command, Stdio}; |
| 35 | use std::sync::atomic::{AtomicU32, Ordering}; |
| 36 | use std::sync::mpsc; |
| 37 | use std::time::Duration; |
| 38 | |
| 39 | const TOKEN: &str = "dra47-bind-test-token"; |
| 40 | |
| 41 | fn binary() -> PathBuf { |
| 42 | std::env::var_os("AIEN_SERVE_HTTP_BIN") |
| 43 | .map(PathBuf::from) |
| 44 | .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_aien-serve-http"))) |
| 45 | } |
| 46 | |
| 47 | fn empty_model_dir() -> PathBuf { |
| 48 | static N: AtomicU32 = AtomicU32::new(0); |
| 49 | let n = N.fetch_add(1, Ordering::Relaxed); |
| 50 | let dir = std::env::temp_dir().join(format!("dra47-bind-{}-{n}", std::process::id())); |
| 51 | std::fs::create_dir_all(&dir).unwrap(); |
| 52 | dir |
| 53 | } |
| 54 | |
| 55 | /// A running server; killed when dropped. |
| 56 | struct Server { |
| 57 | child: Child, |
| 58 | addr: SocketAddr, |
| 59 | } |
| 60 | |
| 61 | impl Drop for Server { |
| 62 | fn drop(&mut self) { |
| 63 | let _ = self.child.kill(); |
| 64 | let _ = self.child.wait(); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// How a start attempt ended: serving at an address, or exited with its stderr. |
| 69 | enum Start { |
| 70 | Serving(Server), |
| 71 | Exited { code: Option<i32>, stderr: String }, |
| 72 | } |
| 73 | |
| 74 | /// Starts the binary with the stub engine on an ephemeral port, plus `extra` flags. |
| 75 | /// The GPU is hidden from it as well (`CUDA_VISIBLE_DEVICES` empty, |
| 76 | /// `NVIDIA_VISIBLE_DEVICES=none`); the stub path never asks for it. |
| 77 | fn start(extra: &[&str]) -> Start { |
| 78 | let model_dir = empty_model_dir(); |
| 79 | let mut child = Command::new(binary()) |
| 80 | .args(["--engine", "stub", "--port", "0", "--model-dir"]) |
| 81 | .arg(&model_dir) |
| 82 | .args(extra) |
| 83 | .env("AIEN_SERVE_HTTP_BEARER_TOKEN", TOKEN) |
| 84 | .env("CUDA_VISIBLE_DEVICES", "") |
| 85 | .env("NVIDIA_VISIBLE_DEVICES", "none") |
| 86 | .stdin(Stdio::null()) |
| 87 | .stdout(Stdio::null()) |
| 88 | .stderr(Stdio::piped()) |
| 89 | .spawn() |
| 90 | .expect("spawn aien-serve-http"); |
| 91 | let stderr = child.stderr.take().unwrap(); |
| 92 | let (tx, rx) = mpsc::channel::<String>(); |
| 93 | std::thread::spawn(move || { |
| 94 | for line in BufReader::new(stderr).lines() { |
| 95 | let Ok(line) = line else { break }; |
| 96 | if tx.send(line).is_err() { |
| 97 | // Keep draining so the child never blocks on a full pipe. |
| 98 | continue; |
| 99 | } |
| 100 | } |
| 101 | }); |
| 102 | let mut seen = String::new(); |
| 103 | loop { |
| 104 | match rx.recv_timeout(Duration::from_secs(60)) { |
| 105 | Ok(line) => { |
| 106 | seen.push_str(&line); |
| 107 | seen.push('\n'); |
| 108 | if let Some(addr) = serving_addr(&line) { |
| 109 | return Start::Serving(Server { child, addr }); |
| 110 | } |
| 111 | } |
| 112 | Err(mpsc::RecvTimeoutError::Disconnected) => { |
| 113 | let status = child.wait().unwrap(); |
| 114 | return Start::Exited { |
| 115 | code: status.code(), |
| 116 | stderr: seen, |
| 117 | }; |
| 118 | } |
| 119 | Err(mpsc::RecvTimeoutError::Timeout) => { |
| 120 | let _ = child.kill(); |
| 121 | let _ = child.wait(); |
| 122 | panic!("no 'serving' line and no exit within 60 s; stderr so far:\n{seen}"); |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// `aien-serve-http: serving <model> at http://<addr>/v1 (engine stub)` -> `<addr>`. |
| 129 | fn serving_addr(line: &str) -> Option<SocketAddr> { |
| 130 | let rest = line.split(" serving ").nth(1)?; |
| 131 | let url = rest.split(" at http://").nth(1)?; |
| 132 | url.split("/v1").next()?.parse().ok() |
| 133 | } |
| 134 | |
| 135 | /// Socket inodes held by `pid`. |
| 136 | fn socket_inodes(pid: u32) -> HashSet<u64> { |
| 137 | let mut out = HashSet::new(); |
| 138 | for ent in std::fs::read_dir(format!("/proc/{pid}/fd")).unwrap() { |
| 139 | let Ok(target) = std::fs::read_link(ent.unwrap().path()) else { |
| 140 | continue; |
| 141 | }; |
| 142 | let t = target.to_string_lossy(); |
| 143 | if let Some(n) = t.strip_prefix("socket:[").and_then(|s| s.strip_suffix(']')) { |
| 144 | out.insert(n.parse().unwrap()); |
| 145 | } |
| 146 | } |
| 147 | out |
| 148 | } |
| 149 | |
| 150 | /// One `/proc/net/tcp{,6}` address (`0100007F` or 32 hex digits) as the address it names. |
| 151 | /// The kernel prints each 32-bit word in host byte order, so the native-endian bytes of the |
| 152 | /// parsed word are the address bytes. |
| 153 | fn proc_ip(hex: &str) -> IpAddr { |
| 154 | let word = |h: &str| u32::from_str_radix(h, 16).unwrap().to_ne_bytes(); |
| 155 | match hex.len() { |
| 156 | 8 => IpAddr::V4(Ipv4Addr::from(word(hex))), |
| 157 | 32 => { |
| 158 | let mut b = [0u8; 16]; |
| 159 | for i in 0..4 { |
| 160 | b[i * 4..i * 4 + 4].copy_from_slice(&word(&hex[i * 8..i * 8 + 8])); |
| 161 | } |
| 162 | IpAddr::V6(Ipv6Addr::from(b)) |
| 163 | } |
| 164 | n => panic!("unexpected address width {n} in /proc/net/tcp: {hex}"), |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | fn is_loopback(ip: IpAddr) -> bool { |
| 169 | match ip { |
| 170 | IpAddr::V4(v4) => v4.is_loopback(), |
| 171 | IpAddr::V6(v6) => { |
| 172 | v6.is_loopback() || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()) |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | /// Every listening TCP socket the process holds, as `(local ip, port)`, read from the kernel's |
| 178 | /// table in the process's network namespace. |
| 179 | fn listeners(pid: u32) -> Vec<(IpAddr, u16)> { |
| 180 | let mine = socket_inodes(pid); |
| 181 | let mut out = Vec::new(); |
| 182 | for table in ["tcp", "tcp6"] { |
| 183 | let Ok(text) = std::fs::read_to_string(format!("/proc/{pid}/net/{table}")) else { |
| 184 | continue; |
| 185 | }; |
| 186 | for row in text.lines().skip(1) { |
| 187 | let f: Vec<&str> = row.split_whitespace().collect(); |
| 188 | // sl local rem st tx:rx tr:when retrnsmt uid timeout inode |
| 189 | if f.len() < 10 || f[3] != "0A" { |
| 190 | continue; |
| 191 | } |
| 192 | let inode: u64 = f[9].parse().unwrap(); |
| 193 | if !mine.contains(&inode) { |
| 194 | continue; |
| 195 | } |
| 196 | let (ip, port) = f[1].split_once(':').unwrap(); |
| 197 | out.push((proc_ip(ip), u16::from_str_radix(port, 16).unwrap())); |
| 198 | } |
| 199 | } |
| 200 | out |
| 201 | } |
| 202 | |
| 203 | /// A non-loopback IPv4 address of this host, if it has one: the source address the kernel |
| 204 | /// would pick to reach TEST-NET-1. A UDP connect sends no packet. |
| 205 | fn host_non_loopback_ipv4() -> Option<Ipv4Addr> { |
| 206 | let s = UdpSocket::bind("0.0.0.0:0").ok()?; |
| 207 | s.connect("192.0.2.1:9").ok()?; |
| 208 | match s.local_addr().ok()?.ip() { |
| 209 | IpAddr::V4(v4) if !v4.is_loopback() && !v4.is_unspecified() => Some(v4), |
| 210 | _ => None, |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | /// No NVIDIA device descriptor open and no CUDA driver library mapped. |
| 215 | fn assert_no_gpu(pid: u32) { |
| 216 | for ent in std::fs::read_dir(format!("/proc/{pid}/fd")).unwrap() { |
| 217 | if let Ok(target) = std::fs::read_link(ent.unwrap().path()) { |
| 218 | let t = target.to_string_lossy(); |
| 219 | assert!(!t.starts_with("/dev/nvidia"), "stub server holds {t}"); |
| 220 | } |
| 221 | } |
| 222 | let maps = std::fs::read_to_string(format!("/proc/{pid}/maps")).unwrap(); |
| 223 | for line in maps.lines() { |
| 224 | assert!( |
| 225 | !line.contains("libcuda") && !line.contains("/dev/nvidia"), |
| 226 | "stub server maps {line}" |
| 227 | ); |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | #[test] |
| 232 | fn default_start_listens_on_ipv4_loopback_only() { |
| 233 | let server = match start(&[]) { |
| 234 | Start::Serving(s) => s, |
| 235 | Start::Exited { code, stderr } => { |
| 236 | panic!("server did not start (exit {code:?}):\n{stderr}") |
| 237 | } |
| 238 | }; |
| 239 | let pid = server.child.id(); |
| 240 | assert_eq!( |
| 241 | server.addr.ip(), |
| 242 | IpAddr::V4(Ipv4Addr::LOCALHOST), |
| 243 | "the binary reports serving at {}", |
| 244 | server.addr |
| 245 | ); |
| 246 | let found = listeners(pid); |
| 247 | assert!( |
| 248 | found.iter().any(|&(_, p)| p == server.addr.port()), |
| 249 | "no listening socket for port {} in /proc/{pid}/net: {found:?}", |
| 250 | server.addr.port() |
| 251 | ); |
| 252 | for (ip, port) in &found { |
| 253 | assert!( |
| 254 | is_loopback(*ip), |
| 255 | "listening on {ip}:{port}, which is not loopback" |
| 256 | ); |
| 257 | } |
| 258 | assert!(TcpStream::connect_timeout(&server.addr, Duration::from_secs(5)).is_ok()); |
| 259 | match host_non_loopback_ipv4() { |
| 260 | Some(ip) => { |
| 261 | let outside = SocketAddr::new(IpAddr::V4(ip), server.addr.port()); |
| 262 | assert!( |
| 263 | TcpStream::connect_timeout(&outside, Duration::from_secs(2)).is_err(), |
| 264 | "the server accepted a connection on the host address {outside}" |
| 265 | ); |
| 266 | } |
| 267 | None => eprintln!( |
| 268 | "no non-loopback IPv4 route on this host; the outside connect check is skipped" |
| 269 | ), |
| 270 | } |
| 271 | assert_no_gpu(pid); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn wildcard_and_outside_binds_are_refused_before_listening() { |
| 276 | for addr in ["0.0.0.0", "::", "192.0.2.1"] { |
| 277 | match start(&["--bind", addr]) { |
| 278 | Start::Serving(s) => panic!("--bind {addr} was accepted: serving at {}", s.addr), |
| 279 | Start::Exited { code, stderr } => { |
| 280 | assert_ne!(code, Some(0), "--bind {addr} exited 0:\n{stderr}"); |
| 281 | assert!( |
| 282 | stderr.contains("loopback"), |
| 283 | "--bind {addr} failed without the loopback refusal:\n{stderr}" |
| 284 | ); |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn listener_table_reader_tells_loopback_from_wildcard() { |
| 292 | // Fixed rows in the kernel's format (little-endian host words), so the reader itself has a |
| 293 | // negative control: a wildcard listener must not read as loopback. |
| 294 | if cfg!(target_endian = "little") { |
| 295 | assert_eq!(proc_ip("0100007F"), IpAddr::V4(Ipv4Addr::LOCALHOST)); |
| 296 | assert_eq!(proc_ip("00000000"), IpAddr::V4(Ipv4Addr::UNSPECIFIED)); |
| 297 | assert_eq!( |
| 298 | proc_ip("00000000000000000000000001000000"), |
| 299 | IpAddr::V6(Ipv6Addr::LOCALHOST) |
| 300 | ); |
| 301 | assert_eq!( |
| 302 | proc_ip("0000000000000000FFFF00000100007F"), |
| 303 | IpAddr::V6(Ipv4Addr::LOCALHOST.to_ipv6_mapped()) |
| 304 | ); |
| 305 | } |
| 306 | assert!(is_loopback(IpAddr::V4(Ipv4Addr::LOCALHOST))); |
| 307 | assert!(is_loopback(IpAddr::V6( |
| 308 | Ipv4Addr::LOCALHOST.to_ipv6_mapped() |
| 309 | ))); |
| 310 | assert!(!is_loopback(IpAddr::V4(Ipv4Addr::UNSPECIFIED))); |
| 311 | assert!(!is_loopback(IpAddr::V6(Ipv6Addr::UNSPECIFIED))); |
| 312 | assert!(!is_loopback(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)))); |
| 313 | } |