Files
sso/docs/plugin-architecture-analysis.md
T
ssw 8e9becaad7 docs: 插件化架构分析与迁移/任务文档,同步 CLAUDE.md 与路线图
新增
  docs/plugin-architecture-analysis.md  内核/插件边界分析、P 阶段拆分与装配契约
  docs/maxkey-migration-analysis.md     MaxKey 端点别名与 context-path 归一化对齐
  docs/task-plan.md                     阶段任务清单与验收口径

同步
  CLAUDE.md    crate 清单与目录地图:plugin-domain 标为「已迁入示例」,
               plugin-llm 明确「不迁入」(LLM 上游代理与配额计费属流量层,
               与本服务「身份层」的定位分界不变,半成品已从 workspace 移除);
               回归口径五套 → 六套;测试配置端口范围 18093-18099
  README.md    结构树补 plugin-domain,端口范围同步
  roadmap.md   P2 标记为已完成(部分)并写明 plugin-llm 不迁入的理由
2026-09-13 10:25:48 +08:00

188 lines
9.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 插件化架构:iPass 统一网关(core + 插件)
> 问题:iPass 有「动态域名 + LLM 路由」,SSO 有「身份 / Key / OAuth」,
> nginx 本来就支持多模块——能不能做成插件模式,共用一个用户基础认证与 Key,其它由插件来做?
>
> **定稿(2026-09-13)**:
> 1. 内核是 **`ipass-core`(网关内核)**,**SSO 是其中一个插件**,与 `domain`、`llm` 平级。
> 身份不是内核——内核只回答「请求是谁、状态存哪、配置怎么装配」。
> 2. **`users.json` 全局共用一份,由 `ipass-core` 独占读写**,插件只读不写。
> 3. 插件是 **Rust crate 级(编译期装配,产出单个 `.so`)**,不是运行时加载多个动态模块。
---
## 一、为什么是 ipass-core,而不是 sso-core
内核的职责应该是「所有插件都要用、且只有一份才有意义」的东西:
| 能力 | 归属 | 理由 |
| --- | --- | --- |
| 共享内存状态表 / 文件写锁 | core | 只能有一个 zone;多份就失去「热路径零文件 I/O」的意义 |
| `users.json` 读写与 Key 索引 | core | 一处吊销处处生效;插件各写一份就等于没共用 |
| 账号模型 `User` | core | 身份是全局概念,域名审批与 LLM 配额都要挂在同一个账号上 |
| 会话 / 登录失败锁定 / 审计 | core | 与账号强绑定,跨插件共享 |
| OAuth2 / OIDC 签发与校验 | plugin-sso | 一种认证协议,不是网关必需品 |
| IAP 身份注入 | plugin-sso | 同上 |
| 动态域名映射与审批 | plugin-domain | 独立业务 |
| LLM 路由 / 配额 / 计费 | plugin-llm | 独立业务 |
一句话判据:**去掉 SSO,网关还能不能转域名、还能不能代理 LLM?** 能 → 那它就不是内核。
## 二、「nginx 支持多模块」≠ 插件 ABI
三个硬约束决定了多 `.so` 只能算「同源编译的多个 C 模块」,不是插件生态:
1. **模块必须与 nginx 二进制同源**。动态模块的 `ngx_module_t` 带 `version` /
`signature`(含 `NGX_MODULE_SIGNATURE` 一长串编译期特性位),不匹配直接拒绝加载。
2. **Rust 没有稳定 ABI**。每个 cdylib 静态链进自己的一份 `std`。跨 `.so` 传递
`Box` / `String` / `Vec` 意味着「A 的分配器分配、B 的分配器释放」→ 双重 free。
3. **加载顺序影响行为**(下一节有源码级证据)。
## 三、如果硬上多 .so,会踩的三个坑(已在 nginx 1.30.4 源码核对)
### 坑 1:共享内存 zone 的 tag 必须相同,否则启动即失败
`src/core/ngx_cycle.c`:
```c
if (tag != shm_zone[i].tag) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"the shared memory zone \"%V\" is "
"already declared for a different use", &shm_zone[i].shm.name);
return NULL; // ← 直接启动失败
}
```
而两边现在传的都是**自己模块的 `ngx_module_t` 地址**:
```rust
// source/rust/src/lib.rs:451
ngx_shared_memory_add(cf, &raw mut name, size, (&raw mut ngx_http_sso_module).cast())
// refs/ipass/rust/src/lib.rs:824
ngx_shared_memory_add(cf, &raw mut name, size, (&raw mut ngx_http_ipass_module).cast())
```
**现在一行不改,同进程加载必然冲突。** 想共用就得把 tag 改成约定值(例如都传 `NULL`),
且 `size` 必须一致(或后者传 0 表示不校验)。
### 坑 2:同名变量会被后加载者「劫持」getter
两边注册了**完全相同的五个变量**:
```rust
static AUTH_VAR_NAMES: [&str; 5] = ["auth_user","auth_email","auth_groups","auth_sub","auth_token"];
```
`src/http/ngx_http_variables.c`:同名 + `NGX_HTTP_VAR_CHANGEABLE` 时
`ngx_http_add_variable` **返回已存在的那个 `v`**(不报错、不新建)。而两边注册后都做:
```rust
unsafe { (*var).get_handler = Some(auth_var_get); } // 覆盖
```
`ngx_http_get_variable_index` 对同名又返回**同一个 slot**。结果是:
> `$auth_user` 取哪个模块的 handler、以及 access 阶段谁最后写入该 slot,
> **完全取决于 `load_module` 的先后顺序**。
这类 bug 不报错,只会「某些部署下身份对、某些部署下身份错」。
### 坑 3:跨 .so 复用 Rust 结构是 UB
`ShmRoot { map: RwLock<RbTreeMap<..>>, file_lock: RwLock<()> }` 是 Rust 布局。
两个 `.so` 各自编译,只要 rustc 版本 / 优化级别 / 结构定义有任一差异,
字段偏移或 `RwLock` 内部表示就可能对不上 → 静默内存损坏。
要跨模块共享只能换成 `#[repr(C)]` + `magic` + `version` + `size` 三重校验的桥接头。
## 四、定稿结构
```
source/rust/
├── Cargo.toml # [workspace] members = crates/* + gateway
├── vendor/ngx-rust/ # 保持(path 依赖,不可走 crates.io / git)
├── crates/
│ ├── ipass-core/ # 网关内核:唯一读写 users.json 的地方
│ │ └── src/{config,models,users,store,state,session,util,http,audit,plugin}.rs
│ ├── plugin-sso/ # 身份插件:OAuth2/OIDC + IAP 注入
│ │ └── src/{oauth,oauth_clients,rsa,otp,captcha,api}.rs
│ ├── plugin-domain/ # 动态域名(后续迁入)
│ └── plugin-llm/ # LLM 路由 / 配额(后续迁入)
└── gateway/ # 装配层:模块壳 + 插件注册表 → 单个 .so
└── src/lib.rs
```
### 插件契约
```rust
pub trait Plugin {
fn name(&self) -> &'static str;
fn commands(&self) -> &[ngx_command_t]; // 配置指令(sso_api / ipass_proxy / ipass_llm ...)
fn preconfig(&self, cf) -> bool; // 注册 nginx 变量
fn postconfig(&self, cf) -> bool; // 注册 phase handler
fn api_routes(&self) -> &[Route]; // 管理接口
fn access(&self, r) -> Option<Status>; // access 阶段(可选)
}
```
装配层按声明顺序依次调用 → **handler 顺序显式可控**(这正是多 .so 方案里最难保证的一点)。
### 共享内存键前缀(现状已天然不冲突,直接沿用)
| 归属 | 前缀 |
| --- | --- |
| core | `sess:` `fail:` `ukey:` |
| plugin-sso | `sso:` `oac:` `ocl:` |
| plugin-domain | `sub:` |
| plugin-llm | `up:` `rl:` `st:` `ust:` `ums:` |
> `ukey:`(API Key → 身份索引)归 core:Key 由 core 签发与吊销,索引就必须由 core 维护,
> 否则会出现「Key 已重置但旧索引还在」的窗口。
## 五、`users.json`:共用一份,core 独占读写
- **物理上只有一份** `data/users.json`;插件**只读**,写入一律经 `ipass_core::users`
- **Schema 取并集**,所有新增字段 `#[serde(default)]`,存量文件可直接接管:
| 来源 | 字段 |
| --- | --- |
| 共用 | `username` `display_name` `role` `salt` `pwd_hash` `api_key` `email` `department` `groups` `created_at` |
| SSO | `failed_count` `locked_until` `totp_secret` `totp_enabled` |
| 域名 | `temp_grant_until` |
| LLM | `allowed_models` `llm_rpm` `llm_daily` |
- `groups` 用**宽容反序列化**(接受 `["rd","eng"]` 与 `"rd,eng"`):
只认数组会让外部目录导出的 `users.json` 整体反序列化失败,表现为「账号全部消失」
- Schema 版本与迁移逻辑由 core 负责;插件不得自行扩展 `User` 字段,
需要扩展时在 core 里加 `#[serde(default)]` 字段
## 六、落地路径
| 阶段 | 内容 | 验收 |
| --- | --- | --- |
| **P0** | 建 workspace;config/models/store/state/session/users/audit 迁入 core;User 取并集 | `run-local-e2e.sh` 五套全绿 |
| **P1** | 插件 trait + 路由注册表;sso 完成插件化;handler 顺序显式化 | 仅编 `--features sso` 与全量都能跑通 |
| **P2** | 迁入 plugin-domain(从 `refs/ipass` 移植,去掉其重复的 oauth/users) | 域名 e2e 全绿 |
| ~~P2'~~ | ~~迁入 plugin-llm~~ —— **已决定不迁入**:LLM 上游代理与配额计费属流量层,与本服务定位分界不变(已从 workspace 移除) | — |
| P3 | (可选)确需独立发版时才做 C ABI bridge,按第三节三条纪律执行 | — |
## 七、遗留待定
- 仓库归属:当前在 `ssw/sso` 仓库内改造,产品名已变为「iPass 统一网关」,
是否新建 `ssw/ipass` 仓库并迁移,由你定。
- `refs/ipass` 目前是带本地 `.git` 的存档副本(无 remote、不入本仓库版本控制),
P2 移植时按「新代码为准、旧实现仅作参考」处理。
---
## 附:本次查证用到的源码位置
| 论断 | 位置 |
| --- | --- |
| zone tag 不同 → EMERG 启动失败 | `src/core/ngx_cycle.c` → `ngx_shared_memory_add` |
| 同名 + CHANGEABLE → 返回已有变量而非新建 | `src/http/ngx_http_variables.c` → `ngx_http_add_variable` |
| sso 的 zone tag = `&ngx_http_sso_module` | `source/rust/src/lib.rs:451` |
| ipass 的 zone tag = `&ngx_http_ipass_module` | `refs/ipass/rust/src/lib.rs:824` |
| 两边注册同名 `$auth_*` 且覆盖 get_handler | `source/rust/src/lib.rs:254-262`、`refs/ipass/rust/src/lib.rs:89` |
| 键前缀全景 | `refs/ipass/rust/src/config.rs:66-101` |
| 代码重复量(oauth 425 / users 525 / models 234 / state 150 行差异) | 两仓库同名文件 diff |