v0.38.0
This commit is contained in:
1 parent
df0e39b899
commit
21aef61dd5
35 files changed
+1360
-100
No files matched your search
@@ -203,13 +203,15 @@ impl App {
|
||||
let shutdown = app.shutdown.clone();
|
||||
app.tunnels
|
||||
.spawn(crate::balance::health_loop(weak, shutdown));
|
||||
app.tunnels.spawn(crate::acme::renewal_loop(
|
||||
Arc::downgrade(&app),
|
||||
app.shutdown.clone(),
|
||||
));
|
||||
if !cfg!(test) {
|
||||
app.tunnels
|
||||
.spawn(crate::acme::runtime_setup_once(Arc::downgrade(&app)));
|
||||
if !headless_enabled() {
|
||||
app.tunnels.spawn(crate::acme::renewal_loop(
|
||||
Arc::downgrade(&app),
|
||||
app.shutdown.clone(),
|
||||
));
|
||||
if !cfg!(test) {
|
||||
app.tunnels
|
||||
.spawn(crate::acme::runtime_setup_once(Arc::downgrade(&app)));
|
||||
}
|
||||
}
|
||||
app.tunnels.spawn(crate::docker::poll_loop(
|
||||
Arc::downgrade(&app),
|
||||
|
||||
@@ -10,6 +10,77 @@ use std::{
|
||||
pub type Fingerprint = [u8; 32];
|
||||
|
||||
pub fn read(path: &Path) -> Result<(Config, Fingerprint)> {
|
||||
let (contents, fingerprint) = read_bytes(path)?;
|
||||
let config = serde_json::from_slice(&contents).context("invalid --config JSON")?;
|
||||
Ok((config, fingerprint))
|
||||
}
|
||||
|
||||
pub fn fingerprint(path: &Path) -> Result<Fingerprint> {
|
||||
Ok(read_bytes(path)?.1)
|
||||
}
|
||||
|
||||
pub fn read_headless(
|
||||
path: &Path,
|
||||
listeners: &crate::settings::Listeners,
|
||||
) -> Result<(Config, Fingerprint)> {
|
||||
let (contents, fingerprint) = read_bytes(path)?;
|
||||
Ok((headless_config(&contents, listeners)?, fingerprint))
|
||||
}
|
||||
|
||||
pub fn headless_config(contents: &[u8], listeners: &crate::settings::Listeners) -> Result<Config> {
|
||||
let mut value: serde_json::Value =
|
||||
serde_json::from_slice(contents).context("invalid --config JSON")?;
|
||||
let object = value
|
||||
.as_object_mut()
|
||||
.context("configuration file must contain a JSON object")?;
|
||||
let declared = object
|
||||
.get("listeners")
|
||||
.and_then(|item| item.get("endpoints"))
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.is_some_and(|endpoints| !endpoints.is_empty());
|
||||
if !declared {
|
||||
object.insert("listeners".into(), serde_json::to_value(listeners)?);
|
||||
}
|
||||
let listener_ids: Vec<serde_json::Value> = object
|
||||
.get("listeners")
|
||||
.and_then(|item| item.get("endpoints"))
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.map(|endpoints| {
|
||||
endpoints
|
||||
.iter()
|
||||
.filter(|endpoint| {
|
||||
endpoint
|
||||
.get("enabled")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(true)
|
||||
})
|
||||
.filter_map(|endpoint| endpoint.get("id").cloned())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
for section in ["vhosts", "redirects", "not_found_hosts"] {
|
||||
let Some(items) = object
|
||||
.get_mut(section)
|
||||
.and_then(serde_json::Value::as_array_mut)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for frontend in items.iter_mut().filter_map(|item| {
|
||||
item.get_mut("frontend")
|
||||
.and_then(serde_json::Value::as_object_mut)
|
||||
}) {
|
||||
frontend
|
||||
.entry("listener_ids")
|
||||
.or_insert_with(|| serde_json::Value::Array(listener_ids.clone()));
|
||||
}
|
||||
}
|
||||
object
|
||||
.entry("geoip_updates")
|
||||
.or_insert_with(|| serde_json::json!({ "enabled": false }));
|
||||
serde_json::from_value(value).context("invalid --config JSON")
|
||||
}
|
||||
|
||||
fn read_bytes(path: &Path) -> Result<(Vec<u8>, Fingerprint)> {
|
||||
ensure!(path.is_absolute(), "--config requires an absolute filename");
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
@@ -33,12 +104,16 @@ pub fn read(path: &Path) -> Result<(Config, Fingerprint)> {
|
||||
contents.len() <= MAX_CONFIG_BYTES,
|
||||
"configuration file exceeds size limit"
|
||||
);
|
||||
let config = serde_json::from_slice(&contents).context("invalid --config JSON")?;
|
||||
Ok((config, Sha256::digest(&contents).into()))
|
||||
let fingerprint = Sha256::digest(&contents).into();
|
||||
Ok((contents, fingerprint))
|
||||
}
|
||||
|
||||
pub fn save(path: &Path, expected: Fingerprint, config: &Config) -> Result<Fingerprint> {
|
||||
let (_, actual) = read(path)?;
|
||||
ensure!(
|
||||
!crate::runtime::headless_enabled(),
|
||||
"headless mode never writes the configuration file"
|
||||
);
|
||||
let actual = fingerprint(path)?;
|
||||
if actual != expected {
|
||||
bail!("configuration file changed externally; reload before saving");
|
||||
}
|
||||
@@ -69,7 +144,7 @@ pub fn save(path: &Path, expected: Fingerprint, config: &Config) -> Result<Finge
|
||||
let mut file = options.open(&temp)?;
|
||||
file.write_all(&bytes)?;
|
||||
file.sync_all()?;
|
||||
if read(path)?.1 != expected {
|
||||
if fingerprint(path)? != expected {
|
||||
bail!("configuration file changed during save");
|
||||
}
|
||||
fs::rename(&temp, path)?;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
static HEADLESS: std::sync::OnceLock<crate::settings::Listeners> = std::sync::OnceLock::new();
|
||||
|
||||
pub fn enable_headless(listeners: crate::settings::Listeners) -> bool {
|
||||
HEADLESS.set(listeners).is_ok()
|
||||
}
|
||||
|
||||
pub fn headless_enabled() -> bool {
|
||||
HEADLESS.get().is_some()
|
||||
}
|
||||
|
||||
pub fn headless_listeners() -> Option<&'static crate::settings::Listeners> {
|
||||
HEADLESS.get()
|
||||
}
|
||||
|
||||
pub fn ensure_headless_supported(config: &config::Config) -> anyhow::Result<()> {
|
||||
if let Some(certificate) = config.tls.certificates.iter().find(|certificate| {
|
||||
certificate
|
||||
.issuer
|
||||
.as_ref()
|
||||
.is_some_and(|issuer| issuer.auto_renew)
|
||||
}) {
|
||||
anyhow::bail!(
|
||||
"certificate {} uses ACME auto-renewal, which needs the administration panel; in headless mode renew it externally (for example with certbot) and reference the files in cert_file/key_file",
|
||||
certificate.id
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
static LAST_RELOAD: std::sync::Mutex<Option<(i64, Option<String>)>> = std::sync::Mutex::new(None);
|
||||
|
||||
pub fn record_headless_reload(error: Option<String>) {
|
||||
if let Ok(mut slot) = LAST_RELOAD.lock() {
|
||||
*slot = Some((crate::auth::now(), error));
|
||||
}
|
||||
}
|
||||
|
||||
fn last_headless_reload() -> serde_json::Value {
|
||||
match LAST_RELOAD.lock().ok().and_then(|slot| slot.clone()) {
|
||||
Some((at, error)) => json!({ "ok": error.is_none(), "at_unix": at, "error": error }),
|
||||
None => serde_json::Value::Null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
pub fn health_router(state: Arc<App>) -> axum::Router {
|
||||
axum::Router::new()
|
||||
.route("/healthz", axum::routing::get(health_status))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn health_status(axum::extract::State(state): axum::extract::State<Arc<App>>) -> Response {
|
||||
let snapshot = state.config.load();
|
||||
let pools: Vec<_> = snapshot
|
||||
.pools
|
||||
.iter()
|
||||
.map(|pool| {
|
||||
let enabled: Vec<_> = pool
|
||||
.members
|
||||
.iter()
|
||||
.filter(|member| member.definition.enabled)
|
||||
.collect();
|
||||
let healthy = enabled
|
||||
.iter()
|
||||
.filter(|member| member.state.healthy())
|
||||
.count();
|
||||
(pool.id.clone(), healthy, enabled.len())
|
||||
})
|
||||
.collect();
|
||||
let degraded: Vec<_> = pools
|
||||
.iter()
|
||||
.filter(|(_, healthy, total)| *total > 0 && *healthy == 0)
|
||||
.map(|(id, _, _)| id.clone())
|
||||
.collect();
|
||||
let status = if degraded.is_empty() {
|
||||
StatusCode::OK
|
||||
} else {
|
||||
StatusCode::SERVICE_UNAVAILABLE
|
||||
};
|
||||
let body = json!({
|
||||
"status": if degraded.is_empty() { "ok" } else { "degraded" },
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"mode": if headless_enabled() { "headless" } else { "panel" },
|
||||
"revision": snapshot.envelope.revision,
|
||||
"last_reload": last_headless_reload(),
|
||||
"uptime_seconds": state.started.elapsed().as_secs(),
|
||||
"vhosts_without_healthy_backends": degraded,
|
||||
"pools": pools
|
||||
.iter()
|
||||
.map(|(id, healthy, total)| json!({ "vhost": id, "healthy": healthy, "backends": total }))
|
||||
.collect::<Vec<_>>(),
|
||||
});
|
||||
let mut response = (status, Json(body)).into_response();
|
||||
response.headers_mut().insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
http::HeaderValue::from_static("no-store"),
|
||||
);
|
||||
response
|
||||
}
|
||||
@@ -215,3 +215,97 @@ mod cache_revision_tests {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod headless_config_tests {
|
||||
use super::*;
|
||||
|
||||
fn startup() -> crate::settings::Listeners {
|
||||
crate::settings::Listeners::from_startup(
|
||||
"127.0.0.1:8080".parse().unwrap(),
|
||||
Some("127.0.0.1:8443".parse().unwrap()),
|
||||
)
|
||||
}
|
||||
|
||||
fn policy() -> ValidationPolicy {
|
||||
ValidationPolicy {
|
||||
tls_addr: Some("127.0.0.1:8443".parse().unwrap()),
|
||||
cert_dir: None,
|
||||
data_dir: None,
|
||||
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
admin_addr: "127.0.0.1:9090".parse().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_document_gets_startup_listeners_and_all_listener_ids() {
|
||||
let document = br#"{"vhosts":[{"id":"app","frontend":{"hosts":["*"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]}]}"#;
|
||||
let config = external_config::headless_config(document, &startup()).unwrap();
|
||||
let ids: Vec<_> = config
|
||||
.listeners
|
||||
.endpoints
|
||||
.iter()
|
||||
.map(|endpoint| endpoint.id.as_str())
|
||||
.collect();
|
||||
assert_eq!(ids, ["http", "https"]);
|
||||
assert_eq!(config.vhosts[0].frontend.listener_ids, ["http", "https"]);
|
||||
assert!(!config.geoip_updates.enabled);
|
||||
let http_only =
|
||||
crate::settings::Listeners::from_startup("127.0.0.1:8080".parse().unwrap(), None);
|
||||
let config = external_config::headless_config(document, &http_only).unwrap();
|
||||
let mut policy = policy();
|
||||
policy.tls_addr = None;
|
||||
let snapshot = config::compile(config, 1, &policy).unwrap();
|
||||
assert!(snapshot
|
||||
.frontend("10.1.2.3", "127.0.0.1:8080".parse().unwrap(), false)
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_listeners_and_explicit_choices_are_kept() {
|
||||
let document = br#"{"listeners":{"endpoints":[
|
||||
{"id":"web","name":"Web","scope":"internal","enabled":true,"binding":{"address":"127.0.0.1:8080","tls":false,"http2":false}},
|
||||
{"id":"off","name":"Off","scope":"internal","enabled":false,"binding":{"address":"127.0.0.1:8081","tls":false,"http2":false}}]},
|
||||
"geoip_updates":{"enabled":true},
|
||||
"vhosts":[
|
||||
{"id":"a","frontend":{"hosts":["a.example"]},"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]},
|
||||
{"id":"b","frontend":{"hosts":["b.example"],"listener_ids":["web"]},"backends":[{"id":"b","url":"http://127.0.0.1:9002","allow_private":true}]}]}"#;
|
||||
let config = external_config::headless_config(document, &startup()).unwrap();
|
||||
assert_eq!(config.listeners.endpoints.len(), 2);
|
||||
assert_eq!(config.vhosts[0].frontend.listener_ids, ["web"]);
|
||||
assert_eq!(config.vhosts[1].frontend.listener_ids, ["web"]);
|
||||
assert!(config.geoip_updates.enabled);
|
||||
assert!(config::compile(config, 1, &policy()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_object_documents_are_rejected() {
|
||||
assert!(external_config::headless_config(b"[]", &startup()).is_err());
|
||||
assert!(external_config::headless_config(b"{\"vhosts\": [", &startup()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acme_auto_renewal_is_refused_in_headless_mode() {
|
||||
let mut config = config::Config::default();
|
||||
config.tls.certificates.push(crate::tls::Certificate {
|
||||
id: "site".into(),
|
||||
covered_hosts: Vec::new(),
|
||||
hosts: vec!["example.org".into()],
|
||||
cert_file: "site.pem".into(),
|
||||
key_file: "site.key".into(),
|
||||
issuer: Some(crate::tls::Issuer {
|
||||
provider: "cloudflare".into(),
|
||||
environment: "staging".into(),
|
||||
auto_renew: true,
|
||||
}),
|
||||
});
|
||||
assert!(ensure_headless_supported(&config).is_err());
|
||||
config.tls.certificates[0]
|
||||
.issuer
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.auto_renew = false;
|
||||
assert!(ensure_headless_supported(&config).is_ok());
|
||||
}
|
||||
}
|
||||
+17
-4
@@ -30,10 +30,17 @@ impl App {
|
||||
.await;
|
||||
};
|
||||
let (config, fingerprint) =
|
||||
tokio::task::spawn_blocking(move || external_config::read(&file))
|
||||
.await
|
||||
.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
tokio::task::spawn_blocking(move || match headless_listeners() {
|
||||
Some(listeners) => external_config::read_headless(&file, listeners),
|
||||
None => external_config::read(&file),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
|
||||
if headless_enabled() {
|
||||
ensure_headless_supported(&config)
|
||||
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
|
||||
}
|
||||
self.update_as_action(
|
||||
Update {
|
||||
expected_revision,
|
||||
@@ -98,6 +105,12 @@ impl App {
|
||||
source_revision: Option<u64>,
|
||||
reload_hash: Option<external_config::Fingerprint>,
|
||||
) -> Result<config::Envelope, ApiError> {
|
||||
if headless_enabled() && reload_hash.is_none() {
|
||||
return Err(ApiError(
|
||||
StatusCode::FORBIDDEN,
|
||||
"headless mode: the configuration file is read-only for RustProxy; edit it and reload".into(),
|
||||
));
|
||||
}
|
||||
let slot = self.update_slots.clone().try_acquire_owned().map_err(|_| {
|
||||
ApiError(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
@@ -164,7 +177,7 @@ impl App {
|
||||
let target = path.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
if let Some(reloaded) = reload_hash {
|
||||
if external_config::read(&target)?.1 != reloaded {
|
||||
if external_config::fingerprint(&target)? != reloaded {
|
||||
anyhow::bail!("configuration file changed during reload");
|
||||
}
|
||||
Ok(reloaded)
|
||||
|
||||
Reference in new issue
Block a user