[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:
+161
-20
@@ -2,31 +2,81 @@
|
||||
// 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/.
|
||||
|
||||
//! The compiled edge config turned into ready-to-serve state: resolved upstream addresses,
|
||||
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
|
||||
//! The compiled edge config turned into ready-to-serve state: parsed upstreams and header
|
||||
//! names, secrets loaded, certificates loaded, the share-link key loaded. Built at startup
|
||||
//! and again on every reload; a reload swaps the whole [`Runtime`] at once (see `shared`).
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use http::{HeaderName, HeaderValue};
|
||||
use ianitor_core::edge_config::{
|
||||
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
|
||||
};
|
||||
use ianitor_core::share::{KEY_CREDENTIAL, ShareKey};
|
||||
use rustls::sign::CertifiedKey;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::error::EdgeError;
|
||||
use crate::logging::AccessLog;
|
||||
use crate::secrets::Secrets;
|
||||
use crate::tls::{CertStore, certified_key};
|
||||
use crate::tls::{certified_key, not_after};
|
||||
|
||||
pub enum Op {
|
||||
Set(HeaderName, HeaderValue),
|
||||
Remove(HeaderName),
|
||||
}
|
||||
|
||||
/// One health probe result, as reported on the admin socket.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Check {
|
||||
/// Increases by one per probe of this upstream.
|
||||
pub seq: u64,
|
||||
/// Unix seconds.
|
||||
pub at: u64,
|
||||
pub ok: bool,
|
||||
/// `health_check` (the host's own check) or `watch` (`GET /` during a trial).
|
||||
pub source: &'static str,
|
||||
/// `refused`, `timeout`, `name`, `tls`, `server_error`, `not_found`, `redirect`,
|
||||
/// `sign_in` or `bad_answer`; `None` when `ok`.
|
||||
pub kind: Option<&'static str>,
|
||||
pub status: Option<u16>,
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// The last few probe results of one upstream.
|
||||
#[derive(Default)]
|
||||
pub struct HealthRecord {
|
||||
inner: Mutex<(u64, VecDeque<Check>)>,
|
||||
}
|
||||
|
||||
/// How many results are kept per upstream.
|
||||
pub const KEPT_CHECKS: usize = 5;
|
||||
|
||||
impl HealthRecord {
|
||||
pub fn record(&self, mut c: Check) {
|
||||
if let Ok(mut g) = self.inner.lock() {
|
||||
g.0 += 1;
|
||||
c.seq = g.0;
|
||||
g.1.push_back(c);
|
||||
while g.1.len() > KEPT_CHECKS {
|
||||
g.1.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn checks(&self) -> Vec<Check> {
|
||||
self.inner
|
||||
.lock()
|
||||
.map(|g| g.1.iter().cloned().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UpstreamRt {
|
||||
/// Host name or IP literal (IPv6 without brackets).
|
||||
pub host: String,
|
||||
@@ -36,6 +86,7 @@ pub struct UpstreamRt {
|
||||
pub tls: bool,
|
||||
pub sni: String,
|
||||
pub healthy: AtomicBool,
|
||||
pub health: HealthRecord,
|
||||
}
|
||||
|
||||
pub struct HostRt {
|
||||
@@ -61,7 +112,15 @@ pub struct Runtime {
|
||||
pub hosts: HashMap<String, Arc<HostRt>>,
|
||||
pub forward_auth: Option<ForwardAuthRt>,
|
||||
pub access_log: Option<AccessLog>,
|
||||
pub certs: Arc<CertStore>,
|
||||
/// Domi certificates (`tls = "domi"`), by hostname.
|
||||
pub file_certs: HashMap<String, Arc<CertifiedKey>>,
|
||||
/// `notAfter` (Unix seconds) of each Domi certificate.
|
||||
pub file_cert_expiry: HashMap<String, i64>,
|
||||
/// Loaded when any host has share links.
|
||||
pub share_key: Option<Arc<ShareKey>>,
|
||||
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
|
||||
/// built from a parsed config.
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
@@ -83,12 +142,45 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
||||
let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read {
|
||||
pub fn sha256_hex(data: &[u8]) -> String {
|
||||
ring::digest::digest(&ring::digest::SHA256, data)
|
||||
.as_ref()
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Largest config file read.
|
||||
const MAX_CONFIG_BYTES: u64 = 16 << 20;
|
||||
|
||||
/// Read and parse a config file; returns the parsed config and the SHA-256 of its bytes.
|
||||
pub fn read_config_file(path: &Path) -> Result<(EdgeConfig, String), EdgeError> {
|
||||
let read_err = |source| EdgeError::Read {
|
||||
path: path.to_owned(),
|
||||
source,
|
||||
};
|
||||
let meta = std::fs::metadata(path).map_err(read_err)?;
|
||||
if meta.len() > MAX_CONFIG_BYTES {
|
||||
return Err(EdgeError::Config {
|
||||
path: path.to_owned(),
|
||||
message: "the file is larger than 16 MiB".into(),
|
||||
});
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(read_err)?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(|_| EdgeError::Config {
|
||||
path: path.to_owned(),
|
||||
message: "the file is not UTF-8".into(),
|
||||
})?;
|
||||
let cfg: EdgeConfig = serde_json::from_str(&text).map_err(|e| EdgeError::Config {
|
||||
let cfg = parse_config(path, text)?;
|
||||
Ok((cfg, sha256_hex(&bytes)))
|
||||
}
|
||||
|
||||
pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
||||
read_config_file(path).map(|(c, _)| c)
|
||||
}
|
||||
|
||||
fn parse_config(path: &Path, text: &str) -> Result<EdgeConfig, EdgeError> {
|
||||
let cfg: EdgeConfig = serde_json::from_str(text).map_err(|e| EdgeError::Config {
|
||||
path: path.to_owned(),
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
@@ -125,6 +217,7 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||
tls: u.tls,
|
||||
sni: u.sni.clone(),
|
||||
healthy: AtomicBool::new(true),
|
||||
health: HealthRecord::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -221,10 +314,18 @@ fn ops(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never
|
||||
/// starts half-configured.
|
||||
/// Read, parse and build a config file. Fails on the first problem; edge never serves a
|
||||
/// half-built config.
|
||||
pub fn build_file(path: &Path, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
|
||||
let (cfg, sha) = read_config_file(path)?;
|
||||
let mut rt = build(cfg, credentials_dir)?;
|
||||
rt.sha256 = sha;
|
||||
Ok(rt)
|
||||
}
|
||||
|
||||
/// Load secrets, certificates and the share-link key. Fails on the first problem.
|
||||
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
|
||||
let names: BTreeSet<String> = cfg
|
||||
let mut names: BTreeSet<String> = cfg
|
||||
.hosts
|
||||
.iter()
|
||||
.flat_map(|h| h.request_headers.iter().chain(&h.response_headers))
|
||||
@@ -236,9 +337,23 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let wants_share = cfg.hosts.iter().any(|h| h.share_links);
|
||||
if wants_share {
|
||||
names.insert(KEY_CREDENTIAL.to_owned());
|
||||
}
|
||||
let secrets = Secrets::load(&names, credentials_dir)?;
|
||||
let share_key = match secrets.get(KEY_CREDENTIAL) {
|
||||
Some(s) if wants_share => Some(Arc::new(ShareKey::new(s.as_bytes()).map_err(|_| {
|
||||
EdgeError::Secret {
|
||||
name: KEY_CREDENTIAL.into(),
|
||||
reason: "the share-link key must be at least 32 characters",
|
||||
}
|
||||
})?)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let certs = Arc::new(CertStore::default());
|
||||
let mut file_certs = HashMap::new();
|
||||
let mut file_cert_expiry = HashMap::new();
|
||||
let mut hosts = HashMap::new();
|
||||
for h in &cfg.hosts {
|
||||
if let EdgeTls::Files { cert, key } = &h.tls {
|
||||
@@ -248,12 +363,15 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
source,
|
||||
})
|
||||
};
|
||||
let pair =
|
||||
certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert {
|
||||
host: h.hostname.clone(),
|
||||
reason,
|
||||
})?;
|
||||
certs.insert(&h.hostname, pair);
|
||||
let cert_pem = read(cert)?;
|
||||
let pair = certified_key(&cert_pem, &read(key)?).map_err(|reason| EdgeError::Cert {
|
||||
host: h.hostname.clone(),
|
||||
reason,
|
||||
})?;
|
||||
if let Some(exp) = not_after(&cert_pem) {
|
||||
file_cert_expiry.insert(h.hostname.clone(), exp);
|
||||
}
|
||||
file_certs.insert(h.hostname.clone(), Arc::new(pair));
|
||||
}
|
||||
let mut secret_values = Vec::new();
|
||||
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
|
||||
@@ -317,7 +435,10 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
hosts,
|
||||
forward_auth,
|
||||
access_log,
|
||||
certs,
|
||||
file_certs,
|
||||
file_cert_expiry,
|
||||
share_key,
|
||||
sha256: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -361,4 +482,24 @@ mod resolve_tests {
|
||||
.await;
|
||||
assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn health_records_keep_the_last_five() {
|
||||
let r = HealthRecord::default();
|
||||
for i in 0..8 {
|
||||
r.record(Check {
|
||||
seq: 0,
|
||||
at: i,
|
||||
ok: i % 2 == 0,
|
||||
source: "health_check",
|
||||
kind: None,
|
||||
status: None,
|
||||
latency_ms: None,
|
||||
});
|
||||
}
|
||||
let c = r.checks();
|
||||
assert_eq!(c.len(), KEPT_CHECKS);
|
||||
assert_eq!(c.first().unwrap().seq, 4);
|
||||
assert_eq!(c.last().unwrap().seq, 8);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user