[edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME

This commit is contained in:
2026-11-07 14:57:36 +01:00
parent 4fe041082d
commit 17e1df8320
24 changed files with 2316 additions and 123 deletions
+1
View File
@@ -26,6 +26,7 @@ serde_json.workspace = true
arc-swap = "1.7"
instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] }
x509-parser = "0.18"
thiserror.workspace = true
[dev-dependencies]
ianitor-testkit.workspace = true
+289
View File
@@ -0,0 +1,289 @@
// 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/.
//! Let's Encrypt (any RFC 8555 directory) through `instant-acme`, HTTP-01 challenges answered
//! on the plain-HTTP listener. Certificates and the account live in `<state_dir>/acme`
//! (key files mode 0600) and are swapped into the SNI store without a restart. A certificate
//! is renewed when it has less than 30 days left; failures are retried with backoff.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use async_trait::async_trait;
use instant_acme::{
Account, AccountCredentials, AuthorizationStatus, ChallengeType, Identifier, NewAccount,
NewOrder, OrderStatus, RetryPolicy,
};
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use crate::logging::now_secs;
use crate::runtime::Runtime;
use crate::tls::{CertStore, certified_key, not_after};
const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0;
const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600);
const FIRST_RETRY: Duration = Duration::from_secs(30);
const MAX_RETRY: Duration = Duration::from_secs(3600);
/// HTTP-01 tokens → key authorizations, shared with the HTTP listener.
#[derive(Default)]
pub struct Challenges(RwLock<HashMap<String, String>>);
impl Challenges {
pub fn get(&self, token: &str) -> Option<String> {
self.0.read().ok()?.get(token).cloned()
}
fn insert(&self, token: String, key_auth: String) {
if let Ok(mut m) = self.0.write() {
m.insert(token, key_auth);
}
}
fn remove(&self, token: &str) {
if let Ok(mut m) = self.0.write() {
m.remove(token);
}
}
}
pub struct AcmeService {
pub rt: Arc<Runtime>,
pub certs: Arc<CertStore>,
pub challenges: Arc<Challenges>,
/// Extra trust root for the ACME directory (tests against Pebble only).
pub ca_root: Option<PathBuf>,
}
fn write_private(path: &Path, data: &[u8]) -> Result<(), String> {
let tmp = path.with_extension("tmp");
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600);
let mut f = opts
.open(&tmp)
.map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
std::io::Write::write_all(&mut f, data)
.map_err(|e| format!("cannot write {}: {e}", tmp.display()))?;
std::fs::rename(&tmp, path).map_err(|e| format!("cannot replace {}: {e}", path.display()))
}
fn fnv(data: &[u8]) -> String {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in data {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
format!("{h:016x}")
}
impl AcmeService {
fn dir(&self) -> PathBuf {
self.rt.acme_dir()
}
fn paths(&self, host: &str) -> (PathBuf, PathBuf) {
(
self.dir().join(format!("{host}.crt")),
self.dir().join(format!("{host}.key")),
)
}
/// Load a stored certificate into the SNI store; returns its expiry.
fn load_stored(&self, host: &str) -> Option<i64> {
let (crt, key) = self.paths(host);
let cert_pem = std::fs::read(&crt).ok()?;
let key_pem = std::fs::read(&key).ok()?;
let expiry = not_after(&cert_pem)?;
match certified_key(&cert_pem, &key_pem) {
Ok(ck) => {
self.certs.insert(host, ck);
Some(expiry)
}
Err(e) => {
log::warn!(target: "ianitor::acme", "{host}: stored certificate is not usable ({e}); ordering a new one");
None
}
}
}
fn builder(&self) -> Result<instant_acme::AccountBuilder, String> {
match &self.ca_root {
Some(p) => Account::builder_with_root(p),
None => Account::builder(),
}
.map_err(|e| format!("cannot set up the ACME client: {e}"))
}
async fn account(&self, directory: &str, email: Option<&str>) -> Result<Account, String> {
let file = self
.dir()
.join(format!("account-{}.json", fnv(directory.as_bytes())));
if let Ok(text) = std::fs::read_to_string(&file) {
let creds: AccountCredentials = serde_json::from_str(&text)
.map_err(|e| format!("{} is damaged: {e}", file.display()))?;
return self
.builder()?
.from_credentials(creds)
.await
.map_err(|e| format!("cannot restore the ACME account: {e}"));
}
let contact = email.map(|e| format!("mailto:{e}"));
let contacts: Vec<&str> = contact.iter().map(String::as_str).collect();
let (account, creds) = self
.builder()?
.create(
&NewAccount {
contact: &contacts,
terms_of_service_agreed: true,
only_return_existing: false,
},
directory.to_owned(),
None,
)
.await
.map_err(|e| format!("cannot create the ACME account: {e}"))?;
let text = serde_json::to_vec(&creds)
.map_err(|e| format!("cannot store the ACME account: {e}"))?;
write_private(&file, &text)?;
log::info!(target: "ianitor::acme", "created ACME account at {directory}");
Ok(account)
}
async fn issue(&self, account: &Account, host: &str) -> Result<i64, String> {
let ids = [Identifier::Dns(host.to_owned())];
let mut order = account
.new_order(&NewOrder::new(&ids))
.await
.map_err(|e| format!("new order: {e}"))?;
let mut tokens = Vec::new();
let mut auths = order.authorizations();
while let Some(result) = auths.next().await {
let mut authz = result.map_err(|e| format!("authorization: {e}"))?;
if authz.status == AuthorizationStatus::Valid {
continue;
}
if authz.status != AuthorizationStatus::Pending {
return Err(format!("authorization is {:?}", authz.status));
}
let mut ch = authz
.challenge(ChallengeType::Http01)
.ok_or("the server offers no HTTP-01 challenge")?;
self.challenges
.insert(ch.token.clone(), ch.key_authorization().as_str().to_owned());
tokens.push(ch.token.clone());
ch.set_ready()
.await
.map_err(|e| format!("challenge ready: {e}"))?;
}
let policy = RetryPolicy::new().timeout(Duration::from_secs(90));
let status = order
.poll_ready(&policy)
.await
.map_err(|e| format!("order: {e}"));
for t in &tokens {
self.challenges.remove(t);
}
match status? {
OrderStatus::Ready => {}
other => return Err(format!("order ended as {other:?}")),
}
let key_pem = order
.finalize()
.await
.map_err(|e| format!("finalize: {e}"))?;
let chain_pem = order
.poll_certificate(&policy)
.await
.map_err(|e| format!("certificate: {e}"))?;
let ck = certified_key(chain_pem.as_bytes(), key_pem.as_bytes())?;
let expiry =
not_after(chain_pem.as_bytes()).ok_or("cannot read the new certificate's expiry")?;
let (crt, key) = self.paths(host);
write_private(&key, key_pem.as_bytes())?;
write_private(&crt, chain_pem.as_bytes())?;
self.certs.insert(host, ck);
log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}");
Ok(expiry)
}
/// One pass over every ACME host. Returns false if any host failed.
async fn round(&self, expiries: &mut HashMap<String, i64>) -> bool {
let Some(acme) = &self.rt.cfg.acme else {
return true;
};
let due: Vec<String> = self
.rt
.acme_hosts()
.into_iter()
.filter(|h| {
expiries
.get(h)
.is_none_or(|e| (*e as f64) - now_secs() < RENEW_BEFORE_SECS)
})
.collect();
if due.is_empty() {
return true;
}
let account = match self.account(&acme.directory, acme.email.as_deref()).await {
Ok(a) => a,
Err(e) => {
log::error!(target: "ianitor::acme", "{e}");
return false;
}
};
let mut ok = true;
for host in due {
match self.issue(&account, &host).await {
Ok(exp) => {
expiries.insert(host, exp);
}
Err(e) => {
log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}");
ok = false;
}
}
}
ok
}
}
#[async_trait]
impl BackgroundService for AcmeService {
async fn start(&self, mut shutdown: ShutdownWatch) {
if self.rt.acme_hosts().is_empty() {
return;
}
let dir = self.dir();
if let Err(e) = std::fs::create_dir_all(&dir) {
log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display());
return;
}
let mut expiries = HashMap::new();
for h in self.rt.acme_hosts() {
if let Some(e) = self.load_stored(&h) {
expiries.insert(h, e);
}
}
let mut retry = FIRST_RETRY;
loop {
let wait = if self.round(&mut expiries).await {
retry = FIRST_RETRY;
CHECK_EVERY
} else {
let w = retry;
retry = (retry * 2).min(MAX_RETRY);
w
};
tokio::select! {
_ = tokio::time::sleep(wait) => {}
_ = shutdown.changed() => return,
}
}
}
}
+37
View File
@@ -0,0 +1,37 @@
// 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/.
//! Startup errors. None of them ever carries a secret value.
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum EdgeError {
#[error("cannot read {path}: {source}")]
Read {
path: PathBuf,
source: std::io::Error,
},
#[error("cannot write {path}: {source}")]
Write {
path: PathBuf,
source: std::io::Error,
},
#[error("{path} is not a valid edge config: {message}")]
Config { path: PathBuf, message: String },
#[error("edge config version {found} is not supported (this build reads version {expected})")]
Version { found: u32, expected: u32 },
#[error("secret `{name}`: {reason}")]
Secret { name: String, reason: &'static str },
#[error("certificate for {host}: {reason}")]
Cert { host: String, reason: String },
#[error("upstream {address}: {reason}")]
Upstream { address: String, reason: String },
#[error("header `{name}`: {reason}")]
Header { name: String, reason: &'static str },
#[error("listener {address}: {reason}")]
Listen { address: String, reason: String },
#[error("command line: {0}")]
Usage(String),
}
+63
View File
@@ -0,0 +1,63 @@
// 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/.
//! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks.
use std::time::Duration;
use bytes::{Bytes, BytesMut};
use pingora::connectors::http::Connector;
use pingora::http::{RequestHeader, ResponseHeader};
use pingora::upstreams::peer::HttpPeer;
use pingora::{Error, ErrorType, Result};
use crate::runtime::UpstreamRt;
pub struct Fetched {
pub header: ResponseHeader,
pub body: Bytes,
}
/// Dial timeout, matching Caddy's reverse_proxy default.
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
pub fn peer(u: &UpstreamRt) -> HttpPeer {
let mut p = HttpPeer::new(u.addr, u.tls, u.sni.clone());
p.options.connection_timeout = Some(DIAL_TIMEOUT);
p
}
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body.
pub async fn fetch(
connector: &Connector,
u: &UpstreamRt,
req: RequestHeader,
max_body: usize,
timeout: Duration,
) -> Result<Fetched> {
let mut p = peer(u);
p.options.read_timeout = Some(timeout);
p.options.write_timeout = Some(timeout);
p.options.total_connection_timeout = Some(timeout);
let (mut http, _reused) = connector.get_http_session(&p).await?;
http.write_request_header(Box::new(req)).await?;
http.finish_request_body().await?;
http.read_response_header().await?;
let header = http
.response_header()
.cloned()
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
let mut body = BytesMut::new();
while let Some(chunk) = http.read_response_body().await? {
if body.len() + chunk.len() > max_body {
return Error::e_explain(ErrorType::InvalidHTTPHeader, "response body too large");
}
body.extend_from_slice(&chunk);
}
// Not returned to the pool: these calls are rare and a fresh connection is simplest.
Ok(Fetched {
header,
body: body.freeze(),
})
}
+105
View File
@@ -0,0 +1,105 @@
// 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/.
//! Forward-auth compatible with Authelia's ForwardAuth implementation
//! (`GET /api/authz/forward-auth`) and with Caddy's `forward_auth` directive:
//!
//! - The subrequest is a `GET` to the configured path, carrying the client's request headers
//! (minus hop-by-hop and framing headers, never a body) plus `X-Forwarded-Method`,
//! `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Uri` and `X-Forwarded-For`, which
//! edge always sets itself (client-supplied values are replaced).
//! - A 2xx answer allows the request: each configured identity header is removed from the
//! client request and, when the auth answer has a non-empty value, set from it.
//! - Any other answer is returned to the client as it is (status, headers, body), and the
//! request never reaches the upstream.
//! - If the auth server cannot be reached, the request fails closed with 502.
use std::time::Duration;
use bytes::Bytes;
use http::header::{self, HeaderName, HeaderValue};
use pingora::Result;
use pingora::connectors::http::Connector;
use pingora::http::{RequestHeader, ResponseHeader};
use pingora::proxy::Session;
use crate::fetch::fetch;
use crate::runtime::ForwardAuthRt;
const MAX_AUTH_BODY: usize = 1 << 20;
const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
pub enum Outcome {
Allow(Vec<(HeaderName, Option<HeaderValue>)>),
Deny(Box<ResponseHeader>, Bytes),
}
/// Request headers never copied to a subrequest or a passed-through response.
pub fn hop_by_hop(name: &HeaderName) -> bool {
matches!(
name.as_str(),
"connection"
| "keep-alive"
| "proxy-connection"
| "te"
| "trailer"
| "transfer-encoding"
| "upgrade"
| "content-length"
| "proxy-authenticate"
| "proxy-authorization"
)
}
fn forwarded(name: &HeaderName) -> bool {
name.as_str().starts_with("x-forwarded-")
}
pub async fn check(
connector: &Connector,
fa: &ForwardAuthRt,
session: &Session,
host_header: &str,
client_ip: Option<String>,
) -> Result<Outcome> {
let req = session.req_header();
let mut sub = RequestHeader::build("GET", fa.path_and_query.as_bytes(), None)?;
for (name, value) in req.headers.iter() {
if !hop_by_hop(name) && !forwarded(name) && name != header::HOST {
sub.append_header(name.clone(), value.clone())?;
}
}
let uri = req.uri.path_and_query().map(|p| p.as_str()).unwrap_or("/");
sub.insert_header(header::HOST, host_header)?;
sub.insert_header("X-Forwarded-Method", req.method.as_str())?;
sub.insert_header("X-Forwarded-Proto", "https")?;
sub.insert_header("X-Forwarded-Host", host_header)?;
sub.insert_header("X-Forwarded-Uri", uri)?;
if let Some(ip) = client_ip {
sub.insert_header("X-Forwarded-For", ip)?;
}
let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?;
let status = got.header.status.as_u16();
if (200..300).contains(&status) {
let copy = fa
.copy_headers
.iter()
.map(|n| {
let v = got.header.headers.get(n).filter(|v| !v.is_empty()).cloned();
(n.clone(), v)
})
.collect();
return Ok(Outcome::Allow(copy));
}
let mut resp = ResponseHeader::build(got.header.status, None)?;
for (name, value) in got.header.headers.iter() {
if !hop_by_hop(name) {
resp.append_header(name.clone(), value.clone())?;
}
}
resp.insert_header(header::CONTENT_LENGTH, got.body.len().to_string())?;
Ok(Outcome::Deny(Box::new(resp), got.body))
}
+76
View File
@@ -0,0 +1,76 @@
// 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/.
//! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream
//! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round
//! runs at startup; upstreams start healthy.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use async_trait::async_trait;
use pingora::connectors::http::Connector;
use pingora::http::RequestHeader;
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use crate::fetch::fetch;
use crate::runtime::{HostRt, Runtime, UpstreamRt};
const TIMEOUT: Duration = Duration::from_secs(5);
pub struct HealthChecks {
pub rt: Arc<Runtime>,
}
async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
return false;
};
if req
.insert_header(http::header::HOST, u.authority.as_str())
.is_err()
{
return false;
}
match tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await {
Ok(Ok(f)) => f.header.status.is_success(),
_ => false,
}
}
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
let connector = Connector::new(None);
loop {
for u in &host.upstreams {
let ok = probe(&connector, u, &path).await;
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
if ok {
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
} else {
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
}
}
}
tokio::time::sleep(every).await;
}
}
#[async_trait]
impl BackgroundService for HealthChecks {
async fn start(&self, mut shutdown: ShutdownWatch) {
let mut tasks = Vec::new();
for host in self.rt.hosts.values() {
if let Some(hc) = &host.cfg.health_check {
let every = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every)));
}
}
let _ = shutdown.changed().await;
for t in tasks {
t.abort();
}
}
}
+90
View File
@@ -0,0 +1,90 @@
// 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 plain-HTTP listener: answers ACME HTTP-01 challenges, redirects known hosts to HTTPS
//! with 308 (like Caddy), and answers 404 for anything else.
use std::sync::Arc;
use std::time::Instant;
use async_trait::async_trait;
use http::{Response, StatusCode, header};
use pingora::apps::http_app::ServeHttp;
use pingora::protocols::http::ServerSession;
use crate::acme::Challenges;
use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::proxy::{host_header, hostname};
use crate::runtime::Runtime;
pub struct HttpApp {
pub rt: Arc<Runtime>,
pub challenges: Arc<Challenges>,
}
fn empty(status: StatusCode) -> Response<Vec<u8>> {
let mut r = Response::new(Vec::new());
*r.status_mut() = status;
r.headers_mut()
.insert(header::CONTENT_LENGTH, http::HeaderValue::from_static("0"));
r
}
#[async_trait]
impl ServeHttp for HttpApp {
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
let start = Instant::now();
let req = session.req_header();
let hh = host_header(req);
let name = hostname(&hh);
let path = req.uri.path().to_owned();
if let Some(token) = path.strip_prefix("/.well-known/acme-challenge/")
&& let Some(key_auth) = self.challenges.get(token)
{
log::info!(target: "ianitor::acme", "answered HTTP-01 challenge for {name}");
let mut r = Response::new(key_auth.into_bytes());
r.headers_mut().insert(
header::CONTENT_TYPE,
http::HeaderValue::from_static("text/plain"),
);
return r;
}
let Some(host) = self.rt.host(&name) else {
return empty(StatusCode::NOT_FOUND);
};
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
let port = self.rt.cfg.https_port;
let location = if port == 443 {
format!("https://{name}{uri}")
} else {
format!("https://{name}:{port}{uri}")
};
let mut r = empty(StatusCode::PERMANENT_REDIRECT);
match http::HeaderValue::from_str(&location) {
Ok(v) => {
r.headers_mut().insert(header::LOCATION, v);
}
Err(_) => return empty(StatusCode::BAD_REQUEST),
}
if host.cfg.access_log
&& let Some(log) = &self.rt.access_log
{
log.write(&AccessRecord {
ts: now_secs(),
host: &host.cfg.hostname,
method: req.method.as_str(),
path: &path,
status: 308,
remote_ip: session
.client_addr()
.and_then(|a| a.as_inet())
.map(|a| truncate_ip(a.ip()).to_string()),
duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
});
}
r
}
}
+125 -1
View File
@@ -2,4 +2,128 @@
// 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/.
//! Ianitor edge: the Pingora data plane.
//! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core`
//! and serves it; it never decides policy.
//!
//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules,
//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects),
//! health checks, ACME issuance and renewal.
pub mod acme;
pub mod error;
pub mod fetch;
pub mod forward_auth;
pub mod health;
pub mod http_app;
pub mod logging;
pub mod proxy;
pub mod runtime;
pub mod secrets;
pub mod tls;
use std::path::PathBuf;
use std::sync::Arc;
use pingora::connectors::http::Connector;
use pingora::listeners::tls::TlsSettings;
use pingora::proxy::http_proxy_service;
use pingora::server::Server;
use pingora::server::configuration::ServerConf;
use pingora::services::background::background_service;
use pingora::services::listening::Service;
pub use error::EdgeError;
pub use runtime::Runtime;
#[derive(Debug, Clone, Default)]
pub struct Options {
/// The compiled edge config (`ianitor-core` edge compiler output).
pub config: PathBuf,
/// Extra trust root for the ACME directory's TLS (Pebble in tests).
pub acme_root: Option<PathBuf>,
}
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
pub fn prepare(opts: &Options) -> Result<Arc<Runtime>, EdgeError> {
let cfg = runtime::read_config(&opts.config)?;
let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from);
runtime::build(cfg, creds.as_deref()).map(Arc::new)
}
/// Assemble the Pingora server with all services. Listeners bind when it runs.
pub fn server(rt: Arc<Runtime>, opts: &Options) -> Result<Server, EdgeError> {
pingora::tls::install_default_crypto_provider();
let conf = ServerConf {
threads: 2,
grace_period_seconds: Some(5),
graceful_shutdown_timeout_seconds: Some(10),
..ServerConf::default()
};
let mut server = Server::new_with_opt_and_conf(None, conf);
server.bootstrap();
let challenges = Arc::new(acme::Challenges::default());
let mut https = http_proxy_service(
&server.configuration,
proxy::EdgeProxy {
rt: rt.clone(),
connector: Connector::new(None),
},
);
let mut tls = TlsSettings::intermediate("", "").map_err(|e| EdgeError::Listen {
address: rt.cfg.https_listen.clone(),
reason: e.to_string(),
})?;
tls.set_cert_resolver(rt.certs.clone());
tls.enable_h2();
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
let mut http = Service::new(
"ianitor http".to_owned(),
http_app::HttpApp {
rt: rt.clone(),
challenges: challenges.clone(),
},
);
http.add_tcp(&rt.cfg.http_listen);
server.add_service(https);
server.add_service(http);
server.add_service(background_service(
"ianitor health checks",
health::HealthChecks { rt: rt.clone() },
));
server.add_service(background_service(
"ianitor acme",
acme::AcmeService {
rt: rt.clone(),
certs: rt.certs.clone(),
challenges,
ca_root: opts.acme_root.clone(),
},
));
Ok(server)
}
/// Run until `stop` resolves (or is dropped). For running edge inside a test process.
#[cfg(unix)]
pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) {
use pingora::server::{RunArgs, ShutdownSignal, ShutdownSignalWatch};
struct Stop(tokio::sync::Mutex<Option<tokio::sync::oneshot::Receiver<()>>>);
#[async_trait::async_trait]
impl ShutdownSignalWatch for Stop {
async fn recv(&self) -> ShutdownSignal {
if let Some(rx) = self.0.lock().await.take() {
let _ = rx.await;
}
ShutdownSignal::FastShutdown
}
}
server.run(RunArgs {
shutdown_signal: Box::new(Stop(tokio::sync::Mutex::new(Some(stop)))),
});
}
+171
View File
@@ -0,0 +1,171 @@
// 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/.
//! Error log (stderr, always on; journald under systemd) and the per-host access log
//! (JSON lines in a local file, client IP truncated to /24 or /48, no query strings).
//!
//! Library crates (Pingora, rustls, h2, ...) are capped at `info` whatever `IANITOR_LOG` says:
//! their debug output can include raw request and response headers.
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use log::{Level, LevelFilter, Log, Metadata, Record};
use serde::Serialize;
use crate::error::EdgeError;
struct StderrLogger {
own: LevelFilter,
}
const LIBRARY_MAX: LevelFilter = LevelFilter::Info;
impl Log for StderrLogger {
fn enabled(&self, m: &Metadata<'_>) -> bool {
let limit = if m.target().starts_with("ianitor") {
self.own
} else {
self.own.min(LIBRARY_MAX)
};
m.level() <= limit
}
fn log(&self, r: &Record<'_>) {
if self.enabled(r.metadata()) {
let lvl = match r.level() {
Level::Error => "ERROR",
Level::Warn => "WARN",
Level::Info => "INFO",
Level::Debug => "DEBUG",
Level::Trace => "TRACE",
};
let mut err = std::io::stderr().lock();
let _ = writeln!(err, "{lvl} {}: {}", r.target(), r.args());
}
}
fn flush(&self) {
let _ = std::io::stderr().flush();
}
}
/// Install the stderr logger. `level` is `error`, `warn`, `info` (default), `debug` or `trace`.
pub fn init(level: Option<&str>) {
let own = match level.map(str::to_ascii_lowercase).as_deref() {
Some("error") => LevelFilter::Error,
Some("warn") => LevelFilter::Warn,
Some("debug") => LevelFilter::Debug,
Some("trace") => LevelFilter::Trace,
_ => LevelFilter::Info,
};
if log::set_boxed_logger(Box::new(StderrLogger { own })).is_ok() {
log::set_max_level(own);
}
}
/// IPv4 → /24, IPv6 → /48 (IPv4-mapped IPv6 is treated as IPv4).
pub fn truncate_ip(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V4(v4) => {
let [a, b, c, _] = v4.octets();
IpAddr::V4(Ipv4Addr::new(a, b, c, 0))
}
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => truncate_ip(IpAddr::V4(v4)),
None => {
let s = v6.segments();
IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0))
}
},
}
}
#[derive(Serialize)]
pub struct AccessRecord<'a> {
pub ts: f64,
pub host: &'a str,
pub method: &'a str,
/// Path only: query strings can carry tokens.
pub path: &'a str,
pub status: u16,
pub remote_ip: Option<String>,
pub duration_ms: u64,
}
pub fn now_secs() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_secs_f64()
}
pub struct AccessLog {
file: Mutex<File>,
}
impl AccessLog {
pub fn open(path: &Path) -> Result<AccessLog, EdgeError> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|source| EdgeError::Write {
path: dir.to_owned(),
source,
})?;
}
let mut opts = OpenOptions::new();
opts.create(true).append(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o640);
let file = opts.open(path).map_err(|source| EdgeError::Write {
path: path.to_owned(),
source,
})?;
Ok(AccessLog {
file: Mutex::new(file),
})
}
pub fn write(&self, rec: &AccessRecord<'_>) {
let Ok(mut line) = serde_json::to_vec(rec) else {
return;
};
line.push(b'\n');
if let Ok(mut f) = self.file.lock()
&& let Err(e) = f.write_all(&line)
{
log::error!(target: "ianitor::access", "cannot write the access log: {e}");
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
fn t(s: &str) -> String {
truncate_ip(s.parse().unwrap()).to_string()
}
#[test]
fn ipv4_is_truncated_to_24() {
assert_eq!(t("192.168.17.42"), "192.168.17.0");
assert_eq!(t("127.0.0.1"), "127.0.0.0");
}
#[test]
fn ipv6_is_truncated_to_48() {
assert_eq!(t("2001:db8:abcd:12:3456::1"), "2001:db8:abcd::");
assert_eq!(t("::1"), "::");
}
#[test]
fn mapped_ipv4_is_treated_as_ipv4() {
assert_eq!(t("::ffff:10.1.2.3"), "10.1.2.0");
}
}
+56 -4
View File
@@ -2,9 +2,61 @@
// 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/.
//! ianitor-edge binary (not implemented yet).
//! `ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]`
//!
//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG`
//! (error, warn, info, debug, trace; libraries are capped at info).
fn main() -> std::process::ExitCode {
eprintln!("ianitor-edge: not implemented yet");
std::process::ExitCode::from(2)
use std::path::PathBuf;
use std::process::ExitCode;
use ianitor_edge::{EdgeError, Options};
fn parse_args() -> Result<(Options, bool), EdgeError> {
let mut opts = Options::default();
let mut check = false;
let mut config = None;
let mut args = std::env::args_os().skip(1);
while let Some(a) = args.next() {
match a.to_str() {
Some("--config") => config = args.next().map(PathBuf::from),
Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from),
Some("--check") => check = true,
Some("--help" | "-h") => {
println!(
"usage: ianitor-edge --config <edge.json> [--check] [--acme-root <ca.pem>]"
);
std::process::exit(0);
}
_ => {
return Err(EdgeError::Usage(format!(
"unknown argument {}",
a.to_string_lossy()
)));
}
}
}
opts.config =
config.ok_or_else(|| EdgeError::Usage("--config <edge.json> is required".into()))?;
Ok((opts, check))
}
fn main() -> ExitCode {
ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref());
let started = parse_args().and_then(|(opts, check)| {
let rt = ianitor_edge::prepare(&opts)?;
log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len());
if check {
return Ok(None);
}
ianitor_edge::server(rt, &opts).map(Some)
});
match started {
Ok(None) => ExitCode::SUCCESS,
Ok(Some(server)) => server.run_forever(),
Err(e) => {
log::error!(target: "ianitor::edge", "{e}");
ExitCode::FAILURE
}
}
}
+332
View File
@@ -0,0 +1,332 @@
// 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 HTTPS reverse proxy. Order per request (same as the Caddy compiler emits):
//! host lookup (unknown → 404) → forward-auth → websocket refusal → upstream with header rules.
use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Instant;
use async_trait::async_trait;
use http::header;
use pingora::connectors::http::Connector;
use pingora::http::{RequestHeader, ResponseHeader};
use pingora::proxy::{FailToProxy, ProxyHttp, Session};
use pingora::upstreams::peer::HttpPeer;
use pingora::{Error, ErrorSource, ErrorType, Result};
use crate::fetch;
use crate::forward_auth::{self, Outcome};
use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::runtime::{HostRt, Op, Runtime};
pub struct EdgeProxy {
pub rt: Arc<Runtime>,
pub connector: Connector,
}
pub struct Ctx {
host: Option<Arc<HostRt>>,
/// The Host header as the client sent it (with port, if any).
host_header: String,
start: Instant,
}
/// Host header (HTTP/1) or :authority (HTTP/2).
pub fn host_header(req: &RequestHeader) -> String {
req.headers
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
.or_else(|| req.uri.authority().map(|a| a.as_str().to_owned()))
.unwrap_or_default()
}
/// Host without port, lowercase. `[v6]:port` keeps the brackets off.
pub fn hostname(host_header: &str) -> String {
let h = host_header.trim();
let name = if let Some(rest) = h.strip_prefix('[') {
rest.split(']').next().unwrap_or("")
} else {
h.rsplit_once(':').map_or(h, |(n, port)| {
if port.bytes().all(|c| c.is_ascii_digit()) {
n
} else {
h
}
})
};
name.to_ascii_lowercase()
}
pub fn client_ip(session: &Session) -> Option<IpAddr> {
session
.client_addr()
.and_then(|a| a.as_inet())
.map(|a| a.ip())
}
/// A response with an empty body, like Caddy's `static_response` and error responses.
pub async fn respond_empty(session: &mut Session, code: u16) -> Result<()> {
let mut resp = ResponseHeader::build(code, Some(1))?;
resp.insert_header(header::CONTENT_LENGTH, "0")?;
session.write_response_header(Box::new(resp), true).await
}
fn apply(
ops: &[Op],
mut set: impl FnMut(&http::HeaderName, Option<&http::HeaderValue>) -> Result<()>,
) -> Result<()> {
for op in ops {
match op {
Op::Set(n, v) => set(n, Some(v))?,
Op::Remove(n) => set(n, None)?,
}
}
Ok(())
}
fn is_websocket_upgrade(req: &RequestHeader) -> bool {
req.headers
.get(header::UPGRADE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket"))
}
#[async_trait]
impl ProxyHttp for EdgeProxy {
type CTX = Ctx;
fn new_ctx(&self) -> Ctx {
Ctx {
host: None,
host_header: String::new(),
start: Instant::now(),
}
}
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
ctx.host_header = host_header(session.req_header());
let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else {
respond_empty(session, 404).await?;
return Ok(true);
};
ctx.host = Some(host.clone());
if host.cfg.forward_auth {
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
})?;
let ip = client_ip(session).map(|i| i.to_string());
let outcome = match forward_auth::check(
&self.connector,
fa,
session,
&ctx.host_header,
ip,
)
.await
{
Ok(o) => o,
Err(e) => {
log::error!(target: "ianitor::auth", "forward-auth for {} failed, denying: {e}", host.cfg.hostname);
return Err(Error::explain(
ErrorType::HTTPStatus(502),
"forward-auth unreachable",
));
}
};
match outcome {
Outcome::Deny(resp, body) => {
let head = session.req_header().method == http::Method::HEAD;
let end = head || body.is_empty();
session.write_response_header(resp, end).await?;
if !end {
session.write_response_body(Some(body), true).await?;
}
return Ok(true);
}
Outcome::Allow(copy) => {
let req = session.req_header_mut();
for (name, value) in copy {
req.remove_header(&name);
if let Some(v) = value {
req.insert_header(name, v)?;
}
}
}
}
}
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
respond_empty(session, 403).await?;
return Ok(true);
}
Ok(false)
}
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
let host = ctx
.host
.as_ref()
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
let n = host.upstreams.len();
let first = host.next.fetch_add(1, Ordering::Relaxed);
let chosen = (0..n)
.map(|i| &host.upstreams[(first + i) % n])
.find(|u| u.healthy.load(Ordering::Relaxed))
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?;
log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority);
Ok(Box::new(fetch::peer(chosen)))
}
fn fail_to_connect(
&self,
_s: &mut Session,
_p: &HttpPeer,
_c: &mut Ctx,
mut e: Box<Error>,
) -> Box<Error> {
// Like Caddy's default (no lb_try_duration): one attempt, then 502.
e.set_retry(false);
e
}
async fn upstream_request_filter(
&self,
session: &mut Session,
req: &mut RequestHeader,
ctx: &mut Ctx,
) -> Result<()> {
// Forwarding headers are always edge's own; client-supplied values are replaced.
match client_ip(session) {
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
None => {
req.remove_header("X-Forwarded-For");
}
}
req.insert_header("X-Forwarded-Proto", "https")?;
req.insert_header("X-Forwarded-Host", ctx.host_header.as_str())?;
if let Some(host) = &ctx.host {
apply(&host.request_ops, |n, v| {
match v {
Some(v) => req.insert_header(n.clone(), v.clone())?,
None => {
req.remove_header(n);
}
}
Ok(())
})?;
}
Ok(())
}
async fn upstream_response_filter(
&self,
_s: &mut Session,
resp: &mut ResponseHeader,
ctx: &mut Ctx,
) -> Result<()> {
let Some(host) = &ctx.host else { return Ok(()) };
apply(&host.response_ops, |n, v| {
match v {
Some(v) => resp.insert_header(n.clone(), v.clone())?,
None => {
resp.remove_header(n);
}
}
Ok(())
})?;
// Defence in depth: never hand a secret back to a client, even if the upstream echoes it.
if !host.secret_values.is_empty() {
let leaking: Vec<http::HeaderName> = resp
.headers
.iter()
.filter(|(_, v)| host.secret_values.iter().any(|s| contains(v.as_bytes(), s)))
.map(|(n, _)| n.clone())
.collect();
for n in leaking {
log::warn!(target: "ianitor::secrets", "{}: dropped response header `{n}` because it contained a secret", host.cfg.hostname);
resp.remove_header(&n);
}
}
Ok(())
}
async fn fail_to_proxy(&self, session: &mut Session, e: &Error, _ctx: &mut Ctx) -> FailToProxy {
let code = match e.etype() {
ErrorType::HTTPStatus(c) => *c,
_ => match e.esource() {
ErrorSource::Upstream => 502,
ErrorSource::Downstream => match e.etype() {
ErrorType::WriteError | ErrorType::ReadError | ErrorType::ConnectionClosed => 0,
_ => 400,
},
ErrorSource::Internal | ErrorSource::Unset => 500,
},
};
if code > 0
&& session.response_written().is_none()
&& let Err(err) = respond_empty(session, code).await
{
log::debug!(target: "ianitor::proxy", "could not send the error response: {err}");
}
FailToProxy {
error_code: code,
can_reuse_downstream: false,
}
}
async fn logging(&self, session: &mut Session, _e: Option<&Error>, ctx: &mut Ctx) {
let Some(host) = &ctx.host else { return };
if !host.cfg.access_log {
return;
}
let Some(log) = &self.rt.access_log else {
return;
};
let req = session.req_header();
log.write(&AccessRecord {
ts: now_secs(),
host: &host.cfg.hostname,
method: req.method.as_str(),
path: req.uri.path(),
status: session.response_written().map_or(0, |r| r.status.as_u16()),
remote_ip: client_ip(session).map(|i| truncate_ip(i).to_string()),
duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX),
});
}
fn request_summary(&self, session: &Session, ctx: &Ctx) -> String {
// Method, host and path only: no query string, no headers.
let req = session.req_header();
format!("{} {}{}", req.method, ctx.host_header, req.uri.path())
}
}
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hostname_strips_port_and_case() {
assert_eq!(hostname("App.Test:8443"), "app.test");
assert_eq!(hostname("app.test"), "app.test");
assert_eq!(hostname("[::1]:443"), "::1");
assert_eq!(hostname(""), "");
}
#[test]
fn contains_finds_substrings() {
assert!(contains(b"abc-secret-def", b"secret"));
assert!(!contains(b"abc", b""));
assert!(!contains(b"sec", b"secret"));
}
}
+251
View File
@@ -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,
})
}
+163
View File
@@ -0,0 +1,163 @@
// 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/.
//! Secrets referenced by header rules, read once at startup from `$CREDENTIALS_DIRECTORY`
//! (systemd `LoadCredential=`). A [`Secret`] never prints its value: `Debug` and `Display`
//! are redacted, the header value is marked sensitive (HPACK never-index) and errors name
//! the secret, never its content.
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::Path;
use http::HeaderValue;
use crate::error::EdgeError;
/// Largest credential file accepted.
const MAX_LEN: u64 = 8192;
#[derive(Clone)]
pub struct Secret {
value: HeaderValue,
}
impl Secret {
pub fn header_value(&self) -> HeaderValue {
self.value.clone()
}
pub fn as_bytes(&self) -> &[u8] {
self.value.as_bytes()
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Secret(<redacted>)")
}
}
impl fmt::Display for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<redacted>")
}
}
/// Turn a credential file's bytes into a header value. One trailing newline (`\n` or `\r\n`)
/// is dropped, as Caddy's `{file.*}` placeholder does; anything else must be one line of
/// visible ASCII, spaces and tabs.
pub fn parse(name: &str, raw: &[u8]) -> Result<Secret, EdgeError> {
let err = |reason| EdgeError::Secret {
name: name.to_owned(),
reason,
};
let trimmed = raw
.strip_suffix(b"\r\n")
.or_else(|| raw.strip_suffix(b"\n"))
.unwrap_or(raw);
if trimmed.is_empty() {
return Err(err("the credential is empty"));
}
if !trimmed
.iter()
.all(|c| (0x20..0x7f).contains(c) || *c == b'\t')
{
return Err(err("the credential must be a single line of visible ASCII"));
}
let mut value = HeaderValue::from_bytes(trimmed)
.map_err(|_| err("the credential is not a valid header value"))?;
value.set_sensitive(true);
Ok(Secret { value })
}
pub struct Secrets(BTreeMap<String, Secret>);
impl Secrets {
pub fn get(&self, name: &str) -> Option<&Secret> {
self.0.get(name)
}
/// Load every named secret from `dir` (the value of `$CREDENTIALS_DIRECTORY`).
pub fn load(names: &BTreeSet<String>, dir: Option<&Path>) -> Result<Secrets, EdgeError> {
let mut out = BTreeMap::new();
for name in names {
// Names are validated by core, but the edge config is input too.
if name.is_empty()
|| !name
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-')
{
return Err(EdgeError::Secret {
name: name.clone(),
reason: "the name is not a valid credential name",
});
}
let Some(dir) = dir else {
return Err(EdgeError::Secret {
name: name.clone(),
reason: "$CREDENTIALS_DIRECTORY is not set (use systemd LoadCredential=)",
});
};
let path = dir.join(name);
let meta = std::fs::metadata(&path).map_err(|_| EdgeError::Secret {
name: name.clone(),
reason: "no such credential in $CREDENTIALS_DIRECTORY",
})?;
if meta.len() > MAX_LEN {
return Err(EdgeError::Secret {
name: name.clone(),
reason: "the credential is larger than 8 KiB",
});
}
let raw = std::fs::read(&path).map_err(|_| EdgeError::Secret {
name: name.clone(),
reason: "the credential cannot be read",
})?;
out.insert(name.clone(), parse(name, &raw)?);
}
Ok(Secrets(out))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::panic)]
use super::*;
#[test]
fn trailing_newline_is_dropped_once() {
assert_eq!(parse("a", b"value\n").unwrap().as_bytes(), b"value");
assert_eq!(parse("a", b"value\r\n").unwrap().as_bytes(), b"value");
assert_eq!(parse("a", b"value").unwrap().as_bytes(), b"value");
}
#[test]
fn multi_line_and_control_bytes_are_refused() {
for bad in [
&b"a\nb"[..],
b"a\n\n",
b"a\rb",
b"\0",
b"",
b"\n",
"ü".as_bytes(),
] {
assert!(parse("a", bad).is_err(), "{bad:?}");
}
}
#[test]
fn debug_and_display_never_show_the_value() {
let s = parse("a", b"hunter2").unwrap();
assert!(!format!("{s:?} {s}").contains("hunter2"));
assert!(s.header_value().is_sensitive());
}
#[test]
fn errors_never_contain_the_value() {
let e = parse("api", b"hunter2\nx").unwrap_err();
assert!(!e.to_string().contains("hunter2"));
}
}
+66
View File
@@ -0,0 +1,66 @@
// 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/.
//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals)
//! without touching connections in flight.
use std::collections::HashMap;
use std::sync::Arc;
use arc_swap::ArcSwap;
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use rustls_pki_types::pem::PemObject;
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
#[derive(Debug, Default)]
pub struct CertStore {
certs: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
}
impl CertStore {
pub fn insert(&self, host: &str, key: CertifiedKey) {
let key = Arc::new(key);
self.certs.rcu(|m| {
let mut m = HashMap::clone(m);
m.insert(host.to_owned(), key.clone());
m
});
}
pub fn has(&self, host: &str) -> bool {
self.certs.load().contains_key(host)
}
}
impl ResolvesServerCert for CertStore {
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
let name = hello.server_name()?.to_ascii_lowercase();
self.certs.load().get(&name).cloned()
}
}
/// Parse a PEM chain and PEM private key into a rustls key pair, checking they match.
pub fn certified_key(cert_pem: &[u8], key_pem: &[u8]) -> Result<CertifiedKey, String> {
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(cert_pem)
.collect::<Result<_, _>>()
.map_err(|e| format!("cannot parse the certificate chain: {e}"))?;
if chain.is_empty() {
return Err("the certificate file has no certificate".into());
}
// Never include key bytes in an error.
let key = PrivateKeyDer::from_pem_slice(key_pem)
.map_err(|_| "cannot parse the private key".to_owned())?;
let provider = rustls::crypto::ring::default_provider();
CertifiedKey::from_der(chain, key, &provider)
.map_err(|e| format!("certificate and key do not form a usable pair: {e}"))
}
/// `notAfter` of the first certificate in a PEM chain, as Unix seconds.
pub fn not_after(cert_pem: &[u8]) -> Option<i64> {
let first = CertificateDer::pem_slice_iter(cert_pem).next()?.ok()?;
let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?;
Some(cert.validity().not_after.timestamp())
}
+52 -11
View File
@@ -13,8 +13,8 @@ use std::sync::Arc;
use std::time::Duration;
use ianitor_core::compile::{self, CompileOptions};
use ianitor_core::{load, SourceFile, TlsMode};
use ianitor_testkit::proc::{free_port, local, wait_for_port, ChildGuard, TempDir};
use ianitor_core::{SourceFile, TlsMode, load};
use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port};
use ianitor_testkit::tls::TestCa;
use rustls::RootCertStore;
@@ -42,7 +42,12 @@ impl Edge {
/// Everything edge wrote or was given, except the credentials themselves.
pub fn all_output(&self) -> String {
format!("{}\n{}\n{}", self.stderr(), self.access_log(), self.config_text)
format!(
"{}\n{}\n{}",
self.stderr(),
self.access_log(),
self.config_text
)
}
pub fn exited(&mut self) -> Option<std::process::ExitStatus> {
@@ -60,7 +65,13 @@ pub struct EdgeSpec<'a> {
impl Default for EdgeSpec<'_> {
fn default() -> Self {
EdgeSpec { site: "", hosts: Vec::new(), secrets: Vec::new(), log_level: "info", extra_args: Vec::new() }
EdgeSpec {
site: "",
hosts: Vec::new(),
secrets: Vec::new(),
log_level: "info",
extra_args: Vec::new(),
}
}
}
@@ -70,14 +81,32 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
for d in ["certs", "state", "creds", "logs"] {
std::fs::create_dir_all(dir.join(d)).unwrap();
}
let sources: Vec<SourceFile> = spec.hosts.iter().map(|(n, c)| SourceFile { name: n, contents: c }).collect();
let model = load(&SourceFile { name: "ianitor.toml", contents: spec.site }, &sources).expect("valid routes");
let sources: Vec<SourceFile> = spec
.hosts
.iter()
.map(|(n, c)| SourceFile {
name: n,
contents: c,
})
.collect();
let model = load(
&SourceFile {
name: "ianitor.toml",
contents: spec.site,
},
&sources,
)
.expect("valid routes");
let ca = TestCa::new("Ianitor Test CA");
for h in model.hosts() {
if h.tls == TlsMode::Domi {
let leaf = ca.issue(&[h.hostname.as_str()]);
std::fs::write(dir.join(&format!("certs/{}.crt", h.hostname)), leaf.cert_pem).unwrap();
std::fs::write(
dir.join(&format!("certs/{}.crt", h.hostname)),
leaf.cert_pem,
)
.unwrap();
std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap();
}
}
@@ -105,15 +134,24 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
cmd.args(&spec.extra_args);
cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds"));
cmd.env("IANITOR_LOG", spec.log_level);
cmd.stdout(Stdio::from(stderr.try_clone().unwrap())).stderr(Stdio::from(stderr));
cmd.stdout(Stdio::from(stderr.try_clone().unwrap()))
.stderr(Stdio::from(stderr));
let child = ChildGuard(cmd.spawn().expect("spawn ianitor-edge"));
Edge { child, http, https, dir, ca, config_text }
Edge {
child,
http,
https,
dir,
ca,
config_text,
}
}
/// Spawn and wait until both listeners accept connections.
pub fn start(spec: EdgeSpec<'_>) -> Edge {
let mut e = spawn(spec);
let ok = wait_for_port(e.https, Duration::from_secs(20)) && wait_for_port(e.http, Duration::from_secs(5));
let ok = wait_for_port(e.https, Duration::from_secs(20))
&& wait_for_port(e.http, Duration::from_secs(5));
if !ok || e.exited().is_some() {
panic!("ianitor-edge did not start:\n{}", e.stderr());
}
@@ -121,5 +159,8 @@ pub fn start(spec: EdgeSpec<'_>) -> Edge {
}
pub fn host_file(hostname: &str, body: &str) -> (String, String) {
(format!("hosts/{hostname}.toml"), format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}"))
(
format!("hosts/{hostname}.toml"),
format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}"),
)
}
+111 -26
View File
@@ -11,10 +11,10 @@
mod common;
use common::{host_file, start, EdgeSpec};
use common::{EdgeSpec, host_file, start};
use ianitor_testkit::authelia::MockAuthelia;
use ianitor_testkit::client::{self, Req, WsOutcome};
use ianitor_testkit::upstream::{closed_port, Echo, WsEcho};
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port};
fn site(auth_url: &str) -> String {
format!("[forward_auth]\nurl = \"{auth_url}\"\n")
@@ -29,8 +29,17 @@ async fn denial_never_reaches_the_upstream() {
let edge = start(EdgeSpec {
site: &site,
hosts: vec![
host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url())),
host_file("wsauth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url())),
host_file(
"auth.test",
&format!(
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
echo.url()
),
),
host_file(
"wsauth.test",
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url()),
),
],
..Default::default()
});
@@ -48,7 +57,10 @@ async fn denial_never_reaches_the_upstream() {
r.header("location"),
Some("https://auth.test/?rd=https%3A%2F%2Fauth.test%2Fprivate%3Fx%3D1")
);
assert_eq!(r.header("set-cookie"), Some("authelia_flow=1; Path=/; HttpOnly"));
assert_eq!(
r.header("set-cookie"),
Some("authelia_flow=1; Path=/; HttpOnly")
);
assert!(r.text().contains("302 Found"));
let r = go(Req::new("HEAD", "auth.test", "/")).await;
@@ -60,7 +72,10 @@ async fn denial_never_reaches_the_upstream() {
let r = go(Req::get("auth.test", "/").header("authorization", "Bearer wrong")).await;
assert_eq!(r.status, 401);
assert_eq!(r.header("www-authenticate"), Some("Basic realm=\"Authorization Required\""));
assert_eq!(
r.header("www-authenticate"),
Some("Basic realm=\"Authorization Required\"")
);
let r = go(Req::get("auth.test", "/").header("cookie", "authelia_session=forbidden")).await;
assert_eq!(r.status, 403);
@@ -74,16 +89,38 @@ async fn denial_never_reaches_the_upstream() {
.header("x-forwarded-for", "10.0.0.1"))
.await;
assert_eq!(r.status, 302);
assert!(r.header("location").unwrap().contains("auth.test%2Fadmin"), "edge sends its own X-Forwarded-*");
assert!(
r.header("location").unwrap().contains("auth.test%2Fadmin"),
"edge sends its own X-Forwarded-*"
);
// A websocket upgrade without a session is denied before any upgrade happens.
match client::websocket(edge.https, "wsauth.test", roots.clone(), "wsauth.test", "/socket", &[], "hi").await.unwrap() {
match client::websocket(
edge.https,
"wsauth.test",
roots.clone(),
"wsauth.test",
"/socket",
&[],
"hi",
)
.await
.unwrap()
{
WsOutcome::Refused(r) => assert_eq!(r.status, 302),
WsOutcome::Upgraded { .. } => panic!("unauthenticated websocket was upgraded"),
}
assert!(echo.proxied().is_empty(), "a denied request reached the upstream: {:?}", echo.proxied());
assert_eq!(ws.connections(), 0, "a denied websocket reached the upstream");
assert!(
echo.proxied().is_empty(),
"a denied request reached the upstream: {:?}",
echo.proxied()
);
assert_eq!(
ws.connections(),
0,
"a denied websocket reached the upstream"
);
// What Authelia was told, per its proxy-authorization guide.
let asked = authelia.requests();
@@ -95,10 +132,22 @@ async fn denial_never_reaches_the_upstream() {
assert_eq!(post.method, "GET", "the auth subrequest is a GET");
assert_eq!(post.path, "/api/authz/forward-auth");
assert_eq!(post.header("x-forwarded-proto"), Some(b"https".as_slice()));
assert_eq!(post.header("x-forwarded-host"), Some(b"auth.test".as_slice()));
assert_eq!(post.header("x-forwarded-uri"), Some(b"/submit?x=1".as_slice()));
assert_eq!(post.header("x-forwarded-for"), Some(b"127.0.0.1".as_slice()));
assert!(post.body.is_empty(), "the request body is not sent to the auth server");
assert_eq!(
post.header("x-forwarded-host"),
Some(b"auth.test".as_slice())
);
assert_eq!(
post.header("x-forwarded-uri"),
Some(b"/submit?x=1".as_slice())
);
assert_eq!(
post.header("x-forwarded-for"),
Some(b"127.0.0.1".as_slice())
);
assert!(
post.body.is_empty(),
"the request body is not sent to the auth server"
);
}
#[tokio::test(flavor = "multi_thread")]
@@ -108,7 +157,13 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() {
let site = site(&authelia.url());
let edge = start(EdgeSpec {
site: &site,
hosts: vec![host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()))],
hosts: vec![host_file(
"auth.test",
&format!(
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
echo.url()
),
)],
..Default::default()
});
let roots = edge.roots();
@@ -131,10 +186,19 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() {
let up = &seen[0];
assert_eq!(up.header("remote-user"), Some(b"alice".as_slice()));
assert_eq!(up.header("remote-groups"), Some(b"admins,dev".as_slice()));
assert_eq!(up.header("remote-email"), Some(b"alice@example.org".as_slice()));
assert_eq!(
up.header("remote-email"),
Some(b"alice@example.org".as_slice())
);
assert_eq!(up.header("remote-name"), Some(b"Alice Example".as_slice()));
assert_eq!(up.body, b"form=data", "the body still reaches the upstream");
assert_eq!(up.headers.iter().filter(|(n, _)| n == "remote-user").count(), 1);
assert_eq!(
up.headers
.iter()
.filter(|(n, _)| n == "remote-user")
.count(),
1
);
// Allowed without identity: the client's own Remote-* headers are removed, not passed on.
echo.clear();
@@ -142,31 +206,52 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() {
edge.https,
"auth.test",
roots.clone(),
&Req::get("auth.test", "/").header("cookie", "authelia_session=nameless").header("remote-user", "mallory"),
&Req::get("auth.test", "/")
.header("cookie", "authelia_session=nameless")
.header("remote-user", "mallory"),
)
.await
.unwrap();
assert_eq!(r.status, 200);
assert_eq!(echo.proxied()[0].header("remote-user"), None);
let r = client::https(edge.https, "auth.test", roots, &Req::get("auth.test", "/").header("authorization", "Bearer good"))
.await
.unwrap();
let r = client::https(
edge.https,
"auth.test",
roots,
&Req::get("auth.test", "/").header("authorization", "Bearer good"),
)
.await
.unwrap();
assert_eq!(r.status, 200);
}
#[tokio::test(flavor = "multi_thread")]
async fn unreachable_auth_server_fails_closed() {
let echo = Echo::start("app").await;
let site = site(&format!("http://127.0.0.1:{}/api/authz/forward-auth", closed_port()));
let site = site(&format!(
"http://127.0.0.1:{}/api/authz/forward-auth",
closed_port()
));
let edge = start(EdgeSpec {
site: &site,
hosts: vec![host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()))],
hosts: vec![host_file(
"auth.test",
&format!(
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
echo.url()
),
)],
..Default::default()
});
let r = client::https(edge.https, "auth.test", edge.roots(), &Req::get("auth.test", "/").header("cookie", "authelia_session=good"))
.await
.unwrap();
let r = client::https(
edge.https,
"auth.test",
edge.roots(),
&Req::get("auth.test", "/").header("cookie", "authelia_session=good"),
)
.await
.unwrap();
assert_eq!(r.status, 502);
assert!(echo.proxied().is_empty());
}
+120 -26
View File
@@ -10,12 +10,15 @@
mod common;
use common::{host_file, start, spawn, EdgeSpec};
use common::{EdgeSpec, host_file, spawn, start};
use ianitor_testkit::client::{self, Req, Resp, WsOutcome};
use ianitor_testkit::upstream::{closed_port, Echo, WsEcho};
use ianitor_testkit::upstream::{Echo, WsEcho, closed_port};
fn unique_secret() -> String {
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
format!("sekret-{}-{nanos:x}-tail", std::process::id())
}
@@ -26,7 +29,11 @@ fn assert_clean(what: &str, haystack: &[u8], secret: &str) {
fn assert_resp_clean(what: &str, r: &Resp, secret: &str) {
for (n, v) in &r.headers {
assert_clean(&format!("{what}: response header {n}"), v.as_bytes(), secret);
assert_clean(
&format!("{what}: response header {n}"),
v.as_bytes(),
secret,
);
}
assert_clean(&format!("{what}: response body"), &r.body, secret);
}
@@ -36,13 +43,32 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
let secret = unique_secret();
let echo = Echo::start("app").await;
let ws = WsEcho::start().await;
let rule = "[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n";
let rule =
"[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n";
let edge = start(EdgeSpec {
site: "secrets = [\"api_key\"]\n",
hosts: vec![
host_file("app.test", &format!("upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", echo.url())),
host_file("down.test", &format!("upstreams = [\"http://127.0.0.1:{}\"]\naccess_log = \"truncated\"\n{rule}", closed_port())),
host_file("ws.test", &format!("upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", ws.url())),
host_file(
"app.test",
&format!(
"upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}",
echo.url()
),
),
host_file(
"down.test",
&format!(
"upstreams = [\"http://127.0.0.1:{}\"]\naccess_log = \"truncated\"\n{rule}",
closed_port()
),
),
host_file(
"ws.test",
&format!(
"upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}",
ws.url()
),
),
],
// systemd credentials usually end with a newline; it is not part of the value.
secrets: vec![("api_key".into(), format!("{secret}\n").into_bytes())],
@@ -57,20 +83,45 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
};
let mut responses = Vec::new();
responses.push(("plain GET", go("app.test", Req::get("app.test", "/hello?token=abc")).await));
responses.push(("POST", go("app.test", Req::new("POST", "app.test", "/submit").body(b"payload")).await));
responses.push((
"plain GET",
go("app.test", Req::get("app.test", "/hello?token=abc")).await,
));
responses.push((
"POST",
go(
"app.test",
Req::new("POST", "app.test", "/submit").body(b"payload"),
)
.await,
));
responses.push((
"client tries to set the header",
go("app.test", Req::get("app.test", "/").header("x-api-key", "attacker")).await,
go(
"app.test",
Req::get("app.test", "/").header("x-api-key", "attacker"),
)
.await,
));
responses.push((
"upstream error status",
go("app.test", Req::get("app.test", "/status/500")).await,
));
responses.push(("upstream error status", go("app.test", Req::get("app.test", "/status/500")).await));
responses.push((
"upstream reflects the secret in a header",
go("app.test", Req::get("app.test", "/reflect?h=x-api-key")).await,
));
responses.push(("upstream down", go("down.test", Req::get("down.test", "/")).await));
responses.push(("unknown host", go("app.test", Req::get("nope.test", "/")).await));
let plain = client::http(edge.http, &Req::get("app.test", "/x?y=1")).await.unwrap();
responses.push((
"upstream down",
go("down.test", Req::get("down.test", "/")).await,
));
responses.push((
"unknown host",
go("app.test", Req::get("nope.test", "/")).await,
));
let plain = client::http(edge.http, &Req::get("app.test", "/x?y=1"))
.await
.unwrap();
responses.push(("plain HTTP redirect", plain));
for (what, r) in &responses {
@@ -78,10 +129,24 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
}
assert_eq!(responses[0].1.status, 200);
assert_eq!(responses[4].1.status, 200);
assert!(responses[4].1.header("x-reflected").is_none(), "edge strips a response header carrying a secret");
assert!(
responses[4].1.header("x-reflected").is_none(),
"edge strips a response header carrying a secret"
);
assert_eq!(responses[5].1.status, 502);
match client::websocket(edge.https, "ws.test", roots.clone(), "ws.test", "/socket", &[], "ping").await.unwrap() {
match client::websocket(
edge.https,
"ws.test",
roots.clone(),
"ws.test",
"/socket",
&[],
"ping",
)
.await
.unwrap()
{
WsOutcome::Upgraded { status, echo } => {
assert_eq!(status, 101);
assert_eq!(echo, "ping");
@@ -93,18 +158,38 @@ async fn injected_secret_never_appears_in_a_response_or_log() {
let seen = echo.proxied();
assert!(seen.len() >= 5, "{seen:?}");
for r in &seen {
assert_eq!(r.header("x-api-key"), Some(secret.as_bytes()), "upstream request {}", r.path);
assert_eq!(
r.header("x-api-key"),
Some(secret.as_bytes()),
"upstream request {}",
r.path
);
}
// Give the access log a moment to flush, then check every output channel.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let access = edge.access_log();
assert!(access.lines().count() >= 7, "access log has the requests:\n{access}");
assert!(access.contains("\"127.0.0.0\""), "IPv4 truncated to /24:\n{access}");
assert!(!access.contains("127.0.0.1"), "full client IP must not be logged:\n{access}");
assert!(!access.contains("token=abc"), "query strings are not logged:\n{access}");
assert!(
access.lines().count() >= 7,
"access log has the requests:\n{access}"
);
assert!(
access.contains("\"127.0.0.0\""),
"IPv4 truncated to /24:\n{access}"
);
assert!(
!access.contains("127.0.0.1"),
"full client IP must not be logged:\n{access}"
);
assert!(
!access.contains("token=abc"),
"query strings are not logged:\n{access}"
);
let stderr = edge.stderr();
assert!(stderr.len() > 100, "trace logging produced output:\n{stderr}");
assert!(
stderr.len() > 100,
"trace logging produced output:\n{stderr}"
);
assert_clean("stderr (trace level)", stderr.as_bytes(), &secret);
assert_clean("access log", access.as_bytes(), &secret);
assert_clean("compiled edge config", edge.config_text.as_bytes(), &secret);
@@ -143,15 +228,24 @@ async fn malformed_secret_is_rejected_without_echoing_it() {
site: "secrets = [\"api_key\"]\n",
hosts: vec![host_file(
"app.test",
&format!("upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", echo.url()),
&format!(
"upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n",
echo.url()
),
)],
// A newline inside the value would split the header: refused.
secrets: vec![("api_key".into(), format!("{secret}\ninjected: yes\n").into_bytes())],
secrets: vec![(
"api_key".into(),
format!("{secret}\ninjected: yes\n").into_bytes(),
)],
log_level: "trace",
..Default::default()
});
let status = wait_exit(&mut edge);
assert!(!status.success(), "edge must refuse a secret that is not a valid header value");
assert!(
!status.success(),
"edge must refuse a secret that is not a valid header value"
);
assert_clean("stderr", edge.stderr().as_bytes(), &secret);
}