This commit is contained in:
Mateusz Gruszczyński committed 2026-11-15 12:21:12 +01:00
1 parent 5e57e48c6a
commit df0e39b899
25 files changed
+319 -97

No files matched your search

+29
View File
@@ -61,6 +61,35 @@ mod renewal_regressions {
app.tunnels.wait().await;
app.store.close().await;
}
#[tokio::test]
async fn docker_reconcile_skips_unchanged_effective_configuration() {
let (app, directory, _original, _output) = configured(true).await;
app.reconcile_docker().await.unwrap();
let first = app.config.load_full();
app.reconcile_docker().await.unwrap();
assert!(Arc::ptr_eq(&first, &app.config.load_full()));
std::thread::sleep(Duration::from_millis(20));
let certs = directory.path().join("certs");
for extension in ["pem", "key"] {
std::fs::copy(
certs.join(format!("acme-next.{extension}")),
certs.join(format!("acme-old.{extension}")),
)
.unwrap();
}
app.reconcile_docker().await.unwrap();
let reloaded = app.config.load_full();
assert!(!Arc::ptr_eq(&first, &reloaded));
app.reconcile_docker().await.unwrap();
assert!(Arc::ptr_eq(&reloaded, &app.config.load_full()));
app.reload_certificates().await.unwrap();
let explicit = app.config.load_full();
assert!(!Arc::ptr_eq(&reloaded, &explicit));
app.reconcile_docker().await.unwrap();
assert!(Arc::ptr_eq(&explicit, &app.config.load_full()));
stop(app).await;
}
#[tokio::test]
async fn renewed_pair_publishes_one_revision_and_preserves_bindings_and_old_files() {
let (app, _directory, original, output) = configured(true).await;
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.37.2",
"version": "0.37.3",
"description": "Administration API for the active panel origin. Sign in through the panel; the same-origin HttpOnly cookie authenticates all private operations. Mutations also require the exact Origin, X-RustProxy-Request: 1 and a session-bound X-CSRF-Token. Loopback HTTP is the default; Settings can enable HTTPS before using a non-loopback administration bind. This document contains no live configuration or credentials. Object schemas marked extensible are summaries: full configuration validation is authoritative in Rust. The API also permits explicitly scoped GeneralApiBearer tokens on a narrow route allowlist, with RO/RW and source CIDR checks; API-token management and Prometheus-token management are browser-session-only."
},
"servers": [
+34 -14
View File
@@ -4,6 +4,17 @@ pub(crate) fn compile_backend_with_timeout(
bindings: &[SocketAddr],
keepalive: &crate::balance::Keepalive,
connect_timeout: std::time::Duration,
) -> Result<CompiledBackend> {
compile_backend_reusing(backend, policy, bindings, keepalive, connect_timeout, None)
}
pub(crate) fn compile_backend_reusing(
backend: &Backend,
policy: &ValidationPolicy,
bindings: &[SocketAddr],
keepalive: &crate::balance::Keepalive,
connect_timeout: std::time::Duration,
reuse: Option<&CompiledBackend>,
) -> Result<CompiledBackend> {
ensure!(valid_id(&backend.id), "invalid backend id");
ensure!(backend.url.len() <= 512, "backend URL too long");
@@ -70,23 +81,32 @@ pub(crate) fn compile_backend_with_timeout(
.as_deref()
.map(|name| format!("{name}:{port}"))
.unwrap_or_else(|| authority.clone());
let client = crate::upstream::client_with_timeout(
backend,
address_policy.clone(),
false,
keepalive,
connect_timeout,
)?;
let build_client = |previous: Option<&crate::upstream::ProxyClient>, websocket: bool| {
let reusable = previous.filter(|client| {
client.built_with(
backend,
&address_policy,
websocket,
keepalive,
connect_timeout,
)
});
match reusable {
Some(client) => Ok(client.clone()),
None => crate::upstream::client_with_timeout(
backend,
address_policy.clone(),
websocket,
keepalive,
connect_timeout,
),
}
};
let client = build_client(reuse.map(|item| &item.client), false)?;
let websocket_client = if backend.protocol == UpstreamProtocol::Http1 {
client.clone()
} else {
crate::upstream::client_with_timeout(
backend,
address_policy.clone(),
true,
keepalive,
connect_timeout,
)?
build_client(reuse.map(|item| &item.websocket_client), true)?
};
let request_origin = format!("{}://{request_authority}", url.scheme());
let request_origin_uri: http::Uri = request_origin.parse()?;
+1 -1
View File
@@ -353,7 +353,7 @@ pub fn compile_with_active(
&web_services,
previous,
&effective_tls,
&tls,
(&tls, &tls_http1),
)?;
let quic_tls = tls
.as_ref()
+45 -6
View File
@@ -7,8 +7,18 @@ fn compile_routing(
web_services: &HashMap<String, Arc<crate::web_server::CompiledService>>,
previous: Option<&Snapshot>,
effective_tls: &crate::tls::Settings,
tls: &Option<Arc<rustls::ServerConfig>>,
(tls, tls_http1): (
&Option<Arc<rustls::ServerConfig>>,
&Option<Arc<rustls::ServerConfig>>,
),
) -> Result<RoutingBuild> {
let mut tls_variants: Vec<(crate::tls::ProtocolPolicy, bool, Arc<rustls::ServerConfig>)> =
Vec::new();
for (config, http2) in [(tls, true), (tls_http1, false)] {
if let Some(config) = config {
tls_variants.push((effective_tls.policy.clone(), http2, config.clone()));
}
}
let mut routes: HashMap<String, Vec<Arc<CompiledRoute>>> = HashMap::new();
let mut fallbacks: HashMap<String, Vec<Arc<CompiledRoute>>> = HashMap::new();
let mut frontends: HashMap<String, Vec<Arc<CompiledFrontend>>> = HashMap::new();
@@ -104,31 +114,43 @@ fn compile_routing(
&& route.source.is_reverse_proxy()
});
let mut compiled_members = Vec::new();
let previous_pool = previous.and_then(|s| s.pools.iter().find(|p| p.id == host.id));
for definition in host.backends.iter().filter(|_| needs_proxy_pool) {
let connect_timeout = host
.proxy_timeouts
.connect_timeout()
.unwrap_or(std::time::Duration::from_secs(10));
let mut backend = compile_backend_with_timeout(
let member_id = format!("{}/{}", host.id, definition.id);
let previous_backend = previous_pool.and_then(|pool| {
pool.members
.iter()
.find(|member| member.backend.id == member_id)
.map(|member| member.backend.clone())
});
let mut backend = compile_backend_reusing(
&definition.backend(),
desired_policy,
guarded_bindings,
&host.load_balancing.keepalive,
connect_timeout,
previous_backend.as_deref(),
)
.with_context(|| format!("vhost {} backend {}", host.id, definition.id))?;
backend.id = format!("{}/{}", host.id, definition.id);
backend.id = member_id;
let health = host.load_balancing.health_for(definition);
if health.mode != crate::balance::HealthMode::Off {
if let Some(probe) =
health_probe_backend(&definition.backend(), health.port)?
{
let mut probe = compile_backend_with_timeout(
let mut probe = compile_backend_reusing(
&probe,
desired_policy,
guarded_bindings,
&host.load_balancing.keepalive,
connect_timeout,
previous_backend
.as_ref()
.and_then(|item| item.health_probe.as_deref()),
)
.with_context(|| {
format!("vhost {} backend {} health check port", host.id, definition.id)
@@ -193,11 +215,11 @@ fn compile_routing(
}
let frontend_tls = tls
.as_ref()
.map(|base| crate::tls::variant(base, &tls_policy, true))
.map(|base| shared_tls_variant(&mut tls_variants, base, &tls_policy, true))
.transpose()?;
let frontend_tls_http1 = tls
.as_ref()
.map(|base| crate::tls::variant(base, &tls_policy, false))
.map(|base| shared_tls_variant(&mut tls_variants, base, &tls_policy, false))
.transpose()?;
let profile_policies: Vec<crate::acl::ProfileAccess> =
crate::acl::profile_ids(host.acl_profile_id.as_deref(), &host.acl_profile_ids)
@@ -498,3 +520,20 @@ fn compile_routing(
vhost_metrics,
})
}
fn shared_tls_variant(
variants: &mut Vec<(crate::tls::ProtocolPolicy, bool, Arc<rustls::ServerConfig>)>,
base: &Arc<rustls::ServerConfig>,
policy: &crate::tls::ProtocolPolicy,
http2: bool,
) -> Result<Arc<rustls::ServerConfig>> {
if let Some((_, _, config)) = variants
.iter()
.find(|(known, known_http2, _)| *known_http2 == http2 && known == policy)
{
return Ok(config.clone());
}
let config = crate::tls::variant(base, policy, http2)?;
variants.push((policy.clone(), http2, config.clone()));
Ok(config)
}
+36 -27
View File
@@ -164,30 +164,38 @@ impl Manager {
*active = current;
}
pub async fn refresh(&self, settings: &Settings, force: bool) -> (Vec<Observation>, bool) {
pub async fn refresh(
&self,
settings: &Settings,
force: bool,
) -> (Arc<BTreeMap<String, Observation>>, bool) {
let now = now_ms();
let snapshot = self.observations.read().await.clone();
let due: Vec<_> = settings
.agents
.iter()
.filter(|agent| agent.enabled)
.filter(|agent| {
force
|| snapshot.get(&agent.id).is_none_or(|observation| {
now.saturating_sub(observation.checked_at_unix_ms)
>= agent.poll_interval_seconds.saturating_mul(1000)
let due: Vec<_> = {
let snapshot = self.observations.read().await;
settings
.agents
.iter()
.filter(|agent| agent.enabled)
.filter_map(|agent| {
let previous = snapshot.get(&agent.id);
let due = force
|| previous.is_none_or(|observation| {
now.saturating_sub(observation.checked_at_unix_ms)
>= agent.poll_interval_seconds.saturating_mul(1000)
});
due.then(|| {
(
agent.clone(),
previous.and_then(|observation| observation.inventory.clone()),
previous.and_then(|observation| observation.last_ok_unix_ms),
)
})
})
.cloned()
.collect();
let futures = due.into_iter().map(|agent| {
let previous_inventory = snapshot
.get(&agent.id)
.and_then(|observation| observation.inventory.clone());
let previous_ok = snapshot
.get(&agent.id)
.and_then(|observation| observation.last_ok_unix_ms);
async move {
})
.collect()
};
let futures = due
.into_iter()
.map(|(agent, previous_inventory, previous_ok)| async move {
let checked_at_unix_ms = now_ms();
match fetch(&agent).await {
Ok(inventory) => Observation {
@@ -207,8 +215,7 @@ impl Manager {
inventory: previous_inventory,
},
}
}
});
});
let refreshed = join_all(futures).await;
let enabled: HashSet<_> = settings
.agents
@@ -224,10 +231,12 @@ impl Manager {
state.insert(observation.agent_id.clone(), observation);
changed = true;
}
if changed {
self.latest.store(Arc::new(state.clone()));
if !changed {
return (self.latest.load_full(), false);
}
(state.values().cloned().collect(), changed)
let latest = Arc::new(state.clone());
self.latest.store(latest.clone());
(latest, true)
}
}
+4 -3
View File
@@ -647,12 +647,13 @@ pub async fn poll_loop(
break;
};
let settings = app.config.load().envelope.config.docker_agents.clone();
let had_observations = !app.docker.view().await.is_empty();
let had_observations = !app.docker.latest().is_empty();
if !settings.agents.is_empty() || had_observations {
let (_, changed) = app.docker.refresh(&settings, false).await;
let config = app.config.load().envelope.config.clone();
let snapshot = app.config.load_full();
app.docker
.track_alerts(&alerts(&config, &app.docker.latest()));
.track_alerts(&alerts(&snapshot.envelope.config, &app.docker.latest()));
drop(snapshot);
if changed {
if let Err(error) = app.reconcile_docker().await {
tracing::warn!(error = ?error, "Docker discovery reconcile failed");
+4 -2
View File
@@ -45,6 +45,7 @@ impl App {
let revision = previous.envelope.revision;
let prepared = tokio::task::spawn_blocking(move || {
let effective = crate::docker::effective_config(desired, &observed)?;
let digest = effective_digest(&effective, policy.cert_dir.as_deref());
let mut prepared = config::compile_with_active(
effective,
revision,
@@ -58,7 +59,7 @@ impl App {
.config
.vhosts
.truncate(desired_vhost_count);
Ok::<_, anyhow::Error>(prepared)
Ok::<_, anyhow::Error>((prepared, digest))
})
.await
.map_err(|_| {
@@ -68,7 +69,8 @@ impl App {
)
})?
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}")))?;
self.config.store(Arc::new(prepared));
let (prepared, digest) = prepared;
self.store_snapshot(prepared, digest);
crate::acl::dynamic::config_changed();
if let Some(certificate_id) = certificate_id {
tracing::info!(
+1
View File
@@ -196,6 +196,7 @@ impl App {
body_idle_timeout,
config_file: Mutex::new(None),
update_lock: Mutex::new(()),
docker_applied: std::sync::Mutex::new(None),
update_slots: Arc::new(Semaphore::new(8)),
});
let weak = Arc::downgrade(&app);
+53 -3
View File
@@ -9,8 +9,20 @@ impl App {
let defaults = self.startup_listeners;
let active_listeners = self.active_listeners.clone();
let revision = previous.envelope.revision;
let previous_weak = Arc::downgrade(&previous);
let applied = self
.docker_applied
.lock()
.ok()
.and_then(|slot| slot.clone())
.filter(|(weak, _)| weak.ptr_eq(&previous_weak))
.map(|(_, digest)| digest);
let prepared = tokio::task::spawn_blocking(move || {
let effective = crate::docker::effective_config(desired, &observed)?;
let digest = effective_digest(&effective, policy.cert_dir.as_deref());
if digest.is_some() && applied == digest {
return Ok::<_, anyhow::Error>((None, digest));
}
let mut prepared = config::compile_with_active(
effective,
revision,
@@ -24,7 +36,7 @@ impl App {
.config
.vhosts
.truncate(desired_vhost_count);
Ok::<_, anyhow::Error>(prepared)
Ok((Some(prepared), digest))
})
.await
.map_err(|_| {
@@ -34,11 +46,23 @@ impl App {
)
})?
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}")))?;
self.config.store(Arc::new(prepared));
let (prepared, digest) = prepared;
let Some(prepared) = prepared else {
return Ok(());
};
self.store_snapshot(prepared, digest);
crate::acl::dynamic::config_changed();
Ok(())
}
fn store_snapshot(&self, prepared: Snapshot, digest: Option<[u8; 32]>) {
let prepared = Arc::new(prepared);
self.config.store(prepared.clone());
if let Ok(mut slot) = self.docker_applied.lock() {
*slot = digest.map(|digest| (Arc::downgrade(&prepared), digest));
}
}
pub async fn refresh_docker(
self: &Arc<Self>,
) -> Result<Vec<crate::docker::Observation>, ApiError> {
@@ -47,6 +71,32 @@ impl App {
if changed {
self.reconcile_docker().await?;
}
Ok(observations)
Ok(observations.values().cloned().collect())
}
}
struct DigestWriter(sha2::Sha256);
impl std::io::Write for DigestWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
sha2::Digest::update(&mut self.0, bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn effective_digest(
config: &config::Config,
certificate_dir: Option<&std::path::Path>,
) -> Option<[u8; 32]> {
let mut writer = DigestWriter(<sha2::Sha256 as sha2::Digest>::new());
serde_json::to_writer(&mut writer, config).ok()?;
for stamp in crate::tls::certificate_file_stamps(&config.tls, certificate_dir) {
for value in stamp {
sha2::Digest::update(&mut writer.0, value.to_le_bytes());
}
}
Some(sha2::Digest::finalize(writer.0).into())
}
+3
View File
@@ -19,6 +19,8 @@ use std::{
};
use tokio::sync::{Mutex, Semaphore};
type DockerApplied = (std::sync::Weak<Snapshot>, [u8; 32]);
pub struct App {
pub basic_workers: Arc<Semaphore>,
pub basic_limits: crate::basic_auth::Limits,
@@ -61,6 +63,7 @@ pub struct App {
pub body_idle_timeout: Duration,
pub config_file: Mutex<Option<(std::path::PathBuf, external_config::Fingerprint)>>,
update_lock: Mutex<()>,
docker_applied: std::sync::Mutex<Option<DockerApplied>>,
update_slots: Arc<Semaphore>,
}
#[derive(Debug)]
+4 -3
View File
@@ -121,8 +121,9 @@ impl App {
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}")))?;
crate::tls::validate_certificate_removals(&previous_config, &desired_config)
.map_err(|error| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{error:#}")))?;
let (prepared, invalidation, slot) = tokio::task::spawn_blocking(move || {
let ((prepared, digest), invalidation, slot) = tokio::task::spawn_blocking(move || {
let effective = crate::docker::effective_config(desired_config, &observed)?;
let digest = effective_digest(&effective, policy.cert_dir.as_deref());
let mut prepared = config::compile_with_active(
effective,
revision,
@@ -137,7 +138,7 @@ impl App {
.vhosts
.truncate(desired_vhost_count);
let invalidation = cache_invalidation(&previous_config, &prepared.envelope.config);
Ok::<_, anyhow::Error>((prepared, invalidation, slot))
Ok::<_, anyhow::Error>(((prepared, digest), invalidation, slot))
})
.await
.map_err(|_| {
@@ -263,7 +264,7 @@ impl App {
this.rate_limiter.reset();
this.logs.configure(envelope.config.logging.clone());
crate::logging::configure_error_log(envelope.config.error_log.clone());
this.config.store(Arc::new(prepared));
this.store_snapshot(prepared, digest);
crate::acl::dynamic::config_changed();
tracing::info!(revision, "configuration applied");
Ok(envelope)
+44
View File
@@ -156,3 +156,47 @@ fn read_pem_with_policy(
);
Ok(data)
}
pub fn certificate_file_stamps(settings: &Settings, directory: Option<&Path>) -> Vec<[i64; 4]> {
let Some(directory) = directory else {
return Vec::new();
};
settings
.certificates
.iter()
.flat_map(|item| [item.cert_file.as_str(), item.key_file.as_str()])
.map(|value| {
configured_certificate_path(directory, value)
.ok()
.and_then(|path| fs::metadata(path).ok())
.map(|meta| file_stamp(&meta))
.unwrap_or([-1; 4])
})
.collect()
}
#[cfg(unix)]
fn file_stamp(meta: &fs::Metadata) -> [i64; 4] {
use std::os::unix::fs::MetadataExt;
[
meta.mtime(),
meta.mtime_nsec(),
meta.size() as i64,
meta.ino() as i64,
]
}
#[cfg(not(unix))]
fn file_stamp(meta: &fs::Metadata) -> [i64; 4] {
let modified = meta
.modified()
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.unwrap_or_default();
[
modified.as_secs() as i64,
modified.subsec_nanos() as i64,
meta.len() as i64,
0,
]
}
+2 -2
View File
@@ -396,10 +396,10 @@ pub fn compile(settings: &Settings, directory: Option<&Path>) -> Result<Option<A
tracing::warn!(certificate = %cert.id, hostname = %host,
"Explicitly serving a TLS certificate without hostname verification; clients may reject it");
}
names.insert(host, Arc::new(key.clone()));
names.insert(host, shared.clone());
}
if settings.default_certificate.as_deref() == Some(cert.id.as_str()) {
default = Some(Arc::new(key));
default = Some(shared.clone());
}
}
if settings.default_certificate.is_some() {
+16
View File
@@ -93,6 +93,22 @@ impl std::fmt::Debug for ProxyClient {
}
impl ProxyClient {
pub fn built_with(
&self,
backend: &Backend,
policy: &AddressPolicy,
websocket: bool,
keepalive: &crate::balance::Keepalive,
timeout: Duration,
) -> bool {
let factory = &self.inner.factory;
factory.websocket == websocket
&& factory.timeout == timeout
&& factory.backend == *backend
&& factory.policy == *policy
&& factory.keepalive == *keepalive
}
fn new(current: RawProxyClient, factory: ClientFactory) -> Self {
Self {
inner: Arc::new(RotatingClient {