v0.40.0
This commit is contained in:
1 parent
3b5fc8dce1
commit
748fe1d146
23 files changed
+2901
-40
No files matched your search
@@ -2,5 +2,6 @@ include!("acme/model.rs");
|
||||
include!("acme/runtime_env.rs");
|
||||
include!("acme/providers/mod.rs");
|
||||
include!("acme/jobs.rs");
|
||||
include!("acme/headless.rs");
|
||||
#[cfg(test)]
|
||||
include!("acme/tests.rs");
|
||||
@@ -0,0 +1,443 @@
|
||||
// Headless ACME: issues and renews the certificates requested with
|
||||
// `--acme-domains` through the same Certbot worker as the panel. Results are
|
||||
// kept in `<data-dir>/certs/headless-acme.json` and merged into the
|
||||
// configuration on reload, so the configuration file stays read-only.
|
||||
|
||||
const HEADLESS_ACME_ACTOR: &str = "system:headless-acme";
|
||||
const HEADLESS_ACME_CHECK_SECONDS: i64 = 12 * 3600;
|
||||
const HEADLESS_ACME_RETRY_SECONDS: [i64; 6] = [600, 1800, 3600, 3 * 3600, 6 * 3600, 12 * 3600];
|
||||
|
||||
fn headless_acme_due(
|
||||
directory: &std::path::Path,
|
||||
acme: &crate::runtime::HeadlessAcme,
|
||||
id: &str,
|
||||
names: &[String],
|
||||
) -> Result<bool, String> {
|
||||
let state = crate::runtime::read_headless_acme_state(directory).map_err(|e| format!("{e:#}"))?;
|
||||
let Some(entry) = state.get(id).filter(|entry| entry.matches(acme, names)) else {
|
||||
return Ok(true);
|
||||
};
|
||||
match crate::tls::certificate_metadata(directory, &entry.cert_file) {
|
||||
Ok(metadata) => Ok(metadata
|
||||
.days_remaining
|
||||
.is_none_or(|days| days <= acme.renew_before_days)),
|
||||
Err(_) => Ok(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn headless_acme_request(
|
||||
acme: &crate::runtime::HeadlessAcme,
|
||||
id: &str,
|
||||
names: &[String],
|
||||
) -> Result<Value, String> {
|
||||
let mut request = serde_json::json!({
|
||||
"certificate_id": id,
|
||||
"provider": acme.provider,
|
||||
"environment": acme.environment,
|
||||
"email": acme.email,
|
||||
"domains": names,
|
||||
"agree_tos": true,
|
||||
"confirm_production": acme.environment == "production",
|
||||
"propagation_seconds": acme.propagation_seconds,
|
||||
});
|
||||
if acme.provider != "http01" {
|
||||
let path = acme
|
||||
.dns_credentials
|
||||
.as_deref()
|
||||
.ok_or_else(|| "acme.secret_missing".to_owned())?;
|
||||
let fields = crate::runtime::headless_dns_credential_fields(&acme.provider, path)
|
||||
.map_err(|error| format!("{error:#}"))?;
|
||||
if let Some(object) = request.as_object_mut() {
|
||||
object.extend(fields);
|
||||
}
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn zeroize_request(request: &mut Value) {
|
||||
for key in [
|
||||
"key_secret",
|
||||
"api_token",
|
||||
"application_key",
|
||||
"application_secret",
|
||||
"consumer_key",
|
||||
] {
|
||||
if let Some(Value::String(secret)) = request.get_mut(key) {
|
||||
secret.zeroize();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn headless_acme_issue(
|
||||
state: &Arc<App>,
|
||||
acme: &crate::runtime::HeadlessAcme,
|
||||
id: &str,
|
||||
names: &[String],
|
||||
) -> Result<Certificate, String> {
|
||||
let mut request = headless_acme_request(acme, id, names)?;
|
||||
let started = Manager::start(state.clone(), request.clone(), HEADLESS_ACME_ACTOR.into()).await;
|
||||
zeroize_request(&mut request);
|
||||
let job = started.map_err(|error| error.1)?;
|
||||
tracing::info!(certificate = id, domains = ?names, provider = %acme.provider,
|
||||
environment = %acme.environment, "requesting ACME certificate");
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = state.shutdown.cancelled() => return Err("acme.cancelled".into()),
|
||||
_ = tokio::time::sleep(Duration::from_secs(2)) => {}
|
||||
}
|
||||
let Some(view) = state.acme.view().filter(|view| view.id == job.id) else {
|
||||
return Err("acme.job_lost".into());
|
||||
};
|
||||
match view.status {
|
||||
"running" => continue,
|
||||
"ready" => {
|
||||
return view
|
||||
.certificate
|
||||
.ok_or_else(|| "acme.invalid_worker_response".to_owned())
|
||||
}
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"{} (Certbot log: {})",
|
||||
view.message, view.log_directory
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn headless_acme_deploy(
|
||||
state: &Arc<App>,
|
||||
directory: &std::path::Path,
|
||||
acme: &crate::runtime::HeadlessAcme,
|
||||
names: &[String],
|
||||
auto: bool,
|
||||
certificate: Certificate,
|
||||
) -> Result<(), String> {
|
||||
let id = certificate.id.clone();
|
||||
let entry = crate::runtime::HeadlessAcmeEntry {
|
||||
provider: acme.provider.clone(),
|
||||
environment: acme.environment.clone(),
|
||||
domains: names.to_vec(),
|
||||
cert_file: certificate.cert_file.clone(),
|
||||
key_file: certificate.key_file.clone(),
|
||||
issued_at: crate::auth::now(),
|
||||
auto,
|
||||
};
|
||||
let dir = directory.to_owned();
|
||||
let record = entry.clone();
|
||||
let key = id.clone();
|
||||
let previous = tokio::task::spawn_blocking(move || {
|
||||
let mut state = crate::runtime::read_headless_acme_state(&dir)?;
|
||||
let previous = state.insert(key, record);
|
||||
crate::runtime::write_headless_acme_state(&dir, &state)?;
|
||||
Ok::<_, anyhow::Error>(previous)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "acme.validation_worker_failed".to_owned())?
|
||||
.map_err(|error| format!("{error:#}"))?;
|
||||
let mut reloaded = Err("acme.configuration_changed".to_owned());
|
||||
for _ in 0..3 {
|
||||
let revision = state.config.load().envelope.revision;
|
||||
match state.reload_from_file(revision).await {
|
||||
Ok(envelope) => {
|
||||
crate::runtime::record_headless_reload(None);
|
||||
tracing::info!(certificate = %id, revision = envelope.revision,
|
||||
"ACME certificate installed; configuration reloaded");
|
||||
reloaded = Ok(());
|
||||
break;
|
||||
}
|
||||
Err(ApiError(StatusCode::CONFLICT, _)) | Err(ApiError(StatusCode::TOO_MANY_REQUESTS, _)) => {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
Err(error) => {
|
||||
crate::runtime::record_headless_reload(Some(error.1.clone()));
|
||||
reloaded = Err(format!(
|
||||
"certificate issued and stored, but the configuration reload failed ({}); it is applied with the next successful reload",
|
||||
error.1
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(old) = previous.filter(|old| old.cert_file != entry.cert_file) {
|
||||
let in_use = state
|
||||
.config
|
||||
.load()
|
||||
.envelope
|
||||
.config
|
||||
.tls
|
||||
.certificates
|
||||
.iter()
|
||||
.any(|c| c.cert_file == old.cert_file || c.key_file == old.key_file);
|
||||
if reloaded.is_ok() && !in_use {
|
||||
for name in [old.cert_file, old.key_file] {
|
||||
if name.starts_with("acme-") && crate::tls::safe_name(&name).is_ok() {
|
||||
let _ = std::fs::remove_file(directory.join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
reloaded
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize)]
|
||||
pub struct HeadlessAcmeStatus {
|
||||
pub domains: Vec<String>,
|
||||
pub auto: bool,
|
||||
pub status: &'static str,
|
||||
pub message: String,
|
||||
pub last_attempt: Option<i64>,
|
||||
pub next_check: i64,
|
||||
pub failures: usize,
|
||||
}
|
||||
|
||||
static HEADLESS_ACME_STATUS: std::sync::Mutex<std::collections::BTreeMap<String, HeadlessAcmeStatus>> =
|
||||
std::sync::Mutex::new(std::collections::BTreeMap::new());
|
||||
|
||||
/// Status of the headless ACME certificates for the health listener.
|
||||
pub fn headless_acme_status() -> std::collections::BTreeMap<String, HeadlessAcmeStatus> {
|
||||
HEADLESS_ACME_STATUS
|
||||
.lock()
|
||||
.map(|status| status.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn set_headless_status(id: &str, update: impl FnOnce(&mut HeadlessAcmeStatus)) {
|
||||
if let Ok(mut status) = HEADLESS_ACME_STATUS.lock() {
|
||||
update(status.entry(id.to_owned()).or_default());
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes automatic certificates that are no longer wanted: their served
|
||||
/// names are gone, or every served name already has an issued replacement.
|
||||
async fn headless_acme_prune(
|
||||
state: &Arc<App>,
|
||||
directory: &std::path::Path,
|
||||
wanted: Vec<Vec<String>>,
|
||||
) {
|
||||
let served = crate::runtime::headless_served_hosts(&state.config.load().envelope.config);
|
||||
let dir = directory.to_owned();
|
||||
let removed = tokio::task::spawn_blocking(move || {
|
||||
let mut acme_state = crate::runtime::read_headless_acme_state(&dir)?;
|
||||
let wanted_ids: std::collections::HashSet<String> = wanted
|
||||
.iter()
|
||||
.map(|names| crate::runtime::headless_acme_certificate_id(names))
|
||||
.collect();
|
||||
let replaced = |name: &String| {
|
||||
wanted.iter().any(|names| {
|
||||
names.contains(name)
|
||||
&& acme_state.contains_key(&crate::runtime::headless_acme_certificate_id(names))
|
||||
})
|
||||
};
|
||||
let stale: Vec<String> = acme_state
|
||||
.iter()
|
||||
.filter(|(id, entry)| {
|
||||
entry.auto
|
||||
&& !wanted_ids.contains(*id)
|
||||
&& entry
|
||||
.domains
|
||||
.iter()
|
||||
.filter(|name| served.contains(*name))
|
||||
.all(&replaced)
|
||||
})
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
let mut files = Vec::new();
|
||||
for id in &stale {
|
||||
if let Some(entry) = acme_state.remove(id) {
|
||||
files.push(entry.cert_file);
|
||||
files.push(entry.key_file);
|
||||
}
|
||||
}
|
||||
if !stale.is_empty() {
|
||||
crate::runtime::write_headless_acme_state(&dir, &acme_state)?;
|
||||
}
|
||||
Ok::<_, anyhow::Error>((stale, files))
|
||||
})
|
||||
.await;
|
||||
let Ok(Ok((stale, files))) = removed else {
|
||||
return;
|
||||
};
|
||||
if stale.is_empty() {
|
||||
return;
|
||||
}
|
||||
let revision = state.config.load().envelope.revision;
|
||||
if state.reload_from_file(revision).await.is_ok() {
|
||||
for name in files {
|
||||
if name.starts_with("acme-") && crate::tls::safe_name(&name).is_ok() {
|
||||
let _ = std::fs::remove_file(directory.join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(mut status) = HEADLESS_ACME_STATUS.lock() {
|
||||
for id in &stale {
|
||||
status.remove(id);
|
||||
}
|
||||
}
|
||||
tracing::info!(certificates = ?stale, "automatic ACME certificates no longer needed (hosts removed or replaced) were deleted");
|
||||
}
|
||||
|
||||
/// Background task of headless mode: issues and renews the certificates of
|
||||
/// `--acme-domains` / `headless.acme.domains` and, with `auto`, of every
|
||||
/// vhost host without a certificate. Settings are re-read after each reload.
|
||||
pub async fn headless_loop(
|
||||
weak: std::sync::Weak<App>,
|
||||
shutdown: tokio_util::sync::CancellationToken,
|
||||
) {
|
||||
// Give the listeners a moment so the HTTP-01 challenge can be answered.
|
||||
tokio::select! { _ = shutdown.cancelled() => return, _ = tokio::time::sleep(Duration::from_secs(3)) => {} }
|
||||
let mut next: std::collections::HashMap<String, i64> = Default::default();
|
||||
let mut failures: std::collections::HashMap<String, usize> = Default::default();
|
||||
let mut fingerprint: Option<(String, String)> = None;
|
||||
loop {
|
||||
let Some(state) = weak.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(directory) = state.policy.cert_dir.clone() else {
|
||||
tracing::error!("headless ACME needs the certificate directory; disabled");
|
||||
return;
|
||||
};
|
||||
let acme = crate::runtime::headless_tls().and_then(|tls| tls.acme);
|
||||
if let Some(acme) = acme.clone() {
|
||||
// A changed provider/environment makes every certificate due again.
|
||||
let current = (acme.provider.clone(), acme.environment.clone());
|
||||
if fingerprint.as_ref() != Some(¤t) {
|
||||
next.clear();
|
||||
failures.clear();
|
||||
fingerprint = Some(current);
|
||||
}
|
||||
let mut wanted: Vec<(Vec<String>, bool)> = acme
|
||||
.certificates
|
||||
.iter()
|
||||
.map(|names| (names.clone(), false))
|
||||
.collect();
|
||||
if acme.auto {
|
||||
let config = state.config.load_full();
|
||||
let dir = directory.clone();
|
||||
let options = acme.clone();
|
||||
let auto = tokio::task::spawn_blocking(move || {
|
||||
crate::runtime::headless_auto_acme_groups(&config.envelope.config, &options, &dir)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
for names in auto {
|
||||
wanted.push((names, true));
|
||||
}
|
||||
}
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
wanted.retain(|(names, _)| ids.insert(crate::runtime::headless_acme_certificate_id(names)));
|
||||
if let Ok(mut status) = HEADLESS_ACME_STATUS.lock() {
|
||||
status.retain(|id, _| ids.contains(id));
|
||||
}
|
||||
for (names, auto) in &wanted {
|
||||
if shutdown.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let id = crate::runtime::headless_acme_certificate_id(names);
|
||||
let now = crate::auth::now();
|
||||
set_headless_status(&id, |entry| {
|
||||
entry.domains = names.clone();
|
||||
entry.auto = *auto;
|
||||
});
|
||||
if next.get(&id).is_some_and(|at| *at > now) {
|
||||
continue;
|
||||
}
|
||||
let dir = directory.clone();
|
||||
let check_acme = acme.clone();
|
||||
let check_id = id.clone();
|
||||
let check_names = names.clone();
|
||||
let due = tokio::task::spawn_blocking(move || {
|
||||
headless_acme_due(&dir, &check_acme, &check_id, &check_names)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| Err("acme.validation_worker_failed".into()));
|
||||
match due {
|
||||
Ok(false) => {
|
||||
next.insert(id.clone(), now + HEADLESS_ACME_CHECK_SECONDS);
|
||||
set_headless_status(&id, |entry| {
|
||||
entry.status = "valid";
|
||||
entry.message.clear();
|
||||
entry.next_check = now + HEADLESS_ACME_CHECK_SECONDS;
|
||||
});
|
||||
continue;
|
||||
}
|
||||
Ok(true) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(certificate = %id, %error, "cannot read the headless ACME state; requesting a new certificate");
|
||||
}
|
||||
}
|
||||
set_headless_status(&id, |entry| {
|
||||
entry.status = "issuing";
|
||||
entry.last_attempt = Some(now);
|
||||
});
|
||||
let result = match headless_acme_issue(&state, &acme, &id, names).await {
|
||||
Ok(certificate) => {
|
||||
headless_acme_deploy(&state, &directory, &acme, names, *auto, certificate).await
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let now = crate::auth::now();
|
||||
match result {
|
||||
Ok(()) => {
|
||||
failures.remove(&id);
|
||||
next.insert(id.clone(), now + HEADLESS_ACME_CHECK_SECONDS);
|
||||
set_headless_status(&id, |entry| {
|
||||
entry.status = "valid";
|
||||
entry.message.clear();
|
||||
entry.failures = 0;
|
||||
entry.next_check = now + HEADLESS_ACME_CHECK_SECONDS;
|
||||
});
|
||||
}
|
||||
Err(error) if error == "acme.cancelled" => return,
|
||||
Err(error) if error == "acme.job_busy" => {
|
||||
next.insert(id.clone(), now + 60);
|
||||
set_headless_status(&id, |entry| {
|
||||
entry.status = "waiting";
|
||||
entry.next_check = now + 60;
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
let count = failures.entry(id.clone()).or_default();
|
||||
let delay = HEADLESS_ACME_RETRY_SECONDS
|
||||
[(*count).min(HEADLESS_ACME_RETRY_SECONDS.len() - 1)];
|
||||
*count += 1;
|
||||
let failed = *count;
|
||||
tracing::error!(certificate = %id, domains = ?names, %error, retry_in_seconds = delay,
|
||||
"headless ACME certificate request failed");
|
||||
next.insert(id.clone(), now + delay);
|
||||
set_headless_status(&id, |entry| {
|
||||
entry.status = "failed";
|
||||
entry.message = error.clone();
|
||||
entry.failures = failed;
|
||||
entry.next_check = now + delay;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if acme.auto {
|
||||
let auto_groups = wanted
|
||||
.iter()
|
||||
.filter(|(_, auto)| *auto)
|
||||
.map(|(names, _)| names.clone())
|
||||
.collect();
|
||||
headless_acme_prune(&state, &directory, auto_groups).await;
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
let now = crate::auth::now();
|
||||
let wait = if acme.is_some() {
|
||||
next.values()
|
||||
.map(|at| at.saturating_sub(now))
|
||||
.min()
|
||||
.unwrap_or(HEADLESS_ACME_CHECK_SECONDS)
|
||||
.clamp(30, HEADLESS_ACME_CHECK_SECONDS)
|
||||
} else {
|
||||
HEADLESS_ACME_CHECK_SECONDS
|
||||
};
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => return,
|
||||
_ = crate::runtime::headless_changed() => {}
|
||||
_ = tokio::time::sleep(Duration::from_secs(wait as u64)) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
+76
-13
@@ -11,16 +11,21 @@ async fn run(
|
||||
startup_admin_addr.port() > 0 && options.proxy_listen.port() > 0,
|
||||
"listener ports must be nonzero"
|
||||
);
|
||||
let headless_options = options.headless_tls.clone().resolve(headless)?;
|
||||
if headless {
|
||||
ensure!(
|
||||
file_config.is_some(),
|
||||
"--headless requires --config /absolute/path/config.json (or RUST_PROXY_CONFIG)"
|
||||
file_config.is_some() || !headless_options.routes.is_empty(),
|
||||
"--headless requires --config /absolute/path/config.json (or RUST_PROXY_CONFIG) or at least one --route HOST=URL"
|
||||
);
|
||||
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,
|
||||
));
|
||||
rust_proxy::runtime::configure_headless_options(
|
||||
headless_options.clone(),
|
||||
data_dir.join("certs"),
|
||||
);
|
||||
}
|
||||
if let Some(health) = options.health_listen {
|
||||
ensure!(
|
||||
@@ -97,16 +102,24 @@ 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 {
|
||||
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
|
||||
let mut headless_load = None;
|
||||
let external = match rust_proxy::runtime::headless_listeners() {
|
||||
Some(listeners) => {
|
||||
let load = rust_proxy::runtime::external_config::load_headless(
|
||||
file_config.as_deref(),
|
||||
listeners,
|
||||
)?;
|
||||
let loaded = (load.config.clone(), load.fingerprint);
|
||||
headless_load = Some((load.tls, load.watch, load.added_certificates));
|
||||
Some((file_config.clone(), loaded))
|
||||
}
|
||||
None => match file_config {
|
||||
Some(path) => Some((
|
||||
Some(path.clone()),
|
||||
rust_proxy::runtime::external_config::read(&path)?,
|
||||
)),
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
let saved_revision = saved.revision;
|
||||
let stored_document = serde_json::to_value(&saved.config)?;
|
||||
@@ -229,9 +242,17 @@ async fn run(
|
||||
startup_locks,
|
||||
geoip,
|
||||
);
|
||||
if let Some((path, (_, hash))) = external {
|
||||
if let Some((Some(path), (_, hash))) = external {
|
||||
state.set_config_file(path, hash).await;
|
||||
}
|
||||
let headless_watch = headless_load.as_ref().is_some_and(|(_, watch, _)| *watch);
|
||||
let headless_tls = headless_load
|
||||
.as_ref()
|
||||
.map(|(tls, _, _)| tls.clone())
|
||||
.unwrap_or_default();
|
||||
if let Some((tls, watch, _)) = headless_load.clone() {
|
||||
rust_proxy::runtime::publish_headless_tls(tls, watch);
|
||||
}
|
||||
state
|
||||
.prometheus_token_hash
|
||||
.store(store.prometheus_token_hash().await?.map(Arc::new));
|
||||
@@ -401,6 +422,16 @@ async fn run(
|
||||
};
|
||||
if headless {
|
||||
tasks.spawn(headless_reload_loop(state.clone(), shutdown.clone()));
|
||||
// Both tasks follow reloads: ACME settings or watch targets may change.
|
||||
state.tunnels.spawn(rust_proxy::acme::headless_loop(
|
||||
Arc::downgrade(&state),
|
||||
state.shutdown.clone(),
|
||||
));
|
||||
if headless_watch {
|
||||
state
|
||||
.tunnels
|
||||
.spawn(headless_watch_loop(state.clone(), shutdown.clone()));
|
||||
}
|
||||
}
|
||||
if let Some(admin_listener) = admin_listener {
|
||||
if let Some(tls) = admin_tls_config {
|
||||
@@ -484,11 +515,43 @@ async fn run(
|
||||
.map(|(path, _)| path.clone())
|
||||
{
|
||||
println!(" Mode: headless, configuration {}", path.display());
|
||||
} else {
|
||||
println!(
|
||||
" Mode: headless, {} route(s) from the command line",
|
||||
headless_options.routes.len()
|
||||
);
|
||||
}
|
||||
if headless_watch {
|
||||
println!(" Watch: configuration and certificate files are reloaded on change");
|
||||
}
|
||||
println!(
|
||||
" Reload: systemctl reload rustproxy, kill -HUP {}, or rust-proxy --headless reload",
|
||||
std::process::id()
|
||||
);
|
||||
if let Some((_, _, added)) = &headless_load {
|
||||
if *added > 0 || headless_tls.acme.is_some() {
|
||||
println!(" TLS: {added} certificate(s) from headless TLS sources");
|
||||
}
|
||||
}
|
||||
if !headless_tls.is_empty() {
|
||||
let tls_listener = state.active_listeners.iter().any(|listener| listener.tls);
|
||||
if !tls_listener {
|
||||
tracing::warn!("headless TLS certificates are configured but no HTTPS listener is active; add --tls-listen 0.0.0.0:443 (or an https listener in the file)");
|
||||
}
|
||||
if let Some(acme) = &headless_tls.acme {
|
||||
println!(
|
||||
" ACME: {} certificate(s){}, {} via {}; state in {}",
|
||||
acme.certificates.len(),
|
||||
if acme.auto { " + automatic for vhost hosts" } else { "" },
|
||||
acme.environment,
|
||||
acme.provider,
|
||||
data_dir.join("certs").join(rust_proxy::runtime::HEADLESS_ACME_STATE).display()
|
||||
);
|
||||
if acme.provider == "http01" && !state.active_listeners.iter().any(|listener| !listener.tls) {
|
||||
tracing::warn!("ACME HTTP-01 needs a plain HTTP listener reachable on port 80");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!(
|
||||
" Panel: {}://{admin_addr}",
|
||||
|
||||
+140
-2
@@ -124,7 +124,11 @@ enum ConfigCommand {
|
||||
Get,
|
||||
Reload,
|
||||
Apply { file: PathBuf },
|
||||
Validate { file: PathBuf },
|
||||
Validate {
|
||||
file: PathBuf,
|
||||
#[command(flatten)]
|
||||
tls: Box<HeadlessTlsArgs>,
|
||||
},
|
||||
}
|
||||
#[derive(Subcommand)]
|
||||
enum BackupCommand {
|
||||
@@ -193,6 +197,139 @@ struct ServeOptions {
|
||||
allow_remote_admin: bool,
|
||||
#[arg(long, env = "RUST_PROXY_HEALTH_LISTEN")]
|
||||
health_listen: Option<SocketAddr>,
|
||||
#[command(flatten)]
|
||||
headless_tls: Box<HeadlessTlsArgs>,
|
||||
}
|
||||
|
||||
/// Headless-only TLS sources: certificate files and automatic ACME (DV) certificates.
|
||||
#[derive(Args, Clone, Default)]
|
||||
struct HeadlessTlsArgs {
|
||||
/// Certificate chain (PEM) to serve; pair each with --tls-key-file (headless only, repeatable)
|
||||
#[arg(long = "tls-cert-file", env = "RUST_PROXY_TLS_CERT_FILE", value_delimiter = ',', value_name = "PEM")]
|
||||
tls_cert_file: Vec<PathBuf>,
|
||||
/// Private key (PEM) for the --tls-cert-file at the same position
|
||||
#[arg(long = "tls-key-file", env = "RUST_PROXY_TLS_KEY_FILE", value_delimiter = ',', value_name = "PEM")]
|
||||
tls_key_file: Vec<PathBuf>,
|
||||
/// Directory with certificate/key pairs, e.g. /etc/letsencrypt/live (headless only, repeatable)
|
||||
#[arg(long = "tls-cert-dir", env = "RUST_PROXY_TLS_CERT_DIR", value_delimiter = ',', value_name = "DIR")]
|
||||
tls_cert_dir: Vec<PathBuf>,
|
||||
/// Names of one ACME certificate, comma-separated (repeat for more certificates; ';' in the environment)
|
||||
#[arg(long = "acme-domains", env = "RUST_PROXY_ACME_DOMAINS", value_delimiter = ';', value_name = "NAMES")]
|
||||
acme_domains: Vec<String>,
|
||||
/// Contact e-mail for the ACME account
|
||||
#[arg(long = "acme-email", env = "RUST_PROXY_ACME_EMAIL")]
|
||||
acme_email: Option<String>,
|
||||
/// Accept the ACME CA terms of service (Let's Encrypt Subscriber Agreement)
|
||||
#[arg(long = "acme-agree-tos", env = "RUST_PROXY_ACME_AGREE_TOS", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
acme_agree_tos: bool,
|
||||
/// Use the Let's Encrypt staging CA (untrusted test certificates, high rate limits)
|
||||
#[arg(long = "acme-staging", env = "RUST_PROXY_ACME_STAGING", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
acme_staging: bool,
|
||||
/// Challenge: http01 (default) or DNS-01 via cloudflare, ovh, rfc2136 (required for wildcards)
|
||||
#[arg(long = "acme-provider", env = "RUST_PROXY_ACME_PROVIDER",
|
||||
value_parser = ["http01", "cloudflare", "ovh", "rfc2136"])]
|
||||
acme_provider: Option<String>,
|
||||
/// Certbot-style INI file with DNS provider credentials (mode 0600)
|
||||
#[arg(long = "acme-dns-credentials", env = "RUST_PROXY_ACME_DNS_CREDENTIALS", value_name = "INI")]
|
||||
acme_dns_credentials: Option<PathBuf>,
|
||||
/// DNS-01 propagation wait in seconds [default: 60]
|
||||
#[arg(long = "acme-propagation-seconds", env = "RUST_PROXY_ACME_PROPAGATION_SECONDS",
|
||||
value_parser = clap::value_parser!(u64).range(10..=900))]
|
||||
acme_propagation_seconds: Option<u64>,
|
||||
/// Renew when this many days or fewer remain [default: 30]
|
||||
#[arg(long = "acme-renew-days", env = "RUST_PROXY_ACME_RENEW_DAYS",
|
||||
value_parser = clap::value_parser!(u64).range(1..=60))]
|
||||
acme_renew_days: Option<u64>,
|
||||
/// Also issue certificates for every vhost host that no other certificate covers
|
||||
#[arg(long = "acme-auto", env = "RUST_PROXY_ACME_AUTO", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
acme_auto: bool,
|
||||
/// Vhost without a configuration file: HOSTS=URLS, e.g. app.example.com=http://127.0.0.1:3000
|
||||
/// (repeatable; ';' between routes in the environment)
|
||||
#[arg(long = "route", env = "RUST_PROXY_ROUTES", value_delimiter = ';', value_name = "HOSTS=URLS")]
|
||||
route: Vec<String>,
|
||||
/// Redirect plain HTTP to HTTPS for --route vhosts (308)
|
||||
#[arg(long = "force-https", env = "RUST_PROXY_FORCE_HTTPS", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
force_https: bool,
|
||||
/// Reload automatically when the configuration or certificate files change
|
||||
#[arg(long = "watch", env = "RUST_PROXY_WATCH", action = clap::ArgAction::SetTrue,
|
||||
value_parser = clap::builder::BoolishValueParser::new())]
|
||||
watch: bool,
|
||||
}
|
||||
|
||||
impl HeadlessTlsArgs {
|
||||
fn requested(&self) -> bool {
|
||||
!self.tls_cert_file.is_empty()
|
||||
|| !self.tls_key_file.is_empty()
|
||||
|| !self.tls_cert_dir.is_empty()
|
||||
|| !self.acme_domains.is_empty()
|
||||
|| self.acme_auto
|
||||
|| !self.route.is_empty()
|
||||
|| self.watch
|
||||
}
|
||||
|
||||
/// Command-line headless options. ACME settings are validated when the
|
||||
/// configuration is loaded, because they may be completed by the
|
||||
/// `"headless"` section of the file.
|
||||
fn resolve(self, headless: bool) -> Result<rust_proxy::runtime::HeadlessOptions> {
|
||||
if !self.requested() {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
ensure!(
|
||||
headless,
|
||||
"--tls-cert-file, --tls-cert-dir, --acme-*, --route and --watch are headless options; in panel mode use the panel"
|
||||
);
|
||||
ensure!(
|
||||
self.tls_cert_file.len() == self.tls_key_file.len(),
|
||||
"every --tls-cert-file needs a matching --tls-key-file (in the same order)"
|
||||
);
|
||||
let cwd = std::env::current_dir()?;
|
||||
let absolute = |path: PathBuf| if path.is_absolute() { path } else { cwd.join(path) };
|
||||
let cert_files = self
|
||||
.tls_cert_file
|
||||
.into_iter()
|
||||
.zip(self.tls_key_file)
|
||||
.map(|(cert, key)| (absolute(cert), absolute(key)))
|
||||
.collect();
|
||||
let cert_dirs = self.tls_cert_dir.into_iter().map(absolute).collect();
|
||||
let acme = rust_proxy::runtime::HeadlessAcmeSettings {
|
||||
domains: self
|
||||
.acme_domains
|
||||
.into_iter()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(rust_proxy::runtime::HeadlessNames::Text)
|
||||
.collect(),
|
||||
auto: self.acme_auto,
|
||||
email: self.acme_email,
|
||||
agree_tos: self.acme_agree_tos,
|
||||
staging: self.acme_staging,
|
||||
provider: self.acme_provider,
|
||||
dns_credentials: self.acme_dns_credentials.map(absolute),
|
||||
propagation_seconds: self.acme_propagation_seconds,
|
||||
renew_days: self.acme_renew_days,
|
||||
};
|
||||
let routes = self
|
||||
.route
|
||||
.iter()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.map(|value| rust_proxy::runtime::HeadlessRoute::parse(value))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
for route in &routes {
|
||||
ensure!(ids.insert(route.id()), "--route lists the same hosts twice");
|
||||
}
|
||||
Ok(rust_proxy::runtime::HeadlessOptions {
|
||||
cert_files,
|
||||
cert_dirs,
|
||||
acme,
|
||||
routes,
|
||||
force_https: self.force_https,
|
||||
watch: self.watch,
|
||||
})
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
fn disable_transparent_huge_pages() {
|
||||
@@ -335,12 +472,13 @@ async fn application() -> Result<()> {
|
||||
signal_headless_reload(&resolve_installed_data_dir(cli.data_dir, data_dir_explicit))
|
||||
}
|
||||
Command::Config {
|
||||
action: ConfigCommand::Validate { file },
|
||||
action: ConfigCommand::Validate { file, tls },
|
||||
} if cli.headless => {
|
||||
validate_headless_file(
|
||||
resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
|
||||
cli.admin_listen,
|
||||
file,
|
||||
tls.resolve(true)?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
+136
-3
@@ -113,6 +113,7 @@ async fn validate_headless_file(
|
||||
data_dir: PathBuf,
|
||||
admin_addr: SocketAddr,
|
||||
file: PathBuf,
|
||||
headless: rust_proxy::runtime::HeadlessOptions,
|
||||
) -> Result<()> {
|
||||
let proxy_addr: SocketAddr = std::env::var("RUST_PROXY_PROXY_LISTEN")
|
||||
.unwrap_or_else(|_| "127.0.0.1:8080".into())
|
||||
@@ -128,12 +129,20 @@ async fn validate_headless_file(
|
||||
} else {
|
||||
std::env::current_dir()?.join(file)
|
||||
};
|
||||
let (config, _) = tokio::task::spawn_blocking(move || {
|
||||
rust_proxy::runtime::external_config::read_headless(&file, &listeners)
|
||||
let cert_path = data_dir.join("certs");
|
||||
let state_dir = cert_path.clone();
|
||||
let options = headless.clone();
|
||||
let load = tokio::task::spawn_blocking(move || {
|
||||
rust_proxy::runtime::external_config::load_headless_with(
|
||||
Some(&file),
|
||||
&listeners,
|
||||
&options,
|
||||
Some(&state_dir),
|
||||
)
|
||||
})
|
||||
.await??;
|
||||
let (config, added, tls, watch) = (load.config, load.added_certificates, load.tls, load.watch);
|
||||
rust_proxy::runtime::ensure_headless_supported(&config)?;
|
||||
let cert_path = data_dir.join("certs");
|
||||
let scratch = if cert_path.is_dir() {
|
||||
None
|
||||
} else {
|
||||
@@ -165,5 +174,129 @@ async fn validate_headless_file(
|
||||
config.vhosts.len(),
|
||||
config.vhosts.iter().map(|vhost| vhost.backends.len()).sum::<usize>()
|
||||
);
|
||||
if !headless.routes.is_empty() {
|
||||
println!("Routes from --route: {}.", headless.routes.len());
|
||||
}
|
||||
if !tls.is_empty() {
|
||||
println!("Headless TLS sources: {added} certificate(s) loaded from files or issued earlier.");
|
||||
if let Some(acme) = &tls.acme {
|
||||
println!(
|
||||
"ACME: {} certificate(s) requested{} ({}, {}); missing ones are issued when the service starts.",
|
||||
acme.certificates.len(),
|
||||
if acme.auto { " + automatic for vhost hosts" } else { "" },
|
||||
acme.provider,
|
||||
acme.environment
|
||||
);
|
||||
}
|
||||
}
|
||||
if watch {
|
||||
println!("Watch: the service reloads automatically when these files change.");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fingerprint of everything a headless reload reads from disk: the
|
||||
/// configuration file, certificate files and the contents of certificate
|
||||
/// directories (symbolic links are followed, so a Certbot renewal is seen).
|
||||
async fn headless_watch_stamp(state: &Arc<App>) -> Vec<(PathBuf, [i64; 4])> {
|
||||
let file = state
|
||||
.config_file
|
||||
.lock()
|
||||
.await
|
||||
.as_ref()
|
||||
.map(|(path, _)| path.clone());
|
||||
let tls = rust_proxy::runtime::headless_tls().unwrap_or_default();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
fn stamp(path: &Path) -> [i64; 4] {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) => {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
[meta.mtime(), meta.mtime_nsec(), meta.size() as i64, meta.ino() as i64]
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let modified = meta
|
||||
.modified()
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|time| time.as_nanos() as i64)
|
||||
.unwrap_or(0);
|
||||
[modified, 0, meta.len() as i64, 0]
|
||||
}
|
||||
}
|
||||
Err(_) => [0; 4],
|
||||
}
|
||||
}
|
||||
let mut paths: Vec<PathBuf> = file.into_iter().collect();
|
||||
for (cert, key) in &tls.cert_files {
|
||||
paths.push(cert.clone());
|
||||
paths.push(key.clone());
|
||||
}
|
||||
paths.extend(tls.cert_dirs.iter().cloned());
|
||||
let files_only = rust_proxy::runtime::HeadlessTls {
|
||||
cert_dirs: tls.cert_dirs.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
if let Ok(found) = rust_proxy::runtime::headless_tls_certificates(&files_only, None) {
|
||||
for certificate in found {
|
||||
paths.push(PathBuf::from(certificate.cert_file));
|
||||
paths.push(PathBuf::from(certificate.key_file));
|
||||
}
|
||||
}
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
paths
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
let value = stamp(&path);
|
||||
(path, value)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `--watch`: reloads when a watched file has changed and then stayed
|
||||
/// unchanged for one more poll (so half-written files are not applied).
|
||||
async fn headless_watch_loop(state: Arc<App>, shutdown: tokio_util::sync::CancellationToken) {
|
||||
let mut applied = headless_watch_stamp(&state).await;
|
||||
let mut pending: Option<Vec<(PathBuf, [i64; 4])>> = None;
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => return,
|
||||
_ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {}
|
||||
}
|
||||
let current = headless_watch_stamp(&state).await;
|
||||
if current == applied {
|
||||
pending = None;
|
||||
continue;
|
||||
}
|
||||
if pending.as_ref() != Some(¤t) {
|
||||
pending = Some(current);
|
||||
continue;
|
||||
}
|
||||
pending = None;
|
||||
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,
|
||||
"file change detected; headless configuration reloaded"
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
rust_proxy::runtime::record_headless_reload(Some(error.1.clone()));
|
||||
tracing::error!(
|
||||
error = %error.1,
|
||||
"file change detected but the reload was rejected; the running configuration is unchanged"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Re-read after the reload: the watched set may have changed.
|
||||
applied = headless_watch_stamp(&state).await;
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,8 @@ async fn read_external_pem(file: PathBuf, private: bool) -> Result<Zeroizing<Vec
|
||||
}
|
||||
async fn config_command(dir: PathBuf, addr: SocketAddr, action: ConfigCommand) -> Result<()> {
|
||||
let action = match action {
|
||||
ConfigCommand::Validate { file } => {
|
||||
ConfigCommand::Validate { file, tls } => {
|
||||
tls.resolve(false)?;
|
||||
let config = read_config_file(file).await?;
|
||||
let proxy_addr = std::env::var("RUST_PROXY_PROXY_LISTEN")
|
||||
.unwrap_or_else(|_| "127.0.0.1:8080".into())
|
||||
|
||||
@@ -5,7 +5,10 @@ include!("runtime/updates.rs");
|
||||
include!("runtime/certificates.rs");
|
||||
include!("runtime/docker.rs");
|
||||
include!("runtime/headless.rs");
|
||||
include!("runtime/headless_tls.rs");
|
||||
include!("runtime/health_endpoint.rs");
|
||||
|
||||
#[cfg(test)]
|
||||
include!("runtime/tests.rs");
|
||||
#[cfg(test)]
|
||||
include!("runtime/headless_tls_tests.rs");
|
||||
@@ -23,16 +23,106 @@ 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))
|
||||
let load = load_headless(Some(path), listeners)?;
|
||||
Ok((load.config, load.fingerprint))
|
||||
}
|
||||
|
||||
/// A headless configuration with every command-line and file TLS source applied.
|
||||
pub struct HeadlessLoad {
|
||||
pub config: Config,
|
||||
pub fingerprint: Fingerprint,
|
||||
/// Effective TLS sources (command line + `"headless"` section of the file).
|
||||
pub tls: crate::runtime::HeadlessTls,
|
||||
/// Number of certificates the TLS sources added.
|
||||
pub added_certificates: usize,
|
||||
/// Automatic reload on file changes (`--watch` or `"headless": {"watch": true}`).
|
||||
pub watch: bool,
|
||||
}
|
||||
|
||||
/// Loads the headless configuration with the options registered at start.
|
||||
/// Without a file (only `--route`) an empty document is used.
|
||||
pub fn load_headless(
|
||||
path: Option<&Path>,
|
||||
listeners: &crate::settings::Listeners,
|
||||
) -> Result<HeadlessLoad> {
|
||||
let default = crate::runtime::HeadlessOptions::default();
|
||||
let options = crate::runtime::headless_options().unwrap_or(&default);
|
||||
load_headless_with(
|
||||
path,
|
||||
listeners,
|
||||
options,
|
||||
crate::runtime::headless_cert_dir(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn load_headless_with(
|
||||
path: Option<&Path>,
|
||||
listeners: &crate::settings::Listeners,
|
||||
options: &crate::runtime::HeadlessOptions,
|
||||
cert_dir: Option<&Path>,
|
||||
) -> Result<HeadlessLoad> {
|
||||
let (contents, fingerprint) = match path {
|
||||
Some(path) => read_bytes(path)?,
|
||||
None => {
|
||||
let contents = b"{}".to_vec();
|
||||
let fingerprint = Sha256::digest(&contents).into();
|
||||
(contents, fingerprint)
|
||||
}
|
||||
};
|
||||
let (mut config, file) = headless_document(&contents, listeners, options)?;
|
||||
let base = match path.and_then(Path::parent) {
|
||||
Some(parent) => parent.to_owned(),
|
||||
None => std::env::current_dir()?,
|
||||
};
|
||||
let tls = options.resolve(&file, &base)?;
|
||||
let added_certificates = crate::runtime::apply_headless_tls(&mut config, &tls, cert_dir)?;
|
||||
Ok(HeadlessLoad {
|
||||
config,
|
||||
fingerprint,
|
||||
tls,
|
||||
added_certificates,
|
||||
watch: options.watch || file.watch,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads a headless document without command-line options; the `"headless"`
|
||||
/// section is accepted and ignored.
|
||||
pub fn headless_config(contents: &[u8], listeners: &crate::settings::Listeners) -> Result<Config> {
|
||||
Ok(headless_document(contents, listeners, &Default::default())?.0)
|
||||
}
|
||||
|
||||
fn headless_document(
|
||||
contents: &[u8],
|
||||
listeners: &crate::settings::Listeners,
|
||||
options: &crate::runtime::HeadlessOptions,
|
||||
) -> Result<(Config, crate::runtime::HeadlessFileSettings)> {
|
||||
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 settings: crate::runtime::HeadlessFileSettings = match object.remove("headless") {
|
||||
Some(section) => serde_json::from_value(section).context("invalid \"headless\" section")?,
|
||||
None => Default::default(),
|
||||
};
|
||||
if !options.routes.is_empty() {
|
||||
let vhosts = object
|
||||
.entry("vhosts")
|
||||
.or_insert_with(|| serde_json::Value::Array(Vec::new()))
|
||||
.as_array_mut()
|
||||
.context("\"vhosts\" must be an array")?;
|
||||
for route in &options.routes {
|
||||
let id = route.id();
|
||||
ensure!(
|
||||
!vhosts
|
||||
.iter()
|
||||
.any(|vhost| vhost.get("id").and_then(serde_json::Value::as_str)
|
||||
== Some(id.as_str())),
|
||||
"--route vhost id {id} is already used in the configuration file"
|
||||
);
|
||||
vhosts.push(route.vhost_json(options.force_https));
|
||||
}
|
||||
}
|
||||
let declared = object
|
||||
.get("listeners")
|
||||
.and_then(|item| item.get("endpoints"))
|
||||
@@ -77,7 +167,8 @@ pub fn headless_config(contents: &[u8], listeners: &crate::settings::Listeners)
|
||||
object
|
||||
.entry("geoip_updates")
|
||||
.or_insert_with(|| serde_json::json!({ "enabled": false }));
|
||||
serde_json::from_value(value).context("invalid --config JSON")
|
||||
let config = serde_json::from_value(value).context("invalid --config JSON")?;
|
||||
Ok((config, settings))
|
||||
}
|
||||
|
||||
fn read_bytes(path: &Path) -> Result<(Vec<u8>, Fingerprint)> {
|
||||
|
||||
@@ -0,0 +1,987 @@
|
||||
// Headless TLS sources given on the command line (or in the service
|
||||
// environment): certificate files, certificate directories and certificates
|
||||
// issued by the headless ACME loop. They are merged into the configuration
|
||||
// read from `--config` on every start, reload and `config validate`; the file
|
||||
// itself is never changed.
|
||||
|
||||
/// File in `<data-dir>/certs` recording the certificates issued in headless mode.
|
||||
pub const HEADLESS_ACME_STATE: &str = "headless-acme.json";
|
||||
const HEADLESS_ACME_STATE_LIMIT: u64 = 262_144;
|
||||
const MAX_HEADLESS_TLS_CERTIFICATES: usize = 256;
|
||||
pub const MAX_HEADLESS_ACME_CERTIFICATES: usize = 32;
|
||||
const MAX_HEADLESS_ACME_NAMES: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HeadlessTls {
|
||||
/// Absolute (certificate chain, private key) pairs.
|
||||
pub cert_files: Vec<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
/// Absolute directories scanned for certificate/key pairs on every load.
|
||||
pub cert_dirs: Vec<std::path::PathBuf>,
|
||||
pub acme: Option<HeadlessAcme>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HeadlessAcme {
|
||||
/// One entry per certificate; each holds 1..=16 normalized names
|
||||
/// (`*.example.com` for wildcards).
|
||||
pub certificates: Vec<Vec<String>>,
|
||||
pub email: String,
|
||||
/// `production` or `staging`.
|
||||
pub environment: String,
|
||||
/// `http01`, `cloudflare`, `ovh` or `rfc2136`.
|
||||
pub provider: String,
|
||||
/// Certbot-style INI credentials for DNS-01 providers.
|
||||
pub dns_credentials: Option<std::path::PathBuf>,
|
||||
pub propagation_seconds: u64,
|
||||
pub renew_before_days: i64,
|
||||
/// Also issue certificates for every vhost/redirect host that no other
|
||||
/// certificate covers (like a Traefik certificate resolver on all routers).
|
||||
pub auto: bool,
|
||||
}
|
||||
|
||||
impl HeadlessTls {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.cert_files.is_empty() && self.cert_dirs.is_empty() && self.acme.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
impl HeadlessAcme {
|
||||
pub fn validate(&self) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
(self.auto || !self.certificates.is_empty())
|
||||
&& self.certificates.len() <= MAX_HEADLESS_ACME_CERTIFICATES,
|
||||
"ACME needs --acme-domains (up to {MAX_HEADLESS_ACME_CERTIFICATES} certificates) or --acme-auto"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
matches!(
|
||||
self.provider.as_str(),
|
||||
"http01" | "cloudflare" | "ovh" | "rfc2136"
|
||||
),
|
||||
"--acme-provider must be http01, cloudflare, ovh or rfc2136"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
matches!(self.environment.as_str(), "production" | "staging"),
|
||||
"invalid ACME environment"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
valid_acme_email(&self.email),
|
||||
"--acme-email must be a valid e-mail address (the CA sends expiry notices to it)"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
(10..=900).contains(&self.propagation_seconds),
|
||||
"--acme-propagation-seconds must be 10..900"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
(1..=60).contains(&self.renew_before_days),
|
||||
"--acme-renew-days must be 1..60"
|
||||
);
|
||||
if self.provider == "http01" {
|
||||
anyhow::ensure!(
|
||||
self.dns_credentials.is_none(),
|
||||
"--acme-dns-credentials needs a DNS provider (--acme-provider cloudflare|ovh|rfc2136)"
|
||||
);
|
||||
} else {
|
||||
let path = self.dns_credentials.as_deref().ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"--acme-provider {} needs --acme-dns-credentials /path/to/credentials.ini",
|
||||
self.provider
|
||||
)
|
||||
})?;
|
||||
anyhow::ensure!(
|
||||
path.is_absolute(),
|
||||
"--acme-dns-credentials requires an absolute path"
|
||||
);
|
||||
}
|
||||
let mut ids = std::collections::HashSet::new();
|
||||
for names in &self.certificates {
|
||||
anyhow::ensure!(
|
||||
!names.is_empty() && names.len() <= MAX_HEADLESS_ACME_NAMES,
|
||||
"--acme-domains: each certificate takes 1..{MAX_HEADLESS_ACME_NAMES} names"
|
||||
);
|
||||
if self.provider == "http01" {
|
||||
if let Some(name) = names.iter().find(|name| name.starts_with("*.")) {
|
||||
anyhow::bail!(
|
||||
"wildcard {name} needs DNS-01 validation; use --acme-provider cloudflare|ovh|rfc2136 with --acme-dns-credentials"
|
||||
);
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(
|
||||
ids.insert(headless_acme_certificate_id(names)),
|
||||
"--acme-domains lists the same certificate twice"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_acme_email(value: &str) -> bool {
|
||||
let Some((local, domain)) = value.split_once('@') else {
|
||||
return false;
|
||||
};
|
||||
value.len() <= 254
|
||||
&& value.is_ascii()
|
||||
&& !local.is_empty()
|
||||
&& !value.bytes().any(|byte| byte.is_ascii_whitespace())
|
||||
&& !domain.contains('@')
|
||||
&& domain
|
||||
.split_once('.')
|
||||
.is_some_and(|(left, right)| !left.is_empty() && !right.is_empty())
|
||||
}
|
||||
|
||||
/// Parses one `--acme-domains` value (`example.com,www.example.com`).
|
||||
pub fn parse_headless_acme_names(value: &str) -> anyhow::Result<Vec<String>> {
|
||||
let mut names = Vec::new();
|
||||
for raw in value.split(',').map(str::trim).filter(|raw| !raw.is_empty()) {
|
||||
let lowered = raw.to_ascii_lowercase();
|
||||
let lowered = lowered.trim_end_matches('.');
|
||||
let (wildcard, base) = match lowered.strip_prefix("*.") {
|
||||
Some(base) => (true, base),
|
||||
None => (false, lowered),
|
||||
};
|
||||
let normalized = crate::config::normalize_host(base)
|
||||
.map_err(|_| anyhow::anyhow!("invalid ACME domain name: {raw}"))?;
|
||||
anyhow::ensure!(
|
||||
normalized.contains('.')
|
||||
&& normalized.parse::<std::net::IpAddr>().is_err()
|
||||
&& !normalized.contains('*'),
|
||||
"ACME issues certificates for DNS names only: {raw}"
|
||||
);
|
||||
let name = if wildcard {
|
||||
format!("*.{normalized}")
|
||||
} else {
|
||||
normalized
|
||||
};
|
||||
if !names.contains(&name) {
|
||||
names.push(name);
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(
|
||||
!names.is_empty(),
|
||||
"--acme-domains needs at least one domain name"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
names.len() <= MAX_HEADLESS_ACME_NAMES,
|
||||
"--acme-domains: at most {MAX_HEADLESS_ACME_NAMES} names per certificate"
|
||||
);
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn id_label(value: &str, limit: usize) -> String {
|
||||
let mut label: String = value
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => c,
|
||||
'*' => 'w',
|
||||
_ => '-',
|
||||
})
|
||||
.collect();
|
||||
label.truncate(limit);
|
||||
let label = label.trim_matches('-').to_owned();
|
||||
if label.is_empty() {
|
||||
"cert".into()
|
||||
} else {
|
||||
label
|
||||
}
|
||||
}
|
||||
|
||||
fn short_digest(value: &[u8]) -> String {
|
||||
Sha256::digest(value)
|
||||
.iter()
|
||||
.take(4)
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Stable certificate id of a headless ACME certificate (independent of name order).
|
||||
pub fn headless_acme_certificate_id(names: &[String]) -> String {
|
||||
let mut sorted = names.to_vec();
|
||||
sorted.sort();
|
||||
format!(
|
||||
"hl-acme-{}-{}",
|
||||
id_label(names.first().map(String::as_str).unwrap_or("cert"), 40),
|
||||
short_digest(sorted.join(",").as_bytes())
|
||||
)
|
||||
}
|
||||
|
||||
fn headless_file_certificate_id(label: &str, cert: &std::path::Path) -> String {
|
||||
format!(
|
||||
"hl-file-{}-{}",
|
||||
id_label(label, 40),
|
||||
short_digest(cert.as_os_str().as_encoded_bytes())
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HeadlessAcmeEntry {
|
||||
pub provider: String,
|
||||
pub environment: String,
|
||||
pub domains: Vec<String>,
|
||||
pub cert_file: String,
|
||||
pub key_file: String,
|
||||
#[serde(default)]
|
||||
pub issued_at: i64,
|
||||
/// Issued by `acme.auto` for vhost hosts rather than listed explicitly.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub auto: bool,
|
||||
}
|
||||
|
||||
impl HeadlessAcmeEntry {
|
||||
pub fn matches(&self, acme: &HeadlessAcme, names: &[String]) -> bool {
|
||||
let mut left = self.domains.clone();
|
||||
let mut right = names.to_vec();
|
||||
left.sort();
|
||||
right.sort();
|
||||
self.provider == acme.provider && self.environment == acme.environment && left == right
|
||||
}
|
||||
|
||||
pub fn matches_settings(&self, acme: &HeadlessAcme) -> bool {
|
||||
self.provider == acme.provider && self.environment == acme.environment
|
||||
}
|
||||
}
|
||||
|
||||
pub type HeadlessAcmeState = std::collections::BTreeMap<String, HeadlessAcmeEntry>;
|
||||
|
||||
pub fn read_headless_acme_state(cert_dir: &std::path::Path) -> anyhow::Result<HeadlessAcmeState> {
|
||||
use std::io::Read;
|
||||
let path = cert_dir.join(HEADLESS_ACME_STATE);
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.custom_flags(libc::O_NOFOLLOW);
|
||||
}
|
||||
let file = match options.open(&path) {
|
||||
Ok(file) => file,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Ok(HeadlessAcmeState::new())
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(anyhow::Error::new(error).context(format!("cannot open {}", path.display())))
|
||||
}
|
||||
};
|
||||
let meta = file.metadata()?;
|
||||
anyhow::ensure!(
|
||||
meta.is_file() && meta.len() <= HEADLESS_ACME_STATE_LIMIT,
|
||||
"{} must be a regular file up to 256 KiB",
|
||||
path.display()
|
||||
);
|
||||
let mut bytes = Vec::new();
|
||||
file.take(HEADLESS_ACME_STATE_LIMIT + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
let state: HeadlessAcmeState = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| anyhow::anyhow!("invalid {}: {error}", path.display()))?;
|
||||
for (id, entry) in &state {
|
||||
anyhow::ensure!(
|
||||
crate::config::valid_id(id)
|
||||
&& crate::tls::safe_name(&entry.cert_file).is_ok()
|
||||
&& crate::tls::safe_name(&entry.key_file).is_ok()
|
||||
&& entry.cert_file.starts_with("acme-")
|
||||
&& entry.key_file.starts_with("acme-"),
|
||||
"invalid entry {id} in {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub fn write_headless_acme_state(
|
||||
cert_dir: &std::path::Path,
|
||||
state: &HeadlessAcmeState,
|
||||
) -> anyhow::Result<()> {
|
||||
use std::io::Write;
|
||||
let bytes = serde_json::to_vec_pretty(state)?;
|
||||
let path = cert_dir.join(HEADLESS_ACME_STATE);
|
||||
let temp = cert_dir.join(format!(
|
||||
".{HEADLESS_ACME_STATE}.{}",
|
||||
crate::auth::random_secret()
|
||||
));
|
||||
let result = (|| -> anyhow::Result<()> {
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
|
||||
}
|
||||
let mut file = options.open(&temp)?;
|
||||
file.write_all(&bytes)?;
|
||||
file.sync_all()?;
|
||||
std::fs::rename(&temp, &path)?;
|
||||
#[cfg(unix)]
|
||||
std::fs::File::open(cert_dir)?.sync_all()?;
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn headless_pair(id: String, cert: &std::path::Path, key: &std::path::Path) -> crate::tls::Certificate {
|
||||
crate::tls::Certificate {
|
||||
issuer: None,
|
||||
id,
|
||||
covered_hosts: Vec::new(),
|
||||
hosts: Vec::new(),
|
||||
cert_file: cert.to_string_lossy().into_owned(),
|
||||
key_file: key.to_string_lossy().into_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds certificate/key pairs in a directory. Supported layouts:
|
||||
/// - the directory itself holds `fullchain.pem` + `privkey.pem` (one Certbot lineage),
|
||||
/// - subdirectories with `fullchain.pem` + `privkey.pem` (Certbot `/etc/letsencrypt/live`),
|
||||
/// - subdirectories `<name>/` with `fullchain.cer` + `<name>.key` (acme.sh),
|
||||
/// - flat files `<name>.crt|.pem|.cer` + `<name>.key`.
|
||||
pub fn scan_headless_certificate_dir(
|
||||
dir: &std::path::Path,
|
||||
) -> anyhow::Result<Vec<crate::tls::Certificate>> {
|
||||
anyhow::ensure!(
|
||||
dir.is_absolute(),
|
||||
"--tls-cert-dir requires an absolute path: {}",
|
||||
dir.display()
|
||||
);
|
||||
let lineage = |path: &std::path::Path| -> Option<(std::path::PathBuf, std::path::PathBuf)> {
|
||||
let cert = path.join("fullchain.pem");
|
||||
let key = path.join("privkey.pem");
|
||||
(cert.is_file() && key.is_file()).then_some((cert, key))
|
||||
};
|
||||
let label = |path: &std::path::Path| {
|
||||
path.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
if let Some((cert, key)) = lineage(dir) {
|
||||
return Ok(vec![headless_pair(
|
||||
headless_file_certificate_id(&label(dir), &cert),
|
||||
&cert,
|
||||
&key,
|
||||
)]);
|
||||
}
|
||||
let mut entries: Vec<std::path::PathBuf> = std::fs::read_dir(dir)
|
||||
.map_err(|error| {
|
||||
anyhow::anyhow!("cannot read --tls-cert-dir {}: {error}", dir.display())
|
||||
})?
|
||||
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
|
||||
.collect();
|
||||
entries.sort();
|
||||
let mut found = Vec::new();
|
||||
for path in entries {
|
||||
let name = label(&path);
|
||||
if name.starts_with('.') {
|
||||
continue;
|
||||
}
|
||||
if path.is_dir() {
|
||||
if let Some((cert, key)) = lineage(&path) {
|
||||
found.push(headless_pair(
|
||||
headless_file_certificate_id(&name, &cert),
|
||||
&cert,
|
||||
&key,
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let cert = path.join("fullchain.cer");
|
||||
let key = path.join(format!("{name}.key"));
|
||||
if cert.is_file() && key.is_file() {
|
||||
found.push(headless_pair(
|
||||
headless_file_certificate_id(&name, &cert),
|
||||
&cert,
|
||||
&key,
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(extension) = path.extension().and_then(|value| value.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(extension, "crt" | "pem" | "cer") || !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
let key = path.with_extension("key");
|
||||
if key.is_file() {
|
||||
let stem = path
|
||||
.file_stem()
|
||||
.map(|stem| stem.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
found.push(headless_pair(
|
||||
headless_file_certificate_id(&stem, &path),
|
||||
&path,
|
||||
&key,
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// Certificates that the headless TLS options contribute right now.
|
||||
pub fn headless_tls_certificates(
|
||||
tls: &HeadlessTls,
|
||||
cert_dir: Option<&std::path::Path>,
|
||||
) -> anyhow::Result<Vec<crate::tls::Certificate>> {
|
||||
let mut certificates = Vec::new();
|
||||
for (cert, key) in &tls.cert_files {
|
||||
anyhow::ensure!(
|
||||
cert.is_absolute() && key.is_absolute(),
|
||||
"--tls-cert-file/--tls-key-file require absolute paths"
|
||||
);
|
||||
let label = cert
|
||||
.parent()
|
||||
.filter(|_| {
|
||||
cert.file_name()
|
||||
.is_some_and(|name| name == "fullchain.pem" || name == "cert.pem")
|
||||
})
|
||||
.unwrap_or(cert)
|
||||
.file_stem()
|
||||
.map(|value| value.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
certificates.push(headless_pair(
|
||||
headless_file_certificate_id(&label, cert),
|
||||
cert,
|
||||
key,
|
||||
));
|
||||
}
|
||||
for dir in &tls.cert_dirs {
|
||||
let found = scan_headless_certificate_dir(dir)?;
|
||||
if found.is_empty() {
|
||||
tracing::warn!(directory = %dir.display(), "--tls-cert-dir contains no certificate/key pairs");
|
||||
}
|
||||
certificates.extend(found);
|
||||
}
|
||||
if let (Some(acme), Some(cert_dir)) = (&tls.acme, cert_dir) {
|
||||
let state = read_headless_acme_state(cert_dir)?;
|
||||
let mut selected: Vec<(String, &HeadlessAcmeEntry)> = Vec::new();
|
||||
for names in &acme.certificates {
|
||||
let id = headless_acme_certificate_id(names);
|
||||
if let Some(entry) = state.get(&id).filter(|entry| entry.matches(acme, names)) {
|
||||
selected.push((id, entry));
|
||||
}
|
||||
}
|
||||
if acme.auto {
|
||||
for (id, entry) in state.iter().filter(|(_, entry)| {
|
||||
entry.auto && entry.provider == acme.provider && entry.environment == acme.environment
|
||||
}) {
|
||||
selected.push((id.clone(), entry));
|
||||
}
|
||||
}
|
||||
for (id, entry) in selected {
|
||||
if cert_dir.join(&entry.cert_file).is_file() && cert_dir.join(&entry.key_file).is_file()
|
||||
{
|
||||
certificates.push(crate::tls::Certificate {
|
||||
issuer: None,
|
||||
id,
|
||||
covered_hosts: Vec::new(),
|
||||
hosts: Vec::new(),
|
||||
cert_file: entry.cert_file.clone(),
|
||||
key_file: entry.key_file.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
certificates.retain(|certificate| seen.insert(certificate.id.clone()));
|
||||
anyhow::ensure!(
|
||||
certificates.len() <= MAX_HEADLESS_TLS_CERTIFICATES,
|
||||
"headless TLS options provide more than {MAX_HEADLESS_TLS_CERTIFICATES} certificates"
|
||||
);
|
||||
Ok(certificates)
|
||||
}
|
||||
|
||||
/// Adds the headless TLS certificates to a configuration read from the file.
|
||||
/// Host names are taken from each certificate's subject alternative names, so
|
||||
/// a vhost whose host the certificate covers serves it without any binding.
|
||||
pub fn apply_headless_tls(
|
||||
config: &mut config::Config,
|
||||
tls: &HeadlessTls,
|
||||
cert_dir: Option<&std::path::Path>,
|
||||
) -> anyhow::Result<usize> {
|
||||
let added = headless_tls_certificates(tls, cert_dir)?;
|
||||
let count = added.len();
|
||||
for certificate in added {
|
||||
anyhow::ensure!(
|
||||
!config
|
||||
.tls
|
||||
.certificates
|
||||
.iter()
|
||||
.any(|existing| existing.id == certificate.id),
|
||||
"certificate id {} from a headless TLS option is already used in the configuration file",
|
||||
certificate.id
|
||||
);
|
||||
config.tls.certificates.push(certificate);
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
/// ACME settings as given on the command line or in the `headless.acme`
|
||||
/// section of the configuration file; merged and validated into [`HeadlessAcme`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HeadlessAcmeSettings {
|
||||
/// One entry per certificate: a list of names or a comma-separated string.
|
||||
pub domains: Vec<HeadlessNames>,
|
||||
pub auto: bool,
|
||||
pub email: Option<String>,
|
||||
pub agree_tos: bool,
|
||||
pub staging: bool,
|
||||
pub provider: Option<String>,
|
||||
pub dns_credentials: Option<std::path::PathBuf>,
|
||||
pub propagation_seconds: Option<u64>,
|
||||
pub renew_days: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum HeadlessNames {
|
||||
List(Vec<String>),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl HeadlessNames {
|
||||
fn parse(&self) -> anyhow::Result<Vec<String>> {
|
||||
match self {
|
||||
Self::Text(text) => parse_headless_acme_names(text),
|
||||
Self::List(names) => parse_headless_acme_names(&names.join(",")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HeadlessAcmeSettings {
|
||||
pub fn requested(&self) -> bool {
|
||||
!self.domains.is_empty() || self.auto
|
||||
}
|
||||
|
||||
/// `primary` (command line) wins for single values; lists are joined.
|
||||
fn merge(primary: &Self, secondary: &Self) -> Self {
|
||||
let mut domains = primary.domains.clone();
|
||||
domains.extend(secondary.domains.iter().cloned());
|
||||
Self {
|
||||
domains,
|
||||
auto: primary.auto || secondary.auto,
|
||||
email: primary.email.clone().or_else(|| secondary.email.clone()),
|
||||
agree_tos: primary.agree_tos || secondary.agree_tos,
|
||||
staging: primary.staging || secondary.staging,
|
||||
provider: primary.provider.clone().or_else(|| secondary.provider.clone()),
|
||||
dns_credentials: primary
|
||||
.dns_credentials
|
||||
.clone()
|
||||
.or_else(|| secondary.dns_credentials.clone()),
|
||||
propagation_seconds: primary.propagation_seconds.or(secondary.propagation_seconds),
|
||||
renew_days: primary.renew_days.or(secondary.renew_days),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve(&self, base: &std::path::Path) -> anyhow::Result<Option<HeadlessAcme>> {
|
||||
if !self.requested() {
|
||||
return Ok(None);
|
||||
}
|
||||
anyhow::ensure!(
|
||||
self.agree_tos,
|
||||
"ACME requires accepting the Let's Encrypt Subscriber Agreement (--acme-agree-tos or \"agree_tos\": true)"
|
||||
);
|
||||
let email = self
|
||||
.email
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("ACME requires a contact e-mail (--acme-email or \"email\")"))?;
|
||||
let mut certificates = Vec::new();
|
||||
for names in &self.domains {
|
||||
let names = names.parse()?;
|
||||
if !certificates.contains(&names) {
|
||||
certificates.push(names);
|
||||
}
|
||||
}
|
||||
let acme = HeadlessAcme {
|
||||
certificates,
|
||||
email,
|
||||
environment: if self.staging { "staging" } else { "production" }.into(),
|
||||
provider: self.provider.clone().unwrap_or_else(|| "http01".into()),
|
||||
dns_credentials: self.dns_credentials.as_ref().map(|path| absolute_in(base, path)),
|
||||
propagation_seconds: self.propagation_seconds.unwrap_or(60),
|
||||
renew_before_days: self.renew_days.unwrap_or(30) as i64,
|
||||
auto: self.auto,
|
||||
};
|
||||
acme.validate()?;
|
||||
Ok(Some(acme))
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute_in(base: &std::path::Path, path: &std::path::Path) -> std::path::PathBuf {
|
||||
if path.is_absolute() {
|
||||
path.to_owned()
|
||||
} else {
|
||||
base.join(path)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HeadlessFilePair {
|
||||
pub cert_file: std::path::PathBuf,
|
||||
pub key_file: std::path::PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HeadlessFileTls {
|
||||
pub certificates: Vec<HeadlessFilePair>,
|
||||
pub directories: Vec<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
/// The optional top-level `"headless"` object of a headless configuration
|
||||
/// file. It is removed before the rest is read as a normal configuration, so
|
||||
/// the panel format is unchanged. Relative paths are relative to the file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct HeadlessFileSettings {
|
||||
pub tls: HeadlessFileTls,
|
||||
pub acme: HeadlessAcmeSettings,
|
||||
pub watch: bool,
|
||||
}
|
||||
|
||||
/// `--route HOSTS=URLS`: a vhost generated without a configuration file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HeadlessRoute {
|
||||
pub hosts: Vec<String>,
|
||||
pub backends: Vec<String>,
|
||||
}
|
||||
|
||||
impl HeadlessRoute {
|
||||
/// Parses `app.example.com,www.app.example.com=http://10.0.0.1:3000,http://10.0.0.2:3000`.
|
||||
pub fn parse(value: &str) -> anyhow::Result<Self> {
|
||||
let (hosts, backends) = value.split_once('=').ok_or_else(|| {
|
||||
anyhow::anyhow!("--route expects HOSTS=URLS, for example app.example.com=http://127.0.0.1:3000")
|
||||
})?;
|
||||
let mut parsed_hosts = Vec::new();
|
||||
for host in hosts.split(',').map(str::trim).filter(|h| !h.is_empty()) {
|
||||
let host = if host == "*" {
|
||||
host.to_owned()
|
||||
} else {
|
||||
crate::config::normalize_host_pattern(host)
|
||||
.map_err(|_| anyhow::anyhow!("--route: invalid host {host}"))?
|
||||
};
|
||||
if !parsed_hosts.contains(&host) {
|
||||
parsed_hosts.push(host);
|
||||
}
|
||||
}
|
||||
let mut parsed_backends = Vec::new();
|
||||
for url in backends.split(',').map(str::trim).filter(|u| !u.is_empty()) {
|
||||
let parsed = url::Url::parse(url)
|
||||
.map_err(|_| anyhow::anyhow!("--route: invalid backend URL {url}"))?;
|
||||
anyhow::ensure!(
|
||||
matches!(parsed.scheme(), "http" | "https") && parsed.host_str().is_some(),
|
||||
"--route: backend {url} must be an http:// or https:// URL"
|
||||
);
|
||||
parsed_backends.push(url.to_owned());
|
||||
}
|
||||
anyhow::ensure!(
|
||||
(1..=16).contains(&parsed_hosts.len()),
|
||||
"--route needs 1..16 host names before '='"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
(1..=32).contains(&parsed_backends.len()),
|
||||
"--route needs 1..32 backend URLs after '='"
|
||||
);
|
||||
Ok(Self {
|
||||
hosts: parsed_hosts,
|
||||
backends: parsed_backends,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn id(&self) -> String {
|
||||
format!(
|
||||
"route-{}-{}",
|
||||
id_label(self.hosts[0].trim_start_matches("*."), 40),
|
||||
short_digest(self.hosts.join(",").as_bytes())
|
||||
)
|
||||
}
|
||||
|
||||
/// The vhost as configuration JSON (defaults are applied by the normal parser).
|
||||
pub fn vhost_json(&self, force_https: bool) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"id": self.id(),
|
||||
"websockets": true,
|
||||
"forward_client_ip": true,
|
||||
"force_ssl": force_https,
|
||||
"frontend": { "hosts": self.hosts },
|
||||
"backends": self.backends.iter().enumerate().map(|(index, url)| serde_json::json!({
|
||||
"id": format!("b{}", index + 1),
|
||||
"url": url,
|
||||
"allow_private": true,
|
||||
})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Headless options from the command line / service environment.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HeadlessOptions {
|
||||
pub cert_files: Vec<(std::path::PathBuf, std::path::PathBuf)>,
|
||||
pub cert_dirs: Vec<std::path::PathBuf>,
|
||||
pub acme: HeadlessAcmeSettings,
|
||||
pub routes: Vec<HeadlessRoute>,
|
||||
pub force_https: bool,
|
||||
pub watch: bool,
|
||||
}
|
||||
|
||||
impl HeadlessOptions {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self == &Self::default()
|
||||
}
|
||||
|
||||
/// Effective TLS sources: command line first, then the file section.
|
||||
pub fn resolve(
|
||||
&self,
|
||||
file: &HeadlessFileSettings,
|
||||
file_dir: &std::path::Path,
|
||||
) -> anyhow::Result<HeadlessTls> {
|
||||
let mut cert_files = self.cert_files.clone();
|
||||
cert_files.extend(file.tls.certificates.iter().map(|pair| {
|
||||
(
|
||||
absolute_in(file_dir, &pair.cert_file),
|
||||
absolute_in(file_dir, &pair.key_file),
|
||||
)
|
||||
}));
|
||||
let mut cert_dirs = self.cert_dirs.clone();
|
||||
cert_dirs.extend(file.tls.directories.iter().map(|dir| absolute_in(file_dir, dir)));
|
||||
// Command-line relative paths were already resolved against the working directory.
|
||||
let acme = HeadlessAcmeSettings::merge(&self.acme, &file.acme).resolve(file_dir)?;
|
||||
Ok(HeadlessTls {
|
||||
cert_files,
|
||||
cert_dirs,
|
||||
acme,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static HEADLESS_OPTIONS: std::sync::OnceLock<(HeadlessOptions, std::path::PathBuf)> =
|
||||
std::sync::OnceLock::new();
|
||||
static HEADLESS_EFFECTIVE: std::sync::Mutex<Option<(HeadlessTls, bool)>> =
|
||||
std::sync::Mutex::new(None);
|
||||
static HEADLESS_CHANGED: std::sync::LazyLock<tokio::sync::Notify> =
|
||||
std::sync::LazyLock::new(tokio::sync::Notify::new);
|
||||
|
||||
/// Registers the command-line headless options of the running service (once, at start).
|
||||
pub fn configure_headless_options(options: HeadlessOptions, cert_dir: std::path::PathBuf) -> bool {
|
||||
HEADLESS_OPTIONS.set((options, cert_dir)).is_ok()
|
||||
}
|
||||
|
||||
pub fn headless_options() -> Option<&'static HeadlessOptions> {
|
||||
HEADLESS_OPTIONS.get().map(|(options, _)| options)
|
||||
}
|
||||
|
||||
pub fn headless_cert_dir() -> Option<&'static std::path::Path> {
|
||||
HEADLESS_OPTIONS.get().map(|(_, dir)| dir.as_path())
|
||||
}
|
||||
|
||||
/// Records the TLS sources of the configuration that is now active and wakes
|
||||
/// the headless ACME and watch tasks.
|
||||
pub fn publish_headless_tls(tls: HeadlessTls, watch: bool) {
|
||||
if let Ok(mut slot) = HEADLESS_EFFECTIVE.lock() {
|
||||
*slot = Some((tls, watch));
|
||||
}
|
||||
HEADLESS_CHANGED.notify_one();
|
||||
}
|
||||
|
||||
/// TLS sources of the active configuration (`None` before the first load).
|
||||
pub fn headless_tls() -> Option<HeadlessTls> {
|
||||
HEADLESS_EFFECTIVE
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| slot.as_ref().map(|(tls, _)| tls.clone()))
|
||||
}
|
||||
|
||||
pub fn headless_watch_requested() -> bool {
|
||||
HEADLESS_EFFECTIVE
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|slot| slot.as_ref().map(|(_, watch)| *watch))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Waits until the active headless configuration changes.
|
||||
pub async fn headless_changed() {
|
||||
HEADLESS_CHANGED.notified().await;
|
||||
}
|
||||
|
||||
fn covers(name: &str, host: &str) -> bool {
|
||||
name == host
|
||||
|| name.strip_prefix("*.").is_some_and(|base| {
|
||||
host.split_once('.')
|
||||
.is_some_and(|(label, rest)| !label.is_empty() && rest == base)
|
||||
})
|
||||
}
|
||||
|
||||
/// Host names that `acme.auto` should request: hosts of enabled vhosts and
|
||||
/// redirects that no other certificate (configured, file or explicit ACME)
|
||||
/// covers. One certificate per vhost (split into groups of 16 names).
|
||||
pub fn headless_auto_acme_groups(
|
||||
config: &config::Config,
|
||||
acme: &HeadlessAcme,
|
||||
cert_dir: &std::path::Path,
|
||||
) -> Vec<Vec<String>> {
|
||||
let mut covered: Vec<String> = acme.certificates.iter().flatten().cloned().collect();
|
||||
for certificate in config
|
||||
.tls
|
||||
.certificates
|
||||
.iter()
|
||||
.filter(|certificate| !certificate.id.starts_with("hl-acme-"))
|
||||
{
|
||||
covered.extend(certificate.hosts.iter().map(|h| h.to_ascii_lowercase()));
|
||||
if let Ok(names) = crate::tls::certificate_covered_hosts(cert_dir, &certificate.cert_file) {
|
||||
covered.extend(names.into_iter().map(|h| h.to_ascii_lowercase()));
|
||||
}
|
||||
}
|
||||
let mut owners: Vec<Vec<String>> = Vec::new();
|
||||
for vhost in config.vhosts.iter().filter(|vhost| vhost.enabled) {
|
||||
owners.push(vhost.routing_hosts().unwrap_or_else(|_| vhost.frontend.hosts.clone()));
|
||||
}
|
||||
for redirect in config.redirects.iter().filter(|host| host.enabled) {
|
||||
owners.push(redirect.frontend.hosts.clone());
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut groups = Vec::new();
|
||||
for hosts in owners {
|
||||
let mut names = Vec::new();
|
||||
for host in hosts {
|
||||
let host = host.to_ascii_lowercase();
|
||||
let host = host.trim_end_matches('.').to_owned();
|
||||
let base = host.strip_prefix("*.").unwrap_or(&host);
|
||||
let eligible = host != crate::config::CATCH_ALL_HOST
|
||||
&& base.contains('.')
|
||||
&& !base.contains('*')
|
||||
&& base.parse::<std::net::IpAddr>().is_err()
|
||||
&& (acme.provider != "http01" || !host.starts_with("*."))
|
||||
&& !covered.iter().any(|name| covers(name, &host));
|
||||
if eligible && seen.insert(host.clone()) {
|
||||
names.push(host);
|
||||
}
|
||||
}
|
||||
for chunk in names.chunks(MAX_HEADLESS_ACME_NAMES) {
|
||||
groups.push(chunk.to_vec());
|
||||
}
|
||||
}
|
||||
groups.truncate(MAX_HEADLESS_AUTO_CERTIFICATES);
|
||||
groups
|
||||
}
|
||||
|
||||
pub const MAX_HEADLESS_AUTO_CERTIFICATES: usize = 64;
|
||||
|
||||
/// Every host name served by enabled vhosts and redirects (lower case).
|
||||
pub fn headless_served_hosts(config: &config::Config) -> std::collections::HashSet<String> {
|
||||
let mut hosts = std::collections::HashSet::new();
|
||||
for vhost in config.vhosts.iter().filter(|vhost| vhost.enabled) {
|
||||
for host in vhost.routing_hosts().unwrap_or_else(|_| vhost.frontend.hosts.clone()) {
|
||||
hosts.insert(host.to_ascii_lowercase());
|
||||
}
|
||||
}
|
||||
for redirect in config.redirects.iter().filter(|host| host.enabled) {
|
||||
hosts.extend(redirect.frontend.hosts.iter().map(|h| h.to_ascii_lowercase()));
|
||||
}
|
||||
hosts
|
||||
}
|
||||
|
||||
/// Reads a Certbot-style DNS credentials INI file and returns the matching
|
||||
/// ACME request fields for the provider.
|
||||
pub fn headless_dns_credential_fields(
|
||||
provider: &str,
|
||||
path: &std::path::Path,
|
||||
) -> anyhow::Result<serde_json::Map<String, serde_json::Value>> {
|
||||
use std::io::Read;
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.read(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.custom_flags(libc::O_NOFOLLOW);
|
||||
}
|
||||
let file = options
|
||||
.open(path)
|
||||
.map_err(|error| anyhow::anyhow!("cannot open {}: {error}", path.display()))?;
|
||||
let meta = file.metadata()?;
|
||||
anyhow::ensure!(
|
||||
meta.is_file() && meta.len() <= 16_384,
|
||||
"{} must be a regular file up to 16 KiB",
|
||||
path.display()
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
anyhow::ensure!(
|
||||
meta.permissions().mode() & 0o077 == 0,
|
||||
"{} must not be readable by group or others (chmod 600)",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
let mut text = zeroize::Zeroizing::new(String::new());
|
||||
file.take(16_385).read_to_string(&mut text)?;
|
||||
let mut values = std::collections::HashMap::new();
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') || line.starts_with(';') || line.starts_with('[')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
values.insert(
|
||||
key.trim().to_ascii_lowercase(),
|
||||
zeroize::Zeroizing::new(value.trim().trim_matches('"').to_owned()),
|
||||
);
|
||||
}
|
||||
let get = |key: &str| values.get(key).map(|value| value.as_str().to_owned());
|
||||
let require = |key: &str| {
|
||||
get(key).ok_or_else(|| anyhow::anyhow!("{} is missing {key}", path.display()))
|
||||
};
|
||||
let mut fields = serde_json::Map::new();
|
||||
let mut put = |name: &str, value: serde_json::Value| {
|
||||
fields.insert(name.to_owned(), value);
|
||||
};
|
||||
match provider {
|
||||
"cloudflare" => put(
|
||||
"api_token",
|
||||
require("dns_cloudflare_api_token")?.into(),
|
||||
),
|
||||
"ovh" => {
|
||||
if let Some(endpoint) = get("dns_ovh_endpoint") {
|
||||
put("endpoint", endpoint.into());
|
||||
}
|
||||
put(
|
||||
"application_key",
|
||||
require("dns_ovh_application_key")?.into(),
|
||||
);
|
||||
put(
|
||||
"application_secret",
|
||||
require("dns_ovh_application_secret")?.into(),
|
||||
);
|
||||
put("consumer_key", require("dns_ovh_consumer_key")?.into());
|
||||
}
|
||||
"rfc2136" => {
|
||||
put("dns_server", require("dns_rfc2136_server")?.into());
|
||||
if let Some(port) = get("dns_rfc2136_port") {
|
||||
let port: u64 = port
|
||||
.parse()
|
||||
.map_err(|_| anyhow::anyhow!("invalid dns_rfc2136_port"))?;
|
||||
put("dns_port", port.into());
|
||||
}
|
||||
put(
|
||||
"key_name",
|
||||
require("dns_rfc2136_name")?
|
||||
.trim_end_matches('.')
|
||||
.to_owned()
|
||||
.into(),
|
||||
);
|
||||
put("key_secret", require("dns_rfc2136_secret")?.into());
|
||||
if let Some(algorithm) = get("dns_rfc2136_algorithm") {
|
||||
put("key_algorithm", algorithm.to_ascii_uppercase().into());
|
||||
}
|
||||
if let Some(sign) = get("dns_rfc2136_sign_query") {
|
||||
put(
|
||||
"sign_query",
|
||||
matches!(sign.to_ascii_lowercase().as_str(), "true" | "1" | "yes").into(),
|
||||
);
|
||||
}
|
||||
}
|
||||
other => anyhow::bail!("provider {other} does not use DNS credentials"),
|
||||
}
|
||||
Ok(fields)
|
||||
}
|
||||
@@ -0,0 +1,565 @@
|
||||
mod headless_tls_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(cert_dir: &std::path::Path) -> ValidationPolicy {
|
||||
ValidationPolicy {
|
||||
tls_addr: Some("127.0.0.1:8443".parse().unwrap()),
|
||||
cert_dir: Some(cert_dir.to_owned()),
|
||||
data_dir: None,
|
||||
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
|
||||
admin_addr: "127.0.0.1:9090".parse().unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
fn minimal(hosts: &[&str]) -> config::Config {
|
||||
let document = serde_json::json!({"vhosts":[{"id":"app","frontend":{"hosts":hosts},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]}]});
|
||||
external_config::headless_config(document.to_string().as_bytes(), &startup()).unwrap()
|
||||
}
|
||||
|
||||
fn acme(names: &[&[&str]], provider: &str) -> HeadlessAcme {
|
||||
HeadlessAcme {
|
||||
certificates: names
|
||||
.iter()
|
||||
.map(|group| group.iter().map(|name| name.to_string()).collect())
|
||||
.collect(),
|
||||
email: "ops@example.com".into(),
|
||||
environment: "production".into(),
|
||||
provider: provider.into(),
|
||||
dns_credentials: (provider != "http01")
|
||||
.then(|| std::path::PathBuf::from("/etc/rustproxy/dns.ini")),
|
||||
propagation_seconds: 60,
|
||||
renew_before_days: 30,
|
||||
auto: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a self-signed pair `<name>.pem`/`<name>.key` in `dir`.
|
||||
fn pair(dir: &std::path::Path, name: &str, hosts: &[&str]) {
|
||||
crate::tls::generate(dir, name, hosts.iter().map(|h| h.to_string()).collect()).unwrap();
|
||||
}
|
||||
|
||||
fn private_dir() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acme_names_are_normalized_and_validated() {
|
||||
assert_eq!(
|
||||
parse_headless_acme_names(" Example.COM., www.example.com ,example.com").unwrap(),
|
||||
vec!["example.com", "www.example.com"]
|
||||
);
|
||||
assert_eq!(
|
||||
parse_headless_acme_names("*.Example.com,example.com").unwrap(),
|
||||
vec!["*.example.com", "example.com"]
|
||||
);
|
||||
assert!(parse_headless_acme_names("").is_err());
|
||||
assert!(parse_headless_acme_names("localhost").is_err());
|
||||
assert!(parse_headless_acme_names("192.0.2.1").is_err());
|
||||
assert!(parse_headless_acme_names("a.*.example.com").is_err());
|
||||
let many: Vec<String> = (0..17).map(|i| format!("h{i}.example.com")).collect();
|
||||
assert!(parse_headless_acme_names(&many.join(",")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acme_certificate_ids_are_stable_valid_and_order_independent() {
|
||||
let a = headless_acme_certificate_id(&["example.com".into(), "www.example.com".into()]);
|
||||
let b = headless_acme_certificate_id(&["www.example.com".into(), "example.com".into()]);
|
||||
let c = headless_acme_certificate_id(&["example.com".into()]);
|
||||
assert!(a.starts_with("hl-acme-"));
|
||||
assert_ne!(a, c);
|
||||
// The label follows the first name, the digest the whole set.
|
||||
assert_eq!(&a[..a.len() - 8], "hl-acme-example-com-");
|
||||
assert_eq!(&a[a.len() - 8..], &b[b.len() - 8..]);
|
||||
let long = headless_acme_certificate_id(&[format!("{}.example.com", "a".repeat(63))]);
|
||||
let wildcard = headless_acme_certificate_id(&["*.example.com".into()]);
|
||||
for id in [a, b, c, long, wildcard] {
|
||||
assert!(crate::config::valid_id(&id), "{id}");
|
||||
assert!(crate::tls::safe_name(&id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn acme_options_are_checked_before_start() {
|
||||
assert!(acme(&[&["example.com", "www.example.com"]], "http01")
|
||||
.validate()
|
||||
.is_ok());
|
||||
let error = acme(&[&["*.example.com"]], "http01")
|
||||
.validate()
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("DNS-01"), "{error}");
|
||||
assert!(acme(&[&["*.example.com", "example.com"]], "cloudflare")
|
||||
.validate()
|
||||
.is_ok());
|
||||
let mut missing = acme(&[&["example.com"]], "ovh");
|
||||
missing.dns_credentials = None;
|
||||
assert!(missing.validate().is_err());
|
||||
let mut needless = acme(&[&["example.com"]], "http01");
|
||||
needless.dns_credentials = Some("/etc/rustproxy/dns.ini".into());
|
||||
assert!(needless.validate().is_err());
|
||||
let mut email = acme(&[&["example.com"]], "http01");
|
||||
for bad in ["", "ops", "ops@", "@example.com", "ops@example", "o ps@example.com"] {
|
||||
email.email = bad.into();
|
||||
assert!(email.validate().is_err(), "{bad}");
|
||||
}
|
||||
assert!(acme(&[&["example.com"], &["example.com"]], "http01")
|
||||
.validate()
|
||||
.is_err());
|
||||
assert!(acme(&[], "http01").validate().is_err());
|
||||
let mut auto_only = acme(&[], "http01");
|
||||
auto_only.auto = true;
|
||||
assert!(auto_only.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_files_are_added_with_san_hosts_and_compile() {
|
||||
let certs = private_dir();
|
||||
let cert_dir = certs.path().join("certs");
|
||||
crate::tls::initialize_default(&cert_dir).unwrap();
|
||||
let external = private_dir();
|
||||
pair(external.path(), "site", &["app.example.com", "www.app.example.com"]);
|
||||
let tls = HeadlessTls {
|
||||
cert_files: vec![(
|
||||
external.path().join("site.pem"),
|
||||
external.path().join("site.key"),
|
||||
)],
|
||||
..Default::default()
|
||||
};
|
||||
let mut config = minimal(&["app.example.com", "www.app.example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 1);
|
||||
let certificate = &config.tls.certificates[0];
|
||||
assert!(certificate.id.starts_with("hl-file-site-"));
|
||||
assert!(certificate.hosts.is_empty());
|
||||
assert!(certificate.issuer.is_none());
|
||||
// Same input, same id: reloads keep the identity stable.
|
||||
let mut again = minimal(&["app.example.com"]);
|
||||
apply_headless_tls(&mut again, &tls, Some(&cert_dir)).unwrap();
|
||||
assert_eq!(again.tls.certificates[0].id, certificate.id);
|
||||
config::compile(config, 1, &policy(&cert_dir)).unwrap();
|
||||
|
||||
// A configured certificate with the same id is a conflict, not a silent override.
|
||||
let mut duplicate = minimal(&["app.example.com"]);
|
||||
duplicate.tls.certificates.push(again.tls.certificates[0].clone());
|
||||
assert!(apply_headless_tls(&mut duplicate, &tls, Some(&cert_dir)).is_err());
|
||||
|
||||
let relative = HeadlessTls {
|
||||
cert_files: vec![("site.pem".into(), "site.key".into())],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(apply_headless_tls(&mut minimal(&["*"]), &relative, Some(&cert_dir)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn certificate_directories_support_certbot_acme_sh_and_flat_layouts() {
|
||||
let root = private_dir();
|
||||
let live = root.path().join("live");
|
||||
std::fs::create_dir(&live).unwrap();
|
||||
// Certbot: live/<name>/fullchain.pem + privkey.pem
|
||||
let scratch = private_dir();
|
||||
pair(scratch.path(), "a", &["a.example.com"]);
|
||||
let lineage = live.join("a.example.com");
|
||||
std::fs::create_dir(&lineage).unwrap();
|
||||
std::fs::copy(scratch.path().join("a.pem"), lineage.join("fullchain.pem")).unwrap();
|
||||
std::fs::copy(scratch.path().join("a.key"), lineage.join("privkey.pem")).unwrap();
|
||||
// acme.sh: <name>/fullchain.cer + <name>/<name>.key
|
||||
pair(scratch.path(), "b", &["b.example.com"]);
|
||||
let acme_sh = live.join("b.example.com");
|
||||
std::fs::create_dir(&acme_sh).unwrap();
|
||||
std::fs::copy(scratch.path().join("b.pem"), acme_sh.join("fullchain.cer")).unwrap();
|
||||
std::fs::copy(scratch.path().join("b.key"), acme_sh.join("b.example.com.key")).unwrap();
|
||||
// flat: <name>.crt + <name>.key; unmatched files and dot entries are ignored
|
||||
pair(scratch.path(), "c", &["c.example.com"]);
|
||||
std::fs::copy(scratch.path().join("c.pem"), live.join("c.crt")).unwrap();
|
||||
std::fs::copy(scratch.path().join("c.key"), live.join("c.key")).unwrap();
|
||||
std::fs::write(live.join("README"), "certbot").unwrap();
|
||||
std::fs::write(live.join("lonely.pem"), "x").unwrap();
|
||||
std::fs::create_dir(live.join(".hidden")).unwrap();
|
||||
std::fs::create_dir(live.join("empty")).unwrap();
|
||||
|
||||
let found = scan_headless_certificate_dir(&live).unwrap();
|
||||
let files: Vec<_> = found
|
||||
.iter()
|
||||
.map(|c| {
|
||||
std::path::Path::new(&c.cert_file)
|
||||
.strip_prefix(&live)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
files,
|
||||
vec![
|
||||
"a.example.com/fullchain.pem",
|
||||
"b.example.com/fullchain.cer",
|
||||
"c.crt"
|
||||
]
|
||||
);
|
||||
assert!(found[0].id.starts_with("hl-file-a-example-com-"));
|
||||
|
||||
// A single lineage directory given directly.
|
||||
let single = scan_headless_certificate_dir(&lineage).unwrap();
|
||||
assert_eq!(single.len(), 1);
|
||||
assert!(single[0].cert_file.ends_with("fullchain.pem"));
|
||||
|
||||
assert!(scan_headless_certificate_dir(std::path::Path::new("live")).is_err());
|
||||
assert!(scan_headless_certificate_dir(&root.path().join("missing")).is_err());
|
||||
|
||||
let certs = private_dir();
|
||||
let cert_dir = certs.path().join("certs");
|
||||
crate::tls::initialize_default(&cert_dir).unwrap();
|
||||
let tls = HeadlessTls {
|
||||
cert_dirs: vec![live.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let mut config = minimal(&["a.example.com", "b.example.com", "c.example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 3);
|
||||
config::compile(config, 1, &policy(&cert_dir)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn issued_acme_certificates_are_added_only_when_the_request_matches() {
|
||||
let certs = private_dir();
|
||||
let cert_dir = certs.path().join("certs");
|
||||
crate::tls::initialize_default(&cert_dir).unwrap();
|
||||
pair(&cert_dir, "acme-0123", &["example.com", "www.example.com"]);
|
||||
let options = acme(&[&["example.com", "www.example.com"]], "http01");
|
||||
let names = options.certificates[0].clone();
|
||||
let id = headless_acme_certificate_id(&names);
|
||||
let tls = HeadlessTls {
|
||||
acme: Some(options.clone()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Nothing issued yet: no certificate and no error.
|
||||
let mut config = minimal(&["example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 0);
|
||||
|
||||
let mut state = HeadlessAcmeState::new();
|
||||
state.insert(
|
||||
id.clone(),
|
||||
HeadlessAcmeEntry {
|
||||
provider: "http01".into(),
|
||||
environment: "production".into(),
|
||||
domains: vec!["www.example.com".into(), "example.com".into()],
|
||||
cert_file: "acme-0123.pem".into(),
|
||||
key_file: "acme-0123.key".into(),
|
||||
issued_at: 1,
|
||||
auto: false,
|
||||
},
|
||||
);
|
||||
write_headless_acme_state(&cert_dir, &state).unwrap();
|
||||
assert_eq!(read_headless_acme_state(&cert_dir).unwrap(), state);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = std::fs::metadata(cert_dir.join(HEADLESS_ACME_STATE))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o600);
|
||||
}
|
||||
|
||||
let mut config = minimal(&["example.com", "www.example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 1);
|
||||
assert_eq!(config.tls.certificates[0].id, id);
|
||||
assert_eq!(config.tls.certificates[0].cert_file, "acme-0123.pem");
|
||||
config::compile(config, 1, &policy(&cert_dir)).unwrap();
|
||||
|
||||
// A different environment, provider or name set waits for a new certificate.
|
||||
for changed in [
|
||||
HeadlessAcme {
|
||||
environment: "staging".into(),
|
||||
..options.clone()
|
||||
},
|
||||
HeadlessAcme {
|
||||
certificates: vec![vec!["example.com".into()]],
|
||||
..options.clone()
|
||||
},
|
||||
] {
|
||||
let tls = HeadlessTls {
|
||||
acme: Some(changed),
|
||||
..Default::default()
|
||||
};
|
||||
let mut config = minimal(&["example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 0);
|
||||
}
|
||||
|
||||
// Missing files are skipped rather than breaking the reload.
|
||||
std::fs::remove_file(cert_dir.join("acme-0123.key")).unwrap();
|
||||
let mut config = minimal(&["example.com"]);
|
||||
assert_eq!(apply_headless_tls(&mut config, &tls, Some(&cert_dir)).unwrap(), 0);
|
||||
|
||||
// Paths in the state file are confined to the certificate directory.
|
||||
std::fs::write(
|
||||
cert_dir.join(HEADLESS_ACME_STATE),
|
||||
format!(r#"{{"{id}":{{"provider":"http01","environment":"production","domains":["example.com"],"cert_file":"../x.pem","key_file":"acme-1.key"}}}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(read_headless_acme_state(&cert_dir).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dns_credentials_use_certbot_ini_names_and_private_files() {
|
||||
let dir = private_dir();
|
||||
let path = dir.path().join("dns.ini");
|
||||
let write = |text: &str, mode: u32| {
|
||||
std::fs::write(&path, text).unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = mode;
|
||||
};
|
||||
write("# token\ndns_cloudflare_api_token = abcdefgh12345678\n", 0o600);
|
||||
let fields = headless_dns_credential_fields("cloudflare", &path).unwrap();
|
||||
assert_eq!(fields["api_token"], "abcdefgh12345678");
|
||||
|
||||
write(
|
||||
"dns_ovh_endpoint = ovh-eu\ndns_ovh_application_key = key12345\ndns_ovh_application_secret = secret123\ndns_ovh_consumer_key = consumer1\n",
|
||||
0o600,
|
||||
);
|
||||
let fields = headless_dns_credential_fields("ovh", &path).unwrap();
|
||||
assert_eq!(fields["endpoint"], "ovh-eu");
|
||||
assert_eq!(fields["consumer_key"], "consumer1");
|
||||
|
||||
write(
|
||||
"dns_rfc2136_server = 192.0.2.53\ndns_rfc2136_port = 5353\ndns_rfc2136_name = keyname.\ndns_rfc2136_secret = c2VjcmV0c2VjcmV0c2VjcmV0\ndns_rfc2136_algorithm = hmac-sha512\ndns_rfc2136_sign_query = true\n",
|
||||
0o600,
|
||||
);
|
||||
let fields = headless_dns_credential_fields("rfc2136", &path).unwrap();
|
||||
assert_eq!(fields["dns_server"], "192.0.2.53");
|
||||
assert_eq!(fields["dns_port"], 5353);
|
||||
assert_eq!(fields["key_name"], "keyname");
|
||||
assert_eq!(fields["key_algorithm"], "HMAC-SHA512");
|
||||
assert_eq!(fields["sign_query"], true);
|
||||
|
||||
assert!(headless_dns_credential_fields("cloudflare", &path).is_err());
|
||||
assert!(headless_dns_credential_fields("http01", &path).is_err());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
write("dns_cloudflare_api_token = abcdefgh12345678\n", 0o644);
|
||||
let error = headless_dns_credential_fields("cloudflare", &path)
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.contains("chmod 600"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn options(file: &str, cli: HeadlessOptions) -> anyhow::Result<external_config::HeadlessLoad> {
|
||||
let dir = private_dir();
|
||||
let path = dir.path().join("config.json");
|
||||
std::fs::write(&path, file).unwrap();
|
||||
let result = external_config::load_headless_with(Some(&path), &startup(), &cli, None);
|
||||
drop(dir);
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_section_in_the_file_configures_tls_acme_and_watch() {
|
||||
let file = r#"{
|
||||
"headless": {
|
||||
"watch": true,
|
||||
"tls": {
|
||||
"certificates": [{"cert_file": "certs/app.pem", "key_file": "/etc/ssl/app.key"}],
|
||||
"directories": ["live"]
|
||||
},
|
||||
"acme": {
|
||||
"email": "ops@example.com", "agree_tos": true, "staging": true,
|
||||
"domains": [["app.example.com", "www.app.example.com"], "api.example.com"],
|
||||
"auto": true, "renew_days": 20
|
||||
}
|
||||
},
|
||||
"vhosts": [{"id":"app","frontend":{"hosts":["app.example.com"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]}]
|
||||
}"#;
|
||||
let dir = private_dir();
|
||||
std::fs::create_dir(dir.path().join("live")).unwrap();
|
||||
let path = dir.path().join("config.json");
|
||||
std::fs::write(&path, file).unwrap();
|
||||
let load = external_config::load_headless_with(
|
||||
Some(&path),
|
||||
&startup(),
|
||||
&HeadlessOptions::default(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(load.watch);
|
||||
assert_eq!(load.config.vhosts.len(), 1);
|
||||
// Relative paths are relative to the configuration file.
|
||||
assert_eq!(load.tls.cert_files[0].0, dir.path().join("certs/app.pem"));
|
||||
assert_eq!(load.tls.cert_files[0].1, std::path::PathBuf::from("/etc/ssl/app.key"));
|
||||
assert_eq!(load.tls.cert_dirs, vec![dir.path().join("live")]);
|
||||
let acme = load.tls.acme.unwrap();
|
||||
assert_eq!(acme.environment, "staging");
|
||||
assert_eq!(acme.provider, "http01");
|
||||
assert!(acme.auto);
|
||||
assert_eq!(acme.renew_before_days, 20);
|
||||
assert_eq!(
|
||||
acme.certificates,
|
||||
vec![
|
||||
vec!["app.example.com".to_string(), "www.app.example.com".to_string()],
|
||||
vec!["api.example.com".to_string()]
|
||||
]
|
||||
);
|
||||
// The panel-format reader ignores the section; unknown keys in it are errors.
|
||||
assert!(external_config::headless_config(file.as_bytes(), &startup()).is_ok());
|
||||
assert!(options(r#"{"headless":{"unknown":1}}"#, HeadlessOptions::default()).is_err());
|
||||
assert!(options(
|
||||
r#"{"headless":{"acme":{"domains":["a.example.com"],"agree_tos":true}}}"#,
|
||||
HeadlessOptions::default()
|
||||
)
|
||||
.is_err());
|
||||
assert!(options(r#"{}"#, HeadlessOptions::default())
|
||||
.unwrap()
|
||||
.tls
|
||||
.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_line_options_complete_and_override_the_file() {
|
||||
let file = r#"{"headless":{"acme":{"email":"file@example.com","agree_tos":true,
|
||||
"provider":"cloudflare","dns_credentials":"/etc/rustproxy/cf.ini",
|
||||
"domains":["example.com,*.example.com"]}}}"#;
|
||||
let cli = HeadlessOptions {
|
||||
acme: HeadlessAcmeSettings {
|
||||
domains: vec![HeadlessNames::Text("api.example.com".into())],
|
||||
email: Some("cli@example.com".into()),
|
||||
..Default::default()
|
||||
},
|
||||
cert_files: vec![("/a/cert.pem".into(), "/a/key.pem".into())],
|
||||
..Default::default()
|
||||
};
|
||||
let load = options(file, cli).unwrap();
|
||||
let acme = load.tls.acme.unwrap();
|
||||
assert_eq!(acme.email, "cli@example.com");
|
||||
assert_eq!(acme.provider, "cloudflare");
|
||||
assert_eq!(acme.certificates.len(), 2);
|
||||
assert_eq!(load.tls.cert_files.len(), 1);
|
||||
// CLI e-mail alone without consent anywhere is rejected at load time.
|
||||
let cli_only = HeadlessOptions {
|
||||
acme: HeadlessAcmeSettings {
|
||||
domains: vec![HeadlessNames::Text("api.example.com".into())],
|
||||
email: Some("cli@example.com".into()),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert!(options("{}", cli_only).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routes_generate_vhosts_without_a_configuration_file() {
|
||||
let route = HeadlessRoute::parse(
|
||||
"App.example.com, www.app.example.com=http://127.0.0.1:3000,http://127.0.0.1:3001",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(route.hosts, vec!["app.example.com", "www.app.example.com"]);
|
||||
assert_eq!(route.backends.len(), 2);
|
||||
assert!(route.id().starts_with("route-app-example-com-"));
|
||||
assert!(crate::config::valid_id(&route.id()));
|
||||
for bad in [
|
||||
"app.example.com",
|
||||
"=http://127.0.0.1:1",
|
||||
"app.example.com=",
|
||||
"app.example.com=ftp://x",
|
||||
"bad host=http://127.0.0.1:1",
|
||||
] {
|
||||
assert!(HeadlessRoute::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
let cli = HeadlessOptions {
|
||||
routes: vec![route, HeadlessRoute::parse("*=http://127.0.0.1:4000").unwrap()],
|
||||
force_https: true,
|
||||
..Default::default()
|
||||
};
|
||||
let load =
|
||||
external_config::load_headless_with(None, &startup(), &cli, None).unwrap();
|
||||
assert_eq!(load.config.vhosts.len(), 2);
|
||||
let vhost = &load.config.vhosts[0];
|
||||
assert!(vhost.force_ssl && vhost.websockets && vhost.forward_client_ip);
|
||||
assert_eq!(vhost.frontend.listener_ids.len(), 2);
|
||||
let certs = private_dir();
|
||||
let cert_dir = certs.path().join("certs");
|
||||
crate::tls::initialize_default(&cert_dir).unwrap();
|
||||
let compiled = config::compile(load.config, 1, &policy(&cert_dir));
|
||||
assert!(compiled.is_ok(), "{:?}", compiled.err());
|
||||
// A file vhost with the same id is a conflict.
|
||||
let id = cli.routes[0].id();
|
||||
let file = format!(
|
||||
r#"{{"vhosts":[{{"id":"{id}","frontend":{{"hosts":["x.example.com"]}},"backends":[{{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}}]}}]}}"#
|
||||
);
|
||||
assert!(options(&file, cli).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_acme_requests_uncovered_vhost_hosts_only() {
|
||||
let certs = private_dir();
|
||||
let cert_dir = certs.path().join("certs");
|
||||
crate::tls::initialize_default(&cert_dir).unwrap();
|
||||
pair(&cert_dir, "covered", &["*.covered.example.com"]);
|
||||
let document = serde_json::json!({
|
||||
"tls": {"certificates": [{"id":"covered","hosts":[],"cert_file":"covered.pem","key_file":"covered.key"}]},
|
||||
"vhosts": [
|
||||
{"id":"a","frontend":{"hosts":["shop.example.com","www.shop.example.com","api.covered.example.com"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]},
|
||||
{"id":"b","frontend":{"hosts":["*","10.0.0.1","localhost","*.wild.example.com","listed.example.com"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]},
|
||||
{"id":"off","enabled":false,"frontend":{"hosts":["off.example.com"]},
|
||||
"backends":[{"id":"a","url":"http://127.0.0.1:9001","allow_private":true}]}
|
||||
],
|
||||
});
|
||||
let config =
|
||||
external_config::headless_config(document.to_string().as_bytes(), &startup()).unwrap();
|
||||
let mut options = acme(&[&["listed.example.com"]], "http01");
|
||||
options.auto = true;
|
||||
let groups = headless_auto_acme_groups(&config, &options, &cert_dir);
|
||||
assert_eq!(
|
||||
groups,
|
||||
vec![vec!["shop.example.com".to_string(), "www.shop.example.com".to_string()]]
|
||||
);
|
||||
// With DNS-01 wildcard vhost hosts are requested as well.
|
||||
let mut dns = acme(&[&["listed.example.com"]], "cloudflare");
|
||||
dns.auto = true;
|
||||
let groups = headless_auto_acme_groups(&config, &dns, &cert_dir);
|
||||
assert_eq!(groups[1], vec!["*.wild.example.com".to_string()]);
|
||||
let served = headless_served_hosts(&config);
|
||||
assert!(served.contains("shop.example.com") && !served.contains("off.example.com"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_examples_parse() {
|
||||
for (name, text) in [
|
||||
("headless-minimal", include_str!("../../examples/headless-minimal.json")),
|
||||
("headless-production", include_str!("../../examples/headless-production.json")),
|
||||
("headless-https-files", include_str!("../../examples/headless-https-files.json")),
|
||||
("headless-acme", include_str!("../../examples/headless-acme.json")),
|
||||
("headless-acme-wildcard-dns", include_str!("../../examples/headless-acme-wildcard-dns.json")),
|
||||
] {
|
||||
let config = external_config::headless_config(text.as_bytes(), &startup());
|
||||
assert!(config.is_ok(), "{name}: {:?}", config.err());
|
||||
let value: serde_json::Value = serde_json::from_str(text).unwrap();
|
||||
if let Some(section) = value.get("headless") {
|
||||
let settings: HeadlessFileSettings = serde_json::from_value(section.clone()).unwrap();
|
||||
let tls = HeadlessOptions::default()
|
||||
.resolve(&settings, std::path::Path::new("/etc/rustproxy"));
|
||||
assert!(tls.is_ok(), "{name}: {:?}", tls.err());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub fn health_router(state: Arc<App>) -> axum::Router {
|
||||
axum::Router::new()
|
||||
.route("/healthz", axum::routing::get(health_status))
|
||||
.route("/certificates", axum::routing::get(certificate_status))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
@@ -52,3 +53,66 @@ async fn health_status(axum::extract::State(state): axum::extract::State<Arc<App
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
/// Read-only certificate inventory (like Envoy's admin `/certs`): every
|
||||
/// active certificate with its source, names and expiry, plus the state of the
|
||||
/// headless ACME requests. Only public certificate data is shown.
|
||||
async fn certificate_status(
|
||||
axum::extract::State(state): axum::extract::State<Arc<App>>,
|
||||
) -> Response {
|
||||
let snapshot = state.config.load_full();
|
||||
let directory = state.policy.cert_dir.clone();
|
||||
let acme = crate::acme::headless_acme_status();
|
||||
let auto_ids: std::collections::HashSet<String> = acme
|
||||
.iter()
|
||||
.filter(|(_, status)| status.auto)
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect();
|
||||
let certificates = tokio::task::spawn_blocking(move || {
|
||||
let config = &snapshot.envelope.config;
|
||||
config
|
||||
.tls
|
||||
.certificates
|
||||
.iter()
|
||||
.map(|certificate| {
|
||||
let source = if certificate.id.starts_with("hl-acme-") {
|
||||
if auto_ids.contains(&certificate.id) {
|
||||
"acme-auto"
|
||||
} else {
|
||||
"acme"
|
||||
}
|
||||
} else if certificate.id.starts_with("hl-file-") {
|
||||
"file"
|
||||
} else {
|
||||
"configuration"
|
||||
};
|
||||
let metadata = directory
|
||||
.as_deref()
|
||||
.and_then(|dir| crate::tls::certificate_metadata(dir, &certificate.cert_file).ok());
|
||||
json!({
|
||||
"id": certificate.id,
|
||||
"source": source,
|
||||
"default": config.tls.default_certificate.as_deref() == Some(certificate.id.as_str()),
|
||||
"hosts": certificate.hosts,
|
||||
"covered_hosts": metadata.as_ref().map(|m| m.covered_hosts.clone()).unwrap_or_default(),
|
||||
"issuer": metadata.as_ref().and_then(|m| m.issuer.clone()),
|
||||
"not_after": metadata.as_ref().and_then(|m| m.not_after.clone()),
|
||||
"days_remaining": metadata.as_ref().and_then(|m| m.days_remaining),
|
||||
"expiry_status": metadata.as_ref().map(|m| m.expiry_status).unwrap_or("unreadable"),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let mut response = (
|
||||
StatusCode::OK,
|
||||
Json(json!({ "certificates": certificates, "acme": acme })),
|
||||
)
|
||||
.into_response();
|
||||
response.headers_mut().insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
http::HeaderValue::from_static("no-store"),
|
||||
);
|
||||
response
|
||||
}
|
||||
+28
-10
@@ -17,6 +17,31 @@ impl App {
|
||||
.await
|
||||
.as_ref()
|
||||
.map(|(path, _)| path.clone());
|
||||
if let Some(listeners) = headless_listeners() {
|
||||
// Headless: the file (or, with only --route, an empty document)
|
||||
// plus the command-line and "headless" TLS sources.
|
||||
let load = tokio::task::spawn_blocking(move || {
|
||||
external_config::load_headless(file.as_deref(), listeners)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
|
||||
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
|
||||
ensure_headless_supported(&load.config)
|
||||
.map_err(|e| ApiError(StatusCode::UNPROCESSABLE_ENTITY, format!("{e:#}")))?;
|
||||
let envelope = self
|
||||
.update_as_action(
|
||||
Update {
|
||||
expected_revision,
|
||||
config: load.config,
|
||||
},
|
||||
"file-reload".into(),
|
||||
None,
|
||||
Some(load.fingerprint),
|
||||
)
|
||||
.await?;
|
||||
publish_headless_tls(load.tls, load.watch);
|
||||
return Ok(envelope);
|
||||
}
|
||||
let Some(file) = file else {
|
||||
let config = self.config.load().envelope.config.clone();
|
||||
return self
|
||||
@@ -30,17 +55,10 @@ impl App {
|
||||
.await;
|
||||
};
|
||||
let (config, fingerprint) =
|
||||
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)
|
||||
tokio::task::spawn_blocking(move || 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:#}")))?;
|
||||
}
|
||||
self.update_as_action(
|
||||
Update {
|
||||
expected_revision,
|
||||
|
||||
Reference in new issue
Block a user