Files
ipass-plugin-cache/src/handlers.rs
T
adminandClaude Code fefd57ac7f feat(cache): 打通 cargo 客户端路径(裸 token + 401 带 WWW-Authenticate)
cargo 客户端此前有三处独立断裂,任一处都足以让它全程 401、装不上 crate:

1. cargo 发的是**裸 token**(Authorization: sk_…,**无 Bearer 前缀**)
   ⇒ core 的 auth::downstream_key 认不出来。
   core 是 ipass-all / ipass-sso 的 LLM / apix 共用口径,改它爆炸半径太大
   ⇒ 插件内新增 src/key.rs:core 的三种携带方式 + 裸 Authorization
   (已排除 Basic/Token/Digest/Negotiate 前缀)。
   取到的值**仍须过 auth::identity()**(比对 shm 的 ukey: 索引)
   ⇒ 不构成任何授权绕过。
2. 客户端不带凭据去拉索引 ⇒ 网关 401,而 cargo 不会重试。
   修法在网关自发的 config.json 里:加 "auth-required": true,
   cargo 才会给**每个**请求(索引文件 + .crate 下载)附 token
   (cargo 0.100.0 http_remote.rs:522-532 / download.rs:67)。
3. 换源链每跳会重跑 ACCESS 阶段 ⇒ 裸 sk_ 必须与 Bearer 形态同等处理:
   cache.rs 的「客户端 Authorization 是不是本网关的 sk_」改用同一个解析器,
   否则裸 token 会被透传给上游源。

另:401 改为插件自己发(core 的 http::fail 硬编码 &[],加不了响应头),
带 WWW-Authenticate: Bearer realm="ipass-cache";
nginx 侧那三处 add_header 已删除(会叠加成重复头,且对 200 也生效)。

Co-Authored-By: Claude Code <[email protected]>
2026-10-31 12:13:03 +08:00

