Files
ianitor/crates/edge/src/shared.rs
T

596 lines
22 KiB
Rust

// 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>,
/// The listener's device-certificate check; its trust follows the runtime.
pub devices: Arc<crate::tls::DeviceVerifier>,
/// Serialises building the device trust with installing a runtime.
trust_lock: Mutex<()>,
/// Size and mtime of the device files when they were last read.
device_stamp: Mutex<Option<DeviceStamp>>,
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>,
/// The highest revocation epoch seen since start; a file with a lower one is refused.
epoch_seen: std::sync::atomic::AtomicU32,
/// Set when the saved epoch floor could not be read: share links stay refused.
floor_error: Option<String>,
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
|| a.cfg.proxy_socket != b.cfg.proxy_socket
{
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 (floor, floor_error) = match read_epoch_floor(&rt) {
Ok(f) => (f, None),
Err(e) => {
log::error!(target: "ianitor::share", "{e}");
(u32::MAX, Some(e))
}
};
let certs = Arc::new(CertStore::default());
certs.replace_files(rt.file_certs.clone());
let devices = Arc::new(crate::tls::DeviceVerifier::default());
devices.replace(rt.device_trust.clone());
let (changed, _) = tokio::sync::watch::channel(1);
let s = Arc::new(Shared {
current: ArcSwap::from_pointee(rt),
certs,
devices,
trust_lock: Mutex::new(()),
device_stamp: Mutex::new(None),
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()),
epoch_seen: std::sync::atomic::AtomicU32::new(floor),
floor_error,
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());
// Read the device files again: the runtime may be older than the latest allow list
// (a revert after a revocation must not let a revoked device back in).
let trust = match fresh_trust(&rt) {
Ok(t) => t,
Err(e) => {
log::error!(target: "ianitor::tls", "{e}; keeping the device check this config was built with");
rt.device_trust.clone()
}
};
// Trust and runtime change together (reload_device_trust checks the runtime under the
// same lock).
let guard = self.trust_lock.lock();
self.devices.replace(trust);
self.current.store(rt);
drop(guard);
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 text = std::fs::read(path).ok();
let sha = text.as_deref().map(runtime::sha256_hex);
let fail = |message: String| {
let mut old = RevocationState::clone(&self.revocations());
old.error = Some(message.clone());
// Remember this content, so the poller reports it once, not every 5 s.
if old.loaded {
old.stamp = sha.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 = text
.and_then(|b| String::from_utf8(b).ok())
.ok_or_else(|| fail("cannot read the revocation file as text".into()))?;
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()))?,
);
}
if let Some(e) = &self.floor_error {
return Err(fail(e.clone()));
}
// The epoch only goes up: a lower one would bring stopped links back.
let seen = self.epoch_seen.load(Ordering::SeqCst);
if file.epoch < seen {
return Err(fail(format!(
"the revocation epoch went down from {seen} to {}; keeping the old state",
file.epoch
)));
}
if file.epoch > seen {
self.epoch_seen.store(file.epoch, Ordering::SeqCst);
if let Err(e) = write_epoch_floor(&self.current(), file.epoch) {
// Still refused within this process; only a restart could forget it.
log::error!(target: "ianitor::share", "cannot save the revocation epoch floor: {e}");
}
}
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()
}
}
/// Edge's own record of the highest revocation epoch it has accepted, in its state
/// directory: a restart (even after control's files were rolled back) still refuses lower.
fn epoch_floor_path(rt: &Runtime) -> PathBuf {
Path::new(&rt.cfg.state_dir).join("share-epoch-floor")
}
/// Missing: 0. Unreadable or not a number: an error, and share links stay refused (failing
/// open would forget which links were stopped).
fn read_epoch_floor(rt: &Runtime) -> Result<u32, String> {
let path = epoch_floor_path(rt);
match std::fs::read_to_string(&path) {
Ok(s) => s.trim().parse().map_err(|_| {
format!(
"{} is not a number; share links are refused until it is fixed",
path.display()
)
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
Err(e) => Err(format!(
"cannot read {} ({e}); share links are refused until it is fixed",
path.display()
)),
}
}
fn write_epoch_floor(rt: &Runtime, epoch: u32) -> std::io::Result<()> {
let path = epoch_floor_path(rt);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
// Unique per write: the admin socket and the poller can both reload the revocations.
static WRITES: AtomicU64 = AtomicU64::new(0);
let tmp = path.with_extension(format!(
"tmp-{}-{}",
std::process::id(),
WRITES.fetch_add(1, Ordering::Relaxed)
));
{
use std::io::Write;
let mut f = std::fs::File::create(&tmp)?;
f.write_all(format!("{epoch}\n").as_bytes())?;
f.sync_all()?;
}
std::fs::rename(&tmp, &path)?;
match path.parent() {
Some(dir) => std::fs::File::open(dir)?.sync_all(),
None => Ok(()),
}
}
fn poisoned() -> AdminError {
AdminError::Conflict("internal state is unavailable".into())
}
fn short(sha: &str) -> &str {
sha.get(..12).unwrap_or(sha)
}
/// The device check for a runtime, built from the files as they are now.
fn fresh_trust(rt: &Runtime) -> Result<Option<Arc<crate::tls::DeviceTrust>>, String> {
let Some(dc) = &rt.cfg.device_certs else {
return Ok(None);
};
let hosts: std::collections::HashSet<String> = rt
.cfg
.hosts
.iter()
.filter(|h| h.device_certs)
.map(|h| h.hostname.clone())
.collect();
if hosts.is_empty() {
return Ok(None);
}
let ca = std::fs::read(&dc.ca).map_err(|e| format!("cannot read {}: {e}", dc.ca))?;
let allow = std::fs::read(&dc.allow).map_err(|e| format!("cannot read {}: {e}", dc.allow))?;
crate::tls::DeviceTrust::new(&ca, &allow, hosts).map(|t| Some(Arc::new(t)))
}
impl Shared {
/// Re-read the device CA bundle and allow list now (control calls this after an issue
/// or a revocation; allowed during a trial). Returns how many devices are allowed.
pub fn reload_device_trust(&self) -> Result<usize, String> {
// Built from the runtime that serves when it is installed: if a reload swapped the
// runtime meanwhile, build again from the new one (its host set may differ).
for _ in 0..5 {
let rt = self.current();
let t = fresh_trust(&rt)?;
let n = t.as_ref().map_or(0, |t| t.allowed());
let _g = self
.trust_lock
.lock()
.map_err(|_| "device lock".to_owned())?;
if Arc::ptr_eq(&rt, &self.current()) {
self.devices.replace(t);
log::info!(target: "ianitor::tls", "device certificates re-read: {n} allowed");
return Ok(n);
}
}
Err("the config changed while the device certificates were read; try again".into())
}
/// The backstop for revocations (every 5 s, like the share deny list): re-read the device
/// files when they changed on disk, so a revocation counts even if control's nudge is lost.
pub fn poll_device_trust(&self) {
let rt = self.current();
let Some(dc) = &rt.cfg.device_certs else {
return;
};
let stamp = |p: &str| {
std::fs::metadata(p)
.ok()
.map(|m| (m.len(), m.modified().ok()))
};
let now = (stamp(&dc.ca), stamp(&dc.allow));
let changed = match self.device_stamp.lock() {
Ok(mut s) => {
let c = s.as_ref() != Some(&now);
*s = Some(now);
c
}
Err(_) => true,
};
if changed && let Err(e) = self.reload_device_trust() {
// Fail closed: an unreadable list lets no device in until it is fixed.
log::error!(target: "ianitor::tls", "{e}; no device certificate is accepted until it is fixed");
self.devices.replace(None);
}
}
}
type FileStamp = Option<(u64, Option<std::time::SystemTime>)>;
type DeviceStamp = (FileStamp, FileStamp);