Skip to main content

fusion_web/middleware/
web_auth.rs

1use std::sync::Arc;
2
3use axum::body::Body;
4use fusion_common::time::now_offset;
5use fusion_core::log::get_trace_id;
6use http::request::Parts;
7use http::{Request, header::AUTHORIZATION, header::CONTENT_TYPE};
8use tower_http::auth::{AsyncAuthorizeRequest, AsyncRequireAuthorizationLayer};
9
10use fusion_common::ctx::Ctx;
11use fusion_core::application::Application;
12
13use crate::extract_ctx;
14use crate::{WebError, middleware::web_error_2_body};
15
16#[derive(Clone)]
17struct ExternalUrl {
18  url: Arc<String>,
19  client: reqwest::Client,
20}
21
22/// WebAuth is a middleware that checks if the request is authorized by calling remote API.
23#[derive(Clone, Default)]
24pub struct WebAuth {
25  /// A list of url paths that must be accessed with authentication.
26  includes: Arc<Vec<String>>,
27  /// A list of url paths that must not be accessed with authentication.
28  excludes: Arc<Vec<String>>,
29  external: Option<ExternalUrl>,
30}
31
32impl WebAuth {
33  /// Set the API base URL.
34  pub fn with_api_base_url(mut self, api_base_url: &str) -> Self {
35    self.external = Some(ExternalUrl {
36      url: Arc::new(format!("{}/api/auth/extract_token", api_base_url.trim_end_matches('/'))),
37      client: reqwest::Client::new(),
38    });
39    self
40  }
41
42  /// Add includes paths.
43  pub fn with_includes(mut self, includes: Vec<String>) -> Self {
44    self.includes = Arc::new(includes);
45    self
46  }
47
48  /// Add excludes paths.
49  pub fn with_excludes(mut self, excludes: Vec<String>) -> Self {
50    self.excludes = Arc::new(excludes);
51    self
52  }
53
54  pub fn into_layer(self) -> AsyncRequireAuthorizationLayer<Self> {
55    AsyncRequireAuthorizationLayer::new(self)
56  }
57}
58
59impl AsyncAuthorizeRequest<Body> for WebAuth {
60  type RequestBody = Body;
61  type ResponseBody = Body;
62  type Future = futures::future::BoxFuture<'static, Result<http::Request<Body>, http::Response<Self::ResponseBody>>>;
63
64  fn authorize(&mut self, request: http::Request<Self::RequestBody>) -> Self::Future {
65    let path = request.uri().path().to_string();
66    // Check if path is in includes (if includes is not empty)
67    if !self.includes.is_empty() && !self.includes.iter().any(|include| path.starts_with(include)) {
68      return Box::pin(async move {
69        Err(web_error_2_body(WebError::new_with_code(401, format!("Url path `{}` is not in includes", path))))
70      });
71    }
72
73    // Check if path is in excludes (if excludes is not empty)
74    if !self.excludes.is_empty() && self.excludes.iter().any(|exclude| path.starts_with(exclude)) {
75      return Box::pin(async move {
76        Err(web_error_2_body(WebError::new_with_code(401, format!("Url path `{}` is in excludes", path))))
77      });
78    }
79
80    match self.external.as_ref() {
81      Some(external) => {
82        let url = external.url.clone();
83        let client = external.client.clone();
84        Box::pin(async move {
85          let (mut parts, body) = request.into_parts();
86          let ctx = validate_token_remote(&url, &client, &parts).await.map_err(web_error_2_body)?;
87          parts.extensions.insert(ctx);
88          Ok(Request::from_parts(parts, body))
89        })
90      }
91      None => Box::pin(async {
92        let (mut parts, body) = request.into_parts();
93        let ctx = extract_ctx(&parts, Application::global().fusion_setting().security()).map_err(web_error_2_body)?;
94        parts.extensions.insert(ctx);
95        Ok(Request::from_parts(parts, body))
96      }),
97    }
98  }
99}
100
101/// Call remote API to validate token and extract context
102async fn validate_token_remote(url: &str, client: &reqwest::Client, parts: &Parts) -> Result<Ctx, WebError> {
103  let header_value = parts
104    .headers
105    .get(AUTHORIZATION)
106    .ok_or_else(|| WebError::new_with_code(401, "Missing authentication token"))?;
107
108  let response = client
109    .post(url)
110    .header(AUTHORIZATION, header_value)
111    .header(CONTENT_TYPE, "application/json")
112    .send()
113    .await
114    .map_err(|e| WebError::new_with_code(401, format!("Failed to call auth API: {}", e)))?;
115
116  if response.status().is_success() {
117    let response_data: serde_json::Value = response
118      .json()
119      .await
120      .map_err(|e| WebError::new_with_code(401, format!("Failed to parse auth response: {}", e)))?;
121
122    // Convert response data to CtxPayload
123    let response_map = response_data
124      .as_object()
125      .ok_or_else(|| WebError::new_with_code(401, "Invalid token response format"))?
126      .clone();
127
128    let ctx_payload = fusion_common::ctx::CtxPayload::from(response_map);
129
130    // Create Ctx from payload
131    let ctx = Ctx::try_new(ctx_payload, Some(now_offset()), get_trace_id())
132      .map_err(|e| WebError::new_with_code(401, format!("Failed to create context: {}", e)))?;
133
134    Ok(ctx)
135  } else {
136    let status = response.status();
137    let error_msg = format!("Token validation failed: {}", status);
138    Err(WebError::new_with_code(401, error_msg))
139  }
140}