按「上游内核为基准」收敛:ipass-core 14 文件与 refs/ipass 逐字节一致。 - 上游采纳我方建议已实现:User.extra flatten (A1) + users::update_extra、 split_value rposition (A2)、iter_prefix_ex (A3) - 新增内核身份端点 api.rs/auth.rs (CorePlugin) + usage.rs - audit.rs 迁出内核(仅 sso 使用 → plugin-sso 本地模块) - Cargo.toml 元数据保留我方 crate 名(产物 libsso_gateway.dylib 为部署依赖)
466 lines
18 KiB
Rust
466 lines
18 KiB
Rust
//! 身份类端点(登录 / 会话 / 账号管理)+ API 分发的公共契约。
|
||
//!
|
||
//! 会话与账号是内核职责(所有插件端点的公共前置),所以这批端点由
|
||
//! `CorePlugin` 直接认领,gateway 把它排在 `PLUGINS` 最前。
|
||
//!
|
||
//! ## `CoreExt`:身份端点的插件扩展点
|
||
//!
|
||
//! 身份端点偶尔需要**插件侧数据**(账号列表要带域名数与用量、删账号要连带
|
||
//! 回收域名、白名单要校验上游存在)。内核不认识插件,这些数据一律通过
|
||
//! [`CoreExt`] 反转:gateway 作为**装配根**实现并注册([`set_ext`]),
|
||
//! 没注册时端点仍可工作(缺装饰、零回收),只是功能变素。
|
||
//!
|
||
//! 路由与鉴权原语([`Guard`] / [`Actor`] / [`run_guarded`] / [`user_or_401`])
|
||
//! 同时供各插件的路由表复用——四份 route 表共用一套鉴权语义。
|
||
|
||
use std::sync::Mutex;
|
||
|
||
use ngx::core::Status;
|
||
use ngx::ffi::ngx_http_request_t;
|
||
use ngx::http::HTTPStatus;
|
||
use serde_json::{Value, json};
|
||
|
||
use crate::config;
|
||
use crate::http;
|
||
use crate::models::User;
|
||
use crate::plugin::Plugin;
|
||
use crate::session;
|
||
use crate::state;
|
||
use crate::users;
|
||
use crate::util;
|
||
|
||
// ===========================================================================
|
||
// 鉴权契约(供内核与各插件的路由表共用)
|
||
// ===========================================================================
|
||
|
||
/// 鉴权后传给处理器的身份
|
||
pub enum Actor {
|
||
/// 公开接口,无身份
|
||
None,
|
||
/// 账号态(X-API-Key)
|
||
User(User),
|
||
/// 管理员态(登录会话)
|
||
Admin(User),
|
||
}
|
||
|
||
impl Actor {
|
||
/// 操作者名称:审核记录 `reviewed_by`、审计日志都用它
|
||
pub fn admin_name(&self) -> &str {
|
||
match self {
|
||
Actor::Admin(u) => &u.username,
|
||
Actor::User(u) => &u.username,
|
||
Actor::None => "",
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy, PartialEq)]
|
||
pub enum Guard {
|
||
Public,
|
||
User,
|
||
Admin,
|
||
}
|
||
|
||
pub type Handler = fn(*mut ngx_http_request_t, Actor) -> Status;
|
||
|
||
/// 账号态接口的公共前置:取账号身份,取不到就回 401(响应已发出)。
|
||
pub fn user_or_401(r: *mut ngx_http_request_t, actor: Actor) -> Result<User, Status> {
|
||
match actor {
|
||
Actor::User(u) => Ok(u),
|
||
_ => Err(http::fail(
|
||
r,
|
||
HTTPStatus::UNAUTHORIZED,
|
||
"API Key 无效或缺失,请在请求头携带 X-API-Key",
|
||
)),
|
||
}
|
||
}
|
||
|
||
/// 账号态鉴权(X-API-Key → users.json 反查)。失败只记日志,由调用方回 401。
|
||
pub fn authenticate_user(r: *mut ngx_http_request_t) -> Option<User> {
|
||
let key = http::header(r, "x-api-key").unwrap_or_default();
|
||
match users::find_by_key(&key) {
|
||
Some(u) => Some(u),
|
||
None => {
|
||
util::log_warn(&format!(
|
||
"[api] API Key 校验失败 client={}",
|
||
http::remote_addr(r)
|
||
));
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 管理员态鉴权(会话 Cookie → 账号)。会话有效但非管理员回 403 而不是 401,
|
||
/// 便于前端区分;两种失败都已把响应写进 r,调用方直接终止即可。
|
||
pub fn authenticate_admin(r: *mut ngx_http_request_t) -> Result<User, Status> {
|
||
let cookie = http::header(r, "cookie");
|
||
match session::authenticate(cookie.as_deref()).and_then(|name| users::get(&name)) {
|
||
Some(u) if u.is_admin() => Ok(u),
|
||
Some(_) => Err(http::fail(r, HTTPStatus::FORBIDDEN, "需要管理员权限")),
|
||
None => Err(http::fail(
|
||
r,
|
||
HTTPStatus::UNAUTHORIZED,
|
||
"未登录或会话已过期,请重新登录",
|
||
)),
|
||
}
|
||
}
|
||
|
||
/// 鉴权 + 执行:按 Guard 求出 Actor 后调用 handler。
|
||
pub fn run_guarded(r: *mut ngx_http_request_t, guard: Guard, handler: Handler) -> Status {
|
||
let actor = match guard {
|
||
Guard::Public => Actor::None,
|
||
Guard::User => match authenticate_user(r) {
|
||
Some(u) => Actor::User(u),
|
||
None => {
|
||
return http::fail(
|
||
r,
|
||
HTTPStatus::UNAUTHORIZED,
|
||
"API Key 无效或缺失,请在请求头携带 X-API-Key",
|
||
);
|
||
}
|
||
},
|
||
Guard::Admin => match authenticate_admin(r) {
|
||
Ok(u) => Actor::Admin(u),
|
||
Err(status) => return status,
|
||
},
|
||
};
|
||
handler(r, actor)
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 插件扩展点
|
||
// ===========================================================================
|
||
|
||
/// 身份端点的插件扩展点。gateway 实现并注册;**方法都给缺省实现**,
|
||
/// 没注册扩展时端点仍可用(账号列表缺装饰、删账号不连带回收)。
|
||
pub trait CoreExt: Sync {
|
||
/// 管理台账号列表:插件侧装饰(域名数 / 用量摘要),一次批量给全部账号
|
||
fn decorate_admin_users(&self, _views: &mut [Value]) {}
|
||
/// `/api/v1/me`:插件侧装饰(我的域名 / 用量摘要 / 策略 TTL)
|
||
fn decorate_me(&self, _username: &str, _view: &mut Value) {}
|
||
/// 删除账号:连带回收该账号名下资源(域名),返回条数
|
||
fn reclaim_on_delete(&self, _username: &str) -> usize {
|
||
0
|
||
}
|
||
/// 账号「可用上游」白名单校验:slot 必须真实存在(plugin-llm 提供)
|
||
fn validate_slots(&self, _slots: &[String]) -> Result<(), String> {
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
static EXT: Mutex<Option<&'static dyn CoreExt>> = Mutex::new(None);
|
||
|
||
/// gateway 在配置解析前注册(装配根是唯一注册方)
|
||
pub fn set_ext(e: &'static dyn CoreExt) {
|
||
if let Ok(mut slot) = EXT.lock() {
|
||
*slot = Some(e);
|
||
}
|
||
}
|
||
|
||
fn ext() -> Option<&'static dyn CoreExt> {
|
||
let guard = EXT.lock().ok()?;
|
||
guard.as_ref().copied()
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 路由
|
||
// ===========================================================================
|
||
|
||
/// 路由表。刻意用精确匹配而非正则——接口路径是固定的,
|
||
/// 正则只会引入「写错锚点导致前缀误匹配」的风险。
|
||
fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> {
|
||
let entry: (Guard, Handler) = match (method, uri) {
|
||
("POST", "/api/admin/login") => (Guard::Public, h_login),
|
||
("POST", "/api/admin/logout") => (Guard::Admin, h_logout),
|
||
("GET", "/api/admin/session") => (Guard::Admin, h_session),
|
||
("GET", "/api/admin/users") => (Guard::Admin, h_admin_users),
|
||
("POST", "/api/admin/users/create") => (Guard::Admin, h_admin_user_create),
|
||
("POST", "/api/admin/users/key") => (Guard::Admin, h_admin_user_key),
|
||
("POST", "/api/admin/users/grant") => (Guard::Admin, h_admin_user_grant),
|
||
("POST", "/api/admin/users/password") => (Guard::Admin, h_admin_user_password),
|
||
("POST", "/api/admin/users/delete") => (Guard::Admin, h_admin_user_delete),
|
||
("POST", "/api/admin/users/models") => (Guard::Admin, h_admin_user_models),
|
||
("POST", "/api/admin/users/limits") => (Guard::Admin, h_admin_user_limits),
|
||
("POST", "/api/admin/users/display") => (Guard::Admin, h_admin_user_display),
|
||
("GET", "/api/v1/me") => (Guard::User, h_me),
|
||
_ => return None,
|
||
};
|
||
Some(entry)
|
||
}
|
||
|
||
/// 本表分发:认领则返回响应状态,不认领返回 `None`(交给下一个插件)。
|
||
pub fn dispatch(r: *mut ngx_http_request_t) -> Option<Status> {
|
||
let method = http::method_str(r);
|
||
let uri = http::uri(r);
|
||
|
||
let Some((guard, handler)) = route(&method, &uri) else {
|
||
return None;
|
||
};
|
||
|
||
Some(run_guarded(r, guard, handler))
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 管理员:登录 / 会话
|
||
// ===========================================================================
|
||
|
||
fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let ip = http::remote_addr(r);
|
||
let now = util::now();
|
||
|
||
if state::get_login_fail(&ip, now) >= config::LOGIN_MAX_FAIL {
|
||
return http::fail(r, HTTPStatus::TOO_MANY_REQUESTS, "登录失败次数过多,请 5 分钟后再试");
|
||
}
|
||
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
let password = p.get("password").cloned().unwrap_or_default();
|
||
|
||
if username.is_empty() || password.is_empty() {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, "请输入账号和密码");
|
||
}
|
||
|
||
let Some(user) = users::get(&username) else {
|
||
state::bump_login_fail(&ip, now);
|
||
util::log_warn(&format!("[api] 登录失败 user={username} client={ip}"));
|
||
return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误");
|
||
};
|
||
|
||
if !util::verify_password(&password, &user.salt, &user.pwd_hash) {
|
||
state::bump_login_fail(&ip, now);
|
||
util::log_warn(&format!("[api] 登录失败 user={username} client={ip}"));
|
||
return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误");
|
||
}
|
||
|
||
if !user.is_admin() {
|
||
return http::fail(r, HTTPStatus::FORBIDDEN, "该账号不是管理员,无法登录管理台");
|
||
}
|
||
|
||
state::clear_login_fail(&ip);
|
||
let token = session::create(&username);
|
||
let cookie = session::set_cookie(&token);
|
||
util::log_notice(&format!("[api] 管理员登录 user={username} client={ip}"));
|
||
|
||
http::ok_with(r, users::view(&user), "登录成功", &[("Set-Cookie", &cookie)])
|
||
}
|
||
|
||
fn h_logout(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let cookie = http::header(r, "cookie");
|
||
session::destroy(cookie.as_deref());
|
||
let cleared = session::clear_cookie();
|
||
http::ok_with(r, json!({}), "已退出登录", &[("Set-Cookie", &cleared)])
|
||
}
|
||
|
||
fn h_session(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||
let Actor::Admin(user) = actor else {
|
||
return http::fail(r, HTTPStatus::UNAUTHORIZED, "未登录或会话已过期,请重新登录");
|
||
};
|
||
http::ok(r, users::view(&user), "ok")
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 管理员:账号管理
|
||
// ===========================================================================
|
||
|
||
fn h_admin_users(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let mut items: Vec<Value> = users::all().iter().map(|u| users::view(u)).collect();
|
||
// 域名数 / 用量等插件数据由装配根装饰(见 CoreExt::decorate_admin_users)
|
||
if let Some(e) = ext() {
|
||
e.decorate_admin_users(&mut items);
|
||
}
|
||
http::ok(r, json!({ "items": items }), "ok")
|
||
}
|
||
|
||
fn h_admin_user_create(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let grant_temp = util::to_bool(p.get("grant_temp"));
|
||
|
||
match users::create(
|
||
p.get("username").map(String::as_str).unwrap_or(""),
|
||
p.get("display_name").map(String::as_str).unwrap_or(""),
|
||
p.get("password").map(String::as_str).unwrap_or(""),
|
||
p.get("role").map(String::as_str).unwrap_or("user"),
|
||
grant_temp,
|
||
) {
|
||
Ok(user) => {
|
||
util::log_notice(&format!(
|
||
"[api] 创建账号 {} name={} role={} temp_grant={grant_temp}",
|
||
user.username, user.display_name, user.role
|
||
));
|
||
http::ok(r, users::view(&user), "账号创建成功")
|
||
}
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
/// 设置展示名(中文姓名等)。传空串 = 清空,前端回落到账号名。
|
||
fn h_admin_user_display(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
|
||
match users::set_display_name(&username, p.get("display_name").map(String::as_str).unwrap_or("")) {
|
||
Ok(u) => http::ok(r, users::view(&u), "已更新展示名"),
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
fn h_admin_user_key(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
|
||
match users::regenerate_key(&username) {
|
||
Ok(key) => http::ok(r, json!({ "username": username, "api_key": key }), "已重置 API Key"),
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
fn h_admin_user_grant(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
|
||
if util::to_bool(p.get("revoke")) {
|
||
if let Err(e) = users::revoke_temp(&username) {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, &e);
|
||
}
|
||
let view = users::get(&username).map(|u| users::view(&u)).unwrap_or(Value::Null);
|
||
return http::ok(r, view, "已取消临时授权权限");
|
||
}
|
||
|
||
match users::grant_temp(&username, p.get("hours")) {
|
||
Ok(_) => {
|
||
let view = users::get(&username).map(|u| users::view(&u)).unwrap_or(Value::Null);
|
||
http::ok(r, view, "已授予临时授权权限")
|
||
}
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
fn h_admin_user_password(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
let password = p.get("password").map(String::as_str).unwrap_or("");
|
||
|
||
match users::set_password(&username, password) {
|
||
Ok(()) => http::ok(r, json!({}), "密码已重置"),
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
fn h_admin_user_delete(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
|
||
if let Err(e) = users::delete(&username, actor.admin_name()) {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, &e);
|
||
}
|
||
|
||
// 连带回收该账号名下的资源(域名等),避免出现无主映射——
|
||
// 装了哪些插件就回收哪些(CoreExt::reclaim_on_delete)
|
||
let removed = ext().map(|e| e.reclaim_on_delete(&username)).unwrap_or(0);
|
||
util::log_notice(&format!("[api] 删除账号 {username},连带域名 {removed} 条"));
|
||
http::ok(r, json!({ "removed_domains": removed }), "账号已删除")
|
||
}
|
||
|
||
/// 设置某账号可用的 LLM 上游白名单(`models` 字段 = 上游 slot 列表,传空串 = 解除限制)。
|
||
///
|
||
/// 注意与**上游登记模型清单**(`Upstream.models`)是两件事:这里管"这个账号能用哪几家
|
||
/// 上游",那里管"这家上游提供哪些模型"。白名单按 slot 生效,模型发现再按白名单过滤。
|
||
fn h_admin_user_models(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
|
||
let slots: Vec<String> = p
|
||
.get("models")
|
||
.map(|s| {
|
||
s.split(',')
|
||
.map(|x| x.trim().to_owned())
|
||
.filter(|x| !x.is_empty())
|
||
.collect()
|
||
})
|
||
.unwrap_or_default();
|
||
|
||
// 上游必须先存在:否则白名单里会存进永远匹配不上的死名字,
|
||
// 表现为「账号被授权了却一直 403」,排查起来很绕。
|
||
// 上游表属 plugin-llm,经 CoreExt 校验。
|
||
if let Err(e) = ext().map(|e| e.validate_slots(&slots)).unwrap_or(Ok(())) {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, &e);
|
||
}
|
||
|
||
match users::set_allowed_models(&username, slots) {
|
||
Ok(u) => http::ok(r, users::view(&u), "已更新可用上游"),
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
/// 设置账号的 LLM 限流参数。字段缺省 = 保持现值,`0` = 不限。
|
||
fn h_admin_user_limits(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||
let p = http::params(r);
|
||
let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default();
|
||
|
||
let parse_limit = |key: &str| -> Result<Option<i64>, String> {
|
||
match p.get(key) {
|
||
None => Ok(None),
|
||
Some(v) if util::trim(v).is_empty() => Ok(None),
|
||
Some(v) => util::trim(v)
|
||
.parse::<i64>()
|
||
.map(Some)
|
||
.map_err(|_| format!("{key} 必须是非负整数(0 表示不限)")),
|
||
}
|
||
};
|
||
|
||
let rpm = match parse_limit("rpm") {
|
||
Ok(v) => v,
|
||
Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
};
|
||
let daily = match parse_limit("daily") {
|
||
Ok(v) => v,
|
||
Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
};
|
||
if rpm.is_none() && daily.is_none() {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, "至少提供 rpm 或 daily 之一");
|
||
}
|
||
|
||
util::log_notice(&format!(
|
||
"[api] 设置账号 {username} LLM 限流 rpm={rpm:?} daily={daily:?}"
|
||
));
|
||
match users::set_llm_limits(&username, rpm, daily) {
|
||
Ok(u) => http::ok(r, users::view(&u), "已更新限流参数"),
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 账号态
|
||
// ===========================================================================
|
||
|
||
fn h_me(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||
let user = match user_or_401(r, actor) {
|
||
Ok(u) => u,
|
||
Err(e) => return e,
|
||
};
|
||
|
||
let mut v = users::view(&user);
|
||
// 我的域名 / 用量摘要 / 策略 TTL 都是插件侧数据,由装配根装饰
|
||
if let Some(e) = ext() {
|
||
e.decorate_me(&user.username, &mut v);
|
||
}
|
||
http::ok(r, v, "ok")
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 装配
|
||
// ===========================================================================
|
||
|
||
/// 内核插件:认领身份类端点。必须排在 gateway 的 `PLUGINS` **最前**。
|
||
pub struct CorePlugin;
|
||
|
||
impl Plugin for CorePlugin {
|
||
fn name(&self) -> &'static str {
|
||
"core"
|
||
}
|
||
|
||
fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option<Status> {
|
||
dispatch(r)
|
||
}
|
||
}
|