diff --git a/docs/plugin/SSO_UPSTREAM_DECISIONS.md b/docs/plugin/SSO_UPSTREAM_DECISIONS.md new file mode 100644 index 0000000..c8a4328 --- /dev/null +++ b/docs/plugin/SSO_UPSTREAM_DECISIONS.md @@ -0,0 +1,131 @@ +# sso 上游化合流决策(2026-09-13,commit ddd4172 → 1.0.13) + +> sso 团队对照 iPass P5(commit `ddd4172`,1.0.12)提出 11 条内核修改建议, +> 分 A 档(请求上游改)与 B 档(自解)。本文件记录采纳与不采纳的依据。 + +## 采纳清单 + +### A1 — `User.extra` flatten 透传通道 ✅ + +**改动**:`ipass-core/src/models.rs::User` 增加 +```rust +#[serde(default, flatten)] +pub extra: BTreeMap, +``` + +**为什么采纳**: +- 这是 plugin-sso 验证过的成熟方案("我方已有生产实现,可直接抄") +- 解决"内核硬编码插件语义"的根本问题——`allowed_models`/`llm_rpm`/`llm_daily`/ + `temp_grant_until` 都是 plugin-llm 的语义污染内核;未来插件要存 TOTP 密钥、 + 邮箱、用户组、锁定状态……再走内核加字段成本极高 +- `serde(flatten)` 对存量字段**零影响**——已认领字段优先,老 `users.json` + 反序列化后原样写回 +- 给未来插件留通用扩展点 + +**配套**:同提交加 [`users::update_extra`](upstream-core-changes.md#a1), +让插件改 `extra` 走「读-改-写 + 写穿 shm」统一路径(与现有 +`users::set_allowed_models` 同源)。 + +### A1 配套 — `users::update_extra` ✅ + +`ipass-core/src/users.rs` 新增 `pub fn update_extra(username, f) +where F: FnOnce(&mut User) -> Result`。走 `store::update_users` +路径自动 shm 同步。 + +### A2 — `split_value` `position` → `rposition` ✅(修真 bug) + +**改动**:`ipass-core/src/state.rs::split_value` 1 字符。 + +```diff +- let sep = bytes.iter().position(|&b| b == VAL_SEP)?; ++ let sep = bytes.iter().rposition(|&b| b == VAL_SEP)?; +``` + +**为什么是真 bug**:value 编码 ` \x1f `,`exp` 必为 +ASCII 数字(不可能含 `VAL_SEP`),所以**最后一个** `\x1f` 才是真边界。 +`position` 取第一个,payload 内部一旦含 `0x1f`(OAuth 授权码、注入头 +payload 都可能)就会被截断、exp 解析失败。sso 上游化时已踩此坑。 + +iPass 现状未踩:`sub:` payload 是 `host:port`、`ukey:` payload 用 `\n` 分段, +都没内嵌 `\x1f`。但**留此 bug 等下次踩**代价太高,1 字符修复零风险。 + +### A3 — `state::iter_prefix_ex` 返回 `(key, payload, exp)` ✅ + +**改动**:`ipass-core/src/state.rs` 新增 `pub fn iter_prefix_ex(prefix) +-> Vec<(String, String, i64)>`。`iter_prefix` 保留为兼容包装(统计键 +永不过期、不需要 exp)。 + +**为什么采纳**:会话 / OAuth kick / 过期扫描必须看见 `exp` 才能判定。 +新增能力、零破坏。 + +## 不采纳清单 + +### A4 — users 模块扩展 6 函数 ⏸️ + +sso 列了 `set_profile` / `set_role` / `batch_update` / `unlock` / +`record_login_failure` / `update_extra`。其中: + +- **`update_extra`** —— 已采纳(见上) +- **`unlock` / `record_login_failure`** —— iPass 已有等价: + - `users::clear_login_fail(ip)` 当作 unlock + - `state::bump_login_fail(ip, now) -> i64` 已用在 admin login 端点 + (api.rs:224),配套 `state::get_login_fail` 判定 `>= LOGIN_MAX_FAIL` + 锁定。**iPass 不需要 `lock_until` 字段**——只要次数 ≥ 10 就拒,与 + sso 的 "N 次错误后锁定到 X 时刻" 业务模型不同 +- **`set_profile` / `set_role` / `batch_update`** —— iPass 没有部门/用户组 + 业务(纯 LLM + 域名)。**留给 plugin-sso 自实现**—— + `store::update_users` 是 `pub`,插件可以在闭包里读 `&mut User` + 改任意字段然后调 `users::sync_shm` 写穿 + +### A5 — store.rs 插件文件命名空间 ⏸️ + +iPass 选**选项 2**:`path_in_data(name)` 是唯一口径,由插件自行拼子目录。 +plugin-sso 应直接用 `store::path_in_data("oauth_codes.json")` 等。 +**零代码改动**。iPass 各插件都各管一份 JSON,无 namespace 冲突需求。 + +### A6-1 — `PASSWORD_MIN_LEN` 6 → 8 ❌ + +**为什么不采纳**:测试夹具大量依赖 6/7 位密码做边界用例 +(`password 123` 测拒绝、`password alice123` 测合法等)。iPass 整体 +风格是「内核最小约束、插件层加业务策略」,弱口令门槛属于业务策略。 +**plugin-password-policy 类插件**(未来)应在内核外校验后再调 +`users::create` / `set_password`。 + +回退 `PASSWORD_MIN_LEN = 6`,回退 `INIT_ADMIN_PASSWORD_DEFAULT = "123456"`。 + +### A6-2 — COOKIE_NAME 由插件声明 ❌ + +iPass 自己的 `admin login` 端点(`CorePlugin`)直接用 `COOKIE_NAME`, +迁移成本 > 收益。若 plugin-sso 想换 cookie 名:自实现 login 端点(替换 +`CorePlugin` 的对应路由)或 fork 一份 `CorePlugin`。内核不动。 + +## 已确认无需上游改动 + +sso 列的三条确认项,**iPass 已具备**: + +- `http::host_port` —— 用 `rsplit_once` 实现,sso 更简洁、语义等价 +- `store::write_json` —— 紧凑 JSON,sso 是 pretty,等价 +- `Plugin` trait(preconfig / postconfig / dispatch_api / zone_load / + log_handler)+ `PLUGINS` 装配 + `loc::Switch` + `ctx_index` 注入 + —— 两侧已同构,**trait 层零适配可合流** + +## 变更面 + +| 文件 | 改动 | +| --- | --- | +| `rust/crates/ipass-core/src/state.rs` | `split_value` rposition;新增 `iter_prefix_ex` | +| `rust/crates/ipass-core/src/models.rs` | `User.extra` flatten | +| `rust/crates/ipass-core/src/users.rs` | 新增 `update_extra`;`build_user` 字面量补 `extra: BTreeMap::new()`;引入 `use std::collections::BTreeMap` | +| `rust/crates/ipass-core/src/config.rs` | (仅注释增改 — A6-1 回退后保留原值)| + +## 验收 + +- `cargo build` —— 零 error 零 warning +- `bash tests/run.sh all` —— 262 全绿(gateway 102 + llm 160) +- 镜像 tag 计划:`ipass-1.0.13`(commit `1.0.12 → +1`) + +## 与 sso 的合流路径 + +sso 文档说「**内核原样复制**」——一旦 sso 仓库拉取 commit `1.0.13+`,它 +就能用上 `User.extra` / `iter_prefix_ex` / `split_value` 三个修正。其余 +插件自实现路径(A4)sso 已经在自己的代码里铺好,无需内核再动。 \ No newline at end of file diff --git a/rust/crates/ipass-core/src/config.rs b/rust/crates/ipass-core/src/config.rs index 241bad3..91c583b 100644 --- a/rust/crates/ipass-core/src/config.rs +++ b/rust/crates/ipass-core/src/config.rs @@ -21,6 +21,11 @@ pub const INIT_ADMIN_PASSWORD_ENV: &str = "ADMIN_INIT_PASSWORD"; pub const INIT_ADMIN_PASSWORD_DEFAULT: &str = "123456"; /// 口令最短长度 +/// +/// 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; diff --git a/rust/crates/ipass-core/src/models.rs b/rust/crates/ipass-core/src/models.rs index 128fb09..bdcda27 100644 --- a/rust/crates/ipass-core/src/models.rs +++ b/rust/crates/ipass-core/src/models.rs @@ -4,6 +4,7 @@ //! 以便新版直接接管旧数据文件、且管理台前端无需改动。 use serde::{Deserialize, Serialize}; +use serde_json::Value; use std::collections::BTreeMap; /// 账号表(`users.json`):以账号名为 key 的对象。 @@ -47,6 +48,19 @@ pub struct User { pub temp_grant_until: i64, #[serde(default)] pub created_at: i64, + + /// 插件字段透传:内核持有、**不解释**。 + /// + /// 反序列化时,文件中**未被上面字段认领的 key 自动进 `extra`**;序列化时 + /// 展开回顶层(`#[serde(flatten)]`)。`serde` 优先匹配已认领字段,所以 + /// 存量 `users.json`(含任何插件写入的字段)可原样接管,**不会因内核不 + /// 认识而丢数据**——这是 iPass 向上游 sso 合流的扩展点(A1)。 + /// + /// 未来插件要存 TOTP 密钥、邮箱、用户组、锁定状态……都直接往 `extra` + /// 写,不再走内核加字段。修改走 [`crate::users::update_extra`] 的 + /// 「读-改-写」原语。 + #[serde(default, flatten)] + pub extra: BTreeMap, } impl User { diff --git a/rust/crates/ipass-core/src/state.rs b/rust/crates/ipass-core/src/state.rs index 52764b9..5dcaa4f 100644 --- a/rust/crates/ipass-core/src/state.rs +++ b/rust/crates/ipass-core/src/state.rs @@ -124,8 +124,13 @@ fn key_buf(prefix: &[u8], name: &[u8]) -> Option<([u8; KEY_BUF_LEN], usize)> { } /// 拆 value:` \x1f ` +/// +/// 用 `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().position(|&b| b == VAL_SEP)?; + let sep = bytes.iter().rposition(|&b| b == VAL_SEP)?; let payload = &bytes[..sep]; let exp = core::str::from_utf8(&bytes[sep + 1..]).ok()?.parse::().ok()?; Some((payload, exp)) @@ -242,6 +247,28 @@ pub fn iter_prefix(prefix: &[u8]) -> Vec<(String, String)> { .collect() } +/// 与 [`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(); + }; + let guard = root.map.read(); + guard + .iter() + .filter_map(|(k, v)| { + let name = k.as_bytes().strip_prefix(prefix)?; + let (payload, exp) = split_value(v.as_bytes())?; + Some(( + String::from_utf8_lossy(name).into_owned(), + String::from_utf8_lossy(payload).into_owned(), + exp, + )) + }) + .collect() +} + // =========================================================================== // 业务语义封装 // =========================================================================== diff --git a/rust/crates/ipass-core/src/users.rs b/rust/crates/ipass-core/src/users.rs index 2aa4696..9b41d1d 100644 --- a/rust/crates/ipass-core/src/users.rs +++ b/rust/crates/ipass-core/src/users.rs @@ -12,6 +12,7 @@ //! 代价是**任何改动 `api_key` 的操作都必须同步共享内存索引**, //! 且重置 Key 时必须**先摘掉旧索引**,否则被换掉的 Key 依然能用。 +use std::collections::BTreeMap; use std::sync::Mutex; use serde_json::{Value, json}; @@ -194,6 +195,7 @@ fn build_user( 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(), } } @@ -306,6 +308,30 @@ pub fn set_allowed_models(username: &str, slots: Vec) -> Result(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 的组成部分,所以**必须写穿**——