refactor: 改造为独立插件仓 ipass-plugin-cache(对齐兄弟仓形态)
- 扁平化:rust/crates/plugin-cache/src → src/,单包 Cargo.toml(name ipass-plugin-cache 2.0.0),
path 依赖改 ../ipass-core(内核+vendor ngx),删除旧单体拆分残留(rust/ 层级、
deps/ipass submodule、.gitmodules、conf/、tests/、多页静态 www/、AGENTS.md)
- R19 启停对齐:access/log 热路径加 plugin_registry::plugin_enabled("cache")
门控,fail-closed 404(数据面是鉴权后磁盘读,禁用放行=无鉴权读缓存盘);
location 圈定暂用 8 前缀路由表,ipass_cache 指令待 gateway 接入轮
- 旧独立应用形态保留在 tag legacy-app-final
- 文档:CLAUDE.md(装配关系+未挂载待办+本机编译 env 姿势)、README.md、
docs/cache-usage.md 保留;docs/plugins.md(单体时代)删除
- 验证:cargo check --release 通过,cargo test 4 passed
Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
1 parent
f7c70a0e19
commit
2c8fb2a1ee
128 files changed
+110
-9496
No files matched your search
+297
@@ -0,0 +1,297 @@
|
||||
//! 缓存插件的 nginx 变量层:把「上游表 + 请求 URI」算成 `proxy_pass` 能用的值。
|
||||
//!
|
||||
//! 注册六个**只读**变量(求值时算,模块从不主动写):
|
||||
//!
|
||||
//! | 变量 | 值 | 谁用 |
|
||||
//! | --- | --- | --- |
|
||||
//! | `$cache_target` | `base + 上游路径前缀 + 尾部 [+ ?query]` | `proxy_pass $cache_target` |
|
||||
//! | `$cache_host` | 上游 Host(含端口) | `proxy_set_header Host $cache_host` |
|
||||
//! | `$cache_upstream_key` | 管理台配的上游凭据**原值**(未配置为空) | 排障/日志 |
|
||||
//! | `$cache_auth` | **实际下发**的 Authorization 值(含防 `sk_` 泄漏规则) | `proxy_set_header Authorization $cache_auth` |
|
||||
//! | `$cache_eco` | 生态名(`go` / `cargo` / …) | 日志与排障 |
|
||||
//! | `$cache_key` | `<route>:<uri>` | `proxy_cache_key`(显式给定,不依赖 `$proxy_host`) |
|
||||
//!
|
||||
//! ⚠️ `$proxy_host` 在**变量式 `proxy_pass`** 下不可靠,所以 `proxy_cache_key`
|
||||
//! 必须显式指定;用本变量即可(同 zone 内 URI 唯一,跨 zone 天然隔离)。
|
||||
//!
|
||||
//! 这就是「UI 配上游 + 动态注入」的落点:上游地址与凭据都来自共享内存
|
||||
//! (`cx:<route>`),改配置立即生效,无需改 nginx conf、无需 reload。
|
||||
|
||||
use ngx::core::{Pool, Status};
|
||||
use ngx::ffi::{
|
||||
NGX_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, ngx_conf_t, ngx_http_add_variable,
|
||||
ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t, ngx_str_t, ngx_uint_t,
|
||||
};
|
||||
use ngx::ngx_string;
|
||||
|
||||
use ipass_core::http;
|
||||
|
||||
use crate::config;
|
||||
use crate::upstreams;
|
||||
|
||||
// ===========================================================================
|
||||
// 变量分派标记
|
||||
// ===========================================================================
|
||||
|
||||
/// `$cache_target`:完整上游 URL
|
||||
pub const VAR_TARGET: usize = 1;
|
||||
/// `$cache_host`:上游 Host 头
|
||||
pub const VAR_HOST: usize = 2;
|
||||
/// `$cache_upstream_key`:上游凭据(空 = 不下发鉴权头)
|
||||
pub const VAR_UPSTREAM_KEY: usize = 3;
|
||||
/// `$cache_eco`:生态名
|
||||
pub const VAR_ECO: usize = 4;
|
||||
/// `$cache_key`:缓存键(`<route>:<uri>`)
|
||||
pub const VAR_KEY: usize = 5;
|
||||
/// `$cache_auth`:**实际下发给上游**的 `Authorization` 头值(含防泄漏规则)
|
||||
pub const VAR_AUTH: usize = 6;
|
||||
|
||||
/// 注册本插件的全部变量。返回 false = 失败,gateway 会 EMERG 退出。
|
||||
///
|
||||
/// # Safety
|
||||
/// `cf` 必须由 nginx 传入且有效。
|
||||
pub unsafe fn preconfig(cf: *mut ngx_conf_t) -> bool {
|
||||
let mut target = ngx_string!("cache_target");
|
||||
let mut host = ngx_string!("cache_host");
|
||||
let mut ukey = ngx_string!("cache_upstream_key");
|
||||
let mut eco = ngx_string!("cache_eco");
|
||||
let mut ckey = ngx_string!("cache_key");
|
||||
let mut auth = ngx_string!("cache_auth");
|
||||
unsafe {
|
||||
add_var(cf, &raw mut target, VAR_TARGET)
|
||||
&& add_var(cf, &raw mut host, VAR_HOST)
|
||||
&& add_var(cf, &raw mut ukey, VAR_UPSTREAM_KEY)
|
||||
&& add_var(cf, &raw mut eco, VAR_ECO)
|
||||
&& add_var(cf, &raw mut ckey, VAR_KEY)
|
||||
&& add_var(cf, &raw mut auth, VAR_AUTH)
|
||||
}
|
||||
}
|
||||
|
||||
/// 注册一个只读变量,值由 [`var_get`] 按 `slot` 分派计算。
|
||||
///
|
||||
/// `NOCACHEABLE`:本变量是「读时现算」,若被 nginx 缓存进 `r->variables`,
|
||||
/// 同一请求多次求值(`proxy_pass` 一次、`proxy_set_header` 再读)会拿到
|
||||
/// 首次结果——对上游配置**中途变更**的场景会读到旧值,故标记不可缓存。
|
||||
unsafe fn add_var(cf: *mut ngx_conf_t, name: *mut ngx_str_t, slot: usize) -> bool {
|
||||
// SAFETY: cf 由 nginx 传入;name 指向调用方栈上的 ngx_str_t,注册时被拷贝
|
||||
let var = unsafe {
|
||||
ngx_http_add_variable(
|
||||
cf,
|
||||
name,
|
||||
(NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t,
|
||||
)
|
||||
};
|
||||
if var.is_null() {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: var 非空且由本函数独占初始化;data 承载分派标记
|
||||
unsafe {
|
||||
(*var).get_handler = Some(var_get);
|
||||
(*var).set_handler = None;
|
||||
(*var).data = slot;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 求值
|
||||
// ===========================================================================
|
||||
|
||||
/// 管理台「测试」用的探针前缀。conf 里对应一个 `internal` location:
|
||||
///
|
||||
/// ```nginx
|
||||
/// location /_cache_test/ {
|
||||
/// internal; # 挡住外部直连(否则可绕过鉴权触达上游)
|
||||
/// proxy_pass $cache_target; # 复用同一个变量,只是 tail 变成 "/"
|
||||
/// proxy_set_header Host $cache_host;
|
||||
/// proxy_set_header Authorization $cache_upstream_key;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 与 apix 的 `/_apix_probe/`、llm 的 `/_upstream_test/` 同一手法:
|
||||
/// **对外出口与内部探针共用同一套「定上游 + 换凭据」逻辑**,探针才能真正
|
||||
/// 代表真实转发的行为(自己另写一套探针代码必然漂移)。
|
||||
pub const PROBE_PREFIX: &str = "/_cache_test/";
|
||||
|
||||
/// 解析请求 URI → `(route, tail)`。
|
||||
///
|
||||
/// * 正常路径:`/go/pkg-a` → `("go", "/pkg-a")`;`/v2/library/x` → `("docker", "/library/x")`
|
||||
/// * 探针路径:`/_cache_test/go` → `("go", "/")` —— 固定打上游根,只验连通与凭据
|
||||
///
|
||||
/// `tail` 恒以 `/` 开头(上游拼 URL 用),空尾也归一成 `/`。
|
||||
pub fn resolve_route(uri: &str) -> Option<(&'static str, String)> {
|
||||
if let Some(rest) = uri.strip_prefix(PROBE_PREFIX) {
|
||||
let seg = rest.trim_start_matches('/').split('/').next().unwrap_or("");
|
||||
let route = config::route_of_seg(seg)?;
|
||||
return Some((route, "/".to_owned()));
|
||||
}
|
||||
let route = config::route_of_uri(uri)?;
|
||||
let seg = uri.trim_start_matches('/').split('/').next().unwrap_or("");
|
||||
let tail = uri.get(1 + seg.len()..).unwrap_or("");
|
||||
let tail = if tail.is_empty() { "/" } else { tail };
|
||||
Some((route, tail.to_owned()))
|
||||
}
|
||||
|
||||
/// 取 base 的 host 部分(含端口)。`https://a.b:8443/x` → `a.b:8443`
|
||||
pub fn host_of(base: &str) -> &str {
|
||||
let rest = base.split_once("://").map(|(_, r)| r).unwrap_or(base);
|
||||
rest.split('/').next().unwrap_or(rest)
|
||||
}
|
||||
|
||||
/// 由 `(route, tail, base)` 拼出上游完整 URL。
|
||||
///
|
||||
/// 再补回 [`config::upstream_path_prefix`](只有 Docker 非空)。
|
||||
///
|
||||
/// 变量形式的 `proxy_pass` **不会自动追加 query**(nginx 已知行为),
|
||||
/// 所以这里必须自己把 `args` 拼上去——否则 `?archive=tar.gz` 这类参数会被吞掉。
|
||||
pub fn build_target(route: &str, tail: &str, base: &str, args: &str) -> String {
|
||||
let mut t = format!("{base}{}{tail}", config::upstream_path_prefix(route));
|
||||
if !args.is_empty() {
|
||||
t.push('?');
|
||||
t.push_str(args);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// 决定下发给上游的 `Authorization` 头值。
|
||||
///
|
||||
/// `configured` 是本路由在管理台配的上游凭据(原值,管理员自己写全
|
||||
/// `Bearer xxx` / `Basic yyy`)。
|
||||
///
|
||||
/// 三种情形,按镜像型缓存的真实需求排:
|
||||
///
|
||||
/// 1. **管理台配了凭据** → 用配置值(管理员自己写全 `Bearer xxx` / `Basic yyy`,
|
||||
/// 这样正好覆盖私有 registry 的各种鉴权方案,模块不去猜 scheme)。
|
||||
/// 2. **没配凭据** → 透传客户端带来的 `Authorization`。Docker Hub 走的就是这条:
|
||||
/// 客户端先向 `auth.docker.io` 换一个短期 Bearer token,再拿它来拉镜像;
|
||||
/// 如果这里把 Authorization 抹成空,`/v2/` 下的镜像一律 401。
|
||||
/// 3. **但客户端的值若就是本网关的下行 `sk_` Key,一律丢弃**。
|
||||
///
|
||||
/// 第 3 条是安全底线:`sk_` 是客户端访问**本网关**的身份(`auth::downstream_key`
|
||||
/// 认 `Authorization: Bearer` / `x-api-key` 等携带位)。原样透传给上游,
|
||||
/// 等于把网关自己的钥匙递给上游——对方可拿它反调本网关的其它路由刷额度。
|
||||
/// ipass 的 LLM 路径在 `docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md` 记过同一个坑
|
||||
/// (宽松厂商会把这个缺陷掩盖成 200,换严格厂商才暴露成 401)。
|
||||
///
|
||||
/// 判据是**逐字节比较**:只有客户端放在 Authorization 里的值等于本次鉴权用的
|
||||
/// 那把 `sk_` 才丢弃;换任何别的值(真上游 token)都照传。
|
||||
///
|
||||
/// ⚠️ 第 1 条必须**先判**且不能被跳过:`auth_header` 只认客户端的头是不够的
|
||||
/// ——那样「配了凭据的路由」永远下发不了凭据,而且客户端带的是 `sk_` 时会被
|
||||
/// 第 3 条抹成空(实测症状:管理台配了 token,上游仍收到空 Authorization,
|
||||
/// 而测试里「未配凭据 → 不下发」那条却通过,很容易误判成上游问题)。
|
||||
fn auth_header(r: *mut ngx_http_request_t, configured: &str) -> String {
|
||||
// 1) 管理台配了凭据 → 用配置值(配置是管理员的显式意图,优先级最高)
|
||||
let configured = configured.trim();
|
||||
if !configured.is_empty() {
|
||||
return configured.to_owned();
|
||||
}
|
||||
let raw = match http::header(r, "authorization") {
|
||||
Some(v) => v.trim().to_owned(),
|
||||
None => return String::new(),
|
||||
};
|
||||
let Some(dk) = ipass_core::auth::downstream_key(r) else {
|
||||
// 客户端没带网关 Key → 原样透传(如纯 x-api-key 场景)
|
||||
return raw;
|
||||
};
|
||||
let bare = raw
|
||||
.strip_prefix("Bearer ")
|
||||
.or_else(|| raw.strip_prefix("bearer "))
|
||||
.unwrap_or(&raw)
|
||||
.trim();
|
||||
if bare == dk { String::new() } else { raw }
|
||||
}
|
||||
|
||||
/// 六个变量共用一个 get_handler,靠 `var.data`(即 `slot`)分派。
|
||||
pub extern "C" fn var_get(
|
||||
r: *mut ngx_http_request_t,
|
||||
v: *mut ngx_http_variable_value_t,
|
||||
data: usize,
|
||||
) -> ngx_int_t {
|
||||
// SAFETY: r/v 由 nginx 传入且有效;本函数只读请求结构、只写 v
|
||||
unsafe {
|
||||
let resolved = (|| -> Option<String> {
|
||||
let uri = http::uri(r);
|
||||
let (route, tail) = resolve_route(&uri)?;
|
||||
let (base, key, _mode) = upstreams::lookup(route)?;
|
||||
Some(match data {
|
||||
VAR_TARGET => {
|
||||
let args = http::args_raw(r);
|
||||
let args = core::str::from_utf8(&args).unwrap_or("");
|
||||
build_target(route, &tail, &base, args)
|
||||
}
|
||||
VAR_HOST => host_of(&base).to_owned(),
|
||||
VAR_UPSTREAM_KEY => key,
|
||||
VAR_AUTH => auth_header(r, &key),
|
||||
VAR_ECO => config::eco_of_route(route).to_owned(),
|
||||
// 缓存键必须含 query(完整资源身份):npm 的 `?write=true`、
|
||||
// docker 的 `?ns=`、go 的 `?go-get=1`、cargo 的 `?archive=tar.gz`
|
||||
// 都靠 query 区分实体。而**变量式 proxy_pass 不把 query 写进
|
||||
// `$uri`**,只看 `$uri` 会让「带 query 的请求」命中「不带 query
|
||||
// 的缓存」,把错的制品发出去(实测:`/go/@v/list?x=1` 命中了
|
||||
// `/go/@v/list` 的缓存体,且完全没有回源)。
|
||||
VAR_KEY => {
|
||||
let args = http::args_raw(r);
|
||||
match core::str::from_utf8(&args) {
|
||||
Ok(a) if !a.is_empty() => format!("{route}:{uri}?{a}"),
|
||||
_ => format!("{route}:{uri}"),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
})
|
||||
})();
|
||||
|
||||
match resolved {
|
||||
Some(value) => set_value(r, v, &value),
|
||||
None => {
|
||||
// 未配置上游 / 非受管制路由:把变量置为「未找到」。
|
||||
// nginx 的变量式 proxy_pass 拿到空值会报 500(no host in upstream),
|
||||
// 所以 access handler 必须先一步用 503 拦掉,别让请求走到这里。
|
||||
(*v).set_not_found(1);
|
||||
(*v).set_valid(0);
|
||||
Status::NGX_ERROR.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 把字符串写进 nginx 变量值(数据从请求内存池分配,生命周期由请求保证)。
|
||||
///
|
||||
/// # Safety
|
||||
/// `r` / `v` 必须由 nginx 传入且在本调用期间有效。
|
||||
unsafe fn set_value(
|
||||
r: *mut ngx_http_request_t,
|
||||
v: *mut ngx_http_variable_value_t,
|
||||
value: &str,
|
||||
) -> ngx_int_t {
|
||||
let pool = Pool::from_ngx_pool((*r).pool);
|
||||
let bytes = value.as_bytes();
|
||||
let data = pool.alloc(bytes.len()) as *mut u8;
|
||||
if data.is_null() {
|
||||
(*v).set_not_found(1);
|
||||
return Status::NGX_ERROR.into();
|
||||
}
|
||||
core::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
|
||||
(*v).data = data;
|
||||
(*v).set_len(bytes.len() as _);
|
||||
(*v).set_valid(1);
|
||||
(*v).set_no_cacheable(1);
|
||||
(*v).set_not_found(0);
|
||||
Status::NGX_OK.into()
|
||||
}
|
||||
|
||||
/// 头字段用的变量名清单——管理台与文档引用它,避免两处写不一致。
|
||||
pub const VARIABLE_DOCS: &[(&str, &str)] = &[
|
||||
("$cache_target", "上游完整 URL(proxy_pass)"),
|
||||
("$cache_host", "上游 Host 头"),
|
||||
("$cache_upstream_key", "管理台配的上游凭据原值(未配置为空)"),
|
||||
(
|
||||
"$cache_auth",
|
||||
"实际下发的 Authorization:配了凭据就用它,没配就透传客户端值,但会剔除下游 sk_ 自身",
|
||||
),
|
||||
("$cache_eco", "生态名"),
|
||||
(
|
||||
"$cache_key",
|
||||
"缓存键(proxy_cache_key)= <route>:<uri>[?args],含 query、不含任何下游凭据(全站共享)",
|
||||
),
|
||||
];
|
||||
Reference in new issue
Block a user