Author SHA1 Message Date
admin 2d1bf44eca build: dev profile 关 incremental,让 sccache 生效
dev/test 构建默认 incremental=true,sccache 对增量目标直接拒缓存
(CannotCache(incremental)),target 只增不减。关掉后 dev 构建也能命中外层缓存。
2026-11-04 10:42:49 +08:00
adminandClaude Code 417c8c9be2 docs(cache): cargo 客户端配方改成「源替换」
`[registries.crates-io] index = …` 会被 cargo **静默忽略**(继续用真正的
crates.io ⇒ 看着「装成功了」,其实没过网关)⇒ 必须用源替换
([source.crates-io] replace-with + 同名的 [registries.ipass])。

另需 `[registry] global-credential-providers = ["cargo:token"]`,
否则 cargo 对需要鉴权的 registry 直接报
「authenticated registries require a credential-provider to be configured」。

Co-Authored-By: Claude Code <[email protected]>
2026-10-31 12:13:03 +08:00
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
adminandClaude Sonnet 5.5 c83d4c7515 fix(cache): 换源链重跑 ACCESS 阶段不该重复扣配额
- nginx 的 error_page → 命名 location 会把 phase_handler 重置到 REWRITE
  起点 ⇒ 每一跳都重跑本插件的 access handler ⇒ 一个客户端请求走完 3 跳
  被扣 3 次配额(平时 1 次)⇒ 上游一挂轮转配额只剩 1/3,客户端提前吃 429。
- Memo 加 ChargeGate(Cell<bool> 内部可变性 ⇒ *const Memo 的取法一个字不用改):
  claim() 首次 true、之后 false;claim_quota_charge() 拿不到 memo 时 fail-closed
  照常计费(宁可多扣,不白送配额)。
- access handler 改成只在 claim 成功时才调 auth::check_quota。
- 前提:$cache_ctx 不带 NOCACHEABLE ⇒ 同一请求拿到同一份 memo ⇒ 闸门在换源链上有效。

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-31 02:44:54 +08:00
adminandClaude Code 85f64f2f1c docs(cache): 说准多源路由凭据门禁的触发条件
门禁拦的是「落库后仍是多源且路由级 key 非空」,不是「本次提交是否形成多源」
⇒ 已经是多源的老路由连改 name/desc 也会 400。注释改成事实。

Co-Authored-By: Claude Code <[email protected]>
2026-10-31 02:03:09 +08:00
adminandClaude Sonnet 5.5 dc49c758fc feat(cache): 多源路由不许把路由级凭据发给第三方源(R-T6-12)
- effective_key:有效源数 > 1 时不再回落路由级 key(源没配凭据 ⇒ 空),
  单源 / v1 payload 维持原回落语义。
- upsert 写入门禁:落库后有效源数 > 1 且路由级 key 非空 ⇒ Err(⇒ 400),
  错误信息说清哪条路由、为什么、怎么改(逐源配 sources[].key)。
- parse_sources 移到 upstreams.rs 并补 7 条单测;字段存在但类型不对 ⇒ Err。
- decode 恢复纯函数:payload 损坏告警挪到读侧,按路由各告警一次,
  只报结构(源个数),不落任何内容字节。
- mask_key:长度 < 8 的凭据整体打码,不再暴露明文片段。
- 源池条目数上限 16 条/路由。
- upsert 文档注释对齐 R-T6-14 的 base 语义。

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-31 01:48:38 +08:00
adminandClaude Sonnet 5.5 ac1c51d374 feat(cache): 管理 API 支持读写源池 sources[]
保存语义:字段不提交 = 不改;提交空数组 = 清空源池(退回单 base)。
视图回显源列表(凭据只给掩码)+ source_count + base_source。

- base 自动补齐 = sources[0].url:让「base 非空」恒等于「已配置」,
  sync_shm / reload_shm 的判据一个字不用改(消除 base 空 + sources 非空的 503 错位)。
- 拒绝控制字符(< 0x20 与 DEL):payload 是换行分隔的,值里藏 \n 会把源列表
  错位拆行且不报错 ⇒ 静默把请求打到错误的 URL 上。
- 源池变更时清掉该路由的 ch:<route>:<下标> 冷却条目:旧下标会套到别的源头上。
- 源 id 自动生成带 host + 路径,同批次内唯一。
- payload 损坏告警只报结构(行数 / 源个数),不落任何内容字节(payload 含凭据)。

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-31 00:59:56 +08:00
adminandClaude Code ed7fe3cac8 docs(cache): 同步 cool_down_failed 注释到 D3 后的取源个数来源
边界检查的源个数已改为从请求级 memo 取(D3),注释里还留着
"另查上游表取源个数"的旧说法,容易把后来的人带回旧的错配。

