use super::{DefaultGarrisonInterceptor, GarrisonInterceptor};
use crate::annotation::Annotation;
use crate::config::GarrisonConfig;
use crate::context::axum_adapter::AxumRequest;
#[cfg(feature = "tenant-isolation")]
use crate::context::tenant::TenantResolver;
use crate::context::GarrisonRequest;
use crate::context::{build_set_cookie_value, CookieType};
use crate::error::GarrisonError;
use crate::stp::context::{clear_renewed_token, get_renewed_token, with_renewed_token_scope};
use crate::stp::{with_current_token, with_login_id_scope};
use axum::body::Body;
use axum::extract::State;
use axum::handler::Handler;
use axum::http::header::SET_COOKIE;
#[cfg(feature = "tenant-isolation")]
use axum::http::StatusCode;
use axum::http::{HeaderName, HeaderValue, Request};
use axum::middleware::{from_fn_with_state, Next};
use axum::response::{IntoResponse, Response};
use axum::Router;
use std::sync::Arc;
#[derive(Clone)]
struct RouteRule {
path: String,
annotation: Annotation,
}
#[derive(Clone)]
struct MiddlewareState {
rules: Arc<Vec<RouteRule>>,
interceptor: Arc<dyn GarrisonInterceptor>,
config: Arc<GarrisonConfig>,
}
pub struct GarrisonRouter {
inner: Router,
rules: Vec<RouteRule>,
interceptor: Arc<dyn GarrisonInterceptor>,
config: Arc<GarrisonConfig>,
}
impl GarrisonRouter {
pub fn new(config: Arc<GarrisonConfig>) -> Self {
Self {
inner: Router::new(),
rules: Vec::new(),
interceptor: Arc::new(DefaultGarrisonInterceptor),
config,
}
}
pub fn with_interceptor<I: GarrisonInterceptor + 'static>(mut self, interceptor: I) -> Self {
self.interceptor = Arc::new(interceptor);
self
}
pub fn route_protected<H, T>(mut self, path: &str, handler: H, annotation: Annotation) -> Self
where
H: Handler<T, ()> + Clone + Send + Sync + 'static,
T: 'static,
{
self.inner = self.inner.route(path, axum::routing::get(handler));
self.rules.push(RouteRule {
path: path.to_string(),
annotation,
});
self
}
pub fn group<F>(self, prefix: &str, annotation: Annotation, f: F) -> Self
where
F: FnOnce(GarrisonRouter) -> GarrisonRouter,
{
assert!(!prefix.is_empty(), "prefix must not be empty");
let trimmed = prefix.trim_end_matches('/');
let child = GarrisonRouter {
inner: Router::new(),
rules: Vec::new(),
interceptor: self.interceptor.clone(),
config: self.config.clone(),
};
let child = f(child);
let mut parent = self;
for rule in child.rules {
let merged_path = format!("{}{}", trimmed, rule.path);
let merged_annotation = if annotation == Annotation::Ignore {
Annotation::Ignore
} else {
rule.annotation
};
parent.rules.push(RouteRule {
path: merged_path,
annotation: merged_annotation,
});
}
if trimmed.is_empty() {
parent.inner = parent.inner.merge(child.inner);
} else {
parent.inner = parent.inner.nest(trimmed, child.inner);
}
parent
}
pub fn build(self) -> Router {
let state = MiddlewareState {
rules: Arc::new(self.rules),
interceptor: self.interceptor,
config: self.config,
};
self.inner
.layer(from_fn_with_state(state, garrison_middleware))
}
}
fn route_matches(pattern: &str, path: &str) -> bool {
let mut pi = pattern.split('/');
let mut ri = path.split('/');
loop {
match (pi.next(), ri.next()) {
(None, None) => return true,
(Some(seg), None) => return is_wildcard_segment(seg),
(Some(seg), Some(part)) => {
if is_wildcard_segment(seg) {
return true;
}
if is_param_segment(seg) {
if part.is_empty() {
return false;
}
} else if seg != part {
return false;
}
},
(None, Some(_)) => return false,
}
}
}
fn is_param_segment(seg: &str) -> bool {
seg.starts_with(':') || (seg.starts_with('{') && seg.ends_with('}') && seg.len() > 2)
}
fn is_wildcard_segment(seg: &str) -> bool {
seg.len() > 3 && seg.starts_with("{*") && seg.ends_with('}')
}
impl Default for GarrisonRouter {
fn default() -> Self {
Self::new(Arc::new(GarrisonConfig::default_config()))
}
}
async fn garrison_middleware(
State(state): State<MiddlewareState>,
req: Request<Body>,
next: Next,
) -> Response {
let path = req.uri().path().to_string();
let rule = state
.rules
.iter()
.find(|r| route_matches(&r.path, &path))
.cloned();
let token = AxumRequest::new(&req)
.get_token(&state.config)
.ok()
.flatten();
let handle = async {
if let Some(rule) = &rule {
state
.interceptor
.pre_handle(&path, &rule.annotation)
.await?;
}
Ok::<_, GarrisonError>(next.run(req).await)
};
let config = state.config.clone();
with_renewed_token_scope(async {
let result = match token {
Some(t) => with_login_id_scope(with_current_token(t, handle)).await,
None => handle.await,
};
let mut resp = match result {
Ok(resp) => resp,
Err(e) => e.into_response(),
};
if let Some(renewed_token) = get_renewed_token() {
if config.is_write_header {
match (
HeaderName::from_bytes(config.token_name.as_bytes()),
HeaderValue::from_str(&renewed_token),
) {
(Ok(name), Ok(value)) => {
resp.headers_mut().insert(name, value);
},
(Err(e), _) => {
tracing::debug!(
error = %e,
token_name = %config.token_name,
"{}",
crate::i18n::translate_detail(
"logs-renewed-token-header-name-invalid",
&[]
)
);
},
(_, Err(e)) => {
tracing::debug!(
error = %e,
"{}",
crate::i18n::translate_detail(
"logs-renewed-token-header-value-invalid",
&[]
)
);
},
}
}
if config.is_write_cookie {
match CookieType::token(&config)
.and_then(|c| build_set_cookie_value(&c, &renewed_token, config.cookie_secure))
{
Ok(cookie) => match HeaderValue::from_str(&cookie) {
Ok(value) => {
resp.headers_mut().append(SET_COOKIE, value);
},
Err(e) => {
tracing::warn!(
error = %e,
"{}",
crate::i18n::translate_detail(
"logs-renewed-token-cookie-value-invalid",
&[]
)
);
},
},
Err(e) => {
tracing::warn!(
error = %e,
"{}",
crate::i18n::translate_detail(
"logs-renewed-token-cookie-build-rejected",
&[]
)
);
},
}
}
clear_renewed_token();
}
resp
})
.await
}
#[cfg(feature = "tenant-isolation")]
pub async fn tenant_resolution_middleware(
State(resolver): State<Arc<dyn TenantResolver>>,
req: Request<Body>,
next: Next,
) -> Result<Response, StatusCode> {
use crate::context::tenant::TENANT;
let ctx = resolver
.resolve(req.headers())
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
Ok(TENANT.scope(ctx, next.run(req)).await)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn route_matches_exact_static_path() {
assert!(route_matches("/admin", "/admin"));
assert!(!route_matches("/admin", "/other"));
}
#[test]
fn route_matches_param_segment() {
assert!(route_matches("/users/:id", "/users/123"));
assert!(route_matches("/users/:id", "/users/abc"));
assert!(!route_matches("/users/:id", "/users/")); }
#[test]
fn route_matches_mixed_static_and_param() {
assert!(route_matches("/api/:version/users/:id", "/api/v1/users/42"));
assert!(!route_matches("/api/:version/users/:id", "/api/v1/users/"));
assert!(!route_matches(
"/api/:version/users/:id",
"/api/v1/items/42"
));
}
#[test]
fn route_matches_segment_count_mismatch() {
assert!(!route_matches("/users/:id", "/users/123/extra"));
assert!(!route_matches("/users/:id/extra", "/users/123"));
}
#[test]
fn route_matches_axum_brace_param() {
assert!(route_matches("/users/{id}", "/users/123"));
assert!(!route_matches("/users/{id}", "/users/")); assert!(!route_matches("/users/{id}", "/users/123/extra"));
assert!(route_matches(
"/api/{version}/users/:id",
"/api/v1/users/42"
));
assert!(!route_matches(
"/api/{version}/users/:id",
"/api/v1/items/42"
));
}
#[test]
fn route_matches_axum_wildcard_suffix() {
assert!(route_matches("/api/{*rest}", "/api"));
assert!(route_matches("/api/{*rest}", "/api/users/42"));
assert!(route_matches("/api/{*rest}", "/api/a/b/c"));
assert!(!route_matches("/api/{*rest}", "/others/x"));
assert!(!route_matches("/api/users/{*rest}", "/api/others/x"));
}
}