//! REST API: authentication, roles, record management with ETags, zone lifecycle, reload. #![allow(clippy::unwrap_used, clippy::expect_used)] use std::io::{Read, Write}; use std::net::SocketAddr; use std::sync::Arc; use serde_json::{Value, json}; fn http(addr: SocketAddr, method: &str, path: &str, token: Option<&str>, body: Option, extra: &str) -> (u16, Value, String) { let mut s = std::net::TcpStream::connect(addr).unwrap(); let body = body.map(|b| b.to_string()).unwrap_or_default(); let mut req = format!("{method} {path} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n{extra}"); if let Some(t) = token { req.push_str(&format!("Authorization: Bearer {t}\r\n")); } req.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", body.len())); s.write_all(req.as_bytes()).unwrap(); let mut buf = Vec::new(); s.read_to_end(&mut buf).unwrap(); let text = String::from_utf8_lossy(&buf).to_string(); let status = text.split_whitespace().nth(1).unwrap().parse().unwrap(); let (head, body) = text.split_once("\r\n\r\n").unwrap(); // axum may use chunked encoding let body = if head.to_ascii_lowercase().contains("transfer-encoding: chunked") { let mut out = String::new(); let mut rest = body; while let Some((size, tail)) = rest.split_once("\r\n") { let n = usize::from_str_radix(size.trim(), 16).unwrap_or(0); if n == 0 { break; } out.push_str(&tail[..n]); rest = &tail[n + 2..]; } out } else { body.to_string() }; (status, serde_json::from_str(&body).unwrap_or(Value::Null), head.to_string()) } #[tokio::test(flavor = "multi_thread")] async fn api_end_to_end() { let dir = std::env::temp_dir().join(format!("easydns-api-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("z.zone"), "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 127.0.0.1\n").unwrap(); std::fs::write(dir.join("admin.token"), "admin-secret").unwrap(); let ro_hash = dns_api::hash_token("reader-secret"); let yaml = format!( r#" server: {{ listen: ["127.0.0.1:0"], data_dir: data }} api: {{ listen: "127.0.0.1:0", tokens: [ {{ name: admin, role: admin, token: "file:admin.token" }}, {{ name: ro, role: read-only, token: "sha256:{ro_hash}" }} ] }} zones: [ {{ name: example.test, type: primary, file: z.zone }} ] "# ); std::fs::write(dir.join("config.yaml"), &yaml).unwrap(); let cfg = dns_config::Config::load(&dir.join("config.yaml")).unwrap(); let auth = dns_api::Auth::from_config(&cfg).unwrap(); let server = Arc::new(dns_server::Server::start(cfg.clone(), Some(dir.join("config.yaml")), Default::default()).await.unwrap()); let st = Arc::new(dns_api::ApiState { server: Arc::clone(&server), auth }); let api = dns_api::serve_api(st, cfg.api.listen, server.shutdown_signal()).await.unwrap(); let a = |m: &'static str, p: String, t: Option<&'static str>, b: Option, e: &'static str| { let p = p.clone(); tokio::task::spawn_blocking(move || http(api, m, &p, t, b, e)) }; // health is public, everything else needs a token assert_eq!(a("GET", "/healthz".into(), None, None, "").await.unwrap().0, 200); assert_eq!(a("GET", "/api/v1/zones".into(), None, None, "").await.unwrap().0, 401); assert_eq!(a("GET", "/api/v1/zones".into(), Some("wrong"), None, "").await.unwrap().0, 401); let (s, v, _) = a("GET", "/api/v1/zones".into(), Some("reader-secret"), None, "").await.unwrap(); assert_eq!((s, v["pagination"]["total"].as_u64()), (200, Some(1))); // read-only cannot modify let rec = json!({"name": "www", "type": "A", "ttl": 120, "data": "192.0.2.5"}); assert_eq!(a("POST", "/api/v1/zones/example.test/records".into(), Some("reader-secret"), Some(rec.clone()), "").await.unwrap().0, 403); // admin adds a record; ETag = serial let (s, v, head) = a("POST", "/api/v1/zones/example.test/records".into(), Some("admin-secret"), Some(rec), "").await.unwrap(); assert_eq!(s, 201, "{v}"); assert!(head.contains("etag: \"2\"") || head.contains("ETag: \"2\""), "{head}"); let id = v["records"][0]["id"].as_str().unwrap().to_string(); // the DNS listener serves it let m = dns_core::client::query( server.bound.dns[0], &"www.example.test.".parse().unwrap(), dns_core::proto::rr::RecordType::A, &Default::default(), ) .await .unwrap(); assert_eq!(m.message.answers.len(), 1); // stale If-Match is rejected let upd = json!({"name": "www", "type": "A", "ttl": 120, "data": "192.0.2.6"}); assert_eq!( a("PUT", format!("/api/v1/zones/example.test/records/{id}"), Some("admin-secret"), Some(upd.clone()), "If-Match: \"1\"\r\n") .await .unwrap() .0, 412 ); let (s, v, _) = a("PUT", format!("/api/v1/zones/example.test/records/{id}"), Some("admin-secret"), Some(upd), "If-Match: \"2\"\r\n").await.unwrap(); assert_eq!((s, v["serial"].as_u64()), (200, Some(3))); // invalid data let bad = json!({"name": "x", "type": "A", "data": "not-an-ip"}); assert_eq!(a("POST", "/api/v1/zones/example.test/records".into(), Some("admin-secret"), Some(bad), "").await.unwrap().0, 400); // list with filter + pagination let (_, v, _) = a("GET", "/api/v1/zones/example.test/records?type=A&per_page=1".into(), Some("reader-secret"), None, "").await.unwrap(); assert_eq!(v["items"].as_array().unwrap().len(), 1); // create + delete an API zone let (s, _, _) = a("POST", "/api/v1/zones".into(), Some("admin-secret"), Some(json!({"name": "new.test", "ns": ["ns1.example.test."]})), "") .await .unwrap(); assert_eq!(s, 201); assert_eq!(a("GET", "/api/v1/zones/new.test".into(), Some("reader-secret"), None, "").await.unwrap().0, 200); assert_eq!(a("DELETE", "/api/v1/zones/example.test".into(), Some("admin-secret"), None, "").await.unwrap().0, 409); assert_eq!(a("DELETE", "/api/v1/zones/new.test".into(), Some("admin-secret"), None, "").await.unwrap().0, 204); assert_eq!(a("GET", "/api/v1/zones/new.test".into(), Some("reader-secret"), None, "").await.unwrap().0, 404); // reload, cache, stats, audit, openapi assert_eq!(a("POST", "/api/v1/config/reload".into(), Some("admin-secret"), None, "").await.unwrap().0, 200); assert_eq!(a("DELETE", "/api/v1/cache".into(), Some("admin-secret"), None, "").await.unwrap().0, 200); assert_eq!(a("GET", "/api/v1/stats".into(), Some("reader-secret"), None, "").await.unwrap().0, 200); let (_, v, _) = a("GET", "/api/v1/audit".into(), Some("reader-secret"), None, "").await.unwrap(); assert!(v["items"].as_array().unwrap().len() >= 5); let (_, v, _) = a("GET", "/api/v1/openapi.json".into(), Some("reader-secret"), None, "").await.unwrap(); assert_eq!(v["openapi"], "3.0.3"); server.shutdown().await; }