Co-Authored-By: Claude Code <[email protected]>
2026-10-31 00:15:59 +08:00
admin 1ab8a84901 fix(cache): 修 read_failed_slot 的未初始化读,补解析失败告警 2026-10-30 23:45:17 +08:00
admin c43ad3749e feat(cache): 失败源进 60s 冷却
换源链在命名 location 里写下 X-Cache-Failed-Slot 响应头,
log 阶段据此把失败的源踢出轮转;最终 502/504 时全部冷却(兜底)。
2026-10-30 20:31:26 +08:00
admin 34eb8c7d0b feat(cache): 三档上游目标变量 + 请求内一致的选源
新增 $cache_target_alt/_alt2、$cache_auth_alt/_alt2 与内部 $cache_pick。
$cache_pick 请求内缓存 ⇒ target/auth/host 必定同源;
$cache_pick 按变量索引读(postconfig 取索引),不用名字查找。
单源配置下行为与旧版逐字节相同。
2026-10-30 20:07:53 +08:00
admin f412ec3dcc feat(cache): 选源纯函数 + 源冷却状态
select() 轮转起点=hash%n,冷却源降权到队尾不丢弃,链长恒为 3;
  冷却项存 shm ch:<route>:<idx>,靠 expires_at 自动过期。
2026-10-30 15:35:49 +08:00
admin 85ec38aa2d feat(cache): shm payload 支持多源(v2),向后兼容 v1 三行格式
v1 payload 仍是三行;v2 在第 4 行打版本标记,源列表每两行一个 (url,key)。
仓内读法 split_payload 取前三行 ⇒ v1/v2 下 base/key/mode 全干净。
旧二进制带的是它自己那份 splitn(3):base/key 仍正确,但 mode 会被后续行污染
(已知残留;生产上无混版本读同一份 shm,唯一暴露面是显式回退二进制)。
2026-10-30 15:24:54 +08:00
admin 838f497290 feat(cache): 上游模型加多源 sources 字段
旧 JSON 无该字段时走 serde default ⇒ 存量文件不用改、行为不变。
2026-10-30 14:46:45 +08:00
9 changed files with 2419 additions and 81 deletions

No files matched your search

