tests.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //! Web module tests: bus semantics, token gate, and a full server boot on an
  2. //! ephemeral port with a fake (unreachable) node.
  3. use crate::config::{Cluster, Config, Node};
  4. use crate::web::events::{Event, build_snapshot};
  5. use crate::web::{AppState, router};
  6. use std::collections::HashMap;
  7. use std::net::SocketAddr;
  8. pub(crate) async fn call(addr: SocketAddr, path: &str) -> reqwest::Response {
  9. reqwest::Client::new()
  10. .get(format!("http://{addr}{path}"))
  11. .send()
  12. .await
  13. .unwrap()
  14. }
  15. /// Config with one node at 127.0.0.1:2222 — connection refused instantly,
  16. /// machine-independent (no real SSH, no hardware).
  17. pub(crate) fn fake_config() -> Config {
  18. Config {
  19. ssh_user: "u".into(),
  20. ssh_key_path: "/nonexistent/key".into(),
  21. clusters: vec![Cluster {
  22. name: "fake".into(),
  23. master_ib_ip: None,
  24. nodes: vec![Node {
  25. name: "n0".into(),
  26. ssh_ip: "127.0.0.1:2222".into(),
  27. ib_ip: None,
  28. rank: 0,
  29. host_key: None,
  30. entity: None,
  31. }],
  32. extra_entities: vec![],
  33. }],
  34. nccl: HashMap::new(),
  35. hf_cache_dir: None,
  36. init_port: 25000,
  37. before_serve: HashMap::new(),
  38. exec_aliases: HashMap::new(),
  39. home_assistant: None,
  40. mikrotik: None,
  41. global_mods_dir: None,
  42. drop_caches: true,
  43. mount_aliases: HashMap::new(),
  44. recipe_sources: Vec::new(),
  45. docker_image_sources: Vec::new(),
  46. cluster_sources: Vec::new(),
  47. registry: None,
  48. }
  49. }
  50. pub(crate) fn app_state(token: Option<&str>) -> AppState {
  51. app_state_with(fake_config(), token)
  52. }
  53. fn app_state_with(config: Config, token: Option<&str>) -> AppState {
  54. let (tx, _) = tokio::sync::broadcast::channel(16);
  55. AppState {
  56. config: std::sync::Arc::new(config),
  57. bus: tx,
  58. token: token.map(String::from),
  59. last: std::sync::Arc::new(std::sync::Mutex::new(None)),
  60. jobs: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
  61. log_attaches: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
  62. }
  63. }
  64. pub(crate) async fn boot() -> (SocketAddr, std::sync::Arc<tokio::task::JoinHandle<()>>) {
  65. boot_with(fake_config()).await
  66. }
  67. async fn boot_with(config: Config) -> (SocketAddr, std::sync::Arc<tokio::task::JoinHandle<()>>) {
  68. boot_app(app_state_with(config, None)).await
  69. }
  70. async fn boot_app(app: AppState) -> (SocketAddr, std::sync::Arc<tokio::task::JoinHandle<()>>) {
  71. let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
  72. let addr = listener.local_addr().unwrap();
  73. let handle = tokio::spawn(async move {
  74. axum::serve(listener, router(app)).await.unwrap();
  75. });
  76. (addr, std::sync::Arc::new(handle))
  77. }
  78. #[tokio::test]
  79. async fn api_state_reports_unreachable_node() {
  80. let (addr, handle) = boot().await;
  81. let body: serde_json::Value = reqwest::get(format!("http://{addr}/api/state"))
  82. .await
  83. .unwrap()
  84. .json()
  85. .await
  86. .unwrap();
  87. assert_eq!(body["clusters"].as_array().unwrap().len(), 1);
  88. assert_eq!(body["clusters"][0]["name"], "fake");
  89. assert_eq!(body["clusters"][0]["nodes"][0]["reachable"], false);
  90. assert_eq!(body["clusters"][0]["free"], 0);
  91. handle.abort();
  92. }
  93. /// The recipes panel is mounted under /recipes: the page, its own SSE
  94. /// stream and the /r/ viewer all live behind the prefix.
  95. #[tokio::test]
  96. async fn recipes_panel_is_mounted_under_prefix() {
  97. let (addr, handle) = boot().await;
  98. let page = reqwest::get(format!("http://{addr}/recipes"))
  99. .await
  100. .unwrap()
  101. .text()
  102. .await
  103. .unwrap();
  104. // its own live stream resolves behind the prefix (headers arrive at once)
  105. let sse = reqwest::get(format!("http://{addr}/recipes/events"))
  106. .await
  107. .unwrap();
  108. assert_eq!(sse.status(), 200);
  109. assert!(
  110. page.contains("auth(\"/recipes/events\")"),
  111. "prefix not applied"
  112. );
  113. assert!(!page.contains("auth(\"/events\")"));
  114. // the dashboard's own routes still resolve
  115. let ui = reqwest::get(format!("http://{addr}/"))
  116. .await
  117. .unwrap()
  118. .text()
  119. .await
  120. .unwrap();
  121. assert!(ui.contains("recwin") || ui.contains("Recipes"));
  122. handle.abort();
  123. }
  124. #[tokio::test]
  125. async fn token_gate_enforces_when_set() {
  126. let app = app_state(Some("s3cret"));
  127. let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
  128. let addr = listener.local_addr().unwrap();
  129. tokio::spawn(async move {
  130. axum::serve(listener, router(app)).await.unwrap();
  131. });
  132. let base = format!("http://{addr}/api/state");
  133. // No token → 401.
  134. assert_eq!(reqwest::get(&base).await.unwrap().status(), 401);
  135. // Wrong token → 401.
  136. assert_eq!(
  137. reqwest::get(format!("{base}?token=wrong"))
  138. .await
  139. .unwrap()
  140. .status(),
  141. 401
  142. );
  143. // Right token (query form — what SSE clients use) → 200.
  144. assert_eq!(
  145. reqwest::get(format!("{base}?token=s3cret"))
  146. .await
  147. .unwrap()
  148. .status(),
  149. 200
  150. );
  151. }
  152. #[tokio::test]
  153. async fn sse_replays_cached_snapshot_on_connect() {
  154. use tokio::io::{AsyncReadExt, AsyncWriteExt};
  155. // Nothing is broadcast after this point: the frame must come from the
  156. // cached snapshot, otherwise a fresh client waits a whole poll tick.
  157. let app = app_state(None);
  158. *app.last.lock().unwrap() = Some(crate::web::events::Snapshot {
  159. ts: 1,
  160. clusters: Vec::new(),
  161. jobs: Vec::new(),
  162. topo: Default::default(),
  163. attaches: Vec::new(),
  164. });
  165. let (addr, handle) = boot_app(app).await;
  166. let mut sock = tokio::net::TcpStream::connect(addr).await.unwrap();
  167. sock.write_all(b"GET /events HTTP/1.1\r\nHost: x\r\n\r\n")
  168. .await
  169. .unwrap();
  170. let mut buf = vec![0u8; 4096];
  171. let n = sock.read(&mut buf).await.unwrap();
  172. let text = String::from_utf8_lossy(&buf[..n]);
  173. assert!(
  174. text.contains("\"type\":\"state\""),
  175. "no replayed frame: {text}"
  176. );
  177. handle.abort();
  178. }
  179. #[tokio::test]
  180. async fn bus_delivers_state_events() {
  181. let (tx, mut rx) = tokio::sync::broadcast::channel::<Event>(8);
  182. let snap = crate::web::events::Snapshot {
  183. ts: 1,
  184. clusters: Vec::new(),
  185. jobs: Vec::new(),
  186. topo: Default::default(),
  187. attaches: Vec::new(),
  188. };
  189. tx.send(Event::State {
  190. ts: snap.ts,
  191. snapshot: snap.clone(),
  192. })
  193. .unwrap();
  194. let got = rx.recv().await.unwrap();
  195. match got {
  196. Event::State { ts, snapshot } => {
  197. assert_eq!(ts, 1);
  198. assert!(snapshot.clusters.is_empty());
  199. }
  200. Event::Job { .. } => panic!("unexpected job event"),
  201. Event::Log { .. } => panic!("unexpected log event"),
  202. }
  203. }
  204. #[tokio::test]
  205. async fn snapshot_serializes_with_type_tag() {
  206. let ev = Event::State {
  207. ts: 7,
  208. snapshot: build_snapshot(
  209. &fake_config(),
  210. &crate::web::probe::Fleet {
  211. nodes: std::collections::HashMap::new(),
  212. switch_off: std::collections::HashMap::new(),
  213. soft_off: std::collections::HashMap::new(),
  214. ha: std::collections::HashMap::new(),
  215. },
  216. &[],
  217. &[],
  218. &std::collections::HashMap::new(),
  219. ),
  220. };
  221. let json = serde_json::to_value(&ev).unwrap();
  222. assert_eq!(json["type"], "state");
  223. assert_eq!(json["ts"], 7);
  224. assert!(json["snapshot"].is_object());
  225. }
  226. // (P2/P3/P4 API round-trip tests moved to api_tests.rs — 500-line cap)
  227. /// Click-through UI tests: boots the real server on an ephemeral port and
  228. /// drives the embedded ui.html with Playwright (deno, npm-free).
  229. /// Skipped when deno or the chromium binary is unavailable.
  230. #[tokio::test]
  231. async fn ui_playwright_checks() {
  232. if std::process::Command::new("deno")
  233. .arg("--version")
  234. .output()
  235. .is_err()
  236. {
  237. eprintln!("SKIP ui_playwright_checks: deno not available");
  238. return;
  239. }
  240. let (addr, _h) = boot_with(playwright_config()).await;
  241. // tokio::process (not std::process::output — that would block this
  242. // runtime's only thread while the axum server runs on it → deadlock).
  243. let out = tokio::process::Command::new("deno")
  244. .arg("run")
  245. .arg("-A")
  246. .arg("src/web/ui.playwright.mjs")
  247. .env("SM121_WEB_URL", format!("http://{addr}"))
  248. .output()
  249. .await
  250. .unwrap();
  251. let stdout = String::from_utf8_lossy(&out.stdout);
  252. let stderr = String::from_utf8_lossy(&out.stderr);
  253. if stdout.contains("SKIP") {
  254. eprintln!("SKIP ui_playwright_checks:\n{stdout}");
  255. return;
  256. }
  257. assert!(
  258. out.status.success(),
  259. "playwright UI checks failed:\n{stdout}\n{stderr}"
  260. );
  261. eprintln!("{stdout}");
  262. }
  263. /// Two offline clusters (both nodes on refused loopback ports) — the
  264. /// fleet the Playwright UI checks render: chip strip with two chips,
  265. /// down-cluster action bar, type-the-name power flow.
  266. fn playwright_config() -> Config {
  267. let mut cfg = fake_config();
  268. cfg.clusters.push(Cluster {
  269. name: "fake2".into(),
  270. master_ib_ip: None,
  271. nodes: vec![Node {
  272. name: "n1".into(),
  273. ssh_ip: "127.0.0.1:2223".into(),
  274. ib_ip: None,
  275. rank: 0,
  276. host_key: None,
  277. entity: None,
  278. }],
  279. extra_entities: vec![],
  280. });
  281. cfg
  282. }