use super::CurrentUser;
#[cfg(feature = "cache")]
use axum::extract::State;
#[cfg(feature = "cache")]
use axum::middleware::Next;
use axum::{body::Body, extract::Request, response::Response};
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock};
use std::task::{Context, Poll};
use tower::{Layer, Service};
use wordval_core::api::ApiError;
pub(crate) fn normalize_path(path: &str) -> std::borrow::Cow<'_, str> {
let canonical = path == "/"
|| (path.starts_with('/')
&& !path.ends_with('/')
&& !path.contains("//")
&& path.split('/').all(|s| s != "." && s != ".."));
if canonical {
return std::borrow::Cow::Borrowed(path);
}
let mut segments: Vec<&str> = Vec::new();
for segment in path.split('/') {
match segment {
"." | "" => continue,
".." => {
segments.pop();
}
s => segments.push(s),
}
}
let mut result = String::with_capacity(path.len() + 1);
result.push('/');
result.push_str(&segments.join("/"));
std::borrow::Cow::Owned(result)
}
pub(crate) fn join_route_path(prefix: &str, path: &str) -> String {
let p = prefix.trim_matches('/');
let path = path.trim_start_matches('/');
if p.is_empty() {
if path.is_empty() {
"/".to_string()
} else {
format!("/{}", path)
}
} else if path.is_empty() {
format!("/{}", p)
} else {
format!("/{}/{}", p, path)
}
}
pub(crate) fn match_path_pattern(pattern: &str, path: &str) -> bool {
let p = normalize_path(pattern);
let q = normalize_path(path);
if p == q {
return true;
}
PathPattern::compile_normalized(&p).matches_normalized(&q)
}
#[derive(Debug, Clone)]
pub(crate) enum Seg {
Lit(String),
Param,
}
#[derive(Debug, Clone)]
pub(crate) enum PathPattern {
Segments(Vec<Seg>),
TailWildcard(String),
}
impl PathPattern {
pub(crate) fn compile(pattern: &str) -> Self {
Self::compile_normalized(&normalize_path(pattern))
}
pub(crate) fn compile_normalized(p: &str) -> Self {
if let Some(prefix) = p.strip_suffix("{*rest}").or_else(|| p.strip_suffix("/*")) {
return Self::TailWildcard(prefix.trim_end_matches('/').to_string());
}
Self::Segments(
p.split('/')
.filter(|s| !s.is_empty())
.map(|s| {
if s.starts_with('{') && s.ends_with('}') {
Seg::Param
} else {
Seg::Lit(s.to_string())
}
})
.collect(),
)
}
pub(crate) fn matches_normalized(&self, q: &str) -> bool {
match self {
Self::Segments(segs) => {
let mut q_segs = q.split('/').filter(|s| !s.is_empty());
for seg in segs {
let Some(qs) = q_segs.next() else { return false };
match seg {
Seg::Lit(l) => {
if l != qs {
return false;
}
}
Seg::Param => {}
}
}
q_segs.next().is_none()
}
Self::TailWildcard(prefix) => {
if prefix.is_empty() {
return true;
}
q == prefix || (q.starts_with(prefix.as_str()) && q.as_bytes().get(prefix.len()) == Some(&b'/'))
}
}
}
}
#[cfg(feature = "cache")]
fn extract_bearer_token(req: &Request) -> Option<String> {
req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(|s| s.to_string())
}
pub(crate) fn is_api_path(normalized: &str, prefixes: &[String]) -> bool {
prefixes.is_empty() || prefixes.iter().any(|p| normalized.starts_with(p.as_str()))
}
#[cfg(feature = "cache")]
pub struct SessionResolverState {
pub cache: wordval_cache::SharedCache,
}
#[cfg(feature = "cache")]
pub async fn session_resolver(
State(state): State<Arc<SessionResolverState>>,
mut req: Request,
next: Next,
) -> Response {
let Some(token) = extract_bearer_token(&req) else {
return next.run(req).await;
};
use wordval_cache::Cache;
match state
.cache
.get::<CurrentUser>(&format!("session:{}", token))
.await
{
Ok(Some(session)) => {
req.extensions_mut().insert(session);
}
Ok(None) => {
tracing::debug!("会话不存在或已过期: token={}", token);
}
Err(e) => {
tracing::warn!("会话查询失败(缓存故障): {}", e);
}
}
next.run(req).await
}
#[derive(Clone)]
pub struct AuthLayer {
pub ignore_paths: Arc<Vec<String>>,
pub method_ignore_rules: Arc<Vec<(String, String)>>,
pub api_prefixes: Arc<Vec<String>>,
pub(crate) compiled: Arc<OnceLock<Arc<CompiledAuth>>>,
}
pub(crate) struct CompiledAuth {
ignore: Vec<PathPattern>,
method_ignore: Vec<(String, PathPattern)>,
api_prefixes: Arc<Vec<String>>,
}
impl CompiledAuth {
fn compile(layer: &AuthLayer) -> Self {
Self {
ignore: layer.ignore_paths.iter().map(|p| PathPattern::compile(p)).collect(),
method_ignore: layer
.method_ignore_rules
.iter()
.map(|(m, p)| (m.clone(), PathPattern::compile(p)))
.collect(),
api_prefixes: layer.api_prefixes.clone(),
}
}
}
impl<S> Layer<S> for AuthLayer {
type Service = AuthService<S>;
fn layer(&self, inner: S) -> Self::Service {
let compiled = self
.compiled
.get_or_init(|| Arc::new(CompiledAuth::compile(self)))
.clone();
AuthService { inner, compiled }
}
}
#[derive(Clone)]
pub struct AuthService<S> {
inner: S,
compiled: Arc<CompiledAuth>,
}
impl<S> Service<Request<Body>> for AuthService<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_path = normalize_path(req.uri().path());
let compiled = &self.compiled;
let method = req.method().as_str();
let is_ignore = compiled
.method_ignore
.iter()
.any(|(m, p)| m.eq_ignore_ascii_case(method) && p.matches_normalized(&normalized_path))
|| (method.eq_ignore_ascii_case("HEAD")
&& compiled.method_ignore.iter().any(|(m, p)| {
m.eq_ignore_ascii_case("GET") && p.matches_normalized(&normalized_path)
}))
|| compiled
.ignore
.iter()
.any(|p| p.matches_normalized(&normalized_path));
let is_page = !compiled.api_prefixes.is_empty()
&& !compiled
.api_prefixes
.iter()
.any(|p| normalized_path.starts_with(p.as_str()));
let is_authenticated = req.extensions().get::<CurrentUser>().is_some();
let replacement = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, replacement);
Box::pin(async move {
if is_ignore || is_page || is_authenticated {
return inner.call(req).await;
}
Ok(super::error_response(ApiError::unauthorized(
"未授权访问,请先登录",
)))
})
}
}
#[cfg(test)]
mod tests {
use super::{join_route_path, match_path_pattern, normalize_path};
#[test]
fn normalize_path_borrows_canonical_and_resolves_dots() {
use std::borrow::Cow;
assert!(matches!(normalize_path("/a/b"), Cow::Borrowed("/a/b")));
assert!(matches!(normalize_path("/"), Cow::Borrowed("/")));
assert_eq!(&*normalize_path("/a/./b"), "/a/b");
assert_eq!(&*normalize_path("/a/../b"), "/b");
assert_eq!(&*normalize_path("//a//b//"), "/a/b");
assert_eq!(&*normalize_path("/a/"), "/a");
assert_eq!(&*normalize_path("users"), "/users");
assert_eq!(&*normalize_path(""), "/");
}
#[test]
fn join_route_path_normalizes_prefix_and_path() {
assert_eq!(join_route_path("", "/users"), "/users");
assert_eq!(join_route_path("/", "/users"), "/users");
assert_eq!(join_route_path("/api", "/users"), "/api/users");
assert_eq!(join_route_path("api", "users"), "/api/users");
assert_eq!(join_route_path("/api/", "/users"), "/api/users");
assert_eq!(join_route_path("/api/", "users"), "/api/users");
assert_eq!(join_route_path("/api", ""), "/api");
assert_eq!(join_route_path("", ""), "/");
assert_eq!(join_route_path("/api", "/users"), "/api/users");
}
#[test]
fn match_path_exact_and_single_param_segment() {
assert!(match_path_pattern(
"/api/public/token/{id}",
"/api/public/token/123"
));
assert!(match_path_pattern(
"/api/public/token/{id}",
"/api/public/token/abc"
));
assert!(!match_path_pattern(
"/api/public/token/{id}",
"/api/public/token/123/delete"
));
assert!(!match_path_pattern(
"/api/public/token/{id}",
"/api/public/token/123/456"
));
assert!(!match_path_pattern(
"/api/public/token/{id}",
"/api/public/token"
));
assert!(!match_path_pattern(
"/api/public/token/{id}",
"/api/public/admin/123"
));
assert!(match_path_pattern("/api/{a}/{b}", "/api/x/y"));
assert!(!match_path_pattern("/api/{a}/{b}", "/api/x/y/z"));
}
#[test]
fn match_path_tail_wildcard() {
assert!(match_path_pattern("/api/public/{*rest}", "/api/public"));
assert!(match_path_pattern("/api/public/{*rest}", "/api/public/a"));
assert!(match_path_pattern(
"/api/public/{*rest}",
"/api/public/a/b/c"
));
assert!(match_path_pattern("/api/public/*", "/api/public/a/b"));
assert!(!match_path_pattern("/api/public/*", "/api/publicSecret"));
assert!(!match_path_pattern("/api/public/{*rest}", "/api/other"));
}
#[test]
fn match_path_normalizes_dot_segments() {
assert!(match_path_pattern("/api/users", "/api/./users"));
assert!(match_path_pattern("/api/users", "/api/x/../users"));
}
}