From 74e567818845bfd5ada78fd77ef749213c7cc0ea Mon Sep 17 00:00:00 2001 From: ssw Date: Sun, 13 Sep 2026 18:52:26 +0800 Subject: [PATCH] =?UTF-8?q?refactor(core):=20=E5=86=85=E6=A0=B8=E5=8E=9F?= =?UTF-8?q?=E6=A0=B7=E5=90=8C=E6=AD=A5=E4=B8=8A=E6=B8=B8=20ipass-core=20ee?= =?UTF-8?q?05b27=20(1.0.13)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按「上游内核为基准」收敛: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 为部署依赖) --- source/rust/crates/ipass-core/src/api.rs | 465 ++++++++++++++ source/rust/crates/ipass-core/src/audit.rs | 150 ----- source/rust/crates/ipass-core/src/auth.rs | 181 ++++++ source/rust/crates/ipass-core/src/config.rs | 83 ++- source/rust/crates/ipass-core/src/http.rs | 29 +- source/rust/crates/ipass-core/src/lib.rs | 36 +- source/rust/crates/ipass-core/src/loc.rs | 65 +- source/rust/crates/ipass-core/src/models.rs | 182 ++---- source/rust/crates/ipass-core/src/plugin.rs | 64 +- source/rust/crates/ipass-core/src/session.rs | 10 +- source/rust/crates/ipass-core/src/state.rs | 141 +++-- source/rust/crates/ipass-core/src/store.rs | 84 +-- source/rust/crates/ipass-core/src/usage.rs | 239 ++++++++ source/rust/crates/ipass-core/src/users.rs | 610 +++++++++---------- source/rust/crates/ipass-core/src/util.rs | 162 +++-- 15 files changed, 1557 insertions(+), 944 deletions(-) create mode 100644 source/rust/crates/ipass-core/src/api.rs delete mode 100644 source/rust/crates/ipass-core/src/audit.rs create mode 100644 source/rust/crates/ipass-core/src/auth.rs create mode 100644 source/rust/crates/ipass-core/src/usage.rs diff --git a/source/rust/crates/ipass-core/src/api.rs b/source/rust/crates/ipass-core/src/api.rs new file mode 100644 index 0000000..88b4972 --- /dev/null +++ b/source/rust/crates/ipass-core/src/api.rs @@ -0,0 +1,465 @@ +//! 身份类端点(登录 / 会话 / 账号管理)+ 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 { + 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 { + 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 { + 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> = 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 { + 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 = 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 = 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, String> { + match p.get(key) { + None => Ok(None), + Some(v) if util::trim(v).is_empty() => Ok(None), + Some(v) => util::trim(v) + .parse::() + .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 { + dispatch(r) + } +} diff --git a/source/rust/crates/ipass-core/src/audit.rs b/source/rust/crates/ipass-core/src/audit.rs deleted file mode 100644 index e6da617..0000000 --- a/source/rust/crates/ipass-core/src/audit.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! 审计日志:append-only JSONL(对齐 MaxKey `mxk_history_login` / `mxk_history_event` -//! 的语义,但落点从数据库表改为本地文件——本项目无 DB)。 -//! -//! ## 形状 -//! -//! 一行一个 JSON 对象: -//! -//! ```json -//! {"ts":1760000000,"ts_text":"2026-09-12 22:00:00","action":"admin.login", -//! "actor":"alice","target":"alice","ok":true,"ip":"127.0.0.1","ua":"curl/8","detail":""} -//! ``` -//! -//! ## 写入与轮转 -//! -//! * 追加走共享内存里的全局文件写锁(与账号/客户端表同一把锁):审计事件都是 -//! 低频登录/管理操作,串行化代价可忽略,换来多 worker 下不交错。 -//! * 单条 `write(2)` 追加 + 行尾换行,POSIX 对 O_APPEND 的小块写保证不交织。 -//! * 超过 `AUDIT_ROTATE_BYTES` 时轮转为 `audit.jsonl.1`(覆盖上一代)—— -//! 防止无限增长,代价是只保留约两代历史,够排查用;要长期留存请外部归档。 -//! -//! ## 读取 -//! -//! `GET /api/admin/audit` 从文件尾部取最近 N 行,支持按 actor / action 过滤。 -//! 读**不上锁**:读到写了一半的行(理论上有锁不会发生)解析失败即跳过。 - -use std::io::Write; - -use serde_json::{Value, json}; - -use crate::store; -use crate::util; - -/// 审计文件名(相对 `sso_data_dir`) -const FILE_NAME: &str = "audit.jsonl"; -/// 轮转阈值(字节):超过即整体搬到 `audit.jsonl.1` -const ROTATE_BYTES: u64 = 5 * 1024 * 1024; -/// 读取接口默认返回的行数上限 -pub const READ_LIMIT_DEFAULT: usize = 100; -/// 读取接口允许的最大行数 -pub const READ_LIMIT_MAX: usize = 1000; - -/// 记录一条审计事件。写失败只记 nginx 错误日志,**绝不影响业务响应**—— -/// 审计是旁路,不能因为磁盘满把登录搞挂。 -pub fn log(action: &str, actor: &str, target: &str, ok: bool, ip: &str, ua: &str, detail: &str) { - let now = util::now(); - let entry = json!({ - "ts": now, - "ts_text": util::fmt_time(now), - "action": action, - "actor": actor, - "target": target, - "ok": ok, - "ip": ip, - "ua": ua, - "detail": detail, - }); - - let path = std::path::PathBuf::from(store::data_dir()).join(FILE_NAME); - let result = (|| -> Result<(), String> { - // 与账号/客户端表共用同一把文件写锁(store 层的 state::file_lock): - // 轮转判断 + 追加必须原子,且低频事件串行化代价可忽略 - let _guard = crate::state::file_lock().ok_or("内部错误:状态锁不可用")?; - if let Ok(meta) = std::fs::metadata(&path) { - if meta.len() > ROTATE_BYTES { - let rotated = path.with_extension("jsonl.1"); - let _ = std::fs::rename(&path, &rotated); - } - } - let mut f = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&path) - .map_err(|e| format!("打开审计文件失败:{e}"))?; - f.write_all(entry.to_string().as_bytes()) - .and_then(|_| f.write_all(b"\n")) - .map_err(|e| format!("写审计文件失败:{e}"))?; - Ok(()) - })(); - - if let Err(e) = result { - util::log_err(&format!("[audit] {e}")); - } -} - -/// 便捷版:调用方只有 actor/target 等基础信息,无 IP/UA(如初始化路径)。 -pub fn log_simple(action: &str, actor: &str, target: &str, ok: bool, detail: &str) { - log(action, actor, target, ok, "-", "", detail); -} - -/// 读取最近事件(新的事件在前)。 -/// -/// `filter_actor` / `filter_action` 精确匹配;`limit` 超界收口到 -/// `READ_LIMIT_MAX`。文件不存在(尚无事件)返回空表。 -pub fn read(limit: usize, filter_actor: &str, filter_action: &str) -> Vec { - let limit = limit.clamp(1, READ_LIMIT_MAX); - let path = std::path::PathBuf::from(store::data_dir()).join(FILE_NAME); - let Ok(text) = std::fs::read_to_string(&path) else { - return Vec::new(); - }; - - let mut out: Vec = Vec::new(); - for line in text.lines().rev() { - if out.len() >= limit { - break; - } - let Ok(v) = serde_json::from_str::(line) else { - continue; // 跳过损坏行,不让单行问题挡住整页 - }; - if !filter_actor.is_empty() && v.get("actor").and_then(|x| x.as_str()) != Some(filter_actor) - { - continue; - } - if !filter_action.is_empty() - && v.get("action").and_then(|x| x.as_str()) != Some(filter_action) - { - continue; - } - out.push(v); - } - out -} - -/// 统计概要(管理台卡片):文件行数与占用字节。 -pub fn stats() -> Value { - let path = std::path::PathBuf::from(store::data_dir()).join(FILE_NAME); - match std::fs::metadata(&path) { - Ok(meta) => json!({ "bytes": meta.len(), "rotated": path.with_extension("jsonl.1").exists() }), - Err(_) => json!({ "bytes": 0, "rotated": false }), - } -} - -/// 供 e2e / 管理台展示的 action 清单(前端筛选下拉用)。 -pub const KNOWN_ACTIONS: &[&str] = &[ - "admin.login", - "admin.logout", - "admin.user.create", - "admin.user.delete", - "admin.user.password", - "admin.user.key", - "admin.user.role", - "admin.user.profile", - "admin.user.unlock", - "admin.user.batch", - "admin.client.save", - "admin.client.rotate", - "admin.client.delete", - "admin.session.kick", - "sso.login", - "oauth.token", -]; diff --git a/source/rust/crates/ipass-core/src/auth.rs b/source/rust/crates/ipass-core/src/auth.rs new file mode 100644 index 0000000..da612cc --- /dev/null +++ b/source/rust/crates/ipass-core/src/auth.rs @@ -0,0 +1,181 @@ +//! 下行链路鉴权与配额 —— LLM 代理与 API 代理(apix)**共用**的契约。 +//! +//! 「去掉 llm 还要(apix 要)、去掉 apix 还要(llm 要)、两个都去掉才不要」 +//! ⇒ 共用 ⇒ 放内核(docs/plugin/PLUGINIZATION_PLAN.md §4②)。 +//! +//! * [`downstream_key`] —— 取下行 Key(三种携带方式) +//! * [`identity`] —— 查 `ukey:` 身份(纯共享内存,热路径不回读 users.json) +//! * [`check_quota`] —— `rl:` 每分钟限流 + `st:` 每日配额(先增后判) +//! * [`fail`] / [`fail_typed`] —— OpenAI 兼容错误体(下行客户端的 SDK 只认这个) +//! +//! ⚠️ access 阶段返回 `NGX_OK` 等于放行:鉴权失败必须返回状态码, +//! 否则请求照样被 `proxy_pass` 转发——「客户端收到 401,但上游仍被调了一次」, +//! 白烧上游额度且账单上看不出这是一次被拒的请求。实测踩过。 + +use ngx::core::Status; +use ngx::ffi::{ngx_http_request_t, ngx_int_t}; +use ngx::http::HTTPStatus; +use serde_json::json; + +use crate::config; +use crate::http; +use crate::state; +use crate::util; + +// =========================================================================== +// 请求解析 +// =========================================================================== + +/// 取下行 Key。 +/// +/// 依次尝试三种携带方式,覆盖主流 SDK 的默认行为: +/// `Authorization: Bearer`(OpenAI)、`x-api-key`(Anthropic)、`X-API-Key`(本项目域名接口)。 +/// 「同一套 Key」意味着这三个位置放的都应该是 `users.json` 里那把 `sk_...`。 +pub fn downstream_key(r: *mut ngx_http_request_t) -> Option { + if let Some(raw) = http::header(r, "authorization") { + let raw = raw.trim(); + let rest = raw + .strip_prefix("Bearer ") + .or_else(|| raw.strip_prefix("bearer ")); + if let Some(k) = rest { + let k = k.trim(); + if !k.is_empty() { + return Some(k.to_owned()); + } + } + } + for name in ["x-api-key", "api-key"] { + if let Some(k) = http::header(r, name) { + let k = k.trim().to_owned(); + if !k.is_empty() { + return Some(k); + } + } + } + None +} + +/// 查共享内存拿身份:`(username, allowed_slots, rpm, daily)`。 +/// +/// `allowed_slots` 为空表示不限(老账号没有该字段,反序列化即空表)。 +/// `rpm` / `daily` 是限流上限;旧版 payload 只有 2 行,此时按全局默认兜底。 +pub fn identity(key: &str) -> Option<(String, Vec, i64, i64)> { + let payload = state::get_live(config::KEY_UKEY_PREFIX, key.as_bytes(), util::now())?; + let mut lines = payload.split('\n'); + let name = lines.next().unwrap_or(""); + let allowed = lines.next().unwrap_or(""); + let rpm = lines + .next() + .and_then(|s| s.parse::().ok()) + .unwrap_or(config::LLM_RPM_DEFAULT); + let daily = lines + .next() + .and_then(|s| s.parse::().ok()) + .unwrap_or(config::LLM_DAILY_DEFAULT); + if name.is_empty() { + return None; + } + let slots: Vec = if allowed.is_empty() { + Vec::new() + } else { + allowed + .split(',') + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) + .collect() + }; + Some((name.to_owned(), slots, rpm, daily)) +} + +// =========================================================================== +// 响应 +// =========================================================================== + +/// OpenAI 兼容的错误体。客户端 SDK 只认这个形状。 +/// +/// **返回状态码而不是 `NGX_OK`**——见模块头注释。 +pub fn fail(r: *mut ngx_http_request_t, status: HTTPStatus, code: &str, msg: &str) -> Status { + fail_typed(r, status, "invalid_request_error", code, msg) +} + +/// 同 [`fail`],但 `type` 字段可指定——429 限流应返回 `rate_limit_error`, +/// SDK(尤其 OpenAI 官方库)据此做退避重试,写成 `invalid_request_error` +/// 会被当成「请求本身有问题」而直接放弃。 +pub fn fail_typed( + r: *mut ngx_http_request_t, + status: HTTPStatus, + err_type: &str, + code: &str, + msg: &str, +) -> Status { + let body = json!({ + "error": { + "message": msg, + "type": err_type, + "code": code, + } + }) + .to_string(); + + let http_code = status.0 as ngx_int_t; + // 先把自定义响应体发出去(nginx 之后不会再补一份默认错误页,因为 header 已发) + let _ = http::send(r, status, &body); + // 再把状态码交回 nginx,由它终结本请求 + Status(http_code) +} + +// =========================================================================== +// 限流与配额 +// =========================================================================== + +/// 限流与每日配额检查。拒绝时直接发 429 并返回 Some(状态),放行返回 None。 +/// +/// **先增后判**:窗口计数里也包含被拒的请求。这只影响「超限后计数继续涨」, +/// 不影响正确性(反正已在超限状态);换来的是实现无需区分「合法请求才计数」。 +/// +/// # Safety +/// `r` 由 nginx 传入且有效。 +pub unsafe fn check_quota( + r: *mut ngx_http_request_t, + username: &str, + rpm: i64, + daily: i64, +) -> Option { + let now = util::now(); + + // 每分钟窗口(60s 滚动对齐到自然分钟)。rpm<=0 表示不限,跳过计数省一次写 + if rpm > 0 { + let used = state::bump_window(config::KEY_RL_PREFIX, username, now / 60); + if used > rpm { + util::log_warn(&format!( + "[llm] {username} 触发每分钟限流 {used}/{rpm},本请求 429" + )); + return Some(fail_typed( + r, + HTTPStatus::TOO_MANY_REQUESTS, + "rate_limit_error", + "rate_limit_exceeded", + &format!("请求过于频繁:每分钟上限 {rpm} 次,请稍后重试"), + )); + } + } + + // 每日窗口按本地自然日切(见 util::day_id) + if daily > 0 { + let today = state::bump_window(config::KEY_ST_PREFIX, username, util::day_id(now)); + if today > daily { + util::log_warn(&format!( + "[llm] {username} 触发每日配额 {today}/{daily},本请求 429" + )); + return Some(fail_typed( + r, + HTTPStatus::TOO_MANY_REQUESTS, + "insufficient_quota", + "insufficient_quota", + &format!("已达每日请求上限 {daily} 次,明日 0 点重置或联系管理员调整"), + )); + } + } + + None +} diff --git a/source/rust/crates/ipass-core/src/config.rs b/source/rust/crates/ipass-core/src/config.rs index 9ba8372..91c583b 100644 --- a/source/rust/crates/ipass-core/src/config.rs +++ b/source/rust/crates/ipass-core/src/config.rs @@ -1,17 +1,16 @@ -//! 全局策略常量(唯一真源)。 +//! 内核策略常量(唯一真源)。 //! -//! **改策略只改这里**,不要散落到 users / oauth / api 里,否则行为会出现多处真源。 - -// =========================================================================== -// 会话与口令 -// =========================================================================== +//! 与旧 OpenResty 版的 `lua/config.lua` 一一对应:**改策略只改这里**, +//! 不要散落到各模块里,否则行为会出现多处真源。 +//! +//! 插件自有常量在各自 crate(plugin-domain/config.rs、plugin-llm/config.rs); +//! 这里只留「身份 / 会话 / 配额 / 两条下行链路共用」的部分。 +/// 管理员授予的「临时授权权限」有效时长(秒) +pub const TEMP_GRANT_TTL: i64 = 6 * 3600; /// 管理员登录会话时长(秒) pub const SESSION_TTL: i64 = 8 * 3600; -/// 口令哈希迭代轮数。 -/// -/// 沿用被剥离项目的历史算法(`sha256` 迭代加盐),使存量 `users.json` -/// 可以原样接管,不必强制所有人改口令。 +/// 口令哈希迭代轮数。**必须与旧版一致**,否则存量用户口令全部失效。 pub const HASH_ROUNDS: usize = 1000; /// 首次启动播种的管理员账号名 @@ -19,36 +18,38 @@ pub const INIT_ADMIN_USER: &str = "admin"; /// 初始管理员口令的环境变量名。 /// nginx.conf 里必须有对应的 `env ADMIN_INIT_PASSWORD;`,否则会被 nginx 剥离。 pub const INIT_ADMIN_PASSWORD_ENV: &str = "ADMIN_INIT_PASSWORD"; -/// 播种口令的缺省值。**仅用于本机/首次启动**,生产必须用环境变量覆盖。 pub const INIT_ADMIN_PASSWORD_DEFAULT: &str = "123456"; -/// 口令最短长度(对齐 MaxKey 密码策略 `mxk_cnf_password_policy` 的 minlength)。 -/// 仅约束 create / set_password 两个写入口;首次播种的管理员不走该校验。 -pub const PASSWORD_MIN_LEN: usize = 8; +/// 口令最短长度 +/// +/// sso 提议提到 8(弱口令门槛);iPass **维持 6 位下限**——既有测试夹具与 +/// 边界用例大量依赖 6/7 位密码(`password 123` 等),改 8 位会破坏 262 项 +/// 回归。**插件层**(plugin-sso / 未来 plugin-password-policy)若需强约束, +/// 应在插件端校验后再调用 `users::create`/`set_password`,内核不动。 +pub const PASSWORD_MIN_LEN: usize = 6; pub const USERNAME_MIN_LEN: usize = 2; pub const USERNAME_MAX_LEN: usize = 32; /// 展示名(中文姓名等)长度上限。按**字符数**算,一个汉字算 1。 pub const DISPLAY_NAME_MAX_LEN: usize = 32; -/// 部门名长度上限 -pub const DEPARTMENT_MAX_LEN: usize = 64; -/// 单个账号可归属的用户组数量上限(挡住把整张目录灌进去的手滑) -pub const GROUPS_MAX: usize = 32; -/// 单个用户组名长度上限 -pub const GROUP_NAME_MAX_LEN: usize = 64; /// 管理会话 Cookie 名(HttpOnly + SameSite=Strict) -pub const COOKIE_NAME: &str = "sso_admin_session"; +pub const COOKIE_NAME: &str = "ipass_admin_session"; /// 同一 IP 在窗口内最多登录失败次数 pub const LOGIN_MAX_FAIL: i64 = 10; /// 登录失败计数窗口(秒) pub const LOGIN_FAIL_TTL: i64 = 300; -/// 账号维度锁定:窗口内连续失败达到该次数即锁定(对齐 MaxKey 登录失败策略) -pub const ACCOUNT_LOCK_THRESHOLD: i64 = 5; -/// 账号锁定时长(秒):到期自动解锁,不要求人工干预 -pub const ACCOUNT_LOCK_TTL: i64 = 600; -/// 默认状态目录,可被 `sso_data_dir` 指令覆盖 +/// 下行链路每 Key 限流默认值:每分钟请求数。账号未显式配置时取此值;0 = 不限 +pub const LLM_RPM_DEFAULT: i64 = 60; +/// 下行链路每 Key 限流默认值:每日请求数。账号未显式配置时取此值;0 = 不限。 +/// +/// 刻意做**请求级**而不是 token 级:token 数在上游响应体里,而 SSE 必须关缓冲 +/// 透传(`proxy_buffering off`),网关不缓冲就解析不到 usage 字段。要 token 级 +/// 计费得自建 upstream,与「单容器零依赖」红线冲突。 +pub const LLM_DAILY_DEFAULT: i64 = 0; + +/// 默认状态目录,可被 `ipass_data_dir` 指令覆盖 pub const DEFAULT_DATA_DIR: &str = "/usr/local/nginx/data"; // =========================================================================== @@ -59,16 +60,34 @@ pub const DEFAULT_DATA_DIR: &str = "/usr/local/nginx/data"; pub const KEY_SESS_PREFIX: &[u8] = b"sess:"; /// 键前缀:登录失败计数(按 IP) pub const KEY_FAIL_PREFIX: &[u8] = b"fail:"; -/// 键前缀:API Key → 身份(**内核维护**:Key 由内核签发与吊销,索引必须同源, -/// 否则会出现「Key 已重置但旧索引还在」的窗口) +/// 键前缀:下行链路的 API Key → 身份(LLM 代理与 API 代理共用)。 +/// +/// payload = ` \n \n \n `(4 行, +/// 与 `users::identity_payload` 严格一致)。一次查表同时拿到「是谁 / 能用哪些上游 / +/// 限流多少」,**避免推理热路径回读 users.json**——那是同步文件 I/O + 全表 JSON 解码, +/// 管理接口用得起,转发热路径用不起。 pub const KEY_UKEY_PREFIX: &[u8] = b"ukey:"; +/// 键前缀:每分钟限流计数(LLM 代理与 API 代理共用)。键 = `rl:` +/// (**每用户固定一个键**),value = `<分钟窗id>:<计数>`——跨窗自动归零靠读时 +/// 比对窗 id,而不是开新键。若按「每分钟一个键」存,shm 里的键会随时间无限 +/// 累积且无处过期。 +pub const KEY_RL_PREFIX: &[u8] = b"rl:"; +/// 键前缀:每日配额计数(LLM 代理与 API 代理共用)。键 = `st:`, +/// value = `<日窗id>:<计数>`。 +pub const KEY_ST_PREFIX: &[u8] = b"st:"; /// 共享内存 value 内部分隔符(ASCII US)。 -/// -/// 用户名只含 `[A-Za-z0-9_-]`,**不可能**包含该字节,所以切分是安全的。 -/// 但 SSO 会话的身份 payload 含姓名/邮箱等自由文本,那里必须改用 `\n` -/// 分隔(见 `oauth::sso_payload`)——两者不可混用。 +/// 后端地址只含 `[A-Za-z0-9._-]` 与 `:`,用户名只含 `[A-Za-z0-9_-]`, +/// 都不可能包含该字节,所以切分是安全的。 pub const VAL_SEP: u8 = 0x1f; /// 键缓冲区上限:`sess:` + 32 字节 token 的 64 位 hex 最长为 69,留足余量 pub const KEY_BUF_LEN: usize = 128; + +// =========================================================================== +// 部署拓扑(LLM 代理与 API 代理共用) +// =========================================================================== + +/// LLM 代理对外域名,用于账号态 API 回显 `base_url`(apix 的「复制地址」也用它)。 +/// 改域名只改这里(`conf/nginx.conf` 的 LLM server_name 要同步改)。 +pub const LLM_PUBLIC_HOST: &str = "lm.mayishangshu.cn"; diff --git a/source/rust/crates/ipass-core/src/http.rs b/source/rust/crates/ipass-core/src/http.rs index 4b4f670..14878e3 100644 --- a/source/rust/crates/ipass-core/src/http.rs +++ b/source/rust/crates/ipass-core/src/http.rs @@ -47,24 +47,21 @@ pub fn header(r: *mut ngx_http_request_t, name: &str) -> Option { None } -/// 请求 Host 头里的端口(带前导冒号,如 `:88`;无端口或默认端口返回空串)。 +/// 请求 Host 里的端口后缀(`:88` / 空串)。 /// -/// 用于给客户端回显 base_url 时**跟随调用方所用端口**——部署在 88 时客户端 -/// 必须带 `:88`,放在 443 反代后又不带端口,写死任何一种都会在另一种部署下 -/// 给出「看着对、打不通」的地址。 +/// 对外三个域名(`mdm` 管理台 / `lm` LLM / `*.dm` 企业)**共用同一个端口**, +/// 所以「管理接口从哪个端口进来,LLM 就该从哪个端口出去」。回显用的 `base_url` +/// 用它拼:写死端口在换端口部署时失效,完全不写则在非 443 部署时指向别处。 pub fn host_port(r: *mut ngx_http_request_t) -> String { - let host = header(r, "host").unwrap_or_default(); - let h = host.trim_matches(|c| c == '[' || c == ']'); - match h.rfind(':') { - Some(i) => { - let p = &h[i + 1..]; - if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) { - format!(":{p}") - } else { - String::new() - } - } - None => String::new(), + let host = match header(r, "Host") { + Some(h) => h, + None => return String::new(), + }; + // IPv6 字面量形如 `[::1]:88`,rsplit 后 `[::1]` / `88` 仍然正确; + // 纯 `[::1]` 会切出非全数字的尾巴,被下面判掉。 + match host.rsplit_once(':') { + Some((_, p)) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => format!(":{p}"), + _ => String::new(), } } diff --git a/source/rust/crates/ipass-core/src/lib.rs b/source/rust/crates/ipass-core/src/lib.rs index f42d1f1..92ec8de 100644 --- a/source/rust/crates/ipass-core/src/lib.rs +++ b/source/rust/crates/ipass-core/src/lib.rs @@ -1,21 +1,27 @@ -//! # ipass-core —— iPass 统一网关内核 +//! ipass-core —— iPass 内核。 //! -//! 内核只做三件事,做得非常保守: +//! 承担「去掉任何插件,网关还能跑」的部分: //! -//! 1. **状态**:一张共享内存表 + 一把跨进程文件写锁([`state`]); -//! 2. **账号**:`users.json` 与 API Key 的**唯一读写者**([`users`]、[`store`]); -//! 3. **装配**:插件契约([`plugin`])与 location 开关([`loc`])。 +//! * `state` —— 唯一共享内存 zone(`RwLock`)+ 文件写锁 +//! * `store` —— JSON 原子写 + 跨 worker 互斥(状态就是几个 JSON 文件,无数据库) +//! * `users` —— 账号唯一写入口(`ukey:` Key 索引、播种管理员、删除钩子) +//! * `session` —— 管理会话 +//! * `auth`(P3 起)—— 下行 `sk_` 鉴权 + `rl:` 配额(LLM 与 API 代理两条链路共用) +//! * `config` / `models` / `util` / `http` —— 常量、账号模型与通用原语 //! -//! ## 边界纪律 +//! 插件(plugin-domain / plugin-llm / plugin-apix)只允许**单向依赖**本 crate; +//! 内核不认识任何插件。插件通过 `Plugin` trait(P1 引入)与 gateway 装配。 //! -//! * 内核**不知道** OAuth、域名、LLM 的存在——它只认「插件」; -//! * 插件**不得**自己写 `users.json`,一律经 [`users`]; -//! * 插件需要扩展 `User` 字段时,在这里加 `#[serde(default)]` 字段, -//! 由内核统一负责向后兼容(老数据缺字段仍能读)。 +//! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md) //! -//! 判据:去掉 SSO,网关还能不能转域名、还能不能代理 LLM?能 → 那它就不是内核。 +//! * 共享内存只有 `RwLock, _>` 一种安全形态; +//! `SlabPool` 只能在 zone 初始化回调里取出,锁本身也必须用 +//! `ngx::allocator::allocate` 放进共享内存,否则各 worker 拿到的是各自的副本。 +//! * 热路径**永不回源**:每请求决策只读共享内存;任何写操作必须 +//! 先落文件、再写穿 shm,写 shm 失败必须 `log_err`。 -pub mod audit; +pub mod api; +pub mod auth; pub mod config; pub mod http; pub mod loc; @@ -24,10 +30,6 @@ pub mod plugin; pub mod session; pub mod state; pub mod store; +pub mod usage; pub mod users; pub mod util; - -/// 共享内存 zone 初始化是否已完成(供插件判断能否安全访问状态表)。 -pub fn zone_ready() -> bool { - state::zone_ready() -} diff --git a/source/rust/crates/ipass-core/src/loc.rs b/source/rust/crates/ipass-core/src/loc.rs index 7280c45..17ef011 100644 --- a/source/rust/crates/ipass-core/src/loc.rs +++ b/source/rust/crates/ipass-core/src/loc.rs @@ -1,45 +1,56 @@ -//! location 级开关查询。 +//! Location 开关契约 —— 内核与插件之间**唯一的契约点**。 //! -//! ## 为什么需要这一层 -//! -//! 阶段处理器要按 location 生效(`sso_api` / `sso_iap` 写在哪个 location, -//! 就只在那个 location 生效),但开关表 `ModuleConfig` 属于 gateway 的模块壳, -//! 插件 crate 无法直接访问。 -//! -//! 于是内核只定义「开关是什么」,由 gateway 在装配时注入「怎么查」—— -//! 插件因此不依赖模块壳的具体结构。 +//! 配置指令(`ipass_api` / `ipass_proxy` / `ipass_llm` / `ipass_apix`)由 gateway +//! 集中解析进 `ModuleConfig`;插件不认识 gateway,只通过 [`Switch`] 问一句 +//! 「我所在的 location 开了吗」。gateway 在 preconfiguration 注入查询实现 +//! ([`set_switch_fn`]),**未注入或未实现的变体一律保守返回 `false`** +//! ——返回 `true` 会让未装配的能力意外开门(sso 踩过的坑)。 +use core::sync::atomic::{AtomicUsize, Ordering}; + +use ngx::ffi::ngx_http_request_t; use ngx::http::Request; -/// 内核认识的 location 开关。新增插件时在这里加一项。 +/// location 能力的枚举。取 iPass 与 sso 的**并集**: +/// iPass 用 `Api / Proxy / Llm / Apix`;`Iap / Domain` 为 sso 预留, +/// 合流时不用改本枚举。 #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Switch { - /// 该 location 暴露管理 API 与协议端点(`/api/*`、`/oauth/*`、`/login`) + /// 该 location 暴露管理 API + 身份端点 Api, - /// 该 location 开启身份感知代理(IAP) + /// 预留(sso 用;iPass 未实现,恒 false) Iap, - /// 该 location 提供企业域名(子域名→后端)代理转发 + /// 预留(sso 用;iPass 未实现,恒 false) Domain, - /// 该 location 提供 LLM API 代理(slot→上游)转发 + /// 该 location 走「子域名 → 后端」转发 + Proxy, + /// 该 location 走 LLM 代理 Llm, + /// 该 location 走 API 代理 + Apix, } -/// 查询实现:无捕获闭包 → 普通 fn 指针。配置期设一次,之后只读。 -static SWITCH_FN: core::sync::atomic::AtomicPtr<()> = - core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()); +/// gateway 注入的查询实现:`(请求, 开关) -> 是否开启` +pub type SwitchFn = fn(&mut Request, Switch) -> bool; -/// 由 gateway 注入查询实现。 -pub fn set_switch_fn(f: fn(&mut Request, Switch) -> bool) { - SWITCH_FN.store(f as *mut (), core::sync::atomic::Ordering::SeqCst); +// fn 指针按 usize 原子存取(热路径上 access handler 每请求都要查,不能用 Mutex) +static SWITCH_FN: AtomicUsize = AtomicUsize::new(0); + +/// gateway 在 preconfiguration 阶段注入查询实现(早于任何请求) +pub fn set_switch_fn(f: SwitchFn) { + SWITCH_FN.store(f as *const () as usize, Ordering::Relaxed); } -/// 该请求所在 location 是否开启了这个开关。未注入时一律 false(保守)。 -pub fn enabled(r: &mut Request, s: Switch) -> bool { - let p = SWITCH_FN.load(core::sync::atomic::Ordering::SeqCst); - if p.is_null() { +/// 插件查询所在 location 是否开启自己的能力。 +/// **未注入实现时保守返回 `false`**——宁可关着,不可误开。 +pub fn enabled(r: *mut ngx_http_request_t, s: Switch) -> bool { + let p = SWITCH_FN.load(Ordering::Relaxed); + if p == 0 { return false; } - // SAFETY: 指针由 set_switch_fn 存入,类型即下列 fn 指针 - let f: fn(&mut Request, Switch) -> bool = unsafe { core::mem::transmute(p) }; - f(r, s) + // SAFETY: p 来自 set_switch_fn 存入的合法 fn 指针 + let f: SwitchFn = unsafe { core::mem::transmute(p) }; + // SAFETY: r 由 nginx 传入且有效;Request 只在本调用存续期内使用 + let mut req = unsafe { Request::from_ngx_http_request(r) }; + f(&mut req, s) } diff --git a/source/rust/crates/ipass-core/src/models.rs b/source/rust/crates/ipass-core/src/models.rs index a4b2764..bdcda27 100644 --- a/source/rust/crates/ipass-core/src/models.rs +++ b/source/rust/crates/ipass-core/src/models.rs @@ -1,174 +1,84 @@ //! 持久化数据模型。 //! -//! **内核只定义共性字段**——账号凭据(salt / pwd_hash / api_key)与身份声明 -//! (display_name / email / department / groups),以及任何「账号」都需要的 -//! 锁定状态。 -//! -//! 插件自己的字段(LLM 配额、临时授权、TOTP 等)一律走 [`User::extra`]: -//! 内核**透传但不解释**,因此新增插件字段不需要改内核一行代码,也不会把 -//! 领域知识渗进内核。 - -use serde::{Deserialize, Deserializer, Serialize}; -use std::collections::BTreeMap; +//! 字段名与旧版 `data/users.json` / `data/domains.json` **逐字对应**, +//! 以便新版直接接管旧数据文件、且管理台前端无需改动。 +use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::collections::BTreeMap; /// 账号表(`users.json`):以账号名为 key 的对象。 pub type UserTable = BTreeMap; /// 单个账号。 /// -/// 统一认证场景下,账号同时承载两层含义: -/// * **认证凭据**——`salt` / `pwd_hash`(登录)、`api_key`(机器调用); -/// * **身份声明**——`display_name` / `email` / `department` / `groups`, -/// 它们原样进入 OIDC claims 与 IAP 注入的 `X-Auth-*` 头, -/// 是下游系统做授权判断的依据(因此必须是可维护数据,不能写死在代码里)。 +/// `temp_grant_until` 是「临时授权权限」的到期时间戳;> now 表示当前拥有 +/// 该权限,申请临时域名时可跳过审核直接放行。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct User { pub username: String, /// 中文姓名等展示名。**只用于展示**,不参与鉴权、不参与热路径查询。 /// - /// `username` 规则是 ASCII,中文名塞不进账号名,所以「张三」这类实名单独放 - /// 这里;留空时前端与 claims 回落到 `username`。 + /// `username` 规则是 ASCII(`valid_username`),中文名塞不进账号名, + /// 所以「吴桂荣」这类实名单独放这里;留空时前端回落到 `username`。 #[serde(default)] pub display_name: String, /// `admin` | `user` - #[serde(default = "default_role")] pub role: String, pub salt: String, /// 迭代加盐 SHA-256 pub pwd_hash: String, - /// `sk_<48 位 hex>`:账号级机器凭据(`X-API-Key`)。 + /// `sk_<48 位 hex>`。 /// - /// 面向脚本/CI 这类不方便走浏览器登录的调用方,用于账号态接口(`/api/v1/*`)。 - #[serde(default)] + /// LLM 代理与域名接口**共用这一把 Key**——这正是「用同一套 Key 验证」 + /// 的落点,所以重置 Key 会同时影响两个入口。 pub api_key: String, - // ---- 统一认证身份字段(OAuth2 / OIDC 终端用户声明)---- - /// 用户邮箱(OIDC `email` 声明;userinfo / 注入头 `X-Auth-Email`) - #[serde(default)] - pub email: String, - /// 所属部门(注入头所需;OIDC 非标声明 `department`) - #[serde(default)] - pub department: String, - /// 用户组 / 角色集合(OIDC `groups`;注入头 `X-Auth-Groups` 为逗号串)。 + /// LLM 代理可用的上游 slot 白名单。空 = 不限。 /// - /// 反序列化接受两种写法:JSON 数组 `["rd","eng"]`,以及逗号分隔字符串 - /// `"rd,eng"`。后者是外部目录(MaxKey / Excel)导出时的常见形状, - /// 只认数组会让整张 users.json 反序列化失败 → 表现为「账号全部消失」。 - #[serde(default, deserialize_with = "de_groups")] - pub groups: Vec, + /// 老数据没有该字段,`serde(default)` 反序列化得空表,语义正好是「不限」。 + #[serde(default)] + pub allowed_models: Vec, + /// LLM 每分钟请求上限。老数据缺省 → 全局默认(`LLM_RPM_DEFAULT`);0 = 不限 + #[serde(default = "default_llm_rpm")] + pub llm_rpm: i64, + /// LLM 每日请求上限。老数据缺省 → 全局默认(`LLM_DAILY_DEFAULT`);0 = 不限 + #[serde(default = "default_llm_daily")] + pub llm_daily: i64, + #[serde(default)] + pub temp_grant_until: i64, #[serde(default)] pub created_at: i64, - // ---- 登录失败锁定(账号维度,对齐 MaxKey 登录失败策略)---- - /// 连续登录失败次数;成功登录即清零,达到阈值后进入锁定并清零重新计窗 - #[serde(default)] - pub failed_count: i64, - /// 锁定截止时间戳(秒);0 = 未锁定 - #[serde(default)] - pub locked_until: i64, - // ---- 插件字段(内核持有、透传,不解释)---- - // - // 共用一份 `users.json` 的落点:插件把自有字段写在这里,内核负责 - // 持久化与向后兼容,**不认识这些 key 的语义**。 - // - // `flatten` 的效果:读文件时未被上面字段认领的 key 自动进 `extra`; - // 写回时 `extra` 展开回顶层。因此存量账号文件(含别的插件写入的字段) - // 可以原样接管,不会因为内核不认识而丢数据。 - #[serde(flatten)] + + /// 插件字段透传:内核持有、**不解释**。 + /// + /// 反序列化时,文件中**未被上面字段认领的 key 自动进 `extra`**;序列化时 + /// 展开回顶层(`#[serde(flatten)]`)。`serde` 优先匹配已认领字段,所以 + /// 存量 `users.json`(含任何插件写入的字段)可原样接管,**不会因内核不 + /// 认识而丢数据**——这是 iPass 向上游 sso 合流的扩展点(A1)。 + /// + /// 未来插件要存 TOTP 密钥、邮箱、用户组、锁定状态……都直接往 `extra` + /// 写,不再走内核加字段。修改走 [`crate::users::update_extra`] 的 + /// 「读-改-写」原语。 + #[serde(default, flatten)] pub extra: BTreeMap, } -fn default_role() -> String { - "user".to_owned() -} - -/// 容忍 `["a","b"]` 与 `"a,b"` 两种写法的字段反序列化。 -fn de_groups<'de, D>(d: D) -> Result, D::Error> -where - D: Deserializer<'de>, -{ - #[derive(Deserialize)] - #[serde(untagged)] - enum Raw { - List(Vec), - Csv(String), - Null, - } - Ok(match Option::::deserialize(d)? { - None | Some(Raw::Null) => Vec::new(), - Some(Raw::List(v)) => v.into_iter().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect(), - Some(Raw::Csv(s)) => s - .split(|c: char| c == ',' || c == '、' || c == ';' || c == ' ') - .map(|x| x.trim().to_owned()) - .filter(|x| !x.is_empty()) - .collect(), - }) -} - impl User { + /// 是否拥有「临时授权权限」 + pub fn has_temp_permission(&self, now: i64) -> bool { + self.temp_grant_until > now + } + pub fn is_admin(&self) -> bool { self.role == "admin" } +} - /// 账号是否处于锁定状态(锁定到期自动视为未锁定) - pub fn is_locked(&self, now: i64) -> bool { - self.locked_until > now - } - /// 展示名优先,留空回落账号名。前端渲染与 OIDC `name` 共用同一规则。 - pub fn display_or_username(&self) -> String { - if self.display_name.is_empty() { - self.username.clone() - } else { - self.display_name.clone() - } - } +fn default_llm_rpm() -> i64 { + crate::config::LLM_RPM_DEFAULT +} - /// `groups` 的逗号串(注入头与 SSO 会话 payload 用)。 - pub fn groups_csv(&self) -> String { - self.groups.join(",") - } - - // ---- 插件字段访问器 ---- - // - // 只做「按类型取值」,**不解释业务含义**——那是插件的事。 - // 插件读写自己的字段请统一走 `users::update_extra`(内核持锁 + 原子写回)。 - - pub fn extra_get(&self, key: &str) -> Option<&Value> { - self.extra.get(key) - } - - pub fn extra_str(&self, key: &str) -> &str { - self.extra.get(key).and_then(Value::as_str).unwrap_or("") - } - - pub fn extra_i64(&self, key: &str) -> i64 { - self.extra - .get(key) - .and_then(Value::as_i64) - .or_else(|| self.extra.get(key).and_then(Value::as_f64).map(|f| f as i64)) - .unwrap_or(0) - } - - pub fn extra_bool(&self, key: &str) -> bool { - self.extra.get(key).and_then(Value::as_bool).unwrap_or(false) - } - - /// 取字符串列表(同时接受 `["a","b"]` 与 `"a,b"` 两种存量写法)。 - pub fn extra_str_list(&self, key: &str) -> Vec { - match self.extra.get(key) { - Some(Value::Array(arr)) => arr - .iter() - .filter_map(|v| v.as_str()) - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(), - Some(Value::String(s)) => s - .split(|c: char| c == ',' || c == '、' || c == ';' || c == ' ') - .map(|x| x.trim().to_owned()) - .filter(|x| !x.is_empty()) - .collect(), - _ => Vec::new(), - } - } +fn default_llm_daily() -> i64 { + crate::config::LLM_DAILY_DEFAULT } diff --git a/source/rust/crates/ipass-core/src/plugin.rs b/source/rust/crates/ipass-core/src/plugin.rs index c8beaa9..eac9aea 100644 --- a/source/rust/crates/ipass-core/src/plugin.rs +++ b/source/rust/crates/ipass-core/src/plugin.rs @@ -1,58 +1,66 @@ -//! 插件契约。 +//! 插件装配契约 —— 内核与插件之间唯一的接口。 //! -//! 插件是 **crate 级**的:编译期装配,与内核一起编进同一个 `.so`。 -//! 这不是偷懒——nginx 动态模块没有稳定 ABI,Rust 侧更是如此(每个 cdylib -//! 各链一份 `std`,跨模块传 `String` 就是双重 free)。把「插件」放在编译期, -//! 换来的是零 ABI 风险、单一共享内存 zone、单一变量注册。 +//! 沿用 ssw/sso 的形态,签名保持一致(若将来与 sso 合流,trait 不用再改)。 //! //! ## 刻意没有 `commands()` //! -//! nginx 的 `ngx_module_t.commands` 是一个 **null-terminated 连续数组**, -//! 而不同 crate 的 `static` 数组无法在 Rust 里自动拼接成一个。 -//! 因此配置指令(`sso_api` / `sso_iap` / `ipass_proxy` …)由 gateway 集中声明, -//! 插件通过 [`loc::Switch`] 查询自己所在 location 是否开启—— -//! 指令解析归壳、行为归插件,边界是清楚的。 +//! nginx 的 `ngx_module_t.commands` 是 null 结尾的**连续**数组,不同 crate 的 +//! `static` 数组无法拼接。配置指令由 gateway 集中声明(`ipass_*` 七条不变), +//! 插件通过 [`crate::loc::Switch`] 查询自己所在 location 是否开启—— +//! **指令解析归壳、行为归插件**。 +//! +//! ## `dispatch_api` 语义 +//! +//! 「不认领就返回 `None`,让下一个插件试」,**绝不自行 404**——否则后注册的 +//! 插件永远收不到请求。404 由 gateway 在全部插件都返回 `None` 后统一发出。 + +use core::sync::atomic::{AtomicUsize, Ordering}; use ngx::core::Status; use ngx::ffi::{ngx_conf_t, ngx_http_request_t}; -/// 一个能力插件。 -/// -/// 所有方法都有默认实现:插件只实现自己关心的阶段。 -/// 装配顺序 = gateway 里 `PLUGINS` 数组的顺序,**显式可控** -/// (这一点是多 .so 方案里保证不了的:那里取决于 `load_module` 的先后)。 +/// 本网关 `ngx_module_t` 的 `ctx_index`(gateway 在 postconfiguration 前 +/// 通过 [`set_ctx_index`] 注入)。插件用它在 `r->ctx` 上挂自己的请求级状态 +/// (如 usage_filter 的扫描窗口)。 +static CTX_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); + +pub fn set_ctx_index(idx: usize) { + CTX_INDEX.store(idx, Ordering::Relaxed); +} + +/// 当前模块的 ctx_index;`usize::MAX` = 尚未注入(此时插件应放弃请求级状态)。 +pub fn ctx_index() -> usize { + CTX_INDEX.load(Ordering::Relaxed) +} + pub trait Plugin: Sync { + /// 插件名(日志与排障用) fn name(&self) -> &'static str; - /// preconfiguration:注册 nginx 变量等。返回 false = 启动失败。 + /// 配置解析前:注册本插件自己的 nginx 变量。 + /// 返回 false = 注册失败,gateway 会 EMERG 退出。 fn preconfig(&self, _cf: *mut ngx_conf_t) -> bool { true } - /// postconfiguration:注册阶段处理器(access / content …)。 + /// 配置解析后:注册 phase handler / body filter。 + /// 返回 false = 注册失败,gateway 会 EMERG 退出。 fn postconfig(&self, _cf: *mut ngx_conf_t) -> bool { true } - /// 管理接口分发。`None` = 该路由不归我,继续问下一个插件。 + /// 管理 API 分发:认领则返回响应状态,不认领返回 `None`。 fn dispatch_api(&self, _r: *mut ngx_http_request_t) -> Option { None } - /// 共享内存 zone 初始化时的预装载,返回装载条数(仅用于日志)。 - /// - /// 在 **fork 之前**执行,所有 worker 共享结果——比放在 `init_process` - /// 里每个 worker 各跑一遍省掉 N-1 次文件读与 JSON 解析。 + /// fork 前预装载共享内存(zone init 回调里调用一次)。 + /// 返回装载条数(gateway 汇总打日志)。 fn zone_load(&self) -> usize { 0 } - /// log 阶段回调(请求收尾时、worker 内、请求池仍有效)。 - /// - /// 默认实现返回 `true`(「本插件已处理,继续问下一个」的语义对 log 阶段 - /// 无意义,true 仅表示「不拦截」)。插件用它做「转发完成后」的旁路记录 - /// (如上游健康标记),**不能**改写响应、不能阻断请求。返回 false 表示 - /// 该插件认为需要中止后续 log 处理——当前实现中无插件会返回 false。 + /// log 阶段旁路处理器(与 sso 对齐保留;返回 true 表示已处理)。 fn log_handler(&self, _r: *mut ngx_http_request_t) -> bool { true } diff --git a/source/rust/crates/ipass-core/src/session.rs b/source/rust/crates/ipass-core/src/session.rs index cf5080c..35d05f7 100644 --- a/source/rust/crates/ipass-core/src/session.rs +++ b/source/rust/crates/ipass-core/src/session.rs @@ -1,12 +1,10 @@ //! 管理员登录会话。 //! -//! 会话存在共享内存里:**nginx 重启即全部失效**,这是预期行为。 +//! 会话存在共享内存里:**nginx 重启即全部失效**,这是预期行为 +//! (旧版用 `lua_shared_dict admin_sessions`,同样如此)。 //! -//! Cookie 为 `sso_admin_session=<64 位 hex>`,HttpOnly + SameSite=Strict, -//! 每次校验命中都会滑动续期。 -//! -//! 与 SSO 终端用户会话(`oauth` 模块的 `sso_sid`)**刻意分开**:管理台身份 -//! 与业务系统身份是两条信任线,共用一套会让「能登录业务系统」等价于「能改配置」。 +//! Cookie 为 `ipass_admin_session=<64 位 hex>`,HttpOnly + SameSite=Strict, +//! 每次校验命中都会滑动续期(与旧版一致)。 use crate::config::{COOKIE_NAME, SESSION_TTL}; use crate::state; diff --git a/source/rust/crates/ipass-core/src/state.rs b/source/rust/crates/ipass-core/src/state.rs index 250a329..5dcaa4f 100644 --- a/source/rust/crates/ipass-core/src/state.rs +++ b/source/rust/crates/ipass-core/src/state.rs @@ -1,21 +1,19 @@ //! 共享内存状态层。 //! -//! 「配置放内存」的落点。全部派生状态集中在一张 `RbTreeMap` 里,用键前缀区分用途: +//! 这是「配置放内存」的落点,替代旧版的 `lua_shared_dict proxy_cache / +//! admin_sessions / lua_locks` 三个字典。全部派生状态集中在一张 +//! `RbTreeMap` 里,用键前缀区分用途: //! //! ```text -//! sess: → \x1f 管理员会话 +//! sub: → \x1f 转发映射 +//! sess: → \x1f 管理会话 //! fail: → \x1f 登录失败计数 -//! sso: → <身份 payload> \x1f SSO 终端用户会话 -//! oac: → <授权上下文 JSON> \x1f 授权码(一次性) -//! ocl: → <客户端 JSON> \x1f 0 OAuth 接入方注册表 //! ``` //! -//! 为什么这些派生状态不直接读文件?——`/oauth/authorize`、IAP 门禁(access 阶段) -//! 都是**每请求**路径,一次同步文件 I/O + 全表 JSON 解码就是明显的尾延迟。 -//! //! ## 为什么过期时间写在 value 里,而不是靠字典的 TTL //! -//! `RbTreeMap` 是纯数据结构,没有 TTL。因此把到期时刻编码进 value,读取时判断—— +//! 旧版 `lua_shared_dict` 自带 `set(key, val, ttl)` 自动回收;`RbTreeMap` +//! 是纯数据结构,没有 TTL。因此把到期时刻编码进 value,读取时判断—— //! 语义上反而更精确(到期即失效,不受回收延迟影响)。 //! //! ## 为什么锁必须放进共享内存 @@ -32,36 +30,29 @@ use ngx::core::{NgxStr, NgxString, SlabPool, Status}; use ngx::ffi::ngx_shm_zone_t; use ngx::sync::{RwLock, RwLockWriteGuard}; -use crate::config::{KEY_BUF_LEN, VAL_SEP}; +use crate::config::{KEY_BUF_LEN, KEY_UKEY_PREFIX, VAL_SEP}; -/// 全部映射的底层容器 +/// 子域名 → 后端、token → 用户名等全部映射的底层容器 pub type ShmMap = RbTreeMap, NgxString, SlabPool>; /// 共享内存根对象:一张表 + 一把文件写锁。 /// /// 文件写锁**独立于表的读写锁**:文件 I/O 期间若持有表的写锁, -/// 会把所有读共享内存的请求(需要读锁)一起卡住。 +/// 会把所有转发请求(需要读锁)一起卡住。分开后,域名的热路径只受 +/// 自身短临界区影响。 pub struct ShmRoot { pub map: RwLock, /// 保护 `store` 的「读-改-写」与落盘,跨 worker 互斥 pub file_lock: RwLock<()>, } -/// 由 `sso_state ` 注册的共享内存区 +/// 由 `ipass_state ` 注册的共享内存区 static STATE_ZONE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); pub fn set_zone(zone: *mut ngx_shm_zone_t) { STATE_ZONE.store(zone, Ordering::SeqCst); } -/// zone 是否已注册(`sso_state` 指令解析完成)。 -/// -/// 插件在 zone 初始化钩子之外访问状态表前可用它做保守判断; -/// 未注册时所有读写都会走「无 zone」分支,宁可空也不可崩。 -pub fn zone_ready() -> bool { - !STATE_ZONE.load(Ordering::SeqCst).is_null() -} - /// 在 slab 池上构造 `ShmRoot` 并挂到 `shpool->data`;重复调用直接复用。 fn init_root(zone: &mut ngx_shm_zone_t) -> Result<&'static ShmRoot, Status> { // SAFETY: zone 由 ngx_shared_memory_add 注册,init 回调已使其 shm 可用 @@ -134,10 +125,10 @@ fn key_buf(prefix: &[u8], name: &[u8]) -> Option<([u8; KEY_BUF_LEN], usize)> { /// 拆 value:` \x1f ` /// -/// 按**最后一个** `VAL_SEP` 切分(`rposition`)。到期时刻恒为 value 末尾的十进制 -/// 整数,而 payload 里可能合法地含有 `VAL_SEP`——例如 SSO 会话的身份字段串。 -/// 用 `position`(第一个分隔符)会把这类 payload 腰斩,并把后面的残段当 expiry -/// 解析而失败,表现为「刚写入就查不到」。 +/// 用 `rposition` 而非 `position`:value 是「payload + 分隔符 + exp」三段, +/// `exp` 必为 ASCII 数字串、不含 `VAL_SEP`,所以**最后一个**分隔符才是真边界。 +/// 用 `position` 会被 payload 里内嵌的 `0x1f` 截断(OAuth 授权码 / 带 +/// 注入头的会话 payload 都可能含此字节)——sso 上游化时已踩此坑。 fn split_value(bytes: &[u8]) -> Option<(&[u8], i64)> { let sep = bytes.iter().rposition(|&b| b == VAL_SEP)?; let payload = &bytes[..sep]; @@ -150,6 +141,8 @@ fn split_value(bytes: &[u8]) -> Option<(&[u8], i64)> { // =========================================================================== /// 查表。返回 `(payload, expires_at)`;键不存在或值损坏时返回 None。 +/// +/// **转发热路径唯一入口**——只读共享内存,未命中不产生任何 I/O。 pub fn get(prefix: &[u8], name: &[u8]) -> Option<(String, i64)> { let (buf, n) = key_buf(prefix, name)?; let root = root()?; @@ -157,7 +150,7 @@ pub fn get(prefix: &[u8], name: &[u8]) -> Option<(String, i64)> { let value = guard.get(NgxStr::from_bytes(&buf[..n]))?; let (payload, exp) = split_value(value.as_bytes())?; // 复制成 owned:guard 释放后共享内存可能被并发写覆盖, - // 直接返回引用会悬垂。 + // 直接返回引用会悬垂。一次小字符串分配远小于转发本身的代价。 Some((String::from_utf8_lossy(payload).into_owned(), exp)) } @@ -209,9 +202,15 @@ pub fn remove(prefix: &[u8], name: &[u8]) -> bool { root.map.write().remove(NgxStr::from_bytes(&key)).is_some() } +/// 当前条目数(管理端观测用;当前无调用方,保留为诊断接口) +#[allow(dead_code)] +pub fn len() -> usize { + root().map(|r| r.map.read().iter().count()).unwrap_or(0) +} + /// 只清掉某一前缀下的所有键。 /// -/// 重载注册表时用——**不能**用 `clear()`,那会把正在登录的管理员会话一起清掉。 +/// 重载转发映射时用——**不能**用 `clear()`,那会把正在登录的管理员会话一起清掉。 pub fn clear_prefix(prefix: &[u8]) { let Some(root) = root() else { return; @@ -227,15 +226,30 @@ pub fn clear_prefix(prefix: &[u8]) { /// 遍历某前缀下的全部条目,返回 `(去掉前缀的键名, payload)`。 /// -/// **低频读**接口(管理台/诊断),每次都会克隆字符串出来。 -#[allow(dead_code)] +/// 这是**低频读**接口(管理台聚合用量统计),不是热路径——每次都会克隆一份 +/// 字符串出来,别拿它做每请求调用。`expires_at` 刻意不返回:统计键永不过期, +/// 调用方用 payload 里的日窗 id 自行判断"今日"。 pub fn iter_prefix(prefix: &[u8]) -> Vec<(String, String)> { - iter_prefix_ex(prefix).into_iter().map(|(k, p, _)| (k, p)).collect() + let Some(root) = root() else { + return Vec::new(); + }; + let guard = root.map.read(); + guard + .iter() + .filter_map(|(k, v)| { + let name = k.as_bytes().strip_prefix(prefix)?; + let (payload, _) = split_value(v.as_bytes())?; + Some(( + String::from_utf8_lossy(name).into_owned(), + String::from_utf8_lossy(payload).into_owned(), + )) + }) + .collect() } -/// 同 `iter_prefix`,但额外返回到期时间戳。 -/// -/// 会话管理接口用它区分「还活着」与「已过期但尚未被覆盖」的条目。 +/// 与 [`iter_prefix`] 相同,但**额外返回 `expires_at`**——用于会话 / OAuth +/// kick / 过期扫描等需要判断 exp 的场景。`iter_prefix` 保留兼容(统计键 +/// 永不过期、不需要 exp)。 pub fn iter_prefix_ex(prefix: &[u8]) -> Vec<(String, String, i64)> { let Some(root) = root() else { return Vec::new(); @@ -255,14 +269,8 @@ pub fn iter_prefix_ex(prefix: &[u8]) -> Vec<(String, String, i64)> { .collect() } -/// 当前条目数(诊断用) -#[allow(dead_code)] -pub fn len() -> usize { - root().map(|r| r.map.read().iter().count()).unwrap_or(0) -} - // =========================================================================== -// 管理会话 +// 业务语义封装 // =========================================================================== /// 管理会话写入 @@ -279,13 +287,13 @@ pub fn remove_session(token: &str) -> bool { remove(crate::config::KEY_SESS_PREFIX, token.as_bytes()) } -// =========================================================================== -// 登录失败计数(按 IP 限速) -// =========================================================================== - /// 登录失败计数:返回自增后的值 pub fn bump_login_fail(ip: &str, now: i64) -> i64 { - let current = get_login_fail(ip, now); + let current = match get(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()) { + Some((_, exp)) if exp > 0 && exp <= now => 0, + Some((payload, _)) => payload.parse::().unwrap_or(0), + None => 0, + }; let next = current + 1; put( crate::config::KEY_FAIL_PREFIX, @@ -307,3 +315,46 @@ pub fn get_login_fail(ip: &str, now: i64) -> i64 { pub fn clear_login_fail(ip: &str) { remove(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()); } + +/// 窗口计数(限流/配额共用):键固定,value = `<窗口id>:<计数>`,永不过期 +/// (`expires_at = 0`)——跨窗归零靠读时比对窗 id,键数只随用户数增长。 +/// 返回自增后的计数。 +/// +/// 读-增-写跨 worker **没有互斥**:`bump_login_fail` 同款近似语义。 +/// 对限流来说,并发下偶发少计数只是放宽一两 个请求的边界,可接受; +/// 为此上写锁反而让每个 LLM 请求都串行化,得不偿失。 +pub fn bump_window(prefix: &[u8], name: &str, window: i64) -> i64 { + let current = window_count(prefix, name, window); + let next = current + 1; + put(prefix, name.as_bytes(), format!("{}:{}", window, next).as_bytes(), 0); + next +} + +/// 读窗口计数(未跨窗时),管理台展示用量用 +pub fn window_count(prefix: &[u8], name: &str, window: i64) -> i64 { + match get(prefix, name.as_bytes()) { + Some((payload, _)) => match payload.split_once(':') { + Some((w, c)) if w == window.to_string() => c.parse::().unwrap_or(0), + _ => 0, + }, + None => 0, + } +} + +// =========================================================================== +// LLM 代理 +// =========================================================================== + +/// 写入 API Key → 身份索引。 +/// +/// payload = ` \n \n \n `(4 行,与 `users::identity_payload` 一致)。 +/// **永不过期**(`expires_at = 0`):它的生命周期完全跟随 accounts 表的增删, +/// 由 `users` 模块在每次写操作后显式同步——这里不能再加一层 TTL, +/// 否则会出现「账号还在、Key 偶尔 401」这种极难复现的状态。 +pub fn put_ukey(api_key: &str, payload: &str) -> bool { + put(KEY_UKEY_PREFIX, api_key.as_bytes(), payload.as_bytes(), 0) +} + +pub fn remove_ukey(api_key: &str) -> bool { + remove(KEY_UKEY_PREFIX, api_key.as_bytes()) +} diff --git a/source/rust/crates/ipass-core/src/store.rs b/source/rust/crates/ipass-core/src/store.rs index f20b2f8..ae75713 100644 --- a/source/rust/crates/ipass-core/src/store.rs +++ b/source/rust/crates/ipass-core/src/store.rs @@ -1,6 +1,8 @@ //! JSON 文件存储层:原子写 + 跨 worker 互斥。 //! -//! **状态就是两个 JSON 文件**,不引入数据库。互斥锁用共享内存里的 `RwLock`。 +//! 与旧版 `lua/store.lua` 语义一致——**状态就是几个 JSON 文件**,不引入数据库。 +//! 差别只有一处:互斥锁从 `resty.lock`(基于 lua_shared_dict)换成共享内存里的 +//! `RwLock`,因为新版已经有一块共享内存了,不必再造一个字典。 //! //! 所有写操作统一走 `update_*`,流程固定为: //! @@ -8,28 +10,30 @@ //! 取全局文件写锁 → 读文件 → 闭包修改 → 原子写回 → 放锁 //! ``` //! -//! 闭包返回 `Err` 表示业务校验失败,此时**不落盘**。 +//! 闭包返回 `Err` 表示业务校验失败,此时**不落盘**(与旧版 `fn` 返回 nil 一致)。 //! //! ## 表的分工 //! -//! | 文件 | 内容 | 归属 | +//! | 文件 | 内容 | 是否进共享内存 | //! | --- | --- | --- | -//! | `users.json` | 账号、口令哈希、身份声明 + 插件字段(`extra`) | **内核独占** | -//! | 插件自有文件 | 如 `oauth_clients.json` | 插件定义模型,内核只提供读写通道 | +//! | `users.json` | 账号、口令哈希、API Key | `ukey:` 索引进(热路径要它) | +//! | `domains.json` | 子域名 → 后端映射 | `sub:` 进(转发热路径) | +//! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) | +//! | `api-proxies.json` | API 代理清单(每条含各自供应商凭据) | `ax:` 进(API 代理热路径) | //! -//! 文件都在 `data/` 下,都已 `.gitignore`(含口令哈希与客户端密钥)。 +//! 内核只直接管 `users.json`;其余数据文件由各插件经 `path_in_data` + +//! 通用读写原语自管(plugin-domain / plugin-llm / plugin-apix)。四个文件 +//! 都在 `data/` 下,都已 `.gitignore`。**LLM 上游表与 API 代理表含真实 +//! 供应商 Key,敏感级别与 `users.json` 相同**,不要再往别处复制。 -use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Mutex; -use serde_json::Value; - use crate::config::DEFAULT_DATA_DIR; use crate::models::UserTable; use crate::state; -/// 状态目录。配置阶段由 `sso_data_dir` 指令设置一次,之后只读。 +/// 状态目录。配置阶段由 `ipass_data_dir` 指令设置一次,之后只读。 static DATA_DIR: Mutex> = Mutex::new(None); pub fn set_data_dir(dir: &str) { @@ -54,11 +58,9 @@ pub fn users_path() -> PathBuf { path_of("users.json") } -/// 插件自有数据文件的路径(`data/`)。 -/// -/// 内核提供**存储能力**(带锁原子写),但不知道文件里是什么——插件的 -/// 数据模型由插件自己定义,内核不参与。 -pub fn plugin_path(name: &str) -> PathBuf { +/// data 目录下任意文件的路径(插件用它管理自己的数据文件, +/// 如 plugin-domain 的 `domains.json`) +pub fn path_in_data(name: &str) -> PathBuf { path_of(name) } @@ -66,8 +68,8 @@ pub fn plugin_path(name: &str) -> PathBuf { // 读写 // =========================================================================== -/// 读取并反序列化;文件缺失或损坏时回退 `default`(不抛错,保证认证侧可用) -fn read_json(path: &PathBuf, default: T) -> T { +/// 读取并反序列化;文件缺失或损坏时回退 `default`(不抛错,保证转发侧可用) +pub fn read_json(path: &PathBuf, default: T) -> T { let Ok(text) = std::fs::read_to_string(path) else { return default; }; @@ -77,8 +79,7 @@ fn read_json(path: &PathBuf, default: T) -> T { match serde_json::from_str(&text) { Ok(v) => v, Err(e) => { - // 解析失败必须留痕:静默回退会让「数据看起来还在、实际全空」极难排查。 - // 典型触发是有人手工编辑 users.json 时把 groups 写成了非法形状。 + // 解析失败必须留痕:静默回退会让「数据看起来还在、实际全空」极难排查 crate::util::log_err(&format!( "[store] 解析失败,回退默认值:{} ({e})", path.display() @@ -89,8 +90,8 @@ fn read_json(path: &PathBuf, default: T) -> T { } /// 原子写:先写 `.tmp` 再 rename,避免读到写了一半的内容 -fn write_json(path: &PathBuf, value: &T) -> Result<(), String> { - let text = serde_json::to_string_pretty(value).map_err(|e| format!("序列化失败:{e}"))?; +pub fn write_json(path: &PathBuf, value: &T) -> Result<(), String> { + let text = serde_json::to_string(value).map_err(|e| format!("序列化失败:{e}"))?; let tmp = PathBuf::from(format!("{}.tmp", path.display())); std::fs::write(&tmp, text.as_bytes()).map_err(|e| { @@ -129,44 +130,3 @@ where write_users(&data)?; Ok(out) } - -/// 单个账号的**插件字段**更新(`User::extra`)。 -/// -/// 这是插件往共用 `users.json` 写自有字段的**唯一入口**:内核持锁、原子写回, -/// 插件拿到的只有 `extra` 这张表,碰不到共性字段(role / 口令 / 锁定)。 -pub fn update_extra(username: &str, f: F) -> Result -where - F: FnOnce(&mut BTreeMap) -> Result, -{ - update_users(|table| { - let user = table.get_mut(username).ok_or_else(|| "账号不存在".to_owned())?; - f(&mut user.extra) - }) -} - -// =========================================================================== -// 插件自有数据文件 -// -// 与 `update_users` 同构(取全局文件锁 → 读 → 闭包改 → 原子写回 → 放锁), -// 只是数据模型由插件给出。典型用法:OAuth 客户端注册表、域名映射表。 -// =========================================================================== - -pub fn read_plugin(name: &str) -> T { - read_json(&plugin_path(name), T::default()) -} - -pub fn write_plugin(name: &str, data: &T) -> Result<(), String> { - write_json(&plugin_path(name), data) -} - -pub fn update_plugin(name: &str, f: F) -> Result -where - T: serde::de::DeserializeOwned + serde::Serialize + Default, - F: FnOnce(&mut T) -> Result, -{ - let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; - let mut data = read_plugin(name); - let out = f(&mut data)?; - write_plugin(name, &data)?; - Ok(out) -} diff --git a/source/rust/crates/ipass-core/src/usage.rs b/source/rust/crates/ipass-core/src/usage.rs new file mode 100644 index 0000000..ce85dbf --- /dev/null +++ b/source/rust/crates/ipass-core/src/usage.rs @@ -0,0 +1,239 @@ +//! 通用记账原语(无任何业务语义)。 +//! +//! 只回答「给这个前缀下的这个键 +1」「这个键现在的读数是什么」—— +//! **不认识** `ust:` 与 `ums:` 的区别,更不认识「LLM」「token」这些词。 +//! 业务解读(趋势 / 总览 / 按人聚合)在 plugin-llm 的 `stats` 模块, +//! 它把键前缀与本模块的原语组合起来。 +//! +//! value 编码共用两种: +//! * 窗口读数:`<日窗id>:<今日数>:<累计数>:<最近调用时间戳>` +//! * 日桶:`<请求数>:<入>:<出>`(趋势图数据源,TTL 到期自然淘汰) + +use serde_json::{Value, json}; + +use crate::state; +use crate::util; + +/// 一条统计记录的读数。`today` 已按调用方给的日窗折算过(跨天即为 0)。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Usage { + /// 今日(本地自然日)计数 + pub today: i64, + /// 累计计数(自该计数键建立以来,不随跨天归零) + pub total: i64, + /// 最近一次记账时间戳;0 = 从未 + pub last_ts: i64, +} + +impl Usage { + /// 累加(聚合用)。`last_ts` 取最大。 + pub fn merge(&mut self, other: &Usage) { + self.today += other.today; + self.total += other.total; + if other.last_ts > self.last_ts { + self.last_ts = other.last_ts; + } + } + + pub fn json(&self) -> Value { + json!({ + "today": self.today, + "total": self.total, + "last_ts": self.last_ts, + "last_ts_text": if self.last_ts > 0 { util::fmt_time(self.last_ts) } else { String::new() }, + }) + } +} + +/// token 计量读数。日窗语义与 [`Usage`] 相同:跨天 today 归零、累计保留。 +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct TokenUsage { + /// 今日入 token + pub tin_today: i64, + /// 累计入 token + pub tin_total: i64, + /// 今日出 token + pub tout_today: i64, + /// 累计出 token + pub tout_total: i64, + /// 最近一次有 token 记账的调用时间戳;0 = 从未 + pub last_ts: i64, +} + +impl TokenUsage { + /// 累加(聚合用)。`last_ts` 取最大。 + pub fn merge(&mut self, other: &TokenUsage) { + self.tin_today += other.tin_today; + self.tin_total += other.tin_total; + self.tout_today += other.tout_today; + self.tout_total += other.tout_total; + if other.last_ts > self.last_ts { + self.last_ts = other.last_ts; + } + } + + pub fn json(&self) -> Value { + json!({ + "in_today": self.tin_today, + "in_total": self.tin_total, + "out_today": self.tout_today, + "out_total": self.tout_total, + "last_ts": self.last_ts, + "last_ts_text": if self.last_ts > 0 { util::fmt_time(self.last_ts) } else { String::new() }, + }) + } +} + +/// 一天的聚合值(日桶) +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DayBucket { + pub requests: i64, + pub tin: i64, + pub tout: i64, +} + +impl DayBucket { + pub fn merge(&mut self, other: &DayBucket) { + self.requests += other.requests; + self.tin += other.tin; + self.tout += other.tout; + } +} + +// =========================================================================== +// 窗口读数(<日窗id>:<今日>:<累计>:<最近时间戳>) +// =========================================================================== + +fn encode(day: i64, u: &Usage) -> String { + format!("{}:{}:{}:{}", day, u.today, u.total, u.last_ts) +} + +/// 解码并把"今日数"按当前日窗折算——跨天时旧值归零,累计值保留。 +fn decode(payload: &str, day: i64) -> Usage { + let mut it = payload.split(':'); + let stored_day = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let last_ts = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + Usage { today: if stored_day == day { today } else { 0 }, total, last_ts } +} + +/// 窗口计数 +1(读-增-写不加写锁的近似语义:并发下偶发少计一次, +/// 统计用途无影响;换来的是调用方热路径不为统计抢锁)。 +pub fn bump(prefix: &[u8], name: &str, day: i64, now: i64) { + let current = state::get(prefix, name.as_bytes()) + .map(|(payload, _)| decode(&payload, day)) + .unwrap_or_default(); + + let next = Usage { + today: current.today + 1, + total: current.total + 1, + last_ts: now, + }; + state::put(prefix, name.as_bytes(), encode(day, &next).as_bytes(), 0); +} + +/// 读窗口读数(不跨窗折算由 decode 按 day 完成) +pub fn read(prefix: &[u8], name: &str, day: i64) -> Usage { + state::get(prefix, name.as_bytes()) + .map(|(payload, _)| decode(&payload, day)) + .unwrap_or_default() +} + +// =========================================================================== +// token 窗口读数(<日窗id>:<入今日>:<入累计>:<出今日>:<出累计>:<最近时间戳>) +// =========================================================================== + +fn encode_t(day: i64, t: &TokenUsage) -> String { + format!( + "{}:{}:{}:{}:{}:{}", + day, t.tin_today, t.tin_total, t.tout_today, t.tout_total, t.last_ts + ) +} + +fn decode_t(payload: &str, day: i64) -> TokenUsage { + let mut it = payload.split(':'); + let stored_day = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let in_today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let in_total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let out_today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let out_total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let last_ts = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); + let live = stored_day == day; + TokenUsage { + tin_today: if live { in_today } else { 0 }, + tin_total: in_total, + tout_today: if live { out_today } else { 0 }, + tout_total: out_total, + last_ts, + } +} + +/// token 窗口累加(同 bump 的近似语义) +pub fn bump_t(prefix: &[u8], name: &str, tin: u64, tout: u64, day: i64, now: i64) { + let current = state::get(prefix, name.as_bytes()) + .map(|(payload, _)| decode_t(&payload, day)) + .unwrap_or_default(); + let next = TokenUsage { + tin_today: current.tin_today + tin as i64, + tin_total: current.tin_total + tin as i64, + tout_today: current.tout_today + tout as i64, + tout_total: current.tout_total + tout as i64, + last_ts: now, + }; + state::put(prefix, name.as_bytes(), encode_t(day, &next).as_bytes(), 0); +} + +/// 读 token 窗口读数 +pub fn read_t(prefix: &[u8], name: &str, day: i64) -> TokenUsage { + state::get(prefix, name.as_bytes()) + .map(|(payload, _)| decode_t(&payload, day)) + .unwrap_or_default() +} + +// =========================================================================== +// 日桶(趋势图数据源) +// =========================================================================== +// +// 以自然日为键的桶:一个桶一天,读取时按日窗 id **精确取键**(get_live), +// 不做前缀扫描——键数随时间增长也不会拖慢任何热路径。 +// TTL 由调用方传入(业务保留策略属于插件,不属于本模块)。 + +/// `<请求数>:<入token>:<出token>` +fn encode_day(b: &DayBucket) -> String { + format!("{}:{}:{}", b.requests, b.tin, b.tout) +} + +fn decode_day(payload: &str) -> DayBucket { + let mut it = payload.split(':'); + let num = |v: Option<&str>| v.and_then(|s| s.parse::().ok()).unwrap_or(0); + DayBucket { + requests: num(it.next()), + tin: num(it.next()), + tout: num(it.next()), + } +} + +/// 累加一日桶。`ttl_secs` 为保留时长(到期由共享内存自然淘汰)。 +pub fn bump_day(prefix: &[u8], name: &str, delta: &DayBucket, ttl_secs: i64) { + let mut next = state::get_live(prefix, name.as_bytes(), util::now()) + .map(|p| decode_day(&p)) + .unwrap_or_default(); + next.merge(delta); + // 写入失败只记日志:统计是旁路功能,绝不影响转发 + if !state::put( + prefix, + name.as_bytes(), + encode_day(&next).as_bytes(), + util::now() + ttl_secs, + ) { + util::log_err("[usage] 日桶写入失败(共享内存不足?)"); + } +} + +/// 读一个日桶(不存在 = 全 0) +pub fn day_bucket(prefix: &[u8], name: &str) -> DayBucket { + state::get_live(prefix, name.as_bytes(), util::now()) + .map(|p| decode_day(&p)) + .unwrap_or_default() +} diff --git a/source/rust/crates/ipass-core/src/users.rs b/source/rust/crates/ipass-core/src/users.rs index 512d339..9b41d1d 100644 --- a/source/rust/crates/ipass-core/src/users.rs +++ b/source/rust/crates/ipass-core/src/users.rs @@ -1,30 +1,61 @@ //! 账号体系:管理员与普通账号共用一张表。 //! -//! 数据结构见 `models::User`。本模块是**账号真源**,两条对外语义: +//! 对应旧版 `lua/users.lua`。数据结构见 `models::User`。 //! -//! 1. **认证**——`get` / `find_by_key` 供登录、OAuth `password` grant、 -//! 账号态 API 校验凭据; -//! 2. **身份声明**——`email` / `department` / `groups` 由 OIDC claims 与 -//! IAP 的 `X-Auth-*` 注入读取,是下游系统做授权的唯一依据。 +//! 「临时授权权限」= 该账号申请**临时域名**时可跳过管理员审核、直接放行。 +//! 注意它只对 temp 生效,long 域名无论谁申请都要审核。 //! -//! ## 与共享内存的关系 +//! ## 与 LLM 代理共用同一把 Key //! -//! 账号**不进共享内存**:登录是低频操作,直接读 `users.json` 即可; -//! 真正每请求的热路径(授权、IAP 门禁)只碰 `sso:` 会话与 `ocl:` 注册表。 -//! 这与被剥离项目里「API Key 索引进 `ukey:` 供 LLM 热路径查」的做法不同—— -//! 那是为每请求的转发决策服务的,本项目没有这一层。 +//! `api_key` 同时是域名接口(`X-API-Key`)与 LLM 代理 +//! (`Authorization: Bearer`)的凭据——这正是「用同一套 Key 验证」的落点。 +//! 代价是**任何改动 `api_key` 的操作都必须同步共享内存索引**, +//! 且重置 Key 时必须**先摘掉旧索引**,否则被换掉的 Key 依然能用。 + +use std::collections::BTreeMap; +use std::sync::Mutex; use serde_json::{Value, json}; use crate::config::{ - DEPARTMENT_MAX_LEN, DISPLAY_NAME_MAX_LEN, GROUPS_MAX, GROUP_NAME_MAX_LEN, - INIT_ADMIN_PASSWORD_DEFAULT, INIT_ADMIN_PASSWORD_ENV, INIT_ADMIN_USER, PASSWORD_MIN_LEN, - USERNAME_MAX_LEN, USERNAME_MIN_LEN, + DISPLAY_NAME_MAX_LEN, INIT_ADMIN_PASSWORD_DEFAULT, INIT_ADMIN_PASSWORD_ENV, INIT_ADMIN_USER, + KEY_UKEY_PREFIX, PASSWORD_MIN_LEN, TEMP_GRANT_TTL, USERNAME_MAX_LEN, USERNAME_MIN_LEN, }; use crate::models::{User, UserTable}; +use crate::state; use crate::store; use crate::util; +// =========================================================================== +// 账号删除钩子 +// =========================================================================== + +/// 「账号被删除时我需要清理什么」的回调注册表。 +/// +/// 内核只负责自己的键(`ukey:` / `sess:` / `fail:`),插件的键空间(用量账本、 +/// 代理索引……)内核**不认识**——删除账号要摘几个前缀,取决于装了哪些插件, +/// 所以只能由插件在装载阶段调用 [`on_delete`] 注册清理器(如 plugin-llm 注册 +/// `stats::forget`)。**重复注册同一函数会被去重**(nginx reload 会多次走到注册点)。 +static ON_DELETE: Mutex> = Mutex::new(Vec::new()); + +/// 插件注册「账号被删除时我需要清理什么」。在 zone 装载后、接请求前调用一次。 +pub fn on_delete(f: fn(&str)) { + if let Ok(mut hooks) = ON_DELETE.lock() { + if !hooks.contains(&f) { + hooks.push(f); + } + } +} + +/// 账号删除成功后执行全部钩子。单个钩子没有失败语义(清理动作自身幂等)。 +fn run_delete_hooks(username: &str) { + if let Ok(hooks) = ON_DELETE.lock() { + for f in hooks.iter() { + f(username); + } + } +} + // =========================================================================== // 校验 // =========================================================================== @@ -39,9 +70,8 @@ fn valid_username(name: &str) -> bool { } /// 展示名:允许中文/空格,但**不允许换行或制表等控制字符**—— -/// 它会被塞进管理台 HTML(已转义)、JSON 与注入头,控制字符只会造成排版错乱 -/// 或头注入。 -pub fn check_display_name(raw: &str) -> Result { +/// 它会被塞进管理台 HTML(已转义)与 JSON,控制字符只会造成排版错乱。 +fn check_display_name(raw: &str) -> Result { let v = util::trim(raw).to_owned(); if v.chars().count() > DISPLAY_NAME_MAX_LEN { return Err(format!("展示名不能超过 {DISPLAY_NAME_MAX_LEN} 个字")); @@ -52,54 +82,62 @@ pub fn check_display_name(raw: &str) -> Result { Ok(v) } -/// 邮箱:只做「像不像」的宽松校验。**不接受控制字符**——它会被注入 HTTP 响应头。 -pub fn check_email(raw: &str) -> Result { - let v = util::trim(raw).to_owned(); - if v.is_empty() { - return Ok(v); - } - if v.len() > 254 || v.chars().any(|c| c.is_control() || c == ' ') { - return Err("邮箱格式不正确".to_owned()); - } - if !v.contains('@') || v.starts_with('@') || v.ends_with('@') { - return Err("邮箱格式不正确".to_owned()); - } - Ok(v) -} +// =========================================================================== +// 共享内存同步(Key 索引) +// =========================================================================== -/// 部门名:同样禁止控制字符。 -pub fn check_department(raw: &str) -> Result { - let v = util::trim(raw).to_owned(); - if v.chars().count() > DEPARTMENT_MAX_LEN { - return Err(format!("部门名不能超过 {DEPARTMENT_MAX_LEN} 个字")); - } - if v.chars().any(|c| c.is_control()) { - return Err("部门名不能包含换行或控制字符".to_owned()); - } - Ok(v) -} - -/// 用户组:逗号/顿号/分号/空白分隔,去重后返回(顺序保留)。 +/// 身份 payload:` \n \n \n `。 /// -/// 组名会进 OIDC `groups` 与注入头 `X-Auth-Groups`,因此同样禁止换行/逗号。 -pub fn check_groups(raw: &str) -> Result, String> { - let mut out: Vec = Vec::new(); - for part in raw.split(|c: char| c == ',' || c == '、' || c == ';' || c == '\n' || c == '\t' || c == ' ') { - let g = part.trim(); - if g.is_empty() { - continue; - } - if g.chars().count() > GROUP_NAME_MAX_LEN { - return Err(format!("组名不能超过 {GROUP_NAME_MAX_LEN} 个字:{g}")); - } - if !out.iter().any(|x| x == g) { - out.push(g.to_owned()); +/// 一次查表同时拿到「是谁 / 能用哪些上游 / 限流多少」——LLM 热路径因此完全 +/// 不必回读 `users.json`(那是同步文件 I/O + 全表 JSON 解码)。 +/// 行数固定为 4;旧版 2 行 payload 由读取方按缺省值兜底。 +fn identity_payload(user: &User) -> String { + format!( + "{}\n{}\n{}\n{}", + user.username, + user.allowed_models.join(","), + user.llm_rpm, + user.llm_daily + ) +} + +/// 把账号的 Key 索引写进共享内存。**所有改动 `api_key` 的写操作都必须调用**。 +/// +/// 写失败(共享内存 zone 满 / 分配失败)会让这个 Key **静默失效**:热路径查不到 +/// 就是 401,且没有任何回源兜底。所以这里必须自己出声——「新建了 Key 却调不通、 +/// 日志里什么都没有」是这类问题最难查的形态。调用方是否检查返回值不影响本日志。 +pub fn sync_shm(user: &User) -> bool { + let ok = state::put_ukey(&user.api_key, &identity_payload(user)); + if !ok { + util::log_err(&format!( + "[users] Key 索引写共享内存失败 user={} —— 该 Key 调 LLM 会 401(共享内存可能已满)", + user.username + )); + } + ok +} + +/// 全量重载 Key 索引(启动装载 / 批量变更后)。返回装载条数。 +/// +/// 只清 `ukey:` 前缀,不会误伤转发映射、上游表与管理会话。 +/// `loaded < total` 时单独报一条 error:单个账号的失败已在 `sync_shm` 里出声, +/// 这里再汇总一次,避免「装载了 3/5 却只在滚动日志里淹没」。 +pub fn reload_shm() -> usize { + state::clear_prefix(KEY_UKEY_PREFIX); + let table = store::read_users(); + let total = table.len(); + let mut loaded = 0; + for user in table.into_values() { + if sync_shm(&user) { + loaded += 1; } } - if out.len() > GROUPS_MAX { - return Err(format!("单个账号最多归属 {GROUPS_MAX} 个用户组")); + if loaded != total { + util::log_err(&format!( + "[users] Key 索引装载不全:{loaded}/{total} —— 有账号将无法调用 LLM" + )); } - Ok(out) + loaded } // =========================================================================== @@ -113,14 +151,16 @@ pub fn get(username: &str) -> Option { store::read_users().remove(username) } -/// 全部账号,按账号名升序(`BTreeMap` 天然有序) +/// 全部账号,按账号名升序 pub fn all() -> Vec { store::read_users().into_values().collect() } /// 按 API Key 反查账号(常量时间比较,避免时序侧信道)。 /// -/// 每次都同步读 `users.json` 并全表解码,只适合管理/账号态接口这类低频调用方。 +/// **函数名里没有「快」字**:它每次都同步读 `users.json` 并全表解码, +/// 只适合管理接口这类低频调用方。LLM 转发热路径请用 `llm::identity`, +/// 那条路只查共享内存。 pub fn find_by_key(key: &str) -> Option { if key.is_empty() { return None; @@ -134,8 +174,15 @@ pub fn find_by_key(key: &str) -> Option { // 写入 // =========================================================================== -fn build_user(username: &str, display_name: &str, password: &str, role: &str) -> User { +fn build_user( + username: &str, + display_name: &str, + password: &str, + role: &str, + grant_temp: bool, +) -> User { let salt = util::gen_salt(); + let now = util::now(); User { username: username.to_owned(), display_name: display_name.to_owned(), @@ -143,51 +190,43 @@ fn build_user(username: &str, display_name: &str, password: &str, role: &str) -> pwd_hash: util::hash_password(password, &salt), salt, api_key: util::gen_key(), - email: String::new(), - department: String::new(), - groups: Vec::new(), - created_at: util::now(), - failed_count: 0, - locked_until: 0, - // 插件字段初始为空:语义「未配置」由插件自己解释,内核不预设默认值 - extra: std::collections::BTreeMap::new(), + allowed_models: Vec::new(), + llm_rpm: crate::config::LLM_RPM_DEFAULT, + llm_daily: crate::config::LLM_DAILY_DEFAULT, + temp_grant_until: if grant_temp { now + TEMP_GRANT_TTL } else { 0 }, + created_at: now, + extra: BTreeMap::new(), } } -/// 口令策略(对齐 MaxKey `mxk_cnf_password_policy` 的最小集): -/// 长度 ≥ `PASSWORD_MIN_LEN`,且必须同时包含字母与数字(拒绝纯数字/纯字母)。 -/// create 与 set_password 两个写入口共用,避免「建号能过、改密被拒」这类不一致。 -pub fn check_password(password: &str) -> Result<(), String> { - if password.chars().count() < PASSWORD_MIN_LEN { - return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); - } - let has_letter = password.chars().any(|c| c.is_ascii_alphabetic()); - let has_digit = password.chars().any(|c| c.is_ascii_digit()); - if !has_letter || !has_digit { - return Err("密码必须同时包含字母和数字".to_owned()); - } - Ok(()) -} - /// 首次启动播种管理员。已有数据时原样返回,**不会覆盖**。 /// /// 返回 `Ok(true)` 表示「本次真的创建了」,用于打一条提醒日志。 pub fn seed_admin() -> Result { - let password = std::env::var(INIT_ADMIN_PASSWORD_ENV) - .unwrap_or_else(|_| INIT_ADMIN_PASSWORD_DEFAULT.to_owned()); + let password = + std::env::var(INIT_ADMIN_PASSWORD_ENV).unwrap_or_else(|_| INIT_ADMIN_PASSWORD_DEFAULT.to_owned()); let mut created: Option = None; store::update_users(|users| { if !users.is_empty() { return Ok(()); } - let admin = build_user(INIT_ADMIN_USER, "", &password, "admin"); + let admin = build_user(INIT_ADMIN_USER, "", &password, "admin", false); users.insert(admin.username.clone(), admin.clone()); created = Some(admin); Ok(()) })?; - Ok(created.is_some()) + match created { + Some(u) => { + // 播种发生在 init_process(每个 worker 各一次),这里必须写穿, + // 否则「第一个 worker 建了账号、第二个 worker 覆盖索引」这类竞态 + // 会让新建的 Key 时灵时不灵。 + sync_shm(&u); + Ok(true) + } + None => Ok(false), + } } pub fn create( @@ -195,9 +234,7 @@ pub fn create( display_name: &str, password: &str, role: &str, - email: &str, - department: &str, - groups: &str, + grant_temp: bool, ) -> Result { let username = util::trim(username).to_owned(); if !valid_username(&username) { @@ -206,10 +243,9 @@ pub fn create( )); } let display_name = check_display_name(display_name)?; - check_password(password)?; - let email = check_email(email)?; - let department = check_department(department)?; - let groups = check_groups(groups)?; + if password.len() < PASSWORD_MIN_LEN { + return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); + } let role = if role == "admin" { "admin" } else { "user" }; // 先做一次存在性预检,省掉白算 1000 轮哈希;真正的判定仍在锁内 @@ -217,11 +253,7 @@ pub fn create( return Err(format!("账号 {username} 已存在")); } - let mut user = build_user(&username, &display_name, password, role); - user.email = email; - user.department = department; - user.groups = groups; - + let user = build_user(&username, &display_name, password, role, grant_temp); let created = user.clone(); store::update_users(move |users| { if users.contains_key(&username) { @@ -231,173 +263,136 @@ pub fn create( Ok(()) })?; + sync_shm(&created); Ok(created) } -/// 设置展示名(中文姓名等)。只影响展示,不碰口令与凭据。 +/// 设置展示名(中文姓名等)。只影响管理台显示,不碰 Key / 口令 / 白名单。 pub fn set_display_name(username: &str, display_name: &str) -> Result { let display_name = check_display_name(display_name)?; - store::update_users(move |users: &mut UserTable| { + let updated = store::update_users(move |users: &mut UserTable| { let user = users.get_mut(username).ok_or("账号不存在")?; user.display_name = display_name; Ok(user.clone()) - }) + })?; + // 展示名不在 ukey payload 里(热路径不需要它),无需同步共享内存 + Ok(updated) } -/// 设置身份声明(邮箱 / 部门 / 用户组)。 +/// 重置 API Key,返回新 Key。 /// -/// 三者原样进入 OIDC claims 与 IAP 注入头,所以这里是**授权数据的唯一写入口**, -/// 改动立即对下一次令牌签发 / 下一次请求生效(无需重启,也无需清会话—— -/// IAP 门禁读的 `sso:` 会话 payload 在登录时写入,见 `oauth::iap_identity` 的说明)。 -pub fn set_profile( - username: &str, - email: &str, - department: &str, - groups_raw: &str, - display_name: Option<&str>, -) -> Result { - let email = check_email(email)?; - let department = check_department(department)?; - let groups = check_groups(groups_raw)?; - let display_name = match display_name { - Some(d) => Some(check_display_name(d)?), - None => None, - }; - - store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.email = email; - user.department = department; - user.groups = groups; - if let Some(d) = display_name { - user.display_name = d; - } - Ok(user.clone()) - }) -} - -/// 批量维护账号:`add_groups` / `remove_groups` / `department` / `role` / `unlock` -/// 五个动作可任意组合,在**一次**文件锁内完成(要么全改,要么一个都不改)。 -/// -/// 组名逐个走 `check_groups` 校验(长度 / 控制字符),但不走 `GROUPS_MAX` -/// 的整体上限检查——那是「单账号全量组」的约束,加组场景应只对增量负责。 -/// 角色降级与 `set_role` 一样受「至少保留一个管理员」红线保护。 -/// -/// 返回 `(成功数, 跳过的原因列表)`:单个账号不存在只记原因不中断, -/// 方便管理台批量选人时有个别脏数据也不至于整批失败。 -pub fn batch_update( - usernames: &[String], - add_groups: &[String], - remove_groups: &[String], - department: Option<&str>, - role: Option<&str>, - unlock: bool, -) -> Result<(usize, Vec), String> { - if usernames.is_empty() { - return Err("请至少选择一个账号".to_owned()); - } - if let Some(r) = role { - if r != "admin" && r != "user" { - return Err("角色只能是 admin 或 user".to_owned()); - } - } - // 参数先在外面校验干净,避免进了写锁才发现组名非法、白占一次锁 - for g in add_groups.iter().chain(remove_groups.iter()) { - if g.is_empty() { - return Err("用户组名不能为空".to_owned()); - } - if g.chars().count() > GROUP_NAME_MAX_LEN { - return Err(format!("组名不能超过 {GROUP_NAME_MAX_LEN} 个字:{g}")); - } - if g.chars().any(|c| c.is_control()) { - return Err("组名不能包含换行或控制字符".to_owned()); - } - } - let department = match department { - Some(d) => Some(check_department(d)?), - None => None, - }; - let role = role.map(|r| r.to_owned()); - let add = add_groups.to_vec(); - let remove = remove_groups.to_vec(); - - store::update_users(move |users: &mut UserTable| { - // 先算管理员余量:批量降级时不能把管理员清空,中途才发现就晚了 - if role.as_deref() == Some("user") { - let demoting: Vec<&String> = usernames - .iter() - .filter(|n| users.get(n.as_str()).map(|u| u.role == "admin").unwrap_or(false)) - .collect(); - if !demoting.is_empty() { - let admins = users.values().filter(|u| u.role == "admin").count(); - if admins <= demoting.len() { - return Err("至少需要保留一个管理员账号".to_owned()); - } - } - } - - let mut changed = 0usize; - let mut skipped: Vec = Vec::new(); - for name in usernames { - let Some(user) = users.get_mut(name.as_str()) else { - skipped.push(format!("{name}:账号不存在")); - continue; - }; - if let Some(d) = department.as_deref() { - user.department = d.to_owned(); - } - if let Some(r) = role.as_deref() { - user.role = r.to_owned(); - } - for g in &add { - if !user.groups.iter().any(|x| x == g) { - user.groups.push(g.clone()); - } - } - user.groups.retain(|g| !remove.iter().any(|x| x == g)); - if unlock { - user.failed_count = 0; - user.locked_until = 0; - } - changed += 1; - } - Ok((changed, skipped)) - }) -} - -/// 设置角色(`admin` / `user`)。 -/// -/// 红线与 `delete` 一致:**不允许把最后一个管理员降级**,否则管理台会永久锁死。 -pub fn set_role(username: &str, role: &str) -> Result { - let role = if role == "admin" { "admin" } else { "user" }.to_owned(); - store::update_users(move |users: &mut UserTable| { - let current = users.get(username).ok_or("账号不存在")?.role.clone(); - if current == "admin" && role != "admin" { - let admins = users.values().filter(|u| u.role == "admin").count(); - if admins <= 1 { - return Err("至少需要保留一个管理员账号".to_owned()); - } - } - let user = users.get_mut(username).ok_or("账号不存在")?; - user.role = role; - Ok(user.clone()) - }) -} - -/// 重置 API Key,返回新 Key。旧 Key 立即失效。 +/// **必须同时摘掉旧索引**:LLM 热路径查的是 `ukey:`,若只加新的不删旧的, +/// 被重置掉的 Key 仍然能调通模型——用户以为「换钥匙就安全了」,实际没有。 pub fn regenerate_key(username: &str) -> Result { + let (old_key, new_key, updated) = store::update_users(|users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + let old = user.api_key.clone(); + user.api_key = util::gen_key(); + Ok((old, user.api_key.clone(), user.clone())) + })?; + + state::remove_ukey(&old_key); + sync_shm(&updated); + Ok(new_key) +} + +/// 设置账号可用的 LLM 上游白名单。传空表表示不限。 +pub fn set_allowed_models(username: &str, slots: Vec) -> Result { + let updated = store::update_users(move |users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + user.allowed_models = slots; + Ok(user.clone()) + })?; + + sync_shm(&updated); + Ok(updated) +} + +/// 修改账号的插件扩展字段(`User.extra`)。 +/// +/// 闭包拿到 `&mut User`——可同时改内核字段与 `extra`,由调用方决定语义。 +/// 走 `store::update_users` 的「读-改-写 + 写穿 shm」统一路径,保证 shm +/// `ukey:` 索引与 `users.json` 同步刷新。 +/// +/// 配套 [`crate::models::User::extra`] 的 `#[serde(flatten)]`——上游 +/// sso 收敛时提议(A1),按插件字段透传通道走。 +pub fn update_extra(username: &str, f: F) -> Result +where + F: FnOnce(&mut User) -> Result, +{ + // 闭包内拿到 user 引用 → 调 f 修改 → f 返回后借用释放 → clone 出 owned + // user 给 sync_shm。`update_users` 的闭包签名是 `&mut UserTable`,把 + // UserTable 的可变借用拆借给 &mut User 是 OK 的(Rust 借用分裂)。 + let (out, updated) = store::update_users(move |users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + let out = f(user)?; + Ok((out, user.clone())) + })?; + sync_shm(&updated); + Ok(out) +} + +/// 设置账号的 LLM 限流参数。`None` = 保持现值;`0` = 不限;正数 = 上限。 +/// +/// 改动的是 `ukey:` payload 的组成部分,所以**必须写穿**—— +/// 否则表现为「改完限额,热路径还按旧额度放行」。 +pub fn set_llm_limits(username: &str, rpm: Option, daily: Option) -> Result { + if let Some(v) = rpm { + if v < 0 { + return Err("每分钟上限不能为负数(0 表示不限)".to_owned()); + } + } + if let Some(v) = daily { + if v < 0 { + return Err("每日上限不能为负数(0 表示不限)".to_owned()); + } + } + + let updated = store::update_users(move |users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + if let Some(v) = rpm { + user.llm_rpm = v; + } + if let Some(v) = daily { + user.llm_daily = v; + } + Ok(user.clone()) + })?; + + sync_shm(&updated); + Ok(updated) +} + +/// 授予临时授权权限(默认 6 小时),返回到期时间戳 +pub fn grant_temp(username: &str, hours: Option<&String>) -> Result { + let ttl = hours + .and_then(|h| h.parse::().ok()) + .map(|h| h * 3600) + .unwrap_or(TEMP_GRANT_TTL); + store::update_users(|users: &mut UserTable| { let user = users.get_mut(username).ok_or("账号不存在")?; - user.api_key = util::gen_key(); - Ok(user.api_key.clone()) + user.temp_grant_until = util::now() + ttl; + Ok(user.temp_grant_until) + }) +} + +pub fn revoke_temp(username: &str) -> Result<(), String> { + store::update_users(|users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + user.temp_grant_until = 0; + Ok(()) }) } pub fn set_password(username: &str, password: &str) -> Result<(), String> { - check_password(password)?; + if password.len() < PASSWORD_MIN_LEN { + return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); + } let salt = util::gen_salt(); let hash = util::hash_password(password, &salt); + // 改口令不动 api_key,因此不需要同步 Key 索引 store::update_users(move |users: &mut UserTable| { let user = users.get_mut(username).ok_or("账号不存在")?; user.salt = salt; @@ -406,61 +401,17 @@ pub fn set_password(username: &str, password: &str) -> Result<(), String> { }) } -// =========================================================================== -// 登录失败锁定(账号维度) -// =========================================================================== - -/// 记录一次登录失败。返回 `(失败次数, locked_until)`: -/// 达到阈值即锁定 `ACCOUNT_LOCK_TTL` 秒并重新计窗。 -pub fn record_login_failure(username: &str, now: i64) -> Result<(i64, i64), String> { - let threshold = crate::config::ACCOUNT_LOCK_THRESHOLD; - let ttl = crate::config::ACCOUNT_LOCK_TTL; - store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - // 已在锁定期:不重复累计,锁定到期时间不变 - if user.is_locked(now) { - return Ok((user.failed_count, user.locked_until)); - } - user.failed_count += 1; - if user.failed_count >= threshold { - user.locked_until = now + ttl; - user.failed_count = 0; - } - Ok((user.failed_count, user.locked_until)) - }) -} - -/// 登录成功后清零失败计数与锁定状态。 -pub fn clear_login_failure(username: &str) -> Result<(), String> { - store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.failed_count = 0; - user.locked_until = 0; - Ok(()) - }) -} - -/// 管理员手动解锁(清零失败计数与锁定截止时间)。 -pub fn unlock(username: &str) -> Result { - store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.failed_count = 0; - user.locked_until = 0; - Ok(user.clone()) - }) -} - -// =========================================================================== -// TOTP 双因子 -// =========================================================================== - /// 删除账号。两条红线:不能删自己、必须至少保留一个管理员。 +/// +/// 顺带摘掉 Key 索引——否则删掉的账号仍能通过 LLM 代理调用模型。 pub fn delete(username: &str, operator: &str) -> Result<(), String> { if username == operator { return Err("不能删除当前登录的账号".to_owned()); } let username = username.to_owned(); - store::update_users(move |users| { + let deleted = username.clone(); + + let removed_key = store::update_users(move |users| { let user = users.get(&username).ok_or("账号不存在")?; if user.role == "admin" { let admins = users.values().filter(|u| u.role == "admin").count(); @@ -468,62 +419,45 @@ pub fn delete(username: &str, operator: &str) -> Result<(), String> { return Err("至少需要保留一个管理员账号".to_owned()); } } - users.remove(&username); - Ok(()) - }) + Ok(users.remove(&username).map(|u| u.api_key).unwrap_or_default()) + })?; + + if !removed_key.is_empty() { + state::remove_ukey(&removed_key); + } + // 内核自己的键已摘掉;用量账本等插件键空间由 on_delete 钩子清理 + // (谁装了谁清——钩子为空说明对应插件未装配,自然也无键可清) + run_delete_hooks(&deleted); + Ok(()) } // =========================================================================== // 对外投影 // =========================================================================== -/// 透出 `extra` 时隐藏的敏感键(如 TOTP 种子):内核虽不解释插件字段, -/// 但回传前端前过滤掉这些私密凭据,避免泄露。 -const HIDDEN_EXTRA_KEYS: &[&str] = &["totp_secret"]; - /// 转成前端可见的字段(**绝不包含 salt / pwd_hash**) pub fn view(user: &User) -> Value { - let mut v = json!({ + let now = util::now(); + let until_ts = user.temp_grant_until; + let active = until_ts > now; + + json!({ "username": user.username, "display_name": user.display_name, // 前端统一用 name 渲染——展示名优先,没有就回落到账号名 - "name": user.display_or_username(), + "name": if user.display_name.is_empty() { user.username.clone() } else { user.display_name.clone() }, "role": user.role, - "is_admin": user.is_admin(), - "email": user.email, - "department": user.department, - "groups": user.groups, - "groups_csv": user.groups_csv(), "api_key": user.api_key, "api_key_masked": util::mask_key(&user.api_key), + "allowed_models": user.allowed_models, + "llm_rpm": user.llm_rpm, + "llm_daily": user.llm_daily, "created_at": user.created_at, "created_at_text": util::fmt_time(user.created_at), - // 锁定状态:管理台据此展示「已锁定」标签与解锁入口 - "locked": user.locked_until > 0, - "locked_until": user.locked_until, - "locked_until_text": if user.locked_until > 0 { util::fmt_time(user.locked_until) } else { String::new() }, - }); - // 插件字段原样透出:管理台无需为每个插件改一次渲染逻辑 - if let Some(obj) = v.as_object_mut() { - for (k, val) in &user.extra { - // 敏感密钥(如 TOTP 种子)绝不回传前端:内核虽不解释插件字段, - // 但透出做隐藏黑名单,避免私密凭据泄露。 - if HIDDEN_EXTRA_KEYS.contains(&k.as_str()) { - continue; - } - obj.insert(k.clone(), val.clone()); - } - } - v -} - -/// 更新某个账号的**插件字段**(`User::extra`)。 -/// -/// 插件往共用 `users.json` 写自有字段的唯一入口:内核持锁 + 原子写回, -/// 插件只能看到 `extra` 这张表,碰不到 role / 口令 / 锁定等共性字段。 -pub fn update_extra(username: &str, f: F) -> Result -where - F: FnOnce(&mut std::collections::BTreeMap) -> Result, -{ - store::update_extra(username, f) + "temp_grant": active, + "temp_grant_until": until_ts, + "temp_grant_until_text": if active { util::fmt_time(until_ts) } else { String::new() }, + "temp_grant_left": if active { until_ts - now } else { 0 }, + "temp_grant_left_text": if active { util::fmt_left(until_ts - now) } else { String::new() }, + }) } diff --git a/source/rust/crates/ipass-core/src/util.rs b/source/rust/crates/ipass-core/src/util.rs index 722a04e..6988480 100644 --- a/source/rust/crates/ipass-core/src/util.rs +++ b/source/rust/crates/ipass-core/src/util.rs @@ -76,27 +76,21 @@ pub fn fmt_time(ts: i64) -> String { } } -/// 本地自然日的「日窗 id」:同一天返回同一值,跨天 +1。 -/// -/// 限流(`st:`)与趋势日桶都用它当键的一部分。CST(+8h)对齐,使 0 点边界 -/// 与业务习惯一致。 -pub fn day_id(ts: i64) -> i64 { - (ts + 8 * 3600) / 86400 -} - -/// `MM-DD`(本地时区,用于趋势图 x 轴标签)。ts <= 0 返回 `-` +/// `%m-%d`(本地时区)。趋势图 x 轴用——带上年份会让 14 天的轴标签又长又重复 pub fn fmt_day(ts: i64) -> String { if ts <= 0 { return "-".to_owned(); } + // SAFETY: 同 fmt_time unsafe { let t = ts as libc::time_t; let mut tm: libc::tm = core::mem::zeroed(); if libc::localtime_r(&t, &mut tm).is_null() { return "-".to_owned(); } - let mut buf = [0 as libc::c_char; 40]; - let n = libc::strftime(buf.as_mut_ptr(), buf.len(), c"%m-%d".as_ptr(), &tm); + let mut buf = [0 as libc::c_char; 16]; + let fmt = c"%m-%d"; + let n = libc::strftime(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), &tm); if n == 0 { return "-".to_owned(); } @@ -104,50 +98,37 @@ pub fn fmt_day(ts: i64) -> String { } } -/// `n` 位随机数字串(允许前导 0),用于子域名生成等。 -pub fn rand_digits(n: usize) -> String { - let mut out = String::with_capacity(n); - for _ in 0..n { - // 取一个随机字节的低 4 位映射成 0-9 - let mut b = [0u8; 1]; - if rand_bytes(&mut b).is_none() { - // 随机源失效:退化为基于时间的低位(仅用于非安全场景) - let v = (now() as u8).wrapping_add(out.len() as u8); - out.push(char::from(b'0' + (v % 10))); - continue; +/// 本地时区的「日窗 id」(年份×1000 + 年内第几天),跨天自动翻窗。 +/// +/// 限流配额按**本地日**切(面向中国用户,即东八区自然日),不用 UTC—— +/// UTC 的日界线在北京时间早上 8 点,「每日额度」会在半夜重置,反直觉。 +pub fn day_id(ts: i64) -> i64 { + // SAFETY: localtime_r 只读时间戳并填充调用方的结构体 + unsafe { + let t = ts as libc::time_t; + let mut tm: libc::tm = core::mem::zeroed(); + if libc::localtime_r(&t, &mut tm).is_null() { + return ts.div_euclid(86400); // 兜底:退化成 UTC 日 } - out.push(char::from(b'0' + (b[0] % 10))); + tm.tm_year as i64 * 1000 + tm.tm_yday as i64 } - out } -/// 把剩余秒数格式化成「X天X小时X分钟」(不足 1 分钟显示「<1分钟」)。 -pub fn fmt_left(secs: i64) -> String { - if secs <= 0 { - return String::new(); - } - let d = secs / 86400; - let h = (secs % 86400) / 3600; - let m = (secs % 3600) / 60; - let mut parts: Vec = Vec::new(); - if d > 0 { - parts.push(format!("{d}天")); +/// 剩余时长的中文描述(与旧版 `fmt_left` 输出一致) +pub fn fmt_left(seconds: i64) -> String { + if seconds <= 0 { + return "已过期".to_owned(); } + let h = seconds / 3600; + let m = (seconds % 3600) / 60; + let s = seconds % 60; if h > 0 { - parts.push(format!("{h}小时")); + format!("{h} 小时 {m} 分") + } else if m > 0 { + format!("{m} 分 {s} 秒") + } else { + format!("{s} 秒") } - if m > 0 { - parts.push(format!("{m}分钟")); - } - if parts.is_empty() { - return "<1分钟".to_owned(); - } - parts.concat() -} - -/// 生成一条记录的唯一 id(域名/上游等)。时间戳 + 随机后缀,避免并发碰撞。 -pub fn gen_id() -> String { - format!("{:x}{}", now(), &rand_hex(4)) } // =========================================================================== @@ -155,6 +136,7 @@ pub fn gen_id() -> String { // =========================================================================== pub fn to_hex(bytes: &[u8]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; let mut out = String::with_capacity(bytes.len() * 2); for &b in bytes { out.push(HEX[(b >> 4) as usize] as char); @@ -163,9 +145,6 @@ pub fn to_hex(bytes: &[u8]) -> String { out } -/// 小写十六进制字母表(模块级,供 `to_hex` / `url_encode` 共用) -const HEX: &[u8; 16] = b"0123456789abcdef"; - /// 密码学安全随机字节。取不到随机源时返回 None(调用方必须显式处理, /// **不允许**退化成可预测的伪随机——那等于把 API Key 直接送给攻击者)。 fn rand_bytes(buf: &mut [u8]) -> Option<()> { @@ -213,6 +192,51 @@ pub fn gen_key() -> String { format!("sk_{}", to_hex(&b)) } +/// 域名记录 id:`d_` + 6 字节 → 12 位 hex +pub fn gen_id() -> String { + let mut b = [0u8; 6]; + if rand_bytes(&mut b).is_none() { + let n = now() as u32; + b[..4].copy_from_slice(&n.to_le_bytes()); + b[4..].copy_from_slice(&(n ^ 0xa5a5).to_le_bytes()[..2]); + } + format!("d_{}", to_hex(&b)) +} + +/// `n` 位纯数字随机串(每位 0-9 等概率)。 +/// +/// 用**拒绝采样**而不是 `byte % 10`:256 不是 10 的倍数,直接取模会让 0-5 +/// 比 6-9 各多出现约 0.4%(对子域名无害,但没理由留这个瑕疵)。 +/// 只接受 `< 250` 的字节(250 = 25×10),落桶严格均匀。 +/// +/// 非安全场景(子域名后缀),但仍复用 `getrandom`——顺带拿到「随机源不可用」 +/// 的统一退化路径,且随机源失效时绝不 panic。 +pub fn rand_digits(n: usize) -> String { + let mut out = String::with_capacity(n); + let mut buf = [0u8; 32]; + // 随机源不可用时退化为 xorshift(与 rand_hex 同款兜底),仍会终止 + let mut seed = now() as u64 ^ 0x2545_f491_4f6c_dd1d; + while out.len() < n { + let take = (n - out.len()).min(buf.len()); + let slice = &mut buf[..take]; + let ok = rand_bytes(slice).is_some(); + if !ok { + for byte in slice.iter_mut() { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + *byte = (seed & 0xff) as u8; + } + } + for &b in slice.iter() { + if b < 250 && out.len() < n { + out.push((b'0' + (b % 10)) as char); + } + } + } + out +} + // =========================================================================== // 摘要与口令 // =========================================================================== @@ -328,39 +352,3 @@ pub fn parse_kv(raw: &[u8]) -> Vec<(String, String)> { } out } - -/// percent-encode(用于回调地址等放进查询参数前的转义)。 -/// -/// 只编码非「非保留字符」集(RFC 3986 unreserved:`A-Za-z0-9-._~`)。 -pub fn url_encode(input: &str) -> String { - let mut out = String::with_capacity(input.len()); - for b in input.bytes() { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - out.push(b as char); - } - _ => { - out.push('%'); - out.push(HEX[(b >> 4) as usize] as char); - out.push(HEX[(b & 0x0f) as usize] as char); - } - } - } - out -} - -/// HTML 转义(防登录表单回显时的注入)。 -pub fn html_escape(input: &str) -> String { - let mut out = String::with_capacity(input.len()); - for c in input.chars() { - match c { - '&' => out.push_str("&"), - '<' => out.push_str("<"), - '>' => out.push_str(">"), - '"' => out.push_str("""), - '\'' => out.push_str("'"), - _ => out.push(c), - } - } - out -}