**影响**
- 改动前:`cargo fmt --check` 报 13 个文件漂移 ⇒ 新代码容易跟着旧风格走,
review diff 噪声大。
- 改动后:`cargo fmt --check` 干净;**零行为变更**(纯排版,
`cargo test` 222 passed / 0 failed / 1 ignored,`cargo clippy -D warnings` 干净)。
**改动**
- `src/{account,auth,codec,crud,db,envelope,ids,protocol,registry,session}.rs`、
`src/domain/identity.rs`、`src/routes/health.rs`、`tests/account_api.rs`:
统一 rustfmt 排版(长行折行、match 分支、struct 字面量多行展开等)。
**设计**
- 单独一笔 style 提交,与语义改动(`fix(crud)`)分开 ⇒ review 时格式噪声可整笔跳过。
- 不引入 `rustfmt.toml`:沿用默认配置,避免与上游风格分叉。
Co-Authored-By: Claude Code <[email protected]>
699 lines
27 KiB
Rust
699 lines
27 KiB
Rust
//! 连接器入向鉴权:白名单 → 内部令牌(+协议版本闸门)→ 会话令牌。
|
||
//!
|
||
//! 逐字照搬上游 `ssw/tdc/filter/TdcAuthFilter.java` 的 5 步:
|
||
//!
|
||
//! ```text
|
||
//! 1. OPTIONS 预检 → 放行
|
||
//! 2. gateway.white-url 命中 → 放行(🔴 不过协议版本闸门)
|
||
//! 3. X-Internal-Token 匹配 → 过协议版本闸门(不兼容 ⇒ HTTP 401)→ 放行
|
||
//! 4. X-Auth-Token 有效 → 放行(🔴 不过协议版本闸门 —— 不是跨端流量)
|
||
//! 5. 都不满足 → HTTP 401
|
||
//! ```
|
||
//!
|
||
//! ⚠️ 上游第 5 步的 JNPF 登录通道:**上游完整前端走的就是它**(`POST /api/oauth/Login` ⇒ `Authorization: bearer <token>`),
|
||
//! ⇒ 本仓按 Task 12 实现**本地账号层**(j7 框架库已排除 ⇒ 自带极简账号表当替身)。
|
||
|
||
use std::sync::Arc;
|
||
|
||
use axum::extract::{Request, State};
|
||
use axum::http::{HeaderMap, Method, StatusCode, Uri};
|
||
use axum::middleware::Next;
|
||
use axum::response::{IntoResponse, Response};
|
||
use serde_json::json;
|
||
|
||
use crate::protocol::{check_protocol, INTERNAL_TOKEN_HEADER, PROTOCOL_VERSION_HEADER};
|
||
use crate::session::{SessionKind, SessionStore};
|
||
|
||
/// 连接器会话令牌头。
|
||
pub const AUTH_TOKEN_HEADER: &str = "X-Auth-Token";
|
||
/// 账号会话令牌(上游完整前端登录后发 `Authorization: bearer <token>`)。
|
||
pub const AUTHORIZATION_HEADER: &str = "authorization";
|
||
/// 跨端调用方声明的操作人。
|
||
pub const OPERATOR_HEADER: &str = "X-Internal-Operator";
|
||
|
||
/// 上游 `gateway.white-url`(Ant 风格)。
|
||
pub const WHITE_URL: &[&str] = &[
|
||
"/api/oauth/Login",
|
||
"/api/ssw/tdc/Auth/Login",
|
||
"/api/ssw/tdc/Auth/SsoConfig",
|
||
"/api/ssw/tdc/Gateway/Invoke",
|
||
"/api/ssw/tdc/Gateway/ProviderInvoke",
|
||
"/api/ssw/tdc/P2P/Handshake",
|
||
"/api/ssw/tdc/P2P/Transfer/Prepare",
|
||
"/api/ssw/tdc/P2P/Transfer/*/Chunk",
|
||
"/api/ssw/tdc/P2P/Transfer/*/Receipt",
|
||
"/api/ssw/tdc/P2P/Download/*",
|
||
"/api/ssw/tdc/Portal/**",
|
||
"/api/ssw/tdc/Topology/Internal/TopologyCheck",
|
||
];
|
||
|
||
/// 本地额外放行:健康检查(探针)。
|
||
pub const EXTRA_WHITE_URL: &[&str] = &["/api/health"];
|
||
|
||
/// 操作主体。
|
||
#[derive(Clone, Debug)]
|
||
pub enum Principal {
|
||
/// 跨端内部令牌通道。
|
||
Internal { operator: Option<String> },
|
||
/// 连接器身份会话通道。
|
||
Session {
|
||
identity_id: String,
|
||
identity_code: String,
|
||
},
|
||
/// 本地账号会话通道(控制台账号口令登录)。
|
||
Account { account_id: String, account: String },
|
||
}
|
||
|
||
/// 鉴权中间件的状态。
|
||
#[derive(Clone)]
|
||
pub struct AuthState {
|
||
pub internal_token: String,
|
||
pub sessions: Arc<SessionStore>,
|
||
}
|
||
|
||
/// Ant 风格路径匹配:`**` 跨段任意、`*` 段内任意、`?` 单字符。
|
||
///
|
||
/// 🔴 **只去前导斜杠,不去尾斜杠** —— 与 Spring `AntPathMatcher` 逐字对齐:
|
||
/// `match("/api/oauth/Login", "/api/oauth/Login/")` = **false**。
|
||
/// (去尾斜杠会让白名单比上游**宽松**,是潜伏的分叉。)
|
||
pub fn ant_match(pattern: &str, path: &str) -> bool {
|
||
let p: Vec<&str> = pattern.trim_start_matches('/').split('/').collect();
|
||
let s: Vec<&str> = path.trim_start_matches('/').split('/').collect();
|
||
match_segments(&p, &s)
|
||
}
|
||
|
||
fn match_segments(pattern: &[&str], path: &[&str]) -> bool {
|
||
if pattern.is_empty() {
|
||
return path.is_empty();
|
||
}
|
||
if pattern[0] == "**" {
|
||
for skip in 0..=path.len() {
|
||
if match_segments(&pattern[1..], &path[skip..]) {
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
if path.is_empty() {
|
||
return false;
|
||
}
|
||
if !segment_match(pattern[0], path[0]) {
|
||
return false;
|
||
}
|
||
match_segments(&pattern[1..], &path[1..])
|
||
}
|
||
|
||
fn segment_match(pattern: &str, segment: &str) -> bool {
|
||
let p: Vec<char> = pattern.chars().collect();
|
||
let s: Vec<char> = segment.chars().collect();
|
||
fn go(p: &[char], s: &[char]) -> bool {
|
||
if p.is_empty() {
|
||
return s.is_empty();
|
||
}
|
||
match p[0] {
|
||
'*' => (0..=s.len()).any(|k| go(&p[1..], &s[k..])),
|
||
'?' => !s.is_empty() && go(&p[1..], &s[1..]),
|
||
c => !s.is_empty() && s[0] == c && go(&p[1..], &s[1..]),
|
||
}
|
||
}
|
||
go(&p, &s)
|
||
}
|
||
|
||
/// 是否命中白名单。
|
||
pub fn is_white_url(path: &str) -> bool {
|
||
WHITE_URL
|
||
.iter()
|
||
.chain(EXTRA_WHITE_URL.iter())
|
||
.any(|p| ant_match(p, path))
|
||
}
|
||
|
||
/// 只有 `/api/` 前缀的路径走业务鉴权。
|
||
///
|
||
/// 🔴 上游完整前端是 **SPA**(`createWebHistory`):深链(`/login`、`/tdc/home`)与静态资源
|
||
/// (`/assets/**`、`/logo.png`)都不带业务凭证,若一并鉴权 ⇒ 打开首页就是 401。
|
||
pub fn uri_path_is_guarded(path: &str) -> bool {
|
||
path == "/api" || path.starts_with("/api/")
|
||
}
|
||
|
||
/// 鉴权失败响应:**裸三字段**,与业务信封不同。
|
||
///
|
||
/// ```json
|
||
/// {"success": false, "code": 401, "msg": "内部接口凭证无效"}
|
||
/// ```
|
||
///
|
||
/// 🔴 **HTTP 状态与 body 的 `code` 恒等**(`code` 由 `status.as_u16()` 推出)——
|
||
/// 本仓的**业务**失败码(`400` / `600`)是「HTTP 200 + body.code」那一族,
|
||
/// 混进鉴权失败会造出「状态码与 body 码不一致」的响应。
|
||
/// 上游同构:`TdcAuthFilter.java` 的 `reject401` / `reject403` 是两个**独立**方法,
|
||
/// 状态码与 body 码恒等 ⇒ 本仓用一个「状态即真相」的函数表达同一件事。
|
||
pub fn reject(status: StatusCode, msg: &str) -> Response {
|
||
(
|
||
status,
|
||
[(axum::http::header::CONTENT_TYPE, "application/json")],
|
||
json!({"success": false, "code": status.as_u16(), "msg": msg}).to_string(),
|
||
)
|
||
.into_response()
|
||
}
|
||
|
||
fn header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
|
||
headers.get(name).and_then(|v| v.to_str().ok())
|
||
}
|
||
|
||
/// 入向鉴权中间件。
|
||
pub async fn auth_middleware(
|
||
State(auth): State<AuthState>,
|
||
headers: HeaderMap,
|
||
method: Method,
|
||
uri: Uri,
|
||
mut req: Request,
|
||
next: Next,
|
||
) -> Response {
|
||
// ① OPTIONS 预检
|
||
if method == Method::OPTIONS {
|
||
return next.run(req).await;
|
||
}
|
||
// ①.5 非业务路径(静态资源 / SPA 深链)不经业务鉴权
|
||
if !uri_path_is_guarded(uri.path()) {
|
||
return next.run(req).await;
|
||
}
|
||
// ② 白名单(不过协议版本闸门)
|
||
if is_white_url(uri.path()) {
|
||
return next.run(req).await;
|
||
}
|
||
// ③ 内部令牌通道(过协议版本闸门)
|
||
if let Some(token) = header_str(&headers, INTERNAL_TOKEN_HEADER) {
|
||
if !token.is_empty() && token == auth.internal_token {
|
||
let declared = header_str(&headers, PROTOCOL_VERSION_HEADER);
|
||
if !check_protocol(declared) {
|
||
return reject(StatusCode::UNAUTHORIZED, "跨端协议版本不兼容,请升级对端");
|
||
}
|
||
let operator = header_str(&headers, OPERATOR_HEADER).map(|s| s.to_string());
|
||
req.extensions_mut()
|
||
.insert(Principal::Internal { operator });
|
||
return next.run(req).await;
|
||
}
|
||
}
|
||
// ④ 会话令牌通道(不过协议版本闸门)
|
||
// · `X-Auth-Token`:连接器身份会话(上游 standalone 通道)
|
||
// · `Authorization: bearer <token>`:本地账号会话(上游完整前端登录后走这条)
|
||
if let Some(token) = session_token(&headers) {
|
||
if let Some(session) = auth.sessions.lookup(token) {
|
||
let principal = match session.kind {
|
||
SessionKind::Identity => Principal::Session {
|
||
identity_id: session.identity_id,
|
||
identity_code: session.identity_code,
|
||
},
|
||
SessionKind::Account => Principal::Account {
|
||
account_id: session.identity_id,
|
||
account: session.identity_code,
|
||
},
|
||
};
|
||
req.extensions_mut().insert(principal);
|
||
return next.run(req).await;
|
||
}
|
||
}
|
||
// ⑤ 都不满足
|
||
reject(StatusCode::UNAUTHORIZED, "内部接口凭证无效")
|
||
}
|
||
|
||
/// 会话令牌来源:`X-Auth-Token`,或 `Authorization: bearer <token>`。
|
||
pub fn session_token(headers: &HeaderMap) -> Option<&str> {
|
||
if let Some(t) = header_str(headers, AUTH_TOKEN_HEADER) {
|
||
if !t.is_empty() {
|
||
return Some(t);
|
||
}
|
||
}
|
||
let raw = header_str(headers, AUTHORIZATION_HEADER)?;
|
||
// scheme 大小写不敏感(HTTP 规范:auth-scheme case-insensitive)
|
||
let (scheme, rest) = raw.split_once(' ')?;
|
||
if !scheme.eq_ignore_ascii_case("bearer") {
|
||
return None;
|
||
}
|
||
let t = rest.trim();
|
||
if t.is_empty() {
|
||
None
|
||
} else {
|
||
Some(t)
|
||
}
|
||
}
|
||
|
||
/// 是否已有可用的操作主体(内部令牌 / 连接器身份会话 / 本地账号会话)。
|
||
fn has_principal(p: Option<&Principal>) -> bool {
|
||
matches!(
|
||
p,
|
||
Some(Principal::Internal { .. })
|
||
| Some(Principal::Session { .. })
|
||
| Some(Principal::Account { .. })
|
||
)
|
||
}
|
||
|
||
/// 控制器层菜单权限闸门(上游 `requireMenuPermission`)。
|
||
///
|
||
/// 🔴 **菜单权限检查因 j7 框架库被排除而 fail-open** —— 今天等价于「有主体就放行」。
|
||
/// 但上游比 `require_internal_or_user` **多一道** `permissionGuard.requireMenu(getClass())`
|
||
/// ⇒ 本函数**刻意不调用** `require_internal_or_user`,两者是**独立的两道门**:
|
||
/// 将来 Task 12 把菜单检查收紧时,只有本函数该变严。
|
||
///
|
||
/// ⚠️ `result_large_err`:`Response` 本体约 128 字节。三道门要返回**可直接回给客户端的
|
||
/// 完整响应**(含状态码与 body),装箱(`Box<Response>`)只会把噪音推给每个调用点 ⇒ 就地豁免。
|
||
#[allow(clippy::result_large_err)]
|
||
pub fn require_menu_permission(p: Option<&Principal>) -> Result<(), Response> {
|
||
if has_principal(p) {
|
||
Ok(())
|
||
} else {
|
||
Err(reject(
|
||
StatusCode::FORBIDDEN,
|
||
"缺少有效凭证(需登录或内部凭证)",
|
||
))
|
||
}
|
||
}
|
||
|
||
/// 控制器层弱闸门(上游 `requireInternalOrUser`):**服务间调用(内部令牌)或已登录用户**。
|
||
///
|
||
/// 🔴 上游它**比** `require_menu_permission` **弱**(没有菜单权限检查)⇒ 数据面端点用它。
|
||
/// 今天两者行为相同(菜单检查 fail-open)⇒ 这里**写成独立 match 臂**而不是别名,
|
||
/// 免得将来收紧菜单检查时把这条更弱的闸门**连坐**收紧。
|
||
#[allow(clippy::result_large_err)]
|
||
pub fn require_internal_or_user(p: Option<&Principal>) -> Result<(), Response> {
|
||
if has_principal(p) {
|
||
Ok(())
|
||
} else {
|
||
Err(reject(
|
||
StatusCode::FORBIDDEN,
|
||
"缺少有效凭证(需登录或内部凭证)",
|
||
))
|
||
}
|
||
}
|
||
|
||
/// 控制器层闸门(上游 `requireInternalOnly`):**仅**内部令牌通道。
|
||
#[allow(clippy::result_large_err)]
|
||
pub fn require_internal_only(p: Option<&Principal>) -> Result<(), Response> {
|
||
match p {
|
||
Some(Principal::Internal { .. }) => Ok(()),
|
||
_ => Err(reject(StatusCode::FORBIDDEN, "缺少有效内部凭证")),
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use axum::body::Body;
|
||
use axum::http::HeaderValue;
|
||
use axum::middleware;
|
||
use axum::Extension;
|
||
use axum::Router;
|
||
use http_body_util::BodyExt;
|
||
use tower::ServiceExt;
|
||
|
||
/// 测试用的内部令牌。
|
||
const TEST_INTERNAL_TOKEN: &str = "secret-internal";
|
||
|
||
/// 把 `Response` 的 body 读成 `serde_json::Value`(测试内私有 helper)。
|
||
async fn resp_body_json(resp: Response) -> serde_json::Value {
|
||
let bytes = resp
|
||
.into_body()
|
||
.collect()
|
||
.await
|
||
.expect("应能读出 body")
|
||
.to_bytes();
|
||
serde_json::from_slice(&bytes).expect("body 必须是合法 JSON")
|
||
}
|
||
|
||
#[test]
|
||
fn ant_match_handles_star_and_double_star() {
|
||
assert!(ant_match(
|
||
"/api/ssw/tdc/Auth/Login",
|
||
"/api/ssw/tdc/Auth/Login"
|
||
));
|
||
assert!(!ant_match(
|
||
"/api/ssw/tdc/Auth/Login",
|
||
"/api/ssw/tdc/Auth/Me"
|
||
));
|
||
assert!(ant_match(
|
||
"/api/ssw/tdc/P2P/Download/*",
|
||
"/api/ssw/tdc/P2P/Download/abc"
|
||
));
|
||
assert!(!ant_match(
|
||
"/api/ssw/tdc/P2P/Download/*",
|
||
"/api/ssw/tdc/P2P/Download/a/b"
|
||
));
|
||
assert!(ant_match("/api/ssw/tdc/Portal/**", "/api/ssw/tdc/Portal"));
|
||
assert!(ant_match(
|
||
"/api/ssw/tdc/Portal/**",
|
||
"/api/ssw/tdc/Portal/a/b/c"
|
||
));
|
||
assert!(ant_match("/static/**", "/static/app.js"));
|
||
assert!(ant_match(
|
||
"/api/ssw/tdc/P2P/Transfer/*/Chunk",
|
||
"/api/ssw/tdc/P2P/Transfer/t1/Chunk"
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn ant_match_keeps_trailing_slash_significant_like_spring() {
|
||
// Spring AntPathMatcher 实测
|
||
assert!(!ant_match("/api/oauth/Login", "/api/oauth/Login/"));
|
||
assert!(!ant_match("/api/health", "/api/health/"));
|
||
assert!(ant_match("/api/oauth/Login/", "/api/oauth/Login/"));
|
||
assert!(ant_match("/api/oauth/Login", "/api/oauth/Login"));
|
||
// `**` 匹配零段(既有语义不许被改坏)
|
||
assert!(ant_match("/api/ssw/tdc/Portal/**", "/api/ssw/tdc/Portal"));
|
||
}
|
||
|
||
#[test]
|
||
fn white_url_covers_upstream_list_plus_local_extras() {
|
||
assert!(is_white_url("/api/oauth/Login"));
|
||
assert!(is_white_url("/api/ssw/tdc/Auth/Login"));
|
||
assert!(is_white_url("/api/ssw/tdc/Auth/SsoConfig"));
|
||
assert!(is_white_url("/api/ssw/tdc/Topology/Internal/TopologyCheck"));
|
||
assert!(is_white_url("/api/health"));
|
||
assert!(!is_white_url("/api/ssw/tdc/Product"));
|
||
assert!(!is_white_url("/api/ssw/tdc/Auth/Me"));
|
||
}
|
||
|
||
#[test]
|
||
fn non_api_paths_are_never_authenticated() {
|
||
// 上游完整前端是 SPA:深链(/login、/tdc/home)与静态资源(/assets/**)不经业务鉴权
|
||
assert!(!uri_path_is_guarded("/login"));
|
||
assert!(!uri_path_is_guarded("/tdc/home"));
|
||
assert!(!uri_path_is_guarded("/assets/index-B9U_HuT1.js"));
|
||
assert!(!uri_path_is_guarded("/logo.png"));
|
||
assert!(uri_path_is_guarded("/api/ssw/tdc/Product"));
|
||
assert!(uri_path_is_guarded("/api/oauth/Login"));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn reject_body_has_no_data_and_has_success_false() {
|
||
let resp = reject(StatusCode::UNAUTHORIZED, "内部接口凭证无效");
|
||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||
|
||
// 🔴 鉴权失败的 body 形状与业务信封不同:裸三字段、**没有 data**。
|
||
// 只断言 HTTP 状态不够(业务错误也是 HTTP 200 + {code,msg,data})。
|
||
let v = resp_body_json(resp).await;
|
||
let obj = v.as_object().expect("body 必须是 JSON 对象");
|
||
assert_eq!(obj.len(), 3, "鉴权失败 body 恰好三个键,实际 {:?}", obj);
|
||
assert_eq!(obj.get("success"), Some(&serde_json::json!(false)));
|
||
assert_eq!(obj.get("code"), Some(&serde_json::json!(401)));
|
||
assert_eq!(obj.get("msg"), Some(&serde_json::json!("内部接口凭证无效")));
|
||
assert!(
|
||
obj.get("data").is_none(),
|
||
"鉴权失败 body 不得含 data 键,实际 {:?}",
|
||
obj
|
||
);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn reject_body_code_always_equals_http_status() {
|
||
for (status, expect) in [
|
||
(StatusCode::UNAUTHORIZED, 401u16),
|
||
(StatusCode::FORBIDDEN, 403u16),
|
||
] {
|
||
let resp = reject(status, "凭证无效");
|
||
assert_eq!(resp.status(), status);
|
||
// 裸三字段:恰好 {success, code, msg},**无 data**
|
||
let body = resp_body_json(resp).await;
|
||
assert_eq!(body["code"], expect);
|
||
assert_eq!(body["success"], false);
|
||
assert_eq!(body["msg"], "凭证无效");
|
||
assert!(body.get("data").is_none(), "鉴权失败不得有 data 字段");
|
||
assert_eq!(body.as_object().unwrap().len(), 3, "裸三字段");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn internal_only_accepts_only_the_internal_channel() {
|
||
let internal = Principal::Internal { operator: None };
|
||
let session = Principal::Session {
|
||
identity_id: "i".into(),
|
||
identity_code: "c".into(),
|
||
};
|
||
assert!(require_internal_only(Some(&internal)).is_ok());
|
||
assert!(require_internal_only(Some(&session)).is_err());
|
||
assert!(require_internal_only(None).is_err());
|
||
}
|
||
|
||
#[test]
|
||
fn menu_permission_accepts_internal_or_session() {
|
||
let internal = Principal::Internal { operator: None };
|
||
let session = Principal::Session {
|
||
identity_id: "i".into(),
|
||
identity_code: "c".into(),
|
||
};
|
||
let account = Principal::Account {
|
||
account_id: "u".into(),
|
||
account: "admin".into(),
|
||
};
|
||
assert!(require_menu_permission(Some(&internal)).is_ok());
|
||
assert!(require_menu_permission(Some(&session)).is_ok());
|
||
assert!(require_menu_permission(Some(&account)).is_ok());
|
||
assert!(require_menu_permission(None).is_err());
|
||
}
|
||
|
||
#[test]
|
||
fn menu_gate_and_internal_or_user_gate_are_independent() {
|
||
let internal = Some(Principal::Internal { operator: None });
|
||
let session = Some(Principal::Session {
|
||
identity_id: "I-1".to_string(),
|
||
identity_code: "C-1".to_string(),
|
||
});
|
||
let account = Some(Principal::Account {
|
||
account_id: "A-1".to_string(),
|
||
account: "admin".to_string(),
|
||
});
|
||
// 今天的语义:两个闸门对三种主体都放行,对 None 都 403
|
||
for p in [internal.clone(), session.clone(), account.clone()] {
|
||
assert!(require_menu_permission(p.as_ref()).is_ok());
|
||
assert!(require_internal_or_user(p.as_ref()).is_ok());
|
||
}
|
||
assert_eq!(
|
||
require_menu_permission(None).unwrap_err().status(),
|
||
StatusCode::FORBIDDEN
|
||
);
|
||
assert_eq!(
|
||
require_internal_or_user(None).unwrap_err().status(),
|
||
StatusCode::FORBIDDEN
|
||
);
|
||
}
|
||
|
||
/// 🔴 **V1 判别器的另一半**:只测 `require_internal_or_user`。
|
||
///
|
||
/// 当 `require_menu_permission` 被临时收紧成「只放行 `Principal::Internal`」时,
|
||
/// 本用例必须**仍全绿**(⇒ 两个闸门已解耦,不是别名)。
|
||
#[test]
|
||
fn internal_or_user_gate_alone_stays_permissive() {
|
||
let internal = Principal::Internal { operator: None };
|
||
let session = Principal::Session {
|
||
identity_id: "I-1".into(),
|
||
identity_code: "C-1".into(),
|
||
};
|
||
let account = Principal::Account {
|
||
account_id: "A-1".into(),
|
||
account: "admin".into(),
|
||
};
|
||
assert!(require_internal_or_user(Some(&internal)).is_ok());
|
||
assert!(require_internal_or_user(Some(&session)).is_ok());
|
||
assert!(require_internal_or_user(Some(&account)).is_ok());
|
||
assert_eq!(
|
||
require_internal_or_user(None).unwrap_err().status(),
|
||
StatusCode::FORBIDDEN
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn session_token_reads_x_auth_token_then_bearer_authorization() {
|
||
let mut h = HeaderMap::new();
|
||
assert!(session_token(&h).is_none());
|
||
h.insert(
|
||
AUTHORIZATION_HEADER,
|
||
HeaderValue::from_static("Bearer abc123"),
|
||
);
|
||
assert_eq!(session_token(&h), Some("abc123"));
|
||
let mut h2 = HeaderMap::new();
|
||
h2.insert(AUTHORIZATION_HEADER, HeaderValue::from_static("bearer xyz"));
|
||
assert_eq!(session_token(&h2), Some("xyz"));
|
||
let mut h3 = HeaderMap::new();
|
||
h3.insert(AUTHORIZATION_HEADER, HeaderValue::from_static("Basic abc"));
|
||
assert!(session_token(&h3).is_none());
|
||
let mut h4 = HeaderMap::new();
|
||
h4.insert(AUTH_TOKEN_HEADER, HeaderValue::from_static("tok"));
|
||
assert_eq!(session_token(&h4), Some("tok"));
|
||
}
|
||
|
||
// ------------------------------------------------------------------
|
||
// 路由级测试:中间件 5 步顺序的真实行为
|
||
// ------------------------------------------------------------------
|
||
|
||
/// 受保护路由的 handler:把 extensions 里读到的 `Principal` 报出来。
|
||
///
|
||
/// 🔴 `Option<Extension<Principal>>` —— axum 的 `Extension<T>` 读的就是**裸类型 `T`**
|
||
/// (extensions 里的键就是 `Principal` 本身)⇒ 与中间件 `req.extensions_mut().insert(principal)`
|
||
/// 的写入口径一致。
|
||
async fn protected_handler(p: Option<Extension<Principal>>) -> String {
|
||
match p {
|
||
Some(Extension(Principal::Internal { .. })) => "PROTECTED:INTERNAL".to_string(),
|
||
Some(Extension(Principal::Session { .. })) => "PROTECTED:SESSION".to_string(),
|
||
Some(Extension(Principal::Account { .. })) => "PROTECTED:ACCOUNT".to_string(),
|
||
None => "PROTECTED:NONE".to_string(),
|
||
}
|
||
}
|
||
|
||
/// 造 3 条路由的测试应用:白名单 / 受保护 / SPA 深链。
|
||
///
|
||
/// 返回 `(Router, 本地账号会话令牌)`。
|
||
fn test_app() -> (Router, String) {
|
||
let sessions = Arc::new(SessionStore::new());
|
||
// 造 token 的那份 SessionStore 与放进 AuthState 的**必须是同一个 Arc**
|
||
let token = sessions.create_account("A-1", "admin");
|
||
let state = AuthState {
|
||
internal_token: TEST_INTERNAL_TOKEN.to_string(),
|
||
sessions,
|
||
};
|
||
let app: Router = Router::new()
|
||
.route(
|
||
"/api/ssw/tdc/Auth/Login",
|
||
axum::routing::get(|| async { "WHITE" }),
|
||
)
|
||
.route(
|
||
"/api/ssw/tdc/Product",
|
||
axum::routing::get(protected_handler),
|
||
)
|
||
.route("/tdc/home", axum::routing::get(|| async { "SPA" }))
|
||
.layer(middleware::from_fn_with_state(state, auth_middleware));
|
||
(app, token)
|
||
}
|
||
|
||
/// 打一个请求,返回 `(状态码, body 文本)`。
|
||
async fn call(app: Router, req: axum::http::Request<Body>) -> (StatusCode, String) {
|
||
let resp = app.oneshot(req).await.expect("服务不应出错");
|
||
let status = resp.status();
|
||
let bytes = resp
|
||
.into_body()
|
||
.collect()
|
||
.await
|
||
.expect("应能读出 body")
|
||
.to_bytes();
|
||
let text = String::from_utf8_lossy(&bytes).to_string();
|
||
(status, text)
|
||
}
|
||
|
||
fn get(uri: &str) -> axum::http::Request<Body> {
|
||
build_req(uri, &[])
|
||
}
|
||
|
||
/// 造一个带若干头的 GET 请求。
|
||
fn build_req(uri: &str, headers: &[(&str, &str)]) -> axum::http::Request<Body> {
|
||
let mut builder = axum::http::Request::builder().uri(uri);
|
||
for (k, v) in headers {
|
||
builder = builder.header(*k, *v);
|
||
}
|
||
builder.body(Body::empty()).expect("请求应能构造")
|
||
}
|
||
|
||
/// a:白名单路径、无任何凭证 ⇒ 到达 handler(② 先于 ⑤)。
|
||
#[tokio::test]
|
||
async fn route_white_url_reaches_handler_without_credentials() {
|
||
let (app, _token) = test_app();
|
||
let (status, body) = call(app, get("/api/ssw/tdc/Auth/Login")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(body, "WHITE");
|
||
}
|
||
|
||
/// b:正确的 `X-Internal-Token` ⇒ 到达 handler(③)。
|
||
///
|
||
/// ⚠️ 显式声明兼容的协议版本:`check_protocol(None)` 会去抢全局的一次性告警 key
|
||
/// (`protocol:missing`),与 `protocol` 模块自己的用例并发 ⇒ 偶发互相干扰。
|
||
/// 这里只关心「内部令牌通道放行」这一件事,版本声明成兼容值即可。
|
||
#[tokio::test]
|
||
async fn route_internal_token_reaches_handler() {
|
||
let (app, _token) = test_app();
|
||
let req = build_req(
|
||
"/api/ssw/tdc/Product",
|
||
&[
|
||
(INTERNAL_TOKEN_HEADER, TEST_INTERNAL_TOKEN),
|
||
(PROTOCOL_VERSION_HEADER, "1.0"),
|
||
],
|
||
);
|
||
let (status, body) = call(app, req).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
// h:内部令牌通道 ⇒ extensions 里的主体是 `Principal::Internal`
|
||
assert_eq!(body, "PROTECTED:INTERNAL");
|
||
}
|
||
|
||
/// c:内部令牌 + 不兼容的协议版本 ⇒ HTTP 401(协议闸门只作用在内部令牌通道)。
|
||
#[tokio::test]
|
||
async fn route_internal_token_with_incompatible_protocol_is_rejected() {
|
||
let (app, _token) = test_app();
|
||
let req = build_req(
|
||
"/api/ssw/tdc/Product",
|
||
&[
|
||
(INTERNAL_TOKEN_HEADER, TEST_INTERNAL_TOKEN),
|
||
// 用一个**本模块专属**的不兼容版本串 ⇒ 不与 protocol 模块用例抢告警 key
|
||
(PROTOCOL_VERSION_HEADER, "7.7"),
|
||
],
|
||
);
|
||
let (status, body) = call(app, req).await;
|
||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||
assert!(
|
||
body.contains("跨端协议版本不兼容,请升级对端"),
|
||
"msg 应说明协议不兼容,实际 {}",
|
||
body
|
||
);
|
||
}
|
||
|
||
/// d:有效会话令牌 + 不兼容的协议版本 ⇒ **仍然到达 handler**
|
||
/// ⇒ 协议闸门**只**作用在内部令牌通道(与上游注释一致)。
|
||
#[tokio::test]
|
||
async fn route_session_token_ignores_protocol_gate() {
|
||
let (app, token) = test_app();
|
||
let req = build_req(
|
||
"/api/ssw/tdc/Product",
|
||
&[
|
||
(AUTHORIZATION_HEADER, &format!("bearer {}", token)),
|
||
(PROTOCOL_VERSION_HEADER, "7.7"),
|
||
],
|
||
);
|
||
let (status, body) = call(app, req).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
// h:会话通道 ⇒ extensions 里的主体是 `Principal::Account`
|
||
assert_eq!(body, "PROTECTED:ACCOUNT");
|
||
}
|
||
|
||
/// e:无凭证 ⇒ HTTP 401,body 恰好三键、**无 `data`**。
|
||
#[tokio::test]
|
||
async fn route_without_credentials_is_rejected_with_bare_three_field_body() {
|
||
let (app, _token) = test_app();
|
||
let resp = app
|
||
.oneshot(get("/api/ssw/tdc/Product"))
|
||
.await
|
||
.expect("服务不应出错");
|
||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||
let v = resp_body_json(resp).await;
|
||
let obj = v.as_object().expect("body 必须是 JSON 对象");
|
||
assert_eq!(obj.len(), 3, "鉴权失败 body 恰好三个键,实际 {:?}", obj);
|
||
assert_eq!(obj.get("success"), Some(&serde_json::json!(false)));
|
||
assert_eq!(obj.get("code"), Some(&serde_json::json!(401)));
|
||
assert!(obj.get("data").is_none(), "鉴权失败不得有 data 键");
|
||
}
|
||
|
||
/// f:`/tdc/home`(非 `/api/`)、无凭证 ⇒ 到达 handler(①.5 生效:SPA 深链不鉴权)。
|
||
#[tokio::test]
|
||
async fn route_spa_deep_link_is_not_authenticated() {
|
||
let (app, _token) = test_app();
|
||
let (status, body) = call(app, get("/tdc/home")).await;
|
||
assert_eq!(status, StatusCode::OK);
|
||
assert_eq!(body, "SPA");
|
||
}
|
||
|
||
/// g:**无效**会话令牌 ⇒ HTTP 401。
|
||
#[tokio::test]
|
||
async fn route_with_invalid_session_token_is_rejected() {
|
||
let (app, _token) = test_app();
|
||
let req = build_req(
|
||
"/api/ssw/tdc/Product",
|
||
&[(AUTHORIZATION_HEADER, "bearer deadbeef")],
|
||
);
|
||
let (status, _body) = call(app, req).await;
|
||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||
}
|
||
}
|