Files
ssw__ipass/rust/crates/plugin-apix/src/handlers.rs
T
admin 85ea0a1531 refactor(plugin): P4 拆 plugin-apix —— API 代理迁入独立插件,过渡期路由清空
- plugin-apix 新 crate:apix/handlers/api/config/models/store
- ApiProxy/ApiProxyStore、api-proxies.json 读写、ax: 键空间与 APIX_* 常量自内核迁入
- ApiProxyHandler 与 $apix_* 六变量注册归 ApixPlugin;用量记账仍走 plugin_llm::stats(同一片键空间、单一写入口)
- gateway 路由表只剩 trend 组合端点(需 users+upstreams+apix 三方名册)
- 行为等价:262 项回归全绿(gateway 102 + llm 160)
2026-09-13 12:16:47 +08:00

92 lines
3.4 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.
//! API 代理热路径(access 阶段):鉴权 → 查代理 → 放行。
//!
//! 与 plugin-llm 的 `LlmHandler` 是同一套下行契约(同一把 `sk_` Key、
//! 同一份限流配额——都在内核 `ipass_core::auth`),差别只在查哪张表、
//! 以及**请求体由网关拼**(`apix::build_body`)——资产选择权必须留在服务端,
/// 否则客户端能自己挑最贵的模型刷。
use ngx::core::Status;
use ngx::ffi::ngx_http_request_t;
use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler, Request};
use crate::apix;
use crate::config;
use ipass_core::{auth, http, loc, util};
use ipass_core::loc::Switch;
/// API 代理 access handler。location 开关:`ipass_apix on`(Switch::Apix)。
pub struct ApiProxyHandler;
impl HttpRequestHandler for ApiProxyHandler {
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;
if !loc::enabled(r, Switch::Apix) {
return Status::NGX_DECLINED;
}
let Some(slug) = apix::slug_of(r) else {
return http::fail(
r,
HTTPStatus::BAD_REQUEST,
"路径缺少代理名,正确形式:/apix/<代理名>?<参数>",
);
};
let Some(key) = auth::downstream_key(r) else {
return http::fail(
r,
HTTPStatus::UNAUTHORIZED,
"缺少 API Key,请在 Authorization: Bearer 或 x-api-key 中携带",
);
};
let Some((username, _allowed, rpm, daily)) = auth::identity(&key) else {
util::log_warn(&format!(
"[apix] API Key 校验失败 slug={slug} client={}",
http::remote_addr(r)
));
return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或已失效");
};
// 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单:
// 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让
// 「管理员明明启用了、某账号却 403」变得难以解释。
let Some((_base, supplier_key, _asset)) = apix::lookup(&slug) else {
return http::fail(
r,
HTTPStatus::NOT_FOUND,
&format!("代理 {slug} 不存在或已停用"),
);
};
if supplier_key.is_empty() {
util::log_err(&format!(
"[apix] 供应商 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写"
));
return http::fail(
r,
HTTPStatus::SERVICE_UNAVAILABLE,
"供应商 API Key 未配置,请联系管理员",
);
}
// SAFETY: r 由 nginx 传入且有效
if let Some(resp) = unsafe { auth::check_quota(r, &username, rpm, daily) } {
return resp;
}
// 用量统计。slot 带 `api/` 前缀,与 LLM 上游在同一片键空间里天然分组
// (键空间归 plugin-llm 的 stats,记账原语在内核 usage——apix 只是租户)
plugin_llm::stats::record(
&username,
&format!("{}{}", config::APIX_STATS_PREFIX, slug),
util::now(),
);
Status::NGX_DECLINED
}
}