[edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME
This commit is contained in:
@@ -0,0 +1,251 @@
|
||||
// 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, ToSocketAddrs};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
|
||||
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 {
|
||||
pub addr: SocketAddr,
|
||||
/// `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>,
|
||||
}
|
||||
|
||||
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: String| EdgeError::Upstream {
|
||||
address: u.address.clone(),
|
||||
reason,
|
||||
};
|
||||
// Resolved once at startup; Pingora peers need a socket address.
|
||||
let addr = u
|
||||
.address
|
||||
.to_socket_addrs()
|
||||
.map_err(|e| err(format!("cannot resolve: {e}")))?
|
||||
.next()
|
||||
.ok_or_else(|| err("resolves to no address".into()))?;
|
||||
Ok(UpstreamRt {
|
||||
addr,
|
||||
authority: u.address.clone(),
|
||||
tls: u.tls,
|
||||
sni: u.sni.clone(),
|
||||
healthy: AtomicBool::new(true),
|
||||
})
|
||||
}
|
||||
|
||||
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<_, _>>()?,
|
||||
}),
|
||||
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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user