diff --git a/src/cache.rs b/src/cache.rs index f32b91e..dde55d9 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -534,7 +534,7 @@ fn auth_header_for(r: *mut ngx_http_request_t, configured: &str, allow_client: b Some(v) => v.trim().to_owned(), None => return String::new(), }; - let Some(dk) = ipass_core::auth::downstream_key(r) else { + let Some(dk) = crate::key::downstream_key(r) else { // 客户端没带网关 Key → 原样透传(如纯 x-api-key 场景) return raw; }; diff --git a/src/handlers.rs b/src/handlers.rs index 95e4537..9aa63fd 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -293,6 +293,21 @@ fn cool_down_failed(r: *mut ngx_http_request_t) { // access:统一 Key 鉴权 + 上游就绪检查 // =========================================================================== +/// 401 响应:**必须带 `WWW-Authenticate`**,否则客户端不知道凭据怎么带。 +/// +/// core 的 `http::fail` 硬编码 `&[]`(加不了响应头)⇒ 这里自己拼。 +/// cargo 不依赖这个头(它靠 config.json 里的 `auth-required` 决定是否附带 token), +/// 但 curl / npm / pip 这类客户端靠它触发「带凭据重试」。 +fn fail_401(r: *mut ngx_http_request_t, msg: &str) -> Status { + let body = serde_json::json!({ "code": 401, "msg": msg }).to_string(); + http::send_with( + r, + HTTPStatus::UNAUTHORIZED, + &body, + &[("WWW-Authenticate", "Bearer realm=\"ipass-cache\"")], + ) +} + /// 制品缓存 access handler。受管制 URI 由路由表(8 前缀)圈定; /// R19 禁用 → fail-closed 404(数据面是鉴权后的磁盘读,放行=无鉴权读缓存盘)。 pub struct CacheAccessHandler; @@ -341,10 +356,11 @@ impl HttpRequestHandler for CacheAccessHandler { } // ---- 统一 Key 鉴权(与 LLM / API 代理同一把 sk_、同一份配额)---- - let Some(key) = auth::downstream_key(r) else { - return http::fail( + // 携带方式:Authorization: Bearer sk_… / Authorization: sk_…(cargo 裸 token) + // / x-api-key: sk_… / api-key: sk_… + let Some(key) = crate::key::downstream_key(r) else { + return fail_401( r, - HTTPStatus::UNAUTHORIZED, "缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带", ); }; @@ -353,7 +369,7 @@ impl HttpRequestHandler for CacheAccessHandler { "[cache] API Key 校验失败 route={route} client={}", http::remote_addr(r) )); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效"); + return fail_401(r, "API Key 无效或已失效"); }; // ⚠️ 换源链的每一跳都会**重跑 ACCESS 阶段**(nginx 1.30.4 的 diff --git a/src/key.rs b/src/key.rs new file mode 100644 index 0000000..f75f7aa --- /dev/null +++ b/src/key.rs @@ -0,0 +1,51 @@ +//! 下行 Key 的**携带方式**解析(缓存插件自己的口径)。 +//! +//! ## 为什么不在 core 里改 +//! +//! 内核 `ipass_core::auth::downstream_key` 是**全平台共用**的口径: +//! `Authorization: Bearer ` / `x-api-key` / `api-key`。 +//! 改它会波及 ipass-all / ipass-sso 的 LLM、apix 等所有路径 ⇒ 爆炸半径太大。 +//! 缓存插件**只多认一种携带方式**,且取到的值照样要过 +//! `auth::identity(&key)`(比对 shm 的 `ukey:` 索引)⇒ **不构成任何授权绕过**。 +//! +//! ## 多认的那一种:裸 token +//! +//! cargo 客户端发的是**裸 token**(不是 `Bearer ` 前缀): +//! +//! ```text +//! Authorization: sk_xxxxxxxx +//! ``` +//! +//! 源码依据(cargo 0.100.0 `src/util/auth/mod.rs`):token 以 +//! `token.expose()` 取值后**直接**放进 `AUTHORIZATION` 头, +//! 中间不拼任何 scheme ⇒ core 的 `downstream_key` 认不出来 ⇒ +//! cargo 全程 401,装不上任何 crate。 +//! +//! ## 安全边界 +//! +//! * 裸值本身**不是凭据**:仍须 `auth::identity()` 命中 shm 索引。 +//! * 已排除常见认证方案前缀(Basic / Token / Digest / Negotiate), +//! 免得把别家客户端的凭据格式误当成 key(虽然最终仍会被 identity 拒掉, +//! 但错误信息会变得难以排查)。 + +use ipass_core::{auth, http}; +use ngx::ffi::ngx_http_request_t; + +/// 取下行 Key:core 的三种携带方式 + **裸 `Authorization: `**。 +/// +/// 返回的字符串**还要**过 `auth::identity(&key)` 才能变成身份。 +pub fn downstream_key(r: *mut ngx_http_request_t) -> Option { + if let Some(k) = auth::downstream_key(r) { + return Some(k); + } + let raw = http::header(r, "authorization")?.trim().to_owned(); + if raw.is_empty() || raw.contains(char::is_whitespace) { + return None; + } + const SCHEMES: [&str; 4] = ["basic", "token", "digest", "negotiate"]; + let head = raw.split(':').next().unwrap_or("").to_ascii_lowercase(); + if SCHEMES.contains(&head.as_str()) { + return None; + } + Some(raw) +} diff --git a/src/lib.rs b/src/lib.rs index 3b5f7c6..95e6b1b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,6 +38,7 @@ pub mod api; pub mod cache; pub mod config; pub mod handlers; +pub mod key; pub mod models; pub mod stats; pub mod store;