This commit is contained in:
Mateusz Gruszczyński committed 2026-11-15 13:45:15 +01:00
1 parent df0e39b899
commit 21aef61dd5
35 files changed
+1360 -100

No files matched your search

+1
View File
@@ -17,6 +17,7 @@ pub(super) static READER_DOCUMENTS: &[(&str, &str, &str)] = &[
reader_doc!("docs/SCREENSHOTS.md", "guides"),
reader_doc!("docs/INSTALL.md", "guides"),
reader_doc!("docs/CONFIGURATION.md", "guides"),
reader_doc!("docs/HEADLESS.md", "guides"),
reader_doc!("docs/VHOSTS.md", "guides"),
reader_doc!("docs/CUSTOM_LOCATIONS.md", "guides"),
reader_doc!("docs/ACCESS.md", "guides"),
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.0.3",
"info": {
"title": "RustProxy Administration API",
"version": "0.37.3",
"version": "0.38.0",
"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": [
+2 -2
View File
@@ -619,7 +619,7 @@ function render() {
identity.append(title, el("div", (v.frontend?.hosts || []).join(", ") || "-", "vhost-hosts")); head.append(identity);
const actions = el("div", undefined, "entity-actions");
const configuredHosts = (v.frontend?.hosts || []).filter(Boolean);
const browseHost = configuredHosts.find(host => !host.startsWith("*.")) || configuredHosts.find(host => host.startsWith("*."))?.slice(2) || null;
const browseHost = configuredHosts.find(host => !host.startsWith("*")) || configuredHosts.find(host => host.startsWith("*."))?.slice(2) || null;
const configuredEndpoints = (v.frontend?.listener_ids || []).map(id => config.listeners?.endpoints?.find(endpoint => endpoint.id === id)).filter(Boolean);
const browseTls = configuredEndpoints.some(endpoint => endpoint.binding?.tls === true);
const openButton = button("vhOpenBrowser", () => { if (browseHost) window.open(`${browseTls ? "https" : "http"}://${browseHost}/`, "_blank", "noopener,noreferrer"); });
@@ -701,7 +701,7 @@ function render() {
if (v.acl_profile_id) policy.append(el("small", `${t("vhAclProfile")}: ${v.acl_profile_id}`, "pill"));
if (v.force_ssl) policy.append(el("small", t("vhForceSsl"), "pill"));
if (v.www_redirect) {
const destination = v.www_redirect_target || (v.frontend?.hosts || []).find(host => !host.startsWith("*.")) || "";
const destination = v.www_redirect_target || (v.frontend?.hosts || []).find(host => !host.startsWith("*")) || "";
policy.append(el("small", `WWW 308 \u2192 ${destination}`, "pill"));
}
if (v.forward_client_ip === false) policy.append(el("small", t("vhClientIpHidden"), "pill"));
+1 -1
View File
@@ -178,7 +178,7 @@ fn compile_routing(
.hosts
.iter()
.find(|name| {
!name.starts_with("*.") && name.parse::<std::net::IpAddr>().is_err()
!name.starts_with('*') && name.parse::<std::net::IpAddr>().is_err()
})
.cloned();
}
+13 -2
View File
@@ -3,7 +3,9 @@ impl Snapshot {
if let Some(value) = lookup(host) {
return Some(value);
}
let last_dot = host.rfind('.')?;
let Some(last_dot) = host.rfind('.') else {
return lookup(CATCH_ALL_HOST);
};
let mut wildcard = [0u8; 256];
wildcard[..2].copy_from_slice(b"*.");
for (index, _) in host.match_indices('.') {
@@ -23,7 +25,7 @@ impl Snapshot {
return Some(value);
}
}
None
lookup(CATCH_ALL_HOST)
}
pub fn host_allowed(&self, host: &str, peer: IpAddr) -> bool {
if self.host_acls.is_empty() {
@@ -431,6 +433,15 @@ pub fn normalize_host(value: &str) -> Result<String> {
);
Ok(host)
}
pub const CATCH_ALL_HOST: &str = "*";
pub fn normalize_frontend_host(value: &str) -> Result<String> {
if value.trim() == CATCH_ALL_HOST {
return Ok(CATCH_ALL_HOST.into());
}
normalize_host_pattern(value)
}
pub fn normalize_host_pattern(value: &str) -> Result<String> {
let value = value.trim();
if let Some(base) = value.strip_prefix("*.") {
+27
View File
@@ -25,6 +25,33 @@ mod tests {
config
}
#[test]
fn catch_all_host_serves_unmatched_names_after_exact_and_wildcard_hosts() {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
let mut catch_all = config.vhosts[0].clone();
catch_all.id = "catch-all".into();
catch_all.frontend.hosts = vec![" * ".into()];
config.vhosts.push(catch_all);
let snapshot = compile(config, 1, &policy()).unwrap();
let local = "127.0.0.1:8080".parse().unwrap();
let vhost = |host: &str| snapshot.frontend(host, local, false).map(|f| f.id.clone());
assert_eq!(vhost("localhost").as_deref(), Some("demo"));
assert_eq!(vhost("demo.localhost").as_deref(), Some("demo"));
for host in ["192.168.1.50", "app.example.org", "intranet"] {
assert_eq!(vhost(host).as_deref(), Some("catch-all"), "{host}");
assert!(snapshot.select_on(host, "/", local, false).is_some());
}
}
#[test]
fn catch_all_host_is_only_valid_alone() {
let mut config = demo_config("127.0.0.1:9000".parse().unwrap());
config.vhosts[0].frontend.hosts = vec!["*.*".into()];
assert!(compile(config.clone(), 1, &policy()).is_err());
config.vhosts[0].frontend.hosts = vec!["*".into(), "*".into()];
assert!(compile(config, 1, &policy()).is_err());
}
#[test]
fn configuration_above_legacy_limit_compiles() {
let config = config_with_large_responses(5);
+1
View File
@@ -9,4 +9,5 @@ include!("main/bootstrap.rs");
include!("main/admin_runtime.rs");
include!("main/proxy_runtime.rs");
include!("main/tasks.rs");
include!("main/headless.rs");
include!("main/shutdown/mod.rs");
+131 -40
View File
@@ -5,11 +5,34 @@ async fn run(
file_config: Option<PathBuf>,
startup_locks: rust_proxy::settings::StartupLocks,
update_check: rust_proxy::update_check::Config,
headless: bool,
) -> Result<()> {
ensure!(
startup_admin_addr.port() > 0 && options.proxy_listen.port() > 0,
"listener ports must be nonzero"
);
if headless {
ensure!(
file_config.is_some(),
"--headless requires --config /absolute/path/config.json (or RUST_PROXY_CONFIG)"
);
ensure!(!options.demo, "--headless cannot be combined with --demo");
rust_proxy::runtime::enable_headless(rust_proxy::settings::Listeners::from_startup(
options.proxy_listen,
options.tls_listen,
));
}
if let Some(health) = options.health_listen {
ensure!(
health.port() > 0
&& health.port() != options.proxy_listen.port()
&& options
.tls_listen
.is_none_or(|tls| tls.port() != health.port())
&& (headless || health.port() != startup_admin_addr.port()),
"health listener port must be nonzero and differ from the other listeners"
);
}
ensure!(
(1..=4096).contains(&options.max_connections) && (1..=4096).contains(&options.max_inflight),
"limits must be 1..4096"
@@ -22,14 +45,14 @@ async fn run(
"timeouts must be positive"
);
ensure!(
startup_admin_addr.port() != options.proxy_listen.port(),
headless || startup_admin_addr.port() != options.proxy_listen.port(),
"admin and proxy ports must differ"
);
if let Some(tls) = options.tls_listen {
ensure!(
tls.port() > 0
&& tls.port() != options.proxy_listen.port()
&& tls.port() != startup_admin_addr.port(),
&& (headless || tls.port() != startup_admin_addr.port()),
"TLS listener port must be nonzero and differ from HTTP/admin"
);
}
@@ -75,10 +98,13 @@ async fn run(
let store = Store::open(&data_dir.join("config.sqlite3"), &initial).await?;
let mut saved = store.load().await?;
let external = if let Some(path) = file_config {
Some((
path.clone(),
rust_proxy::runtime::external_config::read(&path)?,
))
let loaded = match rust_proxy::runtime::headless_listeners() {
Some(listeners) => {
rust_proxy::runtime::external_config::read_headless(&path, listeners)?
}
None => rust_proxy::runtime::external_config::read(&path)?,
};
Some((path.clone(), loaded))
} else {
None
};
@@ -87,6 +113,9 @@ async fn run(
if let Some((_, (config, _))) = &external {
saved.config = config.clone();
}
if headless {
rust_proxy::runtime::ensure_headless_supported(&saved.config)?;
}
startup_locks.ensure_config(&mut saved.config);
let changed_on_disk =
external.is_some() && serde_json::to_value(&saved.config)? != stored_document;
@@ -100,15 +129,16 @@ async fn run(
.config
.administration
.resolved_listen(startup_admin_addr);
let admin_tls_enabled = saved.config.administration.tls;
let remote_admin =
validate_admin_binding(admin_addr, admin_tls_enabled, options.allow_remote_admin)?;
let admin_tls_enabled = saved.config.administration.tls && !headless;
let remote_admin = !headless
&& validate_admin_binding(admin_addr, admin_tls_enabled, options.allow_remote_admin)?;
ensure!(
admin_addr.port() != options.proxy_listen.port()
&& options
.tls_listen
.is_none_or(|tls| tls.port() != admin_addr.port())
&& (!options.demo || options.demo_listen.port() != admin_addr.port()),
headless
|| admin_addr.port() != options.proxy_listen.port()
&& options
.tls_listen
.is_none_or(|tls| tls.port() != admin_addr.port())
&& (!options.demo || options.demo_listen.port() != admin_addr.port()),
"active administration port conflicts with another startup listener"
);
let resolved_policy = ValidationPolicy {
@@ -154,7 +184,9 @@ async fn run(
);
}
rust_proxy::logging::configure_error_log(snapshot.envelope.config.error_log.clone());
let admin_tls_config = {
let admin_tls_config = if headless {
None
} else {
let tls = snapshot.envelope.config.tls.clone();
let administration = snapshot.envelope.config.administration.clone();
let cert_dir = policy.cert_dir.clone();
@@ -165,7 +197,7 @@ async fn run(
};
let setup_required = store.admin_record().await?.is_none();
let authentication = auth::Auth::new(store.clone(), data_dir.clone()).await?;
if !setup_required {
if !setup_required || headless {
authentication.remove_bootstrap_files().await;
}
let renewal_observations = store.load_certificate_renewals().await?;
@@ -175,6 +207,10 @@ async fn run(
geoip_format,
) {
Ok(database) => std::sync::Arc::new(database),
Err(error) if headless && !snapshot.envelope.config.geoip_updates.enabled => {
tracing::debug!(%error, "GeoIP country database not installed");
std::sync::Arc::new(rust_proxy::geoip::Database::empty())
}
Err(error) => {
tracing::warn!(%error, "GeoIP country database unavailable; country allow lists fail closed");
std::sync::Arc::new(rust_proxy::geoip::Database::empty())
@@ -273,9 +309,23 @@ async fn run(
} else {
None
};
let admin_listener = TcpListener::bind(admin_addr)
.await
.context("cannot bind admin listener")?;
let admin_listener = if headless {
None
} else {
Some(
TcpListener::bind(admin_addr)
.await
.context("cannot bind admin listener")?,
)
};
let health_listener = match options.health_listen {
Some(address) => Some(
TcpListener::bind(address)
.await
.with_context(|| format!("cannot bind health listener {address}"))?,
),
None => None,
};
let demo_listener = if options.demo {
Some(
TcpListener::bind(options.demo_listen)
@@ -287,7 +337,9 @@ async fn run(
};
state.start_geoip_updates();
state.start_dns_acl_updates();
state.start_update_check(update_check);
if !headless {
state.start_update_check(update_check);
}
let shutdown = state.shutdown.clone();
let grace = Duration::from_secs(options.shutdown_timeout_secs);
let mut tasks = JoinSet::new();
@@ -332,26 +384,46 @@ async fn run(
metrics,
));
}
if let Some(tls) = admin_tls_config {
tasks.spawn(rust_proxy::server::serve_tls_with_plain_redirect(
admin_listener,
rust_proxy::admin::router(state.clone()),
rust_proxy::admin::https_redirect_router(),
shutdown.clone(),
32,
grace,
tls,
));
} else {
if let Some(listener) = health_listener {
tasks.spawn(rust_proxy::server::serve(
admin_listener,
rust_proxy::admin::router(state.clone()),
listener,
rust_proxy::runtime::health_router(state.clone()),
shutdown.clone(),
32,
16,
grace,
None,
));
}
let _pid_file = if headless {
Some(HeadlessPidFile::create(&data_dir)?)
} else {
None
};
if headless {
tasks.spawn(headless_reload_loop(state.clone(), shutdown.clone()));
}
if let Some(admin_listener) = admin_listener {
if let Some(tls) = admin_tls_config {
tasks.spawn(rust_proxy::server::serve_tls_with_plain_redirect(
admin_listener,
rust_proxy::admin::router(state.clone()),
rust_proxy::admin::https_redirect_router(),
shutdown.clone(),
32,
grace,
tls,
));
} else {
tasks.spawn(rust_proxy::server::serve(
admin_listener,
rust_proxy::admin::router(state.clone()),
shutdown.clone(),
32,
grace,
None,
));
}
}
if let Some(listener) = metrics_listener {
tasks.spawn(rust_proxy::server::serve(
listener,
@@ -403,10 +475,26 @@ async fn run(
stream.id
);
}
println!(
" Panel: {}://{admin_addr}",
if admin_tls_enabled { "https" } else { "http" }
);
if headless {
if let Some(path) = state
.config_file
.lock()
.await
.as_ref()
.map(|(path, _)| path.clone())
{
println!(" Mode: headless, configuration {}", path.display());
}
println!(
" Reload: systemctl reload rustproxy, kill -HUP {}, or rust-proxy --headless reload",
std::process::id()
);
} else {
println!(
" Panel: {}://{admin_addr}",
if admin_tls_enabled { "https" } else { "http" }
);
}
if remote_admin && !admin_tls_enabled {
tracing::warn!(
"REMOTE ADMIN ENABLED OVER PLAIN HTTP: credentials and session cookies can be exposed; restrict access with a firewall/private network and prefer a protected tunnel"
@@ -418,7 +506,10 @@ async fn run(
state.active_prometheus.listen, state.active_prometheus.path
);
}
if setup_required {
if let Some(address) = options.health_listen {
println!(" Health: http://{address}/healthz");
}
if !headless && setup_required {
println!(
" Setup: rust-proxy --data-dir {} admin setup-token",
data_dir.display()
@@ -427,7 +518,7 @@ async fn run(
" Or: rust-proxy --data-dir {} admin init --username YOUR_NAME",
data_dir.display()
);
} else {
} else if !headless {
println!(" Sign in with your administrator account.");
}
println!(" Source: https://git.linuxiarz.pl/gru/RustProxy");
+29
View File
@@ -70,6 +70,14 @@ struct Cli {
_accept_remote_admin_risk: bool,
#[arg(long, global = true)]
livelogs: bool,
#[arg(
long,
global = true,
env = "RUST_PROXY_HEADLESS",
action = clap::ArgAction::SetTrue,
value_parser = clap::builder::BoolishValueParser::new()
)]
headless: bool,
#[command(subcommand)]
command: Option<Command>,
}
@@ -183,6 +191,8 @@ struct ServeOptions {
shutdown_timeout_secs: u64,
#[arg(long)]
allow_remote_admin: bool,
#[arg(long, env = "RUST_PROXY_HEALTH_LISTEN")]
health_listen: Option<SocketAddr>,
}
#[cfg(target_os = "linux")]
fn disable_transparent_huge_pages() {
@@ -316,6 +326,24 @@ async fn application() -> Result<()> {
.command
.context("a subcommand is required (or use --livelogs)")?;
match command {
Command::Reload if cli.headless => {
signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit))
}
Command::Config {
action: ConfigCommand::Reload,
} if cli.headless => {
signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit))
}
Command::Config {
action: ConfigCommand::Validate { file },
} if cli.headless => {
validate_headless_file(
resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
cli.admin_listen,
file,
)
.await
}
Command::Reload => {
config_command(
resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
@@ -374,6 +402,7 @@ async fn application() -> Result<()> {
cli.config,
startup_locks,
update_check,
cli.headless,
)
.await
}
+169
View File
@@ -0,0 +1,169 @@
const HEADLESS_PID_FILE: &str = "rustproxy.pid";
struct HeadlessPidFile(PathBuf);
impl HeadlessPidFile {
fn create(data_dir: &Path) -> Result<Self> {
let path = data_dir.join(HEADLESS_PID_FILE);
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
}
let mut file = options
.open(&path)
.with_context(|| format!("cannot write {}", path.display()))?;
writeln!(file, "{}", std::process::id())?;
Ok(Self(path))
}
}
impl Drop for HeadlessPidFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
async fn headless_reload_loop(
state: Arc<App>,
shutdown: tokio_util::sync::CancellationToken,
) -> Result<()> {
#[cfg(unix)]
{
let mut hangup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
loop {
tokio::select! {
_ = shutdown.cancelled() => return Ok(()),
_ = hangup.recv() => {
let revision = state.config.load().envelope.revision;
match state.reload_from_file(revision).await {
Ok(envelope) => {
rust_proxy::runtime::record_headless_reload(None);
tracing::info!(
revision = envelope.revision,
"headless configuration reloaded; listener changes need a restart"
)
}
Err(error) => {
rust_proxy::runtime::record_headless_reload(Some(error.1.clone()));
tracing::error!(
error = %error.1,
"headless configuration reload rejected; the running configuration is unchanged"
)
}
}
}
}
}
}
#[cfg(not(unix))]
{
let _ = state;
shutdown.cancelled().await;
Ok(())
}
}
fn signal_headless_reload(data_dir: &Path) -> Result<()> {
let path = data_dir.join(HEADLESS_PID_FILE);
let text = std::fs::read_to_string(&path).with_context(|| {
format!(
"{} not found; is rust-proxy serve --headless running with --data-dir {}?",
path.display(),
data_dir.display()
)
})?;
let pid: i32 = text
.trim()
.parse()
.with_context(|| format!("invalid process id in {}", path.display()))?;
ensure!(pid > 1, "invalid process id in {}", path.display());
#[cfg(target_os = "linux")]
{
let command = std::fs::read(format!("/proc/{pid}/cmdline")).unwrap_or_default();
ensure!(
String::from_utf8_lossy(&command).contains("rust-proxy"),
"process {pid} from {} is not a running RustProxy; remove the stale file",
path.display()
);
}
#[cfg(unix)]
{
let result = unsafe { libc::kill(pid, libc::SIGHUP) };
ensure!(
result == 0,
"cannot signal RustProxy process {pid}: {}",
io::Error::last_os_error()
);
println!(
"Reload requested (SIGHUP to process {pid}); the result is written to the service log."
);
Ok(())
}
#[cfg(not(unix))]
{
let _ = pid;
bail!("headless reload by signal is only available on Unix")
}
}
async fn validate_headless_file(
data_dir: PathBuf,
admin_addr: SocketAddr,
file: PathBuf,
) -> Result<()> {
let proxy_addr: SocketAddr = std::env::var("RUST_PROXY_PROXY_LISTEN")
.unwrap_or_else(|_| "127.0.0.1:8080".into())
.parse()?;
let tls_addr: Option<SocketAddr> = std::env::var("RUST_PROXY_TLS_LISTEN")
.ok()
.filter(|value| !value.is_empty())
.map(|value| value.parse())
.transpose()?;
let listeners = rust_proxy::settings::Listeners::from_startup(proxy_addr, tls_addr);
let file = if file.is_absolute() {
file
} else {
std::env::current_dir()?.join(file)
};
let (config, _) = tokio::task::spawn_blocking(move || {
rust_proxy::runtime::external_config::read_headless(&file, &listeners)
})
.await??;
rust_proxy::runtime::ensure_headless_supported(&config)?;
let cert_path = data_dir.join("certs");
let scratch = if cert_path.is_dir() {
None
} else {
let scratch = std::env::temp_dir().join(format!(
"rustproxy-validate-{}",
rust_proxy::auth::random_secret()
));
let directory = scratch.clone();
tokio::task::spawn_blocking(move || rust_proxy::tls::initialize_default(&directory))
.await??;
Some(scratch)
};
let policy = ValidationPolicy {
proxy_addr,
admin_addr,
tls_addr,
cert_dir: Some(scratch.clone().unwrap_or(cert_path)),
data_dir: Some(data_dir),
};
let compiled = tokio::task::spawn_blocking(move || config::compile(config, 0, &policy)).await?;
if let Some(scratch) = scratch {
let _ = std::fs::remove_dir_all(scratch);
}
let snapshot = compiled?;
let config = &snapshot.envelope.config;
println!(
"Headless configuration valid: {} listener(s), {} vhost(s), {} backend(s). Nothing was changed.",
config.listeners.endpoints.len(),
config.vhosts.len(),
config.vhosts.iter().map(|vhost| vhost.backends.len()).sum::<usize>()
);
Ok(())
}
+2
View File
@@ -4,6 +4,8 @@ include!("runtime/constructors.rs");
include!("runtime/updates.rs");
include!("runtime/certificates.rs");
include!("runtime/docker.rs");
include!("runtime/headless.rs");
include!("runtime/health_endpoint.rs");
#[cfg(test)]
include!("runtime/tests.rs");
+9 -7
View File
@@ -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),
+79 -4
View File
@@ -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)?;
+43
View File
@@ -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,
}
}
+54
View File
@@ -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
}
+94
View File
@@ -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
View File
@@ -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)
+8 -2
View File
@@ -253,7 +253,10 @@ pub fn for_all_frontends(
certificate_ids.contains(id),
"{owner} references unknown certificate id"
);
for host in hosts {
for host in hosts
.iter()
.filter(|host| host.as_str() != crate::config::CATCH_ALL_HOST)
{
if let Some(old) = assignments.insert(host.clone(), id.to_owned()) {
ensure!(
old == id,
@@ -268,7 +271,10 @@ pub fn for_all_frontends(
let hosts = vhost.routing_hosts()?;
assign(&hosts, id, "vhost")?;
if vhost.allow_certificate_mismatch {
for host in hosts {
for host in hosts
.into_iter()
.filter(|host| host != crate::config::CATCH_ALL_HOST)
{
result.forced_mismatches.insert((id.clone(), host));
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ impl Vhost {
);
let mut hosts = std::collections::HashSet::new();
for host in &mut self.frontend.hosts {
*host = crate::config::normalize_host_pattern(host)?;
*host = crate::config::normalize_frontend_host(host)?;
ensure!(
hosts.insert(host.clone()),
"hostname {} is listed twice in this vhost",