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

204 lines
6.4 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/.
//! 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, share links, websockets,
//! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and
//! redirects), health checks, ACME issuance and renewal, and the admin socket through which
//! control reloads the config in process (see `shared`).
pub mod acme;
#[cfg(unix)]
pub mod admin;
pub mod error;
pub mod fetch;
pub mod forward_auth;
pub mod health;
pub mod http_app;
pub mod logging;
pub mod pages;
pub mod proxy;
pub mod runtime;
pub mod secrets;
pub mod share;
pub mod shared;
pub mod tls;
use std::path::{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;
pub use shared::Shared;
#[derive(Debug, Clone, Default)]
pub struct Options {
/// The compiled edge config (`ianitor-core` edge compiler output).
pub config: PathBuf,
/// The trial config control writes before an apply; default `<config>.trial`.
pub trial_config: Option<PathBuf>,
/// Admin socket for control (Unix only); none when `None`.
pub admin_socket: Option<PathBuf>,
/// The share-link revocation file control writes; without it, share links are refused.
pub share_revocations: Option<PathBuf>,
/// Extra trust root for the ACME directory's TLS (Pebble in tests).
pub acme_root: Option<PathBuf>,
/// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process).
pub credentials_dir: Option<PathBuf>,
}
impl Options {
pub fn trial_path(&self) -> PathBuf {
self.trial_config
.clone()
.unwrap_or_else(|| default_trial_path(&self.config))
}
}
/// `<config>.trial`, next to the config.
pub fn default_trial_path(config: &Path) -> PathBuf {
let mut name = config.file_name().unwrap_or_default().to_os_string();
name.push(".trial");
config.with_file_name(name)
}
fn credentials_dir(opts: &Options) -> Option<PathBuf> {
opts.credentials_dir
.clone()
.or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from))
}
/// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates.
pub fn prepare(opts: &Options) -> Result<Arc<Shared>, EdgeError> {
let creds = credentials_dir(opts);
let rt = runtime::build_file(&opts.config, creds.as_deref())?;
Ok(shared_for(rt, opts))
}
/// Wrap an already built runtime (tests run edge in process this way).
pub fn shared_for(rt: Runtime, opts: &Options) -> Arc<Shared> {
Shared::new(
rt,
shared::Paths {
config: opts.config.clone(),
trial: opts.trial_path(),
revocations: opts.share_revocations.clone(),
},
credentials_dir(opts),
)
}
/// Assemble the Pingora server with all services. Listeners bind when it runs.
pub fn server(shared: Arc<Shared>, 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 rt = shared.current();
let mut https = http_proxy_service(
&server.configuration,
proxy::EdgeProxy {
shared: shared.clone(),
connector: Connector::new(None),
},
);
let mut tls =
TlsSettings::with_callbacks(Box::new(tls::SniRecorder)).map_err(|e| EdgeError::Listen {
address: rt.cfg.https_listen.clone(),
reason: e.to_string(),
})?;
tls.set_cert_resolver(shared.certs.clone());
tls.set_client_cert_verifier(shared.devices.clone());
tls.enable_h2();
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
https
.endpoints()
.set_pre_tls_callback(Arc::new(tls::HandshakeStart));
let mut http = Service::new(
"ianitor http".to_owned(),
http_app::HttpApp {
shared: shared.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 {
shared: shared.clone(),
},
));
server.add_service(background_service(
"ianitor acme",
acme::AcmeService {
shared: shared.clone(),
challenges,
ca_root: opts.acme_root.clone(),
},
));
#[cfg(unix)]
{
server.add_service(background_service(
"ianitor share revocations",
admin::RevocationPoller {
shared: shared.clone(),
},
));
if let Some(path) = &opts.admin_socket {
server.add_service(background_service(
"ianitor admin socket",
admin::AdminSocket {
shared: shared.clone(),
path: path.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)))),
});
}