[edge] Reload and share links: in-process config swap with self-reverting trials, admin socket with health and certificate status, share-link cookies, visitor pages and throttle
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! State that lives as long as the process, across config reloads (ROADMAP §8.4).
|
||||
//!
|
||||
//! A reload builds a complete new [`Runtime`] from the config file and swaps it in with one
|
||||
//! atomic pointer store. Listeners, TLS sessions and keep-alive connections are untouched:
|
||||
//! each request takes the runtime that is current when it starts and keeps it until it ends,
|
||||
//! so nothing in flight sees a half-applied config, and the next request on the same
|
||||
//! connection already uses the new one. A config that fails to build is refused and the old
|
||||
//! one keeps serving.
|
||||
//!
|
||||
//! A **trial** is a reload control has not confirmed yet: edge keeps the previous runtime and
|
||||
//! swaps it back by itself when the deadline passes without a confirmation. So if control
|
||||
//! dies in the middle of an apply, edge returns to the last good config on its own, and
|
||||
//! because the trial is read from a separate file, a restarted edge reads the last good
|
||||
//! config too.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use ianitor_core::share::{Revocations, ShareId};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::error::EdgeError;
|
||||
use crate::logging::now_secs;
|
||||
use crate::runtime::{self, Runtime};
|
||||
use crate::tls::CertStore;
|
||||
|
||||
/// Health probes of watched hosts during a trial.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WatchSpec {
|
||||
pub hosts: Vec<String>,
|
||||
pub every: Duration,
|
||||
}
|
||||
|
||||
struct Trial {
|
||||
id: u64,
|
||||
sha256: String,
|
||||
previous: Arc<Runtime>,
|
||||
deadline: Instant,
|
||||
}
|
||||
|
||||
/// The share-link revocation file as edge last read it.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct RevocationState {
|
||||
pub revocations: Revocations,
|
||||
/// False when the file is missing or never read: share links are then refused.
|
||||
pub loaded: bool,
|
||||
pub error: Option<String>,
|
||||
/// SHA-256 of the file as last read; the poller re-reads when it changes.
|
||||
stamp: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct RevocationFile {
|
||||
epoch: u32,
|
||||
deny: Vec<String>,
|
||||
}
|
||||
|
||||
/// Most ids on the deny list.
|
||||
pub const MAX_DENY: usize = 10_000;
|
||||
|
||||
/// Certificate state per host, for control (docs/ui-api.md G5).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CertState {
|
||||
/// `ok`, `pending` or `failed`.
|
||||
pub state: &'static str,
|
||||
pub not_after: Option<i64>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
pub struct Paths {
|
||||
pub config: PathBuf,
|
||||
pub trial: PathBuf,
|
||||
pub revocations: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Why an admin request was refused.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AdminError {
|
||||
#[error("{0}")]
|
||||
Refused(#[from] EdgeError),
|
||||
#[error("{0}")]
|
||||
Conflict(String),
|
||||
}
|
||||
|
||||
pub struct Shared {
|
||||
current: ArcSwap<Runtime>,
|
||||
pub certs: Arc<CertStore>,
|
||||
generation: AtomicU64,
|
||||
changed: tokio::sync::watch::Sender<u64>,
|
||||
trial: Mutex<Option<Trial>>,
|
||||
trial_ids: AtomicU64,
|
||||
watch: Mutex<Option<WatchSpec>>,
|
||||
pub paths: Paths,
|
||||
credentials_dir: Option<PathBuf>,
|
||||
revocations: ArcSwap<RevocationState>,
|
||||
pub throttle: crate::share::Throttle,
|
||||
cert_states: Mutex<HashMap<String, CertState>>,
|
||||
pub acme_wake: tokio::sync::Notify,
|
||||
pub started_at: u64,
|
||||
}
|
||||
|
||||
fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> {
|
||||
if a.cfg.http_listen != b.cfg.http_listen || a.cfg.https_listen != b.cfg.https_listen {
|
||||
return Err(EdgeError::Config {
|
||||
path: PathBuf::from("<new config>"),
|
||||
message: "the listen addresses can only change with a restart".into(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
pub fn new(rt: Runtime, paths: Paths, credentials_dir: Option<PathBuf>) -> Arc<Shared> {
|
||||
let certs = Arc::new(CertStore::default());
|
||||
certs.replace_files(rt.file_certs.clone());
|
||||
let (changed, _) = tokio::sync::watch::channel(1);
|
||||
let s = Arc::new(Shared {
|
||||
current: ArcSwap::from_pointee(rt),
|
||||
certs,
|
||||
generation: AtomicU64::new(1),
|
||||
changed,
|
||||
trial: Mutex::new(None),
|
||||
trial_ids: AtomicU64::new(0),
|
||||
watch: Mutex::new(None),
|
||||
paths,
|
||||
credentials_dir,
|
||||
revocations: ArcSwap::from_pointee(RevocationState::default()),
|
||||
throttle: crate::share::Throttle::default(),
|
||||
cert_states: Mutex::new(HashMap::new()),
|
||||
acme_wake: tokio::sync::Notify::new(),
|
||||
started_at: now_secs() as u64,
|
||||
});
|
||||
if let Err(e) = s.reload_revocations() {
|
||||
log::error!(target: "ianitor::share", "{e}; share links are refused until it is fixed");
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// The runtime serving new requests now.
|
||||
pub fn current(&self) -> Arc<Runtime> {
|
||||
self.current.load_full()
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Changes whenever the runtime or the trial watch changes.
|
||||
pub fn subscribe(&self) -> tokio::sync::watch::Receiver<u64> {
|
||||
self.changed.subscribe()
|
||||
}
|
||||
|
||||
pub fn watch_spec(&self) -> Option<WatchSpec> {
|
||||
self.watch.lock().ok().and_then(|w| w.clone())
|
||||
}
|
||||
|
||||
fn notify(&self) {
|
||||
self.changed.send_replace(self.generation());
|
||||
}
|
||||
|
||||
fn install(&self, rt: Arc<Runtime>) {
|
||||
self.certs.replace_files(rt.file_certs.clone());
|
||||
self.current.store(rt);
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
self.notify();
|
||||
self.acme_wake.notify_one();
|
||||
}
|
||||
|
||||
fn build(&self, path: &Path) -> Result<Runtime, EdgeError> {
|
||||
let rt = runtime::build_file(path, self.credentials_dir.as_deref())?;
|
||||
same_listeners(&self.current(), &rt)?;
|
||||
Ok(rt)
|
||||
}
|
||||
|
||||
/// Reload from the config file. Refused while a trial runs.
|
||||
pub fn reload(&self) -> Result<Arc<Runtime>, AdminError> {
|
||||
let guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||
if guard.is_some() {
|
||||
return Err(AdminError::Conflict(
|
||||
"a trial config is running; confirm or abort it first".into(),
|
||||
));
|
||||
}
|
||||
let rt = Arc::new(self.build(&self.paths.config)?);
|
||||
self.install(rt.clone());
|
||||
drop(guard);
|
||||
log::info!(target: "ianitor::reload", "config reloaded ({} hosts, sha256 {})", rt.hosts.len(), short(&rt.sha256));
|
||||
Ok(rt)
|
||||
}
|
||||
|
||||
/// Serve the trial config until [`Shared::confirm`] or the deadline. Returns the trial id
|
||||
/// (for [`Shared::expire_trial`]) and the runtime.
|
||||
pub fn start_trial(
|
||||
&self,
|
||||
confirm_within: Duration,
|
||||
watch: Option<WatchSpec>,
|
||||
) -> Result<(u64, Arc<Runtime>), AdminError> {
|
||||
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||
if guard.is_some() {
|
||||
return Err(AdminError::Conflict(
|
||||
"a trial config is already running".into(),
|
||||
));
|
||||
}
|
||||
let rt = Arc::new(self.build(&self.paths.trial)?);
|
||||
let id = self.trial_ids.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
*guard = Some(Trial {
|
||||
id,
|
||||
sha256: rt.sha256.clone(),
|
||||
previous: self.current(),
|
||||
deadline: Instant::now() + confirm_within,
|
||||
});
|
||||
if let Ok(mut w) = self.watch.lock() {
|
||||
*w = watch;
|
||||
}
|
||||
self.install(rt.clone());
|
||||
log::info!(target: "ianitor::reload", "trial config {} running; reverts in {confirm_within:?} unless confirmed", short(&rt.sha256));
|
||||
Ok((id, rt))
|
||||
}
|
||||
|
||||
/// Keep the trial config. Fails unless a trial with this hash is running.
|
||||
pub fn confirm(&self, sha256: &str) -> Result<(), AdminError> {
|
||||
let mut guard = self.trial.lock().map_err(|_| poisoned())?;
|
||||
match guard.as_ref() {
|
||||
Some(t) if t.sha256 == sha256 => {}
|
||||
Some(_) => {
|
||||
return Err(AdminError::Conflict(
|
||||
"the running trial has another config".into(),
|
||||
));
|
||||
}
|
||||
None => return Err(AdminError::Conflict("no trial config is running".into())),
|
||||
}
|
||||
*guard = None;
|
||||
self.end_watch();
|
||||
log::info!(target: "ianitor::reload", "trial config {} confirmed", short(sha256));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end_watch(&self) {
|
||||
if let Ok(mut w) = self.watch.lock() {
|
||||
*w = None;
|
||||
}
|
||||
self.notify();
|
||||
}
|
||||
|
||||
/// Go back to the config before the trial. Returns whether there was a trial.
|
||||
pub fn abort(&self) -> bool {
|
||||
self.revert_trial(None, "aborted")
|
||||
}
|
||||
|
||||
/// Called when a trial's deadline passes.
|
||||
pub fn expire_trial(&self, id: u64) {
|
||||
self.revert_trial(Some(id), "not confirmed in time");
|
||||
}
|
||||
|
||||
fn revert_trial(&self, id: Option<u64>, why: &str) -> bool {
|
||||
let Ok(mut guard) = self.trial.lock() else {
|
||||
return false;
|
||||
};
|
||||
let matches = guard.as_ref().is_some_and(|t| id.is_none_or(|i| i == t.id));
|
||||
if !matches {
|
||||
return false;
|
||||
}
|
||||
let Some(t) = guard.take() else { return false };
|
||||
self.install(t.previous.clone());
|
||||
self.end_watch();
|
||||
log::warn!(target: "ianitor::reload", "trial config {} {why}; back to {}", short(&t.sha256), short(&t.previous.sha256));
|
||||
true
|
||||
}
|
||||
|
||||
/// (sha256, seconds left, previous sha256) of the running trial.
|
||||
pub fn trial_info(&self) -> Option<(String, u64, String)> {
|
||||
let g = self.trial.lock().ok()?;
|
||||
g.as_ref().map(|t| {
|
||||
(
|
||||
t.sha256.clone(),
|
||||
t.deadline
|
||||
.saturating_duration_since(Instant::now())
|
||||
.as_secs(),
|
||||
t.previous.sha256.clone(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn trial_deadline(&self, id: u64) -> Option<Instant> {
|
||||
let g = self.trial.lock().ok()?;
|
||||
g.as_ref().filter(|t| t.id == id).map(|t| t.deadline)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ share-link revocations
|
||||
|
||||
pub fn revocations(&self) -> Arc<RevocationState> {
|
||||
self.revocations.load_full()
|
||||
}
|
||||
|
||||
/// Re-read the revocation file. A missing file means "refuse every share link"; a broken
|
||||
/// one keeps the last good state.
|
||||
pub fn reload_revocations(&self) -> Result<(), EdgeError> {
|
||||
let Some(path) = &self.paths.revocations else {
|
||||
self.revocations.store(Arc::new(RevocationState {
|
||||
error: Some("no revocation file is configured".into()),
|
||||
..RevocationState::default()
|
||||
}));
|
||||
return Ok(());
|
||||
};
|
||||
let meta = match std::fs::metadata(path) {
|
||||
Ok(m) => m,
|
||||
Err(source) => {
|
||||
self.revocations.store(Arc::new(RevocationState {
|
||||
error: Some(format!("cannot read {}: {source}", path.display())),
|
||||
..RevocationState::default()
|
||||
}));
|
||||
return Err(EdgeError::Read {
|
||||
path: path.clone(),
|
||||
source,
|
||||
});
|
||||
}
|
||||
};
|
||||
let fail = |message: String| {
|
||||
let mut old = RevocationState::clone(&self.revocations());
|
||||
old.error = Some(message.clone());
|
||||
self.revocations.store(Arc::new(old));
|
||||
EdgeError::Config {
|
||||
path: path.clone(),
|
||||
message,
|
||||
}
|
||||
};
|
||||
if meta.len() > 1 << 20 {
|
||||
return Err(fail("the revocation file is larger than 1 MiB".into()));
|
||||
}
|
||||
let text = std::fs::read_to_string(path).map_err(|e| fail(e.to_string()))?;
|
||||
let file: RevocationFile =
|
||||
serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?;
|
||||
if file.deny.len() > MAX_DENY {
|
||||
return Err(fail(format!("more than {MAX_DENY} stopped links")));
|
||||
}
|
||||
let mut deny = std::collections::BTreeSet::new();
|
||||
for id in &file.deny {
|
||||
deny.insert(
|
||||
ShareId::from_hex(id)
|
||||
.ok_or_else(|| fail("a link id is not 32 hex digits".into()))?,
|
||||
);
|
||||
}
|
||||
let stamp = Some(runtime::sha256_hex(text.as_bytes()));
|
||||
self.revocations.store(Arc::new(RevocationState {
|
||||
revocations: Revocations {
|
||||
epoch: file.epoch,
|
||||
deny,
|
||||
},
|
||||
loaded: true,
|
||||
error: None,
|
||||
stamp,
|
||||
}));
|
||||
log::info!(target: "ianitor::share", "share-link revocations loaded: epoch {}, {} stopped", file.epoch, file.deny.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-read the revocation file if it changed (or vanished) since the last read.
|
||||
pub fn poll_revocations(&self) {
|
||||
let Some(path) = &self.paths.revocations else {
|
||||
return;
|
||||
};
|
||||
// Content, not mtime: two writes within one timer tick have the same mtime.
|
||||
let now = std::fs::metadata(path)
|
||||
.ok()
|
||||
.filter(|m| m.len() <= 1 << 20)
|
||||
.and_then(|_| std::fs::read(path).ok())
|
||||
.map(|b| runtime::sha256_hex(&b));
|
||||
let state = self.revocations();
|
||||
if (now != state.stamp || (now.is_none() && state.loaded))
|
||||
&& let Err(e) = self.reload_revocations()
|
||||
{
|
||||
log::error!(target: "ianitor::share", "{e}");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ certificates
|
||||
|
||||
pub fn set_cert_state(&self, host: &str, state: CertState) {
|
||||
if let Ok(mut m) = self.cert_states.lock() {
|
||||
m.insert(host.to_owned(), state);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cert_state(&self, host: &str) -> Option<CertState> {
|
||||
self.cert_states.lock().ok()?.get(host).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
fn poisoned() -> AdminError {
|
||||
AdminError::Conflict("internal state is unavailable".into())
|
||||
}
|
||||
|
||||
fn short(sha: &str) -> &str {
|
||||
sha.get(..12).unwrap_or(sha)
|
||||
}
|
||||
Reference in New Issue
Block a user