精简版之前少了 /legacy/sso.html(身份/OAuth/同步/会话/指南
5 tab 入口都在里面),sso 插件 UMD 硬编码指它,精简版 nginx
无该 location → 5 tab 全 404。修补:
- deploy/legacy/sso.html 从 ipass-all 复制(自包含,76KB,
零外部 css/js 资产,fetch 全走 /api/admin/* 绝对路径)
- Dockerfile 加 COPY deploy/legacy/ /usr/local/nginx/legacy/
- nginx.conf 加 location /legacy/ { alias ...; } 静态段
- gateway Merge 不再继承父 location / 的 api=true,
否则 ipass_api on 的 catch-all 会让 /legacy/ 被 dispatch
接管返回 {"code":404,"msg":"接口不存在"}
- v0.7.5/v0.7.6/v0.7.7/v0.7.8 是这条链上的 debug 迭代,
v0.7.9 是清掉 debug log 后的发布版
460 lines
16 KiB
Rust
460 lines
16 KiB
Rust
//! # ipass-sso —— iPass SSO-only 精简版网关装配层
|
||
//!
|
||
//! 从 ipass-all 派生的精简发行版:只装 ipass-core + ipass-plugin-sso,
|
||
//! 编进单个 .so。剔除的插件(domain / llm / apix / cache / waf)不在
|
||
//! 依赖里也不在编译路径上。
|
||
//!
|
||
//! ```text
|
||
//! load_module modules/libipass_sso_gateway.so;
|
||
//! │
|
||
//! ipass-core sso
|
||
//! (内核) (身份)
|
||
//! ```
|
||
//!
|
||
//! ## 装配顺序(显式可控)
|
||
//!
|
||
//! `PLUGINS` 数组的顺序就是 preconfig → postconfig → dispatch_api 的顺序,
|
||
//! dispatch 按顺序认领、先注册者先得。
|
||
//!
|
||
//! **SsoPlugin 排第一**:两侧重叠的身份端点(login/logout/session/users
|
||
//! CRUD/me)由 sso 优先接管——它带 CAPTCHA、账号锁定、审计与身份字段;
|
||
//! CorePlugin 只补 sso 没有的端点。
|
||
|
||
// 内核模块桥接:本 crate 用 ipass_core 的 users::seed_admin 播种管理员
|
||
pub use ipass_core::{config, http, state, store, users, util};
|
||
|
||
use core::ffi::{c_char, c_void};
|
||
use core::ptr;
|
||
|
||
use ngx::core::{NGX_CONF_ERROR, NGX_CONF_OK, NgxStr, NgxString, SlabPool, Status};
|
||
use ngx::ffi::{
|
||
NGX_CONF_TAKE1, NGX_CONF_TAKE2, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET,
|
||
NGX_HTTP_MAIN_CONF, NGX_HTTP_MAIN_CONF_OFFSET, NGX_HTTP_MODULE, NGX_LOG_EMERG,
|
||
ngx_command_t, ngx_conf_t, ngx_cycle_t, ngx_http_module_t, ngx_http_request_t,
|
||
ngx_int_t, ngx_module_t, ngx_parse_size, ngx_shared_memory_add, ngx_shm_zone_t,
|
||
ngx_str_t, ngx_uint_t,
|
||
};
|
||
use ngx::http::{
|
||
HTTPStatus, HttpModule, HttpModuleLocationConf, HttpPhase, HttpRequestHandler, Merge,
|
||
MergeConfigError, Request,
|
||
};
|
||
use ngx::{ngx_conf_log_error, ngx_string};
|
||
use serde_json::Value;
|
||
|
||
use ipass_core::loc::{self, Switch};
|
||
use ipass_core::plugin::Plugin;
|
||
use ipass_plugin_sso::SsoPlugin;
|
||
|
||
// ===========================================================================
|
||
// 插件装配(PLUGINS 顺序 = 认领顺序;身份端点必须排最前)
|
||
// ===========================================================================
|
||
|
||
/// 插件注册表。**身份类端点(SsoPlugin)排最前**:dispatch 按顺序认领,
|
||
/// 先注册者先得。精简版只装 sso + core。
|
||
static PLUGINS: &[&dyn Plugin] = &[
|
||
&SsoPlugin,
|
||
&ipass_core::api::CorePlugin,
|
||
];
|
||
|
||
/// 装配根的插件扩展:把身份端点需要的插件侧数据回填给内核
|
||
/// (内核不认识任何插件,见 `ipass_core::api::CoreExt`)。
|
||
/// 精简版不挂任何插件侧数据:sso 的身份数据随账号本表删除,无附加回收项;
|
||
/// 无域名/LLM 用量装饰(domain/llm/apix 插件不在装配内)。
|
||
struct GatewayExt;
|
||
|
||
impl ipass_core::api::CoreExt for GatewayExt {
|
||
/// 管理台账号列表:精简版无 domain/llm 装饰。
|
||
fn decorate_admin_users(&self, _views: &mut [Value]) {
|
||
// SSO 精简版:账号只带身份字段,不挂域名数 / 用量摘要
|
||
}
|
||
|
||
/// `/api/v1/me`:精简版只回基础字段。
|
||
fn decorate_me(
|
||
&self,
|
||
_user: &ipass_core::models::User,
|
||
_port: &str,
|
||
_view: &mut Value,
|
||
) {
|
||
// SSO 精简版:不挂域名 / 用量 / 能力目录
|
||
}
|
||
|
||
/// 删除账号:sso 的身份数据随账号本表删除,无附加回收项。
|
||
fn reclaim_on_delete(&self, _username: &str) -> usize {
|
||
0
|
||
}
|
||
|
||
/// 账号「可用上游」白名单校验:精简版无 LLM 上游表,不校验。
|
||
fn validate_slots(&self, _slots: &[String]) -> Result<(), String> {
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 管理 API 分发(壳统一收口)
|
||
// ===========================================================================
|
||
|
||
/// 管理 API 分发:按 PLUGINS 顺序问每个插件,都不认领才统一 404。
|
||
fn dispatch_api(r: *mut ngx_http_request_t) -> Status {
|
||
for p in PLUGINS {
|
||
// R19:被禁插件不认领路由(自然落到下面的统一 404)。
|
||
// core 是网关身份底座,永不跳过。
|
||
if p.name() != "core" && !ipass_core::plugin_registry::plugin_enabled(p.name()) {
|
||
continue;
|
||
}
|
||
if let Some(s) = p.dispatch_api(r) {
|
||
return s;
|
||
}
|
||
}
|
||
let method = http::method_str(r);
|
||
let uri = http::uri(r);
|
||
http::fail(
|
||
r,
|
||
HTTPStatus::NOT_FOUND,
|
||
&format!("接口不存在:{method} {uri}"),
|
||
)
|
||
}
|
||
|
||
/// 管理 API:content 阶段先读请求体,读完后分发。
|
||
///
|
||
/// 精简版只有 sso + core 两个插件处理 API,没有 GatewayRoutes 组合端点。
|
||
struct ApiHandler;
|
||
|
||
impl HttpRequestHandler for ApiHandler {
|
||
const PHASE: HttpPhase = HttpPhase::Content;
|
||
type Output = Status;
|
||
|
||
fn handler(request: &mut Request) -> Self::Output {
|
||
if !Module::location_conf(request).map(|c| c.api).unwrap_or(false) {
|
||
return Status::NGX_DECLINED;
|
||
}
|
||
|
||
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
|
||
|
||
// SAFETY: r 有效;回调只会在请求内存池存活期间被调用
|
||
let rc = unsafe { nginx_sys::ngx_http_read_client_request_body(r, Some(api_body_ready)) };
|
||
|
||
// 读体失败(请求体超限等):把原始状态码交回 nginx,由它生成对应错误页
|
||
if rc >= nginx_sys::NGX_HTTP_SPECIAL_RESPONSE as ngx_int_t {
|
||
return Status(rc);
|
||
}
|
||
|
||
// 响应由回调发出,本阶段到此挂起
|
||
Status::NGX_DONE
|
||
}
|
||
}
|
||
|
||
/// 请求体就绪回调:执行路由分发并终结请求。
|
||
unsafe extern "C" fn api_body_ready(r: *mut ngx_http_request_t) {
|
||
let status = dispatch_api(r);
|
||
// SAFETY: r 由 nginx 传入且仍然有效;NGX_OK 表示响应已完整发出
|
||
unsafe { nginx_sys::ngx_http_finalize_request(r, status.0) };
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 模块定义
|
||
// ===========================================================================
|
||
|
||
struct Module;
|
||
|
||
/// 按 location 生效的开关。精简版只暴露 api + iap 两个开关。
|
||
#[derive(Debug, Default)]
|
||
struct ModuleConfig {
|
||
/// 该 location 暴露管理 API + 身份协议端点(`/api/*`、`/oauth/*`、`/login`)
|
||
api: bool,
|
||
/// 该 location 开启身份感知代理(IAP):未登录 → 跳转登录 / 401,
|
||
/// 已登录 → 注入 `$auth_*` 变量由 `proxy_set_header` 转成 `X-Auth-*` 头。
|
||
iap: bool,
|
||
}
|
||
|
||
unsafe impl HttpModuleLocationConf for Module {
|
||
type LocationConf = ModuleConfig;
|
||
}
|
||
|
||
impl Merge for ModuleConfig {
|
||
fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> {
|
||
// ⚠️ 不从父 location 继承 api:父 location / { ipass_api on; } 会让同 server
|
||
// 的所有兄弟 location(/admin/ /plugin- /manage/ /assets/ /static/plugins/ /legacy/
|
||
// 等静态段)被强制接管,dispatch 抢回 {"code":404,"msg":"接口不存在"}。
|
||
// 想要 API 兜底的子 location 必须显式 `ipass_api on;`(/api/ 与 / 已经显式开了)。
|
||
// iap 仍按父继承:access 阶段的身份门禁按 server 级默认更符合 MaxKey/OAuth2 Proxy
|
||
// 的心智(子 location 多是反向代理,继承省得每处再写)。
|
||
if prev.iap {
|
||
self.iap = true;
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
/// 把本模块的 location 开关暴露给内核,插件据此判断自己是否生效。
|
||
/// 未实现的变体(Domain/Proxy/Llm/Apix)**保守返回 false**,绝不误开。
|
||
fn loc_switch(request: &mut Request, s: Switch) -> bool {
|
||
let conf = Module::location_conf(request);
|
||
match s {
|
||
Switch::Api => conf.map(|c| c.api).unwrap_or(false),
|
||
Switch::Iap => conf.map(|c| c.iap).unwrap_or(false),
|
||
Switch::Domain | Switch::Proxy | Switch::Llm | Switch::Apix => false,
|
||
}
|
||
}
|
||
|
||
impl HttpModule for Module {
|
||
fn module() -> &'static ngx_module_t {
|
||
// SAFETY: 模块定义是静态的,生命周期贯穿进程
|
||
unsafe { &*ptr::addr_of!(ngx_http_ipass_sso_module) }
|
||
}
|
||
|
||
/// 必须在配置解析前注册变量
|
||
unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t {
|
||
// 契约层:注入 location 开关查询实现(早于任何请求与 phase handler)
|
||
loc::set_switch_fn(loc_switch);
|
||
// 装配根注册插件扩展:身份端点所需的插件侧数据经它回填内核
|
||
ipass_core::api::set_ext(&GatewayExt);
|
||
|
||
// 各插件注册自己的 nginx 变量($auth_* 归 sso)
|
||
for p in PLUGINS {
|
||
if !p.preconfig(cf) {
|
||
ngx_conf_log_error!(
|
||
NGX_LOG_EMERG,
|
||
unsafe { &mut *cf },
|
||
"插件 {} 变量注册失败",
|
||
p.name()
|
||
);
|
||
return Status::NGX_ERROR.into();
|
||
}
|
||
}
|
||
|
||
Status::NGX_OK.into()
|
||
}
|
||
|
||
unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t {
|
||
let cf = unsafe { &mut *cf };
|
||
|
||
// R19:装载插件启停注册表
|
||
let cfg = ipass_core::plugin_registry::load(&format!(
|
||
"{}/plugin-config.json",
|
||
store::data_dir()
|
||
));
|
||
ipass_core::plugin_registry::set_current(cfg);
|
||
|
||
// 把本模块 ctx_index 注入内核契约
|
||
ipass_core::plugin::set_ctx_index(Module::module().ctx_index as usize);
|
||
|
||
// 各插件注册自己的 phase handler(IAP 门禁归 sso)
|
||
for p in PLUGINS {
|
||
if !p.postconfig(cf) {
|
||
ngx_conf_log_error!(
|
||
NGX_LOG_EMERG,
|
||
cf,
|
||
"插件 {} 注册阶段处理器失败",
|
||
p.name()
|
||
);
|
||
return Status::NGX_ERROR.into();
|
||
}
|
||
}
|
||
|
||
// 管理接口由壳统一收口,内部按插件顺序分发
|
||
if ngx::http::add_phase_handler::<ApiHandler>(cf).is_err() {
|
||
return Status::NGX_ERROR.into();
|
||
}
|
||
Status::NGX_OK.into()
|
||
}
|
||
}
|
||
|
||
// 精简版只装 sso + core:4 条指令
|
||
static mut NGX_HTTP_IPASS_SSO_COMMANDS: [ngx_command_t; 5] = [
|
||
ngx_command_t {
|
||
name: ngx_string!("ipass_state"),
|
||
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t,
|
||
set: Some(set_state_zone),
|
||
conf: NGX_HTTP_MAIN_CONF_OFFSET,
|
||
offset: 0,
|
||
post: ptr::null_mut(),
|
||
},
|
||
ngx_command_t {
|
||
name: ngx_string!("ipass_data_dir"),
|
||
type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
|
||
set: Some(set_data_dir),
|
||
conf: NGX_HTTP_MAIN_CONF_OFFSET,
|
||
offset: 0,
|
||
post: ptr::null_mut(),
|
||
},
|
||
ngx_command_t {
|
||
name: ngx_string!("ipass_api"),
|
||
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
|
||
set: Some(set_flag_api),
|
||
conf: NGX_HTTP_LOC_CONF_OFFSET,
|
||
offset: 0,
|
||
post: ptr::null_mut(),
|
||
},
|
||
ngx_command_t {
|
||
name: ngx_string!("sso_iap"),
|
||
type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t,
|
||
set: Some(set_flag_iap),
|
||
conf: NGX_HTTP_LOC_CONF_OFFSET,
|
||
offset: 0,
|
||
post: ptr::null_mut(),
|
||
},
|
||
ngx_command_t::empty(),
|
||
];
|
||
|
||
static NGX_HTTP_IPASS_SSO_MODULE_CTX: ngx_http_module_t = ngx_http_module_t {
|
||
preconfiguration: Some(Module::preconfiguration),
|
||
postconfiguration: Some(Module::postconfiguration),
|
||
create_main_conf: None,
|
||
init_main_conf: None,
|
||
create_srv_conf: None,
|
||
merge_srv_conf: None,
|
||
create_loc_conf: Some(Module::create_loc_conf),
|
||
merge_loc_conf: Some(Module::merge_loc_conf),
|
||
};
|
||
|
||
// 脱离 nginx 构建系统、单独产出 cdylib 时必须靠这个宏导出 ngx_modules 表
|
||
#[cfg(feature = "export-modules")]
|
||
ngx::ngx_modules!(ngx_http_ipass_sso_module);
|
||
|
||
#[used]
|
||
#[allow(non_upper_case_globals)]
|
||
pub static mut ngx_http_ipass_sso_module: ngx_module_t = ngx_module_t {
|
||
ctx: &raw const NGX_HTTP_IPASS_SSO_MODULE_CTX as _,
|
||
commands: unsafe { &raw mut NGX_HTTP_IPASS_SSO_COMMANDS[0] },
|
||
type_: NGX_HTTP_MODULE as _,
|
||
init_process: Some(init_process),
|
||
exit_process: Some(exit_process),
|
||
..ngx_module_t::default()
|
||
};
|
||
|
||
/// 每个 worker 启动后执行一次。管理员播种是**幂等**的。
|
||
unsafe extern "C" fn init_process(_cycle: *mut ngx_cycle_t) -> ngx_int_t {
|
||
match users::seed_admin() {
|
||
Ok(true) => util::log_warn(
|
||
"[ipass] 已创建初始管理员 admin,请首次登录后立即修改密码",
|
||
),
|
||
Ok(false) => {}
|
||
Err(e) => util::log_err(&format!("[ipass] 初始化管理员失败: {e}")),
|
||
}
|
||
Status::NGX_OK.into()
|
||
}
|
||
|
||
/// worker 退出前执行一次。精简版无运行期统计要落盘,钩子留空即可。
|
||
unsafe extern "C" fn exit_process(_cycle: *mut ngx_cycle_t) {
|
||
// SSO 精简版:共享内存里只有身份会话与账号 Key,重启即失效属已知代价,
|
||
// 不需要 exit 钩子落盘。
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 指令处理
|
||
// ===========================================================================
|
||
|
||
/// 读第 2 个参数并转成 bool(on/off/1/0/yes/no)。
|
||
unsafe fn arg_flag(cf: *mut ngx_conf_t, idx: usize) -> Option<bool> {
|
||
let cf_ref = unsafe { cf.as_mut() }?;
|
||
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
|
||
let raw = args.get(idx)?.as_bytes();
|
||
let s = core::str::from_utf8(raw).ok()?;
|
||
Some(matches!(s.to_ascii_lowercase().as_str(), "on" | "1" | "true" | "yes"))
|
||
}
|
||
|
||
extern "C" fn set_flag_api(
|
||
cf: *mut ngx_conf_t,
|
||
_cmd: *mut ngx_command_t,
|
||
conf: *mut c_void,
|
||
) -> *mut c_char {
|
||
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
|
||
return NGX_CONF_ERROR;
|
||
};
|
||
// SAFETY: nginx 保证 conf 指向本模块的 loc conf 结构
|
||
unsafe { (*(conf as *mut ModuleConfig)).api = flag };
|
||
NGX_CONF_OK
|
||
}
|
||
|
||
extern "C" fn set_flag_iap(
|
||
cf: *mut ngx_conf_t,
|
||
_cmd: *mut ngx_command_t,
|
||
conf: *mut c_void,
|
||
) -> *mut c_char {
|
||
let Some(flag) = (unsafe { arg_flag(cf, 1) }) else {
|
||
return NGX_CONF_ERROR;
|
||
};
|
||
// SAFETY: 同上
|
||
unsafe { (*(conf as *mut ModuleConfig)).iap = flag };
|
||
NGX_CONF_OK
|
||
}
|
||
|
||
extern "C" fn set_state_zone(
|
||
cf: *mut ngx_conf_t,
|
||
_cmd: *mut ngx_command_t,
|
||
_conf: *mut c_void,
|
||
) -> *mut c_char {
|
||
// SAFETY: 配置回调必然拿到有效的 cf
|
||
let cf_ref = unsafe { cf.as_mut().unwrap() };
|
||
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
|
||
|
||
let mut name: ngx_str_t = args[1];
|
||
let size = unsafe { ngx_parse_size(&raw mut args[2]) };
|
||
if size == -1 {
|
||
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_state: 共享内存大小非法");
|
||
return NGX_CONF_ERROR;
|
||
}
|
||
|
||
let zone = unsafe {
|
||
ngx_shared_memory_add(
|
||
cf,
|
||
&raw mut name,
|
||
size as usize,
|
||
(&raw mut ngx_http_ipass_sso_module).cast(),
|
||
)
|
||
};
|
||
if zone.is_null() {
|
||
return NGX_CONF_ERROR;
|
||
}
|
||
|
||
unsafe {
|
||
(*zone).init = Some(state_zone_init);
|
||
}
|
||
state::set_zone(zone);
|
||
NGX_CONF_OK
|
||
}
|
||
|
||
/// 共享内存初始化:由 nginx 在 **fork 之前**调用一次。
|
||
///
|
||
/// 精简版只装载 sso 自持表(OAuth 接入方表由 SsoPlugin::zone_load 自己装)+
|
||
/// 各插件 zone_load 回调;无 domain/llm/apix 数据面需要预装载。
|
||
extern "C" fn state_zone_init(zone: *mut ngx_shm_zone_t, _data: *mut c_void) -> ngx_int_t {
|
||
let status = state::init_zone(zone);
|
||
if status != Status::NGX_OK {
|
||
return status.into();
|
||
}
|
||
|
||
// 各插件自持表的预装载(sso 的 OAuth 接入方等);
|
||
// 没有自持表的插件返回 0,仅打日志。
|
||
for p in PLUGINS {
|
||
let n = p.zone_load();
|
||
util::log_notice(&format!("[gateway] 插件 {} 预装载 {n} 条", p.name()));
|
||
}
|
||
|
||
Status::NGX_OK.into()
|
||
}
|
||
|
||
extern "C" fn set_data_dir(
|
||
cf: *mut ngx_conf_t,
|
||
_cmd: *mut ngx_command_t,
|
||
_conf: *mut c_void,
|
||
) -> *mut c_char {
|
||
// SAFETY: 配置回调必然拿到有效的 cf
|
||
let cf_ref = unsafe { cf.as_mut().unwrap() };
|
||
let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() };
|
||
|
||
match core::str::from_utf8(args[1].as_bytes()) {
|
||
Ok(dir) => {
|
||
store::set_data_dir(dir);
|
||
NGX_CONF_OK
|
||
}
|
||
Err(_) => {
|
||
ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "ipass_data_dir: 路径不是合法 UTF-8");
|
||
NGX_CONF_ERROR
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 供测试与诊断使用:`NgxStr` 类型在模块里被多处引用,确保编译期链接到正确的符号
|
||
#[allow(dead_code)]
|
||
fn _type_witness(_: &NgxStr, _: &NgxString<SlabPool>) {} |