This commit is contained in:
Mateusz Gruszczyński committed 2026-11-22 15:35:11 +01:00
1 parent 748fe1d146
commit 27b640a0df
22 files changed
+532 -30

No files matched your search

+196 -5
View File
@@ -6,6 +6,137 @@
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];
/// Renewal request left in the data directory by `rust-proxy --headless tls renew`.
pub const HEADLESS_ACME_RENEW_FILE: &str = "headless-acme-renew.json";
/// Requests older than this (for example written while the service was down)
/// are discarded instead of forcing a renewal after a later restart.
const HEADLESS_ACME_RENEW_MAX_AGE: i64 = 600;
const HEADLESS_ACME_RENEW_MAX_TARGETS: usize = 64;
static HEADLESS_ACME_RENEW: std::sync::LazyLock<tokio::sync::Notify> =
std::sync::LazyLock::new(tokio::sync::Notify::new);
/// Operator request to check (or, with `force`, re-issue) headless ACME
/// certificates now. An empty target list means every headless ACME certificate;
/// a target is a certificate id (`hl-acme-…`) or one of its domain names.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HeadlessRenewRequest {
#[serde(default)]
pub force: bool,
#[serde(default)]
pub targets: Vec<String>,
pub requested_at: i64,
}
impl HeadlessRenewRequest {
fn validate(&self) -> Result<(), String> {
if self.targets.len() > HEADLESS_ACME_RENEW_MAX_TARGETS {
return Err("too many renewal targets".into());
}
for target in &self.targets {
if target.is_empty()
|| target.len() > 253
|| !target
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b'*'))
{
return Err(format!("invalid renewal target {target:?}"));
}
}
Ok(())
}
/// Whether this request selects the certificate `id` covering `names`.
pub fn selects(&self, id: &str, names: &[String]) -> bool {
self.targets.is_empty()
|| self.targets.iter().any(|target| {
target == id || names.iter().any(|name| name.eq_ignore_ascii_case(target))
})
}
}
/// Writes a renewal request for the running headless service (atomically,
/// mode 0600, owned by the owner of the data directory).
pub fn write_headless_renew_request(
data_dir: &std::path::Path,
request: &HeadlessRenewRequest,
) -> anyhow::Result<std::path::PathBuf> {
request.validate().map_err(anyhow::Error::msg)?;
let path = data_dir.join(HEADLESS_ACME_RENEW_FILE);
let temporary = data_dir.join(format!(".{HEADLESS_ACME_RENEW_FILE}.{}", std::process::id()));
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 _ = std::fs::remove_file(&temporary);
let result = (|| {
let mut file = options.open(&temporary)?;
std::io::Write::write_all(&mut file, &serde_json::to_vec(request)?)?;
file.sync_all()?;
#[cfg(unix)]
{
// The CLI usually runs as root while the service runs as its own user.
use std::os::unix::fs::MetadataExt;
let owner = std::fs::metadata(data_dir)?;
if owner.uid() != unsafe { libc::geteuid() } {
std::os::unix::fs::chown(&temporary, Some(owner.uid()), Some(owner.gid()))?;
}
}
std::fs::rename(&temporary, &path)?;
Ok::<_, anyhow::Error>(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
result.map(|()| path)
}
/// Reads and removes a pending renewal request. Invalid or stale requests are
/// removed and reported as errors.
pub fn take_headless_renew_request(
data_dir: &std::path::Path,
now: i64,
) -> Result<Option<HeadlessRenewRequest>, String> {
let path = data_dir.join(HEADLESS_ACME_RENEW_FILE);
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(None),
Err(error) => {
let _ = std::fs::remove_file(&path);
return Err(format!("cannot read {}: {error}", path.display()));
}
};
let mut text = Vec::new();
let read = std::io::Read::read_to_end(&mut std::io::Read::take(file, 65_537), &mut text);
let _ = std::fs::remove_file(&path);
read.map_err(|error| format!("cannot read {}: {error}", path.display()))?;
if text.len() > 65_536 {
return Err("renewal request is too large".into());
}
let request: HeadlessRenewRequest =
serde_json::from_slice(&text).map_err(|error| format!("invalid renewal request: {error}"))?;
request.validate()?;
if request.requested_at + HEADLESS_ACME_RENEW_MAX_AGE < now || request.requested_at > now + 60 {
return Err("renewal request is stale (written while the service was not running?)".into());
}
Ok(Some(request))
}
/// Wakes the headless ACME task to process a renewal request (SIGUSR1).
pub fn request_headless_acme_renewal() {
HEADLESS_ACME_RENEW.notify_one();
}
fn headless_acme_due(
directory: &std::path::Path,
@@ -289,6 +420,7 @@ pub async fn headless_loop(
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;
let mut forced: std::collections::HashSet<String> = Default::default();
loop {
let Some(state) = weak.upgrade() else {
return;
@@ -298,6 +430,25 @@ pub async fn headless_loop(
return;
};
let acme = crate::runtime::headless_tls().and_then(|tls| tls.acme);
let renew_request = match state.policy.data_dir.clone() {
Some(data_dir) => {
let now = crate::auth::now();
tokio::task::spawn_blocking(move || take_headless_renew_request(&data_dir, now))
.await
.unwrap_or_else(|_| Err("acme.validation_worker_failed".into()))
}
None => Ok(None),
};
let renew_request = match renew_request {
Ok(request) => request,
Err(error) => {
tracing::error!(%error, "headless ACME renewal request ignored");
None
}
};
if renew_request.is_some() && acme.is_none() {
tracing::warn!("headless ACME renewal requested, but no ACME certificates are configured");
}
if let Some(acme) = acme.clone() {
// A changed provider/environment makes every certificate due again.
let current = (acme.provider.clone(), acme.environment.clone());
@@ -329,6 +480,36 @@ pub async fn headless_loop(
if let Ok(mut status) = HEADLESS_ACME_STATUS.lock() {
status.retain(|id, _| ids.contains(id));
}
forced.retain(|id| ids.contains(id));
if let Some(request) = &renew_request {
let selected: Vec<String> = wanted
.iter()
.map(|(names, _)| (crate::runtime::headless_acme_certificate_id(names), names))
.filter(|(id, names)| request.selects(id, names))
.map(|(id, _)| id)
.collect();
for target in &request.targets {
let known = wanted.iter().any(|(names, _)| {
HeadlessRenewRequest {
targets: vec![target.clone()],
..Default::default()
}
.selects(&crate::runtime::headless_acme_certificate_id(names), names)
});
if !known {
tracing::warn!(%target, "headless ACME renewal target matches no ACME certificate");
}
}
for id in &selected {
next.remove(id);
failures.remove(id);
if request.force {
forced.insert(id.clone());
}
}
tracing::info!(certificates = ?selected, force = request.force,
"headless ACME renewal requested by the operator");
}
for (names, auto) in &wanted {
if shutdown.is_cancelled() {
return;
@@ -342,15 +523,21 @@ pub async fn headless_loop(
if next.get(&id).is_some_and(|at| *at > now) {
continue;
}
let force = forced.contains(&id);
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()));
let due = if force {
tracing::info!(certificate = %id, domains = ?names, "forced ACME renewal");
Ok(true)
} else {
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);
@@ -377,6 +564,9 @@ pub async fn headless_loop(
Err(error) => Err(error),
};
let now = crate::auth::now();
if result.as_ref().err().is_none_or(|error| error != "acme.job_busy") {
forced.remove(&id);
}
match result {
Ok(()) => {
failures.remove(&id);
@@ -437,6 +627,7 @@ pub async fn headless_loop(
tokio::select! {
_ = shutdown.cancelled() => return,
_ = crate::runtime::headless_changed() => {}
_ = HEADLESS_ACME_RENEW.notified() => {}
_ = tokio::time::sleep(Duration::from_secs(wait as u64)) => {}
}
}
+21 -2
View File
@@ -24,8 +24,15 @@ impl Manager {
id: &str,
actor: String,
dry_run: bool,
force: bool,
automatic: bool,
) -> Result<Job, ApiError> {
if force && (dry_run || automatic) {
return Err(ApiError(
StatusCode::BAD_REQUEST,
"acme.force_invalid".into(),
));
}
let directory = state.policy.cert_dir.clone().ok_or_else(|| {
ApiError(StatusCode::CONFLICT, "acme.no_certificate_directory".into())
})?;
@@ -74,6 +81,8 @@ impl Manager {
status: "running",
kind: if dry_run {
"renewal-dry-run"
} else if force {
"renewal-forced"
} else {
"renewal"
},
@@ -86,7 +95,12 @@ impl Manager {
provider: issuer.provider.clone(),
domains,
environment: issuer.environment.clone(),
message: "acme.renewing".into(),
message: if force {
"acme.renewing_forced"
} else {
"acme.renewing"
}
.into(),
certificate: None,
};
state
@@ -95,6 +109,8 @@ impl Manager {
&actor,
if dry_run {
"acme.renew_dry_run"
} else if force {
"acme.renew_forced"
} else {
"acme.renew"
},
@@ -104,7 +120,7 @@ impl Manager {
.map_err(crate::auth::internal)?;
*state.acme.job.lock().unwrap_or_else(|e| e.into_inner()) = Some(job.clone());
let mut request = serde_json::json!({"action":"renew","certificate_id":cert.id,"provider":issuer.provider,
"environment":issuer.environment,"cert_file":cert.cert_file,"key_file":cert.key_file,"dry_run":dry_run});
"environment":issuer.environment,"cert_file":cert.cert_file,"key_file":cert.key_file,"dry_run":dry_run,"force":force});
if issuer.provider != "http01" {
let data_dir = state.policy.data_dir.as_ref().ok_or_else(|| {
ApiError(StatusCode::CONFLICT, "acme.secret_store_unavailable".into())
@@ -155,6 +171,8 @@ impl Manager {
"acme.renewal_test_ok"
} else if changed {
"acme.renewed"
} else if force {
"acme.force_unchanged"
} else {
"acme.not_due"
}
@@ -313,6 +331,7 @@ pub async fn renewal_loop(
&cert.id,
"system:certificate-renewal".into(),
false,
false,
true,
)
.await
+65 -1
View File
@@ -5,7 +5,7 @@ mod renewal_regressions {
config::{self, Config, ValidationPolicy},
db::Store,
};
async fn configured(automatic: bool) -> (Arc<App>, tempfile::TempDir, Certificate, Value) {
pub(super) async fn configured(automatic: bool) -> (Arc<App>, tempfile::TempDir, Certificate, Value) {
let directory = tempfile::tempdir().unwrap();
let cert_dir = directory.path().join("certs");
crate::tls::initialize_default(&cert_dir).unwrap();
@@ -253,3 +253,67 @@ mod runtime_metadata_tests {
assert!(runtime_versions(&executable, true, None).pip.is_none());
}
}
mod forced_renewal {
use super::*;
fn request(force: bool, targets: &[&str], requested_at: i64) -> HeadlessRenewRequest {
HeadlessRenewRequest {
force,
targets: targets.iter().map(|t| t.to_string()).collect(),
requested_at,
}
}
#[test]
fn headless_renew_request_round_trips_and_is_consumed_once() {
let temp = tempfile::tempdir().unwrap();
let now = crate::auth::now();
let written = request(true, &["example.com"], now);
let path = write_headless_renew_request(temp.path(), &written).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
}
assert_eq!(take_headless_renew_request(temp.path(), now).unwrap(), Some(written));
assert!(!path.exists());
assert_eq!(take_headless_renew_request(temp.path(), now).unwrap(), None);
}
#[test]
fn stale_or_invalid_headless_renew_requests_are_discarded() {
let temp = tempfile::tempdir().unwrap();
let now = crate::auth::now();
write_headless_renew_request(temp.path(), &request(true, &[], now - 3600)).unwrap();
assert!(take_headless_renew_request(temp.path(), now).is_err());
assert!(!temp.path().join(HEADLESS_ACME_RENEW_FILE).exists());
assert!(write_headless_renew_request(temp.path(), &request(true, &["a b"], now)).is_err());
std::fs::write(temp.path().join(HEADLESS_ACME_RENEW_FILE), b"{\"force\":1}").unwrap();
assert!(take_headless_renew_request(temp.path(), now).is_err());
assert!(!temp.path().join(HEADLESS_ACME_RENEW_FILE).exists());
}
#[test]
fn headless_renew_request_selects_by_id_or_domain() {
let names = vec!["example.com".to_owned(), "www.example.com".to_owned()];
let id = crate::runtime::headless_acme_certificate_id(&names);
assert!(request(true, &[], 0).selects(&id, &names));
assert!(request(true, &["WWW.example.com"], 0).selects(&id, &names));
assert!(request(true, &[id.as_str()], 0).selects(&id, &names));
assert!(!request(true, &["other.example"], 0).selects(&id, &names));
}
#[tokio::test]
async fn forced_renewal_cannot_be_a_dry_run_or_automatic() {
let (app, _directory, cert, _) = super::renewal_regressions::configured(true).await;
for (dry_run, automatic) in [(true, false), (false, true)] {
let error = Manager::renew(app.clone(), &cert.id, "test".into(), dry_run, true, automatic)
.await
.unwrap_err();
assert_eq!(error.0, StatusCode::BAD_REQUEST);
assert_eq!(error.1, "acme.force_invalid");
}
}
}
+3
View File
@@ -498,4 +498,7 @@ struct RenewRequest {
certificate_id: String,
#[serde(default)]
dry_run: bool,
/// Renew even when Certbot does not consider the certificate due.
#[serde(default)]
force: bool,
}
+6 -1
View File
@@ -1458,6 +1458,11 @@
"dry_run": {
"type": "boolean",
"default": false
},
"force": {
"type": "boolean",
"default": false,
"description": "Request a new certificate now even if Certbot does not consider it due (certbot --force-renewal). Cannot be combined with dry_run. Counts against CA rate limits."
}
},
"additionalProperties": false,
@@ -10781,7 +10786,7 @@
},
"/api/acme/renew": {
"post": {
"summary": "Check/renew a managed certificate",
"summary": "Check, test or force renewal of a managed certificate",
"tags": [
"Certificates"
],
+1
View File
@@ -8,6 +8,7 @@ async fn acme_renew(
&input.certificate_id,
session.username,
input.dry_run,
input.force,
false,
)
.await?;
+4 -3
View File
@@ -138,12 +138,13 @@
if (!envelope) return; const next = structuredClone(envelope.config), target = next.tls.certificates.find(c => c.id === cert.id); if (!target?.issuer) return;
target.issuer.auto_renew = !enabled; if (await saveSection("tls", next.tls || {})) void refresh();
});
for (const [key, dry_run] of [["renewalNow", false], ["renewalDryRun", true]]) {
for (const [key, dry_run, force] of [["renewalNow", false, false], ["renewalForce", false, true], ["renewalDryRun", true, false]]) {
const node = b(key, async () => {
if (force && !(await appConfirm(t("renewalForceConfirm"), { danger: true }))) return;
node.disabled = true; const epoch = authEpoch;
try {
const data = await api("/api/acme/renew", { method: "POST", body: JSON.stringify({ certificate_id: cert.id, dry_run }) });
if (epoch === authEpoch && authenticated) { render(data.job); selectTab("renewal"); toast(t("acme.renewing")); }
const data = await api("/api/acme/renew", { method: "POST", body: JSON.stringify({ certificate_id: cert.id, dry_run, force }) });
if (epoch === authEpoch && authenticated) { render(data.job); selectTab("renewal"); toast(t(force ? "acme.renewing_forced" : "acme.renewing")); }
} catch (error) {
if (epoch === authEpoch) toast(error.message, true);
} finally { node.disabled = false; }
+1
View File
@@ -547,6 +547,7 @@ async fn run(
acme.provider,
data_dir.join("certs").join(rust_proxy::runtime::HEADLESS_ACME_STATE).display()
);
println!(" Renew: rust-proxy --headless tls renew [--force] [--id NAME]");
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");
}
+29
View File
@@ -166,6 +166,22 @@ enum TlsCommand {
key: PathBuf,
},
Reload,
/// Check or force renewal of ACME certificates.
///
/// Panel mode: one managed certificate (`--id`) through the administration
/// API. Headless mode: the running service's ACME certificates (all, or
/// those matching `--id` by certificate id or domain name).
Renew {
/// Certificate id; in headless mode also a domain name (repeatable)
#[arg(long = "id", value_delimiter = ',')]
ids: Vec<String>,
/// Request a new certificate even if it is not due yet (counts against CA rate limits)
#[arg(long, conflicts_with = "dry_run")]
force: bool,
/// Panel mode only: validate the renewal without deploying it
#[arg(long)]
dry_run: bool,
},
}
#[derive(Args)]
struct ServeOptions {
@@ -482,6 +498,19 @@ async fn application() -> Result<()> {
)
.await
}
Command::Tls {
action: TlsCommand::Renew { ids, force, dry_run },
} if cli.headless => {
ensure!(
!dry_run,
"--dry-run is not available in headless mode; use --acme-staging to test issuance"
);
signal_headless_renew(
&resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
ids,
force,
)
}
Command::Reload => {
config_command(
resolve_installed_data_dir(cli.data_dir, data_dir_explicit),
+87 -7
View File
@@ -33,9 +33,13 @@ async fn headless_reload_loop(
#[cfg(unix)]
{
let mut hangup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())?;
// SIGUSR1: `rust-proxy --headless tls renew` left a renewal request.
let mut renew =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::user_defined1())?;
loop {
tokio::select! {
_ = shutdown.cancelled() => return Ok(()),
_ = renew.recv() => rust_proxy::acme::request_headless_acme_renewal(),
_ = hangup.recv() => {
let revision = state.config.load().envelope.revision;
match state.reload_from_file(revision).await {
@@ -66,7 +70,8 @@ async fn headless_reload_loop(
}
}
fn signal_headless_reload(data_dir: &Path) -> Result<()> {
/// Process id of the running headless service, from `<data-dir>/rustproxy.pid`.
fn headless_service_pid(data_dir: &Path) -> Result<i32> {
let path = data_dir.join(HEADLESS_PID_FILE);
let text = std::fs::read_to_string(&path).with_context(|| {
format!(
@@ -89,14 +94,25 @@ fn signal_headless_reload(data_dir: &Path) -> Result<()> {
path.display()
);
}
Ok(pid)
}
#[cfg(unix)]
fn signal_headless_service(pid: i32, signal: libc::c_int) -> Result<()> {
let result = unsafe { libc::kill(pid, signal) };
ensure!(
result == 0,
"cannot signal RustProxy process {pid}: {}",
io::Error::last_os_error()
);
Ok(())
}
fn signal_headless_reload(data_dir: &Path) -> Result<()> {
let pid = headless_service_pid(data_dir)?;
#[cfg(unix)]
{
let result = unsafe { libc::kill(pid, libc::SIGHUP) };
ensure!(
result == 0,
"cannot signal RustProxy process {pid}: {}",
io::Error::last_os_error()
);
signal_headless_service(pid, libc::SIGHUP)?;
println!(
"Reload requested (SIGHUP to process {pid}); the result is written to the service log."
);
@@ -109,6 +125,70 @@ fn signal_headless_reload(data_dir: &Path) -> Result<()> {
}
}
/// Whether the process handles SIGUSR1 (0.40.1+). Older services would be
/// terminated by it, so the request is refused instead.
#[cfg(target_os = "linux")]
fn headless_service_handles_renew(pid: i32) -> bool {
std::fs::read_to_string(format!("/proc/{pid}/status"))
.ok()
.and_then(|status| {
status
.lines()
.find_map(|line| line.strip_prefix("SigCgt:"))
.and_then(|mask| u64::from_str_radix(mask.trim(), 16).ok())
})
.is_some_and(|mask| mask & (1 << (libc::SIGUSR1 - 1)) != 0)
}
/// `rust-proxy --headless tls renew [--force] [--id ID|DOMAIN ...]`: asks the
/// running headless service to check (or re-issue) its ACME certificates now.
fn signal_headless_renew(data_dir: &Path, targets: Vec<String>, force: bool) -> Result<()> {
let pid = headless_service_pid(data_dir)?;
#[cfg(target_os = "linux")]
ensure!(
headless_service_handles_renew(pid),
"the running RustProxy (process {pid}) does not accept renewal requests; restart it with version 0.40.1 or newer"
);
#[cfg(unix)]
{
let targets: Vec<String> = targets
.into_iter()
.map(|target| target.trim().to_ascii_lowercase())
.filter(|target| !target.is_empty())
.collect();
let request = rust_proxy::acme::HeadlessRenewRequest {
force,
targets: targets.clone(),
requested_at: rust_proxy::auth::now(),
};
let path = rust_proxy::acme::write_headless_renew_request(data_dir, &request)?;
if let Err(error) = signal_headless_service(pid, libc::SIGUSR1) {
let _ = std::fs::remove_file(path);
return Err(error);
}
let scope = if targets.is_empty() {
"all headless ACME certificates".to_owned()
} else {
targets.join(", ")
};
if force {
println!(
"Forced renewal requested for {scope} (SIGUSR1 to process {pid}). New certificates are requested from the CA even if not due; progress is written to the service log and /certificates on the health listener."
);
} else {
println!(
"Renewal check requested for {scope} (SIGUSR1 to process {pid}). Certificates that are due are renewed; progress is written to the service log and /certificates on the health listener."
);
}
Ok(())
}
#[cfg(not(unix))]
{
let _ = (pid, targets, force);
bail!("headless renewal requests are only available on Unix")
}
}
async fn validate_headless_file(
data_dir: PathBuf,
admin_addr: SocketAddr,
+44
View File
@@ -108,6 +108,49 @@ async fn config_command(dir: PathBuf, addr: SocketAddr, action: ConfigCommand) -
}
async fn tls_command(dir: PathBuf, addr: SocketAddr, action: TlsCommand) -> Result<()> {
if let TlsCommand::Renew { ids, force, dry_run } = &action {
ensure!(
ids.len() == 1,
"panel mode renews one managed certificate: pass exactly one --id (see Settings → Certificates → Automatic renewal)"
);
let id = ids[0].clone();
auth::prepare_directory(&dir)?;
let path = dir.join("config.sqlite3");
ensure!(
path.is_file(),
"database does not exist at {}; start rust-proxy serve first",
path.display()
);
auth::prepare_database(&path)?;
let store = Store::open(&path, &Config::default()).await?;
let admin = LocalAdminClient::connect(&dir, addr).await?;
let (force, dry_run) = (*force, *dry_run);
let result = async {
let record = store.admin_record().await?.context("create the administrator first")?;
let session = store.create_session(record.generation, "cli", None).await?.context("credentials changed; retry CLI operation")?;
let body = serde_json::json!({"certificate_id": id, "dry_run": dry_run, "force": force}).to_string();
let response = api(&admin, &session, Method::POST, "/api/acme/renew", Some(body)).await;
if let Err(error) = store.end_session(&session.session).await {
tracing::warn!(%error, "CLI session cleanup failed; the capability expires after 60 seconds");
}
let payload: serde_json::Value = serde_json::from_str(&response?)?;
let what = if dry_run {
"Renewal validation (dry run)"
} else if force {
"Forced renewal"
} else {
"Renewal check"
};
println!(
"{what} of certificate {id} started (job {}). Certbot runs in the background; the result appears in the panel under Automatic renewal and in the audit log.",
payload["job"]["id"].as_str().unwrap_or("?")
);
Ok::<_, anyhow::Error>(())
}
.await;
store.close().await;
return result;
}
if matches!(&action, TlsCommand::Reload) {
auth::prepare_directory(&dir)?;
let path = dir.join("config.sqlite3");
@@ -227,6 +270,7 @@ async fn tls_command(dir: PathBuf, addr: SocketAddr, action: TlsCommand) -> Resu
}
TlsCommand::Deploy { .. } => unreachable!("handled above"),
TlsCommand::Reload => unreachable!("handled above"),
TlsCommand::Renew { .. } => unreachable!("handled above"),
}
Ok::<_, anyhow::Error>(())
})