+3
View File
@@ -15,3 +15,6 @@ ngx = { path = "../ipass-core/rust/vendor/ngx-rust" }
nginx-sys = { path = "../ipass-core/rust/vendor/ngx-rust/nginx-sys" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[profile.dev]
incremental = false
+35 -3
View File
@@ -110,8 +110,17 @@ fn h_admin_overview(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
/// 新增/修改一个路由的上游。
///
/// 表单字段:`route`(必填) / `base` / `key` / `name` / `desc` / `note` / `enabled`。
/// 表单字段:`route`(必填) / `base` / `key` / `name` / `desc` / `note` / `enabled`
/// / `sources`。
/// `base` 留空 = 保留原值;`key` 留空 = **清空**(语义差异见 `upstreams::upsert`)。
///
/// ⚠️ **`sources` 的值是一个「JSON 数组的字符串」**,不是 JSON 数组本身。
/// 原因:`ipass_core::http::params()` 解析 JSON body 时,数组/对象类型的字段
/// 会被**丢掉** ⇒ 直接传 `{"sources": [...]}` 会被**静默忽略**
/// (看起来「保存成功」但源池根本没变)。
/// 正确写法:
/// `sources=[{"id":"goproxy-cn","url":"https://goproxy.cn","key":"","note":""}]`
/// (表单编码时整个数组 URL 编码后作为值传;JSON body 时值是字符串,串里再放 JSON)。
fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let p = http::params(r);
let route_raw = p.get("route").cloned().unwrap_or_default();
@@ -121,6 +130,25 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
None => true,
};
// sources:表单里的 JSON 数组字符串。
// 字段不提交(或提交空串)⇒ None ⇒ 不改现有源池;
// 提交合法空数组 `[]` ⇒ Some(vec![]) ⇒ 清空(退回单 base);
// 提交非空数组 ⇒ 覆盖。
let sources = match p.get("sources") {
Some(raw) if !util::trim(raw).is_empty() => match upstreams::parse_sources(raw) {
Ok(v) => Some(v),
Err(e) => {
util::log_err(&format!("[cache] sources 参数解析失败:{e}"));
return http::fail(
r,
HTTPStatus::BAD_REQUEST,
&format!("sources 参数非法:{e}"),
);
}
},
_ => None,
};
// ⚠️ key 用「字段是否出现」区分「不改」与「清空」,所以这里不能把
// `p.get("key")` 归一成空串——前端删掉输入框内容时应提交 `key=`(空串)。
let res = upstreams::upsert(
@@ -131,6 +159,7 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
p.get("desc"),
enabled,
p.get("note"),
sources.as_deref(),
);
match res {
@@ -138,8 +167,10 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
let route = util::trim(&route_raw).to_ascii_lowercase();
let active = upstreams::lookup(&route).is_some();
util::log_notice(&format!(
"[cache] 保存上游 route={route} base={} enabled={} active={active}",
item.base, item.enabled
"[cache] 保存上游 route={route} base={} sources={} enabled={} active={active}",
item.base,
item.sources.len(),
item.enabled
));
http::ok(
r,
@@ -147,6 +178,7 @@ fn h_admin_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
"route": route,
"base": item.base,
"key_set": !item.key.is_empty(),
"source_count": item.sources.len(),
"enabled": item.enabled,
"active": active,
"entry": upstreams::entry_base(r),
+1023 -37
View File
File diff suppressed because it is too large. Load diff
+18 -2
View File
@@ -25,6 +25,17 @@ pub const KEY_CX_PREFIX: &[u8] = b"cx:";
/// 与 `cx:` 分属两片键空间:前者是**配置**,后者是**读数**。
pub const KEY_CACHE_PREFIX: &str = "cache:";
/// 源冷却的键前缀:`ch:<route>:<源下标>` → 值 `"1"`,靠 `expires_at` 自动过期。
///
/// 与 `cx:`(配置)、`cache:`(读数)分属三片键空间:这里是**运行时状态**。
pub const KEY_CH_PREFIX: &[u8] = b"ch:";
/// 失败源的冷却时长(秒)。短到能自愈,长到能挡住一次抽风窗口。
pub const COOLDOWN_SECS: i64 = 60;
/// 换源链长度:首选 + 备选 1 + 备选 2(conf 里固定三跳 ⇒ 这里固定 3)。
pub const MAX_SLOTS: usize = 3;
/// shm payload 内部的行分隔符(base / 上游 Key / mode)。
pub const PAYLOAD_SEP: char = '\n';
@@ -177,8 +188,13 @@ pub const CLIENT_HINTS: &[(&str, &str, &str)] = &[
("go", "Go module proxy", "export GOPROXY={base}/go"),
(
"cargo",
"crates.io 稀疏索引(包本体需另配 /cargo-dl/,见文档)",
"mkdir -p ~/.cargo && printf '[registries.crates-io]\\nindex = \"sparse+{base}/cargo/\"\\n' >> ~/.cargo/config.toml",
"crates.io 稀疏索引(config.json 的 dl 已改写回本网关 ⇒ 包体也走网关)",
// ⚠️ 必须是**源替换**:`[registries.crates-io] index = …` 会被 cargo
// **静默忽略**(继续用真正的 crates.io ⇒ 看着成功,其实没过网关)。
// 另需 `[registry] global-credential-providers`(否则 cargo 报
// "authenticated registries require a credential-provider"),
// token 放 credentials.toml。
"mkdir -p ~/.cargo && printf '[source.crates-io]\\nreplace-with = \"ipass\"\\n[source.ipass]\\nregistry = \"sparse+{base}/cargo/\"\\n[registries.ipass]\\nindex = \"sparse+{base}/cargo/\"\\n[registry]\\nglobal-credential-providers = [\"cargo:token\"]\\n' >> ~/.cargo/config.toml && printf '[registries.ipass]\\ntoken = \"sk_…\"\\n' >> ~/.cargo/credentials.toml",
),
(
"pypi",
+247 -12
View File
@@ -25,23 +25,28 @@ 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_index, ngx_http_request_t,
ngx_str_t, ngx_uint_t,
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;
use crate::upstreams;
/// `$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 退出。
/// postconfiguration:预取**五个**变量索引。失败返回 false,gateway 会 EMERG 退出。
///
/// 五个是:`$upstream_cache_status`、`$scheme`、`$request_id`(**可选**)、
/// `$cache_pick`、以及内部变量 `$cache_ctx`。
///
/// 为什么在 postconfig 而不是 preconfig:`$scheme` 是 core 模块的内建变量,
/// 本模块的 preconfig 早于变量全部注册完成,取 index 可能失败;postconfig
@@ -63,6 +68,36 @@ pub fn prefetch_indexes(cf: *mut ngx_conf_t) -> bool {
}
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
}
@@ -72,6 +107,12 @@ pub fn read_scheme(r: *mut ngx_http_request_t) -> String {
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 {
@@ -94,10 +135,179 @@ pub fn read_cache_status(r: *mut ngx_http_request_t) -> String {
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;
@@ -123,7 +333,15 @@ impl HttpRequestHandler for CacheAccessHandler {
// 上游未配置:**必须在这里拦**。否则变量式 proxy_pass 拿到空
// `$cache_target`,nginx 会报 500 `no host in upstream`,
// 排障时会误以为是缓存本身坏了。
if upstreams::lookup(route).is_none() {
//
// ⚠️ 走**请求级 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)
@@ -138,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 中携带",
);
};
@@ -150,12 +369,22 @@ 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 无效或已失效");
};
// SAFETY: r 由 nginx 传入且有效;check_quota 只读请求头与共享内存
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
return resp;
// ⚠️ 换源链的每一跳都会**重跑 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`(命中不产生任何模块开销)
@@ -192,6 +421,12 @@ impl HttpRequestHandler for CacheLogHandler {
// 生态从 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
}
}
+51
View File
@@ -0,0 +1,51 @@
//! 下行 Key 的**携带方式**解析(缓存插件自己的口径)。
//!
//! ## 为什么不在 core 里改
//!
//! 内核 `ipass_core::auth::downstream_key` 是**全平台共用**的口径:
//! `Authorization: Bearer <sk_…>` / `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: <token>`**。
///
/// 返回的字符串**还要**过 `auth::identity(&key)` 才能变成身份。
pub fn downstream_key(r: *mut ngx_http_request_t) -> Option<String> {
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)
}
+7 -2
View File
@@ -15,8 +15,12 @@
//!
//! ## 装配点(gateway)
//!
//! * `preconfig` —— 注册五个只读变量:`$cache_target` / `$cache_host` /
//! `$cache_upstream_key` / `$cache_eco` / `$cache_key`(见 [`cache`])
//! * `preconfig` —— 注册**十一个对外只读变量 + 一个内部变量**:
//! 对外的:`$cache_target` / `$cache_host` / `$cache_upstream_key` /
//! `$cache_eco` / `$cache_key` / `$cache_auth` / `$cache_target_alt` /
//! `$cache_target_alt2` / `$cache_auth_alt` / `$cache_auth_alt2` /
//! `$cache_pick`;内部的:`$cache_ctx`(请求级 memo 的载体,
//! 值槽里存指针,不是字符串)(见 [`cache`])
//! * `postconfig` —— 预取 `$upstream_cache_status` / `$scheme` 变量索引、
//! 识别 proxy_cache 容量区([`zones`],供容量面板读数与清理),
//! 并注册 access(鉴权)+ log(计量)两个 handler
@@ -34,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;
+30
View File
@@ -34,6 +34,32 @@ impl Default for CacheUpstreamStore {
}
}
/// 多源模式下的**一条上游源**。
///
/// 与 `CacheUpstream.base` 的区别:`base` 是「这条路由的上游」,
/// `sources` 是「这条路由的**镜像池**」——插件在池里轮转选源,
/// 失败的那个进冷却、下次直接跳过。
///
/// ⚠️ `url` 与 `base` 同约定:**不含**路由的协议前缀
/// (docker 的 `/v2` 由插件在 tail 侧补,见 `config::upstream_path_prefix`)。
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CacheSource {
/// 稳定标识(小写字母/数字/`-`),管理台展示与冷却键用;
/// 留空时由 `url` 的 host(+ 路径)自动生成,同一路由内唯一。
#[serde(default)]
pub id: String,
/// 上游 URL:`scheme://host[/镜像自己的路径前缀]`,不带尾斜杠。
#[serde(default)]
pub url: String,
/// 该源自己的凭据(完整 `Authorization` 头值)。
/// 空 = 用路由级 `key`;路由级也空 = 透传客户端的 `Authorization`。
#[serde(default)]
pub key: String,
/// 备注
#[serde(default)]
pub note: String,
}
/// 单个生态的上游配置。
///
/// 这里刻意**不存**「把哪个 URI 前缀映射到本生态」——那由 nginx conf 的
@@ -50,6 +76,9 @@ pub struct CacheUpstream {
/// Authorization,Docker Hub 的 Bearer token 走这条;但下端 `sk_` 会被剔除)。
#[serde(default)]
pub key: String,
/// 镜像源池(非空 = 多源模式)。空 = 退回单 `base` 模式(今天的行为)。
#[serde(default)]
pub sources: Vec<CacheSource>,
/// 模式(见 `config::MODE_PROXY`)
#[serde(default = "default_mode")]
pub mode: String,
@@ -83,6 +112,7 @@ impl Default for CacheUpstream {
Self {
base: String::new(),
key: String::new(),
sources: Vec::new(),
mode: default_mode(),
name: String::new(),
desc: String::new(),
+1005 -25
View File
File diff suppressed because it is too large. Load diff