v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "dns-api"
|
||||
description = "EasyDNS REST API (/api/v1) and metrics endpoint"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-authoritative.workspace = true
|
||||
dns-server.workspace = true
|
||||
dns-policy.workspace = true
|
||||
dns-metrics.workspace = true
|
||||
dns-cache.workspace = true
|
||||
axum.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_norway.workspace = true
|
||||
data-encoding.workspace = true
|
||||
ring = "0.17"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Token authentication, roles, client ACL and request rate limiting.
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::extract::{ConnectInfo, Request, State};
|
||||
use axum::http::{Method, StatusCode};
|
||||
use axum::middleware::Next;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use dns_config::{ApiRole, Config};
|
||||
use dns_policy::Acl;
|
||||
|
||||
use crate::ApiState;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Role {
|
||||
Admin,
|
||||
ReadOnly,
|
||||
}
|
||||
|
||||
/// Who made a request (inserted into request extensions).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Caller {
|
||||
pub name: String,
|
||||
pub role: Role,
|
||||
pub ip: IpAddr,
|
||||
}
|
||||
|
||||
struct Token {
|
||||
name: String,
|
||||
role: Role,
|
||||
hash: [u8; 32],
|
||||
}
|
||||
|
||||
pub struct Auth {
|
||||
required: bool,
|
||||
tokens: Vec<Token>,
|
||||
acl: Acl,
|
||||
rpm: u32,
|
||||
buckets: Mutex<HashMap<IpAddr, (f64, Instant)>>,
|
||||
}
|
||||
|
||||
/// SHA-256 of a token (hex), for `sha256:` token references.
|
||||
pub fn hash_token(t: &str) -> String {
|
||||
data_encoding::HEXLOWER.encode(ring::digest::digest(&ring::digest::SHA256, t.as_bytes()).as_ref())
|
||||
}
|
||||
|
||||
fn sha(t: &str) -> [u8; 32] {
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(ring::digest::digest(&ring::digest::SHA256, t.as_bytes()).as_ref());
|
||||
out
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
pub fn from_config(cfg: &Config) -> Result<Self, String> {
|
||||
let mut tokens = Vec::new();
|
||||
for t in &cfg.api.tokens {
|
||||
let hash = if let Some(h) = t.token.strip_prefix("sha256:") {
|
||||
let b = data_encoding::HEXLOWER_PERMISSIVE.decode(h.as_bytes()).map_err(|_| format!("token {}: bad sha256 hex", t.name))?;
|
||||
<[u8; 32]>::try_from(b.as_slice()).map_err(|_| format!("token {}: sha256 must be 32 bytes", t.name))?
|
||||
} else {
|
||||
sha(&cfg.resolve_secret(&t.token).map_err(|e| format!("token {}: {e}", t.name))?)
|
||||
};
|
||||
let role = match t.role {
|
||||
ApiRole::Admin => Role::Admin,
|
||||
ApiRole::ReadOnly => Role::ReadOnly,
|
||||
};
|
||||
tokens.push(Token { name: t.name.clone(), role, hash });
|
||||
}
|
||||
if cfg.api.local_token {
|
||||
let tok = ensure_control_token(&cfg.control_token_path())?;
|
||||
tokens.push(Token { name: "local-control".into(), role: Role::Admin, hash: sha(&tok) });
|
||||
}
|
||||
Ok(Self {
|
||||
required: cfg.api.auth_required,
|
||||
tokens,
|
||||
acl: Acl(cfg.expand_acl(&cfg.api.allowed_clients)?),
|
||||
rpm: cfg.api.requests_per_minute.max(1),
|
||||
buckets: Mutex::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
fn check_rate(&self, ip: IpAddr) -> bool {
|
||||
let mut m = self.buckets.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if m.len() > 10_000 {
|
||||
m.clear();
|
||||
}
|
||||
let cap = f64::from(self.rpm);
|
||||
let now = Instant::now();
|
||||
let e = m.entry(ip).or_insert((cap, now));
|
||||
e.0 = (e.0 + now.duration_since(e.1).as_secs_f64() * cap / 60.0).min(cap);
|
||||
e.1 = now;
|
||||
if e.0 >= 1.0 {
|
||||
e.0 -= 1.0;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn identify(&self, header: Option<&str>) -> Option<(String, Role)> {
|
||||
let tok = header?.strip_prefix("Bearer ")?.trim();
|
||||
let h = sha(tok);
|
||||
let mut found = None;
|
||||
for t in &self.tokens {
|
||||
// constant-time comparison over all tokens
|
||||
if ct_eq(&h, &t.hash) {
|
||||
found = Some((t.name.clone(), t.role));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the local control token, creating it (random 256-bit, hex, mode 0640) if missing.
|
||||
pub fn ensure_control_token(path: &std::path::Path) -> Result<String, String> {
|
||||
if let Ok(t) = std::fs::read_to_string(path) {
|
||||
let t = t.trim().to_string();
|
||||
if t.len() >= 32 {
|
||||
return Ok(t);
|
||||
}
|
||||
}
|
||||
let mut raw = [0u8; 32];
|
||||
ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut raw).map_err(|_| "random generator failed".to_string())?;
|
||||
let tok = data_encoding::HEXLOWER.encode(&raw);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
let tmp = path.with_extension("token.tmp");
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut o = std::fs::OpenOptions::new();
|
||||
o.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o640);
|
||||
let mut f = o.open(&tmp).map_err(|e| format!("{}: {e}", tmp.display()))?;
|
||||
f.write_all(format!("{tok}\n").as_bytes()).map_err(|e| e.to_string())?;
|
||||
}
|
||||
std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||
tracing::info!(path = %path.display(), "created local control token for the easydns CLI");
|
||||
Ok(tok)
|
||||
}
|
||||
|
||||
/// Constant-time equality for fixed-size digests.
|
||||
fn ct_eq(a: &[u8; 32], b: &[u8; 32]) -> bool {
|
||||
a.iter().zip(b.iter()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
pub fn error(status: StatusCode, msg: &str) -> Response {
|
||||
(status, axum::Json(serde_json::json!({ "error": { "status": status.as_u16(), "message": msg } }))).into_response()
|
||||
}
|
||||
|
||||
/// Middleware: ACL → rate limit → authentication → role check.
|
||||
pub async fn guard(State(st): State<Arc<ApiState>>, ConnectInfo(peer): ConnectInfo<SocketAddr>, mut req: Request, next: Next) -> Response {
|
||||
let ip = dns_policy::canonical_ip(peer.ip());
|
||||
let a = &st.auth;
|
||||
if !a.acl.contains(ip) {
|
||||
return error(StatusCode::FORBIDDEN, "client address not allowed");
|
||||
}
|
||||
if !a.check_rate(ip) {
|
||||
return error(StatusCode::TOO_MANY_REQUESTS, "rate limit exceeded");
|
||||
}
|
||||
let path = req.uri().path().to_string();
|
||||
let public = matches!(path.as_str(), "/healthz" | "/readyz" | "/api/v1/health");
|
||||
let caller = match a.identify(req.headers().get("authorization").and_then(|v| v.to_str().ok())) {
|
||||
Some((name, role)) => Caller { name, role, ip },
|
||||
None if public || !a.required => {
|
||||
Caller { name: "anonymous".into(), role: if a.required { Role::ReadOnly } else { Role::Admin }, ip }
|
||||
}
|
||||
None => return error(StatusCode::UNAUTHORIZED, "missing or invalid bearer token"),
|
||||
};
|
||||
let mutating = !matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS);
|
||||
if mutating && caller.role != Role::Admin {
|
||||
return error(StatusCode::FORBIDDEN, "admin role required");
|
||||
}
|
||||
req.extensions_mut().insert(caller);
|
||||
next.run(req).await
|
||||
}
|
||||
@@ -0,0 +1,798 @@
|
||||
//! Endpoint implementations.
|
||||
use std::collections::BTreeMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::{Extension, Path, Query, State};
|
||||
use axum::http::{HeaderMap, StatusCode, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use dns_authoritative::{ZoneEntry, ZoneKind};
|
||||
use dns_config::{ApiOverlay, Config, ZoneConfig, ZoneType};
|
||||
use dns_core::proto::rr::{Name, RData, Record, RecordType};
|
||||
use dns_server::Runtime;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::ApiState;
|
||||
use crate::auth::{Caller, error};
|
||||
|
||||
type St = State<Arc<ApiState>>;
|
||||
|
||||
fn ok(v: Value) -> Response {
|
||||
Json(v).into_response()
|
||||
}
|
||||
|
||||
fn zone_entry(st: &ApiState, zone: &str) -> Result<Arc<ZoneEntry>, Response> {
|
||||
let name = dns_core::names::parse_name(zone).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?;
|
||||
st.server.shared.rt().zones.get(&name).ok_or_else(|| error(StatusCode::NOT_FOUND, "zone not found"))
|
||||
}
|
||||
|
||||
fn audit(st: &ApiState, c: &Caller, action: &str, target: &str, result: &str, detail: &str) {
|
||||
st.server.shared.audit.record(&format!("api:{}@{}", c.name, c.ip), action, target, result, detail);
|
||||
}
|
||||
|
||||
fn record_id(r: &Record) -> String {
|
||||
let s = format!("{}|{}|{}", r.name.to_lowercase(), r.record_type(), r.data);
|
||||
crate::hash_token(&s)[..16].to_string()
|
||||
}
|
||||
|
||||
fn record_json(r: &Record) -> Value {
|
||||
json!({ "id": record_id(r), "name": r.name.to_string(), "type": r.record_type().to_string(), "ttl": r.ttl, "data": r.data.to_string() })
|
||||
}
|
||||
|
||||
fn etag(serial: u32) -> String {
|
||||
format!("\"{serial}\"")
|
||||
}
|
||||
|
||||
/// `If-Match` guard against lost updates.
|
||||
fn check_if_match(h: &HeaderMap, serial: u32) -> Result<(), Response> {
|
||||
match h.get(header::IF_MATCH).and_then(|v| v.to_str().ok()) {
|
||||
Some(v) if v.trim() != "*" && v.trim() != etag(serial) => {
|
||||
Err(error(StatusCode::PRECONDITION_FAILED, &format!("zone changed (current ETag {})", etag(serial))))
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn zone_summary(e: &ZoneEntry) -> Value {
|
||||
let st = e.status();
|
||||
json!({
|
||||
"name": e.name.to_string(),
|
||||
"kind": e.kind,
|
||||
"views": e.views,
|
||||
"serial": st.serial,
|
||||
"loaded": st.loaded,
|
||||
"expired": st.expired,
|
||||
"records": st.records,
|
||||
"status": st,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn health(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let expired: Vec<String> = rt.zones.all().iter().filter(|z| z.is_expired()).map(|z| z.name.to_string()).collect();
|
||||
ok(json!({ "status": if expired.is_empty() { "ok" } else { "degraded" }, "expired_zones": expired }))
|
||||
}
|
||||
|
||||
pub async fn ready(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let not_loaded = rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Primary && z.current().is_none()).count();
|
||||
if not_loaded == 0 {
|
||||
(StatusCode::OK, "ready\n").into_response()
|
||||
} else {
|
||||
(StatusCode::SERVICE_UNAVAILABLE, "zones not loaded\n").into_response()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn status(State(st): St) -> Response {
|
||||
let s = &st.server.shared;
|
||||
let rt = s.rt();
|
||||
let roles = json!({
|
||||
"primary": rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Primary).count(),
|
||||
"secondary": rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Secondary).count(),
|
||||
"recursive": rt.resolver.is_some(),
|
||||
"forwarder": rt.router.default_pool.is_some() || !rt.router.rules.is_empty(),
|
||||
"forward_zones": rt.router.rules.len(),
|
||||
"default_resolution": rt.cfg.resolution.default,
|
||||
});
|
||||
ok(json!({
|
||||
"version": s.version,
|
||||
"mode": rt.cfg.server.mode,
|
||||
"uptime_seconds": s.started.elapsed().as_secs(),
|
||||
"listeners": st.server.bound,
|
||||
"roles": roles,
|
||||
"zones": rt.zones.all().iter().map(|z| zone_summary(z)).collect::<Vec<_>>(),
|
||||
"dnssec_validation": rt.cfg.recursion.dnssec_validation,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn stats(State(st): St) -> Response {
|
||||
let s = &st.server.shared;
|
||||
let m = &s.metrics;
|
||||
let c = s.cache.stats();
|
||||
let total = c.hits + c.misses;
|
||||
ok(json!({
|
||||
"queries_total": m.total_queries(),
|
||||
"responses": { "noerror": m.rcode("NOERROR"), "nxdomain": m.rcode("NXDOMAIN"), "servfail": m.rcode("SERVFAIL"), "refused": m.rcode("REFUSED") },
|
||||
"sources": dns_metrics::SOURCES.iter().map(|x| (x.to_string(), m.source(x))).collect::<BTreeMap<_, _>>(),
|
||||
"latency_p50_s": m.latency.quantile(0.5), "latency_p95_s": m.latency.quantile(0.95), "latency_p99_s": m.latency.quantile(0.99),
|
||||
"cache": c,
|
||||
"cache_hit_rate": if total > 0 { c_hits(total, &s.cache) } else { 0.0 },
|
||||
"blocked": m.blocked.load(std::sync::atomic::Ordering::Relaxed),
|
||||
"rate_limited": m.rate_limited.load(std::sync::atomic::Ordering::Relaxed),
|
||||
"uptime_seconds": s.started.elapsed().as_secs(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn c_hits(total: u64, c: &dns_cache::Cache) -> f64 {
|
||||
c.stats().hits as f64 / total as f64
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct Page {
|
||||
page: Option<usize>,
|
||||
per_page: Option<usize>,
|
||||
name: Option<String>,
|
||||
#[serde(rename = "type")]
|
||||
rtype: Option<String>,
|
||||
kind: Option<String>,
|
||||
}
|
||||
|
||||
fn paginate<T: Clone>(items: &[T], p: &Page) -> (Vec<T>, Value) {
|
||||
let per = p.per_page.unwrap_or(100).clamp(1, 1000);
|
||||
let page = p.page.unwrap_or(1).max(1);
|
||||
let start = (page - 1) * per;
|
||||
let slice = items.iter().skip(start).take(per).cloned().collect();
|
||||
(slice, json!({ "page": page, "per_page": per, "total": items.len() }))
|
||||
}
|
||||
|
||||
pub async fn zones_list(State(st): St, Query(p): Query<Page>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let all: Vec<Value> = rt
|
||||
.zones
|
||||
.all()
|
||||
.iter()
|
||||
.filter(|z| p.kind.as_deref().is_none_or(|k| format!("{:?}", z.kind).eq_ignore_ascii_case(k)))
|
||||
.filter(|z| p.name.as_deref().is_none_or(|n| z.name.to_string().contains(&n.to_ascii_lowercase())))
|
||||
.map(|z| zone_summary(z))
|
||||
.collect();
|
||||
let (items, meta) = paginate(&all, &p);
|
||||
ok(json!({ "items": items, "pagination": meta }))
|
||||
}
|
||||
|
||||
pub async fn zone_show(State(st): St, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let serial = e.current().map(|z| z.serial()).unwrap_or(0);
|
||||
let mut v = zone_summary(&e);
|
||||
v["config"] = serde_json::to_value(&e.config).unwrap_or(Value::Null);
|
||||
v["journal_entries"] = json!(e.journal.lock().map(|j| j.len()).unwrap_or(0));
|
||||
([(header::ETAG, etag(serial))], Json(v)).into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewZone {
|
||||
name: String,
|
||||
/// Full zone file text; alternatively give `ns` + `hostmaster` to generate a minimal zone.
|
||||
zone_file: Option<String>,
|
||||
#[serde(default)]
|
||||
ns: Vec<String>,
|
||||
hostmaster: Option<String>,
|
||||
#[serde(default)]
|
||||
transfer_acl: Vec<String>,
|
||||
#[serde(default)]
|
||||
notify: Vec<SocketAddr>,
|
||||
}
|
||||
|
||||
fn persist_overlay(cfg: &Config, o: &ApiOverlay) -> Result<(), Response> {
|
||||
let text = serde_norway::to_string(o).map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
|
||||
dns_core::zonefile::atomic_write(&cfg.overlay_path(), text.as_bytes())
|
||||
.map_err(|e| error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))
|
||||
}
|
||||
|
||||
fn reload(st: &ApiState) -> Result<dns_server::server::ReloadReport, Response> {
|
||||
st.server.reload().map_err(|e| error(StatusCode::UNPROCESSABLE_ENTITY, &format!("reload failed, previous configuration kept: {e}")))
|
||||
}
|
||||
|
||||
pub async fn zone_create(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<NewZone>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let name = match dns_core::names::parse_name(&b.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
if rt.zones.get(&name).is_some() {
|
||||
return error(StatusCode::CONFLICT, "zone already exists");
|
||||
}
|
||||
let text = match (&b.zone_file, b.ns.first()) {
|
||||
(Some(t), _) => t.clone(),
|
||||
(None, Some(_)) => {
|
||||
let hm = b.hostmaster.clone().unwrap_or_else(|| format!("hostmaster.{name}"));
|
||||
let mut t = format!("$TTL 3600\n@ IN SOA {} {} 1 3600 900 1209600 300\n", b.ns[0], hm);
|
||||
for ns in &b.ns {
|
||||
t.push_str(&format!("@ IN NS {ns}\n"));
|
||||
}
|
||||
t
|
||||
}
|
||||
_ => return error(StatusCode::BAD_REQUEST, "provide zone_file or ns"),
|
||||
};
|
||||
let records = match dns_core::zonefile::parse_str(&text, &name, None) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return error(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string()),
|
||||
};
|
||||
if let Err(e) = dns_authoritative::Zone::from_records(&name, records) {
|
||||
return error(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string());
|
||||
}
|
||||
let file = rt.cfg.data_dir().join("zones").join(format!("{}zone", name.to_ascii()));
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&file, text.as_bytes()) {
|
||||
return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
o.zones.push(ZoneConfig {
|
||||
source: None,
|
||||
name: name.to_string(),
|
||||
zone_type: ZoneType::Primary,
|
||||
file: Some(file),
|
||||
transfer_acl: b.transfer_acl,
|
||||
transfer_tsig_key: None,
|
||||
notify: b.notify,
|
||||
notify_tsig_key: None,
|
||||
primaries: Vec::new(),
|
||||
transfer: Default::default(),
|
||||
allow_notify: Vec::new(),
|
||||
update_keys: Vec::new(),
|
||||
update_acl: Vec::new(),
|
||||
update_policy: Vec::new(),
|
||||
serial_strategy: Default::default(),
|
||||
views: Vec::new(),
|
||||
journal_size: 100,
|
||||
dnssec: None,
|
||||
});
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "zone-create", &name.to_string(), "ok", "");
|
||||
(StatusCode::CREATED, Json(json!({ "name": name.to_string() }))).into_response()
|
||||
}
|
||||
Err(r) => {
|
||||
o.zones.retain(|z| z.name != name.to_string());
|
||||
let _ = persist_overlay(&rt.cfg, &o);
|
||||
audit(&st, &c, "zone-create", &name.to_string(), "failed", "");
|
||||
r
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ReplaceZone {
|
||||
zone_file: String,
|
||||
}
|
||||
|
||||
/// Replace the full contents of a primary zone (serial is bumped automatically).
|
||||
pub async fn zone_replace(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path(zone): Path<String>,
|
||||
h: HeaderMap,
|
||||
Json(b): Json<ReplaceZone>,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(cur) = e.current() else { return error(StatusCode::SERVICE_UNAVAILABLE, "zone not loaded") };
|
||||
if let Err(r) = check_if_match(&h, cur.serial()) {
|
||||
return r;
|
||||
}
|
||||
let recs = match dns_core::zonefile::parse_str(&b.zone_file, &e.name, None) {
|
||||
Ok(r) => r,
|
||||
Err(err) => return error(StatusCode::UNPROCESSABLE_ENTITY, &err.to_string()),
|
||||
};
|
||||
let new = match dns_authoritative::Zone::from_records(&e.name, recs) {
|
||||
Ok(z) => z,
|
||||
Err(err) => return error(StatusCode::UNPROCESSABLE_ENTITY, &err.to_string()),
|
||||
};
|
||||
let (rm, add) = cur.diff(&new);
|
||||
match e.modify(&rm, &add) {
|
||||
Ok(serial) => {
|
||||
e.send_notifies();
|
||||
audit(&st, &c, "zone-replace", &e.name.to_string(), "ok", &format!("+{} -{} serial {serial}", add.len(), rm.len()));
|
||||
([(header::ETAG, etag(serial))], Json(json!({ "serial": serial, "added": add.len(), "removed": rm.len() }))).into_response()
|
||||
}
|
||||
Err(err) => error(StatusCode::UNPROCESSABLE_ENTITY, &err),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn zone_delete(State(st): St, Extension(c): Extension<Caller>, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let rt = st.server.shared.rt();
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(err) => return error(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string()),
|
||||
};
|
||||
let before = o.zones.len();
|
||||
o.zones.retain(|z| dns_core::names::parse_name(&z.name).ok().as_ref() != Some(&e.name));
|
||||
if o.zones.len() == before {
|
||||
return error(StatusCode::CONFLICT, "zone is defined in the configuration file; remove it there");
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "zone-delete", &e.name.to_string(), "ok", "");
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn records_list(State(st): St, Path(zone): Path<String>, Query(p): Query<Page>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(z) = e.current() else { return error(StatusCode::SERVICE_UNAVAILABLE, "zone not loaded or expired") };
|
||||
let want_type = p.rtype.as_deref().map(|t| t.to_ascii_uppercase());
|
||||
let all: Vec<Value> = z
|
||||
.all_records()
|
||||
.iter()
|
||||
.filter(|r| p.name.as_deref().is_none_or(|n| r.name.to_string().to_ascii_lowercase().starts_with(&n.to_ascii_lowercase())))
|
||||
.filter(|r| want_type.as_deref().is_none_or(|t| r.record_type().to_string() == t))
|
||||
.map(record_json)
|
||||
.collect();
|
||||
let (items, meta) = paginate(&all, &p);
|
||||
([(header::ETAG, etag(z.serial()))], Json(json!({ "items": items, "pagination": meta, "serial": z.serial() }))).into_response()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RecordBody {
|
||||
name: String,
|
||||
#[serde(rename = "type")]
|
||||
rtype: String,
|
||||
#[serde(default = "default_ttl")]
|
||||
ttl: u32,
|
||||
data: String,
|
||||
}
|
||||
|
||||
fn default_ttl() -> u32 {
|
||||
3600
|
||||
}
|
||||
|
||||
fn build_record(zone: &Name, b: &RecordBody) -> Result<Record, Response> {
|
||||
let name = if b.name == "@" {
|
||||
zone.clone()
|
||||
} else if b.name.ends_with('.') {
|
||||
dns_core::names::parse_name(&b.name).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?
|
||||
} else {
|
||||
dns_core::names::parse_name(&format!("{}.{}", b.name, zone)).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?
|
||||
};
|
||||
if !zone.zone_of(&name) {
|
||||
return Err(error(StatusCode::BAD_REQUEST, "record name outside zone"));
|
||||
}
|
||||
let rtype: RecordType = b.rtype.to_ascii_uppercase().parse().map_err(|_| error(StatusCode::BAD_REQUEST, "unknown record type"))?;
|
||||
if matches!(rtype, RecordType::SOA) {
|
||||
return Err(error(StatusCode::BAD_REQUEST, "SOA is managed automatically; use PUT /zones/{zone}"));
|
||||
}
|
||||
let data = RData::try_from_str(rtype, &b.data).map_err(|e| error(StatusCode::BAD_REQUEST, &format!("invalid {rtype} data: {e}")))?;
|
||||
let data = match data {
|
||||
// relative names in RDATA are made absolute against the zone
|
||||
RData::CNAME(c) if !c.0.is_fqdn() => RData::CNAME(dns_core::proto::rr::rdata::CNAME(
|
||||
c.0.append_domain(zone).map_err(|e| error(StatusCode::BAD_REQUEST, &e.to_string()))?,
|
||||
)),
|
||||
other => other,
|
||||
};
|
||||
Ok(Record::from_rdata(name, b.ttl, data))
|
||||
}
|
||||
|
||||
fn find_record(e: &ZoneEntry, id: &str) -> Option<Record> {
|
||||
e.current()?.all_records().into_iter().find(|r| record_id(r) == id && r.record_type() != RecordType::SOA)
|
||||
}
|
||||
|
||||
async fn change(
|
||||
st: &ApiState,
|
||||
c: &Caller,
|
||||
e: &Arc<ZoneEntry>,
|
||||
h: &HeaderMap,
|
||||
removed: Vec<Record>,
|
||||
added: Vec<Record>,
|
||||
action: &str,
|
||||
) -> Response {
|
||||
let Some(cur) = e.current() else { return error(StatusCode::SERVICE_UNAVAILABLE, "zone not loaded") };
|
||||
if e.kind != ZoneKind::Primary {
|
||||
return error(StatusCode::CONFLICT, "records can only be changed on primary zones");
|
||||
}
|
||||
if let Err(r) = check_if_match(h, cur.serial()) {
|
||||
return r;
|
||||
}
|
||||
match e.modify(&removed, &added) {
|
||||
Ok(serial) => {
|
||||
e.send_notifies();
|
||||
audit(st, c, action, &e.name.to_string(), "ok", &format!("+{} -{} serial {serial}", added.len(), removed.len()));
|
||||
let body = json!({ "serial": serial, "records": added.iter().map(record_json).collect::<Vec<_>>() });
|
||||
let status = if action == "record-add" { StatusCode::CREATED } else { StatusCode::OK };
|
||||
(status, [(header::ETAG, etag(serial))], Json(body)).into_response()
|
||||
}
|
||||
Err(err) => {
|
||||
audit(st, c, action, &e.name.to_string(), "rejected", &err);
|
||||
error(StatusCode::UNPROCESSABLE_ENTITY, &err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn record_add(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path(zone): Path<String>,
|
||||
h: HeaderMap,
|
||||
Json(b): Json<RecordBody>,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let rec = match build_record(&e.name, &b) {
|
||||
Ok(r) => r,
|
||||
Err(r) => return r,
|
||||
};
|
||||
change(&st, &c, &e, &h, vec![], vec![rec], "record-add").await
|
||||
}
|
||||
|
||||
pub async fn record_update(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path((zone, id)): Path<(String, String)>,
|
||||
h: HeaderMap,
|
||||
Json(b): Json<RecordBody>,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(old) = find_record(&e, &id) else { return error(StatusCode::NOT_FOUND, "record not found") };
|
||||
let rec = match build_record(&e.name, &b) {
|
||||
Ok(r) => r,
|
||||
Err(r) => return r,
|
||||
};
|
||||
change(&st, &c, &e, &h, vec![old], vec![rec], "record-update").await
|
||||
}
|
||||
|
||||
pub async fn record_delete(
|
||||
State(st): St,
|
||||
Extension(c): Extension<Caller>,
|
||||
Path((zone, id)): Path<(String, String)>,
|
||||
h: HeaderMap,
|
||||
) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
let Some(old) = find_record(&e, &id) else { return error(StatusCode::NOT_FOUND, "record not found") };
|
||||
change(&st, &c, &e, &h, vec![old], vec![], "record-delete").await
|
||||
}
|
||||
|
||||
pub async fn zone_notify(State(st): St, Extension(c): Extension<Caller>, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if e.config.notify.is_empty() {
|
||||
return error(StatusCode::CONFLICT, "zone has no notify targets");
|
||||
}
|
||||
e.send_notifies();
|
||||
audit(&st, &c, "zone-notify", &e.name.to_string(), "ok", "");
|
||||
(StatusCode::ACCEPTED, Json(json!({ "targets": e.config.notify }))).into_response()
|
||||
}
|
||||
|
||||
pub async fn zone_sync(State(st): St, Extension(c): Extension<Caller>, Path(zone): Path<String>) -> Response {
|
||||
let e = match zone_entry(&st, &zone) {
|
||||
Ok(e) => e,
|
||||
Err(r) => return r,
|
||||
};
|
||||
if e.kind != ZoneKind::Secondary {
|
||||
return error(StatusCode::CONFLICT, "sync is only valid for secondary zones");
|
||||
}
|
||||
let res = dns_authoritative::secondary::refresh_once(&e).await;
|
||||
if res.is_ok() {
|
||||
e.set_expired(false);
|
||||
e.update_status(|s| {
|
||||
s.last_success_unix = Some(dns_core::tsig::now());
|
||||
s.last_error = None;
|
||||
});
|
||||
}
|
||||
audit(&st, &c, "zone-sync", &e.name.to_string(), if res.is_ok() { "ok" } else { "failed" }, "");
|
||||
match res {
|
||||
Ok(o) => ok(json!({ "result": format!("{o:?}"), "serial": e.current().map(|z| z.serial()) })),
|
||||
Err(err) => error(StatusCode::BAD_GATEWAY, &err),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn zone_transfers(State(st): St, Path(zone): Path<String>) -> Response {
|
||||
match zone_entry(&st, &zone) {
|
||||
Ok(e) => ok(json!({ "items": e.transfers() })),
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cache_stats(State(st): St) -> Response {
|
||||
ok(serde_json::to_value(st.server.shared.cache.stats()).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CacheClear {
|
||||
domain: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn cache_clear(State(st): St, Extension(c): Extension<Caller>, Query(q): Query<CacheClear>) -> Response {
|
||||
let cache = &st.server.shared.cache;
|
||||
let removed = match &q.domain {
|
||||
Some(d) => match dns_core::names::parse_name(d) {
|
||||
Ok(n) => cache.clear_domain(&n),
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
},
|
||||
None => cache.clear(),
|
||||
};
|
||||
// encoded answers may contain the flushed data
|
||||
st.server.shared.packet_cache.invalidate();
|
||||
audit(&st, &c, "cache-clear", q.domain.as_deref().unwrap_or("*"), "ok", &format!("{removed} entries"));
|
||||
ok(json!({ "removed": removed }))
|
||||
}
|
||||
|
||||
pub async fn upstreams_list(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let mut groups = Vec::new();
|
||||
if let Some(p) = &rt.router.default_pool {
|
||||
groups.push(json!({ "group": "default", "strategy": p.strategy, "servers": p.stats().into_iter().map(|(a, s)| json!({"address": a, "stats": s})).collect::<Vec<_>>() }));
|
||||
}
|
||||
for r in &rt.router.rules {
|
||||
groups.push(json!({ "group": r.suffix.to_string(), "strategy": r.pool.strategy, "servers": r.pool.stats().into_iter().map(|(a, s)| json!({"address": a, "stats": s})).collect::<Vec<_>>() }));
|
||||
}
|
||||
ok(json!({ "items": groups }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewUpstream {
|
||||
address: String,
|
||||
}
|
||||
|
||||
pub async fn upstreams_add(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<NewUpstream>) -> Response {
|
||||
if let Err(e) = dns_config::upstream::UpstreamAddr::parse(&b.address) {
|
||||
return error(StatusCode::BAD_REQUEST, &e);
|
||||
}
|
||||
let rt = st.server.shared.rt();
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
if !o.upstreams.contains(&b.address) {
|
||||
o.upstreams.push(b.address.clone());
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "upstream-add", &b.address, "ok", "");
|
||||
(StatusCode::CREATED, Json(json!({ "address": b.address }))).into_response()
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn policies_get(State(st): St) -> Response {
|
||||
let cfg = st.server.shared.rt().cfg.clone();
|
||||
ok(json!({
|
||||
"recursion_allowed_clients": cfg.recursion.allowed_clients,
|
||||
"acls": cfg.acls,
|
||||
"views": cfg.resolution.views,
|
||||
"rate_limit": cfg.rate_limit,
|
||||
"policy": cfg.policy,
|
||||
"api_allowed_clients": cfg.api.allowed_clients,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct PolicyPut {
|
||||
allowlist: Option<Vec<String>>,
|
||||
block_action: Option<dns_config::BlockAction>,
|
||||
}
|
||||
|
||||
pub async fn policies_put(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<PolicyPut>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
if b.allowlist.is_some() {
|
||||
o.allowlist = b.allowlist;
|
||||
}
|
||||
if b.block_action.is_some() {
|
||||
o.block_action = b.block_action;
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "policy-update", "policy", "ok", "");
|
||||
policies_get(State(st)).await
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn blocklists_get(State(st): St) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
ok(json!({ "lists": rt.cfg.policy.blocklists, "loaded": rt.policy.list_names(), "rules": rt.policy.rule_count() }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct NewRule {
|
||||
rule: String,
|
||||
}
|
||||
|
||||
pub async fn blocklists_add(State(st): St, Extension(c): Extension<Caller>, Json(b): Json<NewRule>) -> Response {
|
||||
let rt = st.server.shared.rt();
|
||||
let rule = b.rule.trim().to_string();
|
||||
if rule.is_empty() || rule.contains('\n') {
|
||||
return error(StatusCode::BAD_REQUEST, "invalid rule");
|
||||
}
|
||||
let mut test = dns_policy::BlockPolicy::default();
|
||||
if let Err(e) = test.add_rule("api", &rule) {
|
||||
return error(StatusCode::BAD_REQUEST, &e);
|
||||
}
|
||||
let mut o = match rt.cfg.load_overlay() {
|
||||
Ok(o) => o,
|
||||
Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
};
|
||||
if !o.block_rules.contains(&rule) {
|
||||
o.block_rules.push(rule.clone());
|
||||
}
|
||||
let file = rt.cfg.data_dir().join("blocklists").join("api.txt");
|
||||
if let Err(e) = dns_core::zonefile::atomic_write(&file, (o.block_rules.join("\n") + "\n").as_bytes()) {
|
||||
return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
if let Err(r) = persist_overlay(&rt.cfg, &o) {
|
||||
return r;
|
||||
}
|
||||
match reload(&st) {
|
||||
Ok(_) => {
|
||||
audit(&st, &c, "blocklist-add", &rule, "ok", "");
|
||||
(StatusCode::CREATED, Json(json!({ "rule": rule }))).into_response()
|
||||
}
|
||||
Err(r) => r,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn config_reload(State(st): St, Extension(c): Extension<Caller>) -> Response {
|
||||
match st.server.reload() {
|
||||
Ok(rep) => {
|
||||
audit(&st, &c, "config-reload", "config", "ok", &format!("{rep:?}"));
|
||||
ok(serde_json::to_value(rep).unwrap_or(Value::Null))
|
||||
}
|
||||
Err(e) => {
|
||||
audit(&st, &c, "config-reload", "config", "failed", &e);
|
||||
error(StatusCode::UNPROCESSABLE_ENTITY, &format!("reload failed, previous configuration kept: {e}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct AuditQ {
|
||||
n: Option<usize>,
|
||||
}
|
||||
|
||||
pub async fn audit_tail(State(st): St, Query(q): Query<AuditQ>) -> Response {
|
||||
ok(json!({ "items": st.server.shared.audit.tail(q.n.unwrap_or(100).min(10_000)) }))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DnsQ {
|
||||
name: String,
|
||||
#[serde(rename = "type")]
|
||||
rtype: Option<String>,
|
||||
}
|
||||
|
||||
/// Run a query through this server (convenience for `easydns query`).
|
||||
pub async fn api_query(State(st): St, Query(q): Query<DnsQ>) -> Response {
|
||||
let Some(mut addr) = st.server.bound.dns.first().copied() else { return error(StatusCode::SERVICE_UNAVAILABLE, "no DNS listener") };
|
||||
if addr.ip().is_unspecified() {
|
||||
addr.set_ip(if addr.is_ipv4() { [127, 0, 0, 1].into() } else { std::net::Ipv6Addr::LOCALHOST.into() });
|
||||
}
|
||||
let name = match dns_core::names::parse_name(&q.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return error(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
let t: RecordType = q.rtype.as_deref().unwrap_or("A").to_ascii_uppercase().parse().unwrap_or(RecordType::A);
|
||||
match dns_core::client::query(addr, &name, t, &Default::default()).await {
|
||||
Ok(ex) => ok(json!({
|
||||
"rcode": rcode_name(ex.message.metadata.response_code),
|
||||
"aa": ex.message.metadata.authoritative,
|
||||
"answers": ex.message.answers.iter().map(record_json).collect::<Vec<_>>(),
|
||||
"authority": ex.message.authorities.iter().map(record_json).collect::<Vec<_>>(),
|
||||
"elapsed_ms": ex.elapsed.as_secs_f64() * 1000.0,
|
||||
})),
|
||||
Err(e) => error(StatusCode::BAD_GATEWAY, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn rcode_name(r: dns_core::proto::op::ResponseCode) -> String {
|
||||
use dns_core::proto::op::ResponseCode as R;
|
||||
match r {
|
||||
R::NoError => "NOERROR".into(),
|
||||
R::NXDomain => "NXDOMAIN".into(),
|
||||
R::ServFail => "SERVFAIL".into(),
|
||||
R::Refused => "REFUSED".into(),
|
||||
R::FormErr => "FORMERR".into(),
|
||||
R::NotImp => "NOTIMP".into(),
|
||||
other => format!("RCODE{}", u16::from(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn openapi() -> Response {
|
||||
let eps: &[(&str, &[&str], &str)] = &[
|
||||
("/status", &["get"], "Service and role status"),
|
||||
("/stats", &["get"], "Counters and statistics"),
|
||||
("/zones", &["get", "post"], "List / create zones"),
|
||||
("/zones/{zone}", &["get", "put", "delete"], "Zone details / replace contents / delete API-created zone"),
|
||||
("/zones/{zone}/records", &["get", "post"], "List (paginated, filter by name/type) / add records"),
|
||||
("/zones/{zone}/records/{id}", &["put", "delete"], "Replace / delete a record (If-Match supported)"),
|
||||
("/zones/{zone}/notify", &["post"], "Send NOTIFY to secondaries"),
|
||||
("/zones/{zone}/sync", &["post"], "Refresh a secondary zone now"),
|
||||
("/zones/{zone}/transfers", &["get"], "Transfer history"),
|
||||
("/cache", &["get", "delete"], "Cache statistics / flush (optionally ?domain=)"),
|
||||
("/upstreams", &["get", "post"], "Upstream status / add an upstream"),
|
||||
("/policies", &["get", "put"], "ACLs, views, rate limits, allowlist / block action"),
|
||||
("/blocklists", &["get", "post"], "Block lists / add a rule"),
|
||||
("/config/reload", &["post"], "Hot reload with rollback"),
|
||||
("/audit", &["get"], "Audit log tail"),
|
||||
("/query", &["get"], "Resolve through this server"),
|
||||
("/health", &["get"], "Health check (no auth)"),
|
||||
];
|
||||
let mut paths = serde_json::Map::new();
|
||||
for (p, methods, desc) in eps {
|
||||
let mut m = serde_json::Map::new();
|
||||
for meth in *methods {
|
||||
m.insert((*meth).into(), json!({ "summary": desc, "security": [{"bearer": []}],
|
||||
"responses": { "200": {"description": "OK"}, "401": {"description": "Unauthorized"}, "403": {"description": "Forbidden"} } }));
|
||||
}
|
||||
paths.insert(format!("/api/v1{p}"), Value::Object(m));
|
||||
}
|
||||
ok(json!({
|
||||
"openapi": "3.0.3",
|
||||
"info": { "title": "EasyDNS API", "version": env!("CARGO_PKG_VERSION") },
|
||||
"components": { "securitySchemes": { "bearer": { "type": "http", "scheme": "bearer" } } },
|
||||
"paths": paths,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Per-zone gauges (cardinality bounded by the number of configured zones).
|
||||
pub fn zone_metrics(rt: &Runtime) -> String {
|
||||
let mut s = String::from("# HELP dns_zone_serial Current SOA serial per zone\n# TYPE dns_zone_serial gauge\n");
|
||||
for z in rt.zones.all() {
|
||||
if let Some(cur) = z.snapshot_any() {
|
||||
s.push_str(&format!("dns_zone_serial{{zone=\"{}\",role=\"{:?}\"}} {}\n", z.name, z.kind, cur.serial()));
|
||||
}
|
||||
}
|
||||
s.push_str("# HELP dns_zone_expired Secondary zone expired (1) or not (0)\n# TYPE dns_zone_expired gauge\n");
|
||||
for z in rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Secondary) {
|
||||
s.push_str(&format!("dns_zone_expired{{zone=\"{}\"}} {}\n", z.name, u8::from(z.is_expired())));
|
||||
}
|
||||
s.push_str("# HELP dns_zone_last_sync_timestamp_seconds Last successful refresh of a secondary zone\n# TYPE dns_zone_last_sync_timestamp_seconds gauge\n");
|
||||
for z in rt.zones.all().iter().filter(|z| z.kind == ZoneKind::Secondary) {
|
||||
if let Some(t) = z.status().last_success_unix {
|
||||
s.push_str(&format!("dns_zone_last_sync_timestamp_seconds{{zone=\"{}\"}} {t}\n", z.name));
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
//! REST API (`/api/v1`), health endpoints and the Prometheus `/metrics` listener.
|
||||
//!
|
||||
//! * Listens on loopback by default; `api.allowed_clients` is enforced per request.
|
||||
//! * Bearer tokens with roles `admin` / `read-only`; tokens are configured as references
|
||||
//! (`env:`, `file:`) or as `sha256:<hex>` hashes and compared in constant time.
|
||||
//! * Every state-changing call is audited; record changes support `If-Match` (zone serial ETag).
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
// Handlers return `Result<_, axum::Response>`; boxing the error would only add noise.
|
||||
#![allow(clippy::result_large_err)]
|
||||
|
||||
mod auth;
|
||||
mod handlers;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::Router;
|
||||
use axum::routing::{get, post, put};
|
||||
use dns_server::ServerHandle;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub use auth::{Auth, Role, hash_token};
|
||||
|
||||
/// Shared API state.
|
||||
pub struct ApiState {
|
||||
pub server: Arc<ServerHandle>,
|
||||
pub auth: auth::Auth,
|
||||
}
|
||||
|
||||
/// Build the API router.
|
||||
pub fn router(state: Arc<ApiState>) -> Router {
|
||||
use handlers::*;
|
||||
let v1 = Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/stats", get(stats))
|
||||
.route("/zones", get(zones_list).post(zone_create))
|
||||
.route("/zones/{zone}", get(zone_show).put(zone_replace).delete(zone_delete))
|
||||
.route("/zones/{zone}/records", get(records_list).post(record_add))
|
||||
.route("/zones/{zone}/records/{id}", put(record_update).delete(record_delete))
|
||||
.route("/zones/{zone}/notify", post(zone_notify))
|
||||
.route("/zones/{zone}/sync", post(zone_sync))
|
||||
.route("/zones/{zone}/transfers", get(zone_transfers))
|
||||
.route("/cache", get(cache_stats).delete(cache_clear))
|
||||
.route("/upstreams", get(upstreams_list).post(upstreams_add))
|
||||
.route("/policies", get(policies_get).put(policies_put))
|
||||
.route("/blocklists", get(blocklists_get).post(blocklists_add))
|
||||
.route("/config/reload", post(config_reload))
|
||||
.route("/audit", get(audit_tail))
|
||||
.route("/query", get(api_query))
|
||||
.route("/health", get(health))
|
||||
.route("/openapi.json", get(openapi));
|
||||
Router::new()
|
||||
.nest("/api/v1", v1)
|
||||
.route("/healthz", get(health))
|
||||
.route("/readyz", get(ready))
|
||||
.layer(axum::middleware::from_fn_with_state(Arc::clone(&state), auth::guard))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Serve the API until shutdown. Returns the bound address.
|
||||
pub async fn serve_api(state: Arc<ApiState>, addr: SocketAddr, mut shutdown: watch::Receiver<bool>) -> Result<SocketAddr, String> {
|
||||
let l = TcpListener::bind(addr).await.map_err(|e| format!("bind API {addr}: {e}"))?;
|
||||
let bound = l.local_addr().map_err(|e| e.to_string())?;
|
||||
let app = router(state).into_make_service_with_connect_info::<SocketAddr>();
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(l, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = shutdown.changed().await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
tracing::info!(%bound, "REST API listening");
|
||||
Ok(bound)
|
||||
}
|
||||
|
||||
/// Serve `/metrics` (Prometheus text format) until shutdown.
|
||||
pub async fn serve_metrics(server: Arc<ServerHandle>, addr: SocketAddr, mut shutdown: watch::Receiver<bool>) -> Result<SocketAddr, String> {
|
||||
let l = TcpListener::bind(addr).await.map_err(|e| format!("bind metrics {addr}: {e}"))?;
|
||||
let bound = l.local_addr().map_err(|e| e.to_string())?;
|
||||
let app = Router::new()
|
||||
.route(
|
||||
"/metrics",
|
||||
get(move || {
|
||||
let s = Arc::clone(&server);
|
||||
async move {
|
||||
let shared = &s.shared;
|
||||
let mut extra = shared.cache.render_metrics();
|
||||
extra.push_str(&handlers::zone_metrics(&shared.rt()));
|
||||
extra.push_str(&shared.packet_cache.render_metrics());
|
||||
([(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")], shared.metrics.render(&extra))
|
||||
}
|
||||
}),
|
||||
)
|
||||
.route("/healthz", get(|| async { "ok\n" }));
|
||||
tokio::spawn(async move {
|
||||
let _ = axum::serve(l, app)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = shutdown.changed().await;
|
||||
})
|
||||
.await;
|
||||
});
|
||||
tracing::info!(%bound, "metrics listening");
|
||||
Ok(bound)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
//! 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<Value>, 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<Value>, 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;
|
||||
}
|
||||
Reference in new issue
Block a user