#![forbid(unsafe_code)]
#![deny(missing_docs)]
use std::fmt;
use std::future::Future;
use std::net::{Ipv4Addr, SocketAddr};
use std::time::Duration;
use axum::Router;
use seiva::ports::PortResult;
use seiva::worker::{run_worker, WorkerConfig};
use std::sync::Arc;
use seiva_config::{EnvReader, FromEnv};
use seiva_http::{
router_with_auth, Authenticator, Health, HttpSecurity, JwtAuthenticator, RateLimit,
};
use tokio::net::TcpListener;
pub use seiva::worker::WorkerReport;
pub use seiva_config::{AppEnv, ConfigError};
pub mod observability {
use tracing_subscriber::{fmt, EnvFilter};
pub fn init() {
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
let _ = fmt()
.json()
.with_current_span(false)
.with_env_filter(filter)
.try_init();
}
}
pub const HTTP_ADDR_VAR: &str = "SEIVA_HTTP_ADDR";
pub const PORT_VAR: &str = "PORT";
pub const EXPOSE_ERROR_DETAILS_VAR: &str = "SEIVA_EXPOSE_ERROR_DETAILS";
pub const DEFAULT_HTTP_ADDR: &str = "127.0.0.1:8080";
pub const METRICS_ADDR_VAR: &str = "SEIVA_METRICS_ADDR";
pub const CORS_ALLOWED_ORIGINS_VAR: &str = "SEIVA_CORS_ALLOWED_ORIGINS";
pub const TRUST_FORWARDED_FOR_VAR: &str = "SEIVA_TRUST_FORWARDED_FOR";
pub const EXPOSE_DOCS_VAR: &str = "SEIVA_EXPOSE_DOCS";
pub const RATE_LIMIT_MAX_REQUESTS_VAR: &str = "SEIVA_RATE_LIMIT_MAX_REQUESTS";
pub const RATE_LIMIT_WINDOW_SECS_VAR: &str = "SEIVA_RATE_LIMIT_WINDOW_SECS";
pub const OIDC_JWKS_FILE_VAR: &str = "SEIVA_OIDC_JWKS_FILE";
pub const OIDC_ISSUER_VAR: &str = "SEIVA_OIDC_ISSUER";
pub const OIDC_AUDIENCE_VAR: &str = "SEIVA_OIDC_AUDIENCE";
pub const OIDC_TENANT_CLAIM_VAR: &str = "SEIVA_OIDC_TENANT_CLAIM";
pub const OIDC_PERMISSION_CLAIM_VAR: &str = "SEIVA_OIDC_PERMISSION_CLAIM";
#[derive(Debug, Clone)]
pub struct ServerConfig {
pub env: AppEnv,
pub http_addr: SocketAddr,
pub expose_error_details: bool,
pub security: HttpSecurity,
pub oidc: Option<OidcConfig>,
}
#[derive(Debug, Clone)]
pub struct OidcConfig {
pub jwks_file: String,
pub issuer: String,
pub audience: String,
pub tenant_claim: Option<String>,
pub permission_claim: Option<String>,
}
fn resolve_oidc(reader: &mut EnvReader) -> Option<Option<OidcConfig>> {
let present = reader.optional_var(OIDC_JWKS_FILE_VAR).is_some()
|| reader.optional_var(OIDC_ISSUER_VAR).is_some()
|| reader.optional_var(OIDC_AUDIENCE_VAR).is_some();
if !present {
return Some(None);
}
let jwks_file = reader.require_var(OIDC_JWKS_FILE_VAR);
let issuer = reader.require_var(OIDC_ISSUER_VAR);
let audience = reader.require_var(OIDC_AUDIENCE_VAR);
let tenant_claim = reader.optional_var(OIDC_TENANT_CLAIM_VAR);
let permission_claim = reader.optional_var(OIDC_PERMISSION_CLAIM_VAR);
Some(Some(OidcConfig {
jwks_file: jwks_file?,
issuer: issuer?,
audience: audience?,
tenant_claim,
permission_claim,
}))
}
impl ServerConfig {
pub fn from_process_env() -> Result<Self, ConfigError> {
seiva_config::load::<Self>()
}
#[must_use]
pub fn default_http_addr() -> SocketAddr {
SocketAddr::from((Ipv4Addr::LOCALHOST, 8080))
}
}
fn resolve_http_addr(reader: &mut EnvReader) -> Option<SocketAddr> {
if reader.optional_var(HTTP_ADDR_VAR).is_some() {
reader.optional_parsed::<SocketAddr>(HTTP_ADDR_VAR, ServerConfig::default_http_addr())
} else if reader.optional_var(PORT_VAR).is_some() {
let port = reader.optional_parsed::<u16>(PORT_VAR, 0)?;
Some(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)))
} else {
Some(ServerConfig::default_http_addr())
}
}
fn resolve_security(reader: &mut EnvReader) -> Option<HttpSecurity> {
let cors_allowed_origins = reader
.optional_var(CORS_ALLOWED_ORIGINS_VAR)
.map(|raw| {
raw.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from)
.collect()
})
.unwrap_or_default();
let trust_forwarded_for = reader.optional_bool(TRUST_FORWARDED_FOR_VAR, false)?;
let expose_docs = reader.optional_bool(EXPOSE_DOCS_VAR, true)?;
let max_requests = reader
.optional_parsed::<u32>(RATE_LIMIT_MAX_REQUESTS_VAR, RateLimit::DEFAULT_MAX_REQUESTS)?;
let window_secs = reader.optional_parsed::<u64>(
RATE_LIMIT_WINDOW_SECS_VAR,
RateLimit::DEFAULT_WINDOW.as_secs(),
)?;
let rate_limit = (max_requests > 0).then(|| RateLimit {
max_requests,
window: Duration::from_secs(window_secs.max(1)),
});
Some(HttpSecurity {
cors_allowed_origins,
rate_limit,
trust_forwarded_for,
expose_docs,
})
}
impl FromEnv for ServerConfig {
fn from_env(reader: &mut EnvReader) -> Option<Self> {
let env = reader.app_env();
let http_addr = resolve_http_addr(reader);
let expose_error_details = reader.optional_bool(EXPOSE_ERROR_DETAILS_VAR, false);
let security = resolve_security(reader);
let oidc = resolve_oidc(reader);
let config = Self {
env,
http_addr: http_addr?,
expose_error_details: expose_error_details?,
security: security?,
oidc: oidc?,
};
reader.guard(
config
.env
.reject_dev_shortcut(EXPOSE_ERROR_DETAILS_VAR, config.expose_error_details),
);
Some(config)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum ServeError {
Bind(std::io::Error),
Serve(std::io::Error),
Identity(String),
RouteCollision(Vec<String>),
Observability(String),
#[cfg(feature = "mtls")]
Tls(String),
}
impl fmt::Display for ServeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServeError::Bind(e) => write!(f, "failed to bind the HTTP listener: {e}"),
ServeError::Serve(e) => write!(f, "the HTTP server failed: {e}"),
ServeError::Identity(m) => write!(f, "failed to build the OIDC authenticator: {m}"),
ServeError::RouteCollision(prefixes) => write!(
f,
"two or more facades mount on the same route prefix ({}); \
rename a facade so each resolves to a distinct `<version>/<resource>`",
prefixes.join(", ")
),
ServeError::Observability(m) => {
write!(f, "failed to install an observability exporter: {m}")
}
#[cfg(feature = "mtls")]
ServeError::Tls(m) => write!(f, "failed to load the mutual-TLS configuration: {m}"),
}
}
}
impl std::error::Error for ServeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ServeError::Bind(e) | ServeError::Serve(e) => Some(e),
ServeError::Identity(_)
| ServeError::RouteCollision(_)
| ServeError::Observability(_) => None,
#[cfg(feature = "mtls")]
ServeError::Tls(_) => None,
}
}
}
fn build_authenticator(
config: &ServerConfig,
) -> Result<Option<Arc<dyn Authenticator>>, ServeError> {
let Some(oidc) = &config.oidc else {
return Ok(None);
};
let jwks_json = std::fs::read_to_string(&oidc.jwks_file)
.map_err(|e| ServeError::Identity(format!("reading JWKS file {}: {e}", oidc.jwks_file)))?;
let mut auth = JwtAuthenticator::from_jwks_json(&jwks_json, &oidc.issuer, &oidc.audience)
.map_err(|e| ServeError::Identity(format!("parsing JWKS {}: {e}", oidc.jwks_file)))?;
if let Some(claim) = &oidc.tenant_claim {
auth = auth.with_tenant_claim(claim);
}
if let Some(claim) = &oidc.permission_claim {
auth = auth.with_permission_claim(claim);
}
Ok(Some(Arc::new(auth)))
}
pub async fn serve(
config: ServerConfig,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), ServeError> {
seiva_http::problem::set_expose_error_details(config.expose_error_details);
let health = Health::starting();
let authenticator = build_authenticator(&config)?;
let app = router_with_auth(health.clone(), &config.security, authenticator);
serve_router(config.http_addr, app, health, shutdown).await
}
pub async fn serve_router(
addr: SocketAddr,
router: Router,
health: Health,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), ServeError> {
let collisions = seiva_http::route_collisions();
if !collisions.is_empty() {
return Err(ServeError::RouteCollision(collisions));
}
let listener = TcpListener::bind(addr).await.map_err(ServeError::Bind)?;
health.set_ready();
let draining = {
let health = health.clone();
async move {
shutdown.await;
health.set_draining();
}
};
axum::serve(
listener,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(draining)
.await
.map_err(ServeError::Serve)?;
Ok(())
}
#[cfg(feature = "mtls")]
pub mod mtls;
#[cfg(feature = "mtls")]
pub use mtls::{serve_router_mtls, MtlsFiles};
#[derive(Debug)]
pub struct Server {
config: ServerConfig,
#[cfg(feature = "metrics")]
metrics_addr: Option<SocketAddr>,
#[cfg(feature = "tracing-otlp")]
tracing: Option<seiva_observability::tracing::TracingConfig>,
}
impl Server {
#[must_use]
pub fn new(config: ServerConfig) -> Self {
Self {
config,
#[cfg(feature = "metrics")]
metrics_addr: None,
#[cfg(feature = "tracing-otlp")]
tracing: None,
}
}
#[cfg(feature = "metrics")]
#[must_use]
pub fn with_metrics(mut self, addr: SocketAddr) -> Self {
self.metrics_addr = Some(addr);
self
}
#[cfg(feature = "tracing-otlp")]
#[must_use]
pub fn with_tracing(mut self, config: seiva_observability::tracing::TracingConfig) -> Self {
self.tracing = Some(config);
self
}
pub async fn serve(
self,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> Result<(), ServeError> {
let (tx, rx) = tokio::sync::watch::channel(false);
tokio::spawn(async move {
shutdown.await;
let _ = tx.send(true);
});
#[cfg(feature = "tracing-otlp")]
let tracing_provider = match self.tracing {
Some(config) => Some(
seiva_observability::tracing::init(config)
.map_err(|e| ServeError::Observability(e.to_string()))?,
),
None => None,
};
#[cfg(feature = "metrics")]
if let Some(metrics_addr) = self.metrics_addr {
let handle = seiva_observability::metrics::install_recorder().map_err(|e| {
ServeError::Observability(format!("installing the Prometheus recorder: {e}"))
})?;
let mut metrics_rx = rx.clone();
let metrics_shutdown = async move {
let _ = metrics_rx.wait_for(|stop| *stop).await;
};
tokio::spawn(async move {
if let Err(error) = seiva_observability::metrics::serve_metrics(
metrics_addr,
handle,
metrics_shutdown,
)
.await
{
tracing::error!(%error, "the Prometheus /metrics exporter failed");
}
});
tracing::info!(addr = %metrics_addr, "serving Prometheus /metrics on a separate bind");
}
let mut main_rx = rx;
let main_shutdown = async move {
let _ = main_rx.wait_for(|stop| *stop).await;
};
let result = serve(self.config, main_shutdown).await;
#[cfg(feature = "tracing-otlp")]
if let Some(provider) = tracing_provider {
let _ = provider.shutdown();
}
result
}
}
pub async fn shutdown_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{signal, SignalKind};
let mut term = signal(SignalKind::terminate()).expect("install a SIGTERM handler");
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}
pub const DEFAULT_WORKER_INTERVAL: Duration = Duration::from_secs(30);
pub async fn demo_pass() -> PortResult<u64> {
Ok(0)
}
pub async fn run_workers(shutdown: impl Future<Output = ()> + Send) -> Vec<WorkerReport> {
let config = WorkerConfig::new("demo-noop", DEFAULT_WORKER_INTERVAL);
let report = run_worker(config, shutdown, demo_pass).await;
vec![report]
}
pub async fn run_idempotency_purge<U, St, Sh>(
uow: std::sync::Arc<U>,
store: std::sync::Arc<St>,
config: WorkerConfig,
shutdown: Sh,
) -> WorkerReport
where
U: seiva::ports::UnitOfWork + 'static,
St: seiva::ports::IdempotencyStore + 'static,
Sh: Future<Output = ()>,
{
run_worker(config, shutdown, move || {
let uow = std::sync::Arc::clone(&uow);
let store = std::sync::Arc::clone(&store);
async move {
uow.transaction(seiva::ports::Scope::Global, move || async move {
store.purge_expired().await
})
.await
}
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use seiva_config::load_from;
use std::collections::HashMap;
use tower::ServiceExt;
fn application(health: Health) -> Router {
let accounts =
accounts_interface::accounts_router(accounts_interface::AccountsController::new(
accounts_infrastructure::InMemoryCredentialRepository::new(),
));
seiva_http::router(health).merge(accounts)
}
fn map(pairs: &[(&str, &str)]) -> HashMap<String, String> {
pairs
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect()
}
#[test]
fn config_defaults_to_loopback_8080_and_development() {
let cfg: ServerConfig = load_from(map(&[])).expect("empty env is a valid dev config");
assert_eq!(cfg.http_addr, ServerConfig::default_http_addr());
assert_eq!(cfg.http_addr.to_string(), "127.0.0.1:8080");
assert!(cfg.env.is_development());
assert!(!cfg.expose_error_details);
}
#[test]
fn config_http_addr_var_wins_over_port() {
let cfg: ServerConfig =
load_from(map(&[(HTTP_ADDR_VAR, "0.0.0.0:9000"), (PORT_VAR, "1234")]))
.expect("valid address");
assert_eq!(cfg.http_addr.to_string(), "0.0.0.0:9000");
}
#[test]
fn config_port_fallback_binds_all_interfaces() {
let cfg: ServerConfig = load_from(map(&[(PORT_VAR, "8081")])).expect("valid port fallback");
assert_eq!(cfg.http_addr.to_string(), "0.0.0.0:8081");
}
#[test]
fn config_rejects_unparseable_address() {
let err = load_from::<ServerConfig>(map(&[(HTTP_ADDR_VAR, "not-an-addr")])).unwrap_err();
assert!(err.problems()[0].contains(HTTP_ADDR_VAR));
}
#[test]
fn config_production_guard_rejects_expose_error_details() {
let err = load_from::<ServerConfig>(map(&[
("APP_ENV", "production"),
(EXPOSE_ERROR_DETAILS_VAR, "true"),
]))
.unwrap_err();
assert_eq!(err.problems().len(), 1);
assert!(err.problems()[0].contains(EXPOSE_ERROR_DETAILS_VAR));
assert!(err.problems()[0].contains("production"));
}
#[test]
fn config_development_allows_the_same_shortcut() {
let cfg: ServerConfig = load_from(map(&[
("APP_ENV", "development"),
(EXPOSE_ERROR_DETAILS_VAR, "true"),
]))
.expect("dev permits the shortcut");
assert!(cfg.expose_error_details);
assert!(cfg.env.is_development());
}
#[test]
fn security_defaults_to_the_secure_baseline() {
let cfg: ServerConfig = load_from(map(&[])).expect("empty env is valid");
assert!(cfg.security.cors_allowed_origins.is_empty());
assert!(!cfg.security.trust_forwarded_for);
assert_eq!(cfg.security.rate_limit, Some(RateLimit::default()));
}
#[test]
fn security_reads_cors_trust_proxy_and_rate_limit_from_env() {
let cfg: ServerConfig = load_from(map(&[
(
CORS_ALLOWED_ORIGINS_VAR,
" https://app.example.com , https://admin.example.com ,",
),
(TRUST_FORWARDED_FOR_VAR, "true"),
(RATE_LIMIT_MAX_REQUESTS_VAR, "100"),
(RATE_LIMIT_WINDOW_SECS_VAR, "30"),
]))
.expect("valid security config");
assert_eq!(
cfg.security.cors_allowed_origins,
vec![
"https://app.example.com".to_string(),
"https://admin.example.com".to_string()
]
);
assert!(cfg.security.trust_forwarded_for);
assert_eq!(
cfg.security.rate_limit,
Some(RateLimit {
max_requests: 100,
window: Duration::from_secs(30)
})
);
}
#[test]
fn oidc_is_absent_by_default_and_parsed_when_fully_set() {
let none: ServerConfig = load_from(map(&[])).expect("empty env");
assert!(none.oidc.is_none());
let cfg: ServerConfig = load_from(map(&[
(OIDC_JWKS_FILE_VAR, "/etc/seiva/jwks.json"),
(OIDC_ISSUER_VAR, "https://id.example.com/"),
(OIDC_AUDIENCE_VAR, "seiva-api"),
(OIDC_TENANT_CLAIM_VAR, "org_id"),
]))
.expect("full oidc config");
let oidc = cfg.oidc.expect("present");
assert_eq!(oidc.jwks_file, "/etc/seiva/jwks.json");
assert_eq!(oidc.issuer, "https://id.example.com/");
assert_eq!(oidc.audience, "seiva-api");
assert_eq!(oidc.tenant_claim.as_deref(), Some("org_id"));
assert!(oidc.permission_claim.is_none());
}
#[test]
fn a_partial_oidc_config_fails_the_boot() {
let err = load_from::<ServerConfig>(map(&[(OIDC_ISSUER_VAR, "https://id.example.com/")]))
.unwrap_err();
let problems = err.problems().join(" ");
assert!(problems.contains(OIDC_JWKS_FILE_VAR));
assert!(problems.contains(OIDC_AUDIENCE_VAR));
}
#[test]
fn rate_limit_is_disabled_by_a_zero_budget() {
let cfg: ServerConfig =
load_from(map(&[(RATE_LIMIT_MAX_REQUESTS_VAR, "0")])).expect("zero disables");
assert_eq!(cfg.security.rate_limit, None);
}
#[test]
fn config_rejects_unparseable_rate_limit() {
let err =
load_from::<ServerConfig>(map(&[(RATE_LIMIT_MAX_REQUESTS_VAR, "lots")])).unwrap_err();
assert!(err.problems()[0].contains(RATE_LIMIT_MAX_REQUESTS_VAR));
}
#[tokio::test]
async fn health_live_is_ok_and_ready_tracks_the_lifecycle() {
let health = Health::starting();
let app = seiva_http::router(health.clone());
let res = app
.clone()
.oneshot(
Request::builder()
.uri("/health/live")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let res = app
.clone()
.oneshot(
Request::builder()
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
health.set_ready();
let res = app
.oneshot(
Request::builder()
.uri("/health/ready")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn merged_app_serves_the_accounts_create_route() {
let app = application(Health::starting());
let denied = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/accounts/create_user")
.header("content-type", "application/json")
.body(Body::from(r#"{"username":"alice","password":"hunter2"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(denied.status(), StatusCode::FORBIDDEN);
let ok = app
.oneshot(
Request::builder()
.method("POST")
.uri("/v1/accounts/create_user")
.header("content-type", "application/json")
.extension(std::sync::Arc::new(seiva_http::Principal::in_tenant(
"user",
"acme",
["accounts.create"],
)))
.body(Body::from(r#"{"username":"alice","password":"hunter2"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(ok.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(ok.into_body(), usize::MAX)
.await
.unwrap();
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["username"], "alice");
let rendered = body.to_string();
assert!(
!rendered.contains("hunter2") && !rendered.contains("$argon2id$"),
"no secret must appear in the response: {rendered}"
);
}
#[tokio::test]
async fn openapi_discovers_the_mounted_facade() {
let app = application(Health::starting());
let res = app
.oneshot(
Request::builder()
.uri("/openapi.json")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(res.status(), StatusCode::OK);
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
.await
.unwrap();
let doc: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let paths = doc["paths"].as_object().expect("paths object");
assert!(
paths.keys().any(|p| p.contains("/accounts")),
"the mounted accounts module must be discovered and documented: {:?}",
paths.keys().collect::<Vec<_>>()
);
}
#[tokio::test]
async fn serve_binds_ephemeral_and_returns_on_resolved_shutdown() {
let config = ServerConfig {
env: AppEnv::Development,
http_addr: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
expose_error_details: false,
security: HttpSecurity::default(),
oidc: None,
};
serve(config, async {})
.await
.expect("serve binds and drains cleanly");
}
#[tokio::test]
async fn run_workers_stops_and_reports_the_demo_pass() {
let reports = run_workers(async {}).await;
assert_eq!(reports.len(), 1);
let report = &reports[0];
assert!(report.passes >= 1, "at least one pass runs before shutdown");
assert_eq!(report.processed, 0, "the demo pass processes nothing");
assert_eq!(report.errors, 0, "the demo pass never fails");
}
#[tokio::test]
async fn idempotency_purge_worker_runs_passes_and_never_fails() {
use seiva_testing::{InMemoryIdempotencyStore, InMemoryUnitOfWork};
use std::sync::Arc;
let uow = Arc::new(InMemoryUnitOfWork::new());
let store = Arc::new(InMemoryIdempotencyStore::new());
let config = WorkerConfig::new("idempotency-purge", std::time::Duration::ZERO);
let report = run_idempotency_purge(uow, store, config, async {}).await;
assert!(report.passes >= 1, "the purge worker ran at least one pass");
assert_eq!(report.errors, 0, "purge must not fail");
}
}