#![forbid(unsafe_code)]
pub mod audit;
pub mod authn;
pub mod backpressure;
pub mod bus;
pub mod ctx;
pub mod docs;
pub mod guard;
pub mod health;
pub mod idempotency;
pub mod metrics;
#[cfg(feature = "mtls")]
pub mod mtls;
pub mod problem;
pub mod rate_limit;
pub mod request_id;
pub mod security;
pub mod valid;
use axum::body::Bytes;
use axum::extract::DefaultBodyLimit;
use axum::http::{header, HeaderMap, StatusCode};
use axum::middleware::{from_fn, from_fn_with_state};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::Router;
use sha2::{Digest, Sha256};
pub use audit::audit;
pub use authn::{authn, AuthConfig, Authn};
pub use backpressure::{with_route_controls, RouteControls, RouteLimit};
pub use bus::{Authorize, Idempotent, DEFAULT_IDEMPOTENCY_TTL};
pub use ctx::Ctx;
pub use docs::{docs_handler, redoc_handler, scalar_handler, DOCS_HTML};
pub use guard::{permission_guard, require_permission, PrincipalExt, RequiredPermission, Scoped};
pub use health::{
health_router, health_router_with_dependency, Health, HealthState, ReadinessCheck,
};
pub use idempotency::{
fingerprint, in_progress_problem, mismatch_problem, scoped_key, IdempotencyKey,
OptionalIdempotencyKey, IDEMPOTENCY_HEADER, MAX_KEY_LEN,
};
pub use metrics::{track_metrics, REQUESTS_IN_FLIGHT, REQUESTS_TOTAL, REQUEST_DURATION_SECONDS};
pub use problem::{Problem, ProblemResponse, PROBLEM_JSON};
pub use rate_limit::{
rate_limit, rate_limit_with_store, DistributedRateLimit, RateLimit, RateLimiter,
};
pub use request_id::{request_id, RequestId, REQUEST_ID_HEADER};
pub use security::{cors_layer, security_headers, HttpSecurity};
pub use seiva_ports::{AuditEntry, AuditSink};
pub use seiva_ports::{RateLimitDecision, RateLimitStore};
pub use valid::{Valid, Validate, ValidationError};
pub use seiva_identity::{
ApiKeyAuthenticator, AuthError, Authenticator, JwtAuthenticator, Principal, TokenAuthenticator,
};
pub const DEFAULT_BODY_LIMIT_BYTES: usize = 1024 * 1024;
pub const DEFAULT_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub fn openapi_document() -> serde_json::Value {
let facades = seiva::contract::registered_facades();
seiva_openapi::openapi_document(
seiva_openapi::ApiInfo {
title: "Delonix Seiva service".to_string(),
version: seiva::VERSION.to_string(),
},
&facades,
)
}
async fn openapi_handler(headers: HeaderMap) -> Response {
let cached = cached_openapi();
if let Some(inm) = headers.get(header::IF_NONE_MATCH) {
if inm.as_bytes() == cached.etag.as_bytes() {
return StatusCode::NOT_MODIFIED.into_response();
}
}
(
[
(header::CONTENT_TYPE, "application/json"),
(header::ETAG, cached.etag.as_str()),
(header::CACHE_CONTROL, "public, max-age=300"),
],
cached.body.clone(),
)
.into_response()
}
struct CachedOpenApi {
body: Bytes,
etag: String,
}
fn cached_openapi() -> &'static CachedOpenApi {
static CACHE: std::sync::OnceLock<CachedOpenApi> = std::sync::OnceLock::new();
CACHE.get_or_init(|| {
let body = serde_json::to_vec(&openapi_document())
.expect("the generated OpenAPI document always serializes");
let etag = format!("\"{}\"", idempotency::hex(Sha256::digest(&body).as_slice()));
CachedOpenApi {
body: Bytes::from(body),
etag,
}
})
}
#[must_use]
pub fn route_collisions() -> Vec<String> {
seiva::contract::route_collisions(&seiva::contract::registered_facades())
}
pub fn router(health: Health) -> Router {
router_with_security(health, &HttpSecurity::default())
}
pub fn router_with_security(health: Health, security: &HttpSecurity) -> Router {
router_with_auth(health, security, AuthConfig::none())
}
pub fn router_with_auth(
health: Health,
security: &HttpSecurity,
auth: impl Into<AuthConfig>,
) -> Router {
apply_framework_layers(
framework_routes(health, security.expose_docs),
security,
auth.into(),
None,
)
}
pub fn router_with_modules(
health: Health,
security: &HttpSecurity,
auth: impl Into<AuthConfig>,
modules: Router,
) -> Router {
apply_framework_layers(
framework_routes(health, security.expose_docs).merge(modules),
security,
auth.into(),
None,
)
}
pub fn router_with_modules_distributed(
health: Health,
security: &HttpSecurity,
auth: impl Into<AuthConfig>,
modules: Router,
distributed: DistributedRateLimit,
) -> Router {
apply_framework_layers(
framework_routes(health, security.expose_docs).merge(modules),
security,
auth.into(),
Some(distributed),
)
}
fn framework_routes(health: Health, expose_docs: bool) -> Router {
let mut router = Router::new().merge(health_router(health));
if expose_docs {
router = router
.route("/openapi.json", get(openapi_handler))
.route("/docs", get(docs::docs_handler))
.route("/redoc", get(docs::redoc_handler))
.route("/scalar", get(docs::scalar_handler));
}
router
}
fn apply_framework_layers(
app: Router,
security: &HttpSecurity,
auth: AuthConfig,
distributed: Option<DistributedRateLimit>,
) -> Router {
let mut app = app
.layer(DefaultBodyLimit::max(DEFAULT_BODY_LIMIT_BYTES))
.layer(tower_http::timeout::TimeoutLayer::with_status_code(
axum::http::StatusCode::REQUEST_TIMEOUT,
DEFAULT_REQUEST_TIMEOUT,
));
if let Some(cors) = cors_layer(security) {
app = app.layer(cors);
}
if let Some(dist) = distributed {
app = app.layer(from_fn_with_state(dist, rate_limit_with_store));
} else if let Some(limit) = security.rate_limit {
let limiter = RateLimiter::new(limit).trusting_forwarded_for(security.trust_forwarded_for);
app = app.layer(from_fn_with_state(limiter, rate_limit));
}
if let Some(authn_state) = auth.into_authn() {
app = app.layer(from_fn_with_state(authn_state, authn));
}
app = app
.layer(from_fn(security_headers))
.layer(from_fn(request_id));
app.layer(from_fn(metrics::track_metrics))
}