| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- use axum::{
- async_trait,
- extract::FromRequestParts,
- http::request::Parts,
- Json,
- };
- use bos_core::{ApiResponse, BosError};
- use bos_scope::AuthContext;
- use seoh_service_sdk::{GrantedUpperBound, UnifiedAcContext};
- use serde::de::DeserializeOwned;
- use crate::state::AppState;
- pub struct RequireAuth(pub AuthContext);
- pub struct OptionalAuth(pub Option<AuthContext>);
- /// 取本次请求的**最终用户 JWT 票面原文**(`Authorization: Bearer …` 去掉前缀),用途单一=
- /// 客体树写接口把它**原样转发**给平台(`U-103`:`rt.node.*`/`rt.resource.*` 授在 `end_user`
- /// 档位,业务服务是**转发方**、⛔ 代持方,⛔ 用服务账号令牌顶替)。
- ///
- /// ⚠️ 本函数**只搬运、不解释**:⛔ 解 `sub` 当身份用(红线见 [`ac_identity`]——「谁登录」只认
- /// AC 上下文)。取不到 ⇒ `None`,由 `AuthContext::end_user_token` 在使用点失败关闭。
- fn bearer_token(parts: &Parts) -> Option<String> {
- let raw = parts
- .headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(str::trim)
- .unwrap_or_default();
- let rest = raw
- .strip_prefix("Bearer ")
- .or_else(|| raw.strip_prefix("bearer "))
- .or_else(|| raw.strip_prefix("BEARER "))?;
- let token = rest.trim();
- (!token.is_empty()).then(|| token.to_string())
- }
- /// 「当前是哪个业务账号」的**唯一**可信来源=SDK 统一判权中间件写入请求扩展的
- /// [`UnifiedAcContext`](其 `identity_id` 由 `access/check@v1` 回显,等于人类 JWT 的 `sub`
- /// =IAM `user/create` 的 `id`,见 18 册 §18.3 第六轮)。
- ///
- /// ⛔ 三类旧写法(平台《外部项目服务接入约束》§8.3 红线 6「信任客户端自行带来的身份」):
- /// * `X-Seoh-User-Id`:任何直连 `:8088` 的调用方都能伪造成任意账号;
- /// * `X-Granted-Resource-Instances`:授权范围由调用方自报=行级可见范围可被放大;
- /// * 自行 base64 解 `Authorization` 里的 JWT `sub`(不验签):伪造一个 JWT 形状的字符串即可冒充。
- /// 需要自行解析人类 JWT 时必须**验签**,本项目改走 AC 上下文,不再自解。
- fn ac_identity(parts: &Parts) -> Option<String> {
- parts
- .extensions
- .get::<UnifiedAcContext>()
- .and_then(|ctx| ctx.identity_id.clone())
- .map(|v| v.trim().to_string())
- .filter(|v| !v.is_empty())
- }
- #[async_trait]
- impl FromRequestParts<AppState> for RequireAuth {
- type Rejection = axum::response::Response;
- async fn from_request_parts(
- parts: &mut Parts,
- state: &AppState,
- ) -> Result<Self, Self::Rejection> {
- if let Some(auth) = parts.extensions.get::<AuthContext>() {
- return Ok(RequireAuth(auth.clone()));
- }
- let Some(user_id) = ac_identity(parts) else {
- // 判权中间件没给出身份=该请求没经过 AC(多为绕网关直连或路由未登记),
- // 一律失败关闭,⛔ 退回到「读头自认身份」。
- tracing::warn!(
- "缺少 AC 判权上下文(UnifiedAcContext.identity_id),拒绝按未认证请求处理 route={}",
- parts.uri.path()
- );
- return Err(json_err(BosError::biz(
- bos_core::ErrorCode::Unauthorized,
- "未登录(缺少 AC 判权上下文)",
- )));
- };
- // 通道②授权上界(工单回件 §5.2 B2):两条下发路径同由 SDK `resolve_upper_bound` 解析,
- // 谁在取谁——
- // 1. [`crate::grant::grant_inject_middleware`]:网关写进请求体根级的注入(我方当前唯一可用来源);
- // 2. [`seoh_service_sdk::GrantedUpperBound`]:SDK 从 AC 响应写入的扩展(我方路由当前取不到:
- // SDK 路由表把 `x-scope` 原样发给 AC、⛔ 折叠 `x-enumeration-kind`,而手写
- // `x-scope.source_enumeration` 会被注册中心拒,详见 grant.rs 头注)。
- // 两者都取不到 ⇒ `None`=**未注入**,消费方保持现状的失败关闭(⛔ 当「不限」放行)。
- let grant = parts
- .extensions
- .get::<crate::grant::GrantInjection>()
- .map(|g| g.0.clone())
- .or_else(|| {
- parts
- .extensions
- .get::<GrantedUpperBound>()
- .map(|g| g.0.clone())
- });
- // `raw_token`:原样留存的最终用户票面,供客体树写接口转发(`U-103`)。
- // ⛔ 用它判身份(身份只认上面的 AC 上下文),⛔ 拿它换服务令牌再自用。
- let raw_token = bearer_token(parts);
- let auth = crate::load_binding(&state.db, &user_id, grant.as_ref(), raw_token.as_deref())
- .await
- .map_err(json_err)?;
- // `X-Seoh-Env` 只用于「请求打到了错误环境的实例」这类快速失败,⛔ 当身份或判权依据
- // (接入约束 §6/讨论稿 K8:该头由网关剥离重注,客户端传了也没用)。
- if let Some(env) = parts.headers.get("X-Seoh-Env").and_then(|v| v.to_str().ok()) {
- if env != state.bos_env {
- return Err(json_err(BosError::bad_params(format!(
- "X-Seoh-Env={env} 与实例 BOS_ENV={} 不一致",
- state.bos_env
- ))));
- }
- }
- parts.extensions.insert(auth.clone());
- Ok(RequireAuth(auth))
- }
- }
- #[async_trait]
- impl FromRequestParts<AppState> for OptionalAuth {
- type Rejection = axum::response::Response;
- async fn from_request_parts(
- parts: &mut Parts,
- state: &AppState,
- ) -> Result<Self, Self::Rejection> {
- match RequireAuth::from_request_parts(parts, state).await {
- Ok(RequireAuth(a)) => Ok(OptionalAuth(Some(a))),
- Err(_) => Ok(OptionalAuth(None)),
- }
- }
- }
- pub struct DataBody<T>(pub T);
- #[async_trait]
- impl<S, T> axum::extract::FromRequest<S> for DataBody<T>
- where
- S: Send + Sync,
- T: DeserializeOwned,
- {
- type Rejection = axum::response::Response;
- async fn from_request(req: axum::extract::Request, state: &S) -> Result<Self, Self::Rejection> {
- let Json(wrapper): Json<serde_json::Value> = Json::from_request(req, state)
- .await
- .map_err(|e| json_err(BosError::bad_params(e.to_string())))?;
- let data = wrapper
- .get("data")
- .cloned()
- .ok_or_else(|| json_err(BosError::bad_params("缺少 data")))?;
- let typed: T = serde_json::from_value(data)
- .map_err(|e| json_err(BosError::bad_params(e.to_string())))?;
- Ok(DataBody(typed))
- }
- }
- pub fn json_err(err: BosError) -> axum::response::Response {
- use axum::response::IntoResponse;
- let body = ApiResponse::<()>::from_error(&err);
- (axum::http::StatusCode::OK, axum::Json(body)).into_response()
- }
- pub fn json_err_data<T: serde::Serialize>(err: BosError, data: T) -> axum::response::Response {
- use axum::response::IntoResponse;
- let body = ApiResponse::from_error_with_data(&err, data);
- (axum::http::StatusCode::OK, axum::Json(body)).into_response()
- }
- pub fn json_ok<T: serde::Serialize>(data: T) -> axum::response::Response {
- use axum::response::IntoResponse;
- (axum::http::StatusCode::OK, axum::Json(ApiResponse::ok(data))).into_response()
- }
|