- source/rust → rust/ - source/conf → conf/ - source/www → www/ - source/data-seed → data-seed/ - source/data → data/ - scripts/ 保留(语义不对应 ipass deploy/) - /build/ 加入 .gitignore(本机 nginx 源码树) - README.md 目录树同步 + build 路径 /tmp/sso-build → ./build - Cargo.toml path 依赖 '../../deps/ipass' → '../deps/ipass' - CLAUDE.md 同步路径示例 cargo check 通过(52s);release build 通过(1m26s),产物 libsso_gateway.dylib
227 lines
8.3 KiB
Rust
227 lines
8.3 KiB
Rust
//! # plugin-sso —— 身份插件
|
||
//!
|
||
//! 提供两件事,都建立在 `ipass-core` 的账号与 Key 之上:
|
||
//!
|
||
//! * **IdP**:OAuth2 / OIDC 签发与校验(`/oauth/*`、discovery、JWKS、introspect)
|
||
//! * **IAP**:access 阶段判定身份,写入 `$auth_*` 变量,由 nginx
|
||
//! `proxy_set_header X-Auth-*` 注入后端,业务系统零改造
|
||
//!
|
||
//! 本插件**不持有**账号数据——只读 `ipass_core::users`,写入一律走内核。
|
||
//! 这是「SSO 与域名 / LLM 共用同一份 `users.json`、同一把 API Key」的落点。
|
||
|
||
mod accounts;
|
||
mod api;
|
||
mod audit;
|
||
mod captcha;
|
||
mod cas;
|
||
mod geo;
|
||
mod ldap;
|
||
mod scim;
|
||
mod otp;
|
||
mod reset;
|
||
mod portal;
|
||
mod sync;
|
||
pub mod oauth;
|
||
mod oauth_clients;
|
||
mod oauth_keys;
|
||
mod oauth_state;
|
||
mod rsa;
|
||
mod storex;
|
||
mod utilx;
|
||
mod compat;
|
||
|
||
use core::ptr;
|
||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||
use std::ffi::CString;
|
||
|
||
use ipass_core::plugin::Plugin;
|
||
use ngx::core::{Pool, Status};
|
||
use ngx::ffi::{
|
||
NGX_HTTP_VAR_CHANGEABLE, ngx_conf_t, ngx_http_add_variable, ngx_http_get_variable_index,
|
||
ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t, ngx_str_t, ngx_uint_t,
|
||
};
|
||
use ngx::http::{HttpPhase, HttpRequestHandler};
|
||
use ngx::http::HTTPStatus;
|
||
|
||
/// IAP 注入变量 `$auth_user/$auth_email/$auth_groups/$auth_sub/$auth_token` 的下标。
|
||
///
|
||
/// 顺序固定对应 `AUTH_VAR_NAMES`,与 `set_auth_vars` 一一对应。
|
||
static AUTH_VAR_INDEX: [AtomicUsize; 5] = [
|
||
AtomicUsize::new(usize::MAX),
|
||
AtomicUsize::new(usize::MAX),
|
||
AtomicUsize::new(usize::MAX),
|
||
AtomicUsize::new(usize::MAX),
|
||
AtomicUsize::new(usize::MAX),
|
||
];
|
||
static AUTH_VAR_NAMES: [&str; 5] = ["auth_user", "auth_email", "auth_groups", "auth_sub", "auth_token"];
|
||
|
||
/// 身份插件(SSO)。
|
||
///
|
||
/// 本仓库只持有这一个身份插件;域名 / LLM / API 代理等通用子系统
|
||
/// 由主项目 ipass/ipass 提供(见仓库根 `deps/ipass` 子模块),本网关不再内置。
|
||
pub struct SsoPlugin;
|
||
|
||
impl Plugin for SsoPlugin {
|
||
fn name(&self) -> &'static str {
|
||
"sso"
|
||
}
|
||
|
||
fn preconfig(&self, cf: *mut ngx_conf_t) -> bool {
|
||
// SAFETY: 配置回调必然拿到有效 cf
|
||
unsafe { register_auth_vars(cf) }
|
||
}
|
||
|
||
fn postconfig(&self, cf: *mut ngx_conf_t) -> bool {
|
||
// SAFETY: 配置回调必然拿到有效 cf
|
||
let cf = unsafe { &mut *cf };
|
||
ngx::http::add_phase_handler::<IapHandler>(cf).is_ok()
|
||
}
|
||
|
||
fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option<Status> {
|
||
let method = ipass_core::http::method_str(r);
|
||
let uri = ipass_core::http::uri(r);
|
||
// 精确命中,或按 MaxKey context-path 归一化后命中 → 归我处理
|
||
if api::matches(&method, &uri) {
|
||
Some(api::dispatch(r))
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
fn zone_load(&self) -> usize {
|
||
oauth_clients::reload_shm()
|
||
}
|
||
}
|
||
|
||
/// IAP 门禁:access 阶段判定身份并注入 `$auth_*`。
|
||
///
|
||
/// 与 MaxKey / OAuth2 Proxy 同构——网关在转发前判定身份,并把身份写进
|
||
/// `$auth_*` 变量,下游 `proxy_set_header X-Auth-*` 据此注入(后端只信网关,
|
||
/// 客户端伪装的同名头被覆盖)。无有效身份时返回 401,由 nginx `error_page`
|
||
/// 内部跳转 `@oauth_login` 完成登录重定向(见 conf/*.conf),与模块解耦。
|
||
struct IapHandler;
|
||
|
||
impl HttpRequestHandler for IapHandler {
|
||
const PHASE: HttpPhase = HttpPhase::Access;
|
||
type Output = Status;
|
||
|
||
fn handler(request: &mut ngx::http::Request) -> Self::Output {
|
||
if !ipass_core::loc::enabled(request.into(), ipass_core::loc::Switch::Iap) {
|
||
return Status::NGX_DECLINED;
|
||
}
|
||
let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t;
|
||
|
||
match oauth::iap_identity(r) {
|
||
Some((user, email, groups, sub, token)) => {
|
||
let vals = [user, email, groups, sub, token];
|
||
set_auth_vars(r, &vals);
|
||
Status::NGX_DECLINED
|
||
}
|
||
None => {
|
||
// 无身份:返回 401,带 login 提示;浏览器由 error_page 跳登录页,
|
||
// API 客户端按 WWW-Authenticate 走 Bearer / 登录换码。
|
||
let login = format!("{}/login", oauth::issuer());
|
||
request.add_header_out(
|
||
"WWW-Authenticate",
|
||
&format!("Bearer realm=\"sso\", login=\"{login}\""),
|
||
);
|
||
HTTPStatus::UNAUTHORIZED.into()
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 把身份写入 `$auth_user/$auth_email/$auth_groups/$auth_sub/$auth_token`,
|
||
/// 供 `proxy_set_header X-Auth-*` 求值时取到。
|
||
fn set_auth_vars(r: *mut ngx_http_request_t, vals: &[String; 5]) {
|
||
for i in 0..5 {
|
||
let idx = AUTH_VAR_INDEX[i].load(Ordering::SeqCst);
|
||
if idx == usize::MAX {
|
||
continue;
|
||
}
|
||
// SAFETY: idx 由 ngx_http_get_variable_index 分配且在 r->variables 内;
|
||
// 值分配在请求池,随请求回收。
|
||
unsafe {
|
||
let pool = Pool::from_ngx_pool((*r).pool);
|
||
let bytes = vals[i].as_bytes();
|
||
let data = pool.alloc(bytes.len()) as *mut u8;
|
||
if data.is_null() {
|
||
continue;
|
||
}
|
||
ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
|
||
let vv: *mut ngx_http_variable_value_t = (*r).variables.add(idx);
|
||
(*vv).data = data;
|
||
(*vv).set_len(bytes.len() as _);
|
||
(*vv).set_valid(1);
|
||
(*vv).set_not_found(0);
|
||
// 必须为 0:变量定义侧也刻意不含 NGX_HTTP_VAR_NOCACHEABLE,
|
||
// 保证 content 阶段读取时直接命中缓存,不回落到 auth_var_get
|
||
// (回调拿不到注入值,会把变量读成空)。
|
||
(*vv).set_no_cacheable(0);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 注册 IAP 注入变量(运行时名,需手动构造 `ngx_str_t`)。
|
||
///
|
||
/// 必须在配置解析前注册,否则 `proxy_set_header X-Auth-User $auth_user` 无法解析。
|
||
unsafe fn register_auth_vars(cf: *mut ngx_conf_t) -> bool {
|
||
let cf = &mut *cf;
|
||
for i in 0..AUTH_VAR_NAMES.len() {
|
||
let name = AUTH_VAR_NAMES[i];
|
||
let c = match CString::new(name) {
|
||
Ok(c) => c,
|
||
Err(_) => return false,
|
||
};
|
||
let mut ns = ngx_str_t {
|
||
len: name.len() as ngx_uint_t,
|
||
data: c.as_ptr() as *mut u8,
|
||
};
|
||
|
||
// 1) 先登记变量名 + get_handler。只调 ngx_http_get_variable_index 是
|
||
// 不够的:它会往 cmcf->variables 里推一项(get_handler=NULL),而
|
||
// nginx 的 ngx_http_variables_init_vars 随后要求每个这样的名字都能在
|
||
// cmcf->variables_keys(由 ngx_http_add_variable 填充)里找到 handler,
|
||
// 否则启动即 EMERG `unknown "auth_user" variable`。
|
||
//
|
||
// 刻意**不加** NGX_HTTP_VAR_NOCACHEABLE,理由见 `set_auth_vars`。
|
||
let var =
|
||
unsafe { ngx_http_add_variable(cf, &mut ns, NGX_HTTP_VAR_CHANGEABLE as ngx_uint_t) };
|
||
if var.is_null() {
|
||
return false;
|
||
}
|
||
// SAFETY: var 非空且由本函数独占初始化
|
||
unsafe {
|
||
(*var).get_handler = Some(auth_var_get);
|
||
(*var).set_handler = None;
|
||
(*var).data = 0;
|
||
}
|
||
|
||
// 2) 取写入槽位下标(IAP 热路径直接写 r->variables[idx],见 set_auth_vars)
|
||
let idx = unsafe { ngx_http_get_variable_index(cf, &mut ns) };
|
||
if idx == -1 {
|
||
return false;
|
||
}
|
||
AUTH_VAR_INDEX[i].store(idx as usize, Ordering::SeqCst);
|
||
}
|
||
true
|
||
}
|
||
|
||
/// `$auth_*` 的兜底 get_handler:IAP 未注入时返回 DECLINED(等价于空变量)。
|
||
///
|
||
/// 正常路径下永不被调用——IAP 已在 access 阶段把 `r->variables[idx]` 标为
|
||
/// valid(见 `set_auth_vars`),读取时走缓存短路。此函数只为满足
|
||
/// `ngx_http_variables_init_vars` 对「已登记变量必须有 handler」的硬性要求。
|
||
extern "C" fn auth_var_get(
|
||
_r: *mut ngx_http_request_t,
|
||
_v: *mut ngx_http_variable_value_t,
|
||
_data: usize,
|
||
) -> ngx_int_t {
|
||
Status::NGX_DECLINED.into()
|
||
}
|
||
|
||
/// 供 gateway 在 zone 初始化后打印装载结果(仅日志用)
|
||
pub fn zone_load_log(n: usize) -> String {
|
||
format!("[sso] 已装载 {n} 个 OAuth2 接入方")
|
||
}
|