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

541 lines
17 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/.
//! 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, VecDeque};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
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::{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,
pub port: u16,
/// `host:port` as configured; the Host header of health checks.
pub authority: String,
pub tls: bool,
pub sni: String,
pub healthy: AtomicBool,
pub health: HealthRecord,
}
pub struct HostRt {
pub cfg: EdgeHost,
pub upstreams: Vec<UpstreamRt>,
pub next: AtomicUsize,
pub request_ops: Vec<Op>,
pub response_ops: Vec<Op>,
/// Values of the secrets this host injects; a response header containing one is dropped.
pub secret_values: Vec<Vec<u8>>,
}
pub struct ForwardAuthRt {
pub upstream: UpstreamRt,
pub path_and_query: String,
pub copy_headers: Vec<HeaderName>,
/// Removed from every client request on a forward-auth host before anything else.
pub strip_headers: Vec<HeaderName>,
}
pub struct Runtime {
pub cfg: EdgeConfig,
pub hosts: HashMap<String, Arc<HostRt>>,
pub forward_auth: Option<ForwardAuthRt>,
pub access_log: Option<AccessLog>,
/// 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>>,
/// Loaded when any host has `device_certs`.
pub device_trust: Option<Arc<crate::tls::DeviceTrust>>,
/// 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 {
pub fn host(&self, name: &str) -> Option<&Arc<HostRt>> {
self.hosts.get(name)
}
pub fn acme_hosts(&self) -> Vec<String> {
self.cfg
.hosts
.iter()
.filter(|h| h.tls == EdgeTls::Acme)
.map(|h| h.hostname.clone())
.collect()
}
pub fn acme_dir(&self) -> PathBuf {
Path::new(&self.cfg.state_dir).join("acme")
}
}
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 = 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(),
})?;
if cfg.version != EDGE_CONFIG_VERSION {
return Err(EdgeError::Version {
found: cfg.version,
expected: EDGE_CONFIG_VERSION,
});
}
Ok(cfg)
}
fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
let err = |reason: &str| EdgeError::Upstream {
address: u.address.clone(),
reason: reason.to_owned(),
};
let (host, port) = u
.address
.rsplit_once(':')
.ok_or_else(|| err("expected host:port"))?;
let port: u16 = port.parse().map_err(|_| err("bad port"))?;
let host = host
.strip_prefix('[')
.and_then(|h| h.strip_suffix(']'))
.unwrap_or(host);
if host.is_empty() {
return Err(err("empty host"));
}
Ok(UpstreamRt {
host: host.to_owned(),
port,
authority: u.address.clone(),
tls: u.tls,
sni: u.sni.clone(),
healthy: AtomicBool::new(true),
health: HealthRecord::default(),
})
}
/// How long a name lookup may take before the request fails with 502. Matches the 3 s dial
/// timeout (Caddy's default), which in Go also bounds the lookup.
pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(3);
impl UpstreamRt {
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's
/// dialer), so DNS changes and unresolvable names only affect requests, not startup.
/// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error.
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
resolve_with(
&self.host,
self.port,
RESOLVE_TIMEOUT,
|host, port| async move {
tokio::net::lookup_host((host.as_str(), port))
.await
.map(Iterator::collect)
},
)
.await
}
}
/// [`UpstreamRt::resolve`] with the lookup passed in, so the deadline can be tested.
pub async fn resolve_with<F, Fut>(
host: &str,
port: u16,
deadline: Duration,
lookup: F,
) -> std::io::Result<Vec<SocketAddr>>
where
F: FnOnce(String, u16) -> Fut,
Fut: Future<Output = std::io::Result<Vec<SocketAddr>>>,
{
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
return Ok(vec![SocketAddr::new(ip, port)]);
}
let addrs = match tokio::time::timeout(deadline, lookup(host.to_owned(), port)).await {
Ok(r) => r?,
Err(_) => {
return Err(std::io::Error::new(
std::io::ErrorKind::TimedOut,
format!("name lookup took longer than {deadline:?}"),
));
}
};
if addrs.is_empty() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"name resolves to no address",
));
}
Ok(addrs)
}
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
name: name.to_owned(),
reason: "not a valid header name",
})
}
fn ops(
list: &[EdgeHeaderOp],
secrets: &Secrets,
values: &mut Vec<Vec<u8>>,
) -> Result<Vec<Op>, EdgeError> {
list.iter()
.map(|op| match op {
EdgeHeaderOp::Remove { name } => Ok(Op::Remove(header_name(name)?)),
EdgeHeaderOp::Set { name, value } => {
let v = match value {
EdgeValue::Literal { value } => {
HeaderValue::from_str(value).map_err(|_| EdgeError::Header {
name: name.clone(),
reason: "value is not a valid header value",
})?
}
EdgeValue::Secret { name: secret } => {
let s = secrets.get(secret).ok_or(EdgeError::Secret {
name: secret.clone(),
reason: "not loaded",
})?;
values.push(s.as_bytes().to_vec());
s.header_value()
}
};
Ok(Op::Set(header_name(name)?, v))
}
})
.collect()
}
/// 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 mut names: BTreeSet<String> = cfg
.hosts
.iter()
.flat_map(|h| h.request_headers.iter().chain(&h.response_headers))
.filter_map(|op| match op {
EdgeHeaderOp::Set {
value: EdgeValue::Secret { name },
..
} => Some(name.clone()),
_ => 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 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 {
let read = |p: &str| {
std::fs::read(p).map_err(|source| EdgeError::Read {
path: PathBuf::from(p),
source,
})
};
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)?;
let response_ops = ops(&h.response_headers, &secrets, &mut secret_values)?;
let upstreams = h
.upstreams
.iter()
.map(upstream)
.collect::<Result<Vec<_>, _>>()?;
if upstreams.is_empty() {
return Err(EdgeError::Upstream {
address: h.hostname.clone(),
reason: "host has no upstream".into(),
});
}
hosts.insert(
h.hostname.clone(),
Arc::new(HostRt {
cfg: h.clone(),
upstreams,
next: AtomicUsize::new(0),
request_ops,
response_ops,
secret_values,
}),
);
}
let device_hosts: std::collections::HashSet<String> = cfg
.hosts
.iter()
.filter(|h| h.device_certs)
.map(|h| h.hostname.clone())
.collect();
let device_trust = match (&cfg.device_certs, device_hosts.is_empty()) {
(_, true) => None,
(None, false) => {
return Err(EdgeError::Config {
path: PathBuf::from("<config>"),
message: "a host needs device certificates but the config names no CA bundle"
.into(),
});
}
(Some(dc), false) => {
let read = |p: &str| {
std::fs::read(p).map_err(|source| EdgeError::Read {
path: PathBuf::from(p),
source,
})
};
let trust =
crate::tls::DeviceTrust::new(&read(&dc.ca)?, &read(&dc.allow)?, device_hosts)
.map_err(|message| EdgeError::Config {
path: PathBuf::from(&dc.ca),
message,
})?;
Some(Arc::new(trust))
}
};
let forward_auth = match &cfg.forward_auth {
Some(fa) => Some(ForwardAuthRt {
upstream: upstream(&fa.upstream)?,
path_and_query: fa.path_and_query.clone(),
copy_headers: fa
.copy_headers
.iter()
.map(|h| header_name(h))
.collect::<Result<_, _>>()?,
strip_headers: fa
.strip_headers
.iter()
.map(|h| header_name(h))
.collect::<Result<_, _>>()?,
}),
None => None,
};
if forward_auth.is_none() && cfg.hosts.iter().any(|h| h.forward_auth) {
return Err(EdgeError::Config {
path: PathBuf::from("<edge config>"),
message: "a host uses forward-auth but no forward_auth endpoint is configured".into(),
});
}
let access_log = if cfg.hosts.iter().any(|h| h.access_log) {
Some(AccessLog::open(Path::new(&cfg.access_log))?)
} else {
None
};
Ok(Runtime {
cfg,
hosts,
forward_auth,
access_log,
file_certs,
file_cert_expiry,
share_key,
device_trust,
sha256: String::new(),
})
}
#[cfg(test)]
mod resolve_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[tokio::test(start_paused = true)]
async fn a_slow_resolver_times_out() {
let t = tokio::time::Instant::now();
let err = resolve_with("slow.test", 80, RESOLVE_TIMEOUT, |_, _| async {
tokio::time::sleep(Duration::from_secs(10)).await;
Ok(vec!["127.0.0.1:80".parse().unwrap()])
})
.await
.unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::TimedOut);
assert_eq!(t.elapsed(), RESOLVE_TIMEOUT);
}
#[tokio::test(start_paused = true)]
async fn a_prompt_resolver_and_ip_literals_pass() {
let a: SocketAddr = "127.0.0.1:80".parse().unwrap();
let got = resolve_with(
"ok.test",
80,
RESOLVE_TIMEOUT,
|_, _| async move { Ok(vec![a]) },
)
.await;
assert_eq!(got.unwrap(), vec![a]);
let got = resolve_with("::1", 8080, RESOLVE_TIMEOUT, |_, _| async {
unreachable!("IP literals are not looked up")
})
.await;
assert_eq!(got.unwrap(), vec!["[::1]:8080".parse().unwrap()]);
let got = resolve_with("empty.test", 80, RESOLVE_TIMEOUT, |_, _| async {
Ok(vec![])
})
.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);
}
}