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

365 lines
11 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: resolved upstream addresses,
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
use std::collections::{BTreeSet, HashMap};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::time::Duration;
use http::{HeaderName, HeaderValue};
use ianitor_core::edge_config::{
EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
};
use crate::error::EdgeError;
use crate::logging::AccessLog;
use crate::secrets::Secrets;
use crate::tls::{CertStore, certified_key};
pub enum Op {
Set(HeaderName, HeaderValue),
Remove(HeaderName),
}
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 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>,
pub certs: Arc<CertStore>,
}
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 read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read {
path: path.to_owned(),
source,
})?;
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),
})
}
/// 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()
}
/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never
/// starts half-configured.
pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime, EdgeError> {
let 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 secrets = Secrets::load(&names, credentials_dir)?;
let certs = Arc::new(CertStore::default());
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 pair =
certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert {
host: h.hostname.clone(),
reason,
})?;
certs.insert(&h.hostname, 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 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,
certs,
})
}
#[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);
}
}