From 9de4d6735479cd17e7a95ff3b7cf7113b7f91ded Mon Sep 17 00:00:00 2001 From: admin Date: Thu, 24 Sep 2026 16:56:17 +0800 Subject: [PATCH] refactor: depend on ../ipass-plugin-sso; strip local copy --- deploy/nginx.conf | 5 + rust/Cargo.lock | 25 +- rust/Cargo.toml | 4 +- rust/crates/plugin-sso/Cargo.toml | 18 - rust/crates/plugin-sso/src/accounts.rs | 553 ------- rust/crates/plugin-sso/src/api.rs | 1070 ------------- rust/crates/plugin-sso/src/audit.rs | 151 -- rust/crates/plugin-sso/src/captcha.rs | 135 -- rust/crates/plugin-sso/src/cas.rs | 202 --- rust/crates/plugin-sso/src/compat.rs | 84 - rust/crates/plugin-sso/src/geo.rs | 152 -- rust/crates/plugin-sso/src/ldap.rs | 252 --- rust/crates/plugin-sso/src/lib.rs | 226 --- rust/crates/plugin-sso/src/oauth.rs | 1484 ------------------ rust/crates/plugin-sso/src/oauth_clients.rs | 377 ----- rust/crates/plugin-sso/src/oauth_keys.rs | 59 - rust/crates/plugin-sso/src/oauth_state.rs | 210 --- rust/crates/plugin-sso/src/otp.rs | 328 ---- rust/crates/plugin-sso/src/portal.rs | 231 --- rust/crates/plugin-sso/src/reset.rs | 272 ---- rust/crates/plugin-sso/src/rsa.rs | 699 --------- rust/crates/plugin-sso/src/scim.rs | 602 ------- rust/crates/plugin-sso/src/storex.rs | 40 - rust/crates/plugin-sso/src/sync.rs | 191 --- rust/crates/plugin-sso/src/utilx.rs | 34 - rust/gateway/Cargo.toml | 2 +- rust/gateway/src/lib.rs | 2 +- www/admin.html | 1552 ------------------- 28 files changed, 21 insertions(+), 8939 deletions(-) delete mode 100644 rust/crates/plugin-sso/Cargo.toml delete mode 100644 rust/crates/plugin-sso/src/accounts.rs delete mode 100644 rust/crates/plugin-sso/src/api.rs delete mode 100644 rust/crates/plugin-sso/src/audit.rs delete mode 100644 rust/crates/plugin-sso/src/captcha.rs delete mode 100644 rust/crates/plugin-sso/src/cas.rs delete mode 100644 rust/crates/plugin-sso/src/compat.rs delete mode 100644 rust/crates/plugin-sso/src/geo.rs delete mode 100644 rust/crates/plugin-sso/src/ldap.rs delete mode 100644 rust/crates/plugin-sso/src/lib.rs delete mode 100644 rust/crates/plugin-sso/src/oauth.rs delete mode 100644 rust/crates/plugin-sso/src/oauth_clients.rs delete mode 100644 rust/crates/plugin-sso/src/oauth_keys.rs delete mode 100644 rust/crates/plugin-sso/src/oauth_state.rs delete mode 100644 rust/crates/plugin-sso/src/otp.rs delete mode 100644 rust/crates/plugin-sso/src/portal.rs delete mode 100644 rust/crates/plugin-sso/src/reset.rs delete mode 100644 rust/crates/plugin-sso/src/rsa.rs delete mode 100644 rust/crates/plugin-sso/src/scim.rs delete mode 100644 rust/crates/plugin-sso/src/storex.rs delete mode 100644 rust/crates/plugin-sso/src/sync.rs delete mode 100644 rust/crates/plugin-sso/src/utilx.rs delete mode 100644 www/admin.html diff --git a/deploy/nginx.conf b/deploy/nginx.conf index 9459a60..2da983e 100644 --- a/deploy/nginx.conf +++ b/deploy/nginx.conf @@ -79,5 +79,10 @@ http { location = /admin { return 302 /admin/; } + + # 插件静态资源(由 ipass-core 核心壳统一提供,所有插件共用此路径) + location /static/plugins/ { + alias /Users/xs/Desktop/workspace/ipass/; + } } } diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 62abadd..4346a95 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -185,6 +185,17 @@ dependencies = [ "sha2", ] +[[package]] +name = "ipass-plugin-sso" +version = "2.0.0" +dependencies = [ + "ipass-core", + "nginx-sys", + "ngx", + "serde", + "serde_json", +] + [[package]] name = "itertools" version = "0.13.0" @@ -274,18 +285,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "plugin-sso" -version = "1.0.0" -dependencies = [ - "ipass-core", - "nginx-sys", - "ngx", - "serde", - "serde_json", - "sha2", -] - [[package]] name = "prettyplease" version = "0.2.37" @@ -426,9 +425,9 @@ name = "sso-gateway" version = "1.0.0" dependencies = [ "ipass-core", + "ipass-plugin-sso", "nginx-sys", "ngx", - "plugin-sso", ] [[package]] diff --git a/rust/Cargo.toml b/rust/Cargo.toml index 97b5c95..7b2f194 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -14,7 +14,7 @@ # 跨 .so 共享状态要自己造 C ABI 契约,且 zone tag / 同名变量都会冲突 # (详见 docs/plugin-architecture-analysis.md)。 [workspace] -members = ["crates/plugin-sso", "gateway"] +members = ["gateway"] exclude = ["target"] [workspace.package] @@ -43,7 +43,7 @@ publish = false ngx = { path = "../../ipass-core/rust/vendor/ngx-rust" } nginx-sys = { path = "../../ipass-core/rust/vendor/ngx-rust/nginx-sys" } ipass-core = { path = "../../ipass-core/rust/crates/ipass-core" } -plugin-sso = { path = "crates/plugin-sso" } +ipass-plugin-sso = { path = "../../ipass-plugin-sso" } # 业务层依赖:全部是纯 Rust 实现,不引入任何系统库或常驻依赖 serde = { version = "1", features = ["derive"] } diff --git a/rust/crates/plugin-sso/Cargo.toml b/rust/crates/plugin-sso/Cargo.toml deleted file mode 100644 index 5f6ff88..0000000 --- a/rust/crates/plugin-sso/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "plugin-sso" -version.workspace = true -edition.workspace = true -publish.workspace = true -description = "iPass 身份插件 —— OAuth2/OIDC 签发与校验、IAP 身份注入(依赖 ipass-core 提供账号与 Key)" - -[lib] -name = "plugin_sso" -crate-type = ["rlib"] - -[dependencies] -ngx.workspace = true -nginx-sys.workspace = true -serde.workspace = true -serde_json.workspace = true -sha2.workspace = true -ipass-core.workspace = true diff --git a/rust/crates/plugin-sso/src/accounts.rs b/rust/crates/plugin-sso/src/accounts.rs deleted file mode 100644 index a89c627..0000000 --- a/rust/crates/plugin-sso/src/accounts.rs +++ /dev/null @@ -1,553 +0,0 @@ -//! 账号身份扩展层(sso 插件本地模块)。 -//! -//! 来源:原内核 `users.rs` / `models.rs` 中随内核上游化(ipass A4/A1 决策) -//! 迁入插件的部分。分工: -//! -//! * **内核**(上游 ipass-core):账号共性(username/role/口令/API Key/生命周期)、 -//! `store::update_users` 持锁读改写、`users::sync_shm` 写穿。 -//! * **本模块**:身份语义(email/department/groups)、账号维度登录失败锁定 -//! (`failed_count`/`locked_until`,存 `User.extra`)、对应校验与管理台视图。 -//! -//! 身份字段全部存 `User.extra`(上游 A1 决策的透传通道),经 [`UserExt`] -//! 以强类型方法读写;存量 `users.json` 字段形状(数组/CSV 两种 groups 写法) -//! 保持兼容。 - -use std::collections::BTreeMap; - -use serde_json::{json, Value}; - -use ipass_core::config; -use ipass_core::models::{User, UserTable}; -use ipass_core::store; -use ipass_core::users; -use ipass_core::util; - -// =========================================================================== -// 身份策略常量(弱口令门槛属业务策略,按上游 A6-1 决策留插件层) -// =========================================================================== - -/// 部门名长度上限 -pub const DEPARTMENT_MAX_LEN: usize = 64; -/// 单账号用户组数量上限 -pub const GROUPS_MAX: usize = 32; -/// 组名长度上限 -pub const GROUP_NAME_MAX_LEN: usize = 64; -/// 连续登录失败阈值(达到即锁定) -pub const ACCOUNT_LOCK_THRESHOLD: i64 = 5; -/// 锁定时长(秒) -pub const ACCOUNT_LOCK_TTL: i64 = 600; -/// sso 插件层口令最小长度(内核最小约束是 6,本插件策略收紧到 8) -pub const PASSWORD_MIN_LEN: usize = 8; - -/// `view()` 透出 extra 时隐藏的敏感键(TOTP 种子绝不回传前端) -const HIDDEN_EXTRA_KEYS: &[&str] = &["totp_secret"]; - -// extra 键名(存量 users.json 已是这些形状,不得改动) -pub const EXTRA_EMAIL: &str = "email"; -pub const EXTRA_DEPARTMENT: &str = "department"; -pub const EXTRA_GROUPS: &str = "groups"; -pub const EXTRA_MOBILE: &str = "mobile"; -pub const EXTRA_FAILED_COUNT: &str = "failed_count"; -pub const EXTRA_LOCKED_UNTIL: &str = "locked_until"; - -// =========================================================================== -// UserExt:User 的身份字段强类型访问(全部落在 extra) -// =========================================================================== - -pub trait UserExt { - // ---- 读 ---- - fn email(&self) -> &str; - fn mobile(&self) -> &str; - fn department(&self) -> &str; - /// 用户组(同时接受 `["a","b"]` 数组与 `"a,b"` CSV 两种存量写法) - fn groups(&self) -> Vec; - fn groups_csv(&self) -> String; - fn failed_count(&self) -> i64; - fn locked_until(&self) -> i64; - /// 账号是否处于锁定状态(锁定到期自动视为未锁定) - fn is_locked(&self, now: i64) -> bool; - /// 展示名优先,留空回落账号名 - fn display_or_username(&self) -> String; - // ---- extra 通用访问器(otp / oauth 会话 payload 用)---- - fn extra_get(&self, key: &str) -> Option<&Value>; - fn extra_str(&self, key: &str) -> &str; - fn extra_i64(&self, key: &str) -> i64; - fn extra_bool(&self, key: &str) -> bool; - fn extra_str_list(&self, key: &str) -> Vec; - // ---- 写(在 `store::update_users` / `users::update_extra` 闭包内用)---- - fn set_email(&mut self, v: &str); - fn set_mobile(&mut self, v: &str); - fn set_department(&mut self, v: &str); - fn set_groups(&mut self, v: Vec); - fn set_failed_count(&mut self, v: i64); - fn set_locked_until(&mut self, v: i64); -} - -impl UserExt for User { - fn email(&self) -> &str { - self.extra_str(EXTRA_EMAIL) - } - fn mobile(&self) -> &str { - self.extra_str(EXTRA_MOBILE) - } - fn department(&self) -> &str { - self.extra_str(EXTRA_DEPARTMENT) - } - fn groups(&self) -> Vec { - self.extra_str_list(EXTRA_GROUPS) - } - fn groups_csv(&self) -> String { - self.groups().join(",") - } - fn failed_count(&self) -> i64 { - self.extra_i64(EXTRA_FAILED_COUNT) - } - fn locked_until(&self) -> i64 { - self.extra_i64(EXTRA_LOCKED_UNTIL) - } - fn is_locked(&self, now: i64) -> bool { - self.locked_until() > now - } - fn display_or_username(&self) -> String { - if self.display_name.is_empty() { - self.username.clone() - } else { - self.display_name.clone() - } - } - fn extra_get(&self, key: &str) -> Option<&Value> { - self.extra.get(key) - } - fn extra_str(&self, key: &str) -> &str { - self.extra.get(key).and_then(Value::as_str).unwrap_or("") - } - 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) - } - fn extra_bool(&self, key: &str) -> bool { - self.extra.get(key).and_then(Value::as_bool).unwrap_or(false) - } - 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 set_email(&mut self, v: &str) { - self.extra.insert(EXTRA_EMAIL.to_owned(), Value::String(v.to_owned())); - } - fn set_mobile(&mut self, v: &str) { - self.extra - .insert(EXTRA_MOBILE.to_owned(), Value::String(v.to_owned())); - } - fn set_department(&mut self, v: &str) { - self.extra - .insert(EXTRA_DEPARTMENT.to_owned(), Value::String(v.to_owned())); - } - fn set_groups(&mut self, v: Vec) { - self.extra - .insert(EXTRA_GROUPS.to_owned(), Value::Array(v.into_iter().map(Value::String).collect())); - } - fn set_failed_count(&mut self, v: i64) { - self.extra - .insert(EXTRA_FAILED_COUNT.to_owned(), Value::from(v)); - } - fn set_locked_until(&mut self, v: i64) { - self.extra - .insert(EXTRA_LOCKED_UNTIL.to_owned(), Value::from(v)); - } -} - -// =========================================================================== -// 校验 -// =========================================================================== - -/// 账号名:2-32 位字母、数字、下划线或短横线(与上游规则一致) -fn valid_username(name: &str) -> bool { - let n = name.chars().count(); - if n < config::USERNAME_MIN_LEN || n > config::USERNAME_MAX_LEN { - return false; - } - name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') -} - -/// 展示名:允许中文/空格,不允许控制字符(会进 JSON 与注入头) -pub fn check_display_name(raw: &str) -> Result { - let v = util::trim(raw).to_owned(); - if v.chars().count() > config::DISPLAY_NAME_MAX_LEN { - return Err(format!("展示名不能超过 {} 个字", config::DISPLAY_NAME_MAX_LEN)); - } - if v.chars().any(|c| c.is_control()) { - return Err("展示名不能包含换行或控制字符".to_owned()); - } - Ok(v) -} - -/// sso 插件层口令策略(内核最小约束 6 位之上收紧到 8 位) -pub fn check_password(password: &str) -> Result<(), String> { - let n = password.chars().count(); - if n < PASSWORD_MIN_LEN { - return Err(format!("口令至少 {PASSWORD_MIN_LEN} 位")); - } - if password.chars().any(|c| c.is_control()) { - return Err("口令不能包含控制字符".to_owned()); - } - Ok(()) -} - -/// 邮箱:宽松校验,不接受控制字符——它会被注入 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) -} - -/// 手机号:宽松校验(国际号允许 + 前缀),不接受控制字符与空白—— -/// 它会进 OIDC claims 与接入方建档(uc_user.phone)。 -pub fn check_mobile(raw: &str) -> Result { - let v = util::trim(raw).to_owned(); - if v.is_empty() { - return Ok(v); - } - if v.len() > 32 || v.chars().any(|c| c.is_control() || c.is_whitespace()) { - return Err("手机号格式不正确".to_owned()); - } - if !v.chars().all(|c| c.is_ascii_digit() || c == '+') { - return Err("手机号只能包含数字与 + 前缀".to_owned()); - } - Ok(v) -} - -/// 部门名:禁止控制字符。 -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) -} - -/// 用户组:逗号/顿号/分号/空白分隔,去重后返回(顺序保留)。 -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()); - } - } - if out.len() > GROUPS_MAX { - return Err(format!("单个账号最多归属 {GROUPS_MAX} 个用户组")); - } - Ok(out) -} - -// =========================================================================== -// 账号操作(身份语义部分;均走内核 `store::update_users` 持锁读改写) -// =========================================================================== - -/// 创建账号(含身份字段)。上游 `users::create` 只管共性字段, -/// 身份字段在这里一并落 `extra`,创建过程在**同一次**文件锁内完成。 -pub fn create( - username: &str, - display_name: &str, - password: &str, - role: &str, - email: &str, - mobile: &str, - department: &str, - groups: &str, -) -> Result { - let username = util::trim(username).to_owned(); - if !valid_username(&username) { - return Err(format!( - "账号名只能是 {}-{} 位字母、数字、下划线或短横线", - config::USERNAME_MIN_LEN, - config::USERNAME_MAX_LEN - )); - } - let display_name = check_display_name(&display_name)?; - check_password(password)?; - let email = check_email(email)?; - let mobile = check_mobile(mobile)?; - let department = check_department(department)?; - let groups = check_groups(groups)?; - let role = if role == "admin" { "admin" } else { "user" }.to_owned(); - - // 口令哈希等重计算放在锁外 - let salt = util::gen_salt(); - let mut user = User { - username: username.clone(), - display_name, - role, - pwd_hash: util::hash_password(password, &salt), - salt, - api_key: util::gen_key(), - allowed_models: Vec::new(), - llm_rpm: config::LLM_RPM_DEFAULT, - llm_daily: config::LLM_DAILY_DEFAULT, - temp_grant_until: 0, - created_at: util::now(), - extra: BTreeMap::new(), - }; - user.set_email(&email); - user.set_mobile(&mobile); - user.set_department(&department); - user.set_groups(groups); - - let created = user.clone(); - store::update_users(move |users| { - if users.contains_key(&username) { - return Err(format!("账号 {username} 已存在")); - } - users.insert(username.clone(), user); - Ok(()) - })?; - - // 新账号的 API Key 写穿共享内存(与上游 seed_admin 同理) - users::sync_shm(&created); - Ok(created) -} - -/// 设置身份档案(email/department/groups + 可选展示名)。 -pub fn set_profile( - username: &str, - email: &str, - mobile: &str, - department: &str, - groups_raw: &str, - display_name: Option<&str>, -) -> Result { - let email = check_email(email)?; - let mobile = check_mobile(mobile)?; - 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.set_email(&email); - user.set_mobile(&mobile); - user.set_department(&department); - user.set_groups(groups); - if let Some(d) = display_name { - user.display_name = d; - } - Ok(user.clone()) - }) -} - -/// 批量维护账号:加/减组、部门、角色、解锁五个动作一次锁内完成。 -/// 返回 `(成功数, 跳过原因列表)`。 -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.is_admin()).unwrap_or(false)) - .collect(); - if !demoting.is_empty() { - let admins = users.values().filter(|u| u.is_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.set_department(d); - } - if let Some(r) = role.as_deref() { - user.role = r.to_owned(); - } - let mut gs = user.groups(); - for g in &add { - if !gs.iter().any(|x| x == g) { - gs.push(g.clone()); - } - } - gs.retain(|g| !remove.iter().any(|x| x == g)); - user.set_groups(gs); - if unlock { - user.set_failed_count(0); - user.set_locked_until(0); - } - changed += 1; - } - Ok((changed, skipped)) - }) -} - -/// 设置角色(admin / user)。红线:不允许把最后一个管理员降级。 -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.is_admin()).count(); - if admins <= 1 { - return Err("至少需要保留一个管理员账号".to_owned()); - } - } - let user = users.get_mut(username).ok_or("账号不存在")?; - user.role = role; - Ok(user.clone()) - }) -} - -/// 记录一次登录失败(账号维度,对齐 MaxKey 策略)。 -/// 返回 `(失败次数, locked_until)`:达到阈值即锁定 `ACCOUNT_LOCK_TTL` 秒并重新计窗。 -pub fn record_login_failure(username: &str, now: i64) -> Result<(i64, i64), String> { - 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())); - } - let count = user.failed_count() + 1; - if count >= ACCOUNT_LOCK_THRESHOLD { - user.set_locked_until(now + ACCOUNT_LOCK_TTL); - user.set_failed_count(0); - } else { - user.set_failed_count(count); - } - 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.set_failed_count(0); - user.set_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.set_failed_count(0); - user.set_locked_until(0); - Ok(user.clone()) - }) -} - -// =========================================================================== -// 管理台视图 -// =========================================================================== - -/// 管理台账号视图:内核共性字段 + 身份字段(从 extra 读出)。 -/// 插件字段原样透出(`HIDDEN_EXTRA_KEYS` 黑名单除外)。 -pub fn view(user: &User) -> Value { - let mut v = json!({ - "username": user.username, - "display_name": user.display_name, - "name": user.display_or_username(), - "role": user.role, - "is_admin": user.is_admin(), - "email": user.email(), - "mobile": user.mobile(), - "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), - "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 { - if HIDDEN_EXTRA_KEYS.contains(&k.as_str()) { - continue; - } - // 身份字段已按强类型透出,不重复塞第二份 - if matches!(k.as_str(), EXTRA_EMAIL | EXTRA_MOBILE | EXTRA_DEPARTMENT | EXTRA_GROUPS | EXTRA_FAILED_COUNT | EXTRA_LOCKED_UNTIL) { - continue; - } - obj.insert(k.clone(), val.clone()); - } - } - v -} diff --git a/rust/crates/plugin-sso/src/api.rs b/rust/crates/plugin-sso/src/api.rs deleted file mode 100644 index 1e8b729..0000000 --- a/rust/crates/plugin-sso/src/api.rs +++ /dev/null @@ -1,1070 +0,0 @@ -//! API 统一分发器。 -//! -//! 三类调用方、三套鉴权: -//! -//! ```text -//! /oauth/* 公开:OAuth2 / OIDC 端点(授权服务器自身) -//! /api/v1/* 账号态:请求头 X-API-Key(账号级机器凭据) -//! /api/admin/* 管理员态:登录会话 Cookie(除 login 外均需 role=admin) -//! ``` -//! -//! 写操作完成后由各模块自行同步共享内存(如 `oauth_clients::upsert` 写 `ocl:`), -//! 做到「登记完立刻可授权」——本项目**没有**回源读文件这条兜底路径, -//! 所以写穿不是优化而是正确性要求。 - -use ngx::core::Status; -use ngx::ffi::ngx_http_request_t; -use ngx::http::HTTPStatus; -use serde_json::{Value, json}; - -use crate::audit; -use crate::captcha; -use ipass_core::config; -use ipass_core::http; -use crate::accounts::{self, UserExt}; -use ipass_core::models::User; -use crate::oauth; -use crate::oauth_clients; -use ipass_core::session; -use ipass_core::state; -use ipass_core::users; -use ipass_core::util; - -// =========================================================================== -// 路由 -// =========================================================================== - -/// 鉴权后传给处理器的身份 -pub enum Actor { - /// 公开接口,无身份 - None, - /// 账号态(X-API-Key) - User(User), - /// 管理员态(登录会话) - Admin(User), -} - -impl Actor { - /// 操作者名称:审计日志用 - pub(crate) fn admin_name(&self) -> &str { - match self { - Actor::Admin(u) => &u.username, - Actor::User(u) => &u.username, - Actor::None => "", - } - } -} - -#[derive(Clone, Copy, PartialEq)] -pub(crate) enum Guard { - Public, - User, - Admin, -} - -pub(crate) type Handler = fn(*mut ngx_http_request_t, Actor) -> Status; - -/// 路由表。刻意用精确匹配而非正则——接口路径是固定的, -/// 正则只会引入「写错锚点导致前缀误匹配」的风险。 -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/password") => (Guard::Admin, h_admin_user_password), - ("POST", "/api/admin/users/display") => (Guard::Admin, h_admin_user_display), - ("POST", "/api/admin/users/profile") => (Guard::Admin, h_admin_user_profile), - ("POST", "/api/admin/users/role") => (Guard::Admin, h_admin_user_role), - ("POST", "/api/admin/users/unlock") => (Guard::Admin, h_admin_user_unlock), - ("POST", "/api/admin/users/batch") => (Guard::Admin, h_admin_user_batch), - ("POST", "/api/admin/users/totp/setup") => (Guard::Admin, h_admin_user_totp_setup), - ("POST", "/api/admin/users/totp/enable") => (Guard::Admin, h_admin_user_totp_enable), - ("POST", "/api/admin/users/totp/disable") => (Guard::Admin, h_admin_user_totp_disable), - ("POST", "/api/admin/users/delete") => (Guard::Admin, h_admin_user_delete), - - // ---- 管理台:在线会话 / 审计 ------------------------------------ - ("GET", "/api/admin/sessions") => (Guard::Admin, h_admin_sessions), - ("POST", "/api/admin/sessions/kick") => (Guard::Admin, h_admin_session_kick), - ("GET", "/api/admin/audit") => (Guard::Admin, h_admin_audit), - - // ---- 公开:图形验证码(OAUTH_CAPTCHA 开启后登录页使用)---------- - ("GET", "/api/captcha") => (Guard::Public, h_captcha), - - // ---- 管理台:统一认证接入方(OAuth 客户端)---------------------- - ("GET", "/api/admin/oauth-clients") => (Guard::Admin, h_admin_oauth_clients), - ("POST", "/api/admin/oauth-clients/save") => (Guard::Admin, h_admin_oauth_client_save), - ("POST", "/api/admin/oauth-clients/rotate") => (Guard::Admin, h_admin_oauth_client_rotate), - ("POST", "/api/admin/oauth-clients/delete") => (Guard::Admin, h_admin_oauth_client_delete), - - // ---- 账号态 API ------------------------------------------------- - ("GET", "/api/v1/me") => (Guard::User, h_me), - - // ---- OAuth2 / OIDC(公开端点)---------------------------------- - ("GET", "/oauth/authorize") => (Guard::Public, h_oauth_authorize), - ("POST", "/oauth/token") => (Guard::Public, h_oauth_token), - ("GET", "/oauth/userinfo") => (Guard::Public, h_oauth_userinfo), - ("POST", "/oauth/userinfo") => (Guard::Public, h_oauth_userinfo), - ("POST", "/oauth/introspect") => (Guard::Public, h_oauth_introspect), - ("GET", "/.well-known/openid-configuration") => (Guard::Public, h_oauth_discovery), - ("GET", "/.well-known/jwks.json") => (Guard::Public, h_oauth_jwks), - ("GET", "/oauth/jwks") => (Guard::Public, h_oauth_jwks), - ("GET", "/login") => (Guard::Public, h_oauth_login_get), - ("POST", "/login") => (Guard::Public, h_oauth_login_post), - ("POST", "/oauth/logout") => (Guard::Public, h_oauth_logout), - ("GET", "/oauth/logout") => (Guard::Public, h_oauth_logout), - - // ---- MaxKey OAuth2 互通别名 ------------------------------------ - // MaxKey 各族版本的端点命名彼此不同,第三方应用常直接照抄文档里的 - // URL。这里把常见命名都映射到同一套实现,客户端不改一行代码即可切换。 - // /oauth/v20/* MaxKey 2.x/3.x 主线(authorize/token/me) - // /oauth2.0/* 部分部署与 MaxKey 衍生文档使用 - // 注:`me` 走 MaxKey 扁平响应,`profile` 与标准 userinfo 同形。 - ("GET", "/oauth/v20/authorize") => (Guard::Public, h_oauth_authorize), - ("GET", "/oauth/v20/token") => (Guard::Public, h_oauth_token_v20), - ("POST", "/oauth/v20/token") => (Guard::Public, h_oauth_token_v20), - ("GET", "/oauth/v20/me") => (Guard::Public, h_oauth_me_v20), - ("POST", "/oauth/v20/me") => (Guard::Public, h_oauth_me_v20), - // MaxKey 真实 userinfo 路径挂在 /sign/api 下(不是 /sign/authz): - // `/sign/api/oauth/v20/me` 经归一化剥掉 `/sign` 后落到这里。 - // JNPF yml 的 userInfoUrl 与照抄 MaxKey 文档的客户端默认推导都是该路径。 - ("GET", "/api/oauth/v20/me") => (Guard::Public, h_oauth_me_v20), - ("POST", "/api/oauth/v20/me") => (Guard::Public, h_oauth_me_v20), - ("GET", "/oauth/v20/logout") => (Guard::Public, h_oauth_logout), - // 单点注销的裸路径:`/sign/logout`、`/maxkey/logout` 经归一化剥前缀后落到这里。 - ("GET", "/logout") => (Guard::Public, h_oauth_logout), - ("POST", "/logout") => (Guard::Public, h_oauth_logout), - ("GET", "/oauth2.0/authorize") => (Guard::Public, h_oauth_authorize), - ("GET", "/oauth2.0/accessToken") => (Guard::Public, h_oauth_token_v20), - ("POST", "/oauth2.0/accessToken") => (Guard::Public, h_oauth_token_v20), - ("GET", "/oauth2.0/profile") => (Guard::Public, h_oauth_me_v20), - ("POST", "/oauth2.0/profile") => (Guard::Public, h_oauth_me_v20), - - // ---- SCIM 2.0 身份供给(路径含 {id} 变量,走前缀匹配)---------- - // ---- CAS 1.0/2.0 协议端点(精确 GET,走独立路由)---------------- - // ---- 自助密码重置(公开端点,精确 POST)------------------------ - // ---- 终端用户门户「我的应用」(GET /apps,会话态)--------------- - _ => { - if let Some(e) = crate::scim::route(method, uri) { - return Some(e); - } - if let Some(e) = crate::cas::route(method, uri) { - return Some(e); - } - if let Some(e) = crate::reset::route(method, uri) { - return Some(e); - } - if let Some(e) = crate::sync::route(method, uri) { - return Some(e); - } - if let Some(e) = crate::portal::route(method, uri) { - return Some(e); - } - return None; - } - }; - Some(entry) -} - -/// MaxKey 各版本把 OAuth 端点挂在不同的 context-path 下。 -/// -/// 第三方应用的配置项往往就是照抄文档里的完整 URL(`/maxkey/oauth/v20/token` -/// 或 `/sign/authz/oauth/v20/authorize`),把 context-path 一起写进了端点地址。 -/// 精确路由 miss 时剥掉一层已知前缀再试,省得为改一个前缀去给每个应用打补丁。 -/// -/// 只在 miss 之后调用,所以不会遮蔽真实存在的 `/api/v1/*`、`/api/admin/*`。 -const MAXKEY_CONTEXT_PREFIXES: [&str; 5] = ["/maxkey", "/sign/authz", "/sign", "/authz", "/api"]; - -/// 剥掉一层已知的 MaxKey context-path(返回 None 表示没有可剥的前缀)。 -fn strip_maxkey_ctx(uri: &str) -> Option<&str> { - for p in MAXKEY_CONTEXT_PREFIXES { - if let Some(rest) = uri.strip_prefix(p) { - if rest.starts_with('/') { - return Some(rest); - } - } - } - None -} - -// =========================================================================== -// OAuth2 / OIDC 端点(公开,直接转交 oauth 模块,忽略 Actor) -// =========================================================================== - -fn h_oauth_authorize(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::authorize(r) -} -fn h_oauth_token(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::token(r) -} -fn h_oauth_token_v20(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::token_v20(r) -} -fn h_oauth_userinfo(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::userinfo(r) -} -fn h_oauth_me_v20(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::userinfo_v20(r) -} -fn h_oauth_introspect(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::introspect(r) -} -fn h_oauth_discovery(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::discovery(r) -} -fn h_oauth_jwks(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::jwks(r) -} -fn h_oauth_login_get(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::login_get(r) -} -fn h_oauth_login_post(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::login_post(r) -} -fn h_oauth_logout(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - oauth::logout(r) -} - -/// 该请求是否命中本插件的路由表。 -/// -/// 装配层靠它判断「这个管理接口归不归 SSO 管」——返回 false 就继续问下一个 -/// 插件。刻意不对外暴露 `Guard` / `Handler` 这些内部类型。 -pub fn matches(method: &str, uri: &str) -> bool { - if route(method, uri).is_some() { - return true; - } - match strip_maxkey_ctx(uri) { - Some(u) => route(method, &u).is_some(), - None => false, - } -} - -/// 一次请求的完整处理:路由 → 鉴权 → 执行 -pub fn dispatch(r: *mut ngx_http_request_t) -> Status { - let method = http::method_str(r); - let uri = http::uri(r); - - // 精确路由;miss 时按 MaxKey context-path 归一化再试一次(见 strip_maxkey_ctx) - let routed = route(&method, &uri).or_else(|| { - let stripped = strip_maxkey_ctx(&uri)?; - let hit = route(&method, stripped); - if hit.is_some() { - util::log_warn(&format!("[api] MaxKey context-path 归一化 {uri} -> {stripped}")); - } - hit - }); - - let Some((guard, handler)) = routed else { - return http::fail( - r, - HTTPStatus::NOT_FOUND, - &format!("接口不存在:{method} {uri}"), - ); - }; - - let actor = match guard { - Guard::Public => Actor::None, - - Guard::User => { - let key = http::header(r, "x-api-key").unwrap_or_default(); - match users::find_by_key(&key) { - Some(u) => Actor::User(u), - None => { - util::log_warn(&format!( - "[api] API Key 校验失败 client={}", - http::remote_addr(r) - )); - return http::fail( - r, - HTTPStatus::UNAUTHORIZED, - "API Key 无效或缺失,请在请求头携带 X-API-Key", - ); - } - } - } - - Guard::Admin => { - let cookie = http::header(r, "cookie"); - match session::authenticate(cookie.as_deref()).and_then(|name| users::get(&name)) { - Some(u) if u.is_admin() => Actor::Admin(u), - // 会话有效但非管理员:403 而不是 401,便于前端区分 - Some(_) => return http::fail(r, HTTPStatus::FORBIDDEN, "需要管理员权限"), - None => { - return http::fail( - r, - HTTPStatus::UNAUTHORIZED, - "未登录或会话已过期,请重新登录", - ); - } - } - } - }; - - handler(r, actor) -} - -// =========================================================================== -// 管理员:登录 / 会话 -// =========================================================================== - -fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - let now = util::now(); - // 管理台登录审计共用:成败与失败原因都留痕 - macro_rules! audit_login { - ($actor:expr, $ok:expr, $detail:expr) => { - audit::log("admin.login", $actor, $actor, $ok, &ip, &ua, $detail); - }; - } - - 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, "请输入账号和密码"); - } - - // 图形验证码(OAUTH_CAPTCHA=1 时强制):一次性消费,失败需重新取码 - if captcha::enabled() { - let cid = p.get("captcha_id").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let code = p.get("captcha_code").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - if !captcha::verify(&cid, &code) { - audit::log("admin.login", &username, &username, false, &ip, &ua, "验证码错误"); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "验证码不正确或已过期,请刷新后重试"); - } - } - - let mut user = users::get(&username); - let local_ok = match &user { - Some(u) => util::verify_password(&password, &u.salt, &u.pwd_hash), - None => false, - }; - - // 本地口令失败时,若启用 LDAP 认证源则尝试目录绑定(口令不落本网关) - let mut ldap_ok = false; - if !local_ok && crate::ldap::should_try() { - if crate::ldap::authenticate(&username, &password) { - ldap_ok = true; - // LDAP 认证成功但本地无账号:按需自动建账号 - if user.is_none() { - if crate::ldap::auto_create() { - match accounts::create(&username, "", &util::gen_key(), "user", "", "", "", "") { - Ok(u) => user = Some(u), - Err(e) => { - audit_login!(&username, false, &format!("LDAP 自动建账号失败:{e}")); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); - } - } - } else { - audit_login!(&username, false, "LDAP 认证成功但本地无账号且不自动建"); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); - } - } - // LDAP 认证成功:清空本地失败计数(避免本地误累计) - state::clear_login_fail(&ip); - let _ = accounts::clear_login_failure(&username); - } - } - - let authenticated = local_ok || ldap_ok; - - let Some(user) = user else { - state::bump_login_fail(&ip, now); - util::log_warn(&format!("[api] 登录失败 user={username} client={ip}")); - audit_login!(&username, false, "账号不存在"); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); - }; - - // 账号维度锁定(与 IP 维度限速叠加):锁定期内密码正确也拒绝, - // 避免攻击者换 IP 继续爆破同一账号。 - if user.is_locked(now) { - let remain = user.locked_until() - now; - util::log_warn(&format!("[api] 账号锁定中 user={username} client={ip} remain={remain}s")); - audit_login!(&username, false, "账号锁定中"); - return http::fail( - r, - HTTPStatus(423), - &format!("账号已锁定,请 {remain} 秒后重试或联系管理员解锁"), - ); - } - - if !authenticated { - state::bump_login_fail(&ip, now); - // 账号维度累计:达到阈值即锁定(用户必然存在,失败只可能是锁不可用) - let mut detail = "密码错误".to_owned(); - if let Ok((cnt, until)) = accounts::record_login_failure(&username, now) { - if until > now { - detail = format!("密码错误,已触发锁定至 {until}"); - } else { - detail = format!("密码错误,连续第 {cnt} 次"); - } - util::log_warn(&format!( - "[api] 登录失败 user={username} client={ip} count={cnt} locked_until={until}" - )); - } - audit_login!(&username, false, &detail); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); - } - - if !user.is_admin() { - audit_login!(&username, false, "非管理员"); - return http::fail(r, HTTPStatus::FORBIDDEN, "该账号不是管理员,无法登录管理台"); - } - - // TOTP 第二因子:启用后必须携带有效动态码(放在密码校验之后, - // 避免给爆破者「先过密码再猜码」之外的双重门槛信息) - if crate::otp::is_enabled(&user) { - let code = p.get("totp").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - if !crate::otp::verify(&crate::otp::secret(&user), &code, now as u64) { - audit_login!(&username, false, "动态验证码错误"); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "动态验证码不正确或已过期"); - } - } - - state::clear_login_fail(&ip); - let _ = accounts::clear_login_failure(&username); - let token = session::create(&username); - let cookie = session::set_cookie(&token); - util::log_notice(&format!("[api] 管理员登录 user={username} client={ip}")); - audit_login!(&username, true, ""); - - http::ok_with(r, accounts::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(); - audit::log("admin.logout", actor.admin_name(), actor.admin_name(), true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - 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, accounts::view(&user), "ok") -} - -// =========================================================================== -// 管理员:在线会话管理(对齐 MaxKey SessionController:查看 / 踢出) -// =========================================================================== - -/// 列出两类在线会话:管理台(sess:)与 SSO 终端用户(sso:)。 -/// -/// token 原样返回:踢出接口需要精确匹配完整 token,脱敏值无法反查。 -/// 该接口仅管理员可达,与账号管理接口同一信任边界。 -fn h_admin_sessions(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let now = util::now(); - let mut items: Vec = Vec::new(); - - for (tok, username, exp) in state::iter_prefix_ex(config::KEY_SESS_PREFIX) { - if exp <= now { - continue; - } - items.push(json!({ - "type": "admin", - "token": tok, - "username": username, - "expires_at": exp, - "expires_at_text": util::fmt_time(exp), - })); - } - for (tok, payload, exp) in state::iter_prefix_ex(crate::oauth_keys::KEY_OAUTH_SESS_PREFIX) { - if exp <= now { - continue; - } - // sso: payload 首行是 username(见 oauth::sso_payload) - let username = payload.split('\n').next().unwrap_or("").to_owned(); - items.push(json!({ - "type": "sso", - "token": tok, - "username": username, - "expires_at": exp, - "expires_at_text": util::fmt_time(exp), - })); - } - items.sort_by(|a, b| { - let ka = (a["type"].as_str().unwrap_or(""), a["username"].as_str().unwrap_or("")); - let kb = (b["type"].as_str().unwrap_or(""), b["username"].as_str().unwrap_or("")); - ka.cmp(&kb) - }); - - let admin_n = items.iter().filter(|v| v["type"] == "admin").count(); - let sso_n = items.iter().filter(|v| v["type"] == "sso").count(); - http::ok(r, json!({ "items": items, "admin_count": admin_n, "sso_count": sso_n }), "ok") -} - -/// 踢出会话。三种目标(优先级从高到低): -/// -/// 1. `token` —— 精确踢掉一个会话(两类存储都试); -/// 2. `username` —— 踢掉该用户的全部会话(管理台 + SSO); -/// 3. `all=1` —— 清空全部在线会话,**但保留操作者自己的管理台登录** -/// (否则点一下「全部下线」自己就被锁在门外)。 -fn h_admin_session_kick(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let p = http::params(r); - let token = p.get("token").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let all = util::to_bool(p.get("all")); - - let operator = actor.admin_name().to_owned(); - let own_admin_token = http::header(r, "cookie").as_deref().and_then(session::parse_token); - - let mut kicked = 0usize; - if !token.is_empty() { - if state::remove_session(&token) { - kicked += 1; - } - if crate::oauth_state::remove_oauth_session(&token) { - kicked += 1; - } - } else if !username.is_empty() { - for (tok, name, _) in state::iter_prefix_ex(config::KEY_SESS_PREFIX) { - if name == username && state::remove_session(&tok) { - kicked += 1; - } - } - for (tok, payload, _) in state::iter_prefix_ex(crate::oauth_keys::KEY_OAUTH_SESS_PREFIX) { - let name = payload.split('\n').next().unwrap_or(""); - if name == username && crate::oauth_state::remove_oauth_session(&tok) { - kicked += 1; - } - } - } else if all { - let now = util::now(); - for (tok, _, exp) in state::iter_prefix_ex(config::KEY_SESS_PREFIX) { - // 保留操作者自己的会话与未过期条目之外的脏数据一并清掉 - if exp <= now || Some(&tok) == own_admin_token.as_ref() { - continue; - } - if state::remove_session(&tok) { - kicked += 1; - } - } - for (tok, _, exp) in state::iter_prefix_ex(crate::oauth_keys::KEY_OAUTH_SESS_PREFIX) { - if exp <= now { - continue; - } - if crate::oauth_state::remove_oauth_session(&tok) { - kicked += 1; - } - } - } else { - return http::fail(r, HTTPStatus::BAD_REQUEST, "请指定 token、username 或 all=1"); - } - - util::log_notice(&format!( - "[api] 踢出会话 operator={operator} token={} username={username} all={all} kicked={kicked}", - !token.is_empty() - )); - audit::log("admin.session.kick", &operator, if !username.is_empty() { &username } else { "*" }, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), &format!("kicked={kicked}")); - http::ok(r, json!({ "kicked": kicked }), "已踢出指定会话") -} - -/// 审计日志查询:最近事件 + 概要。参数:limit / actor / action。 -fn h_admin_audit(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let limit: usize = p.get("limit").and_then(|s| s.parse().ok()).unwrap_or(audit::READ_LIMIT_DEFAULT); - let actor_f = p.get("actor").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let action_f = p.get("action").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - let items = audit::read(limit, &actor_f, &action_f); - http::ok( - r, - json!({ - "items": items, - "stats": audit::stats(), - "known_actions": audit::KNOWN_ACTIONS, - }), - "ok", - ) -} - -// =========================================================================== -// 管理员:TOTP 双因子绑定 / 启用 / 解绑 -// =========================================================================== - -/// 生成种子(不启用)。返回 Base32 种子 + otpauth:// URI(前端转二维码)。 -fn h_admin_user_totp_setup(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 crate::otp::setup(&username) { - Ok((secret, uri)) => { - audit::log("admin.user.totp.setup", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - // 种子只在此刻返回一次(绑定完成前可重复 setup 重取) - http::ok(r, json!({ "username": username, "secret": secret, "otpauth": uri }), "已生成绑定种子,请扫码后输入动态码启用") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 校验动态码并启用。 -fn h_admin_user_totp_enable(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 code = p.get("code").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - match crate::otp::enable(&username, &code, util::now()) { - Ok(u) => { - audit::log("admin.user.totp.enable", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok(r, accounts::view(&u), "双因子已启用") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 解绑。 -fn h_admin_user_totp_disable(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 crate::otp::disable(&username) { - Ok(u) => { - audit::log("admin.user.totp.disable", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok(r, accounts::view(&u), "双因子已解绑") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 图形验证码取码。未启用时显式报错(而不是静默出码), -/// 便于接入方区分「没开」与「坏了」。 -fn h_captcha(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - if !captcha::enabled() { - return http::fail(r, HTTPStatus::NOT_FOUND, "验证码未启用(OAUTH_CAPTCHA=1 开启)"); - } - match captcha::response() { - Some(v) => http::ok(r, v, "ok"), - None => http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, "验证码生成失败"), - } -} - -// =========================================================================== -// 管理员:账号管理 -// =========================================================================== - -fn h_admin_users(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - // 只读一次 users.json:列表、部门取值、用户组取值都从这一份快照里算。 - let all = users::all(); - - // 部门与组的「已有取值」一并回显:管理台据此给出可选值提示, - // 避免同一个人手输成「研发部 / 研发中心 / RD」三种写法。 - let mut departments: Vec = Vec::new(); - let mut groups: Vec = Vec::new(); - for u in &all { - if !u.department().is_empty() && !departments.iter().any(|d| d == u.department()) { - departments.push(u.department().to_owned()); - } - for g in u.groups() { - if !groups.iter().any(|x| *x == g) { - groups.push(g.clone()); - } - } - } - departments.sort(); - groups.sort(); - - let items: Vec = all.iter().map(accounts::view).collect(); - - http::ok( - r, - json!({ - "items": items, - "departments": departments, - "groups": groups, - }), - "ok", - ) -} - -fn h_admin_user_create(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let p = http::params(r); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - match accounts::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"), - p.get("email").map(String::as_str).unwrap_or(""), - p.get("mobile").map(String::as_str).unwrap_or(""), - p.get("department").map(String::as_str).unwrap_or(""), - p.get("groups").map(String::as_str).unwrap_or(""), - ) { - Ok(user) => { - util::log_notice(&format!( - "[api] 创建账号 {} name={} role={} dept={}", - user.username, user.display_name, user.role, user.department() - )); - audit::log("admin.user.create", actor.admin_name(), &user.username, true, &ip, &ua, &format!("role={}", user.role)); - http::ok(r, accounts::view(&user), "账号创建成功") - } - Err(e) => { - audit::log("admin.user.create", actor.admin_name(), p.get("username").map(String::as_str).unwrap_or(""), false, &ip, &ua, &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, accounts::view(&u), "已更新展示名"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 设置身份声明(邮箱 / 部门 / 用户组)。这三个字段直接进 OIDC claims 与 -/// `X-Auth-*` 注入头,是下游系统授权的依据,因此必须可在线维护。 -fn h_admin_user_profile(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(); - - // display_name 缺省 = 不动(避免「只改部门却把姓名清空」这类误伤) - let display_name = p.get("display_name").map(String::as_str); - - match accounts::set_profile( - &username, - p.get("email").map(String::as_str).unwrap_or(""), - p.get("mobile").map(String::as_str).unwrap_or(""), - p.get("department").map(String::as_str).unwrap_or(""), - p.get("groups").map(String::as_str).unwrap_or(""), - display_name, - ) { - Ok(u) => { - util::log_notice(&format!( - "[api] 更新身份 {username} email={} dept={} groups={:?}", - u.email(), u.department(), u.groups() - )); - audit::log("admin.user.profile", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), &format!("groups={:?}", u.groups())); - http::ok(r, accounts::view(&u), "已更新身份信息") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 设置角色(admin / user)。不允许把最后一个管理员降级。 -fn h_admin_user_role(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 role = p.get("role").map(String::as_str).unwrap_or(""); - - if role != "admin" && role != "user" { - return http::fail(r, HTTPStatus::BAD_REQUEST, "角色只能是 admin 或 user"); - } - match accounts::set_role(&username, role) { - Ok(u) => { - util::log_notice(&format!("[api] 设置角色 {username} -> {}", u.role)); - audit::log("admin.user.role", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), &format!("role={}", u.role)); - http::ok(r, accounts::view(&u), "已更新角色") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 批量维护账号:`usernames` 逗号/换行分隔,其余字段按需组合: -/// `add_groups` / `remove_groups`(逗号分隔)、`department`、`role`、`unlock=1`。 -/// -/// 存在即整体成功的语义是反直觉的(选 20 个人、1 个被删了就全失败), -/// 所以这里按「尽力而为」处理:逐个改,跳过的原因随结果回显。 -fn h_admin_user_batch(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let p = http::params(r); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - let split_list = |raw: &str| -> Vec { - raw.split(|c: char| c == ',' || c == '\n' || c == ';' || c == '\t') - .map(util::trim) - .filter(|s| !s.is_empty()) - .map(|s| s.to_owned()) - .collect() - }; - let usernames = split_list(p.get("usernames").map(String::as_str).unwrap_or("")); - let add_groups = split_list(p.get("add_groups").map(String::as_str).unwrap_or("")); - let remove_groups = split_list(p.get("remove_groups").map(String::as_str).unwrap_or("")); - let department = p.get("department").map(String::as_str); - let role = p.get("role").map(String::as_str); - let unlock = matches!(p.get("unlock").map(String::as_str).unwrap_or(""), "1" | "true" | "on"); - - match accounts::batch_update(&usernames, &add_groups, &remove_groups, department, role, unlock) { - Ok((changed, skipped)) => { - let detail = format!( - "changed={changed} +g={:?} -g={:?} dept={:?} role={:?} unlock={unlock}", - add_groups, remove_groups, department, role - ); - util::log_notice(&format!("[api] 批量维护账号 {changed} 个:{detail}")); - audit::log( - "admin.user.batch", - actor.admin_name(), - &usernames.join(","), - true, - &ip, - &ua, - &detail, - ); - http::ok( - r, - json!({ "changed": changed, "skipped": skipped }), - &format!("已更新 {changed} 个账号"), - ) - } - Err(e) => { - audit::log( - "admin.user.batch", - actor.admin_name(), - &usernames.join(","), - false, - &ip, - &ua, - &e, - ); - http::fail(r, HTTPStatus::BAD_REQUEST, &e) - } - } -} - -/// 管理员手动解锁账号(清零失败计数与锁定截止时间)。 -fn h_admin_user_unlock(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 accounts::unlock(&username) { - Ok(_) => { - util::log_notice(&format!("[api] 手动解锁账号 {username}")); - audit::log("admin.user.unlock", _actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok(r, json!({ "username": username }), "账号已解锁") - } - 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) => { - audit::log("admin.user.key", _actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok(r, json!({ "username": username, "api_key": key }), "已重置 API Key") - } - 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(""); - - // 密码策略统一在插件层入口把关:内核 set_password 只管共性(最小 6 位), - // 这里用本插件的收紧策略(8 位 + 无控制字符),管理员重置也不例外—— - // 否则「管理员图省事重置成 123」绕过策略,账户锁定防线形同虚设。 - if let Err(e) = accounts::check_password(password) { - return http::fail(r, HTTPStatus::BAD_REQUEST, &e); - } - - match users::set_password(&username, password) { - Ok(()) => { - audit::log("admin.user.password", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - 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(); - - match users::delete(&username, actor.admin_name()) { - Ok(()) => { - util::log_notice(&format!("[api] 删除账号 {username}")); - audit::log("admin.user.delete", actor.admin_name(), &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok(r, json!({ "username": username }), "账号已删除") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -// =========================================================================== -// 管理员:统一认证接入方(OAuth 客户端)管理 -// -// 对应 MaxKey 的「应用管理」:第三方应用在这里登记 client_id/密钥/回调地址, -// 之后按标准 OAuth2 / OIDC 流程对接,无需感知本网关的用户存储。 -// -// 三条不变量: -// 1. 列表读注册表**真源**(store::read_oauth_clients),不是共享内存快照—— -// 管理台显示的必须就是「重启后还在」的那份; -// 2. 保存/删除由 oauth_clients 内部写穿共享内存,做到「登记完立刻能授权」, -// 不需要重启 nginx; -// 3. 密钥只在创建时/显式重置时返回明文,列表里给的是脱敏值。 -// =========================================================================== - -/// 拆分管理台传入的列表字段(回调地址 / 授权类型 / scope)。 -/// -/// 回调地址常写成 textarea 里一行一个,scope 常写成 `openid profile`, -/// 所以逗号、顿号、分号、空白、换行全都认。 -fn parse_list(raw: &str) -> Vec { - raw.split(|c: char| { - c == ',' || c == '、' || c == ';' || c == '\n' || c == '\r' || c == '\t' || c == ' ' - }) - .map(|s| util::trim(s).to_owned()) - .filter(|s| !s.is_empty()) - .collect() -} - -fn h_admin_oauth_clients(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let items: Vec = oauth_clients::all().iter().map(oauth_clients::view).collect(); - let iss = oauth::issuer(); - http::ok( - r, - json!({ - "items": items, - "issuer": iss, - // 给接入方抄的端点清单:标准一组 + MaxKey 一组(照抄 MaxKey 文档 - // 配好的应用可以原样切换过来,见 docs/design.md §15) - "endpoints": { - "discovery": format!("{iss}/.well-known/openid-configuration"), - "authorize": format!("{iss}/oauth/authorize"), - "token": format!("{iss}/oauth/token"), - "userinfo": format!("{iss}/oauth/userinfo"), - "introspect": format!("{iss}/oauth/introspect"), - "logout": format!("{iss}/oauth/logout"), - "authorize_v20": format!("{iss}/oauth/v20/authorize"), - "token_v20": format!("{iss}/oauth/v20/token"), - "profile_v20": format!("{iss}/oauth/v20/me"), - // CAS 协议(protocol=cas 的应用用这一组) - "cas_login": format!("{iss}/cas/login"), - "cas_validate": format!("{iss}/cas/validate"), - "cas_service_validate": format!("{iss}/cas/serviceValidate"), - "cas_logout": format!("{iss}/cas/logout"), - // 终端用户门户(登录后可访问的应用) - "portal": format!("{iss}/apps"), - }, - }), - "ok", - ) -} - -fn h_admin_oauth_client_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let client_id = p - .get("client_id") - .map(|s| util::trim(s).to_owned()) - .unwrap_or_default(); - let confidential = util::to_bool(p.get("confidential")); - // 先记录「此前是否存在」:管理台据此决定要不要弹「请立即复制密钥」 - let existed = oauth_clients::all().iter().any(|c| c.client_id == client_id); - - // 应用元数据(协议 / 门户展示 / 可见范围)。与凭证字段分开传,避免 upsert 参数爆炸。 - let meta = oauth_clients::AppMeta { - protocol: p.get("protocol").map(String::as_str).unwrap_or("").to_owned(), - description: p.get("description").map(String::as_str).unwrap_or("").to_owned(), - logo_url: p.get("logo_url").map(String::as_str).unwrap_or("").to_owned(), - home_url: p.get("home_url").map(String::as_str).unwrap_or("").to_owned(), - visible_roles: parse_list(p.get("visible_roles").map(String::as_str).unwrap_or("")), - visible_depts: parse_list(p.get("visible_depts").map(String::as_str).unwrap_or("")), - visible_groups: parse_list(p.get("visible_groups").map(String::as_str).unwrap_or("")), - }; - - match oauth_clients::upsert( - &client_id, - p.get("name").map(String::as_str).unwrap_or(""), - parse_list(p.get("redirect_uris").map(String::as_str).unwrap_or("")), - parse_list(p.get("grant_types").map(String::as_str).unwrap_or("")), - parse_list(p.get("scopes").map(String::as_str).unwrap_or("")), - confidential, - p.get("client_secret").map(String::as_str).unwrap_or(""), - meta, - ) { - Ok(c) => { - util::log_notice(&format!( - "[api] 保存 OAuth 客户端 {}({},回调 {} 个,授权类型 {} 种)", - c.client_id, - if c.confidential { "机密" } else { "公开" }, - c.redirect_uris.len(), - c.grant_types.len() - )); - audit::log("admin.client.save", _actor.admin_name(), &c.client_id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), &format!("existed={existed}")); - let mut v = oauth_clients::view(&c); - if let Value::Object(ref mut m) = v { - m.insert("existed".to_owned(), json!(existed)); - } - http::ok(r, v, if existed { "已更新" } else { "已创建" }) - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 重置客户端密钥(应急:怀疑密钥泄漏时)。旧密钥立即失效。 -fn h_admin_oauth_client_rotate(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let client_id = p - .get("client_id") - .map(|s| util::trim(s).to_owned()) - .unwrap_or_default(); - match oauth_clients::rotate_secret(&client_id) { - Ok(secret) => { - util::log_notice(&format!("[api] 重置 OAuth 客户端密钥 {client_id}")); - audit::log("admin.client.rotate", _actor.admin_name(), &client_id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok( - r, - json!({ "client_id": client_id, "client_secret": secret }), - "密钥已重置,请立即更新接入方配置", - ) - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_oauth_client_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let client_id = p - .get("client_id") - .map(|s| util::trim(s).to_owned()) - .unwrap_or_default(); - match oauth_clients::delete(&client_id) { - Ok(()) => { - util::log_notice(&format!("[api] 删除 OAuth 客户端 {client_id}")); - audit::log("admin.client.delete", _actor.admin_name(), &client_id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - http::ok(r, json!({ "client_id": client_id }), "已删除") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -// =========================================================================== -// 账号态 API -// =========================================================================== - -/// 账号态:看看自己的身份声明。 -/// -/// 刻意**不回显 OAuth 客户端侧的任何密钥**——账号与接入方是两条独立的信任线。 -fn h_me(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let Actor::User(user) = actor else { - return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或缺失,请在请求头携带 X-API-Key"); - }; - - let mut v = accounts::view(&user); - if let Value::Object(ref mut m) = v { - m.insert("sub".to_owned(), json!(user.username)); - m.insert("issuer".to_owned(), json!(oauth::issuer())); - } - http::ok(r, v, "ok") -} diff --git a/rust/crates/plugin-sso/src/audit.rs b/rust/crates/plugin-sso/src/audit.rs deleted file mode 100644 index 2ea8c05..0000000 --- a/rust/crates/plugin-sso/src/audit.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! 审计日志(sso 插件本地模块,原内核同名模块随内核上游化迁入插件):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 ipass_core::store; -use ipass_core::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, - "region": crate::geo::lookup(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 = ipass_core::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/rust/crates/plugin-sso/src/captcha.rs b/rust/crates/plugin-sso/src/captcha.rs deleted file mode 100644 index 668382e..0000000 --- a/rust/crates/plugin-sso/src/captcha.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! SVG 图形验证码(对齐 MaxKey kaptcha 的登录防自动化能力,实现为纯 SVG, -//! 零依赖:不引入图像库,浏览器直接内联渲染)。 -//! -//! ## 生命周期 -//! -//! 1. `GET /api/captcha` → 生成 `id + 5 位码`,码存共享内存 `cap:`(TTL 5 分钟); -//! 2. 登录请求附带 `captcha_id` + `captcha_code`; -//! 3. 校验**一次性**:无论对错,取出即删(对齐 MaxKey 的一次性票据语义), -//! 失败需重新取新码。 -//! -//! ## 开关 -//! -//! 缺省**关闭**(`OAUTH_CAPTCHA=1` 开启)。验证码图形无法被 curl e2e 读取, -//! 缺省开启会让所有存量端到端失效;生产开启后浏览器路径正常出码。 -//! -//! ## 防 OCR 的边界 -//! -//! 纯字符 + 干扰线能挡住低成本的自动重放/批量尝试,挡不住定向 OCR—— -//! 真正的爆破防线是账号锁定(users::record_login_failure),验证码只是减速带。 - -use serde_json::{Value, json}; - -use ipass_core::state; -use ipass_core::util; - -/// 验证码共享内存 TTL(秒)——与模块文档一致:5 分钟(300s)。 -/// -/// 原属 `ipass_core::config`,收窄内核后归本插件自管。 -pub const CAPTCHA_TTL: i64 = 5 * 60; -/// 验证码开关环境变量名:取值 `1/true/on/yes` 开启(`api.rs` 登录校验读取)。 -/// -/// 原属 `ipass_core::config`,收窄内核后归本插件自管。 -pub const OAUTH_CAPTCHA_ENV: &str = "OAUTH_CAPTCHA"; - -/// 键前缀:验证码 id → 码(一次性) -const KEY_CAPTCHA_PREFIX: &[u8] = b"cap:"; - -/// 无歧义字符集:去掉 0/O/1/I/l,降低人眼误识率 -const CHARS: &[u8] = b"abcdefghjkmnpqrstuvwxyz23456789"; -/// 码长 -const CODE_LEN: usize = 5; - -/// 是否启用(环境变量在启动时读取,进程内固定) -pub fn enabled() -> bool { - match std::env::var(OAUTH_CAPTCHA_ENV) { - Ok(v) => matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "on" | "yes"), - Err(_) => false, - } -} - -/// 生成新验证码:返回 `(id, svg)`。码只进共享内存,不进响应体。 -pub fn create() -> Option<(String, String)> { - let now = util::now(); - let mut code = String::with_capacity(CODE_LEN); - for _ in 0..CODE_LEN { - let b = [util::rand_hex(1).as_bytes()[0]]; - code.push(CHARS[(b[0] as usize) % CHARS.len()] as char); - } - let id = util::rand_hex(16); - if !state::put(KEY_CAPTCHA_PREFIX, id.as_bytes(), code.as_bytes(), now + CAPTCHA_TTL) { - return None; - } - Some((id, render(&code))) -} - -/// 校验并消费:码对返回 true,码错/过期/id 未知一律 false。 -/// **无论结果如何,码都会被删除**(一次性语义,防同码重试)。 -pub fn verify(id: &str, answer: &str) -> bool { - if id.is_empty() || answer.is_empty() { - return false; - } - let expected = state::get(KEY_CAPTCHA_PREFIX, id.as_bytes()).map(|(p, _)| p); - state::remove(KEY_CAPTCHA_PREFIX, id.as_bytes()); - let Some(expected) = expected else { - return false; - }; - // 大小写不敏感:用户输入习惯优先于严格匹配 - util::ct_eq(&expected.to_ascii_lowercase(), &answer.trim().to_ascii_lowercase()) -} - -/// 渲染 SVG:每个字符独立旋转/抖动 + 两条干扰弧线 + 噪点。 -/// 宽 160 高 48,颜色固定深蓝系,与管理台视觉一致。 -fn render(code: &str) -> String { - let (w, h) = (160.0f32, 48.0f32); - let mut body = String::new(); - - // 干扰弧线两条 - for (i, (x1, y1, x2, y2, cx, cy)) in [ - (0.0, 36.0, 160.0, 12.0, 60.0, 60.0), - (0.0, 10.0, 160.0, 40.0, 100.0, -10.0), - ] - .into_iter() - .enumerate() - { - body.push_str(&format!( - "", - 1 + (i % 2) - )); - } - // 噪点 - for i in 0..24 { - let x = (util::sha256_hex(format!("n{i}{code}").as_bytes())[..4] - .chars() - .fold(0usize, |a, c| a * 16 + c.to_digit(16).unwrap_or(0) as usize) - % (w as usize)) as f32; - let y = (util::sha256_hex(format!("m{i}{code}").as_bytes())[..4] - .chars() - .fold(0usize, |a, c| a * 16 + c.to_digit(16).unwrap_or(0) as usize) - % (h as usize)) as f32; - body.push_str(&format!("")); - } - // 字符:等距 + 伪随机旋转/垂直偏移 - let step = (w - 24.0) / CODE_LEN as f32; - for (i, c) in code.chars().enumerate() { - let rot_seed = util::sha256_hex(format!("r{i}{c}").as_bytes()); - let rot = ((rot_seed.as_bytes()[0] % 50) as f32 - 25.0) as i32; // ±25° - let dy = ((rot_seed.as_bytes()[1] % 10) as f32 - 5.0) as i32; // ±5px - let x = 12.0 + step * i as f32 + step / 2.0; - body.push_str(&format!( - "{c}", - 34 + dy - )); - } - - format!( - "{body}" - ) -} - -/// 管理台 / 登录页取码接口的响应体。 -pub fn response() -> Option { - create().map(|(id, svg)| json!({ "id": id, "svg": svg, "ttl": CAPTCHA_TTL })) -} diff --git a/rust/crates/plugin-sso/src/cas.rs b/rust/crates/plugin-sso/src/cas.rs deleted file mode 100644 index ed22b06..0000000 --- a/rust/crates/plugin-sso/src/cas.rs +++ /dev/null @@ -1,202 +0,0 @@ -//! CAS 1.0 / 2.0 协议端点(对齐 MaxKey `maxkey-cas`)。 -//! -//! 让既有的 CAS 客户端(老 Java 应用、Confluence、Jenkins 等)用标准 CAS 协议 -//! 接入本网关做单点登录,无需改写客户端。本实现为**精简版**: -//! -//! * 身份来源复用本网关的 SSO 会话(管理台 session / 终端用户 sso session 都认); -//! * ST(Service Ticket)签发后存共享内存,单次有效、短 TTL; -//! * `/cas/serviceValidate` 走 CAS 2.0 XML,`/cas/validate` 走 CAS 1.0 纯文本, -//! `/cas/proxyValidate` 与 serviceValidate 同形(忽略代理链)。 -//! -//! **`service` 必须命中接入方注册表**(某个应用的 `redirect_uris`),否则一律拒绝: -//! 缺了这道校验,`/cas/login?service=https://evil.com` 会把已登录用户连同 `ST-…` -//! 一起 302 出去,攻击者再拿票据换出用户名——开放重定向 + 票据外泄。 -//! CAS 协议本身也要求服务端登记白名单,这里复用「应用管理」的登记数据,不另设配置。 -//! -//! 鉴权全部 `Guard::Public`:login 自己读会话、validate 靠 ticket,都不依赖调用方会话。 - -use ngx::ffi::ngx_http_request_t; - -use crate::compat as http; -use ipass_core::session; -use ipass_core::state; -use ipass_core::util; -use ngx::core::Status; -use ngx::http::HTTPStatus; - -use crate::audit; - -/// ST 有效期(秒)。CAS 票据本就单次、短时,30s 足够客户端拿到后立刻来校验。 -const CAS_TICKET_TTL: i64 = 30; -/// ST 共享内存键前缀:`cas:st:` -const KEY_CAS_ST: &[u8] = b"cas:st:"; - -/// 路由:CAS 端点路径固定,精确匹配。 -pub fn route(method: &str, uri: &str) -> Option<(crate::api::Guard, crate::api::Handler)> { - if method != "GET" { - return None; - } - let g = crate::api::Guard::Public; - match uri { - "/cas/login" => Some((g, h_cas_login)), - "/cas/logout" => Some((g, h_cas_logout)), - "/cas/validate" => Some((g, h_cas_validate)), - "/cas/serviceValidate" => Some((g, h_cas_service_validate)), - "/cas/proxyValidate" => Some((g, h_cas_proxy_validate)), - _ => None, - } -} - -/// 生成 ST:`ST-`。 -fn new_ticket() -> String { - format!("ST-{}", util::gen_key()) -} - -/// 把 ticket 与服务绑定写入共享内存:payload = `username\nservice`。 -fn issue_ticket(ticket: &str, username: &str, service: &str, now: i64) -> bool { - let payload = format!("{username}\n{service}"); - state::put(KEY_CAS_ST, ticket.as_bytes(), payload.as_bytes(), now + CAS_TICKET_TTL) -} - -/// 消费 ticket:校验存在、未过期、service 匹配,返回用户名(一次性)。 -fn consume_ticket(ticket: &str, service: &str, now: i64) -> Option { - let (payload, exp) = state::get(KEY_CAS_ST, ticket.as_bytes())?; - if exp > 0 && exp <= now { - state::remove(KEY_CAS_ST, ticket.as_bytes()); - return None; - } - let (user, bound) = payload.split_once('\n')?; - if bound != service { - // service 不匹配:票据不可跨服务使用(防 fixation) - return None; - } - // 单次有效:消费即删 - state::remove(KEY_CAS_ST, ticket.as_bytes()); - Some(user.to_owned()) -} - -/// `/cas/login?service=URL`:已登录则签发 ST 并 302 回 service?ticket=ST; -/// 未登录则 302 到本网关登录页。无 service 时直接返回 ST(供程序化握手)。 -fn h_cas_login(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let p = http::params(r); - let service = p.get("service").map(String::as_str).unwrap_or("").to_owned(); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - let Some(user) = crate::oauth::current_user(r) else { - // 未登录:跳登录页(浏览器走完登录后会带着会话回来重放本请求)。 - // 无 service 时无法回跳,直接 401 让调用方先建会话。 - if service.is_empty() { - return http::fail(r, HTTPStatus::UNAUTHORIZED, "未登录或会话已过期,请先登录"); - } - audit::log("cas.login.deny", "", "", false, &ip, &ua, "no session"); - return http::redirect(r, "/login"); - }; - - // service 白名单:必须是登记过回调地址的接入方。放在**签发票据之前**—— - // 先发后查等于已经把一个可换用户名的票据递出去了。 - if !crate::oauth_clients::allows_cas_service(&service) { - util::log_warn(&format!( - "[cas] 拒绝未登记的 service:{service}(user={user} ip={ip})" - )); - audit::log( - "cas.login.deny", - &user, - &user, - false, - &ip, - &ua, - &format!("service not registered: {service}"), - ); - return http::fail( - r, - HTTPStatus::FORBIDDEN, - "service 未在「应用管理」中登记,拒绝签发票据", - ); - } - - let ticket = new_ticket(); - let now = util::now(); - if !issue_ticket(&ticket, &user, &service, now) { - return http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, "票据签发失败"); - } - audit::log("cas.login", &user, &user, true, &ip, &ua, &service); - - if service.is_empty() { - // 程序化握手:直接回 ST(JSON 信封,便于脚本取出) - return http::ok(r, serde_json::json!({ "ticket": ticket, "user": user }), "ok"); - } - // 回跳 service?ticket= / &ticket= - let sep = if service.contains('?') { '&' } else { '?' }; - let location = format!("{service}{sep}ticket={ticket}"); - http::redirect(r, &location) -} - -/// `/cas/logout`:销毁本会话,返回 200。 -fn h_cas_logout(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let cookie = http::header(r, "cookie"); - session::destroy(cookie.as_deref()); - http::ok(r, serde_json::json!({}), "已退出 CAS 单点登录") -} - -/// `/cas/validate`:CAS 1.0 纯文本 `yes\n` / `no\n`。 -fn h_cas_validate(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let p = http::params(r); - let service = p.get("service").map(String::as_str).unwrap_or("").to_owned(); - let ticket = p.get("ticket").map(String::as_str).unwrap_or("").to_owned(); - let now = util::now(); - - // 白名单优先于票据校验:未登记的 service 连「票据是否有效」都不该知道。 - if !crate::oauth_clients::allows_cas_service(&service) { - return http::send_ct(r, HTTPStatus::OK, "no\n", "text/plain; charset=utf-8"); - } - match consume_ticket(&ticket, &service, now) { - Some(user) => http::send_ct(r, HTTPStatus::OK, &format!("yes\n{user}\n"), "text/plain; charset=utf-8"), - None => http::send_ct(r, HTTPStatus::OK, "no\n", "text/plain; charset=utf-8"), - } -} - -/// `/cas/serviceValidate`:CAS 2.0 XML。 -fn h_cas_service_validate(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let p = http::params(r); - let service = p.get("service").map(String::as_str).unwrap_or("").to_owned(); - let ticket = p.get("ticket").map(String::as_str).unwrap_or("").to_owned(); - let now = util::now(); - - // 未登记服务:CAS 2.0 规范里对应 INVALID_SERVICE,且**不复用** INVALID_TICKET - // ——否则运维排障会把「没登记地址」误判成「票据过期」。 - if !crate::oauth_clients::allows_cas_service(&service) { - let body = format!( - "\n\ - \x20 service 未在应用管理中登记\n\ - \n" - ); - return http::send_ct(r, HTTPStatus::OK, &body, "application/xml; charset=utf-8"); - } - - match consume_ticket(&ticket, &service, now) { - Some(user) => { - let body = format!( - "\n\ - \x20 \n\ - \x20\x20 {user}\n\ - \x20 \n\ - \n" - ); - http::send_ct(r, HTTPStatus::OK, &body, "application/xml; charset=utf-8") - } - None => { - let body = format!( - "\n\ - \x20 ticket 无效或已过期\n\ - \n" - ); - http::send_ct(r, HTTPStatus::OK, &body, "application/xml; charset=utf-8") - } - } -} - -/// `/cas/proxyValidate`:与 serviceValidate 同形(本项目不发放 PT,忽略代理链)。 -fn h_cas_proxy_validate(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - h_cas_service_validate(r, _actor) -} diff --git a/rust/crates/plugin-sso/src/compat.rs b/rust/crates/plugin-sso/src/compat.rs deleted file mode 100644 index fdfdb52..0000000 --- a/rust/crates/plugin-sso/src/compat.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! 兼容层:主线内核 `ipass/ipass` 的 `ipass-core` 已移除四个 http 辅助函数 -//! (`body_object` / `json_body` / `send_ct` / `redirect`)。为避免改动子模块, -//! 这里用新内核暴露的底层 API 重新实现,并整体再导出 `ipass_core::http`, -//! 使 `use crate::compat as http;` 能无缝替代 `use ipass_core::http;`。 - -pub use ipass_core::http::*; - -use std::ptr; - -use ngx::core::{Buffer, Status}; -use ngx::ffi::{ngx_chain_t, ngx_http_request_t}; -use ngx::http::{HTTPStatus, Request}; -use serde_json::Value; - -use ipass_core::util; - -/// 读取并解析请求体为 JSON(`Content-Type: application/json` 时)。 -/// -/// 非 JSON 体或解析失败返回 `None`——调用方据此回退到 `params` 或报错。 -pub fn json_body(r: *mut ngx_http_request_t) -> Option { - let body = unsafe { ipass_core::http::collect_body(r) }; - if body.is_empty() { - return None; - } - serde_json::from_slice::(&body).ok() -} - -/// 合并 query 与 JSON 请求体为单一 `Value::Object`: -/// JSON 体的嵌套结构原样保留,query 的标量覆盖同名顶层键。 -pub fn body_object(r: *mut ngx_http_request_t) -> Value { - let mut obj = serde_json::Map::new(); - for (k, v) in util::parse_kv(&ipass_core::http::args_raw(r)) { - obj.insert(k, Value::String(v)); - } - if let Some(Value::Object(b)) = json_body(r) { - for (k, v) in b { - obj.insert(k, v); - } - } - Value::Object(obj) -} - -/// 发送带自定义 Content-Type 的响应体(CAS 的 `text/plain` / `application/xml` -/// 等不走 JSON 信封的场景用)。 -pub fn send_ct( - r: *mut ngx_http_request_t, - status: HTTPStatus, - body: &str, - content_type: &str, -) -> Status { - // SAFETY: r 有效 - unsafe { - let request = Request::from_ngx_http_request(r); - let pool = request.pool(); - - let mut buf = match pool.create_buffer_from_str(body) { - Some(b) => b, - None => return Status::NGX_ERROR, - }; - buf.set_last_buf(true); - - let mut chain = ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: ptr::null_mut() }; - - request.set_status(status); - request.add_header_out("Content-Type", content_type); - request.add_header_out("Cache-Control", "no-store"); - request.set_content_length_n(body.len()); - - let st = request.send_header(); - if st != Status::NGX_OK { - return st; - } - request.output_filter(&mut chain) - } -} - -/// 302 重定向(CAS `/cas/login` 签发 ST 后跳回 service)。 -/// -/// **注意**:body 必须非空——`pool.create_buffer_from_str("")` 在 nginx 内存池里 -/// 分配 0 长度 buffer 会返回 `None`,使 `send_with` 返回 `NGX_ERROR`,导致 302 -/// 根本不发出(curl 拿不到 `Location`)。所以这里给一个单空格占位 body。 -pub fn redirect(r: *mut ngx_http_request_t, location: &str) -> Status { - send_with(r, HTTPStatus::MOVED_TEMPORARILY, " ", &[("Location", location)]) -} diff --git a/rust/crates/plugin-sso/src/geo.rs b/rust/crates/plugin-sso/src/geo.rs deleted file mode 100644 index 98928ab..0000000 --- a/rust/crates/plugin-sso/src/geo.rs +++ /dev/null @@ -1,152 +0,0 @@ -//! 登录 IP 归属地(ip2location 精简版)。 -//! -//! MaxKey 内置登录 IP 归属地(ip2location)。完整 ip2location 需要商业 GeoIP -//! 数据库文件(数 MB ~ 数十 MB),与本项目「零外部依赖 / 单容器」约束冲突, -//! 因此这里做**内嵌精简版**: -//! -//! * 内网 / 保留地址(RFC 1918、loopback、link-local 等)直接归类为「内网」; -//! * 内嵌一份**代表性**的 CN IPv4 CIDR 表(非全量),命中即标「中国」; -//! * 其余归「海外」。 -//! -//! 这是「归属地做精致了再加」的第一步:后续若要精确,把 DB 文件放 `data_dir` -//! 下、在此处替换为查表即可,调用方(audit)无需改动。 - -/// 内嵌的 CN IPv4 CIDR 表(代表性片段,非全量 APNIC 分配)。 -/// 形如 `"1.2.3.0/24"`。仅用于"是否在中国"的粗判。 -const CN_CIDRS: &[&str] = &[ - "1.0.1.0/24", "1.0.2.0/23", "1.2.4.0/22", "1.8.0.0/16", "1.24.0.0/13", - "1.56.0.0/13", "1.68.0.0/14", "1.80.0.0/13", "1.92.0.0/14", "1.116.0.0/14", - "1.180.0.0/14", "1.188.0.0/14", "1.192.0.0/13", "1.202.0.0/15", "1.204.0.0/14", - "14.0.0.0/8", "27.0.0.0/10", "36.0.0.0/8", "39.0.0.0/8", "42.0.0.0/8", - "43.0.0.0/8", "45.0.0.0/8", "49.0.0.0/8", "58.0.0.0/7", "59.32.0.0/11", - "60.0.0.0/8", "61.0.0.0/8", "101.0.0.0/8", "103.0.0.0/8", "106.0.0.0/8", - "110.0.0.0/7", "111.0.0.0/8", "112.0.0.0/7", "113.0.0.0/8", "114.0.0.0/8", - "115.0.0.0/8", "116.0.0.0/8", "117.0.0.0/8", "118.0.0.0/8", "119.0.0.0/8", - "120.0.0.0/8", "121.0.0.0/8", "122.0.0.0/8", "123.0.0.0/8", "124.0.0.0/8", - "125.0.0.0/8", "129.0.0.0/8", "130.0.0.0/8", "131.0.0.0/8", "132.0.0.0/8", - "133.0.0.0/8", "134.0.0.0/8", "135.0.0.0/8", "136.0.0.0/8", "137.0.0.0/8", - "138.0.0.0/8", "139.0.0.0/8", "140.0.0.0/8", "144.0.0.0/8", "149.0.0.0/8", - "150.0.0.0/8", "151.0.0.0/8", "152.0.0.0/8", "153.0.0.0/8", "154.0.0.0/8", - "155.0.0.0/8", "156.0.0.0/8", "157.0.0.0/8", "159.0.0.0/8", "160.0.0.0/8", - "161.0.0.0/8", "162.0.0.0/8", "163.0.0.0/8", "164.0.0.0/8", "166.0.0.0/8", - "167.0.0.0/8", "168.0.0.0/8", "169.0.0.0/8", "170.0.0.0/8", "171.0.0.0/8", - "172.0.0.0/8", "175.0.0.0/8", "180.0.0.0/8", "182.0.0.0/8", "183.0.0.0/8", - "184.0.0.0/8", "185.0.0.0/8", "186.0.0.0/8", "189.0.0.0/8", "190.0.0.0/8", - "192.0.0.0/8", "193.0.0.0/8", "196.0.0.0/8", "198.0.0.0/8", "202.0.0.0/8", - "203.0.0.0/8", "210.0.0.0/7", "211.0.0.0/8", "218.0.0.0/7", "219.0.0.0/8", - "220.0.0.0/8", "221.0.0.0/8", "222.0.0.0/8", "223.0.0.0/8", -]; - -/// 把一个 IPv4 地址按 `.` 拆成 4 个 u8;非法返回 None。 -fn parse_v4(ip: &str) -> Option<[u8; 4]> { - let mut parts = [0u8; 4]; - let mut i = 0; - for seg in ip.split('.') { - if i >= 4 { - return None; - } - let n: u8 = seg.parse().ok()?; - parts[i] = n; - i += 1; - } - if i == 4 { - Some(parts) - } else { - None - } -} - -/// 判断 `ip` 是否属于 CIDR `a.b.c.d/n`。 -fn in_cidr(ip: [u8; 4], cidr: &str) -> bool { - let Some((net, plen)) = cidr.split_once('/') else { - return false; - }; - let prefix = match parse_v4(net) { - Some(p) => p, - None => return false, - }; - let bits: u32 = match plen.parse().ok() { - Some(b) => b, - None => return false, - }; - if bits > 32 { - return false; - } - let ip_u32 = u32::from_be_bytes(ip); - let net_u32 = u32::from_be_bytes(prefix); - let mask: u32 = if bits == 0 { - 0 - } else { - (!0u32) << (32 - bits) - }; - (ip_u32 & mask) == (net_u32 & mask) -} - -/// 是否为内网 / 保留地址(命中即"内网",无需查表)。 -fn is_private(ip: [u8; 4]) -> bool { - match ip { - [10, ..] => true, - [127, ..] => true, - [169, 254, ..] => true, - [172, 16..=31, ..] => true, - [192, 168, ..] => true, - [0, ..] => true, - [100, 64..=127, ..] => true, // CGNAT - _ => false, - } -} - -/// 解析登录 IP,返回归属地文本(如「中国」「内网」「海外」「未知」)。 -/// -/// 设计上**不依赖任何外部库**:IPv4 字符串解析 + CIDR 匹配即可。 -/// IPv6 暂统一回「海外」(精简版不做 v6 GeoIP)。 -pub fn lookup(ip: &str) -> String { - let ip = ip.trim(); - // 去掉可能的端口后缀(remote_addr 有时带端口) - let ip = ip.split(':').next().unwrap_or(ip); - match parse_v4(ip) { - Some(addr) => { - if is_private(addr) { - return "内网".to_owned(); - } - if CN_CIDRS.iter().any(|c| in_cidr(addr, c)) { - return "中国".to_owned(); - } - "海外".to_owned() - } - None => { - if ip.is_empty() || ip == "-" { - "未知".to_owned() - } else { - "海外".to_owned() - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn private_ranges() { - assert_eq!(lookup("127.0.0.1"), "内网"); - assert_eq!(lookup("192.168.1.50"), "内网"); - assert_eq!(lookup("10.0.0.1"), "内网"); - assert_eq!(lookup("172.16.5.5"), "内网"); - } - - #[test] - fn cn_range() { - // 36.0.0.0/8 在表中 - assert_eq!(lookup("36.110.0.1"), "中国"); - assert_eq!(lookup("116.204.0.1"), "中国"); - } - - #[test] - fn foreign() { - assert_eq!(lookup("8.8.8.8"), "海外"); - assert_eq!(lookup("-"), "未知"); - assert_eq!(lookup(""), "未知"); - } -} diff --git a/rust/crates/plugin-sso/src/ldap.rs b/rust/crates/plugin-sso/src/ldap.rs deleted file mode 100644 index 2690e18..0000000 --- a/rust/crates/plugin-sso/src/ldap.rs +++ /dev/null @@ -1,252 +0,0 @@ -//! LDAP / AD 认证源(对齐 MaxKey `maxkey-ldap`)。 -//! -//! 把企业目录(Active Directory / OpenLDAP)作为**认证源**接入:用户用目录里的 -//! 账号密码登录管理台,口令不在本网关落地(由 AD 校验)。 -//! -//! **零外部依赖**:不引 ldap3(其 async/tokio 模型与 nginx 单线程 FFI 冲突), -//! 这里手工编码 LDAP 的 BER/ASN.1 简单绑定(Simple Bind)——只够做「bind 成功 / -//! 失败」判定,不拉属性。属性同步走 [`crate::sync`] 连接器。 -//! -//! 配置(env,全部可选): -//! LDAP_ENABLED=1 开启 -//! LDAP_SERVER=ldap.corp.com 目录服务器 -//! LDAP_PORT=389 端口(仅明文 389;TLS 由上层终结) -//! LDAP_BASE_DN=dc=corp,dc=com 基准 DN -//! LDAP_USER_DN_TEMPLATE=uid={user},{base} 用户 DN 模板 -//! LDAP_AUTO_CREATE=1 目录认证成功但本地无账号时自动建账号 -//! -//! 安全性:连接超时 3s,任何错误都降级为「认证失败」(绝不 panic、绝不放行)。 - -use std::io::{Read, Write}; -use std::net::TcpStream; -use std::time::Duration; - -use ipass_core::util; - -/// 配置读取 -fn enabled() -> bool { - std::env::var("LDAP_ENABLED").map(|v| v.trim() == "1").unwrap_or(false) -} - -pub(crate) fn auto_create() -> bool { - std::env::var("LDAP_AUTO_CREATE").map(|v| v.trim() == "1").unwrap_or(false) -} - -fn server() -> String { - std::env::var("LDAP_SERVER").unwrap_or_default() -} - -fn port() -> u16 { - std::env::var("LDAP_PORT") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .unwrap_or(389) -} - -fn user_dn(username: &str) -> String { - let base = std::env::var("LDAP_BASE_DN").unwrap_or_default(); - let tpl = std::env::var("LDAP_USER_DN_TEMPLATE") - .unwrap_or_else(|_| "uid={user},{base}".to_owned()); - tpl.replace("{user}", username).replace("{base}", &base) -} - -// =========================================================================== -// BER / ASN.1 极简编解码 -// =========================================================================== - -/// 定长 TLV:tag + 长度 + 内容。长度 < 128 用单字节,否则长形式。 -fn ber_len(n: usize) -> Vec { - if n < 128 { - vec![n as u8] - } else { - let mut bytes = Vec::new(); - let mut v = n; - while v > 0 { - bytes.push((v & 0xff) as u8); - v >>= 8; - } - bytes.reverse(); - let mut out = vec![0x80 | bytes.len() as u8]; - out.extend_from_slice(&bytes); - out - } -} - -fn ber_seq(content: &[u8]) -> Vec { - let mut v = vec![0x30]; - v.extend_from_slice(&ber_len(content.len())); - v.extend_from_slice(content); - v -} - -fn ber_int(n: i64) -> Vec { - // 最小字节(补码),小正整数走一个字节 - let mut b = (n as i64).to_be_bytes().to_vec(); - while b.len() > 1 && b[0] == 0 { - b.remove(0); - } - let mut v = vec![0x02]; - v.extend_from_slice(&ber_len(b.len())); - v.extend_from_slice(&b); - v -} - -fn ber_octet(s: &[u8]) -> Vec { - let mut v = vec![0x04]; - v.extend_from_slice(&ber_len(s.len())); - v.extend_from_slice(s); - v -} - -/// [APPLICATION n] 构造(如 BindRequest=0x60, BindResponse=0x61) -fn ber_app(app: u8, content: &[u8]) -> Vec { - let mut v = vec![0x60 | app]; - v.extend_from_slice(&ber_len(content.len())); - v.extend_from_slice(content); - v -} - -/// [CONTEXT n] 构造(如 simple 认证 = 0x80) -fn ber_ctx(ctx: u8, content: &[u8]) -> Vec { - let mut v = vec![0x80 | ctx]; - v.extend_from_slice(&ber_len(content.len())); - v.extend_from_slice(content); - v -} - -/// 解析一个 TLV,返回 (tag, 内容起始, 内容结束) -fn read_tlv(buf: &[u8], pos: usize) -> Option<(u8, usize, usize)> { - let tag = *buf.get(pos)?; - let mut p = pos + 1; - let first = *buf.get(p)? as usize; - let len = if first & 0x80 == 0 { - p += 1; - first - } else { - let nbytes = first & 0x7f; - p += 1; - let mut l = 0usize; - for _ in 0..nbytes { - l = (l << 8) | *buf.get(p)? as usize; - p += 1; - } - l - }; - let start = p; - let end = start + len; - if end > buf.len() { - return None; - } - Some((tag, start, end)) -} - -/// 从 BindResponse 里取 resultCode(ENUMERATED,tag 0x0A)。 -/// 简单做法:在整条消息里找第一个 0x0A,读其整数值(BindResponse 中唯一 ENUMERATED)。 -fn result_code(msg: &[u8]) -> Option { - let mut i = 0; - while i < msg.len() { - if msg[i] == 0x0a { - // 长度(单字节即可,resultCode 很小) - let l = *msg.get(i + 1)? as usize; - let val_pos = i + 2; - if val_pos + l <= msg.len() { - let mut v: u32 = 0; - for k in 0..l { - v = (v << 8) | (*msg.get(val_pos + k)? as u32); - } - return Some(v as u8); - } - } - i += 1; - } - None -} - -/// 解析整条 LDAPMessage(外层 SEQUENCE 长度可能跨多个 read)。 -fn take_message(buf: &[u8]) -> Option<&[u8]> { - let (_, _start, end) = read_tlv(buf, 0)?; - if end <= buf.len() { - Some(&buf[..end]) - } else { - None - } -} - -// =========================================================================== -// 绑定 -// =========================================================================== - -/// 与目录服务器做一次 Simple Bind。成功返回 Ok(()),否则 Err。 -fn bind(dn: &str, password: &str) -> Result<(), String> { - let server = server(); - if server.is_empty() { - return Err("LDAP_SERVER 未配置".to_owned()); - } - let mut stream = TcpStream::connect((server.as_str(), port())) - .map_err(|e| format!("连接目录服务器失败:{e}"))?; - stream.set_read_timeout(Some(Duration::from_secs(3))).ok(); - stream.set_write_timeout(Some(Duration::from_secs(3))).ok(); - - // BindRequest 内容 = version(INT 3) + name(OCTET DN) + authentication(ctx[0]=simple, password) - let mut content = ber_int(3); - content.extend_from_slice(&ber_octet(dn.as_bytes())); - content.extend_from_slice(&ber_ctx(0, password.as_bytes())); - let bindreq = ber_app(0, &content); - // LDAPMessage = SEQUENCE { messageID INT 1, bindRequest } - let mut msg = ber_seq(&ber_int(1)); - msg.extend_from_slice(&bindreq); - - stream - .write_all(&msg) - .map_err(|e| format!("发送绑定请求失败:{e}"))?; - - // 读回应:循环读到拿到完整 LDAPMessage - let mut buf = Vec::new(); - let mut tmp = [0u8; 4096]; - loop { - if let Some(full) = take_message(&buf) { - return match result_code(full) { - Some(0) => Ok(()), - Some(code) => Err(format!("目录返回结果码 {code}(非成功)")), - None => Err("无法解析绑定响应".to_owned()), - }; - } - match stream.read(&mut tmp) { - Ok(0) => break, - Ok(n) => buf.extend_from_slice(&tmp[..n]), - Err(_) => break, - } - if buf.len() > 65536 { - break; - } - } - Err("绑定未收到完整响应".to_owned()) -} - -/// 认证入口:LDAP 开启时校验用户名/口令。 -/// -/// 返回 true 仅当 bind 成功;其余情况(未开启 / 任何错误)一律 false。 -pub fn authenticate(username: &str, password: &str) -> bool { - if !enabled() { - return false; - } - if password.is_empty() { - return false; - } - let dn = user_dn(username); - match bind(&dn, password) { - Ok(()) => { - util::log_notice(&format!("[ldap] 认证成功 user={username} dn={dn}")); - true - } - Err(e) => { - util::log_warn(&format!("[ldap] 认证失败 user={username}:{e}")); - false - } - } -} - -/// 供登录流程判断是否需要尝试 LDAP(未开启时直接 false,零开销)。 -pub fn should_try() -> bool { - enabled() -} diff --git a/rust/crates/plugin-sso/src/lib.rs b/rust/crates/plugin-sso/src/lib.rs deleted file mode 100644 index 5a0d4a7..0000000 --- a/rust/crates/plugin-sso/src/lib.rs +++ /dev/null @@ -1,226 +0,0 @@ -//! # 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::(cf).is_ok() - } - - fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option { - 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 接入方") -} diff --git a/rust/crates/plugin-sso/src/oauth.rs b/rust/crates/plugin-sso/src/oauth.rs deleted file mode 100644 index fe0804b..0000000 --- a/rust/crates/plugin-sso/src/oauth.rs +++ /dev/null @@ -1,1484 +0,0 @@ -//! OAuth2 / OIDC 授权服务器(本项目就是 IdP)。 -//! -//! 本协议层**对齐 MaxKey 的 OAuth2 实现**(端点命名、grant type、scope、claims), -//! 但**完全不依赖 MaxKey 运行时**——第三方应用按标准 OAuth2 / OIDC 流程对接即可, -//! 照抄 MaxKey 文档配好的应用也能零改造切过来(见 `api.rs` 的端点别名)。 -//! -//! 端点(均走 `sso_api` content 阶段,公开无管理员态): -//! -//! | 端点 | 方法 | 说明 | -//! | --- | --- | --- | -//! | `/oauth/authorize` | GET | 授权码流程入口(浏览器) | -//! | `/oauth/token` | POST | 换发 access_token / id_token / refresh_token | -//! | `/oauth/userinfo` | GET | Bearer token → 用户声明 | -//! | `/oauth/introspect` | POST | RFC 7662 令牌自省(IAP / 资源服校验用) | -//! | `/.well-known/openid-configuration` | GET | OIDC discovery | -//! | `/login` | GET/POST | SSO 登录页(建立 `sso_sid` 会话) | -//! | `/oauth/logout` | GET/POST | 销毁 SSO 会话 | -//! -//! 令牌格式:**HS256 签名 JWT**(对称密钥取自 `OAUTH_SIGNING_SECRET`)。零新增 -//! 依赖——HMAC-SHA256 用现成的 `sha2`,base64url 自实现。多 worker 无共享状态也能 -//! 验证(契合「无数据库」哲学)。 -//! -//! > ⚠️ **已知限制**:HS256 是对称签名,第三方无法本地验签(必须回源调 -//! > `/oauth/introspect`,或拿 `client_secret` 当密钥)。升级 RS256 + `/oauth/jwks` -//! > 是既定 v2 项,见 `docs/roadmap.md`。 -//! -//! ## 两类身份,两套会话,不可混用 -//! -//! * **终端用户**(OAuth2 主体):`sso:` 前缀 + `sso_sid` Cookie, -//! 生命周期由 `OAUTH_SESSION_TTL` 控制,供授权码流程与 IAP 使用; -//! * **管理员**(管理台主体):`sess:` 前缀 + `sso_admin_session` Cookie, -//! 见 `session` 模块。 -//! -//! 把两者合成一套会让「登录管理台 = 具备 SSO 身份」,权限边界直接消失。 - -use std::sync::OnceLock; - -use sha2::{Digest, Sha256}; -use serde_json::{Value, json}; - -use ngx::core::{Buffer, Status}; -use ngx::ffi::ngx_http_request_t; -use ngx::http::HTTPStatus; - -use crate::audit; -use crate::oauth_keys::{ - IAP_TOKEN_AUDIENCE, IAP_TOKEN_SCOPE, OAUTH_ACCESS_TTL, OAUTH_CODE_CHALLENGE_METHODS, - OAUTH_CODE_TTL, OAUTH_COOKIE_DOMAIN_ENV, OAUTH_DEFAULT_ISSUER, OAUTH_ID_TOKEN_TTL, - OAUTH_ISSUER_ENV, OAUTH_REFRESH_TTL, OAUTH_SCOPES_SUPPORTED, OAUTH_SESSION_COOKIE, - OAUTH_SESSION_TTL, OAUTH_SIGNING_SECRET_ENV, -}; -use ipass_core::http; -use crate::accounts::{self, UserExt}; -use ipass_core::models::User; -use crate::oauth_clients; -use ipass_core::users; -use crate::utilx; -use ipass_core::util; - -// =========================================================================== -// 配置(环境变量,启动时固化) -// =========================================================================== - -static SECRET: OnceLock = OnceLock::new(); -static ISSUER: OnceLock = OnceLock::new(); - -/// HS256 对称密钥。未设置则随机生成并告警(重启使旧 token 失效)。 -fn signing_secret() -> String { - SECRET - .get_or_init(|| match std::env::var(OAUTH_SIGNING_SECRET_ENV) { - Ok(s) if !s.is_empty() => s, - _ => { - let g = util::rand_hex(32); - util::log_warn(&format!( - "[oauth] 未设置 {OAUTH_SIGNING_SECRET_ENV},临时随机密钥(重启后已签发 token 失效):{}…", - &g[..8] - )); - g - } - }) - .clone() -} - -/// 签发者(issuer),discovery 与 token `iss` 用它。 -pub(crate) fn issuer() -> String { - ISSUER - .get_or_init(|| { - std::env::var(OAUTH_ISSUER_ENV).unwrap_or_else(|_| OAUTH_DEFAULT_ISSUER.to_owned()) - }) - .clone() -} - -/// SSO Cookie 的 Domain(跨主机单点登录用,如 `.yourdomain.com`)。 -/// -/// 留空则 Cookie 绑定签发主机——同域多子站共享 SSO 时必须设成带点的父域, -/// 否则 `app.a.com` 拿不到 `sso.a.com` 登录时下发的 Cookie,表现为「登录了但一直 -/// 被弹回登录页」(重定向循环)。 -fn cookie_domain() -> String { - std::env::var(OAUTH_COOKIE_DOMAIN_ENV).unwrap_or_default() -} - -// =========================================================================== -// base64url + HMAC-SHA256(零新增依赖) -// =========================================================================== - -pub(crate) fn oauth_b64_encode(input: &[u8]) -> String { - b64url_encode(input) -} - -pub(crate) fn oauth_b64_decode(input: &str) -> Vec { - b64url_decode(input).unwrap_or_default() -} - -fn b64url_encode(input: &[u8]) -> String { - const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - let mut out = String::with_capacity((input.len() + 2) / 3 * 4); - let mut i = 0; - while i + 3 <= input.len() { - let n = u32::from_be_bytes([input[i], input[i + 1], input[i + 2], 0]); - out.push(T[((n >> 26) & 0x3f) as usize] as char); - out.push(T[((n >> 20) & 0x3f) as usize] as char); - out.push(T[((n >> 14) & 0x3f) as usize] as char); - out.push(T[((n >> 8) & 0x3f) as usize] as char); - i += 3; - } - let rem = input.len() - i; - if rem == 1 { - let n = input[i] as u32; - out.push(T[((n >> 2) & 0x3f) as usize] as char); - out.push(T[((n << 4) & 0x3f) as usize] as char); - } else if rem == 2 { - let n = ((input[i] as u32) << 8) | input[i + 1] as u32; - out.push(T[((n >> 10) & 0x3f) as usize] as char); - out.push(T[((n >> 4) & 0x3f) as usize] as char); - out.push(T[((n << 2) & 0x3f) as usize] as char); - } - out -} - -fn b64url_decode(input: &str) -> Option> { - let mut buf: Vec = Vec::with_capacity(input.len()); - for c in input.chars() { - let v = match c { - 'A'..='Z' => c as u8 - b'A', - 'a'..='z' => c as u8 - b'a' + 26, - '0'..='9' => c as u8 - b'0' + 52, - '-' => 62, - '_' => 63, - '=' | ' ' => continue, - _ => return None, - }; - buf.push(v); - } - // 6 位一组 → 8 位;buf.len()*6 必须能被 8 整除(忽略尾部不足字节) - let bits = buf.len() * 6; - let out_len = bits / 8; - let mut out = vec![0u8; out_len]; - let mut acc = 0u32; - let mut acc_bits = 0; - let mut idx = 0; - for &b in &buf { - acc = (acc << 6) | b as u32; - acc_bits += 6; - if acc_bits >= 8 { - acc_bits -= 8; - if idx < out_len { - out[idx] = ((acc >> acc_bits) & 0xff) as u8; - idx += 1; - } - } - } - Some(out) -} - -/// HMAC-SHA256(RFC 2104)。 -fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] { - const BLOCK: usize = 64; - let mut k = [0u8; BLOCK]; - if key.len() > BLOCK { - let h = Sha256::digest(key); - k[..32].copy_from_slice(&h); - } else { - k[..key.len()].copy_from_slice(key); - } - for b in k.iter_mut() { - *b ^= 0x36; - } - let mut inner = Sha256::new(); - inner.update(&k); - inner.update(data); - let inner_h = inner.finalize(); - - for b in k.iter_mut() { - *b ^= 0x36 ^ 0x5c; - } - let mut outer = Sha256::new(); - outer.update(&k); - outer.update(&inner_h); - let h = outer.finalize(); - let mut out = [0u8; 32]; - out.copy_from_slice(&h); - out -} - -/// SHA256(PKCE S256 挑战用)。 -fn sha256_raw(data: &[u8]) -> [u8; 32] { - let mut h = Sha256::new(); - h.update(data); - let d = h.finalize(); - let mut out = [0u8; 32]; - out.copy_from_slice(&d); - out -} - -// =========================================================================== -// 签名密钥管理(HS256 对称密钥 | RS256 + JWKS,roadmap v2) -// =========================================================================== - -/// 当前签名密钥。RS256 时持有完整私钥(CRT 分量), -/// HS256 仅为兼容模式(`OAUTH_JWT_ALG=HS256` 显式指定)。 -struct SignKey { - alg: &'static str, - /// RS256:active 私钥 - rsa: Option, -} - -/// 密钥目录:`OAUTH_JWK_DIR`,缺省 `/jwks` -fn jwk_dir() -> std::path::PathBuf { - match std::env::var("OAUTH_JWK_DIR") { - Ok(d) if !d.is_empty() => std::path::PathBuf::from(d), - _ => std::path::PathBuf::from(ipass_core::store::data_dir()).join("jwks"), - } -} - -fn init_sign_key() -> Result { - let alg = std::env::var("OAUTH_JWT_ALG").unwrap_or_else(|_| "RS256".to_owned()); - if alg == "HS256" { - util::log_notice("[oauth] JWT 签名算法:HS256(兼容模式,第三方无法本地验签)"); - return Ok(SignKey { alg: "HS256", rsa: None }); - } - - // RS256:加载或生成 active 密钥。生成放共享内存文件锁内, - // 防止多 worker 首启竞态各自生成密钥互相覆盖。 - let dir = jwk_dir(); - std::fs::create_dir_all(&dir).map_err(|e| format!("创建 jwk 目录失败:{e}"))?; - let path = dir.join("active.jwk.json"); - - let _guard = ipass_core::state::file_lock().ok_or("内部错误:状态锁不可用")?; - if path.exists() { - let text = std::fs::read_to_string(&path).map_err(|e| format!("读取 {path:?} 失败:{e}"))?; - let v: Value = serde_json::from_str(&text).map_err(|e| format!("解析 active.jwk.json 失败:{e}"))?; - let kp = crate::rsa::from_jwk(&v).ok_or("active.jwk.json 分量不完整")?; - if !kp.has_private() { - return Err("active.jwk.json 缺少私钥分量(疑似误放公钥文件)".to_owned()); - } - util::log_notice(&format!("[oauth] 已加载 RS256 密钥 kid={}", kp.kid)); - return Ok(SignKey { alg: "RS256", rsa: Some(kp) }); - } - - let t0 = util::now(); - let kp = crate::rsa::generate()?; - std::fs::write(&path, crate::rsa::to_jwk(&kp).to_string()) - .map_err(|e| format!("写 active.jwk.json 失败:{e}"))?; - util::log_notice(&format!( - "[oauth] 已生成 RS256-2048 密钥 kid={}(耗时 {}s),存储 {}", - kp.kid, - util::now() - t0, - path.display() - )); - Ok(SignKey { alg: "RS256", rsa: Some(kp) }) -} - -/// 全局签名密钥(首次使用时惰性初始化;失败则 panic 级错误会打日志并回退 HS256) -fn sign_key() -> Option<&'static SignKey> { - static KEY: OnceLock> = OnceLock::new(); - match KEY.get_or_init(init_sign_key) { - Ok(k) => Some(k), - Err(e) => { - util::log_err(&format!("[oauth] RS256 密钥初始化失败,令牌签发不可用:{e}")); - None - } - } -} - -// =========================================================================== -// JWT(RS256 默认 | HS256 兼容) -// =========================================================================== - -fn jwt_sign(claims: &Value) -> Option { - let key = sign_key()?; - let payload = b64url_encode(serde_json::to_string(claims).unwrap_or_default().as_bytes()); - match key.alg { - "HS256" => { - let header = b64url_encode(br#"{"alg":"HS256","typ":"JWT"}"#); - let signing_input = format!("{header}.{payload}"); - let sig = hmac_sha256(signing_secret().as_bytes(), signing_input.as_bytes()); - Some(format!("{signing_input}.{}", b64url_encode(&sig))) - } - "RS256" => { - let rsa = key.rsa.as_ref()?; - if !rsa.has_private() { - return None; - } - let header = format!( - "{{\"alg\":\"RS256\",\"typ\":\"JWT\",\"kid\":\"{}\"}}", - rsa.kid - ); - let header = b64url_encode(header.as_bytes()); - let signing_input = format!("{header}.{payload}"); - let digest = sha256_raw(signing_input.as_bytes()); - let sig = crate::rsa::sign_crt(&digest, rsa); - Some(format!("{signing_input}.{}", b64url_encode(&sig))) - } - _ => None, - } -} - -/// 校验签名并核对 `exp`;返回 claims。 -/// -/// **alg 白名单**:只认 HS256 / RS256(且必须与密钥形态一致),拒绝 `none`; -/// 拒绝拿公钥当 HMAC 密钥的 alg 混淆攻击(header 写 HS256 但签名用 RSA 公钥算的 -/// HMAC 一律对不上,反之亦然——两个分支的密钥完全独立)。 -/// `kid` 用于在多把公钥(轮换期)中选对验证密钥。 -fn jwt_verify(token: &str) -> Option { - let mut parts = token.splitn(3, '.'); - let h = parts.next()?; - let p = parts.next()?; - let s = parts.next()?; - if h.is_empty() || p.is_empty() || s.is_empty() { - return None; - } - let signing_input = format!("{h}.{p}"); - let sig = b64url_decode(s)?; - - // 解析 header(失败/非对象一律拒绝) - let header: Value = serde_json::from_slice(&b64url_decode(h)?).ok()?; - let alg = header.get("alg").and_then(|v| v.as_str())?; - - let verified = match alg { - "HS256" => { - let expected = hmac_sha256(signing_secret().as_bytes(), signing_input.as_bytes()); - sig.len() == expected.len() && util::ct_eq(&util::to_hex(&sig), &util::to_hex(&expected)) - } - "RS256" => { - let key = sign_key()?; - let rsa = key.rsa.as_ref()?; - // kid 匹配:轮换期旧令牌带旧 kid,active 私钥签的带新 kid。 - // 当前只保留一把 active 私钥(旧公钥文件在 jwks 端点另行列出), - // kid 不匹配 active 且无法在历史公钥里验过 → 拒绝。 - let kid = header.get("kid").and_then(|v| v.as_str()).unwrap_or(""); - let digest = sha256_raw(signing_input.as_bytes()); - if !kid.is_empty() && kid != rsa.kid { - // 尝试历史公钥(dir/*.pub.jwk.json) - verify_with_history_pub(&sig, &digest, kid) - } else { - crate::rsa::verify(&sig, &rsa.n, rsa.e) == Some(digest) - } - } - _ => false, - }; - if !verified { - return None; - } - - let payload = b64url_decode(p)?; - let claims: Value = serde_json::from_slice(&payload).ok()?; - let exp = claims.get("exp").and_then(|v| v.as_i64()).unwrap_or(i64::MAX); - if exp <= util::now() { - return None; - } - Some(claims) -} - -/// 用历史公钥目录(`*.pub.jwk.json`)验证旧 kid 的令牌(轮换期过渡)。 -fn verify_with_history_pub(sig: &[u8], digest: &[u8; 32], kid: &str) -> bool { - let dir = jwk_dir(); - let Ok(entries) = std::fs::read_dir(&dir) else { - return false; - }; - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - if !name.ends_with(".pub.jwk.json") { - continue; - } - let Ok(text) = std::fs::read_to_string(entry.path()) else { - continue; - }; - let Ok(v) = serde_json::from_str::(&text) else { - continue; - }; - if v.get("kid").and_then(|x| x.as_str()) != Some(kid) { - continue; - } - if let Some(kp) = crate::rsa::from_jwk(&v) { - if crate::rsa::verify(sig, &kp.n, kp.e) == Some(*digest) { - return true; - } - } - } - false -} - -// =========================================================================== -// 令牌签发 -// =========================================================================== - -/// 颁发 access_token(RS256 默认 / HS256 兼容)。 -fn mint_access_token( - sub: &str, - email: &str, - name: &str, - groups: &[String], - department: &str, - mobile: &str, - client_id: &str, - scope: &str, - now: i64, -) -> Option { - let claims = json!({ - "iss": issuer(), - "sub": sub, - "aud": client_id, - "client_id": client_id, - // `preferred_username` 必须是**登录账号**,不是显示名: - // 第三方系统(Grafana / 各类 SSO 对接)普遍用它做账号绑定与查找, - // 放显示名(如"爱丽丝")会导致账号匹配不上。显示名走 `name`。 - "preferred_username": sub, - "name": name, - "email": email, - // 手机号:接入方(uc_user.phone 等)建档依赖;空值也写键,保证 claim 形状稳定 - "mobile": mobile, - "department": department, - "groups": groups, - "scope": scope, - "token_type": "access", - "iat": now, - "exp": now + OAUTH_ACCESS_TTL, - "jti": util::rand_hex(16), - }); - jwt_sign(&claims) -} - -/// 颁发 id_token(OIDC)。 -fn mint_id_token(sub: &str, email: &str, name: &str, client_id: &str, nonce: &str, now: i64) -> Option { - let mut claims = json!({ - "iss": issuer(), - "sub": sub, - "aud": client_id, - "preferred_username": name, - "email": email, - "iat": now, - "exp": now + OAUTH_ID_TOKEN_TTL, - "jti": util::rand_hex(16), - }); - if !nonce.is_empty() { - claims["nonce"] = json!(nonce); - } - jwt_sign(&claims) -} - -/// 颁发 refresh_token(JWT,typ=refresh)。 -fn mint_refresh_token(sub: &str, client_id: &str, now: i64) -> Option { - let claims = json!({ - "iss": issuer(), - "sub": sub, - "aud": client_id, - "client_id": client_id, - "typ": "refresh", - "iat": now, - "exp": now + OAUTH_REFRESH_TTL, - "jti": util::rand_hex(16), - }); - jwt_sign(&claims) -} - -// =========================================================================== -// SSO 会话(浏览器 IAP 用) -// =========================================================================== - -/// 构造 SSO 会话 payload:` \n \n \n \n `。 -/// 把身份平铺进共享内存,IAP 热路径只读内存、不回读 `users.json`。 -/// -/// 分隔符用 `\n`(与 `ukey:` 身份 payload 同一约定),**不能**用 `0x1f`: -/// 那是 `state::VAL_SEP`,即共享内存 value 里「payload / expiry」的分隔符, -/// 用作字段分隔会让 `state::get` 切错位置、读到的会话立刻判为无效。 -fn sso_payload(u: &User) -> String { - format!( - "{}\n{}\n{}\n{}\n{}", - u.username, - u.email(), - u.groups().join(","), - u.department(), - if u.display_name.is_empty() { - u.username.clone() - } else { - u.display_name.clone() - } - ) -} - -fn parse_cookie(header: Option<&str>, name: &str) -> Option { - let header = header?; - let needle = format!("{name}="); - for part in header.split(';') { - let part = part.trim(); - if let Some(v) = part.strip_prefix(&needle) { - if !v.is_empty() { - return Some(util::url_decode(v)); - } - } - } - None -} - -/// 当前登录用户:**管理台会话与终端用户 SSO 会话都认**。 -/// -/// 两套会话是互相独立的存储:管理台走 `session::authenticate`(内核会话表), -/// 终端用户走 `sso_sid` cookie + 共享内存。CAS 登录页与用户门户面向浏览器, -/// 用户从任一侧登录进来都可能命中,这里依次尝试——否则会出现「明明已登录, -/// 却被告知未登录」的诡异现象。 -pub fn current_user(r: *mut ngx_http_request_t) -> Option { - let cookie = http::header(r, "cookie"); - if let Some(u) = ipass_core::session::authenticate(cookie.as_deref()) { - return Some(u); - } - let tok = parse_cookie(cookie.as_deref(), OAUTH_SESSION_COOKIE)?; - let payload = crate::oauth_state::get_oauth_session(&tok, util::now())?; - let name = payload.split('\n').next().unwrap_or("").trim().to_owned(); - if name.is_empty() { - None - } else { - Some(name) - } -} - -fn sso_cookie(token: &str, max_age: i64) -> String { - let dom = cookie_domain(); - let dom_part = if dom.is_empty() { String::new() } else { format!("; Domain={dom}") }; - format!( - "{OAUTH_SESSION_COOKIE}={token}; Path=/{dom_part}; HttpOnly; SameSite=Lax; Max-Age={max_age}" - ) -} - -// =========================================================================== -// 鉴权辅助 -// =========================================================================== - -/// 从 `Authorization: Bearer ` 取令牌。 -fn bearer_token(r: *mut ngx_http_request_t) -> Option { - let h = http::header(r, "authorization")?; - let h = h.trim(); - if let Some(t) = h.strip_prefix("Bearer ") { - Some(t.trim().to_owned()) - } else if let Some(t) = h.strip_prefix("Bearer:") { - Some(t.trim().to_owned()) - } else { - None - } -} - -/// 取访问令牌:优先 `Authorization: Bearer`,回退 `access_token` 查询/表单参数。 -/// -/// 回退分支是为 **MaxKey 互通** 准备的:MaxKey 的 userinfo 端点是 -/// `POST /api/oauth/v20/me`,令牌放在表单体里(`access_token=...`), -/// 而非标准 OIDC 的 Bearer 头。缺了这条,照抄 MaxKey 文档的应用会 401。 -fn access_token_of(r: *mut ngx_http_request_t) -> Option { - if let Some(t) = bearer_token(r) { - return Some(t); - } - let p = http::params(r); - p.get("access_token") - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) -} - -/// 校验客户端身份(confidential 需 secret,public 仅 client_id)。 -/// 返回客户端,或 None(无效)。 -fn authenticate_client(r: *mut ngx_http_request_t, body: &std::collections::HashMap) -> Option { - let mut cid = String::new(); - let mut csec = String::new(); - - // 1) Basic Authorization: client_id:client_secret - if let Some(auth) = http::header(r, "authorization") { - if let Some(b64) = auth.strip_prefix("Basic ") { - if let Some(decoded) = b64url_decode_safe(b64) { - if let Some((id, sec)) = decoded.split_once(':') { - cid = id.to_owned(); - csec = sec.to_owned(); - } - } - } - } - // 2) 表单/JSON 覆盖 - if let Some(v) = body.get("client_id") { - cid = v.clone(); - } - if let Some(v) = body.get("client_secret") { - csec = v.clone(); - } - - if cid.is_empty() { - return None; - } - let client = oauth_clients::get(&cid)?; - if client.confidential { - if csec.is_empty() || !util::ct_eq(&csec, &client.client_secret) { - util::log_warn(&format!("[oauth] 客户端 {cid} 密钥校验失败")); - return None; - } - } - Some(client) -} - -/// 宽松 base64 解码(允许标准字母表与 padding),仅供 Basic Auth。 -fn b64url_decode_safe(input: &str) -> Option { - let bytes = std_base64_decode(input)?; - String::from_utf8(bytes).ok() -} - -/// 标准 base64(+/ 字母表 + 可选 padding)→ 字节。先规整成 url-safe 再复用 `b64url_decode`。 -fn std_base64_decode(input: &str) -> Option> { - let norm: String = input.chars().map(|c| match c { '+' => '-', '/' => '_', _ => c }).collect(); - b64url_decode(&norm) -} - -// =========================================================================== -// 端点处理 -// =========================================================================== - -/// GET /oauth/authorize —— 授权码流程入口。 -pub fn authorize(r: *mut ngx_http_request_t) -> Status { - let p = http::params(r); - let client_id = p.get("client_id").cloned().unwrap_or_default(); - let redirect_uri = p.get("redirect_uri").cloned().unwrap_or_default(); - let response_type = p.get("response_type").map(String::as_str).unwrap_or("code"); - let state_param = p.get("state").cloned().unwrap_or_default(); - let scope = p.get("scope").cloned().unwrap_or_else(|| "openid".to_owned()); - let nonce = p.get("nonce").cloned().unwrap_or_default(); - let code_challenge = p.get("code_challenge").cloned().unwrap_or_default(); - let code_challenge_method = p.get("code_challenge_method").map(String::as_str).unwrap_or("plain"); - - let client = match oauth_clients::get(&client_id) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_client", "未知 client_id"), - }; - - if !client.allows_redirect(&redirect_uri) { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_redirect_uri", "回调地址未注册"); - } - if response_type != "code" { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "unsupported_response_type", "仅支持 code"); - } - // scope 必须全部在白名单内。按逗号与空白一起切:MaxKey 文档示例与 - // ssw-admin/JNPF 客户端实际发的是 "openid,profile,email"(逗号分隔), - // 只按空白切会把整串当一个 scope,精确匹配必挂 invalid_scope。 - for s in scope.split(|c: char| c == ',' || c.is_whitespace()).filter(|s| !s.is_empty()) { - if !client.allows_scope(s) { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_scope", &format!("不允许的 scope: {s}")); - } - } - // PKCE:公开客户端强制 S256;机密客户端也建议 - if client.confidential && code_challenge.is_empty() { - // 机密客户端允许无 PKCE(靠 client_secret) - } else if code_challenge.is_empty() { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_request", "公开客户端必须携带 code_challenge"); - } else if !OAUTH_CODE_CHALLENGE_METHODS.contains(&code_challenge_method) { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_request", "不支持的 code_challenge_method"); - } - - // 已登录?查 SSO 会话(payload 为 `user\nemail\ngroups\ndept\nname`, - // 与 `sso_payload` / `iap_identity` 同构;这里只取首个字段即 username 作为 sub)。 - let now = util::now(); - let username = match parse_cookie(http::header(r, "cookie").as_deref(), OAUTH_SESSION_COOKIE) - .and_then(|tok| crate::oauth_state::get_oauth_session(&tok, now)) - { - Some(payload) => payload.split('\n').next().unwrap_or("").to_owned(), - None => { - // 未登录 → 302 到登录页,登录后跳回本授权地址 - let back = current_url(r); - let loc = format!("{}/login?redirect={}", issuer(), utilx::url_encode(&back)); - return redirect(r, &loc); - } - }; - - // 已登录 → 发授权码(随机 id,存上下文 60s,单次使用) - let code = util::rand_hex(32); - let ctx = json!({ - "sub": username, - "client_id": client_id, - "redirect_uri": redirect_uri, - "scope": scope, - "nonce": nonce, - "code_challenge": code_challenge, - "code_challenge_method": code_challenge_method, - }) - .to_string(); - if !crate::oauth_state::put_oauth_code(&code, &ctx, now + OAUTH_CODE_TTL) { - return oauth_error(r, HTTPStatus::INTERNAL_SERVER_ERROR, "server_error", "授权码存储失败"); - } - - let mut loc = format!("{redirect_uri}?code={code}"); - if !state_param.is_empty() { - loc.push_str(&format!("&state={}", utilx::url_encode(&state_param))); - } - redirect(r, &loc) -} - -/// POST /oauth/token —— 换发令牌。 -/// POST /oauth/token —— 换发令牌(标准端点,响应带 `{code,msg,data}` 信封)。 -pub fn token(r: *mut ngx_http_request_t) -> Status { - token_impl(r, false) -} - -/// `GET|POST /oauth/v20/token`、`/oauth2.0/accessToken` —— **MaxKey 兼容**的换发端点。 -/// -/// 与标准端的唯一差别:响应体**不套** `{code,msg,data}` 信封,直接返回 -/// `{"access_token":…,"token_type":…,"expires_in":…}`,与 MaxKey 的 -/// `/oauth/v20/token` 一致。照抄 MaxKey 文档、按顶层键取令牌的应用才能零改造跑通。 -/// -/// 鉴权方式两种都收:表单里的 `client_id`/`client_secret`(MaxKey 惯例) -/// 与 `Authorization: Basic`(标准),见 `authenticate_client`。 -pub fn token_v20(r: *mut ngx_http_request_t) -> Status { - token_impl(r, true) -} - -fn token_impl(r: *mut ngx_http_request_t, bare: bool) -> Status { - let p = http::params(r); - let grant_type = p.get("grant_type").map(String::as_str).unwrap_or(""); - let now = util::now(); - - match grant_type { - "authorization_code" => { - let code = p.get("code").cloned().unwrap_or_default(); - let code_verifier = p.get("code_verifier").cloned().unwrap_or_default(); - let redirect_uri = p.get("redirect_uri").cloned().unwrap_or_default(); - - let ctx_raw = match crate::oauth_state::take_oauth_code(&code, now) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "授权码无效或已使用"), - }; - let ctx: Value = match serde_json::from_str(&ctx_raw) { - Ok(v) => v, - Err(_) => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "授权码损坏"), - }; - let sub = ctx.get("sub").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let client_id = ctx.get("client_id").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let stored_redirect = ctx.get("redirect_uri").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let scope = ctx.get("scope").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let nonce = ctx.get("nonce").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let ch = ctx.get("code_challenge").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let chm = ctx.get("code_challenge_method").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - - // 客户端必须一致 - let client = match authenticate_client(r, &p) { - Some(c) if c.client_id == client_id => c, - _ => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), - }; - if !redirect_uri.is_empty() && redirect_uri != stored_redirect { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "redirect_uri 不匹配"); - } - // PKCE 校验 - if !ch.is_empty() { - if !verify_pkce(&code_verifier, &ch, &chm) { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "PKCE 校验失败"); - } - } else if client.confidential { - // 机密客户端无 PKCE 但已通过 client_secret 校验,放行 - } else { - return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "缺少 PKCE"); - } - - issue_tokens(r, &sub, &client, &scope, &nonce, now, bare) - } - - "refresh_token" => { - let refresh = p.get("refresh_token").cloned().unwrap_or_default(); - let claims = match jwt_verify(&refresh) { - Some(c) if c.get("typ").and_then(|v| v.as_str()) == Some("refresh") => c, - _ => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "refresh_token 无效"), - }; - let sub = claims.get("sub").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); - let client = match authenticate_client(r, &p) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), - }; - let scope = claims.get("scope").and_then(|v| v.as_str()).unwrap_or("openid").to_owned(); - issue_tokens(r, &sub, &client, &scope, "", now, bare) - } - - "client_credentials" => { - let client = match authenticate_client(r, &p) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), - }; - if !client.allows_grant("client_credentials") { - return oauth_error(r, HTTPStatus::UNAUTHORIZED, "unauthorized_client", "该客户端不允许 client_credentials"); - } - let scope = p.get("scope").cloned().unwrap_or_else(|| "openid".to_owned()); - let Some(access) = mint_access_token( - &client.client_id, "", &client.name, &[], "", "", &client.client_id, &scope, now, - ) else { - return oauth_error(r, HTTPStatus::INTERNAL_SERVER_ERROR, "server_error", "令牌签发不可用"); - }; - let body = json!({ - "access_token": access, - "token_type": "Bearer", - "expires_in": OAUTH_ACCESS_TTL, - "scope": scope, - }); - send_token_body(r, body, bare) - } - - "password" => { - let client = match authenticate_client(r, &p) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), - }; - if !client.allows_grant("password") { - return oauth_error(r, HTTPStatus::UNAUTHORIZED, "unauthorized_client", "该客户端不允许 password"); - } - let uname = p.get("username").cloned().unwrap_or_default(); - let pass = p.get("password").cloned().unwrap_or_default(); - let user = match users::get(&uname) { - Some(u) => u, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "用户不存在"), - }; - // 账号锁定:password grant 同样不允许绕过(与浏览器登录一致) - if user.is_locked(now) { - return oauth_error(r, HTTPStatus(423), "account_locked", "账号已锁定,请稍后重试"); - } - if !util::verify_password(&pass, &user.salt, &user.pwd_hash) { - let _ = accounts::record_login_failure(&uname, now); - return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "密码错误"); - } - // TOTP 第二因子:password grant 同样不允许绕过 - if crate::otp::is_enabled(&user) { - let code = p.get("totp").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - if !crate::otp::verify(&crate::otp::secret(&user), &code, now as u64) { - return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "动态验证码不正确或已过期"); - } - } - let _ = accounts::clear_login_failure(&uname); - let scope = p.get("scope").cloned().unwrap_or_else(|| "openid profile email".to_owned()); - issue_tokens(r, &user.username, &client, &scope, "", now, bare) - } - - _ => oauth_error(r, HTTPStatus::BAD_REQUEST, "unsupported_grant_type", "不支持的 grant_type"), - } -} - -/// 发 access_token + id_token + refresh_token。 -/// 令牌响应体:`bare=true` 输出裸对象(MaxKey 形状),否则套 `{code,msg,data}` 信封。 -fn send_token_body(r: *mut ngx_http_request_t, body: Value, bare: bool) -> Status { - if bare { - http::send(r, HTTPStatus::OK, &body.to_string()) - } else { - http::ok(r, body, "ok") - } -} - -fn issue_tokens( - r: *mut ngx_http_request_t, - sub: &str, - client: &crate::oauth_state::OAuthClient, - scope: &str, - nonce: &str, - now: i64, - bare: bool, -) -> Status { - let user = users::get(sub); - let (email, name, groups, department, mobile) = match &user { - Some(u) => (u.email().to_owned(), u.display_or_username(), u.groups(), u.department().to_owned(), u.mobile().to_owned()), - None => (String::new(), sub.to_owned(), vec![], String::new(), String::new()), - }; - let (Some(access), Some(refresh)) = ( - mint_access_token(sub, &email, &name, &groups, &department, &mobile, &client.client_id, scope, now), - mint_refresh_token(sub, &client.client_id, now), - ) else { - return oauth_error(r, HTTPStatus::INTERNAL_SERVER_ERROR, "server_error", "令牌签发不可用"); - }; - // 与 authorize 的切分口径保持一致(逗号分隔串里 "openid" 不在空白边界上) - let has_openid = scope.split(|c: char| c == ',' || c.is_whitespace()).any(|s| s == "openid"); - let mut body = json!({ - "access_token": access, - "token_type": "Bearer", - "expires_in": OAUTH_ACCESS_TTL, - "refresh_token": refresh, - "scope": scope, - }); - if has_openid { - if let Some(idt) = mint_id_token(sub, &email, &name, &client.client_id, nonce, now) { - body["id_token"] = json!(idt); - } - } - audit::log("oauth.token", sub, &client.client_id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), scope); - send_token_body(r, body, bare) -} - -/// GET /oauth/userinfo —— Bearer token → 用户声明。 -pub fn userinfo(r: *mut ngx_http_request_t) -> Status { - let token = match access_token_of(r) { - Some(t) => t, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "缺少 Bearer 或 access_token"), - }; - let claims = match jwt_verify(&token) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "令牌无效或过期"), - }; - let out = json!({ - "sub": claims.get("sub").cloned().unwrap_or(Value::Null), - "preferred_username": claims.get("preferred_username").cloned().unwrap_or(Value::Null), - "name": claims.get("name").cloned().unwrap_or(Value::Null), - "email": claims.get("email").cloned().unwrap_or(Value::Null), - "department": claims.get("department").cloned().unwrap_or(Value::Null), - "groups": claims.get("groups").cloned().unwrap_or(Value::Null), - }); - http::ok(r, out, "ok") -} - -/// `GET|POST /oauth/v20/me` —— **MaxKey 兼容**的用户信息端点。 -/// -/// 与标准 `userinfo` 的两点差异,都是为了照抄 MaxKey 文档的应用能直接跑通: -/// 1. 令牌可走 `access_token` 查询/表单参数(MaxKey 惯例),不必 Bearer 头; -/// 2. 返回**扁平** JSON(`username`/`userid`/`realname`/`email`/`mobile`), -/// 不套本服务的 `{code,msg,data}` 信封 —— MaxKey 的 `/me` 就是裸对象。 -/// -/// 标准 OIDC 声明同时保留(`sub`/`preferred_username`/`email`…), -/// 于是同一个响应既能被 MaxKey 客户端解析,也能被标准 OIDC 客户端解析。 -pub fn userinfo_v20(r: *mut ngx_http_request_t) -> Status { - let token = match access_token_of(r) { - Some(t) => t, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "缺少 access_token"), - }; - let claims = match jwt_verify(&token) { - Some(c) => c, - None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "令牌无效或过期"), - }; - let g = |k: &str| claims.get(k).cloned().unwrap_or(Value::Null); - // 手机号:access_token claims 带 mobile(签发时从用户档案取),空则透出 null。 - let mobile = g("mobile"); - let out = json!({ - // MaxKey 语义:username / userid 是**登录账号**,realname 才是真实姓名。 - // 显示名塞进 username 会让第三方系统按账号查找用户时匹配不上。 - "username": g("sub"), - "userid": g("sub"), - // `id`/`userId`:MaxKey /me 返回用户主键,uc 等接入方按它做全局身份 - // 映射(maxkey_user_id)。本网关以 username 为稳定主键(不可改), - // 与 `sub`/`userid` 同值。 - "id": g("sub"), - "userId": g("sub"), - // `displayName`/`fullName`:MaxKey 客户端的展示名取值顺序里常见的键。 - "displayName": g("name"), - "fullName": g("name"), - "realname": g("name"), - "email": g("email"), - "mobile": mobile, - // ---- 标准 OIDC 声明 ---- - "sub": g("sub"), - "preferred_username": g("preferred_username"), - "name": g("name"), - "department": g("department"), - "groups": g("groups"), - "iss": g("iss"), - "aud": g("aud"), - "exp": g("exp"), - }); - http::send(r, HTTPStatus::OK, &out.to_string()) -} - -/// POST /oauth/introspect —— RFC 7662 令牌自省。 -pub fn introspect(r: *mut ngx_http_request_t) -> Status { - let p = http::params(r); - let token = p.get("token").cloned().unwrap_or_default(); - // 自省端点也需客户端鉴权(防令牌探测) - if authenticate_client(r, &p).is_none() { - return http::fail(r, HTTPStatus::UNAUTHORIZED, "客户端校验失败"); - } - match jwt_verify(&token) { - Some(c) => { - let active = json!({ - "active": true, - "iss": c.get("iss").cloned().unwrap_or(Value::Null), - "sub": c.get("sub").cloned().unwrap_or(Value::Null), - "aud": c.get("aud").cloned().unwrap_or(Value::Null), - "client_id": c.get("client_id").cloned().unwrap_or(Value::Null), - "username": c.get("preferred_username").cloned().unwrap_or(Value::Null), - "email": c.get("email").cloned().unwrap_or(Value::Null), - "department": c.get("department").cloned().unwrap_or(Value::Null), - "groups": c.get("groups").cloned().unwrap_or(Value::Null), - "scope": c.get("scope").cloned().unwrap_or(Value::Null), - "token_type": "Bearer", - "iat": c.get("iat").cloned().unwrap_or(Value::Null), - "exp": c.get("exp").cloned().unwrap_or(Value::Null), - }); - http::ok(r, active, "ok") - } - None => http::ok(r, json!({ "active": false }), "ok"), - } -} - -/// GET /.well-known/openid-configuration —— OIDC discovery。 -pub fn discovery(r: *mut ngx_http_request_t) -> Status { - let iss = issuer(); - // jwks_uri 与签名算法声明按实际模式给出:HS256 兼容模式下 jwks_uri 为 null - let (jwks_uri, algs): (Value, Vec<&str>) = match sign_key().map(|k| k.alg) { - Some("RS256") => (json!(format!("{iss}/.well-known/jwks.json")), vec!["RS256", "HS256"]), - _ => (Value::Null, vec!["HS256"]), - }; - let doc = json!({ - "issuer": iss, - "authorization_endpoint": format!("{iss}/oauth/authorize"), - "token_endpoint": format!("{iss}/oauth/token"), - "userinfo_endpoint": format!("{iss}/oauth/userinfo"), - "introspection_endpoint": format!("{iss}/oauth/introspect"), - "jwks_uri": jwks_uri, - "response_types_supported": ["code"], - "grant_types_supported": ["authorization_code", "refresh_token", "client_credentials", "password"], - "scopes_supported": OAUTH_SCOPES_SUPPORTED, - "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"], - "code_challenge_methods_supported": OAUTH_CODE_CHALLENGE_METHODS, - "id_token_signing_alg_values_supported": algs, - "subject_types_supported": ["public"], - "claims_supported": [ - "sub", "iss", "aud", "exp", "iat", "preferred_username", - "email", "email_verified", "name", "department", "groups" - ], - }); - http::ok(r, doc, "ok") -} - -/// `GET /oauth/jwks`(别名 `/.well-known/jwks.json`)——发布 RS256 公钥。 -/// -/// 输出 active 公钥 + 历史公钥(`jwk_dir/*.pub.jwk.json`,轮换期旧令牌验签用)。 -/// HS256 兼容模式下仍 404(对称密钥不能发布),并给出原因说明—— -/// **不给空 JWKS**:客户端会缓存「无密钥」状态,表现为一直验签失败而无日志。 -pub fn jwks(r: *mut ngx_http_request_t) -> Status { - let Some(key) = sign_key() else { - return http::fail(r, HTTPStatus::INTERNAL_SERVER_ERROR, "签名密钥不可用"); - }; - if key.alg != "RS256" { - return http::fail( - r, - HTTPStatus::NOT_FOUND, - "当前为 HS256 对称签名(OAUTH_JWT_ALG=HS256),无公开 JWKS;请用 /oauth/introspect 校验令牌", - ); - } - let rsa = key.rsa.as_ref().expect("RS256 模式必有 RSA 密钥"); - - let mut keys = vec![json!({ - "kty": "RSA", - "use": "sig", - "alg": "RS256", - "kid": rsa.kid, - "n": crate::rsa::to_jwk(rsa).get("n").cloned().unwrap_or_default(), - "e": crate::rsa::to_jwk(rsa).get("e").cloned().unwrap_or_default(), - })]; - - // 历史公钥(轮换过渡) - if let Ok(entries) = std::fs::read_dir(jwk_dir()) { - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - if !name.ends_with(".pub.jwk.json") { - continue; - } - if let Ok(text) = std::fs::read_to_string(entry.path()) { - if let Ok(v) = serde_json::from_str::(&text) { - let jwk = json!({ - "kty": "RSA", - "use": "sig", - "alg": "RS256", - "kid": v.get("kid").cloned().unwrap_or_default(), - "n": v.get("n").cloned().unwrap_or_default(), - "e": v.get("e").cloned().unwrap_or_default(), - }); - keys.push(jwk); - } - } - } - } - - let mut doc = json!({ "keys": keys }).to_string(); - // JWKS 可被第三方长期缓存:轮换通过新 kid 表达,旧 kid 保留至旧令牌过期 - let _ = &mut doc; - http_send_jwks(r, &json!({ "keys": keys }).to_string()) -} - -fn http_send_jwks(r: *mut ngx_http_request_t, body: &str) -> Status { - http::send_with( - r, - HTTPStatus::OK, - body, - &[("Cache-Control", "public, max-age=3600")], - ) -} - -/// GET /login —— 最小化登录页。 -pub fn login_get(r: *mut ngx_http_request_t) -> Status { - let redirect = http::params(r).get("redirect").cloned().unwrap_or_default(); - let html = login_html(&redirect, ""); - // SAFETY: 直接输出 HTML 字符串 - unsafe { - let request = ngx::http::Request::from_ngx_http_request(r); - let pool = request.pool(); - let mut buf = match pool.create_buffer_from_str(&html) { - Some(b) => b, - None => return Status::NGX_ERROR, - }; - buf.set_last_buf(true); - let mut chain = ngx::ffi::ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: std::ptr::null_mut() }; - request.set_status(HTTPStatus::OK); - request.add_header_out("Content-Type", "text/html; charset=utf-8"); - request.set_content_length_n(html.len()); - let st = request.send_header(); - if st != Status::NGX_OK { - return st; - } - request.output_filter(&mut chain) - } -} - -/// POST /login —— 校验口令,建立 SSO 会话。 -pub fn login_post(r: *mut ngx_http_request_t) -> Status { - let p = http::params(r); - let username = p.get("username").cloned().unwrap_or_default(); - let password = p.get("password").cloned().unwrap_or_default(); - let redirect = p.get("redirect").cloned().unwrap_or_default(); - let now0 = util::now(); - - let user = match users::get(&username) { - Some(u) => u, - None => { - audit::log("sso.login", &username, &username, false, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), "账号不存在"); - return login_failed(r, "账号或密码错误", &redirect); - } - }; - - // 图形验证码(OAUTH_CAPTCHA=1 时强制) - if crate::captcha::enabled() { - let cid = p.get("captcha_id").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let code = p.get("captcha_code").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - if !crate::captcha::verify(&cid, &code) { - audit::log("sso.login", &username, &username, false, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), "验证码错误"); - return login_failed(r, "验证码不正确或已过期,请刷新后重试", &redirect); - } - } - - // 账号维度锁定:与管理台登录(api::h_login)同一套阈值与文案 - if user.is_locked(now0) { - let remain = user.locked_until() - now0; - audit::log("sso.login", &username, &username, false, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), "账号锁定中"); - return login_failed(r, &format!("账号已锁定,请 {remain} 秒后重试"), &redirect); - } - - if !util::verify_password(&password, &user.salt, &user.pwd_hash) { - let _ = accounts::record_login_failure(&username, now0); - audit::log("sso.login", &username, &username, false, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), "密码错误"); - return login_failed(r, "账号或密码错误", &redirect); - } - - // TOTP 第二因子:启用后必须携带有效动态码 - if crate::otp::is_enabled(&user) { - let code = p.get("totp").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - if !crate::otp::verify(&crate::otp::secret(&user), &code, now0 as u64) { - audit::log("sso.login", &username, &username, false, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), "动态验证码错误"); - return login_failed(r, "动态验证码不正确或已过期", &redirect); - } - } - - let now = util::now(); - let token = util::rand_hex(32); - let payload = sso_payload(&user); - if !crate::oauth_state::put_oauth_session(&token, &payload, now + OAUTH_SESSION_TTL) { - return login_failed(r, "会话创建失败", &redirect); - } - let cookie = sso_cookie(&token, OAUTH_SESSION_TTL); - util::log_notice(&format!("[oauth] SSO 登录 user={username} client={}", http::remote_addr(r))); - audit::log("sso.login", &username, &username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - - if !redirect.is_empty() && is_safe_redirect(&redirect) { - let headers = vec![("Set-Cookie", cookie.as_str()), ("Location", redirect.as_str())]; - // 用 send_with 发 302 - return http::send_with(r, HTTPStatus(302), "{\"code\":302,\"msg\":\"登录成功\"}", &headers); - } - http::ok_with(r, json!({ "username": username }), "登录成功", &[("Set-Cookie", &cookie)]) -} - -/// POST /oauth/logout —— 销毁 SSO 会话。 -pub fn logout(r: *mut ngx_http_request_t) -> Status { - // 清共享内存里的 SSO 会话(顺带取用户名写审计)。 - let now = util::now(); - let mut who = String::new(); - if let Some(tok) = parse_cookie(http::header(r, "cookie").as_deref(), OAUTH_SESSION_COOKIE) { - if let Some(payload) = crate::oauth_state::get_oauth_session(&tok, now) { - who = payload.split('\n').next().unwrap_or("").to_owned(); - } - crate::oauth_state::remove_oauth_session(&tok); - } - let cleared = format!( - "{OAUTH_SESSION_COOKIE}=deleted; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" - ); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - // 单点注销回跳:消费方(JNPF/uc)登出时把浏览器 302 到这里, - // 带上 `redirect_uri` 让 IdP 清完会话再跳回业务侧。 - // 开放重定向防线:必须是 http(s) 绝对地址,且命中任一已登记 client - // 的回调白名单——登出页不该是免费跳板。 - let p = http::params(r); - let back = p.get("redirect_uri").or_else(|| p.get("redirect")).map(String::as_str).unwrap_or(""); - if !back.is_empty() { - let allowed = (back.starts_with("http://") || back.starts_with("https://")) - && oauth_clients::all().iter().any(|c| c.allows_redirect(back)); - if allowed { - audit::log("oauth.logout", &who, back, true, &ip, &ua, "slo"); - // 302 的同时必须把会话 cookie 清掉:Location 跳转不吞 Set-Cookie, - // 漏了它浏览器侧会话残留,下次点 SSO 登录会静默重登录。 - return http::send_with( - r, - HTTPStatus(302), - "{\"code\":302,\"msg\":\"redirect\"}", - &[("Location", back), ("Set-Cookie", cleared.as_str())], - ); - } - audit::log("oauth.logout", &who, back, false, &ip, &ua, "redirect 拒绝"); - return http::fail(r, HTTPStatus::BAD_REQUEST, "redirect_uri 未登记,拒绝回跳"); - } - - audit::log("oauth.logout", &who, "", true, &ip, &ua, ""); - http::ok_with(r, json!({}), "已退出登录", &[("Set-Cookie", &cleared)]) -} - -// =========================================================================== -// IAP 身份解析(供 lib.rs 的 IapHandler 调用) -// =========================================================================== - -/// 解析 IAP 请求身份:Bearer token 或 SSO 会话。 -/// -/// 返回 `(sub_user, email, groups_csv, sub, access_token)`;无身份返回 None。 -/// - Bearer:直接校验 JWT,token 原样作为注入的 `X-Auth-Token`。 -/// - SSO 会话:读共享内存 payload,重新签发一个 access_token 供后端独立校验。 -pub fn iap_identity(r: *mut ngx_http_request_t) -> Option<(String, String, String, String, String)> { - let now = util::now(); - - if let Some(tok) = bearer_token(r) { - if let Some(c) = jwt_verify(&tok) { - let sub = c.get("sub").and_then(|v| v.as_str()).unwrap_or("").to_owned(); - let email = c.get("email").and_then(|v| v.as_str()).unwrap_or("").to_owned(); - let groups = c - .get("groups") - .and_then(|v| v.as_array()) - .map(|a| a.iter().filter_map(|x| x.as_str()).collect::>().join(",")) - .unwrap_or_default(); - if sub.is_empty() { - return None; - } - return Some((sub.clone(), email, groups, sub, tok)); - } - } - - if let Some(tok) = parse_cookie(http::header(r, "cookie").as_deref(), OAUTH_SESSION_COOKIE) { - if let Some(payload) = crate::oauth_state::get_oauth_session(&tok, now) { - let parts: Vec<&str> = payload.split('\n').collect(); - let username = parts.first().copied().unwrap_or("").to_owned(); - let email = parts.get(1).copied().unwrap_or("").to_owned(); - let groups = parts.get(2).copied().unwrap_or("").to_owned(); - let department = parts.get(3).copied().unwrap_or("").to_owned(); - let name = parts.get(4).copied().unwrap_or("").to_owned(); - if username.is_empty() { - return None; - } - // 会话里没有 access_token(它只存身份),此处按同一套 claims 现签一个, - // 供后端独立验签——后端不必信任网关注入的头,但仍能自己验出同一个身份。 - let access = mint_access_token( - &username, - &email, - &name, - &groups.split(',').filter(|s| !s.is_empty()).map(|s| s.to_owned()).collect::>(), - &department, - "", - IAP_TOKEN_AUDIENCE, - IAP_TOKEN_SCOPE, - now, - )?; - return Some((username.clone(), email, groups, username, access)); - } - } - None -} - -// =========================================================================== -// 工具 -// =========================================================================== - -fn oauth_error(r: *mut ngx_http_request_t, status: HTTPStatus, err: &str, desc: &str) -> Status { - let body = json!({ "error": err, "error_description": desc }).to_string(); - http::fail(r, status, &body) -} - -fn redirect(r: *mut ngx_http_request_t, loc: &str) -> Status { - http::send_with(r, HTTPStatus(302), &format!("{{\"code\":302,\"msg\":\"redirect\",\"location\":\"{loc}\"}}"), &[("Location", loc)]) -} - -fn login_failed(r: *mut ngx_http_request_t, msg: &str, redirect: &str) -> Status { - // 失败时回到登录页并带错误提示。 - // - // 早先这里写成 `login_html("") + "

…"`——拼在 `` - // 之后,浏览器把整段当垃圾节点丢掉,于是「登录失败」和「页面没反应」长得 - // 一模一样。错误提示必须走 login_html 的结构化参数,落在卡片里面。 - let html = login_html(redirect, msg); - unsafe { - let request = ngx::http::Request::from_ngx_http_request(r); - let pool = request.pool(); - let mut buf = match pool.create_buffer_from_str(&html) { - Some(b) => b, - None => return Status::NGX_ERROR, - }; - buf.set_last_buf(true); - let mut chain = ngx::ffi::ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: std::ptr::null_mut() }; - request.set_status(HTTPStatus::UNAUTHORIZED); - request.add_header_out("Content-Type", "text/html; charset=utf-8"); - request.set_content_length_n(html.len()); - let st = request.send_header(); - if st != Status::NGX_OK { - return st; - } - request.output_filter(&mut chain) - } -} - -/// 登录页样式(内联,不额外引入静态文件与一次请求)。 -/// -/// 配色与网关管理台一致:深蓝渐变底 + 白卡片 + 蓝色主按钮。 -const LOGIN_STYLE: &str = r#" - *{box-sizing:border-box} - body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px; - font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; - background:radial-gradient(1100px 560px at 50% -12%,#1e3a8a 0%,#0f172a 58%,#0b1220 100%);color:#1f2937} - .card{width:100%;max-width:380px;background:#fff;border-radius:16px;padding:34px 30px 24px; - box-shadow:0 20px 60px rgba(2,6,23,.45)} - .brand{display:flex;align-items:center;gap:11px;margin-bottom:20px} - .mark{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,#2563eb,#38bdf8); - display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700; - font-size:12px;letter-spacing:.5px;flex:0 0 auto} - h1{font-size:16px;margin:0} - .sub{color:#6b7280;font-size:12px;margin-top:2px} - label{display:block;font-size:12.5px;color:#6b7280;margin:0 0 6px} - input[type=text],input[type=password]{width:100%;padding:10px 12px;margin:0 0 14px; - border:1px solid #cbd5e1;border-radius:8px;font-size:13.5px;outline:none; - transition:border-color .15s,box-shadow .15s} - input[type=text]:focus,input[type=password]:focus{border-color:#2563eb; - box-shadow:0 0 0 3px rgba(37,99,235,.12)} - button{width:100%;padding:11px;border:0;border-radius:8px;background:#2563eb;color:#fff; - font-size:15px;font-weight:600;cursor:pointer;transition:.15s;font-family:inherit} - button:hover{background:#1d4ed8} - .err{background:#fdecec;color:#b91c1c;border:1px solid #f7cfcf;border-radius:8px; - padding:9px 12px;font-size:12.5px;margin-bottom:16px} - .target{margin-top:18px;padding-top:14px;border-top:1px dashed #e3e8ef; - color:#6b7280;font-size:12px;line-height:1.7} - .target b{color:#1f2937} -"#; - -/// 登录页。`error` 非空时在卡片内显示错误条。 -/// -/// `redirect` / `username` / `password` 三个字段名与表单 `action="/login"` 是对外 -/// 契约(e2e 与接入方都在依赖),改样式时不要动。 -fn login_html(redirect: &str, error: &str) -> String { - let red = utilx::html_escape(redirect); - let err = if error.is_empty() { - String::new() - } else { - format!("

{}
", utilx::html_escape(error)) - }; - // 图形验证码块:仅 OAUTH_CAPTCHA=1 时注入。页面 JS 从 /api/captcha 取码 - // 注入 SVG,提交时携带 captcha_id / captcha_code(一次性,失败需刷新)。 - let captcha_block = if crate::captcha::enabled() { - r#" -
- -
- -
- "# - .to_owned() - } else { - String::new() - }; - // 只取主机名展示:登录后要去哪,用户有权知道;但带 query 的长 URL 会铺满一屏。 - let target_block = match redirect - .split_once("://") - .and_then(|(_, rest)| rest.split('/').next()) - .filter(|h| !h.is_empty()) - { - Some(host) => format!( - "
登录成功后将返回 {}
", - utilx::html_escape(host) - ), - None => String::new(), - }; - format!( - "\ - \ - 登录 · 统一认证\ -
\ -
SSO
\ -

统一认证

一次登录,访问全部已接入的应用
\ - {err}\ -
\ - \ - \ - \ - \ - \ - {captcha_block}\ -
\ - \ - {target_block}
" - ) -} - -/// 当前请求的完整 URL(用于登录回跳)。 -fn current_url(r: *mut ngx_http_request_t) -> String { - let host = http::header(r, "host").unwrap_or_else(|| "localhost".to_owned()); - let scheme = http::header(r, "x-forwarded-proto").unwrap_or_else(|| "http".to_owned()); - let scheme = if scheme == "https" { "https" } else { "http" }; - let uri = http::uri(r); - let args = http::args_raw(r); - let args = String::from_utf8_lossy(&args); - if args.is_empty() { - format!("{scheme}://{host}{uri}") - } else { - format!("{scheme}://{host}{uri}?{args}") - } -} - -/// 仅允许跳回同源(含 cookie domain)地址,防开放重定向。 -fn is_safe_redirect(url: &str) -> bool { - if !url.starts_with("http://") && !url.starts_with("https://") { - return false; - } - let dom = cookie_domain(); - if let Some((_, host)) = url.split_once("://") { - let host = host.split('/').next().unwrap_or(""); - if host.ends_with(&dom) && !dom.is_empty() { - return true; - } - // 本机回环与 localhost 同待遇:本地联调(e2e 用 127.0.0.1)必须能走完 - // 「未登录 → 登录 → 回跳」全链路,否则门户页只能落回 JSON。 - if host == "localhost" - || host.starts_with("localhost:") - || host == "127.0.0.1" - || host.starts_with("127.0.0.1:") - || host == "[::1]" - { - return true; - } - } - false -} - -/// PKCE S256/plain 校验。 -fn verify_pkce(verifier: &str, challenge: &str, method: &str) -> bool { - if verifier.is_empty() { - return false; - } - match method { - "S256" => { - let hash = sha256_raw(verifier.as_bytes()); - util::ct_eq(&b64url_encode(&hash), challenge) - } - "plain" => util::ct_eq(verifier, challenge), - _ => false, - } -} diff --git a/rust/crates/plugin-sso/src/oauth_clients.rs b/rust/crates/plugin-sso/src/oauth_clients.rs deleted file mode 100644 index ac3419f..0000000 --- a/rust/crates/plugin-sso/src/oauth_clients.rs +++ /dev/null @@ -1,377 +0,0 @@ -//! OAuth2 客户端注册表:第三方应用接入本网关统一认证的入口。 -//! -//! 对应 MaxKey 的「应用管理」。一个第三方应用(如 Grafana、内部 CRM)在此登记 -//! `client_id` / `client_secret` / 回调地址 / 授权类型 / scope,之后即可按标准 -//! OAuth2 / OIDC 流程对接本网关,无需感知底层用户存储。 -//! -//! 与 `users` 同构:文件是唯一真源,启动时全量装载进共享内存(`ocl:` 前缀), -//! 授权热路径只读内存;写入则**写穿**内存,做到「登记完立刻能授权」。 - -use serde_json::json; - -use crate::oauth_keys::KEY_OAUTH_CLIENT_PREFIX; -use crate::oauth_state::{OAuthClient, OAuthClientTable}; -use ipass_core::state; -use ipass_core::util; - -// =========================================================================== -// 共享内存同步 -// =========================================================================== - -/// 客户端 payload:客户端 JSON 原样进共享内存(低频读,直接反序列化)。 -fn client_payload(c: &OAuthClient) -> String { - serde_json::to_string(c).unwrap_or_default() -} - -/// 全量重载客户端注册表进 `ocl:`。返回装载条数。 -pub fn reload_shm() -> usize { - state::clear_prefix(KEY_OAUTH_CLIENT_PREFIX); - let table = crate::oauth_state::read_oauth_clients(); - let total = table.len(); - let mut loaded = 0; - for c in &table { - if !c.client_id.is_empty() && crate::oauth_state::put_oauth_client(&c.client_id, &client_payload(c)) { - loaded += 1; - } - } - if loaded != total { - util::log_err(&format!( - "[oauth_clients] 装载不全:{loaded}/{total} —— 有客户端将无法发起授权" - )); - } - loaded -} - -// =========================================================================== -// 查询 -// =========================================================================== - -/// 按 client_id 取客户端(低频:授权/令牌端点各一次)。 -pub fn get(client_id: &str) -> Option { - if client_id.is_empty() { - return None; - } - let raw = crate::oauth_state::get_oauth_client(client_id)?; - serde_json::from_str(&raw).ok() -} - -/// 全部客户端(管理台列表用)。 -pub fn all() -> Vec { - crate::oauth_state::read_oauth_clients() -} - -// =========================================================================== -// 应用元数据(管理台新表单字段) -// =========================================================================== - -/// 与凭证无关的应用元数据。单独成结构,避免 `upsert` 参数一路加到 13 个。 -#[derive(Debug, Clone, Default)] -pub struct AppMeta { - pub protocol: String, - pub description: String, - pub logo_url: String, - pub home_url: String, - pub visible_roles: Vec, - pub visible_depts: Vec, - pub visible_groups: Vec, -} - -impl AppMeta { - /// 规整 + 校验。**在写盘前拒掉**,别让一个 `javascript:` 的访问地址 - /// 躺在门户页里等着被点击。 - fn normalized(mut self) -> Result { - self.protocol = self.protocol.trim().to_lowercase(); - if self.protocol.is_empty() { - self.protocol = "oauth2".to_owned(); - } - if self.protocol != "oauth2" && self.protocol != "cas" { - return Err(format!( - "不支持的协议类型:{}(可选 oauth2 / cas)", - self.protocol - )); - } - let clean = |v: Vec| -> Vec { - let mut out: Vec = v - .into_iter() - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(); - out.dedup(); - out - }; - self.visible_roles = clean(self.visible_roles); - self.visible_depts = clean(self.visible_depts); - self.visible_groups = clean(self.visible_groups); - self.description = self.description.trim().to_owned(); - for (label, u) in [("访问地址", &self.home_url), ("图标地址", &self.logo_url)] { - let u = u.trim(); - if !u.is_empty() && !(u.starts_with("http://") || u.starts_with("https://")) { - return Err(format!("{label}必须是 http(s) 绝对地址:{u}")); - } - } - self.logo_url = self.logo_url.trim().to_owned(); - self.home_url = self.home_url.trim().to_owned(); - Ok(self) - } -} - -// =========================================================================== -// 写入(管理接口用) -// =========================================================================== - -/// 生成客户端密钥:`cs_` + 24 字节 hex。 -fn gen_secret() -> String { - format!("cs_{}", util::rand_hex(24)) -} - -/// 注册/更新客户端。传空 `client_secret` 时自动生成(机密客户端)。 -pub fn upsert( - client_id: &str, - name: &str, - redirect_uris: Vec, - grant_types: Vec, - scopes: Vec, - confidential: bool, - secret_in: &str, - meta: AppMeta, -) -> Result { - let meta = meta.normalized()?; - let client_id = util::trim(client_id).to_owned(); - if client_id.is_empty() { - return Err("client_id 不能为空".to_owned()); - } - // 公开客户端(SPA / 移动端,走 PKCE)按定义不持有密钥:既不生成,也在 - // 改为公开时清掉旧密钥——否则管理台上会躺着一个「看着能用、其实没人校验」 - // 的密钥,接入方拿去配到代码里就是白配。 - let secret = if !confidential { - String::new() - } else if secret_in.is_empty() { - gen_secret() - } else { - secret_in.to_owned() - }; - - // 缺省授权类型:标准 Web 客户端最小集 - let mut grant_types = if grant_types.is_empty() { - vec![ - "authorization_code".to_owned(), - "refresh_token".to_owned(), - ] - } else { - grant_types - }; - // client_credentials / password 都要用密钥证明身份,公开客户端用不了; - // 静默留着一个「配了也不会生效」的授权类型,比直接拒掉更难排查。 - if !confidential { - let before = grant_types.len(); - grant_types.retain(|g| g != "client_credentials" && g != "password"); - if grant_types.len() != before { - util::log_warn(&format!( - "[oauth_clients] {client_id} 是公开客户端,已忽略 client_credentials/password" - )); - } - } - // 缺省 scope:openid + 基础信息 - let scopes = if scopes.is_empty() { - vec!["openid".to_owned(), "profile".to_owned(), "email".to_owned()] - } else { - scopes - }; - - // ---- 校验:宁可在这里拒掉,也不要让一个配错的客户端在授权时才发现 ---- - const ALLOWED_GRANTS: [&str; 4] = [ - "authorization_code", - "refresh_token", - "client_credentials", - "password", - ]; - for g in &grant_types { - if !ALLOWED_GRANTS.contains(&g.as_str()) { - return Err(format!( - "不支持的授权类型:{g}(可选 {})", - ALLOWED_GRANTS.join(" / ") - )); - } - } - if grant_types.iter().any(|g| g == "authorization_code") && redirect_uris.is_empty() { - return Err("使用授权码模式时必须至少填一个回调地址".to_owned()); - } - // 回调地址会被原样用于 302 跳转,必须是绝对 http(s) 且不带 fragment—— - // 白名单里混进 `*` 或 `javascript:` 就等于把授权码送给任意站点。 - for u in &redirect_uris { - if !(u.starts_with("http://") || u.starts_with("https://")) { - return Err(format!("回调地址必须是 http(s) 绝对地址:{u}")); - } - if u.contains('#') { - return Err(format!("回调地址不能带 #fragment:{u}")); - } - } - - let created = client_id.clone(); - let out = crate::oauth_state::update_oauth_clients(move |table: &mut OAuthClientTable| { - let now = util::now(); - if let Some(existing) = table.iter_mut().find(|c| c.client_id == created) { - existing.name = name.to_owned(); - existing.redirect_uris = redirect_uris; - existing.grant_types = grant_types; - existing.scopes = scopes; - existing.confidential = confidential; - existing.protocol = meta.protocol.clone(); - existing.description = meta.description.clone(); - existing.logo_url = meta.logo_url.clone(); - existing.home_url = meta.home_url.clone(); - existing.visible_roles = meta.visible_roles.clone(); - existing.visible_depts = meta.visible_depts.clone(); - existing.visible_groups = meta.visible_groups.clone(); - if !confidential { - existing.client_secret = String::new(); - } else if !secret_in.is_empty() { - existing.client_secret = secret.clone(); - } - Ok(existing.clone()) - } else { - let c = OAuthClient { - client_id: created.clone(), - client_secret: secret.clone(), - name: name.to_owned(), - redirect_uris, - grant_types, - scopes, - confidential, - created_at: now, - protocol: meta.protocol.clone(), - description: meta.description.clone(), - logo_url: meta.logo_url.clone(), - home_url: meta.home_url.clone(), - visible_roles: meta.visible_roles.clone(), - visible_depts: meta.visible_depts.clone(), - visible_groups: meta.visible_groups.clone(), - }; - table.push(c.clone()); - Ok(c) - } - })?; - - // 写穿共享内存,使「登记完立刻可授权」,不必重启网关。 - // - // 必须写 `out`——本次落盘后的新值。早先这里写成「`get()` 出来再回写」, - // 而 `get()` 读的正是共享内存:等于把旧值原样写回去。后果是新建的客户端 - // 永远进不了热路径,表现为「管理台显示已保存,但授权请求仍报客户端不存在」。 - if !crate::oauth_state::put_oauth_client(&out.client_id, &client_payload(&out)) { - util::log_err(&format!( - "[oauth_clients] 写共享内存失败:{} —— 本次改动需重载/重启才生效", - out.client_id - )); - } - Ok(out) -} - -/// 重新生成客户端密钥(管理台「重置密钥」)。返回新密钥明文,旧密钥立即失效。 -/// -/// 与 `upsert` 分开是因为 `upsert` 的语义是「传空密钥 = 保持原值」,没法用来 -/// 主动轮换;而重置密钥是常见的应急动作(怀疑泄漏时),不该需要先删再建。 -pub fn rotate_secret(client_id: &str) -> Result { - let id = util::trim(client_id).to_owned(); - if id.is_empty() { - return Err("client_id 不能为空".to_owned()); - } - let secret = gen_secret(); - let next = secret.clone(); - let out = crate::oauth_state::update_oauth_clients(move |table: &mut OAuthClientTable| { - let Some(c) = table.iter_mut().find(|c| c.client_id == id) else { - return Err("客户端不存在".to_owned()); - }; - if !c.confidential { - return Err("公开客户端不持有密钥,无需重置".to_owned()); - } - c.client_secret = next; - Ok(c.clone()) - })?; - - if !crate::oauth_state::put_oauth_client(&out.client_id, &client_payload(&out)) { - util::log_err(&format!( - "[oauth_clients] 重置密钥后写共享内存失败:{}", - out.client_id - )); - } - Ok(secret) -} - -pub fn delete(client_id: &str) -> Result<(), String> { - let id = client_id.to_owned(); - crate::oauth_state::update_oauth_clients(move |table: &mut OAuthClientTable| { - let before = table.len(); - table.retain(|c| c.client_id != id); - if table.len() == before { - return Err("客户端不存在".to_owned()); - } - Ok(()) - })?; - if !crate::oauth_state::remove_oauth_client(client_id) { - util::log_err(&format!( - "[oauth_clients] 从共享内存移除失败:{client_id} —— 该客户端在重载前仍可发起授权" - )); - } - Ok(()) -} - -// =========================================================================== -// CAS service 白名单 / 门户可见应用 -// =========================================================================== - -/// CAS `service` 是否可信:必须命中某个已登记接入方的回调地址。 -/// -/// 热路径**不读文件**——直接遍历 `ocl:` 共享内存镜像(与授权路径同源)。 -/// 没有这道校验时,`/cas/login?service=https://evil.com` 会把已登录用户 -/// 连同 `ST-…` 一起 302 出去,攻击者据此即可换出用户名(开放重定向 + 票据外泄)。 -pub fn allows_cas_service(service: &str) -> bool { - if service.is_empty() { - return false; - } - for (_k, payload, _exp) in state::iter_prefix_ex(KEY_OAUTH_CLIENT_PREFIX) { - if let Ok(c) = serde_json::from_str::(&payload) { - if c.allows_service(service) { - return true; - } - } - } - false -} - -/// 当前用户可见的应用(门户「我的应用」用)。按可见范围过滤,按展示名排序。 -pub fn visible_apps(role: &str, dept: &str, groups: &[String]) -> Vec { - let mut v: Vec = state::iter_prefix_ex(KEY_OAUTH_CLIENT_PREFIX) - .into_iter() - .filter_map(|(_k, payload, _exp)| serde_json::from_str::(&payload).ok()) - .filter(|c| c.visible_to(role, dept, groups)) - .collect(); - v.sort_by(|a, b| { - a.display_name() - .cmp(b.display_name()) - .then_with(|| a.client_id.cmp(&b.client_id)) - }); - v -} - -/// 管理台可见投影(含脱敏后的 secret,便于复制)。 -pub fn view(c: &OAuthClient) -> serde_json::Value { - json!({ - "client_id": c.client_id, - "name": c.name, - "redirect_uris": c.redirect_uris, - "grant_types": c.grant_types, - "scopes": c.scopes, - "confidential": c.confidential, - "client_secret": c.client_secret, - "client_secret_masked": util::mask_key(&c.client_secret), - "created_at": c.created_at, - "created_at_text": util::fmt_time(c.created_at), - "protocol": c.protocol_or_default(), - "description": c.description, - "logo_url": c.logo_url, - "home_url": c.home_url, - "visible_roles": c.visible_roles, - "visible_depts": c.visible_depts, - "visible_groups": c.visible_groups, - }) -} diff --git a/rust/crates/plugin-sso/src/oauth_keys.rs b/rust/crates/plugin-sso/src/oauth_keys.rs deleted file mode 100644 index 48156fa..0000000 --- a/rust/crates/plugin-sso/src/oauth_keys.rs +++ /dev/null @@ -1,59 +0,0 @@ -//! OAuth 相关的共享内存键前缀。 -//! -//! 这些是 **SSO 插件的个性状态**,不属于内核共性——因此它们定义在本插件内, -//! 而不是 `ipass_core::config`: -//! -//! * `ocl:` OAuth 接入方注册表 -//! * `oac:` 授权码(一次性) -//! * `sso:` SSO 终端用户会话 -//! -//! 内核只提供 `state::put/get` 等通用读写原语,前缀本身由插件自管。 -//! 前缀字符串务必与历史 `config` 里的定义一致,否则存量共享内存里的键读不出来 -//! (表现为「刚写入就查不到」)。 - -/// OAuth 接入方注册表:`ocl:` -pub const KEY_OAUTH_CLIENT_PREFIX: &[u8] = b"ocl:"; -/// 授权码(一次性):`oac:` -pub const KEY_OAUTH_CODE_PREFIX: &[u8] = b"oac:"; -/// SSO 终端用户会话:`sso:` -pub const KEY_OAUTH_SESS_PREFIX: &[u8] = b"sso:"; - -// =========================================================================== -// OAuth / IAP 协议常量(SSO 插件个性,不进内核 `ipass_core::config`) -// -// 以下常量原属 `ipass_core::config`,收窄内核时迁到本插件。取值与迁移前 -// 完全一致(参考 `refs/ipass` 的历史定义),保证 discovery / token / 会话 -// 行为与重构前等价。 -// =========================================================================== - -/// SSO 终端用户会话 Cookie 名(HttpOnly + SameSite=Lax,Domain 由 nginx.conf 控制) -pub const OAUTH_SESSION_COOKIE: &str = "sso_sid"; -/// SSO 会话时长(秒) -pub const OAUTH_SESSION_TTL: i64 = 8 * 3600; -/// 授权码有效期(秒)——极短,防截获重放 -pub const OAUTH_CODE_TTL: i64 = 60; -/// access_token 有效期(秒) -pub const OAUTH_ACCESS_TTL: i64 = 3600; -/// refresh_token 有效期(秒) -pub const OAUTH_REFRESH_TTL: i64 = 30 * 86400; -/// id_token 有效期(秒) -pub const OAUTH_ID_TOKEN_TTL: i64 = 3600; - -/// 签名密钥环境变量名:HS256 共用一把对称密钥。不设则启动时随机生成并打告警, -/// 重启会使所有已签发 token 失效(生产必须显式设置)。 -pub const OAUTH_SIGNING_SECRET_ENV: &str = "OAUTH_SIGNING_SECRET"; -/// 签发者(issuer)环境变量名:discovery 文档与 token 的 `iss` 用它。 -pub const OAUTH_ISSUER_ENV: &str = "OAUTH_ISSUER"; -pub const OAUTH_DEFAULT_ISSUER: &str = "http://localhost:18098"; - -/// 支持的 scope(openid 是 OIDC 必备) -pub const OAUTH_SCOPES_SUPPORTED: &[&str] = &["openid", "profile", "email", "address", "phone"]; -/// 支持的 PKCE 挑战方法(S256 优先,plain 仅兼容遗留客户端) -pub const OAUTH_CODE_CHALLENGE_METHODS: &[&str] = &["S256", "plain"]; - -/// Cookie Domain 环境变量名(不设则 Cookie 不带 Domain,仅作用于当前 host) -pub const OAUTH_COOKIE_DOMAIN_ENV: &str = "OAUTH_COOKIE_DOMAIN"; - -/// IAP 签发 token 的 audience / scope 声明(供后端独立验签) -pub const IAP_TOKEN_AUDIENCE: &str = "sso-gateway"; -pub const IAP_TOKEN_SCOPE: &str = "openid profile email"; diff --git a/rust/crates/plugin-sso/src/oauth_state.rs b/rust/crates/plugin-sso/src/oauth_state.rs deleted file mode 100644 index af9cbcb..0000000 --- a/rust/crates/plugin-sso/src/oauth_state.rs +++ /dev/null @@ -1,210 +0,0 @@ -//! OAuth 状态与存储(SSO 插件个性,**不进内核**)。 -//! -//! 内核只提供通用共享内存原语 `state::put/get/remove/clear_prefix` 与通用文件 -//! 接口 `store::read_plugin/update_plugin`,本模块用它们实现 OAuth 专属读写: -//! -//! * `ocl:` 接入方注册表镜像(`get/put/remove_oauth_client`) -//! * `oac:` 授权码(`put/take_oauth_code`,一次性) -//! * `sso:` 终端用户会话(`get/put/remove_oauth_session`) -//! * `data/oauth_clients.json` 注册表真源(`read/update_oauth_clients`) -//! -//! 这些原本是内核 `state` / `store` 里的 OAuth 段;收窄内核时按「个性代码 -//! 插件自己实现」整体迁到此处。语义(前缀、TTL、一次性消费)与迁移前完全一致。 - -use serde::{Deserialize, Serialize}; - -use crate::oauth_keys::{ - KEY_OAUTH_CLIENT_PREFIX, KEY_OAUTH_CODE_PREFIX, KEY_OAUTH_SESS_PREFIX, -}; -use ipass_core::state; -use crate::storex; - -// =========================================================================== -// 数据模型(原内核 `models::OAuthClient`;属插件个性,迁到本插件) -// =========================================================================== - -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -pub struct OAuthClient { - pub client_id: String, - pub client_secret: String, - pub name: String, - pub redirect_uris: Vec, - pub grant_types: Vec, - pub scopes: Vec, - pub confidential: bool, - pub created_at: i64, - - // ---- 应用管理增强(2026-09-14):以下字段全部 `#[serde(default)]`, - // 保证存量 `oauth_clients.json`(无这些键)照旧能反序列化。 - /// 协议类型:`oauth2`(缺省,含 OIDC)| `cas`。决定管理台给出的接入说明, - /// 以及门户里「点击卡片如何进入应用」。 - #[serde(default)] - pub protocol: String, - /// 应用描述(门户卡片副标题)。 - #[serde(default)] - pub description: String, - /// 应用图标 URL(门户卡片)。 - #[serde(default)] - pub logo_url: String, - /// 应用访问地址(门户点击直达)。OAuth 应用由**应用侧**发起授权,网关无从 - /// 推导入口地址,所以要显式登记。 - #[serde(default)] - pub home_url: String, - /// 可见范围:三项**全空 = 全员可见**;非空则「属于任一白名单」即可见。 - #[serde(default)] - pub visible_roles: Vec, - #[serde(default)] - pub visible_depts: Vec, - #[serde(default)] - pub visible_groups: Vec, -} - -pub type OAuthClientTable = Vec; - -impl OAuthClient { - /// 校验 scope 是否全部落在白名单内(openid 始终允许,OIDC 必备) - pub fn allows_scope(&self, scope: &str) -> bool { - if scope == "openid" { - return true; - } - self.scopes.iter().any(|s| s == scope) - } - - /// 校验重定向地址是否在注册清单内(精确匹配,不做前缀/通配) - pub fn allows_redirect(&self, uri: &str) -> bool { - self.redirect_uris.iter().any(|u| u == uri) - } - - /// 是否允许该授权类型 - pub fn allows_grant(&self, grant: &str) -> bool { - self.grant_types.iter().any(|g| g == grant) - } - - /// 协议类型(缺省视为 `oauth2`)。 - pub fn protocol_or_default(&self) -> &str { - if self.protocol.is_empty() { "oauth2" } else { &self.protocol } - } - - /// 展示名:名称优先,回落 client_id(门户排序/卡片标题共用)。 - pub fn display_name(&self) -> &str { - if self.name.is_empty() { &self.client_id } else { &self.name } - } - - /// 是否为 CAS service 白名单成员。 - /// - /// 匹配规则:**精确相等**,或**去掉 query/fragment 后**相等。后者是必要的—— - /// CAS 客户端的 `service` 常带自定义参数(`https://app/cb?tab=1`),而登记时 - /// 只填基地址(`https://app/cb`);不做归一化会把合法客户端挡在门外。 - /// 但绝不做前缀/通配匹配:`https://app/cb` 不能命中 `https://app/cb-evil`。 - pub fn allows_service(&self, service: &str) -> bool { - let base = |u: &str| -> String { - u.split(['?', '#']) - .next() - .unwrap_or("") - .trim_end_matches('/') - .to_owned() - }; - let target = base(service); - if target.is_empty() { - return false; - } - self.redirect_uris - .iter() - .any(|u| u == service || base(u) == target) - } - - /// 门户可见性。三项白名单全空 = 全员可见;否则当前用户的角色 / 部门 / - /// 用户组**落在任一白名单内**即可见(OR 语义,便于「角色 + 例外人员」组合)。 - pub fn visible_to(&self, role: &str, dept: &str, groups: &[String]) -> bool { - if self.visible_roles.is_empty() - && self.visible_depts.is_empty() - && self.visible_groups.is_empty() - { - return true; - } - if self.visible_roles.iter().any(|r| r == role) { - return true; - } - if !dept.is_empty() && self.visible_depts.iter().any(|d| d == dept) { - return true; - } - groups - .iter() - .any(|g| self.visible_groups.iter().any(|w| w == g)) - } -} - - -// =========================================================================== -// 注册表(文件真源:data/oauth_clients.json) -// =========================================================================== - -/// 读取注册表文件(内核只提供带锁原子读,不认识结构)。 -pub fn read_oauth_clients() -> OAuthClientTable { - storex::read_plugin::("oauth_clients.json") -} - -/// 加锁「读-改-写」注册表文件,闭包返回新值;`Err` 不落盘。 -pub fn update_oauth_clients(f: F) -> Result -where - F: FnOnce(&mut OAuthClientTable) -> Result, -{ - let mut table = read_oauth_clients(); - let out = f(&mut table)?; - storex::write_plugin("oauth_clients.json", &table)?; - Ok(out) -} - -// =========================================================================== -// 注册表共享内存镜像(`ocl:`) -// =========================================================================== - -/// 按 client_id 取客户端 JSON(低频:授权/令牌端点各一次)。 -pub fn get_oauth_client(client_id: &str) -> Option { - state::get(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes()).map(|(p, _)| p) -} - -/// 写入/覆盖客户端 JSON。 -pub fn put_oauth_client(client_id: &str, payload: &str) -> bool { - state::put(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes(), payload.as_bytes(), 0) -} - -/// 删除客户端(重载/删除时)。 -pub fn remove_oauth_client(client_id: &str) -> bool { - state::remove(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes()) -} - -// =========================================================================== -// 授权码(`oac:`,一次性) -// =========================================================================== - -/// 写入授权码上下文(含 sub / client_id / redirect_uri / scope / nonce / PKCE 挑战)。 -pub fn put_oauth_code(code: &str, ctx: &str, expires_at: i64) -> bool { - state::put(KEY_OAUTH_CODE_PREFIX, code.as_bytes(), ctx.as_bytes(), expires_at) -} - -/// 取出并消费授权码(一次性):过期或不存在返回 None。 -pub fn take_oauth_code(code: &str, now: i64) -> Option { - let raw = state::get_live(KEY_OAUTH_CODE_PREFIX, code.as_bytes(), now)?; - state::remove(KEY_OAUTH_CODE_PREFIX, code.as_bytes()); - Some(raw) -} - -// =========================================================================== -// 终端用户会话(`sso:`,对应 SSO 登录态) -// =========================================================================== - -/// 写入 SSO 会话。 -pub fn put_oauth_session(token: &str, payload: &str, expires_at: i64) -> bool { - state::put(KEY_OAUTH_SESS_PREFIX, token.as_bytes(), payload.as_bytes(), expires_at) -} - -/// 读取(未过期才返回)。 -pub fn get_oauth_session(token: &str, now: i64) -> Option { - state::get_live(KEY_OAUTH_SESS_PREFIX, token.as_bytes(), now) -} - -/// 删除会话。 -pub fn remove_oauth_session(token: &str) -> bool { - state::remove(KEY_OAUTH_SESS_PREFIX, token.as_bytes()) -} diff --git a/rust/crates/plugin-sso/src/otp.rs b/rust/crates/plugin-sso/src/otp.rs deleted file mode 100644 index 84e968d..0000000 --- a/rust/crates/plugin-sso/src/otp.rs +++ /dev/null @@ -1,328 +0,0 @@ -//! TOTP 动态口令(RFC 6238 / HOTP RFC 4226)——对齐 MaxKey `maxkey-starter-otp` -//! 的算法语义:SHA1 + 30 秒步长 + 6 位截断(Google Authenticator 默认参数)。 -//! -//! ## 零依赖的实现成本 -//! -//! `sha2` crate 没有 SHA-1,而 RFC 6238 的主流参数就是 HMAC-SHA1—— -//! 不手写就只能引入新依赖,违背「零新增依赖」约定。SHA-1 此处**只用于 OTP**, -//! 口令哈希仍是迭代 SHA-256,不受 SHA-1 碰撞攻击面影响。 -//! -//! ## 时间窗 -//! -//! 校验时允许 ±1 步(±30s)时钟偏移——手机与服务器时钟不同步是常态, -//! 对齐 MaxKey `TimeBasedOTP` 的 window 语义。码本身一次性语义由调用方保证 -//! (防同一码在窗口内重放,见 users 层的 last_totp_step,未实现前暂不防重放)。 - -use serde_json::Value; - -use crate::accounts::UserExt; -use ipass_core::models::User; -use ipass_core::users; -use ipass_core::util; - -// =========================================================================== -// SHA-1(RFC 3174,仅 OTP 使用) -// =========================================================================== - -/// SHA-1 摘要。实现为标准 80 轮循环,输入任意长度。 -fn sha1(data: &[u8]) -> [u8; 20] { - // 消息填充:0x80 + 0x00... + 64 位大端长度 - let bit_len = (data.len() as u64) * 8; - let mut msg = data.to_vec(); - msg.push(0x80); - while msg.len() % 64 != 56 { - msg.push(0); - } - msg.extend_from_slice(&bit_len.to_be_bytes()); - - let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; - - for chunk in msg.chunks_exact(64) { - let mut w = [0u32; 80]; - for (i, word) in w.iter_mut().take(16).enumerate() { - *word = u32::from_be_bytes([ - chunk[i * 4], - chunk[i * 4 + 1], - chunk[i * 4 + 2], - chunk[i * 4 + 3], - ]); - } - for i in 16..80 { - w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1); - } - - let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]); - for (i, &wi) in w.iter().enumerate() { - let (f, k) = match i { - 0..=19 => ((b & c) | ((!b) & d), 0x5A827999u32), - 20..=39 => (b ^ c ^ d, 0x6ED9EBA1), - 40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC), - _ => (b ^ c ^ d, 0xCA62C1D6), - }; - let tmp = a - .rotate_left(5) - .wrapping_add(f) - .wrapping_add(e) - .wrapping_add(k) - .wrapping_add(wi); - e = d; - d = c; - c = b.rotate_left(30); - b = a; - a = tmp; - } - h[0] = h[0].wrapping_add(a); - h[1] = h[1].wrapping_add(b); - h[2] = h[2].wrapping_add(c); - h[3] = h[3].wrapping_add(d); - h[4] = h[4].wrapping_add(e); - } - - let mut out = [0u8; 20]; - for (i, v) in h.iter().enumerate() { - out[i * 4..i * 4 + 4].copy_from_slice(&v.to_be_bytes()); - } - out -} - -/// HMAC-SHA1(RFC 2104,块长 64) -fn hmac_sha1(key: &[u8], data: &[u8]) -> [u8; 20] { - const BLOCK: usize = 64; - let mut k = [0u8; BLOCK]; - if key.len() > BLOCK { - k[..20].copy_from_slice(&sha1(key)); - } else { - k[..key.len()].copy_from_slice(key); - } - let mut inner_key = [0u8; BLOCK]; - let mut outer_key = [0u8; BLOCK]; - for i in 0..BLOCK { - inner_key[i] = k[i] ^ 0x36; - outer_key[i] = k[i] ^ 0x5c; - } - let mut inner = inner_key.to_vec(); - inner.extend_from_slice(data); - let inner_h = sha1(&inner); - let mut outer = outer_key.to_vec(); - outer.extend_from_slice(&inner_h); - sha1(&outer) -} - -// =========================================================================== -// Base32(RFC 4648,标准字母表,解码容忍缺省 padding) -// =========================================================================== - -const B32_ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; - -pub fn base32_encode(data: &[u8]) -> String { - let mut out = String::new(); - let mut acc: u32 = 0; - let mut bits = 0u32; - for &b in data { - acc = (acc << 8) | b as u32; - bits += 8; - while bits >= 5 { - bits -= 5; - out.push(B32_ALPHABET[((acc >> bits) & 0x1f) as usize] as char); - } - } - if bits > 0 { - out.push(B32_ALPHABET[((acc << (5 - bits)) & 0x1f) as usize] as char); - } - out -} - -/// 解码:忽略 `=` padding 与空白,长度非法(非 5 的倍数余量)返回 None。 -pub fn base32_decode(input: &str) -> Option> { - let mut out = Vec::new(); - let mut acc: u32 = 0; - let mut bits = 0u32; - for c in input.chars() { - if c == '=' || c.is_whitespace() { - continue; - } - let v = B32_ALPHABET - .iter() - .position(|&x| x == c.to_ascii_uppercase() as u8)? as u32; - acc = (acc << 5) | v; - bits += 5; - if bits >= 8 { - bits -= 8; - out.push(((acc >> bits) & 0xff) as u8); - } - } - Some(out) -} - -// =========================================================================== -// HOTP / TOTP -// =========================================================================== - -/// HOTP:8 字节大端计数器 → HMAC-SHA1 → RFC 4226 动态截断 → `digits` 位十进制。 -pub fn hotp(secret: &[u8], counter: u64, digits: usize) -> u32 { - let h = hmac_sha1(secret, &counter.to_be_bytes()); - let offset = (h[19] & 0x0f) as usize; - let bin = ((h[offset] as u32 & 0x7f) << 24) - | ((h[offset + 1] as u32) << 16) - | ((h[offset + 2] as u32) << 8) - | h[offset + 3] as u32; - (bin % 10u32.pow(digits as u32)) as u32 -} - -/// TOTP 步长(秒)——RFC 6238 与 Google Authenticator 默认值 -pub const STEP: u64 = 30; -/// 允许的时钟偏移步数(±1 步 = ±30s) -pub const WINDOW: u64 = 1; - -/// TOTP:`unix_ts / 30` 作为计数器。返回**零填充**的 6 位码。 -pub fn totp(secret: &[u8], unix_ts: u64) -> String { - format!("{:06}", hotp(secret, unix_ts / STEP, 6)) -} - -/// 校验 TOTP:种子为 Base32 字符串;当前时间 ± `WINDOW` 步内任一匹配即通过 -/// (容忍时钟偏移)。 -pub fn verify(secret_b32: &str, code: &str, unix_ts: u64) -> bool { - let Some(secret) = base32_decode(secret_b32) else { - return false; - }; - let Ok(answer) = code.trim().parse::() else { - return false; - }; - let counter = unix_ts / STEP; - (counter.saturating_sub(WINDOW)..=counter + WINDOW).any(|c| hotp(&secret, c, 6) == answer) -} - -/// 生成新种子:20 字节随机数 → Base32(160 位,Google Authenticator 兼容)。 -pub fn gen_secret() -> String { - let hex = util::rand_hex(20); - let bytes: Vec = (0..hex.len()) - .step_by(2) - .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap_or(0)) - .collect(); - base32_encode(&bytes) -} - -/// otpauth:// 绑定 URI(二维码内容)。issuer 固定 `SSO`。 -pub fn otpauth_uri(username: &str, secret_b32: &str) -> String { - format!( - "otpauth://totp/SSO:{username}?secret={secret_b32}&issuer=SSO&algorithm=SHA1&digits=6&period=30" - ) -} - -// =========================================================================== -// 账号侧 TOTP(数据存于 `User.extra`,由插件自管;内核只透传、不解释) -// =========================================================================== -// -// TOTP 是 SSO 插件的个性能力,数据挂在 `users.json` 的 `extra` 上, -// 经内核 `users::update_extra` 持锁写回: -// * `totp_secret` Base32 种子(仅 setup 时回传一次,view 透出时被隐藏) -// * `totp_enabled` 是否已启用(启用后登录 / password grant 必须带动态码) - -const EXTRA_TOTP_SECRET: &str = "totp_secret"; -const EXTRA_TOTP_ENABLED: &str = "totp_enabled"; - -/// 账号是否已启用 TOTP 第二因子。 -pub fn is_enabled(user: &User) -> bool { - user.extra_bool(EXTRA_TOTP_ENABLED) -} - -/// 账号的 TOTP 种子(Base32)。启用校验时取用。 -pub fn secret(user: &User) -> String { - user.extra_str(EXTRA_TOTP_SECRET).to_owned() -} - -/// 生成种子(不启用)。返回 `(Base32 种子, otpauth:// URI)` 供前端转二维码; -/// 启用前可重复 setup 重取。 -pub fn setup(username: &str) -> Result<(String, String), String> { - let sec = gen_secret(); - users::update_extra(username, |user| { - user.extra.insert(EXTRA_TOTP_SECRET.to_owned(), Value::String(sec.clone())); - Ok(sec.clone()) - })?; - let uri = otpauth_uri(username, &sec); - Ok((sec, uri)) -} - -/// 校验动态码并启用。返回更新后的账号。 -pub fn enable(username: &str, code: &str, now: i64) -> Result { - let sec = users::get(username) - .ok_or_else(|| "账号不存在".to_owned())? - .extra_str(EXTRA_TOTP_SECRET) - .to_owned(); - if sec.is_empty() { - return Err("尚未生成 TOTP 密钥,请先 setup".to_owned()); - } - if !verify(&sec, code, now as u64) { - return Err("动态验证码不正确或已过期".to_owned()); - } - users::update_extra(username, |user| { - user.extra.insert(EXTRA_TOTP_ENABLED.to_owned(), Value::Bool(true)); - Ok(()) - })?; - users::get(username).ok_or_else(|| "账号不存在".to_owned()) -} - -/// 解绑:删除种子与启用标记。返回更新后的账号。 -pub fn disable(username: &str) -> Result { - users::update_extra(username, |user| { - user.extra.remove(EXTRA_TOTP_SECRET); - user.extra.remove(EXTRA_TOTP_ENABLED); - Ok(()) - })?; - users::get(username).ok_or_else(|| "账号不存在".to_owned()) -} - -// =========================================================================== -// 单元测试:RFC 标准向量(对齐 MaxKey HmacOTPTest / TimeBasedOTPTest 的验证思路) -// =========================================================================== - -#[cfg(test)] -mod tests { - use super::*; - - /// RFC 4226 附录 D:ASCII 种子 "12345678901234567890",6 位截断 - #[test] - fn hotp_rfc4226_vectors() { - let secret = b"12345678901234567890"; - let expect = [755224u32, 287082, 359152, 969429, 338314]; - for (c, &e) in expect.iter().enumerate() { - assert_eq!(hotp(secret, c as u64, 6), e, "counter={c}"); - } - } - - /// RFC 6238 附录 B(SHA-1,8 位):种子同上,T 以 59s 起跳 - #[test] - fn totp_rfc6238_vectors() { - let secret = b"12345678901234567890"; - let cases: [(u64, u32); 4] = [ - (59, 94287082), - (1111111109, 07081804), - (1111111111, 14050471), - (1234567890, 89005924), - ]; - for (t, e) in cases { - assert_eq!(hotp(secret, t / 30, 8), e, "t={t}"); - } - } - - #[test] - fn base32_roundtrip() { - let data = b"hello totp seed!!"; - assert_eq!(base32_decode(&base32_encode(data)).as_deref(), Some(&data[..])); - // MaxKey TimeBasedOTPTest 的种子 - assert!(base32_decode("DCGAGPE2BCDBD6D3FG4NX2QGACVIHXP4").is_some()); - } - - #[test] - fn verify_window() { - let secret = base32_encode(b"12345678901234567890"); - let t = 59u64; - assert!(verify(&secret, &totp(b"12345678901234567890", t), t)); - // ±1 步内可过 - assert!(verify(&secret, &totp(b"12345678901234567890", t), t + STEP)); - // 超窗拒绝 - assert!(!verify(&secret, &totp(b"12345678901234567890", t), t + STEP * 3)); - // 错码拒绝 - assert!(!verify(&secret, "000000", t)); - } -} diff --git a/rust/crates/plugin-sso/src/portal.rs b/rust/crates/plugin-sso/src/portal.rs deleted file mode 100644 index 75af73d..0000000 --- a/rust/crates/plugin-sso/src/portal.rs +++ /dev/null @@ -1,231 +0,0 @@ -//! 终端用户门户「我的应用」(对齐 MaxKey 的统一门户)。 -//! -//! 管理台登记的应用(`oauth_clients` 注册表)在这里以**卡片**形式呈现给终端用户: -//! 登录后能看到「自己可访问的应用」并直接进入,不必记住各系统的地址。 -//! -//! * `GET /apps` 门户页(HTML,服务端渲染) -//! * `GET /api/portal/apps` 同一份数据的 JSON(给其他前端/脚本用) -//! -//! 可见范围由应用上的 `visible_roles` / `visible_depts` / `visible_groups` 决定 -//! (三项全空 = 全员可见),过滤逻辑在 `oauth_clients::visible_apps`。 -//! -//! 鉴权是**会话态**(SSO cookie,`Guard::Public` + 自己读会话),不是 `Guard::User` -//! 的 API Key——门户是给人用浏览器打开的,不是给程序调的。 - -use ngx::core::Status; -use ngx::ffi::ngx_http_request_t; -use ngx::http::HTTPStatus; - -use crate::compat as http; -use ipass_core::users; - -use crate::accounts::UserExt; -use crate::oauth_clients; -use crate::oauth_state::OAuthClient; -use crate::utilx; - -/// 门户页模板。用占位符 `replace` 拼装,**不用 `format!`**——页面里的 CSS/JS -/// 到处都是 `{}`,走 `format!` 得逐个写成 `{{`/`}}`,改一次错一次。 -const APPS_PAGE: &str = r##" - - - - -我的应用 · 统一认证 - - - -
- 统一认证 · 我的应用 - 已登录:{{WHO}} - -
-
-

我的应用

-
共 {{COUNT}} 个可访问应用。灰底卡片未配置访问地址,需管理员在「应用管理」里补全。
- {{BODY}} -
- - -"##; - -/// 路由:门户端点。 -pub fn route(method: &str, uri: &str) -> Option<(crate::api::Guard, crate::api::Handler)> { - if method != "GET" { - return None; - } - let g = crate::api::Guard::Public; - match uri { - "/apps" => Some((g, h_apps_page)), - "/api/portal/apps" => Some((g, h_apps_json)), - _ => None, - } -} - -/// 卡片的进入地址。 -/// -/// * CAS 应用:走 `/cas/login?service=<登记的 service>`(网关侧发起,能直接落到应用); -/// * 其他:用登记的应用访问地址 `home_url`; -/// * 都没有则返回空——OAuth 应用由**应用侧**发起授权,网关推不出入口, -/// 此时卡片显示为不可点击(比给一个点了没反应的链接好)。 -fn entry_url(c: &OAuthClient) -> String { - if c.protocol_or_default() == "cas" { - if let Some(first) = c.redirect_uris.first() { - return format!("/cas/login?service={}", utilx::url_encode(first)); - } - } - c.home_url.clone() -} - -/// 登录用户名 → (展示名, 角色, 部门, 用户组)。查不到用户时给安全兜底(什么权限都没有)。 -fn actor_scope(username: &str) -> (String, String, String, Vec) { - match users::get(username) { - Some(u) => { - let disp = if u.display_name.is_empty() { - u.username.clone() - } else { - u.display_name.clone() - }; - (disp, u.role.clone(), u.department().to_owned(), u.groups()) - } - None => (username.to_owned(), String::new(), String::new(), Vec::new()), - } -} - -/// `GET /apps`:门户页。 -fn h_apps_page(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let Some(username) = crate::oauth::current_user(r) else { - // 未登录:跳登录页并带上回跳。回跳必须是**绝对地址**——登录成功后的 - // 安全性校验(`is_safe_redirect`)只认 http(s) 绝对 URL,传 `/apps` 会被 - // 判为不安全而退化成 JSON 响应(浏览器上就是一片白)。 - let back = format!("{}/apps", crate::oauth::issuer()); - return http::redirect(r, &format!("/login?redirect={}", utilx::url_encode(&back))); - }; - - let (disp, role, dept, groups) = actor_scope(&username); - let apps = oauth_clients::visible_apps(&role, &dept, &groups); - - let body = if apps.is_empty() { - "
暂无可访问的应用。
请联系管理员在管理台「OAuth 应用」中登记,
并把你的角色 / 部门 / 用户组加入该应用的可见范围。
".to_owned() - } else { - let mut cards = String::with_capacity(apps.len() * 512); - cards.push_str("
"); - for c in &apps { - cards.push_str(&card_html(c)); - } - cards.push_str("
"); - cards - }; - - let html = APPS_PAGE - .replace("{{WHO}}", &utilx::html_escape(&disp)) - .replace("{{COUNT}}", &apps.len().to_string()) - .replace("{{BODY}}", &body); - http::send_ct(r, HTTPStatus::OK, &html, "text/html; charset=utf-8") -} - -/// 单张应用卡片。 -fn card_html(c: &OAuthClient) -> String { - let name_raw = c.display_name(); - let entry = entry_url(c); - let logo = if c.logo_url.is_empty() { - let initial = name_raw - .chars() - .next() - .map(|ch| ch.to_uppercase().to_string()) - .unwrap_or_else(|| "?".to_owned()); - format!("", utilx::html_escape(&initial)) - } else { - format!( - "", - utilx::html_escape(&c.logo_url) - ) - }; - let desc = if c.description.is_empty() { - String::new() - } else { - utilx::html_escape(&c.description) - }; - let proto_tag = if c.protocol_or_default() == "cas" { - "CAS" - } else { - "OAuth2 / OIDC" - }; - let inner = format!( - "{logo}
{}
{desc}
\ -
{proto_tag}{}
", - utilx::html_escape(name_raw), - utilx::html_escape(&c.client_id) - ); - if entry.is_empty() { - // 灰底 + 明确标签:只靠 opacity 不够显眼,用户会以为是加载失败 - format!( - "
{inner}\ -
未配置访问地址
" - ) - } else { - format!("{inner}", utilx::html_escape(&entry)) - } -} - -/// `GET /api/portal/apps`:同一份数据的 JSON(未登录 401)。 -fn h_apps_json(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let Some(username) = crate::oauth::current_user(r) else { - return http::fail(r, HTTPStatus::UNAUTHORIZED, "未登录或会话已过期"); - }; - let (disp, role, dept, groups) = actor_scope(&username); - let items: Vec = oauth_clients::visible_apps(&role, &dept, &groups) - .iter() - .map(|c| { - serde_json::json!({ - "client_id": c.client_id, - "name": c.display_name(), - "description": c.description, - "logo_url": c.logo_url, - "protocol": c.protocol_or_default(), - "home_url": c.home_url, - "redirect_uris": c.redirect_uris, - "entry_url": entry_url(c), - }) - }) - .collect(); - http::ok( - r, - serde_json::json!({ - "username": username, - "display_name": disp, - "portal": format!("{}/apps", crate::oauth::issuer()), - "items": items, - }), - "ok", - ) -} diff --git a/rust/crates/plugin-sso/src/reset.rs b/rust/crates/plugin-sso/src/reset.rs deleted file mode 100644 index 5381d35..0000000 --- a/rust/crates/plugin-sso/src/reset.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! 自助密码重置(对齐 MaxKey 密码找回)。 -//! -//! 两个公开端点,无需登录: -//! -//! * `POST /api/public/forgot-password` —— 凭账号名 / 邮箱申请重置,签发一次性 -//! token(存共享内存,不落 `users.json`,避免出现在管理台视图里),并「发信」。 -//! * `POST /api/public/reset-password` —— 凭 token + 新口令完成重置。 -//! * `GET /forgot` / `GET /reset?token=…` —— 上面两个 API 的**终端用户页面** -//! (没有页面时,发给用户的邮件链接会指向 POST 端点,点开必然失败)。 -//! -//! token 用共享内存 `pwdrst: → username` 存储,带 TTL,单次有效(用后即删)。 -//! 「发信」是可配置抽象:默认只写日志;设 `PASSWORD_RESET_TOKEN_SINK` 把 token -//! 落到本地文件(本地联调 / e2e 取用);生产可接 SMTP / webhook(见 sender 分支)。 - -use ngx::ffi::ngx_http_request_t; - -use crate::compat as http; -use ipass_core::state; -use ipass_core::users; -use ipass_core::util; -use ngx::core::Status; -use ngx::http::HTTPStatus; - -use crate::accounts::{self, UserExt}; -use crate::audit; -use crate::oauth; -use crate::utilx; - -/// 重置 token 共享内存前缀:`pwdrst: → username` -const KEY_PWD_RESET: &[u8] = b"pwdrst:"; -/// 默认 token 有效期(秒) -const RESET_TTL_DEFAULT: i64 = 1800; - -/// 路由 -pub fn route(method: &str, uri: &str) -> Option<(crate::api::Guard, crate::api::Handler)> { - let g = crate::api::Guard::Public; - match (method, uri) { - ("POST", "/api/public/forgot-password") => Some((g, h_forgot_password)), - ("POST", "/api/public/reset-password") => Some((g, h_reset_password)), - // 终端用户页面(GET)。放在这里而不是主路由表:同属「密码重置」这一族。 - ("GET", "/forgot") => Some((g, h_forgot_page)), - ("GET", "/reset") => Some((g, h_reset_page)), - _ => None, - } -} - -/// token 有效期:可由 `PASSWORD_RESET_TTL` 覆盖(秒)。 -fn reset_ttl() -> i64 { - match std::env::var("PASSWORD_RESET_TTL") { - Ok(v) => v.trim().parse::().unwrap_or(RESET_TTL_DEFAULT).max(60), - Err(_) => RESET_TTL_DEFAULT, - } -} - -/// 把重置信息「发出去」:配置化抽象(默认日志;SINK 文件;生产可扩展 SMTP/webhook)。 -fn send_reset(user: &str, token: &str) { - let base = oauth::issuer(); - // 注意:必须指向 **GET 页面**,不能直接指向 POST 端点(点开会是 405/空响应)。 - let link = format!("{base}/reset?token={token}"); - util::log_notice(&format!("[reset] 密码重置链接 user={user} {link}")); - - if let Ok(sink) = std::env::var("PASSWORD_RESET_TOKEN_SINK") { - // 本地联调 / e2e:把 token 落到文件,便于脚本取出(不含 PII,仅 token) - let _ = std::fs::write(&sink, format!("{token}\n")); - } -} - -/// `POST /api/public/forgot-password`:账号名或邮箱。 -/// -/// 安全:无论账号是否存在都返回同样的成功文案,避免账号枚举。 -fn h_forgot_password(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let p = http::params(r); - let ident = p - .get("username") - .or_else(|| p.get("email")) - .map(String::as_str) - .unwrap_or("") - .to_owned(); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - if ident.is_empty() { - return http::fail(r, HTTPStatus::BAD_REQUEST, "请提供账号名或邮箱"); - } - - // 按账号名或邮箱定位用户 - let found = users::get(&ident).or_else(|| { - let lower = ident.to_ascii_lowercase(); - users::all().into_iter().find(|u| u.email().to_ascii_lowercase() == lower) - }); - - if let Some(u) = found { - let token = util::gen_key(); - let exp = util::now() + reset_ttl(); - state::put(KEY_PWD_RESET, token.as_bytes(), u.username.as_bytes(), exp); - send_reset(&u.username, &token); - audit::log("pwd.forgot", &u.username, &u.username, true, &ip, &ua, ""); - } else { - audit::log("pwd.forgot", &ident, &ident, false, &ip, &ua, "no such account"); - } - - http::ok(r, serde_json::json!({}), "若账号存在,重置链接已发送") -} - -/// `POST /api/public/reset-password`:token + 新口令。 -fn h_reset_password(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let p = http::params(r); - let token = p.get("token").map(String::as_str).unwrap_or("").to_owned(); - let password = p.get("password").map(String::as_str).unwrap_or("").to_owned(); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - if token.is_empty() || password.is_empty() { - return http::fail(r, HTTPStatus::BAD_REQUEST, "token 与新口令均必填"); - } - if let Err(e) = accounts::check_password(&password) { - return http::fail(r, HTTPStatus::BAD_REQUEST, &e); - } - - let Some((username, exp)) = state::get(KEY_PWD_RESET, token.as_bytes()) else { - return http::fail(r, HTTPStatus::BAD_REQUEST, "token 无效或已使用"); - }; - if exp > 0 && exp <= util::now() { - state::remove(KEY_PWD_RESET, token.as_bytes()); - return http::fail(r, HTTPStatus::BAD_REQUEST, "token 已过期,请重新申请"); - } - - match users::set_password(&username, &password) { - Ok(()) => { - // 单次有效:消费即删 - state::remove(KEY_PWD_RESET, token.as_bytes()); - audit::log("pwd.reset", &username, &username, true, &ip, &ua, ""); - http::ok(r, serde_json::json!({}), "密码已重置,请用新口令登录") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -// =========================================================================== -// 终端用户页面(自助密码重置的「另一半」) -// =========================================================================== -// -// 只有 API 没有页面时,用户拿到的邮件链接会指向一个 POST 端点——点开必然 -// 405/400。所以这里补两个 GET 页面: -// GET /forgot 输入账号名/邮箱,申请重置 -// GET /reset?token=… 凭一次性 token 设置新口令 -// 页面用 fetch 提交,不依赖跨请求表单 POST(token 也就不会出现在地址栏历史里 -// 之外的任何地方)。 - -/// 两个页面共用的样式:与登录页同一套配色(深蓝渐变底 + 白卡片 + 蓝色主按钮)。 -const PAGE_STYLE: &str = r#" - *{box-sizing:border-box} - body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px; - font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; - background:radial-gradient(1100px 560px at 50% -12%,#1e3a8a 0%,#0f172a 58%,#0b1220 100%);color:#1f2937} - .card{width:100%;max-width:400px;background:#fff;border-radius:16px;padding:34px 30px 24px; - box-shadow:0 20px 60px rgba(2,6,23,.45)} - .brand{display:flex;align-items:center;gap:11px;margin-bottom:20px} - .mark{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,#2563eb,#38bdf8); - display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700; - font-size:12px;letter-spacing:.5px;flex:0 0 auto} - h1{font-size:16px;margin:0} - .sub{color:#6b7280;font-size:12px;margin-top:2px} - label{display:block;font-size:12.5px;color:#6b7280;margin:0 0 6px} - input[type=text],input[type=password]{width:100%;padding:10px 12px;margin:0 0 14px; - border:1px solid #cbd5e1;border-radius:8px;font-size:13.5px;outline:none; - transition:border-color .15s,box-shadow .15s} - input[type=text]:focus,input[type=password]:focus{border-color:#2563eb; - box-shadow:0 0 0 3px rgba(37,99,235,.12)} - button{width:100%;padding:11px;border:0;border-radius:8px;background:#2563eb;color:#fff; - font-size:15px;font-weight:600;cursor:pointer;transition:.15s;font-family:inherit} - button:hover{background:#1d4ed8} - button:disabled{opacity:.6;cursor:not-allowed} - .msg{border-radius:8px;padding:9px 12px;font-size:12.5px;margin-bottom:16px;display:none} - .msg.ok{background:#e7f6ec;color:#15803d;border:1px solid #bfe3cb;display:block} - .msg.err{background:#fdecec;color:#b91c1c;border:1px solid #f7cfcf;display:block} - .foot{margin-top:16px;padding-top:14px;border-top:1px dashed #e3e8ef; - color:#6b7280;font-size:12px;text-align:center} - .foot a{color:#2563eb;text-decoration:none} -"#; - -/// 找回密码页。用占位符替换而不是 `format!`:页面里有大量 JS 花括号, -/// 走 `format!` 得把每一个都写成 `{{`/`}}`,改起来极易出错。 -const FORGOT_PAGE: &str = r#" - -找回密码 · 统一认证 -
-
SSO
-

找回密码

输入账号名或邮箱,系统会发送一次性重置链接
-
-
- - -
- -
-"#; - -/// 重置口令页。`__TOKEN__` 为一次性 token(HTML 转义后填入隐藏域)。 -const RESET_PAGE: &str = r#" - -重置密码 · 统一认证 -
-
SSO
-

设置新密码

凭重置链接设置新口令,该链接仅可使用一次
-
__MSG__
-
- - - - - -
- -
-"#; - -fn forgot_html() -> String { - FORGOT_PAGE.replace("__STYLE__", PAGE_STYLE) -} - -fn reset_html(token: &str, error: &str) -> String { - let empty = token.trim().is_empty(); - let (cls, hidden) = if empty { ("err", "hidden") } else { ("", "") }; - let msg = if empty { "链接不完整或已失效,请重新申请" } else { error }; - RESET_PAGE - .replace("__STYLE__", PAGE_STYLE) - .replace("__TOKEN__", &utilx::html_escape(token)) - .replace("__MSG_CLS__", cls) - .replace("__MSG__", &utilx::html_escape(msg)) - .replace("__FORM_HIDDEN__", hidden) -} - -/// `GET /forgot` —— 找回密码页(登录页有「忘记密码?」链接指过来)。 -fn h_forgot_page(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - http::send_ct(r, HTTPStatus::OK, &forgot_html(), "text/html; charset=utf-8") -} - -/// `GET /reset?token=…` —— 凭一次性 token 设置新口令页。 -/// -/// token 为空时直接在页面上给出提示(不发往服务端),其余情况即使 token 无效 -/// 也照常渲染表单——真正的校验在 POST 时做,避免把「token 是否存在」暴露成页面差异。 -fn h_reset_page(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status { - let p = http::params(r); - let token = p.get("token").map(String::as_str).unwrap_or("").to_owned(); - http::send_ct(r, HTTPStatus::OK, &reset_html(&token, ""), "text/html; charset=utf-8") -} diff --git a/rust/crates/plugin-sso/src/rsa.rs b/rust/crates/plugin-sso/src/rsa.rs deleted file mode 100644 index 1078da3..0000000 --- a/rust/crates/plugin-sso/src/rsa.rs +++ /dev/null @@ -1,699 +0,0 @@ -//! 手写 RSA-2048 + RS256 签名/验签(roadmap v2)。 -//! -//! ## 为什么手写 -//! -//! 「零新增依赖 / vendor 离线可编译」是 v1 的硬约定。引入 `rsa` crate 意味着 -//! 连带 vendor `num-bigint-dig` / `der` / `pkcs8` / `zeroize` 等十余个 crate; -//! 而 RS256 的数学内核(Montgomery 模乘 + Miller-Rabin)约 400 行可控代码。 -//! 本模块是模块内**唯一**的大数运算,不与外部共享。 -//! -//! ## 算法选型 -//! -//! * 模乘用 **Montgomery CIOS**(避免实现 Knuth D 长除法,且无除法分支); -//! * 签名用 **CRT**(dp/dq/qi 两个 1024-bit 模幂 + 重组合)——IAP 会话路径 -//! 每请求重签 access_token,CRT 比全长模幂快约 4 倍; -//! * 素性用 **Miller-Rabin**(24 証人 + 小素数试除); -//! * `dp / dq / qi` 用**二进制移位长除法**计算(仅 keygen 时用,性能无关)。 -//! -//! ## 密钥存储(对 roadmap 的偏离说明) -//! -//! roadmap 原文是 `OAUTH_JWK_DIR/active.pem`。手写 ASN.1/PEM 编解码的收益低, -//! 实际存储为 `active.jwk.json`:分量(n/e/d/p/q/dp/dq/qi)全部 base64url, -//! `kid` 为公钥 SHA-256 前 16 hex。轮换语义照 roadmap:私钥只保留 active 一把, -//! 旧公钥文件(`*.pub.jwk.json`)保留在 JWKS 输出中直到旧令牌过期。 -//! -//! ## 安全红线 -//! -//! * 私钥文件在 `data_dir/jwks/` 下,**不进版本库**; -//! * 验签只信任 JWT header 中白名单 `alg`(RS256/HS256),拒绝 `none`, -//! 并按 header 中的 `kid` 选择密钥(缺省用 active)。 - - -use serde_json::{Value, json}; - -use ipass_core::util; - -// =========================================================================== -// BigUint:u32 小端 limbs 的最小实现 -// =========================================================================== - -type Big = Vec; - -/// 大端字节流 → u32 小端 limbs:末字节为最低有效字节。 -/// ( limbs[k] 的权重是 2^(32k),BE 第 i 字节距最低位偏移 = len-1-i ) -fn be_to_limbs(bytes: &[u8]) -> Big { - let n = bytes.len(); - let mut out = vec![0u32; (n + 3) / 4]; - for (i, &b) in bytes.iter().enumerate() { - let pos = n - 1 - i; - out[pos / 4] |= (b as u32) << (8 * (pos % 4)); - } - out -} - - - -fn trim(mut a: Big) -> Big { - while a.len() > 1 && *a.last().unwrap() == 0 { - a.pop(); - } - a -} - -fn cmp(a: &[u32], b: &[u32]) -> core::cmp::Ordering { - let n = a.len().max(b.len()); - for i in (0..n).rev() { - let x = a.get(i).copied().unwrap_or(0); - let y = b.get(i).copied().unwrap_or(0); - match x.cmp(&y) { - core::cmp::Ordering::Equal => continue, - o => return o, - } - } - core::cmp::Ordering::Equal -} - -fn add(a: &[u32], b: &[u32]) -> Big { - let n = a.len().max(b.len()) + 1; - let mut out = Vec::with_capacity(n); - let mut carry = 0u64; - for i in 0..n { - let s = a.get(i).copied().unwrap_or(0) as u64 - + b.get(i).copied().unwrap_or(0) as u64 - + carry; - out.push(s as u32); - carry = s >> 32; - } - trim(out) -} - -fn sub(a: &[u32], b: &[u32]) -> Big { - let mut out = Vec::with_capacity(a.len()); - let mut borrow = 0i64; - for i in 0..a.len() { - let mut d = a[i] as i64 - b.get(i).copied().unwrap_or(0) as i64 - borrow; - if d < 0 { - d += 1 << 32; - borrow = 1; - } else { - borrow = 0; - } - out.push(d as u32); - } - debug_assert_eq!(borrow, 0, "sub 下溢"); - trim(out) -} - -/// 学校簿乘法(u32 基)。只用于 keygen 与 CRT 重组合,非热路径。 -fn mul(a: &[u32], b: &[u32]) -> Big { - if a.iter().all(|&x| x == 0) || b.iter().all(|&x| x == 0) { - return vec![0]; - } - let mut out = vec![0u32; a.len() + b.len()]; - for (i, &x) in a.iter().enumerate() { - let mut carry = 0u64; - for (j, &y) in b.iter().enumerate() { - let t = x as u64 * y as u64 + out[i + j] as u64 + carry; - out[i + j] = t as u32; - carry = t >> 32; - } - let mut k = i + b.len(); - while carry > 0 { - let t = out[k] as u64 + carry; - out[k] = t as u32; - carry = t >> 32; - k += 1; - } - } - trim(out) -} - -/// 二进制移位长除法:`a mod m`(仅 keygen 使用:dp/dq/qinv 计算)。 -fn mod_binary(a: &[u32], m: &[u32]) -> Big { - debug_assert!(cmp(m, &[1]) != core::cmp::Ordering::Less); - let mut r: Big = vec![0]; - for bit in (0..(a.len() * 32)).rev() { - // r = r << 1 | bit - shl1(&mut r); - if (a[bit / 32] >> (bit % 32)) & 1 == 1 { - r[0] |= 1; - } - if cmp(&r, m) != core::cmp::Ordering::Less { - r = sub(&r, m); - } - } - r -} - -fn shl1(a: &mut Big) { - let mut carry = 0u32; - for limb in a.iter_mut() { - let nc = *limb >> 31; - *limb = (*limb << 1) | carry; - carry = nc; - } - if carry > 0 { - a.push(carry); - } -} - -/// 模逆:`a^{-1} mod m`(gcd(a,m)=1)。系数全程保持在 [0, m): -/// 不变式 `a·s ≡ r (mod m)` 只需模 m 成立,因此 s 的减法在模 m 内进行, -/// 天然无负数——避开带符号大数实现。 -fn mod_inv(a: &[u32], m: &[u32]) -> Option { - let mut r0 = mod_binary(a, m); - let mut r1 = m.to_vec(); - let mut s0: Big = vec![1]; - let mut s1: Big = vec![0]; - while cmp(&r1, &[0]) == core::cmp::Ordering::Greater { - let (q, rem) = divmod(&r0, &r1); - r0 = r1; - r1 = rem; - // s_new = (s0 - q·s1) mod m - let qs = mod_binary(&mul(&q, &s1), m); - let s_new = if cmp(&s0, &qs) == core::cmp::Ordering::Less { - sub(&add(&s0, m), &qs) - } else { - sub(&s0, &qs) - }; - s0 = s1; - s1 = s_new; - } - if r0 == [1] { Some(s0) } else { None } -} - -/// 扩展欧几里得:返回 `g = gcd(a, m)` 与 `x` 使 `a·x ≡ g (mod m)`。 -/// 递归版,只用于 keygen(d、qinv)。 -fn ext_gcd(a: &[u32], m: &[u32]) -> (Big, Big, Big) { - // 迭代实现:保持 (old_r, r) 与 (old_s, s),t 序列不需要(只要 x mod m) - let mut old_r = a.to_vec(); - let mut r = m.to_vec(); - let mut old_s: Big = vec![1]; - let mut s: Big = vec![0]; - while cmp(&r, &[0]) == core::cmp::Ordering::Greater { - // q = old_r / r(二进制估商:反复减太慢,直接用逐位除法) - let (q, rem) = divmod(&old_r, &r); - old_r = r; - r = rem; - let t = sub(&old_s, &mul(&q, &s)); - // t 可能暂为「负」,此处 a、m 均 > 0 且最终结果 mod m 为正; - // 为避免实现带符号大数,用 mod m 的同余性质:先 mod m 再继续。 - // 简化处理:q 通常很小(辗转相除商均值 ~φ),减法下溢概率极低; - // 若下溢则结果等价于 mod 2^(32n),在最终 mod m 后仍同余(模 2^k 世界里 - // 负数与加 2^k 同余,欧几里得的线性组合性质保持成立到 m < 2^(32k))。 - old_s = core::mem::replace(&mut s, t); - } - (old_r, old_s, r) -} - -/// 带商的除法(Knuth D 的简化版:二进制逐位)返回 `(q, r)`。仅 keygen 用。 -fn divmod(a: &[u32], b: &[u32]) -> (Big, Big) { - debug_assert!(cmp(b, &[0]) != core::cmp::Ordering::Equal); - let mut q = vec![0u32; a.len()]; - let mut r: Big = vec![0]; - for bit in (0..(a.len() * 32)).rev() { - shl1(&mut r); - if (a[bit / 32] >> (bit % 32)) & 1 == 1 { - if r.len() == 1 && r[0] == 0 { r[0] = 1; } else { r[0] |= 1; } - } - if cmp(&r, b) != core::cmp::Ordering::Less { - r = sub(&r, b); - q[bit / 32] |= 1 << (bit % 32); - } - } - (trim(q), r) -} - -// =========================================================================== -// Montgomery 模乘(CIOS) -// =========================================================================== - -/// 固定模数的 Montgomery 上下文 -struct Mont { - /// 模数(奇数),L 个 limbs - n: Big, - /// -n^{-1} mod 2^32 - n0: u32, - /// R^2 mod n(进 Montgomery 域用) - r2: Big, - /// R mod n(退出域用) - r1: Big, - /// 期望的 limbs 数 - l: usize, -} - -impl Mont { - fn new(n: &[u32]) -> Mont { - let mut n = trim(n.to_vec()); - if n.len() == 1 && n[0] == 1 { - n = vec![1]; // 不应发生;占位 - } - let l = n.len(); - // n0inv:牛顿迭代求 n[0] 的逆 mod 2^32,再取负 - let mut x = n[0]; // 奇数,必有逆 - for _ in 0..4 { - x = x.wrapping_mul(2u32.wrapping_sub(n[0].wrapping_mul(x))); - } - let n0 = x.wrapping_neg(); - - let mut mont = Mont { n, n0, r2: vec![0], r1: vec![0], l }; - // R mod n:R = 2^(32L),从 1 开始翻倍 32L 次,每步条件减 n - let mut r: Big = vec![1]; - for _ in 0..(32 * l) { - shl1(&mut r); - if cmp(&r, &mont.n) != core::cmp::Ordering::Less { - r = sub(&r, &mont.n); - } - } - mont.r1 = trim(r.clone()); - // R^2 mod n:继续翻倍 32L 次 - let mut r2 = r; - for _ in 0..(32 * l) { - shl1(&mut r2); - if cmp(&r2, &mont.n) != core::cmp::Ordering::Less { - r2 = sub(&r2, &mont.n); - } - } - mont.r2 = trim(r2); - mont - } - - /// CIOS 蒙哥马利乘:返回 `a·b·R^{-1} mod n`(a、b 为 Montgomery 域内值) - fn mul(&self, a: &[u32], b: &[u32]) -> Big { - let l = self.l; - // CIOS 固定按 n 的 limb 数循环;操作数可能被 trim 短(如 0、1), - // 统一补零到 l 位,避免越界。 - let mut ap = a.to_vec(); - ap.resize(l, 0); - let mut bp = b.to_vec(); - bp.resize(l, 0); - let a: &[u32] = ≈ - let b: &[u32] = &bp; - let mut t = vec![0u64; l + 2]; - for i in 0..l { - // 第一遍:t += a[i] * b - let mut carry = 0u64; - let ai = a[i] as u64; - for j in 0..l { - let s = t[j] + ai * b[j] as u64 + carry; - t[j] = s & 0xffff_ffff; - carry = s >> 32; - } - let s = t[l] as u64 + carry; - t[l] = s & 0xffff_ffff; - t[l + 1] = (s >> 32) as u64; - - // 归约步:m = t[0] * n0 mod 2^32;t += m * n;整体右移一个 limb - let m = (t[0] as u32).wrapping_mul(self.n0); - carry = (m as u64 * self.n[0] as u64 + t[0]) >> 32; - for j in 1..l { - let s = t[j] + m as u64 * self.n[j] as u64 + carry; - t[j - 1] = s & 0xffff_ffff; - carry = s >> 32; - } - let s = t[l] as u64 + carry; - t[l - 1] = s & 0xffff_ffff; - t[l] = t[l + 1] + ((s >> 32) as u64); - t[l + 1] = 0; - } - // 结果在 t[0..l];可能比 n 大一个 R,条件减一次 - let mut out: Vec = t[..l].iter().map(|&x| x as u32).collect(); - if t[l] != 0 || cmp(&out, &self.n) != core::cmp::Ordering::Less { - out = sub(&out, &self.n); - } - trim(out) - } - - /// 进入 Montgomery 域:`a → a·R mod n` - fn to_mont(&self, a: &[u32]) -> Big { - self.mul(&mod_binary(a, &self.n), &self.r2) - } - - /// 退出 Montgomery 域:`a → a·R^{-1} mod n` - fn from_mont(&self, a: &[u32]) -> Big { - self.mul(a, &[1]) - } -} - -/// `a^e mod n`(Montgomery,e 为 u32 小端 limbs 的指数,如 d) -fn powmod(base: &[u32], exp_le: &[u32], mont: &Mont) -> Big { - let base_m = mont.to_mont(base); - let mut result = mont.r1.clone(); // = 1 in Montgomery 域 - let mut started = false; - for i in (0..exp_le.len()).rev() { - for bit in (0..32).rev() { - if started { - result = mont.mul(&result, &result); - } - if (exp_le[i] >> bit) & 1 == 1 { - if started { - result = mont.mul(&result, &base_m); - } else { - started = true; - result = base_m.clone(); - } - } - } - } - if !started { - return vec![1]; // e == 0 - } - mont.from_mont(&result) -} - -// =========================================================================== -// Miller-Rabin 素性检测 -// =========================================================================== - -const SMALL_PRIMES: [u32; 96] = [ - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, - 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, - 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, - 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, - 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, -]; - -fn is_probable_prime(cand: &[u32]) -> bool { - // 小素数试除 - for &p in &SMALL_PRIMES { - if cmp(cand, &[p]) == core::cmp::Ordering::Equal { - return true; - } - let (_, r) = divmod(cand, &[p]); - if r == [0] { - return false; - } - } - // cand-1 = d·2^s - let one: Big = vec![1]; - let d = sub(cand, &one); - let mut s = 0usize; - let mut dd = d.clone(); - while dd[0] & 1 == 0 { - // 右移一位 - let mut carry = 0u32; - for limb in dd.iter_mut().rev() { - let nc = *limb & 1; - *limb = (*limb >> 1) | (carry << 31); - carry = nc; - } - dd = trim(dd); - s += 1; - if dd == [0] { - return false; // cand-1 全 0 → cand == 1,不是素数 - } - } - - let mont = Mont::new(cand); - // 24 个固定証人(对 1024-bit:错误率 < 2^-48,与 OpenSSL 常用组合相当) - for &w in [ - 2u32, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, - 89, - ] - .iter() - { - let a = mod_binary(&vec![w], cand); - if cmp(&a, &one) == core::cmp::Ordering::Equal - || cmp(&a, &sub(cand, &one)) == core::cmp::Ordering::Equal - { - continue; - } - let mut x = powmod(&a, &dd_le(&d), &mont); - // 初始即「合数」:只有平方链中碰到 n-1 才能洗清。 - // 初值若为 false,s=1(n-1 = d·2,随机奇数 ~50% 概率)时循环零次 - // 执行,会把这个证人也放行——这正是曾产出合数"素数"的 bug。 - let mut composite = true; - if x == one || cmp(&x, &sub(cand, &one)) == core::cmp::Ordering::Equal { - continue; - } - for _ in 0..s.saturating_sub(1) { - // x = x^2 mod cand(域内自乘) - x = mont.mul(&x, &x); - if cmp(&x, &sub(cand, &one)) == core::cmp::Ordering::Equal { - composite = false; - break; - } - if x == one { - composite = true; - break; - } - composite = true; - } - if composite { - return false; - } - } - true -} - -/// 大端序转 u32 小端 limbs(powmod 的指数表示) -fn dd_le(d_be_big: &Big) -> Big { - d_be_big.clone() // Big 本身就是 u32 小端 limbs -} - -// =========================================================================== -// 密钥生成与序列化 -// =========================================================================== - -fn rand_limbs(nbytes: usize) -> Big { - let hex = util::rand_hex(nbytes); - let mut out = vec![0u32; nbytes / 4]; - for (i, limb) in out.iter_mut().enumerate() { - let mut v = 0u32; - for j in 0..4 { - v |= (u8::from_str_radix(&hex[i * 8 + j * 2..i * 8 + j * 2 + 2], 16) - .unwrap_or(0) as u32) - << (j * 8); - } - *limb = v; - } - out -} - -/// 生成指定位数的奇素数(top two bits set,保证 n 足位) -fn gen_prime(bits: usize) -> Big { - let nbytes = bits / 8; - loop { - let mut c = rand_limbs(nbytes); - // 置最高两位与最低位:保证 n = p·q 达到 2048 bit 且 c 为奇数 - let top = c.len() - 1; - c[top] |= 0b1100_0000_0000_0000_0000_0000_0000_0000; - c[0] |= 1; - c = trim(c); - if is_probable_prime(&c) { - return c; - } - } -} - -pub struct RsaKeypair { - pub n: Big, - pub e: u32, - pub d: Big, - pub p: Big, - pub q: Big, - pub dp: Big, - pub dq: Big, - pub qinv: Big, - pub kid: String, -} - -/// 生成 RSA-2048 密钥对。e 固定 65537。 -pub fn generate() -> Result { - let e: u32 = 65537; - let one: Big = vec![1]; - let e_big: Big = vec![e]; - - let (p, q) = loop { - let p = gen_prime(1024); - let q = gen_prime(1024); - if cmp(&p, &q) == core::cmp::Ordering::Equal { - continue; - } - // gcd(p-1, e) == 1 且 gcd(q-1, e) == 1(e = 65537 是素数,只需 p-1 不整除 e) - let (_, r1) = divmod(&sub(&p, &one), &e_big); - let (_, r2) = divmod(&sub(&q, &one), &e_big); - if r1 != [0] && r2 != [0] { - break (p, q); - } - }; - - let n = mul(&p, &q); - if n.len() != 64 { - return Err("模长不足 2048 位".to_owned()); - } - // φ(n) = (p-1)(q-1) - let phi = mul(&sub(&p, &one), &sub(&q, &one)); - // d = e^{-1} mod φ - let Some(d) = mod_inv(&e_big, &phi) else { - return Err("e 与 φ(n) 不互素".to_owned()); - }; - - let dp = mod_binary(&d, &sub(&p, &one)); - let dq = mod_binary(&d, &sub(&q, &one)); - // qinv = q^{-1} mod p - let qinv = mod_inv(&q, &p).ok_or("q 与 p 不互素".to_owned())?; - - let kid = util::sha256_hex(&to_be_bytes(&n))[..16].to_owned(); - Ok(RsaKeypair { n, e, d, p, q, dp, dq, qinv, kid }) -} - -fn to_be_bytes(a: &[u32]) -> Vec { - let mut out = Vec::with_capacity(a.len() * 4); - for limb in a.iter().rev() { - out.extend_from_slice(&limb.to_be_bytes()); - } - // 去前导零 - let first_nonzero = out.iter().position(|&b| b != 0).unwrap_or(out.len() - 1); - out.drain(..first_nonzero); - out -} - -fn b64url_bytes(a: &[u32]) -> String { - crate::oauth::oauth_b64_encode(&to_be_bytes(a)) -} - -fn from_b64url(s: &str) -> Big { - trim(be_to_limbs(&crate::oauth::oauth_b64_decode(s))) -} - -/// 序列化为 JWK JSON(含私钥分量)。 -pub fn to_jwk(k: &RsaKeypair) -> Value { - json!({ - "kty": "RSA", - "alg": "RS256", - "use": "sig", - "kid": k.kid, - "n": b64url_bytes(&k.n), - "e": b64url_bytes(&[k.e]), - "d": b64url_bytes(&k.d), - "p": b64url_bytes(&k.p), - "q": b64url_bytes(&k.q), - "dp": b64url_bytes(&k.dp), - "dq": b64url_bytes(&k.dq), - "qi": b64url_bytes(&k.qinv), - }) -} - -/// 从 JWK JSON 解析。**公钥文件**(仅 n/e/kid)也可解析——私钥分量缺省为空, -/// 只用于验签;签发路径必须用完整私钥(`has_private` 检查)。 -pub fn from_jwk(v: &Value) -> Option { - let get = |k: &str| -> Option { - v.get(k).and_then(|x| x.as_str()).map(|s| s.to_owned()) - }; - Some(RsaKeypair { - n: from_b64url(&get("n")?), - e: from_b64url(&get("e")?).first().copied().unwrap_or(65537), - d: get("d").map(|x| from_b64url(&x)).unwrap_or_default(), - p: get("p").map(|x| from_b64url(&x)).unwrap_or_default(), - q: get("q").map(|x| from_b64url(&x)).unwrap_or_default(), - dp: get("dp").map(|x| from_b64url(&x)).unwrap_or_default(), - dq: get("dq").map(|x| from_b64url(&x)).unwrap_or_default(), - qinv: get("qi").map(|x| from_b64url(&x)).unwrap_or_default(), - kid: get("kid").unwrap_or_default(), - }) -} - -impl RsaKeypair { - /// 是否持有私钥分量(签发需要,验签不需要)。 - pub fn has_private(&self) -> bool { - !self.d.is_empty() - } -} - -// =========================================================================== -// 签名(CRT)/ 验签 -// =========================================================================== - -/// PKCS#1 v1.5 EMSA 编码:`0x00 01 FF..FF 00 || DigestInfo(SHA-256) || hash` -fn emsa_pkcs1(t_len: usize, k: usize, digest: &[u8; 32]) -> Big { - // SHA-256 的 DigestInfo DER 前缀(RFC 8017 注 1) - const PREFIX: [u8; 19] = [ - 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, - 0x05, 0x00, 0x04, 0x20, - ]; - let t_len_full = PREFIX.len() + 32; - debug_assert_eq!(t_len_full, t_len); - let mut em = vec![0u8; k]; - em[0] = 0x00; - em[1] = 0x01; - for b in em[2..k - t_len_full - 1].iter_mut() { - *b = 0xff; - } - em[k - t_len_full - 1] = 0x00; - em[k - t_len_full..k - 32].copy_from_slice(&PREFIX); - em[k - 32..].copy_from_slice(digest); - // BE bytes → u32 LE limbs - be_to_limbs(&em) -} - -/// CRT 签名:`sig = m^d mod n`,拆为 p、q 两半。 -pub fn sign_crt(digest: &[u8; 32], k: &RsaKeypair) -> Vec { - let k_len = k.n.len(); - let mont_p = Mont::new(&k.p); - let mont_q = Mont::new(&k.q); - let m = emsa_pkcs1(51, k_len * 4, digest); - - // m1 = m^dp mod p;m2 = m^dq mod q - let m_p = mod_binary(&m, &k.p); - let m_q = mod_binary(&m, &k.q); - let m1 = powmod(&m_p, &k.dp, &mont_p); - let m2 = powmod(&m_q, &k.dq, &mont_q); - - // Garner: h = qinv * (m1 - m2) mod p;注意 m1 可能 < m2 → 加 p 防下溢 - let mut diff = sub(&m1, &m2); - if cmp(&m1, &m2) == core::cmp::Ordering::Less { - diff = sub(&add(&m1, &k.p), &m2); - } - // qinv、diff 均 < p → 在 Montgomery 域内乘 - let qinv_m = mont_p.to_mont(&k.qinv); - let h_m = mont_p.mul(&mont_p.to_mont(&diff), &qinv_m); - let h = mont_p.from_mont(&h_m); - - // s = m2 + h * q - let sig = add(&m2, &mul(&h, &k.q)); - let sig = mod_binary(&sig, &k.n); - // JWT/RS256 签名必须定长(模长字节数):短签名左补零 - let sb = to_be_bytes(&sig); - let mut out = vec![0u8; k_len * 4 - sb.len()]; - out.extend_from_slice(&sb); - out -} - -/// 公钥验签:`m = sig^e mod n`,比对 EMSA 编码。 -pub fn verify(sig_be: &[u8], n: &[u32], e: u32) -> Option<[u8; 32]> { - if sig_be.len() != n.len() * 4 || sig_be.is_empty() { - return None; - } - let sig = be_to_limbs(sig_be); - if cmp(&sig, n) != core::cmp::Ordering::Less { - return None; - } - let mont = Mont::new(n); - let m = powmod(&sig, &[e], &mont); - // to_be_bytes 会去前导零;EMSA 编码必须按模长定长(首字节 0x00),补齐 - let emb = to_be_bytes(&m); - let mut em = vec![0u8; n.len() * 4 - emb.len()]; - em.extend_from_slice(&emb); - - const PREFIX: [u8; 19] = [ - 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, - 0x05, 0x00, 0x04, 0x20, - ]; - // 结构:00 01 FF..FF 00 || PREFIX || hash32 - if em.len() != n.len() * 4 || em[0] != 0x00 || em[1] != 0x01 { - return None; - } - let t_start = em.len() - 51; - for &b in &em[2..t_start - 1] { - if b != 0xff { - return None; - } - } - if em[t_start - 1] != 0x00 || em[t_start..t_start + 19] != PREFIX { - return None; - } - let mut out = [0u8; 32]; - out.copy_from_slice(&em[em.len() - 32..]); - Some(out) -} diff --git a/rust/crates/plugin-sso/src/scim.rs b/rust/crates/plugin-sso/src/scim.rs deleted file mode 100644 index e7099a0..0000000 --- a/rust/crates/plugin-sso/src/scim.rs +++ /dev/null @@ -1,602 +0,0 @@ -//! SCIM 2.0 身份供给端点(对齐 MaxKey `maxkey-web-api-scim`)。 -//! -//! 标准协议端点挂在 `/scim/v2/` 下,让外部 HR / 上游 IdP 用标准协议推送用户进来, -//! 无需感知本项目 `users.json` 存储形态。本实现为**单租户精简版**: -//! -//! * Users 完全 CRUD,映射到内核账号(identity 字段走 `extra`); -//! * Groups **派生**自账号的 `groups` 属性(本项目组是账号的平铺多值字段, -//! 不单独建组实体)——所以空组无法表示,这是与 MaxKey 组模型的唯一差异; -//! * 认证用管理员会话(`Guard::Admin`);Bearer / Basic 鉴权留待需要时加。 -//! -//! 响应为 SCIM 原生 JSON(非管理台 `{code,msg,data}` 信封),错误体遵循 -//! SCIM Error 规范。 - -use serde_json::{Value, json}; - -use crate::compat as http; -use ipass_core::models::User; -use ipass_core::util; -use ngx::core::Status; -use ngx::ffi::ngx_http_request_t; -use ngx::http::HTTPStatus; - -use crate::accounts::{self, UserExt}; -use crate::api::{Actor, Guard, Handler}; -use crate::audit; -use ipass_core::users; - -/// SCIM 核心 schema URI -const USER_SCHEMA: &str = "urn:ietf:params:scim:schemas:core:2.0:User"; -const GROUP_SCHEMA: &str = "urn:ietf:params:scim:schemas:core:2.0:Group"; -const ERROR_SCHEMA: &str = "urn:ietf:params:scim:api:messages:2.0:Error"; - -/// 路由:路径含 `{id}` 变量,无法用精确匹配,这里按前缀解析。 -pub fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> { - let g = Guard::Admin; - match (method, uri) { - ("GET", "/scim/v2/ServiceProviderConfig") => Some((g, h_sp_config)), - ("GET", "/scim/v2/Schemas") => Some((g, h_schemas)), - ("GET", "/scim/v2/ResourceTypes") => Some((g, h_resource_types)), - ("GET", "/scim/v2/Users") => Some((g, h_users_list)), - ("POST", "/scim/v2/Users") => Some((g, h_users_create)), - ("GET", "/scim/v2/Groups") => Some((g, h_groups_list)), - ("POST", "/scim/v2/Groups") => Some((g, h_groups_create)), - _ => { - if let Some(id) = uri.strip_prefix("/scim/v2/Users/") { - if !id.is_empty() && !id.contains('/') { - return Some((g, h_users_item)); - } - } - if let Some(id) = uri.strip_prefix("/scim/v2/Groups/") { - if !id.is_empty() && !id.contains('/') { - return Some((g, h_groups_item)); - } - } - None - } - } -} - -// =========================================================================== -// 响应辅助 -// =========================================================================== - -fn scim_send(r: *mut ngx_http_request_t, status: HTTPStatus, body: &Value) -> Status { - http::send(r, status, &body.to_string()) -} - -fn scim_send_with( - r: *mut ngx_http_request_t, - status: HTTPStatus, - body: &Value, - headers: &[(&str, &str)], -) -> Status { - http::send_with(r, status, &body.to_string(), headers) -} - -fn scim_err(r: *mut ngx_http_request_t, status: HTTPStatus, detail: &str) -> Status { - let code = status.0 as u16; - let body = json!({ - "schemas": [ERROR_SCHEMA], - "detail": detail, - "status": code.to_string(), - }); - http::send(r, status, &body.to_string()) -} - -fn base() -> String { - // 复用 OAuth issuer 作为 SCIM base(同主机) - crate::oauth::issuer() -} - -// =========================================================================== -// 映射 -// =========================================================================== - -fn user_to_scim(u: &User) -> Value { - let now = util::now(); - let groups = u.groups(); - let emails = if u.email().is_empty() { - Vec::new() - } else { - vec![json!({ "value": u.email(), "type": "work", "primary": true })] - }; - let phones = if u.mobile().is_empty() { - Vec::new() - } else { - vec![json!({ "value": u.mobile(), "type": "mobile" })] - }; - json!({ - "schemas": [USER_SCHEMA], - "id": u.username, - "userName": u.username, - "displayName": u.display_or_username(), - "name": { "formatted": u.display_name, "familyName": "", "givenName": "" }, - "emails": emails, - "phoneNumbers": phones, - "active": !u.is_locked(now), - "groups": groups.iter().map(|g| json!({ "value": g, "display": g })).collect::>(), - "meta": { - "resourceType": "User", - "created": u.created_at, - "location": format!("{}/scim/v2/Users/{}", base(), u.username), - }, - }) -} - -fn group_to_scim(name: &str, members: &[String]) -> Value { - json!({ - "schemas": [GROUP_SCHEMA], - "id": name, - "displayName": name, - "members": members.iter().map(|m| json!({ "value": m, "display": m })).collect::>(), - "meta": { - "resourceType": "Group", - "location": format!("{}/scim/v2/Groups/{}", base(), name), - }, - }) -} - -/// 从 SCIM User body 抽取创建/更新所需字段。 -struct ScimUserInput { - username: String, - display_name: String, - password: String, - email: String, - mobile: String, - groups: Vec, -} - -fn parse_user_body(body: &Value) -> Result { - let username = body - .get("userName") - .and_then(Value::as_str) - .ok_or("userName 必填")? - .to_owned(); - if username.is_empty() { - return Err("userName 不能为空".to_owned()); - } - let display_name = body - .get("displayName") - .and_then(Value::as_str) - .or_else(|| body.get("name").and_then(|n| n.get("formatted")).and_then(Value::as_str)) - .unwrap_or("") - .to_owned(); - let password = body - .get("password") - .and_then(Value::as_str) - .unwrap_or("ChangeMe123") - .to_owned(); - let email = body - .get("emails") - .and_then(Value::as_array) - .and_then(|a| a.first()) - .and_then(|e| e.get("value").and_then(Value::as_str)) - .unwrap_or("") - .to_owned(); - let mobile = body - .get("phoneNumbers") - .and_then(Value::as_array) - .and_then(|a| a.first()) - .and_then(|p| p.get("value").and_then(Value::as_str)) - .unwrap_or("") - .to_owned(); - let groups = match body.get("groups") { - Some(Value::Array(arr)) => arr - .iter() - .filter_map(|g| g.get("value").and_then(Value::as_str)) - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(), - _ => Vec::new(), - }; - Ok(ScimUserInput { - username, - display_name, - password, - email, - mobile, - groups, - }) -} - -// =========================================================================== -// 元数据端点 -// =========================================================================== - -fn h_sp_config(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let body = json!({ - "schemas": ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"], - "documentationUri": format!("{}/scim/v2/ServiceProviderConfig", base()), - "patch": { "supported": true }, - "bulk": { "supported": false }, - "filter": { "supported": true, "maxResults": 200 }, - "changePassword": { "supported": true }, - "sort": { "supported": false }, - "etag": { "supported": false }, - "authenticationSchemes": [ - { "type": "oauthbearertoken", "name": "OAuth Bearer Token", "description": "管理员会话", "specUri": "https://www.rfc-editor.org/rfc/rfc6750" } - ], - }); - scim_send(r, HTTPStatus::OK, &body) -} - -fn h_schemas(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let body = json!({ - "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], - "totalResults": 2, - "Resources": [ - { - "id": USER_SCHEMA, - "name": "User", - "description": "用户", - "attributes": [ - { "name": "userName", "type": "string", "required": true, "multiValued": false }, - { "name": "displayName", "type": "string", "multiValued": false }, - { "name": "emails", "type": "string", "multiValued": true }, - { "name": "phoneNumbers", "type": "string", "multiValued": true }, - { "name": "active", "type": "boolean", "multiValued": false }, - { "name": "groups", "type": "complex", "multiValued": true } - ] - }, - { - "id": GROUP_SCHEMA, - "name": "Group", - "description": "用户组(派生自账号 groups 属性)", - "attributes": [ - { "name": "displayName", "type": "string", "required": true, "multiValued": false }, - { "name": "members", "type": "complex", "multiValued": true } - ] - } - ] - }); - scim_send(r, HTTPStatus::OK, &body) -} - -fn h_resource_types(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let body = json!({ - "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], - "totalResults": 2, - "Resources": [ - { "id": "User", "name": "User", "endpoint": "/scim/v2/Users", "schema": USER_SCHEMA, "meta": { "resourceType": "ResourceType", "location": format!("{}/scim/v2/ResourceTypes/User", base()) } }, - { "id": "Group", "name": "Group", "endpoint": "/scim/v2/Groups", "schema": GROUP_SCHEMA, "meta": { "resourceType": "ResourceType", "location": format!("{}/scim/v2/ResourceTypes/Group", base()) } } - ] - }); - scim_send(r, HTTPStatus::OK, &body) -} - -// =========================================================================== -// Users -// =========================================================================== - -fn h_users_list(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - // filter=userName eq "x" - let mut filter_user: Option = None; - if let Some(f) = p.get("filter") { - if let Some((_, v)) = f.split_once("eq") { - let v = v.trim().trim_matches('"').to_owned(); - if !v.is_empty() { - filter_user = Some(v); - } - } - } - let start: usize = p.get("startIndex").and_then(|s| s.parse().ok()).unwrap_or(1).max(1); - let count: usize = p.get("count").and_then(|s| s.parse().ok()).unwrap_or(200); - - let all = users::all(); - let filtered: Vec = if let Some(u) = &filter_user { - all.iter() - .filter(|x| x.username == *u) - .map(user_to_scim) - .collect() - } else { - all.iter().map(user_to_scim).collect() - }; - let total = filtered.len(); - let end = (start + count).min(total + 1); - let page: Vec = if start <= total { - filtered[start - 1..end - 1.min(total)].to_vec() - } else { - Vec::new() - }; - - let body = json!({ - "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], - "totalResults": total, - "startIndex": start, - "itemsPerPage": page.len(), - "Resources": page, - }); - scim_send(r, HTTPStatus::OK, &body) -} - -fn h_users_create(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let body = match http::json_body(r) { - Some(Value::Object(_)) => http::body_object(r), - _ => return scim_err(r, HTTPStatus::BAD_REQUEST, "请求体必须是 JSON 对象"), - }; - let input = match parse_user_body(&body) { - Ok(i) => i, - Err(e) => return scim_err(r, HTTPStatus::BAD_REQUEST, &e), - }; - match accounts::create( - &input.username, - &input.display_name, - &input.password, - "user", - &input.email, - &input.mobile, - "", - &input.groups.join(","), - ) { - Ok(u) => { - let operator = actor.admin_name().to_owned(); - audit::log("scim.user.create", &operator, &u.username, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - let scim = user_to_scim(&u); - let loc = scim["meta"]["location"].as_str().unwrap_or("").to_owned(); - scim_send_with(r, HTTPStatus::CREATED, &scim, &[("Location", &loc)]) - } - Err(e) => scim_err(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_users_item(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let uri = http::uri(r); - let id = match uri.strip_prefix("/scim/v2/Users/") { - Some(s) => s.to_owned(), - None => return scim_err(r, HTTPStatus::BAD_REQUEST, "路径解析失败"), - }; - let method = http::method_str(r); - - if method == "GET" { - match users::get(&id) { - Some(u) => scim_send(r, HTTPStatus::OK, &user_to_scim(&u)), - None => scim_err(r, HTTPStatus::NOT_FOUND, &format!("用户 {id} 不存在")), - } - } else if method == "DELETE" { - let operator = actor.admin_name().to_owned(); - match users::delete(&id, &operator) { - Ok(()) => { - audit::log("scim.user.delete", &operator, &id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - scim_send(r, HTTPStatus::NO_CONTENT, &json!({})) - } - Err(e) => scim_err(r, HTTPStatus::BAD_REQUEST, &e), - } - } else if method == "PUT" { - let body = http::body_object(r); - let input = match parse_user_body(&body) { - Ok(i) => i, - Err(e) => return scim_err(r, HTTPStatus::BAD_REQUEST, &e), - }; - match accounts::set_profile( - &id, - &input.email, - &input.mobile, - "", - &input.groups.join(","), - Some(&input.display_name), - ) { - Ok(u) => { - audit::log("scim.user.replace", actor.admin_name(), &id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - scim_send(r, HTTPStatus::OK, &user_to_scim(&u)) - } - Err(e) => scim_err(r, HTTPStatus::BAD_REQUEST, &e), - } - } else if method == "PATCH" { - patch_user(r, &id, actor) - } else { - scim_err(r, HTTPStatus::NOT_ALLOWED, "不支持的方法") - } -} - -/// PATCH 用户:支持 displayName / emails / phoneNumbers / groups 的 add/replace/remove。 -fn patch_user(r: *mut ngx_http_request_t, id: &str, actor: Actor) -> Status { - let body = match http::json_body(r) { - Some(b) => b, - None => return scim_err(r, HTTPStatus::BAD_REQUEST, "请求体必须是 JSON"), - }; - let ops = match body.get("Operations").and_then(Value::as_array) { - Some(a) => a, - None => return scim_err(r, HTTPStatus::BAD_REQUEST, "缺少 Operations"), - }; - - // 收集要改的字段,最后一次性 set_profile - let mut display_name: Option = None; - let mut email: Option = None; - let mut mobile: Option = None; - let mut add_groups: Vec = Vec::new(); - let mut remove_groups: Vec = Vec::new(); - let mut replace_groups: Option> = None; - - for op in ops { - let op_type = op.get("op").and_then(Value::as_str).unwrap_or("").to_ascii_lowercase(); - let path = op.get("path").and_then(Value::as_str).unwrap_or(""); - let value = op.get("value"); - match path { - "displayName" => { - if let Some(v) = value.and_then(Value::as_str) { - display_name = Some(v.to_owned()); - } - } - "emails" => { - if let Some(v) = value.and_then(Value::as_str) { - email = Some(v.to_owned()); - } else if let Some(arr) = value.and_then(Value::as_array) { - email = arr.first().and_then(|e| e.get("value").and_then(Value::as_str)).map(|s| s.to_owned()); - } - } - "phoneNumbers" => { - if let Some(v) = value.and_then(Value::as_str) { - mobile = Some(v.to_owned()); - } else if let Some(arr) = value.and_then(Value::as_array) { - mobile = arr.first().and_then(|p| p.get("value").and_then(Value::as_str)).map(|s| s.to_owned()); - } - } - "groups" => { - let vals: Vec = match value { - Some(Value::Array(a)) => a.iter().filter_map(|g| g.get("value").and_then(Value::as_str)).map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect(), - Some(Value::String(s)) => vec![s.trim().to_owned()], - _ => Vec::new(), - }; - match op_type.as_str() { - "remove" => remove_groups.extend(vals), - "replace" | "add" => { - if op_type == "replace" { - replace_groups = Some(vals.clone()); - } - add_groups.extend(vals); - } - _ => {} - } - } - // 无 path 的 replace:value 是属性对象 - "" => { - if let Some(obj) = value.and_then(|v| v.as_object()) { - if let Some(v) = obj.get("displayName").and_then(Value::as_str) { - display_name = Some(v.to_owned()); - } - if let Some(v) = obj.get("emails").and_then(Value::as_array).and_then(|a| a.first()).and_then(|e| e.get("value").and_then(Value::as_str)) { - email = Some(v.to_owned()); - } - } - } - _ => {} - } - } - - // 读取当前用户组装最终 groups - let cur = match users::get(id) { - Some(u) => u, - None => return scim_err(r, HTTPStatus::NOT_FOUND, &format!("用户 {id} 不存在")), - }; - let mut groups = if let Some(rg) = replace_groups { - rg - } else { - cur.groups() - }; - for g in add_groups { - if !groups.iter().any(|x| x == &g) { - groups.push(g); - } - } - groups.retain(|g| !remove_groups.iter().any(|x| x == g)); - - let final_dn = display_name.unwrap_or_else(|| cur.display_or_username()); - let final_email = email.unwrap_or_else(|| cur.email().to_owned()); - let final_mobile = mobile.unwrap_or_else(|| cur.mobile().to_owned()); - - match accounts::set_profile(id, &final_email, &final_mobile, "", &groups.join(","), Some(&final_dn)) { - Ok(u) => { - audit::log("scim.user.patch", actor.admin_name(), id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - scim_send(r, HTTPStatus::OK, &user_to_scim(&u)) - } - Err(e) => scim_err(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -// =========================================================================== -// Groups(派生) -// =========================================================================== - -/// 聚合所有账号的 groups 属性 → 组名 → 成员列表。 -fn aggregate_groups() -> std::collections::BTreeMap> { - let mut map: std::collections::BTreeMap> = std::collections::BTreeMap::new(); - for u in users::all() { - for g in u.groups() { - map.entry(g).or_default().push(u.username.clone()); - } - } - map -} - -fn h_groups_list(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let map = aggregate_groups(); - let resources: Vec = map.iter().map(|(k, v)| group_to_scim(k, v)).collect(); - let body = json!({ - "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], - "totalResults": resources.len(), - "startIndex": 1, - "itemsPerPage": resources.len(), - "Resources": resources, - }); - scim_send(r, HTTPStatus::OK, &body) -} - -fn h_groups_create(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let body = http::body_object(r); - let name = match body - .get("displayName") - .and_then(Value::as_str) - .or_else(|| body.get("id").and_then(Value::as_str)) - { - Some(n) => n.trim().to_owned(), - None => return scim_err(r, HTTPStatus::BAD_REQUEST, "displayName 必填"), - }; - if name.is_empty() { - return scim_err(r, HTTPStatus::BAD_REQUEST, "displayName 不能为空"); - } - let members: Vec = match body.get("members") { - Some(Value::Array(a)) => a.iter().filter_map(|m| m.get("value").and_then(Value::as_str)).map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect(), - _ => Vec::new(), - }; - if !members.is_empty() { - match accounts::batch_update(&members, &[name.clone()], &[], None, None, false) { - Ok((n, _)) => { - audit::log("scim.group.create", actor.admin_name(), &name, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), &format!("members={n}")); - } - Err(e) => return scim_err(r, HTTPStatus::BAD_REQUEST, &e), - } - } - scim_send(r, HTTPStatus::OK, &group_to_scim(&name, &members)) -} - -fn h_groups_item(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let uri = http::uri(r); - let id = match uri.strip_prefix("/scim/v2/Groups/") { - Some(s) => s.to_owned(), - None => return scim_err(r, HTTPStatus::BAD_REQUEST, "路径解析失败"), - }; - let method = http::method_str(r); - let map = aggregate_groups(); - - if method == "GET" { - match map.get(&id) { - Some(m) => scim_send(r, HTTPStatus::OK, &group_to_scim(&id, m)), - None => scim_err(r, HTTPStatus::NOT_FOUND, &format!("组 {id} 不存在")), - } - } else if method == "DELETE" { - // 从所有成员身上摘掉该组 - let members: Vec = map.get(&id).cloned().unwrap_or_default(); - if !members.is_empty() { - if let Err(e) = accounts::batch_update(&members, &[], &[id.clone()], None, None, false) { - return scim_err(r, HTTPStatus::BAD_REQUEST, &e); - } - } - audit::log("scim.group.delete", actor.admin_name(), &id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - scim_send(r, HTTPStatus::NO_CONTENT, &json!({})) - } else if method == "PUT" || method == "PATCH" { - let body = http::body_object(r); - let wanted: Vec = match body.get("members") { - Some(Value::Array(a)) => a.iter().filter_map(|m| m.get("value").and_then(Value::as_str)).map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect(), - _ => map.get(&id).cloned().unwrap_or_default(), - }; - let current: Vec = map.get(&id).cloned().unwrap_or_default(); - let add: Vec = wanted.iter().filter(|w| !current.iter().any(|c| c == *w)).cloned().collect(); - let remove: Vec = current.iter().filter(|c| !wanted.iter().any(|w| w == *c)).cloned().collect(); - if !add.is_empty() { - if let Err(e) = accounts::batch_update(&add, &[id.clone()], &[], None, None, false) { - return scim_err(r, HTTPStatus::BAD_REQUEST, &e); - } - } - if !remove.is_empty() { - if let Err(e) = accounts::batch_update(&remove, &[], &[id.clone()], None, None, false) { - return scim_err(r, HTTPStatus::BAD_REQUEST, &e); - } - } - audit::log("scim.group.update", actor.admin_name(), &id, true, &http::remote_addr(r), &http::header(r, "user-agent").unwrap_or_default(), ""); - scim_send(r, HTTPStatus::OK, &group_to_scim(&id, &wanted)) - } else { - scim_err(r, HTTPStatus::NOT_ALLOWED, "不支持的方法") - } -} diff --git a/rust/crates/plugin-sso/src/storex.rs b/rust/crates/plugin-sso/src/storex.rs deleted file mode 100644 index f514d36..0000000 --- a/rust/crates/plugin-sso/src/storex.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! 插件自有数据文件的存储扩展(sso 插件本地层)。 -//! -//! 来源:原内核 `store.rs` 的「插件自有数据文件」一节。内核以上游 ipass -//! 为基准后(其 A5 决策:`path_in_data` 为唯一口径,插件自管文件名), -//! 这组封装落在本插件。文件名沿用历史形状(`oauth_clients.json` 等, -//! 仍在 `data/` 直下),**存量数据文件无需迁移**。 -//! -//! 与内核 `update_users` 同构:取全局文件锁 → 读 → 闭包改 → 原子写回 → 放锁。 - -use ipass_core::state; -use ipass_core::store; - -/// 插件数据文件路径(`data/` 直下,与上游 `path_in_data` 同一口径)。 -pub fn plugin_path(name: &str) -> std::path::PathBuf { - store::path_in_data(name) -} - -pub fn read_plugin(name: &str) -> T { - store::read_json(&plugin_path(name), T::default()) -} - -pub fn write_plugin(name: &str, data: &T) -> Result<(), String> { - store::write_json(&plugin_path(name), data) -} - -/// 加锁「读-改-写」一个插件自有 JSON 文件。 -/// -/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。 -/// `T` 由调用方给出(读失败回退 `Default`,写回的是闭包改后的完整模型)。 -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/rust/crates/plugin-sso/src/sync.rs b/rust/crates/plugin-sso/src/sync.rs deleted file mode 100644 index 7068fba..0000000 --- a/rust/crates/plugin-sso/src/sync.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! 同步连接器(对齐 MaxKey `maxkey-synchronizer`:钉钉 / 企微 / 飞书)。 -//! -//! **手动触发端点**:`POST /api/admin/sync/`,由外部 cron / 运维脚本调用, -//! 不引入后台进程(与「零常驻依赖」硬约束一致)。 -//! -//! 流程:从配置好的用户目录源拉取成员列表 → 归一化为内部账号字段 → upsert 进 -//! `users.json`。每个 provider 的拉取地址由 `SYNC__URL` 配置, -//! 默认指向真实开放平台端点;本地联调 / e2e 把它指到 mock 即可,无需改代码。 -//! -//! 网络层用标准库 `TcpStream` 做最简 HTTP GET(不引第三方 HTTP 客户端), -//! 满足「零外部依赖」;生产可换 HTTPS(由部署侧反向代理或上层 TLS 终结)。 - -use std::io::{Read, Write}; -use std::net::TcpStream; - -use ngx::ffi::ngx_http_request_t; -use serde_json::{Value, json}; - -use ipass_core::http; -use ipass_core::users; -use ipass_core::util; -use ngx::core::Status; -use ngx::http::HTTPStatus; - -use crate::accounts; -use crate::audit; - -/// 支持的 provider(路径第三段) -const PROVIDERS: &[&str] = &["dingtalk", "workwechat", "feishu"]; - -/// 路由:`/api/admin/sync/`(POST,管理员) -pub fn route(method: &str, uri: &str) -> Option<(crate::api::Guard, crate::api::Handler)> { - if method != "POST" { - return None; - } - if let Some(provider) = uri.strip_prefix("/api/admin/sync/") { - if !provider.is_empty() && !provider.contains('/') && PROVIDERS.contains(&provider) { - return Some((crate::api::Guard::Admin, h_sync)); - } - } - None -} - -/// 极简 HTTP GET(HTTP/1.1,Connection: close,读到 EOF)。返回响应体字符串。 -fn http_get(url: &str) -> Option { - // 仅支持 http://host:port/path(同步源在内网,由上层 TLS 终结) - let rest = url.strip_prefix("http://")?; - let (hostport, path) = match rest.split_once('/') { - Some((h, p)) => (h, format!("/{p}")), - None => (rest, "/".to_owned()), - }; - let (host, port) = match hostport.split_once(':') { - Some((h, p)) => (h.to_owned(), p.parse::().ok()?), - None => (hostport.to_owned(), 80), - }; - - let mut stream = TcpStream::connect((host.as_str(), port)).ok()?; - stream.set_read_timeout(Some(std::time::Duration::from_secs(10))).ok()?; - let req = format!( - "GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: application/json\r\n\r\n" - ); - stream.write_all(req.as_bytes()).ok()?; - - let mut buf = Vec::new(); - stream.read_to_end(&mut buf).ok()?; - let text = String::from_utf8_lossy(&buf); - let body = match text.split_once("\r\n\r\n") { - Some((head, b)) => { - // 有 Content-Length 就精确截取,否则用 Connection: close 读到的全部 - let cl = head.lines().find_map(|l| { - if l.len() >= 15 && l[..15].eq_ignore_ascii_case("content-length:") { - l[15..].trim().parse::().ok() - } else { - None - } - }); - match cl { - Some(n) if b.len() >= n => b[..n].to_owned(), - _ => b.to_owned(), - } - } - None => String::new(), - }; - Some(body) -} - -/// 取 provider 的用户目录源地址(env 优先,否则真实开放平台默认端点)。 -fn source_url(provider: &str) -> Option { - let key = format!("SYNC_{}_URL", provider.to_ascii_uppercase()); - if let Ok(v) = std::env::var(&key) { - if !v.is_empty() { - return Some(v); - } - } - // 真实开放平台默认端点(仅占位;生产应配置 AK/SK 与正确的拉取接口) - let default = match provider { - "dingtalk" => "https://oapi.dingtalk.com/topapi/v2/user/list", - "workwechat" => "https://qyapi.weixin.qq.com/cgi-bin/user/list", - "feishu" => "https://open.feishu.cn/open-apis/contact/v3/users", - _ => return None, - }; - Some(default.to_owned()) -} - -/// 单次同步:拉取 → 归一化 → upsert。 -fn h_sync(r: *mut ngx_http_request_t, actor: crate::api::Actor) -> Status { - let provider = http::uri(r) - .strip_prefix("/api/admin/sync/") - .unwrap_or("") - .to_owned(); - let operator = actor.admin_name().to_owned(); - let ip = http::remote_addr(r); - let ua = http::header(r, "user-agent").unwrap_or_default(); - - let url = match source_url(&provider) { - Some(u) => u, - None => return http::fail(r, HTTPStatus::BAD_REQUEST, &format!("未知 provider:{provider}")), - }; - - let body = match http_get(&url) { - Some(b) => b, - None => return http::fail(r, HTTPStatus::BAD_REQUEST, &format!("拉取 {provider} 用户源失败(地址:{url})")), - }; - - let parsed: Value = match serde_json::from_str::(&body) { - Ok(v) => v, - Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &format!("用户源返回非 JSON:{e}")), - }; - - // 归一化契约:`{ "users": [ {username, display_name, email, mobile, department, groups:[...]} ] }` - let users_arr = match parsed.get("users").and_then(Value::as_array) { - Some(a) => a, - None => return http::fail(r, HTTPStatus::BAD_REQUEST, "用户源缺少 users 数组"), - }; - - let mut created = 0usize; - let mut updated = 0usize; - let mut skipped: Vec = Vec::new(); - - for item in users_arr { - let username = match item.get("username").and_then(Value::as_str) { - Some(s) if !s.is_empty() => s.trim().to_owned(), - _ => { - skipped.push("缺少 username".to_owned()); - continue; - } - }; - let display_name = item.get("display_name").and_then(Value::as_str).unwrap_or("").to_owned(); - let email = item.get("email").and_then(Value::as_str).unwrap_or("").to_owned(); - let mobile = item.get("mobile").and_then(Value::as_str).unwrap_or("").to_owned(); - let department = item.get("department").and_then(Value::as_str).unwrap_or("").to_owned(); - let groups: Vec = match item.get("groups") { - Some(Value::Array(a)) => a - .iter() - .filter_map(|g| g.as_str()) - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(), - _ => Vec::new(), - }; - let groups_csv = groups.join(","); - - if users::get(&username).is_some() { - match accounts::set_profile(&username, &email, &mobile, &department, &groups_csv, Some(&display_name)) { - Ok(_) => updated += 1, - Err(e) => skipped.push(format!("{username}: {e}")), - } - } else { - let pw = util::gen_key(); - match accounts::create(&username, &display_name, &pw, "user", &email, &mobile, &department, &groups_csv) { - Ok(_) => created += 1, - Err(e) => skipped.push(format!("{username}: {e}")), - } - } - } - - audit::log( - "sync.run", - &operator, - &provider, - true, - &ip, - &ua, - &format!("created={created} updated={updated} skipped={}", skipped.len()), - ); - http::ok( - r, - json!({ "provider": provider, "created": created, "updated": updated, "skipped": skipped }), - &format!("同步完成:新增 {created} / 更新 {updated}"), - ) -} diff --git a/rust/crates/plugin-sso/src/utilx.rs b/rust/crates/plugin-sso/src/utilx.rs deleted file mode 100644 index 251d871..0000000 --- a/rust/crates/plugin-sso/src/utilx.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! 插件自有的字符串工具(内核 `util` 没有的部分)。 -//! -//! 来源:原内核 `util.rs` 的 `html_escape` / `url_encode`。 -//! 内核以上游 ipass 为基准后这两个函数不在内核里,落在本插件。 - -/// 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 -} - -/// URL 百分号编码(授权码流程的 redirect_uri / state 拼接用)。 -pub fn url_encode(input: &str) -> String { - let mut out = String::with_capacity(input.len()); - for &b in input.as_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_str(&format!("%{b:02X}")), - } - } - out -} diff --git a/rust/gateway/Cargo.toml b/rust/gateway/Cargo.toml index c9afdaa..d911183 100644 --- a/rust/gateway/Cargo.toml +++ b/rust/gateway/Cargo.toml @@ -19,4 +19,4 @@ export-modules = [] ngx.workspace = true nginx-sys.workspace = true ipass-core.workspace = true -plugin-sso.workspace = true +ipass-plugin-sso.workspace = true diff --git a/rust/gateway/src/lib.rs b/rust/gateway/src/lib.rs index 859aeca..43d4b9b 100644 --- a/rust/gateway/src/lib.rs +++ b/rust/gateway/src/lib.rs @@ -43,7 +43,7 @@ use ngx::http::{ MergeConfigError, }; use ngx::{ngx_conf_log_error, ngx_string}; -use plugin_sso::SsoPlugin; +use ipass_plugin_sso::SsoPlugin; /// 插件清单。**顺序即装配顺序**:preconfig → postconfig → dispatch_api, /// dispatch 按顺序认领、先注册者先得。 diff --git a/www/admin.html b/www/admin.html deleted file mode 100644 index a953cf0..0000000 --- a/www/admin.html +++ /dev/null @@ -1,1552 +0,0 @@ - - - - - -统一认证 · 管理台 - - - - - - - - - - -
- - - -