433 lines
21 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 缓存插件的两个 phase handler。
//!
//! * **access**([`CacheAccessHandler`]):统一 `sk_` Key 鉴权 → 查上游表 →
//! 配额校验 → 放行给 nginx 的 `proxy_cache` 数据面。
//! * **log**([`CacheLogHandler`]):读 `$upstream_cache_status`,按生态记账。
//!
//! ## 为什么鉴权在 access 而计量在 log
//!
//! 鉴权必须早于数据面(access 阶段),否则未授权的请求会白白拉一遍上游;
//! 而**命中与否**只有在代理模块把响应交给客户端之后才最终确定(`HIT` 是
//! 「本次没回源」,由缓存模块在响应阶段判定),access 阶段拿不到。
//! 这与 plugin-llm 的 `LlmHealthHandler` 同构——真实流量自己当探针。
//!
//! ## 缓存为什么是「共享」的
//!
//! `proxy_cache_key` 由 [`crate::cache`] 的 `$cache_key` 给出 = `<route>:<uri>`,
//! **不含用户的 `sk_`**。这是刻意的:同一份 go module / npm 包被 N 个账号拉取时,
//! 只应该回源一次——制品缓存的价值就在这里。鉴权在 access 层做(谁能读),
//! 数据在共享层复用(读什么不必各存一份)。
//!
//! 代价:任一有效 Key 都能命中别人拉过的制品。对公开 registry 无碍;
//! 若某路由指向**私有**上游,请理解这一点再启用(见 docs 的边界说明)。
use core::sync::atomic::{AtomicIsize, Ordering};
use ngx::core::Status;
use ngx::ffi::{
ngx_conf_t, ngx_http_get_indexed_variable, ngx_http_get_variable, ngx_http_get_variable_index,
ngx_http_request_t, ngx_str_t, ngx_uint_t,
};
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
use ipass_core::{auth, http, plugin_registry, util};
use crate::cache;
use crate::config;
use crate::stats;
/// `$upstream_cache_status` 的变量索引(postconfig 解析一次,log 阶段复用)
static CACHE_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
/// `$scheme` 的变量索引(管理 API 拼「下游地址」时要回显 http/https)
static SCHEME_IDX: AtomicIsize = AtomicIsize::new(-1);
/// `$request_id` 的变量索引(选源散列用)。**可选**:拿不到就退化为 URI 散列。
static REQUEST_ID_IDX: AtomicIsize = AtomicIsize::new(-1);
/// postconfiguration:预取**五个**变量索引。失败返回 false,gateway 会 EMERG 退出。
///
/// 五个是:`$upstream_cache_status`、`$scheme`、`$request_id`(**可选**)、
/// `$cache_pick`、以及内部变量 `$cache_ctx`。
///
/// 为什么在 postconfig 而不是 preconfig:`$scheme` 是 core 模块的内建变量,
/// 本模块的 preconfig 早于变量全部注册完成,取 index 可能失败;postconfig
/// 时所有模块的变量都已就位(与 plugin-llm 取 `$upstream_status` 同一时机)。
pub fn prefetch_indexes(cf: *mut ngx_conf_t) -> bool {
let mut cs = ngx_str_t {
len: "upstream_cache_status".len() as usize,
data: b"upstream_cache_status\0".as_ptr() as *mut u8,
};
let mut sc = ngx_str_t {
len: "scheme".len() as usize,
data: b"scheme\0".as_ptr() as *mut u8,
};
// SAFETY: cf 由 nginx 传入且有效;两个 ngx_str_t 指向栈上合法内存
let i1 = unsafe { ngx_http_get_variable_index(cf, &mut cs) };
let i2 = unsafe { ngx_http_get_variable_index(cf, &mut sc) };
if i1 < 0 || i2 < 0 {
return false;
}
CACHE_STATUS_IDX.store(i1 as isize, Ordering::Relaxed);
SCHEME_IDX.store(i2 as isize, Ordering::Relaxed);
// `$request_id` 是**可选**的:拿不到就退化为 URI 散列(见 cache::hash_of_request),
// 因此这里解析失败**不致命**——与上面两个不同,它们缺了会让核心功能不可用。
let mut rid = ngx_str_t {
len: "request_id".len() as usize,
data: b"request_id\0".as_ptr() as *mut u8,
};
// SAFETY: cf 由 nginx 传入且有效;ngx_str_t 指向栈上合法内存
let i3 = unsafe { ngx_http_get_variable_index(cf, &mut rid) };
REQUEST_ID_IDX.store(i3 as isize, Ordering::Relaxed);
// `$cache_pick`(本插件自己注册的变量)——运行时按**索引**读,
// 不用 ngx_http_get_variable 的名字查找(那个 API 的 key 是哈希桶号,
// 传 0 会间歇性查不中,详见 cache::read_pick_var 的注释)。
let mut cp = ngx_str_t {
len: "cache_pick".len() as usize,
data: b"cache_pick\0".as_ptr() as *mut u8,
};
// SAFETY: cf 由 nginx 传入且有效;ngx_str_t 指向栈上合法内存
let i4 = unsafe { ngx_http_get_variable_index(cf, &mut cp) };
if i4 < 0 {
return false;
}
crate::cache::set_pick_index(i4 as isize);
// 内部变量 `$cache_ctx`(请求级 memo 的载体)——同样按索引读。
if !crate::cache::prefetch_memo_index(cf) {
return false;
}
true
}
/// 读当前请求的 `$scheme`(拿不到返回空串,调用方回落 `http`)。
pub fn read_scheme(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 由 nginx 传入且有效;索引在 postconfig 已解析
unsafe { read_indexed(r, SCHEME_IDX.load(Ordering::Relaxed)) }
}
/// 读当前请求的 `$request_id`(空串 = 拿不到,调用方自行退化)
pub fn read_request_id(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 由 nginx 传入且有效;索引在 postconfig 已解析
unsafe { read_indexed(r, REQUEST_ID_IDX.load(Ordering::Relaxed)) }
}
/// 安全读取一个已索引变量的字符串值;拿不到返回空串。
unsafe fn read_indexed(r: *mut ngx_http_request_t, idx: isize) -> String {
if idx < 0 {
return String::new();
}
let v = ngx_http_get_indexed_variable(r, idx as ngx_uint_t);
if v.is_null() || (*v).not_found() != 0 || (*v).data.is_null() {
return String::new();
}
let len = (*v).len() as usize;
if len == 0 {
return String::new();
}
String::from_utf8_lossy(core::slice::from_raw_parts((*v).data, len)).into_owned()
}
/// 读当前请求的 `$upstream_cache_status`(供管理 API / 排障复用)
pub fn read_cache_status(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 由 nginx 传入且有效;索引在 postconfig 已解析
unsafe { read_indexed(r, CACHE_STATUS_IDX.load(Ordering::Relaxed)) }
}
// ===========================================================================
// log:把失败的源打入冷却(熔断)
// ===========================================================================
/// 读换源链写下的「失败顺位」响应头 `$sent_http_x_cache_failed_slot`。
///
/// 契约(由 nginx conf 保证):换源链的命名 location 里
/// `add_header X-Cache-Failed-Slot "<顺位>" always;`
/// ——「我这一跳是第几跳」=「上一跳(及更早)失败了」。
/// 拿不到 = 本次没有失败过(正常命中或一次成功)。
///
/// ⚠️ 这里 `ngx_http_get_variable(r, name, 0)` 的 `key = 0` **是安全的**,
/// 与 Task 4 的 `$cache_pick` 不同——因为 `sent_http_` 是 nginx 的
/// **前缀变量**(`ngx_http_variables.c:399` 注册):
/// `ngx_http_get_variable()` 先查 `variables_hash`(查不到),
/// 再落到 `cmcf->prefix_variables` 兜底(src/http/ngx_http_variables.c:727-750),
/// 这条路径**不看 `key`** ⇒ 传 0 无所谓。
/// 反过来,**普通变量**(像 `$cache_pick`)走的就是 `variables_hash`
/// 那条路,`key` 是哈希桶号 ⇒ 必须用索引读,别照抄这里的写法。
///
/// 头名映射:nginx 把响应头名小写并把 `-` 换成 `_` 后比较
/// (src/http/ngx_http_variables.c:971-984),
/// 所以 `X-Cache-Failed-Slot` ↔ `x_cache_failed_slot` ✔。
pub fn read_failed_slot(r: *mut ngx_http_request_t) -> Option<usize> {
let mut name = ngx_str_t {
len: "sent_http_x_cache_failed_slot".len(),
data: b"sent_http_x_cache_failed_slot\0".as_ptr() as *mut u8,
};
// SAFETY: r 由 nginx 传入且有效;sent_http_ 是 nginx 内建前缀变量
let v = unsafe { ngx_http_get_variable(r, &raw mut name, 0) };
if v.is_null() {
return None;
}
// ⚠️ **先判 not_found,再碰 data / len**(两步走,别合成一个元组):
// nginx 的「未找到」分支(ngx_http_variables.c:998-1001)**只置 not_found**,
// **不动 data / len**;而这个值槽是 `ngx_palloc` 分配的(同文件 :725)
// ⇒ **不清零** ⇒ not_found 为真时 data / len 是**未初始化**的。
// 元组/逗号表达式会**按顺序求值全部元素** ⇒ 把 data/len 提到 not_found
// 之前读 ⇒ 未初始化读(UB)。故这里**提前 return**。
//
// ⚠️ 本函数走的是**按名查**(`ngx_http_get_variable`)⇒ 值槽是
// `ngx_palloc` 的**未清零**内存。
// 对比 `cache.rs::read_indexed_var`(按索引查):值槽在
// `r->variables[]` 里,是 `ngx_pcalloc` 的**清零**内存 ⇒ 那边没这个问题。
// SAFETY: v 非空 ⇒ 可读它的字段;nginx 保证了 not_found 已被写过
if unsafe { (*v).not_found() != 0 } {
return None;
}
// SAFETY: not_found 为假 ⇒ nginx 走的是 unknown_header 的**成功分支**
// (ngx_http_variables.c:1003-1011 / 1017-1029)⇒ data / len 都被写好了
let data = unsafe { (*v).data };
if data.is_null() {
return None;
}
// SAFETY: 同上 ⇒ len 也已被 nginx 写好
let len = unsafe { (*v).len() as usize };
if len == 0 {
return None;
}
// SAFETY: data 非空 ⇒ data 指向 len 字节的有效内存
let s = unsafe { core::slice::from_raw_parts(data, len) };
let s = String::from_utf8_lossy(s);
let s = s.trim();
// ⚠️ nginx 对**同名**的多个响应头会用 ", " 拼接成一个值
// (ngx_http_variable_unknown_header:多个匹配头拼成 "a, b")。
// 契约是「一个整数」,但若 conf 在**同一层**写了两次该头,
// 拿到的就是 "1, 2" ⇒ 直接 parse 会失败 ⇒ **静默地一个源都不冷却**。
// ⇒ 取**最后一段**(内层/后写的那次最贴近真实失败顺位)再解析。
let last = s.rsplit(',').next().unwrap_or(s).trim();
match last.parse::<usize>() {
Ok(v) => Some(v),
Err(_) => {
// ⚠️ **只在「有值但解析不出来」时告警**(D4):
// 之前这里是 `.ok()` ⇒ 静默吞掉 ⇒ 排障时看不到任何线索
// (换源链写坏了头 / conf 写了两次 / 上游塞了脏值,都表现为
// 「一个源都不冷却」,无从判断是「没失败」还是「解析失败」)。
// 「头不存在」走的是上面的 not_found 早退、「值为空」走 len==0
// 早退 ⇒ **都不在这里打**,避免正常请求(没失败过)在热路径上
// 无脑刷日志。
//
// ⚠️ 头值**可能来自上游**(`sent_http_` 读的是响应头全集)
// ⇒ 截断到 64 字符再打(免得灌日志);`{:?}` 会转义控制字符
// (免得伪造日志行)。
let shown: String = s.chars().take(64).collect();
util::log_warn(&format!(
"[cache] 响应头 X-Cache-Failed-Slot 的值无法解析为顺位号:{shown:?} —— 本次不冷却任何源"
));
None
}
}
}
/// 把失败的源打入冷却(`cache::cool_down`,60 秒)。
///
/// 判定「哪些源失败」用两条线索:
/// 1. **响应头 `X-Cache-Failed-Slot`**(换源链写下的顺位)——它给的是
/// **最后一跳失败的那个顺位**,而走到那一跳说明 `slots[0..=k]` 全都失败过
/// ⇒ 冷却**整段 `0..=k`**(R34 / R-T5-4);
/// 2. **最终状态码是 403/5xx** ⇒ 整条链都失败 ⇒ 全部顺位冷却
/// (兜底:conf 没写该响应头、或旧版 conf 没这个机制)。
/// 403 也在内,因为换源链把 403 当「该源拒绝我们」⇒ 走到最后仍是 403
/// 就说明整个池都在拒绝我们。404 不在列(= 确实没这个包,不是源的问题)。
///
/// 顺位 → 源下标的映射**必须**走 `$cache_pick`(R-T5-5):它是**请求内缓存**
/// 的(Task 4 的 memo)⇒ 与本次请求**实际用的源**严格一致;
/// 另查一次上游表拿到的是**此刻**的池子 ⇒ 管理员在请求中途改了池子就错位。
/// ⇒ 边界检查用的「源个数」也**从同一个请求级 memo 取**
/// (`cache::memo_source_count`,D3),不另查表、也不 clone 整份源列表:
/// 顺位下标与源个数因此处在**同一个下标空间**里,天然不会错位。
///
/// ⚠️ 调用点必须在 log handler 的 `status.is_empty()` **早退之后**
/// (R-T5-1):没过缓存层的请求(401 无效 Key / 429 超配额 / 503 未配上游)
/// **没有回源** ⇒ 没有源失败 ⇒ 不该冷却任何源。
fn cool_down_failed(r: *mut ngx_http_request_t) {
let Some(route) = config::route_of_uri(&http::uri(r)) else {
return;
};
// SAFETY: r 由 nginx 传入且有效;只读响应状态码
let final_status = unsafe { (*r).headers_out.status as u16 };
let all_failed = matches!(final_status, 403 | 500 | 502 | 503 | 504);
let slot = if all_failed { None } else { read_failed_slot(r) };
let failed = cache::failed_slots(all_failed, slot);
if failed.is_empty() {
return;
}
let raw = cache::read_pick_var(r);
let Some(slots) = cache::parse_pick(&raw) else {
return;
};
// 源个数(**只**用于边界检查;真相源是 $cache_pick,见上)
//
// ⚠️ **走请求级 memo**(Task 4 建的那份快照,D3):
// memo 里装的就是**本次请求选源时用的那份源列表** ⇒ 顺位下标
// (`$cache_pick`)与它是**同一个下标空间** ⇒ 边界检查天然成立。
// 这样 log 阶段**不必再查一次上游表、也不必 clone 整份源列表**
// (每次多一次 shm 读 + 逐行解码 + 一批 String 分配)。
//
// ⚠️ memo 拿不到 ⇒ 本请求**没有选过源** ⇒ `$cache_pick` 也拿不到
// (两者同源)⇒ 直接返回,不冷却任何源。
let Some(n_sources) = cache::memo_source_count(r, route) else {
return;
};
if n_sources == 0 {
return;
}
for slot in failed {
let Some(idx) = slots.get(slot) else { continue };
if *idx >= n_sources {
continue;
}
cache::cool_down(route, *idx);
}
}
// ===========================================================================
// 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;
impl HttpRequestHandler for CacheAccessHandler {
const PHASE: HttpPhase = HttpPhase::Access;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
// 非受管制路径(favicon、探针等)直接放行,交给 nginx 自己的 location 处理
let uri = http::uri(r);
let Some(route) = config::route_of_uri(&uri) else {
return Status::NGX_DECLINED;
};
// R19 总闸。location 级开关(`ipass_cache on` → `loc::Switch::Cache`)
// 待 gateway 接入轮随 core 补变体后一并加回,路由前缀判定保留作第二道闸。
if !plugin_registry::plugin_enabled("cache") {
return HTTPStatus::NOT_FOUND.into();
}
// 上游未配置:**必须在这里拦**。否则变量式 proxy_pass 拿到空
// `$cache_target`,nginx 会报 500 `no host in upstream`,
// 排障时会误以为是缓存本身坏了。
//
// ⚠️ 走**请求级 memo**(`cache::upstream_configured`)而不是
// `upstreams::lookup()`:后者会**再查一次上游表** ⇒
// 一个请求查两次表(access 一次 + 变量求值一次),
// 且两次快照可能不同(中间配置被改)⇒ 判「未配置」与
// 实际选中的源对不上。
// memo 在这里**第一次**被建立(查表发生在此),
// 后面数据面变量求值时**复用同一份快照**(R-T4-2)。
if !cache::upstream_configured(r, route) {
util::log_warn(&format!(
"[cache] 路由 {route} 未配置上游,拒绝 {uri}(client={})",
http::remote_addr(r)
));
return http::fail(
r,
HTTPStatus::SERVICE_UNAVAILABLE,
&format!(
"生态 {route} 的上游尚未配置,请联系管理员到「制品缓存」页填写上游地址"
),
);
}
// ---- 统一 Key 鉴权(与 LLM / API 代理同一把 sk_、同一份配额)----
// 携带方式: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,
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
);
};
let Some((username, _allowed, rpm, daily)) = auth::identity(&key) else {
util::log_warn(&format!(
"[cache] API Key 校验失败 route={route} client={}",
http::remote_addr(r)
));
return fail_401(r, "API Key 无效或已失效");
};
// ⚠️ 换源链的每一跳都会**重跑 ACCESS 阶段**(nginx 1.30.4 的
// `error_page … = @<name>;` → `ngx_http_named_location()` 会把
// `r->phase_handler` 重置到 REWRITE 起点 ⇒ 阶段全部再跑一遍)
// ⇒ 这里会被执行多次 ⇒ **配额只能扣一次**。
// 计费闸挂在**请求级 memo** 上(`$cache_ctx` 不带 NOCACHEABLE
// ⇒ nginx 把值缓存在 `r->variables[index]`,内部重定向不清
// `r->variables` ⇒ 同一请求拿到同一份 memo)。
// ⚠️ 必须在上面的 `upstream_configured`(建 memo)**之后**。
if cache::claim_quota_charge(r, route) {
// SAFETY: r 由 nginx 传入且有效;check_quota 只读请求头与共享内存
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
return resp;
}
}
// 放行:数据面交给 nginx `proxy_cache`(命中不产生任何模块开销)
Status::NGX_DECLINED
}
}
// ===========================================================================
// log:按生态记命中
// ===========================================================================
/// 缓存命中计量(log 阶段)。同样按路由表圈定(与 access 一致);禁用时不记账。
pub struct CacheLogHandler;
impl HttpRequestHandler for CacheLogHandler {
const PHASE: HttpPhase = HttpPhase::Log;
type Output = Status;
fn handler(request: &mut Request) -> Self::Output {
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
// 只计缓存路由的请求(非缓存 URI 不进命中率分母);R19 禁用时跳过。
if config::route_of_uri(&http::uri(r)).is_none()
|| !plugin_registry::plugin_enabled("cache")
{
return Status::NGX_DECLINED;
}
let status = read_cache_status(r);
if status.is_empty() {
// 没拿到状态:请求被鉴权拦下(401/503)、或上游连接失败未走缓存模块。
// 这类请求不该计入命中率分母——它们根本没进缓存层。
return Status::NGX_DECLINED;
}
// 生态从 URI 首段推导(直读 r->uri,不依赖任何 nginx 变量)
let eco = config::eco_of_uri(&http::uri(r));
stats::record(eco, &status, util::now());
// 失败源冷却(换源链失败时把那个源踢出轮转 60s)
//
// ⚠️ 必须放在上面 `status.is_empty()` 的早退**之后**(R-T5-1):
// 没过缓存层的请求(401 无效 Key / 429 超配额 / 503 未配上游)
// **没有回源** ⇒ 没有源失败 ⇒ 一个源都不该被冷却。
cool_down_failed(r);
Status::NGX_DECLINED
}
}