fix(auth): 闸门解耦 + 拒绝体自洽 + 白名单尾斜杠对齐 Spring

- require_internal_or_user 改成独立 match 臂,不再是 require_menu_permission 的别名
  (上游两者语义不同;别名会让 Task 12 收紧菜单检查时连坐收紧数据面闸门)
- reject() 改成显式传 HTTP 状态,body 的 code 由状态推出 ⇒ 结构上不可能错配
- ant_match 只去前导斜杠,尾斜杠保持显著(对齐 Spring AntPathMatcher)
- 补路由级中间件测试:白名单/内部令牌/协议闸门只作用内部通道/会话通道/SPA 深链/401 形状
- 补三个断言型测试:闸门独立性、拒绝体 code==状态、尾斜杠语义

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
adminandClaude Code committed 2026-10-24 19:24:37 +08:00
1 parent aea73ab040
commit c95b9d6e10
3 files changed
+332 -22

No files matched your search

Generated
+2
View File
@@ -1582,12 +1582,14 @@ dependencies = [
"chrono",
"ed25519-dalek",
"hex",
"http-body-util",
"pglite-rs",
"rand 0.8.8",
"reqwest",
"serde",
"serde_json",
"tokio",
"tower",
"tower-http",
]
+5
View File
@@ -33,6 +33,11 @@ pglite-rs = "0.2"
# 真实 UTC 时间戳(last_heartbeat / 同步日志用,避免手写日历换算)
chrono = { version = "0.4", default-features = false, features = ["clock"] }
[dev-dependencies]
# 路由级中间件测试(Task 5 fix round 1):`tower::ServiceExt::oneshot` 打请求
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
[profile.release]
opt-level = 2
lto = "thin"
+325 -22
View File
@@ -69,9 +69,13 @@ pub struct AuthState {
}
/// 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_matches('/').split('/').collect();
let s: Vec<&str> = path.trim_matches('/').split('/').collect();
let p: Vec<&str> = pattern.trim_start_matches('/').split('/').collect();
let s: Vec<&str> = path.trim_start_matches('/').split('/').collect();
match_segments(&p, &s)
}
@@ -133,12 +137,17 @@ pub fn uri_path_is_guarded(path: &str) -> bool {
/// ```json
/// {"success": false, "code": 401, "msg": "内部接口凭证无效"}
/// ```
pub fn reject(code: u16, msg: &str) -> Response {
let status = StatusCode::from_u16(code).unwrap_or(StatusCode::UNAUTHORIZED);
///
/// 🔴 **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": code, "msg": msg}).to_string(),
json!({"success": false, "code": status.as_u16(), "msg": msg}).to_string(),
)
.into_response()
}
@@ -173,7 +182,7 @@ pub async fn auth_middleware(
if !token.is_empty() && token == auth.internal_token {
let declared = header_str(&headers, PROTOCOL_VERSION_HEADER);
if !check_protocol(declared) {
return reject(401, "跨端协议版本不兼容,请升级对端");
return reject(StatusCode::UNAUTHORIZED, "跨端协议版本不兼容,请升级对端");
}
let operator = header_str(&headers, OPERATOR_HEADER).map(|s| s.to_string());
req.extensions_mut().insert(Principal::Internal { operator });
@@ -200,7 +209,7 @@ pub async fn auth_middleware(
}
}
// ⑤ 都不满足
reject(401, "内部接口凭证无效")
reject(StatusCode::UNAUTHORIZED, "内部接口凭证无效")
}
/// 会话令牌来源:`X-Auth-Token`,或 `Authorization: bearer <token>`。
@@ -224,39 +233,87 @@ pub fn session_token(headers: &HeaderMap) -> Option<&str> {
}
}
/// 控制器层三道门(上游 `requireMenuPermission` / `requireInternalOrUser` / `requireInternalOnly`)。
/// 是否已有可用的操作主体(内部令牌 / 连接器身份会话 / 本地账号会话)。
fn has_principal(p: Option<&Principal>) -> bool {
matches!(
p,
Some(Principal::Internal { .. })
| Some(Principal::Session { .. })
| Some(Principal::Account { .. })
)
}
/// 控制器层菜单权限闸门(上游 `requireMenuPermission`)。
///
/// 菜单权限依赖 j7 框架库(已排除)⇒ **fail-open**:登录身份与内部令牌都放行。
/// 🔴 **菜单权限检查因 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> {
match p {
Some(Principal::Internal { .. })
| Some(Principal::Session { .. })
| Some(Principal::Account { .. }) => Ok(()),
None => Err(reject(403, "缺少有效凭证(需登录或内部凭证)")),
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> {
require_menu_permission(p)
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(403, "缺少有效内部凭证")),
_ => 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() {
@@ -270,6 +327,17 @@ mod tests {
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"));
@@ -294,16 +362,12 @@ mod tests {
#[tokio::test]
async fn reject_body_has_no_data_and_has_success_false() {
let resp = reject(401, "内部接口凭证无效");
let resp = reject(StatusCode::UNAUTHORIZED, "内部接口凭证无效");
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
// 🔴 鉴权失败的 body 形状与业务信封不同:裸三字段、**没有 data**。
// 只断言 HTTP 状态不够(业务错误也是 HTTP 200 + {code,msg,data})。
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.expect("应能读出 body");
let v: serde_json::Value =
serde_json::from_slice(&body).expect("body 必须是合法 JSON");
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)));
@@ -316,6 +380,24 @@ mod tests {
);
}
#[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 };
@@ -336,6 +418,50 @@ mod tests {
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();
@@ -352,4 +478,181 @@ mod tests {
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);
}
}