v0.42.2_fix1

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-26 11:53:05 +01:00
1 parent f38a2b9e5e
commit 15c7f9ff9e
24 files changed
+464 -77

No files matched your search

+132 -31
View File
@@ -2,11 +2,12 @@ use crate::config::Config;
use anyhow::{ensure, Result};
use arc_swap::ArcSwap;
use futures_util::{stream, StreamExt};
use serde::Serialize;
use std::{
collections::{BTreeSet, HashMap},
net::IpAddr,
sync::{Arc, LazyLock, Weak},
time::{Duration, Instant},
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use tokio::{sync::Notify, time::MissedTickBehavior};
use tokio_util::sync::CancellationToken;
@@ -18,7 +19,7 @@ const MAX_ADDRESSES: usize = 32;
const PARALLEL_LOOKUPS: usize = 8;
const LOOKUP_SECONDS: u64 = 4;
#[derive(Clone)]
#[derive(Clone, Debug)]
struct Addresses {
ips: Vec<IpAddr>,
valid_until: Instant,
@@ -26,8 +27,63 @@ struct Addresses {
static CACHE: LazyLock<ArcSwap<HashMap<String, Addresses>>> =
LazyLock::new(|| ArcSwap::from_pointee(HashMap::new()));
static DIAGNOSTICS: LazyLock<ArcSwap<HashMap<String, DnsDiagnostic>>> =
LazyLock::new(|| ArcSwap::from_pointee(HashMap::new()));
static CHANGED: LazyLock<Notify> = LazyLock::new(Notify::new);
#[derive(Clone)]
struct DnsDiagnostic {
checked_unix_ms: u64,
error: Option<String>,
}
/// A read-only view of the live resolver, not a second source of ACL permissions.
#[derive(Debug, Serialize)]
pub(crate) struct DnsAclStatus {
pub hostname: String,
pub state: &'static str,
pub addresses: Vec<IpAddr>,
pub last_checked_unix_ms: Option<u64>,
pub valid_for_seconds: Option<u64>,
pub error: Option<String>,
}
pub(crate) fn statuses(config: &Config) -> Result<Vec<DnsAclStatus>> {
let names = configured_hostnames(config)?;
let diagnostics = DIAGNOSTICS.load();
let cache = CACHE.load();
let now = Instant::now();
Ok(names.into_iter().map(|name| status_for_name(name, &cache, &diagnostics, now)).collect())
}
fn status_for_name(
hostname: String,
cache: &HashMap<String, Addresses>,
diagnostics: &HashMap<String, DnsDiagnostic>,
now: Instant,
) -> DnsAclStatus {
let latest = diagnostics.get(&hostname);
let cached = cache.get(&hostname);
let current = cached.filter(|entry| entry.valid_until > now);
let state = if current.is_some() {
"resolved"
} else if latest.is_none() {
"pending"
} else if latest.is_some_and(|entry| entry.error.is_some()) {
"failed"
} else {
"expired"
};
DnsAclStatus {
hostname,
state,
addresses: current.map_or_else(Vec::new, |entry| entry.ips.clone()),
last_checked_unix_ms: latest.map(|entry| entry.checked_unix_ms),
valid_for_seconds: current.map(|entry| entry.valid_until.duration_since(now).as_secs()),
error: latest.and_then(|entry| entry.error.clone()),
}
}
pub(crate) fn matches(name: &str, ip: IpAddr) -> bool {
let cache = CACHE.load();
cache.get(name).is_some_and(|entry| {
@@ -114,38 +170,47 @@ pub(crate) fn configured_hostnames(config: &Config) -> Result<Vec<String>> {
Ok(names.into_iter().collect())
}
async fn resolve(name: String) -> (String, Option<Addresses>) {
fn checked_unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64
}
fn validate_addresses(mut ips: Vec<IpAddr>) -> std::result::Result<Addresses, String> {
ips.sort_unstable();
ips.dedup();
if ips.is_empty() {
return Err("DNS response contains no A/AAAA addresses".into());
}
if ips.len() > MAX_ADDRESSES {
return Err(format!("DNS response exceeds the limit of {MAX_ADDRESSES} unique addresses"));
}
if ips
.iter()
.any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some()))
{
return Err("DNS response contains an IPv4-mapped IPv6 address".into());
}
Ok(Addresses {
ips,
valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS),
})
}
async fn resolve(name: String) -> (String, std::result::Result<Addresses, String>) {
let lookup_name = name.clone();
let answer = tokio::time::timeout(
Duration::from_secs(LOOKUP_SECONDS),
tokio::net::lookup_host((lookup_name.as_str(), 0u16)),
)
.await;
let mut ips = match answer {
Ok(Ok(sockets)) => sockets.map(|socket| socket.ip()).collect::<Vec<_>>(),
_ => {
tracing::warn!(hostname = %name, "dynamic ACL DNS lookup failed; no addresses permitted");
return (name, None);
}
let result = match answer {
Err(_) => Err(format!("DNS lookup timed out after {LOOKUP_SECONDS} seconds")),
Ok(Err(error)) => Err(format!("system DNS resolver returned: {error}")),
Ok(Ok(sockets)) => validate_addresses(sockets.map(|socket| socket.ip()).collect()),
};
ips.sort_unstable();
ips.dedup();
if ips.is_empty()
|| ips.len() > MAX_ADDRESSES
|| ips
.iter()
.any(|ip| matches!(ip, IpAddr::V6(v6) if v6.to_ipv4_mapped().is_some()))
{
tracing::warn!(hostname = %name, "dynamic ACL DNS returned an invalid or excessive address set");
return (name, None);
}
(
name,
Some(Addresses {
ips,
valid_until: Instant::now() + Duration::from_secs(MAX_AGE_SECONDS),
}),
)
(name, result)
}
pub(crate) fn config_changed() {
@@ -155,6 +220,7 @@ pub(crate) fn config_changed() {
pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: CancellationToken) {
let mut interval = tokio::time::interval(Duration::from_secs(REFRESH_SECONDS));
interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
let mut previous_names = Vec::new();
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
@@ -165,16 +231,25 @@ pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: Cancella
break;
};
let snapshot = state.config.load();
let Ok(names) = configured_hostnames(&snapshot.envelope.config) else {
continue;
let names = match configured_hostnames(&snapshot.envelope.config) {
Ok(names) => names,
Err(error) => {
tracing::error!(error = %error, "ACL DDNS inventory invalid; dynamic DNS rules fail closed");
CACHE.store(Arc::new(HashMap::new()));
DIAGNOSTICS.store(Arc::new(HashMap::new()));
continue;
}
};
drop(snapshot);
if names != previous_names {
tracing::info!(hostnames = ?names, "ACL DDNS resolver inventory updated");
previous_names = names.clone();
}
let results: HashMap<_, _> = tokio::select! {
_ = shutdown.cancelled() => break,
result = stream::iter(names.iter().cloned())
.map(resolve)
.buffer_unordered(PARALLEL_LOOKUPS)
.filter_map(|(name, answer)| async move { answer.map(|value| (name, value)) })
.collect() => result,
};
let current = state.config.load();
@@ -182,9 +257,35 @@ pub(crate) async fn poll_loop(app: Weak<crate::runtime::App>, shutdown: Cancella
CHANGED.notify_one();
continue;
}
CACHE.store(Arc::new(results));
let previous = CACHE.load();
let previous_diagnostics = DIAGNOSTICS.load();
let mut addresses = HashMap::new();
let mut diagnostics = HashMap::new();
for (hostname, result) in results {
let checked_unix_ms = checked_unix_ms();
match result {
Ok(value) => {
if previous.get(&hostname).is_none_or(|old| old.ips != value.ips)
|| previous_diagnostics.get(&hostname).is_some_and(|old| old.error.is_some())
{
tracing::info!(hostname = %hostname, addresses = ?value.ips,
"ACL DDNS resolved; allow rule matches only these client addresses");
}
addresses.insert(hostname.clone(), value);
diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: None });
}
Err(error) => {
tracing::warn!(hostname = %hostname, reason = %error,
"ACL DDNS resolution failed; hostname allows no client addresses");
diagnostics.insert(hostname, DnsDiagnostic { checked_unix_ms, error: Some(error) });
}
}
}
CACHE.store(Arc::new(addresses));
DIAGNOSTICS.store(Arc::new(diagnostics));
}
CACHE.store(Arc::new(HashMap::new()));
DIAGNOSTICS.store(Arc::new(HashMap::new()));
}
#[cfg(test)]