extract.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. use axum::{
  2. async_trait,
  3. extract::FromRequestParts,
  4. http::request::Parts,
  5. Json,
  6. };
  7. use bos_core::{ApiResponse, BosError};
  8. use bos_scope::AuthContext;
  9. use seoh_service_sdk::{GrantedUpperBound, UnifiedAcContext};
  10. use serde::de::DeserializeOwned;
  11. use crate::state::AppState;
  12. pub struct RequireAuth(pub AuthContext);
  13. pub struct OptionalAuth(pub Option<AuthContext>);
  14. /// 取本次请求的**最终用户 JWT 票面原文**(`Authorization: Bearer …` 去掉前缀),用途单一=
  15. /// 客体树写接口把它**原样转发**给平台(`U-103`:`rt.node.*`/`rt.resource.*` 授在 `end_user`
  16. /// 档位,业务服务是**转发方**、⛔ 代持方,⛔ 用服务账号令牌顶替)。
  17. ///
  18. /// ⚠️ 本函数**只搬运、不解释**:⛔ 解 `sub` 当身份用(红线见 [`ac_identity`]——「谁登录」只认
  19. /// AC 上下文)。取不到 ⇒ `None`,由 `AuthContext::end_user_token` 在使用点失败关闭。
  20. fn bearer_token(parts: &Parts) -> Option<String> {
  21. let raw = parts
  22. .headers
  23. .get("authorization")
  24. .and_then(|v| v.to_str().ok())
  25. .map(str::trim)
  26. .unwrap_or_default();
  27. let rest = raw
  28. .strip_prefix("Bearer ")
  29. .or_else(|| raw.strip_prefix("bearer "))
  30. .or_else(|| raw.strip_prefix("BEARER "))?;
  31. let token = rest.trim();
  32. (!token.is_empty()).then(|| token.to_string())
  33. }
  34. /// 「当前是哪个业务账号」的**唯一**可信来源=SDK 统一判权中间件写入请求扩展的
  35. /// [`UnifiedAcContext`](其 `identity_id` 由 `access/check@v1` 回显,等于人类 JWT 的 `sub`
  36. /// =IAM `user/create` 的 `id`,见 18 册 §18.3 第六轮)。
  37. ///
  38. /// ⛔ 三类旧写法(平台《外部项目服务接入约束》§8.3 红线 6「信任客户端自行带来的身份」):
  39. /// * `X-Seoh-User-Id`:任何直连 `:8088` 的调用方都能伪造成任意账号;
  40. /// * `X-Granted-Resource-Instances`:授权范围由调用方自报=行级可见范围可被放大;
  41. /// * 自行 base64 解 `Authorization` 里的 JWT `sub`(不验签):伪造一个 JWT 形状的字符串即可冒充。
  42. /// 需要自行解析人类 JWT 时必须**验签**,本项目改走 AC 上下文,不再自解。
  43. fn ac_identity(parts: &Parts) -> Option<String> {
  44. parts
  45. .extensions
  46. .get::<UnifiedAcContext>()
  47. .and_then(|ctx| ctx.identity_id.clone())
  48. .map(|v| v.trim().to_string())
  49. .filter(|v| !v.is_empty())
  50. }
  51. #[async_trait]
  52. impl FromRequestParts<AppState> for RequireAuth {
  53. type Rejection = axum::response::Response;
  54. async fn from_request_parts(
  55. parts: &mut Parts,
  56. state: &AppState,
  57. ) -> Result<Self, Self::Rejection> {
  58. if let Some(auth) = parts.extensions.get::<AuthContext>() {
  59. return Ok(RequireAuth(auth.clone()));
  60. }
  61. let Some(user_id) = ac_identity(parts) else {
  62. // 判权中间件没给出身份=该请求没经过 AC(多为绕网关直连或路由未登记),
  63. // 一律失败关闭,⛔ 退回到「读头自认身份」。
  64. tracing::warn!(
  65. "缺少 AC 判权上下文(UnifiedAcContext.identity_id),拒绝按未认证请求处理 route={}",
  66. parts.uri.path()
  67. );
  68. return Err(json_err(BosError::biz(
  69. bos_core::ErrorCode::Unauthorized,
  70. "未登录(缺少 AC 判权上下文)",
  71. )));
  72. };
  73. // 通道②授权上界(工单回件 §5.2 B2):两条下发路径同由 SDK `resolve_upper_bound` 解析,
  74. // 谁在取谁——
  75. // 1. [`crate::grant::grant_inject_middleware`]:网关写进请求体根级的注入(我方当前唯一可用来源);
  76. // 2. [`seoh_service_sdk::GrantedUpperBound`]:SDK 从 AC 响应写入的扩展(我方路由当前取不到:
  77. // SDK 路由表把 `x-scope` 原样发给 AC、⛔ 折叠 `x-enumeration-kind`,而手写
  78. // `x-scope.source_enumeration` 会被注册中心拒,详见 grant.rs 头注)。
  79. // 两者都取不到 ⇒ `None`=**未注入**,消费方保持现状的失败关闭(⛔ 当「不限」放行)。
  80. let grant = parts
  81. .extensions
  82. .get::<crate::grant::GrantInjection>()
  83. .map(|g| g.0.clone())
  84. .or_else(|| {
  85. parts
  86. .extensions
  87. .get::<GrantedUpperBound>()
  88. .map(|g| g.0.clone())
  89. });
  90. // `raw_token`:原样留存的最终用户票面,供客体树写接口转发(`U-103`)。
  91. // ⛔ 用它判身份(身份只认上面的 AC 上下文),⛔ 拿它换服务令牌再自用。
  92. let raw_token = bearer_token(parts);
  93. let auth = crate::load_binding(&state.db, &user_id, grant.as_ref(), raw_token.as_deref())
  94. .await
  95. .map_err(json_err)?;
  96. // `X-Seoh-Env` 只用于「请求打到了错误环境的实例」这类快速失败,⛔ 当身份或判权依据
  97. // (接入约束 §6/讨论稿 K8:该头由网关剥离重注,客户端传了也没用)。
  98. if let Some(env) = parts.headers.get("X-Seoh-Env").and_then(|v| v.to_str().ok()) {
  99. if env != state.bos_env {
  100. return Err(json_err(BosError::bad_params(format!(
  101. "X-Seoh-Env={env} 与实例 BOS_ENV={} 不一致",
  102. state.bos_env
  103. ))));
  104. }
  105. }
  106. parts.extensions.insert(auth.clone());
  107. Ok(RequireAuth(auth))
  108. }
  109. }
  110. #[async_trait]
  111. impl FromRequestParts<AppState> for OptionalAuth {
  112. type Rejection = axum::response::Response;
  113. async fn from_request_parts(
  114. parts: &mut Parts,
  115. state: &AppState,
  116. ) -> Result<Self, Self::Rejection> {
  117. match RequireAuth::from_request_parts(parts, state).await {
  118. Ok(RequireAuth(a)) => Ok(OptionalAuth(Some(a))),
  119. Err(_) => Ok(OptionalAuth(None)),
  120. }
  121. }
  122. }
  123. pub struct DataBody<T>(pub T);
  124. #[async_trait]
  125. impl<S, T> axum::extract::FromRequest<S> for DataBody<T>
  126. where
  127. S: Send + Sync,
  128. T: DeserializeOwned,
  129. {
  130. type Rejection = axum::response::Response;
  131. async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
  132. let Json(wrapper): Json<serde_json::Value> = Json::from_request(req, state)
  133. .await
  134. .map_err(|e| json_err(BosError::bad_params(e.to_string())))?;
  135. let data = wrapper
  136. .get("data")
  137. .cloned()
  138. .ok_or_else(|| json_err(BosError::bad_params("缺少 data")))?;
  139. let typed: T = serde_json::from_value(data)
  140. .map_err(|e| json_err(BosError::bad_params(e.to_string())))?;
  141. Ok(DataBody(typed))
  142. }
  143. }
  144. pub fn json_err(err: BosError) -> axum::response::Response {
  145. use axum::response::IntoResponse;
  146. let body = ApiResponse::<()>::from_error(&err);
  147. (axum::http::StatusCode::OK, axum::Json(body)).into_response()
  148. }
  149. pub fn json_err_data<T: serde::Serialize>(err: BosError, data: T) -> axum::response::Response {
  150. use axum::response::IntoResponse;
  151. let body = ApiResponse::from_error_with_data(&err, data);
  152. (axum::http::StatusCode::OK, axum::Json(body)).into_response()
  153. }
  154. pub fn json_ok<T: serde::Serialize>(data: T) -> axum::response::Response {
  155. use axum::response::IntoResponse;
  156. (axum::http::StatusCode::OK, axum::Json(ApiResponse::ok(data))).into_response()
  157. }