use super::auth::{normalize_path, PathPattern};
use super::{best_rule, rule_specificity, RuleKey};
use crate::router::RouteEntry;
use axum::body::Body;
use axum::extract::Request;
use axum::http::header;
use axum::response::Response;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll};
use std::time::Instant;
use tower::{Layer, Service};
use crate::audit::{AuditRecord, AuditResult};
#[derive(Debug, Clone)]
pub struct AuditRule {
pub path: String,
pub methods: Vec<String>,
pub action: String,
pub is_guard: bool,
}
pub(crate) struct CompiledRule {
pattern: PathPattern,
methods: Vec<String>,
action: String,
specificity: (usize, usize),
is_guard: bool,
}
impl CompiledRule {
fn compile(rule: &AuditRule) -> Self {
Self {
pattern: PathPattern::compile(&rule.path),
methods: rule.methods.clone(),
action: rule.action.clone(),
specificity: rule_specificity(&rule.path),
is_guard: rule.is_guard,
}
}
}
impl RuleKey for CompiledRule {
fn pattern(&self) -> &PathPattern {
&self.pattern
}
fn methods(&self) -> &[String] {
&self.methods
}
fn is_guard(&self) -> bool {
self.is_guard
}
fn specificity(&self) -> (usize, usize) {
self.specificity
}
}
#[derive(Clone)]
pub struct AuditLayer {
pub rules: Arc<Vec<AuditRule>>,
pub writer: Option<Arc<crate::audit::AuditWriter>>,
pub(crate) compiled: Arc<OnceLock<Arc<Vec<CompiledRule>>>>,
}
impl AuditLayer {
pub fn empty() -> Self {
Self {
rules: Arc::new(Vec::new()),
writer: None,
compiled: Arc::new(OnceLock::new()),
}
}
pub fn with_writer(mut self, writer: Arc<crate::audit::AuditWriter>) -> Self {
self.writer = Some(writer);
self
}
pub fn from_config_with_prefix(routes: &[wordval_config::AuditRoute], prefix: &str) -> Self {
Self::empty().with_config_routes(routes, prefix)
}
pub fn with_config_routes(mut self, routes: &[wordval_config::AuditRoute], prefix: &str) -> Self {
let rules = Arc::make_mut(&mut self.rules);
rules.reserve(routes.len());
for r in routes {
rules.push(AuditRule {
path: super::auth::join_route_path(prefix, &r.path),
methods: if r.method.is_empty() {
Vec::new()
} else {
vec![r.method.clone()]
},
action: r.action.clone(),
is_guard: false,
});
}
self
}
pub fn with_route_guards(mut self, routes: &[RouteEntry], prefix: &str) -> Self {
let rules = Arc::make_mut(&mut self.rules);
rules.reserve(routes.len());
for r in routes {
let Some(action) = r.guard.audit.as_deref() else {
continue;
};
rules.push(AuditRule {
path: super::auth::join_route_path(prefix, &r.path),
methods: vec![r.method.clone()],
action: action.to_string(),
is_guard: true,
});
}
self
}
pub fn has_rules(&self) -> bool {
!self.rules.is_empty()
}
}
impl<S> Layer<S> for AuditLayer {
type Service = AuditService<S>;
fn layer(&self, inner: S) -> Self::Service {
let rules = self
.compiled
.get_or_init(|| Arc::new(self.rules.iter().map(CompiledRule::compile).collect()))
.clone();
AuditService {
inner,
rules,
writer: self.writer.clone(),
}
}
}
#[derive(Clone)]
pub struct AuditService<S> {
inner: S,
rules: Arc<Vec<CompiledRule>>,
writer: Option<Arc<crate::audit::AuditWriter>>,
}
impl<S> Service<Request<Body>> for AuditService<S>
where
S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let normalized = normalize_path(req.uri().path());
let action = match best_rule(&self.rules, &normalized, req.method().as_str()) {
Some(r) => r.action.clone(),
None => {
let replacement = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, replacement);
return Box::pin(async move { inner.call(req).await });
}
};
let method = req.method().as_str().to_string();
let ctx = CapturedContext::from_request(&req);
let writer = self.writer.clone();
let resource = normalized.into_owned();
let replacement = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, replacement);
Box::pin(async move {
let resp = inner.call(req).await;
let (status, ok) = match &resp {
Ok(r) => (Some(r.status().as_u16()), true),
Err(_) => (None, false),
};
let code = status.unwrap_or(500);
let result = if ok {
AuditResult::from_status(code)
} else {
AuditResult::Error
};
let record = ctx.into_record(action, resource, method, code, result);
match &writer {
Some(w) => w.write(record),
None => crate::resources::audit_write(record),
}
resp
})
}
}
struct CapturedContext {
request_id: Option<String>,
user_agent: Option<String>,
ip: Option<String>,
user_id: String,
tenant: Option<String>,
started: Option<Instant>,
}
impl CapturedContext {
fn from_request(req: &Request<Body>) -> Self {
let ext = req.extensions();
Self {
request_id: ext.get::<super::request_id::RequestId>().map(|r| r.0.clone()),
user_agent: req
.headers()
.get(header::USER_AGENT)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string()),
ip: ext.get::<super::client_identity::ClientIp>().map(|c| c.0.clone()),
user_id: ext
.get::<super::CurrentUser>()
.map(|u| u.id.to_string())
.unwrap_or_default(),
tenant: crate::tenant::current_tenant_id().map(|t| t.to_string()),
started: ext.get::<super::client_identity::RequestStart>().map(|s| s.0),
}
}
fn into_record(
self,
action: String,
resource: String,
method: String,
status: u16,
result: AuditResult,
) -> AuditRecord {
let mut rec = AuditRecord::new(action, resource, result)
.with_user(self.user_id)
.with_method(method)
.with_tenant(self.tenant)
.with_request_id(self.request_id)
.with_user_agent(self.user_agent)
.with_ip(self.ip)
.with_status(status);
if let Some(started) = self.started {
rec = rec.with_elapsed_ms(started.elapsed().as_millis() as u64);
}
rec
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::router::{RouteEntry, RouteGuard};
use wordval_config::AuditRoute;
fn compiled(layer: &AuditLayer) -> Vec<CompiledRule> {
layer.rules.iter().map(CompiledRule::compile).collect()
}
fn route(path: &str, method: &str, action: &str) -> AuditRoute {
AuditRoute {
method: method.to_string(),
path: path.to_string(),
action: action.to_string(),
}
}
fn guard_route(method: &str, path: &str, action: &str) -> RouteEntry {
RouteEntry {
method: method.to_string(),
path: path.to_string(),
guard: RouteGuard::auditing(action),
}
}
#[test]
fn config_and_guard_rules_match_with_guard_priority() {
let layer = AuditLayer::from_config_with_prefix(&[route("/orders", "", "cfg.order")], "")
.with_route_guards(&[guard_route("DELETE", "/orders", "order.delete")], "");
let rules = compiled(&layer);
let hit = best_rule(&rules, "/orders", "DELETE").unwrap();
assert_eq!(hit.action, "order.delete");
let hit = best_rule(&rules, "/orders", "GET").unwrap();
assert_eq!(hit.action, "cfg.order");
}
#[test]
fn head_uses_explicit_rule_before_get_fallback() {
let layer = AuditLayer::empty().with_route_guards(
&[
guard_route("GET", "/orders", "order.list"),
guard_route("HEAD", "/orders", "order.head"),
guard_route("GET", "/goods", "goods.list"),
],
"",
);
let rules = compiled(&layer);
assert_eq!(
best_rule(&rules, "/orders", "HEAD").unwrap().action,
"order.head"
);
assert_eq!(
best_rule(&rules, "/goods", "HEAD").unwrap().action,
"goods.list"
);
}
#[test]
fn guard_rule_joined_with_global_prefix() {
let layer = AuditLayer::empty()
.with_route_guards(&[guard_route("POST", "/orders", "order.create")], "/api");
let rules = compiled(&layer);
assert!(best_rule(&rules, "/api/orders", "POST").is_some());
assert!(best_rule(&rules, "/orders", "POST").is_none());
}
#[test]
fn routes_without_audit_contribute_no_rules() {
let plain = RouteEntry {
method: "POST".to_string(),
path: "/orders".to_string(),
guard: RouteGuard::default(),
};
let layer = AuditLayer::empty().with_route_guards(&[plain], "");
assert!(!layer.has_rules());
}
#[test]
fn most_specific_pattern_wins() {
let layer = AuditLayer::from_config_with_prefix(
&[route("/admin", "", "admin:any"), route("/admin/{id}", "", "admin:detail")],
"",
);
let rules = compiled(&layer);
assert_eq!(best_rule(&rules, "/admin/7", "GET").unwrap().action, "admin:detail");
}
#[test]
fn global_prefix_joined_into_rule_path() {
let layer =
AuditLayer::from_config_with_prefix(&[route("/orders", "POST", "order.create")], "/api");
let rules = compiled(&layer);
assert!(best_rule(&rules, "/api/orders", "POST").is_some());
assert!(best_rule(&rules, "/orders", "POST").is_none());
}
#[test]
fn unmatched_method_produces_no_rule_hit() {
let layer =
AuditLayer::from_config_with_prefix(&[route("/orders", "POST", "order.create")], "");
let rules = compiled(&layer);
assert!(best_rule(&rules, "/orders", "GET").is_none());
assert!(best_rule(&rules, "/orders", "post").is_some());
}
}