use crate::annotation::Annotation;
use crate::config::GarrisonConfig;
use crate::context::token_extract::extract_token_from_headers;
use crate::error::GarrisonResult;
use crate::router::{DefaultGarrisonInterceptor, GarrisonInterceptor};
use crate::stp::with_current_token;
use std::collections::HashMap;
use std::sync::Arc;
use warp::http::HeaderMap;
use warp::Filter;
fn normalize_route_path(path: &str) -> &str {
if path.len() > 1 {
path.trim_end_matches('/')
} else {
path
}
}
fn route_matches_rule(pattern: &str, path: &str) -> bool {
let pattern = normalize_route_path(pattern);
let path = normalize_route_path(path);
let mut p = pattern.split('/');
let mut s = path.split('/');
loop {
match (p.next(), s.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 == "*" || (seg.len() > 3 && seg.starts_with("{*") && seg.ends_with('}'))
}
impl super::GarrisonRouter {
pub fn new(config: Arc<GarrisonConfig>) -> Self {
Self {
rules: HashMap::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(mut self, path: &str, annotation: Annotation) -> Self {
if path.is_empty() || !path.starts_with('/') {
tracing::error!(
path = %path,
"{}",
crate::i18n::translate_detail("logs-router-invalid-path-protected", &[])
);
return self;
}
if self.rules.contains_key(path) {
tracing::warn!(
path = %path,
"{}",
crate::i18n::translate_detail("logs-router-duplicate-path-override", &[])
);
}
self.rules.insert(path.to_string(), annotation);
self
}
pub fn into_filter(self) -> impl Filter<Extract = ((),), Error = warp::Rejection> + Clone {
let rules = Arc::new(self.rules);
let interceptor = self.interceptor;
let config = self.config;
warp::any()
.and(warp::path::full())
.and(warp::header::headers_cloned())
.and_then(move |path: warp::path::FullPath, headers: HeaderMap| {
let rules = rules.clone();
let interceptor = interceptor.clone();
let config = config.clone();
async move {
let path_str = path.as_str().to_string();
let annotation = rules
.iter()
.find(|(pattern, _)| route_matches_rule(pattern, &path_str))
.map(|(_, annotation)| annotation.clone());
if let Some(annotation) = annotation {
let token = extract_token_from_headers(&headers, &config)
.map_err(|e| warp::reject::custom(super::GarrisonRejection(e)))?;
let auth_check =
async { interceptor.pre_handle(&path_str, &annotation).await };
let result: GarrisonResult<()> = match token {
Some(t) => with_current_token(t, auth_check).await,
None => auth_check.await,
};
result.map_err(|e| warp::reject::custom(super::GarrisonRejection(e)))?;
}
Ok::<(), warp::Rejection>(())
}
})
}
}
impl Default for super::GarrisonRouter {
fn default() -> Self {
Self::new(Arc::new(GarrisonConfig::default_config()))
}
}
#[cfg(test)]
mod route_match_tests {
use super::*;
#[test]
fn route_matches_rule_exact_and_trailing_slash() {
assert!(route_matches_rule("/api/users", "/api/users"));
assert!(route_matches_rule("/api/users", "/api/users/"));
assert!(route_matches_rule("/api/users/", "/api/users"));
assert!(!route_matches_rule("/api/users", "/api/other"));
}
#[test]
fn route_matches_rule_param_and_wildcard() {
assert!(route_matches_rule("/api/users/{id}", "/api/users/42"));
assert!(route_matches_rule("/api/users/:id", "/api/users/42"));
assert!(!route_matches_rule("/api/users/{id}", "/api/users/"));
assert!(route_matches_rule("/api/*", "/api"));
assert!(route_matches_rule("/api/*", "/api/users/42"));
assert!(route_matches_rule("/api/users/{*rest}", "/api/users/a/b"));
assert!(!route_matches_rule("/api/users/{*rest}", "/api/others/x"));
}
#[test]
fn route_matches_rule_mixed_segments() {
assert!(route_matches_rule(
"/api/{version}/users/:id",
"/api/v1/users/42"
));
assert!(!route_matches_rule(
"/api/{version}/users/:id",
"/api/v1/items/42"
));
}
}