diff --git a/AGENTS.md b/AGENTS.md index 2850704..d33bb42 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # RustProxy source and documentation maintenance -Current source version: **0.40.0**. The Cargo package and binary are named `rust-proxy`. +Current source version: **0.40.1**. The Cargo package and binary are named `rust-proxy`. Before editing, read [README.md](README.md), the relevant [documentation guide](docs/README.md) and the actual code and tests. Historical release experiments are not current specifications. Use the bundled `src/admin/openapi.json` for API routes and payloads; the source implementation is authoritative for runtime behavior. diff --git a/CHANGELOG.md b/CHANGELOG.md index e70ea23..474d571 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ Release history focused on **features, settings, default behavior, compatibility and fixes**. Changes to internal code structure and preliminary performance experiments are intentionally omitted. Historical descriptions reflect their respective releases; consult the current documentation for the settings available in the latest release. +## 0.40.1 — Forced certificate renewal (panel and headless) + +- **Panel — Force renewal now:** each managed ACME certificate in **Certificates → Automatic renewal** has a new action next to *Check now* and *Validate renewal (dry run)*. It runs `certbot renew --force-renewal` for that profile, so a new certificate is requested even if the current one is not due (key compromise, CA revocation, chain change). A confirmation explains the CA rate limits; the current certificate stays active until the new pair is validated and deployed. The job kind is `renewal-forced`, the audit action `acme.renew_forced`; if Certbot returns the installed pair unchanged the result is `acme.force_unchanged`. +- **API:** `POST /api/acme/renew` accepts `"force": true` (default `false`). It cannot be combined with `dry_run` (`400 acme.force_invalid`); the automatic scheduler never forces. OpenAPI updated. +- **CLI (panel mode):** new `rust-proxy tls renew --id ID [--force | --dry-run]`, using the local administration listener like `tls reload`. +- **Headless — `rust-proxy --headless tls renew [--force] [--id NAME|ID ...]`:** asks the running service to check its ACME certificates now (only due ones, ignoring the failure back-off) or, with `--force`, to request new ones regardless of expiry — all explicit and `acme.auto` certificates, or only those whose id or domain matches `--id`. The command writes `/headless-acme-renew.json` (`0600`, owned by the data directory owner) and sends `SIGUSR1`; the ACME task consumes the request once, after any request in progress. Requests older than 10 minutes are discarded; unknown targets are logged. On Linux the command refuses to signal a service that does not handle `SIGUSR1` (older than 0.40.1) instead of terminating it. `--dry-run` is rejected in headless mode (use `staging`). +- **Compatibility:** configuration format, existing API fields and default behaviour are unchanged; automatic renewal still lets Certbot decide when a certificate is due. +- **Verification:** new unit tests for the headless request file (round trip, single consumption, `0600`, stale/invalid requests, target matching by id and domain) and for rejecting `force` with `dry_run`/automatic renewal; Certbot worker request validation checked with Python; full suite passes (1029 library tests, 7 CLI tests), `cargo clippy --all-targets` and `cargo fmt --check` clean. The real binary was run in headless mode with two ACME certificates: `tls renew --force --id api.example.com` was picked up after the request in progress, forced only that certificate past its back-off and the request file was removed; `--dry-run` and invalid targets were refused. Issuance from a real CA and the panel button in a browser were not tested in this environment. + ## 0.40.0 — Headless HTTPS, automatic certificates, routes without a file and watch All additions are headless-only and optional; without them headless and panel mode behave as in 0.39.2. See [Headless mode](docs/HEADLESS.md#https-certificate-files-and-automatic-certificates). diff --git a/Cargo.lock b/Cargo.lock index 46d55c2..7913ccc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1914,7 +1914,7 @@ dependencies = [ [[package]] name = "rust-proxy" -version = "0.40.0" +version = "0.40.1" dependencies = [ "anyhow", "arc-swap", diff --git a/Cargo.toml b/Cargo.toml index 3239995..75ff804 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-proxy" -version = "0.40.0" +version = "0.40.1" edition = "2021" rust-version = "1.99.1" description = "RustProxy - independent reverse proxy with local administration" diff --git a/docs/CERTIFICATES.md b/docs/CERTIFICATES.md index 70e140f..31e6cd1 100644 --- a/docs/CERTIFICATES.md +++ b/docs/CERTIFICATES.md @@ -52,6 +52,26 @@ Provider tokens and TSIG secrets are security credentials: use least privilege, Managed certificates have configurable automatic renewal. RustProxy runs the scheduler while the service is active; this is **not** a separate cron service. Certificate status and next checks are visible in Certificates. The scheduler uses spaced checks and retry/backoff on failure, without automatically forcing a CA reissue on every check. +### Checking now or forcing a renewal + +Each managed certificate in **Certificates → Automatic renewal** has three actions: + +- **Check now** — runs `certbot renew` for that profile; Certbot decides whether the certificate is due (result `acme.not_due` otherwise). +- **Force renewal now** (since 0.40.1) — runs `certbot renew --force-renewal`, so a new certificate is requested from the CA even if the current one is far from expiry. Use it after a key compromise, a CA revocation, or when the names or chain must change immediately. The action asks for confirmation because every forced certificate counts against the CA rate limits (Let's Encrypt: 5 certificates for the same names per week). The current certificate stays active until the new pair is validated and deployed; the audit log records `acme.renew_forced`. +- **Validate renewal (dry run)** — tests the challenge against the staging CA and deploys nothing. + +The same is available through the API and the local CLI: + +```bash +# API (session or API token with certificate permissions) +curl -X POST https://admin.example.com/api/acme/renew -H 'content-type: application/json' \ + -d '{"certificate_id":"site","force":true}' +# local CLI on the server (uses the administration listener) +sudo rust-proxy --data-dir /var/lib/rustproxy tls renew --id site --force +``` + +`force` cannot be combined with `dry_run`. The renewal runs in the background; the job and the result are shown in the panel. Headless mode has its own command, see [Headless: forcing a new certificate](HEADLESS.md#forcing-a-new-certificate-tls-renew---force). + After successful renewal, RustProxy validates the new pair and publishes it to new TLS handshakes without interrupting existing connections. Invalid/rejected material should leave the previous active pair in place. Keep room for archived ACME generations and monitor expiry; this is not an independent external expiry-alert service. **Do not run an overlapping system Certbot timer** against the RustProxy-managed ACME profiles. ## Externally managed Certbot / PEM files diff --git a/docs/FEATURES.md b/docs/FEATURES.md index a2171be..bb3485a 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -42,7 +42,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se ## Certificates - Self-signed certificates, PEM import and externally managed certificate paths (for example Certbot). -- Managed ACME with HTTP-01 and DNS-01 (Cloudflare, OVH, RFC 2136), automatic renewal and job history. +- Managed ACME with HTTP-01 and DNS-01 (Cloudflare, OVH, RFC 2136), automatic renewal, on-demand check, forced renewal (panel, API, `tls renew --force`) and job history. - Certificate inventory with expiry, coverage check and bulk assignment to Vhosts. - Restricted certificate API keys for deploy/reload from external systems such as OPNsense. - Prometheus metrics for the expiry date and remaining days of every installed certificate, ready for alerting. @@ -97,7 +97,7 @@ RustProxy is a single service that combines a reverse proxy, a static/PHP web se - Configuration stored in SQLite or in a JSON file, with validation before activation and hot reload. - Headless mode without the panel: configuration from a read-only JSON file, catch-all `*` host, reload by `SIGHUP`/`systemctl reload` and a `/healthz` endpoint ([Headless mode](HEADLESS.md)). -- Headless HTTPS and Traefik-style operation: certificate files or directories (Certbot/acme.sh layouts) and automatic DV certificates with renewal (HTTP-01 or DNS-01 with Cloudflare, OVH, RFC 2136, wildcards), `acme.auto` for every vhost host, configured in a `"headless"` JSON section or on the command line; `--route HOST=URL` without a configuration file, `--force-https`, automatic reload on file changes (`watch`) and a `/certificates` status endpoint ([Headless mode](HEADLESS.md#https-certificate-files-and-automatic-certificates)). +- Headless HTTPS and Traefik-style operation: certificate files or directories (Certbot/acme.sh layouts) and automatic DV certificates with renewal (HTTP-01 or DNS-01 with Cloudflare, OVH, RFC 2136, wildcards), `acme.auto` for every vhost host, configured in a `"headless"` JSON section or on the command line; `--route HOST=URL` without a configuration file, `--force-https`, automatic reload on file changes (`watch`), forced re-issue of ACME certificates on demand (`rust-proxy --headless tls renew --force`) and a `/certificates` status endpoint ([Headless mode](HEADLESS.md#https-certificate-files-and-automatic-certificates)). - Revision history with diff and one-click restore. - Encrypted full backups and validated offline restore; encrypted Secret Store for credentials. - Docker and Podman discovery through a separate agent: publish containers as Vhosts with one switch, one-time agent provisioning codes, publishing from container labels, multiple domains and certificate lists per agent, per-app HTTP Basic Auth, method policy, rate limit, country access, security and diagnostic headers, a searchable list of published apps, host and container diagnostics with history, authenticated agent process diagnostics and bounded inventory polling, Docker alerts, Prometheus host metrics and optional Docker Overview cards; the Grafana dashboard covers several RustProxy servers. diff --git a/docs/HEADLESS.md b/docs/HEADLESS.md index bbda1d9..ea9067d 100644 --- a/docs/HEADLESS.md +++ b/docs/HEADLESS.md @@ -19,6 +19,7 @@ Available since 0.38.0. | Certificate files | import in the panel | `headless.tls` / `--tls-cert-file`, `--tls-cert-dir` (since 0.40.0) | | Configuration file | optional | required, unless `--route` is used (since 0.40.0) | | Automatic reload on file change | — | `"watch": true` / `--watch` (since 0.40.0) | +| Forced certificate renewal | **Force renewal now** in Automatic renewal, `POST /api/acme/renew` with `force`, `rust-proxy tls renew --id ID --force` | `rust-proxy --headless tls renew [--force] [--id NAME]` (since 0.40.1) | | Software update check | on | off | | Health endpoint | optional `--health-listen` | optional `--health-listen` | @@ -303,6 +304,25 @@ How it works: - A failed request is logged with the path of the Certbot log and retried after 10 minutes, 30 minutes, 1, 3, 6 and then every 12 hours; Let's Encrypt limits failed validations, so test new setups with `staging` first. If the configuration file is invalid at that moment, the certificate is kept and applied by the next successful reload. - Removing a name from `domains` changes the certificate id; the old entry in `headless-acme.json` is simply no longer used. +### Forcing a new certificate (`tls renew --force`) + +Since 0.40.1 the running service can be asked to request a certificate **now**, even if it is not due yet — for example after a key compromise, after switching from `staging` to production, or after a CA revocation: + +```bash +# re-issue every headless ACME certificate (explicit and acme.auto) +sudo rust-proxy --headless --data-dir /var/lib/rustproxy tls renew --force +# only the certificate containing this name (or with this hl-acme-… id); --id may be repeated or comma-separated +sudo rust-proxy --headless --data-dir /var/lib/rustproxy tls renew --force --id api.example.com +# without --force: check now and renew only what is due, also skipping the failure back-off +sudo rust-proxy --headless --data-dir /var/lib/rustproxy tls renew +``` + +- The command writes a short request to `/headless-acme-renew.json` (mode `0600`, owned by the owner of the data directory) and sends `SIGUSR1` to the process in `/rustproxy.pid`. The ACME task picks it up as soon as the request in progress (if any) finishes; it is processed once and deleted. Requests older than 10 minutes are discarded, so a request left behind while the service was stopped never forces a renewal after a restart. +- A forced request skips the expiry check and the failure back-off; the new certificate is installed exactly like a renewal (internal reload, connections and cache kept, the previous generation deleted). If it fails, the old certificate stays active and normal retries follow. +- Targets that match no ACME certificate are logged as warnings. Progress and results are in the service log and in [`/certificates`](#certificate-status-certificates). +- Every forced certificate counts against the CA rate limits (Let's Encrypt: 5 certificates for the same set of names per week); use `staging` to test. +- `--dry-run` is panel-only; in headless mode test with `staging`. A service older than 0.40.1 does not handle `SIGUSR1`, so on Linux the command checks this first and refuses instead of stopping it. + ### Automatic certificates for every vhost (`acme.auto`) Like a Traefik certificate resolver attached to every router: with `"auto": true` (or `--acme-auto`) RustProxy collects the hosts of all enabled vhosts and redirects, leaves out those already covered by another certificate (from `tls.certificates`, certificate files/directories or `acme.domains`, wildcards included), and requests **one certificate per vhost** for the rest (up to 16 names each, at most 64 automatic certificates). Skipped automatically: `*`, IP addresses, single-label names and, with HTTP-01, wildcard hosts (they are requested with a DNS-01 provider). diff --git a/docs/README.md b/docs/README.md index ca83f55..2f236c1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,7 +31,7 @@ Guides for operating RustProxy: installation, publishing services, security, cer ## Security and access - [Access and authentication](ACCESS.md) — ACLs, countries, rate limits, Basic Auth, Forward Auth and OIDC. -- [Certificates](CERTIFICATES.md) — PEM import, ACME HTTP-01/DNS-01, external Certbot files and automatic renewal. +- [Certificates](CERTIFICATES.md) — PEM import, ACME HTTP-01/DNS-01, external Certbot files, automatic and forced renewal. - [Security model](SECURITY.md) — trust boundaries and deployment recommendations. ## Performance and delivery diff --git a/langs/en_US.json b/langs/en_US.json index 8021707..bfa18aa 100644 --- a/langs/en_US.json +++ b/langs/en_US.json @@ -916,6 +916,11 @@ "renewalDisable": "Disable automatic renewal", "renewalNow": "Check now", "renewalDryRun": "Validate renewal (dry run)", + "renewalForce": "Force renewal now", + "renewalForceConfirm": "Request a new certificate from the CA now, even though it is not due yet? Each forced renewal counts against the CA rate limits (Let's Encrypt: 5 identical certificates per week). The current certificate stays active until the new one is validated and deployed.", + "acme.renewing_forced": "Forcing certificate renewal", + "acme.force_unchanged": "Forced renewal finished but Certbot returned the installed certificate; nothing changed.", + "acme.force_invalid": "A forced renewal cannot be combined with a dry run or automatic renewal.", "renewalLast": "Last check", "renewalNext": "Next check", "renewalExpires": "Valid until", diff --git a/langs/pl_pl.json b/langs/pl_pl.json index e894f1e..b1d4924 100644 --- a/langs/pl_pl.json +++ b/langs/pl_pl.json @@ -916,6 +916,11 @@ "renewalDisable": "Wyłącz odnawianie", "renewalNow": "Sprawdź teraz", "renewalDryRun": "Sprawdź odnowienie (dry run)", + "renewalForce": "Wymuś odnowienie teraz", + "renewalForceConfirm": "Pobrać teraz nowy certyfikat z CA, mimo że nie jest jeszcze wymagane odnowienie? Każde wymuszone odnowienie liczy się do limitów CA (Let's Encrypt: 5 identycznych certyfikatów tygodniowo). Obecny certyfikat działa do czasu sprawdzenia i wdrożenia nowego.", + "acme.renewing_forced": "Wymuszanie odnowienia certyfikatu", + "acme.force_unchanged": "Wymuszone odnowienie zakończone, ale Certbot zwrócił zainstalowany certyfikat; nic nie zmieniono.", + "acme.force_invalid": "Wymuszonego odnowienia nie można łączyć z trybem dry run ani z automatycznym odnawianiem.", "renewalLast": "Ostatnia kontrola", "renewalNext": "Kolejna kontrola", "renewalExpires": "Ważny do", diff --git a/scripts/runtime/acme_provider.py b/scripts/runtime/acme_provider.py index 8422275..f3edf3e 100755 --- a/scripts/runtime/acme_provider.py +++ b/scripts/runtime/acme_provider.py @@ -321,7 +321,7 @@ def certificate_dates(pem: bytes, executable: str | None = None) -> dict: def renewal_request(raw: object) -> dict: - if not isinstance(raw, dict) or set(raw) - {"action", "certificate_id", "provider", "environment", "cert_file", "key_file", "dry_run", "credential_ini_b64"}: + if not isinstance(raw, dict) or set(raw) - {"action", "certificate_id", "provider", "environment", "cert_file", "key_file", "dry_run", "force", "credential_ini_b64"}: raise AcmeError("acme.invalid_renewal_request") if raw.get("action") != "renew" or raw.get("provider") not in PROVIDERS or raw.get("environment") not in DIRECTORIES: raise AcmeError("acme.invalid_renewal_request") @@ -331,7 +331,9 @@ def renewal_request(raw: object) -> dict: value = raw.get(name) if not isinstance(value, str) or not re.fullmatch(r"acme-[A-Za-z0-9_-]{1,80}" + re.escape(suffix), value): raise AcmeError("acme.invalid_renewal_request") - if type(raw.get("dry_run", False)) is not bool: + if type(raw.get("dry_run", False)) is not bool or type(raw.get("force", False)) is not bool: + raise AcmeError("acme.invalid_renewal_request") + if raw.get("dry_run", False) and raw.get("force", False): raise AcmeError("acme.invalid_renewal_request") if raw["provider"] != "http01": encoded = raw.get("credential_ini_b64") @@ -343,16 +345,17 @@ def renewal_request(raw: object) -> dict: raise AcmeError("acme.invalid_api_credential") else: credential_ini = b"" - value = dict(raw, dry_run=raw.get("dry_run", False)) + value = dict(raw, dry_run=raw.get("dry_run", False), force=raw.get("force", False)) value["credential_ini"] = credential_ini value.pop("credential_ini_b64", None) return value def renew(raw: dict, certificate_directory: Path, executable: str | None = None) -> dict: - """Renew ONE existing, consented lineage; never force issuance or create a profile. + """Renew ONE existing, consented lineage; never create a profile. - Certbot decides when a certificate is due (including its ARI support). A zero + Certbot decides when a certificate is due (including its ARI support) unless + the operator explicitly forces a renewal (`--force-renewal`). A zero exit status alone does not prove a renewal: compare actual certificate/key bytes with the installed generation, so crash-after-renewal is recoverable. Dry-run validates challenge access but never stages/deploys its test output. @@ -406,6 +409,8 @@ def renew(raw: dict, certificate_directory: Path, executable: str | None = None) "--config-dir", str(work / "config"), "--work-dir", str(work / "work"), "--logs-dir", str(work / "logs")] if value["dry_run"]: args.append("--dry-run") + elif value["force"]: + args.append("--force-renewal") try: result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2100, check=False) diff --git a/src/acme/headless.rs b/src/acme/headless.rs index 0477153..3d7b7d2 100644 --- a/src/acme/headless.rs +++ b/src/acme/headless.rs @@ -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 = + 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, + 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 { + 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, 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 = Default::default(); let mut failures: std::collections::HashMap = Default::default(); let mut fingerprint: Option<(String, String)> = None; + let mut forced: std::collections::HashSet = 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 = 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)) => {} } } diff --git a/src/acme/jobs.rs b/src/acme/jobs.rs index 8078598..da1e80e 100644 --- a/src/acme/jobs.rs +++ b/src/acme/jobs.rs @@ -24,8 +24,15 @@ impl Manager { id: &str, actor: String, dry_run: bool, + force: bool, automatic: bool, ) -> Result { + 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 diff --git a/src/acme/tests.rs b/src/acme/tests.rs index e1f027e..892e99f 100644 --- a/src/acme/tests.rs +++ b/src/acme/tests.rs @@ -5,7 +5,7 @@ mod renewal_regressions { config::{self, Config, ValidationPolicy}, db::Store, }; - async fn configured(automatic: bool) -> (Arc, tempfile::TempDir, Certificate, Value) { + pub(super) async fn configured(automatic: bool) -> (Arc, 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"); + } + } +} diff --git a/src/admin/certificates.rs b/src/admin/certificates.rs index 43ea3b5..9c9c42b 100644 --- a/src/admin/certificates.rs +++ b/src/admin/certificates.rs @@ -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, } diff --git a/src/admin/openapi.json b/src/admin/openapi.json index 0a79acd..ddf64d7 100644 --- a/src/admin/openapi.json +++ b/src/admin/openapi.json @@ -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" ], diff --git a/src/admin/tail.rs b/src/admin/tail.rs index 07badf8..3d62d7b 100644 --- a/src/admin/tail.rs +++ b/src/admin/tail.rs @@ -8,6 +8,7 @@ async fn acme_renew( &input.certificate_id, session.username, input.dry_run, + input.force, false, ) .await?; diff --git a/src/admin/web/acme.js b/src/admin/web/acme.js index 27b2daf..29ce6b4 100644 --- a/src/admin/web/acme.js +++ b/src/admin/web/acme.js @@ -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; } diff --git a/src/main/admin_runtime.rs b/src/main/admin_runtime.rs index 2dcb7ee..5237f2a 100644 --- a/src/main/admin_runtime.rs +++ b/src/main/admin_runtime.rs @@ -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"); } diff --git a/src/main/bootstrap.rs b/src/main/bootstrap.rs index fc5e301..c4d2d78 100644 --- a/src/main/bootstrap.rs +++ b/src/main/bootstrap.rs @@ -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, + /// 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), diff --git a/src/main/headless.rs b/src/main/headless.rs index 7173bc4..7d74751 100644 --- a/src/main/headless.rs +++ b/src/main/headless.rs @@ -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 `/rustproxy.pid`. +fn headless_service_pid(data_dir: &Path) -> Result { 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, 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 = 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, diff --git a/src/main/shutdown/mod.rs b/src/main/shutdown/mod.rs index 4a8891d..3aa3a0f 100644 --- a/src/main/shutdown/mod.rs +++ b/src/main/shutdown/mod.rs @@ -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>(()) })