refactor(sso): plugin-sso 适配上游内核(身份语义迁入插件层)
上游决策 A4/A5 的落点: - accounts.rs(新):UserExt 扩展 trait(email/department/groups/锁定态存 extra 强类型读写)、账号操作 create/set_profile/set_role/batch_update/ unlock/record_login_failure(经 store::update_users + sync_shm 官方路径)、 管理台 view、身份校验(口令策略 8 位留插件层,A6-1) - storex.rs(新):插件文件读写(path_in_data 口径,A5),存量数据文件零迁移 - utilx.rs(新):html_escape/url_encode(内核以上游为准后移入插件) - audit.rs(新):原内核审计模块迁入(仅 sso 使用) - update_extra 闭包适配上游 FnOnce(&mut User) 签名;字段访问改 UserExt 方法
This commit is contained in:
1 parent
74e5678188
commit
7764fa76b7
9 files changed
+803
-51
No files matched your search
@@ -0,0 +1,520 @@
|
||||
//! 账号身份扩展层(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_FAILED_COUNT: &str = "failed_count";
|
||||
pub const EXTRA_LOCKED_UNTIL: &str = "locked_until";
|
||||
|
||||
// ===========================================================================
|
||||
// UserExt:User 的身份字段强类型访问(全部落在 extra)
|
||||
// ===========================================================================
|
||||
|
||||
pub trait UserExt {
|
||||
// ---- 读 ----
|
||||
fn email(&self) -> &str;
|
||||
fn department(&self) -> &str;
|
||||
/// 用户组(同时接受 `["a","b"]` 数组与 `"a,b"` CSV 两种存量写法)
|
||||
fn groups(&self) -> Vec<String>;
|
||||
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<String>;
|
||||
// ---- 写(在 `store::update_users` / `users::update_extra` 闭包内用)----
|
||||
fn set_email(&mut self, v: &str);
|
||||
fn set_department(&mut self, v: &str);
|
||||
fn set_groups(&mut self, v: Vec<String>);
|
||||
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 department(&self) -> &str {
|
||||
self.extra_str(EXTRA_DEPARTMENT)
|
||||
}
|
||||
fn groups(&self) -> Vec<String> {
|
||||
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<String> {
|
||||
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_department(&mut self, v: &str) {
|
||||
self.extra
|
||||
.insert(EXTRA_DEPARTMENT.to_owned(), Value::String(v.to_owned()));
|
||||
}
|
||||
fn set_groups(&mut self, v: Vec<String>) {
|
||||
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<String, String> {
|
||||
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<String, String> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// 部门名:禁止控制字符。
|
||||
pub fn check_department(raw: &str) -> Result<String, String> {
|
||||
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<Vec<String>, String> {
|
||||
let mut out: Vec<String> = 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,
|
||||
department: &str,
|
||||
groups: &str,
|
||||
) -> Result<User, String> {
|
||||
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 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_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,
|
||||
department: &str,
|
||||
groups_raw: &str,
|
||||
display_name: Option<&str>,
|
||||
) -> Result<User, String> {
|
||||
let email = check_email(email)?;
|
||||
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_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>), 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<String> = 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<User, String> {
|
||||
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<User, 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(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(),
|
||||
"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_DEPARTMENT | EXTRA_GROUPS | EXTRA_FAILED_COUNT | EXTRA_LOCKED_UNTIL) {
|
||||
continue;
|
||||
}
|
||||
obj.insert(k.clone(), val.clone());
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
@@ -17,10 +17,11 @@ use ngx::ffi::ngx_http_request_t;
|
||||
use ngx::http::HTTPStatus;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use ipass_core::audit;
|
||||
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;
|
||||
@@ -324,7 +325,7 @@ fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
// 账号维度锁定(与 IP 维度限速叠加):锁定期内密码正确也拒绝,
|
||||
// 避免攻击者换 IP 继续爆破同一账号。
|
||||
if user.is_locked(now) {
|
||||
let remain = user.locked_until - 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(
|
||||
@@ -338,7 +339,7 @@ fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
state::bump_login_fail(&ip, now);
|
||||
// 账号维度累计:达到阈值即锁定(用户必然存在,失败只可能是锁不可用)
|
||||
let mut detail = "密码错误".to_owned();
|
||||
if let Ok((cnt, until)) = users::record_login_failure(&username, now) {
|
||||
if let Ok((cnt, until)) = accounts::record_login_failure(&username, now) {
|
||||
if until > now {
|
||||
detail = format!("密码错误,已触发锁定至 {until}");
|
||||
} else {
|
||||
@@ -368,13 +369,13 @@ fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
}
|
||||
|
||||
state::clear_login_fail(&ip);
|
||||
let _ = users::clear_login_failure(&username);
|
||||
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, users::view(&user), "登录成功", &[("Set-Cookie", &cookie)])
|
||||
http::ok_with(r, accounts::view(&user), "登录成功", &[("Set-Cookie", &cookie)])
|
||||
}
|
||||
|
||||
fn h_logout(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
@@ -389,7 +390,7 @@ 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, users::view(&user), "ok")
|
||||
http::ok(r, accounts::view(&user), "ok")
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
@@ -554,7 +555,7 @@ fn h_admin_user_totp_enable(r: *mut ngx_http_request_t, actor: Actor) -> Status
|
||||
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, users::view(&u), "双因子已启用")
|
||||
http::ok(r, accounts::view(&u), "双因子已启用")
|
||||
}
|
||||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||||
}
|
||||
@@ -568,7 +569,7 @@ fn h_admin_user_totp_disable(r: *mut ngx_http_request_t, actor: Actor) -> Status
|
||||
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, users::view(&u), "双因子已解绑")
|
||||
http::ok(r, accounts::view(&u), "双因子已解绑")
|
||||
}
|
||||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||||
}
|
||||
@@ -599,11 +600,11 @@ fn h_admin_users(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
let mut departments: Vec<String> = Vec::new();
|
||||
let mut groups: Vec<String> = Vec::new();
|
||||
for u in &all {
|
||||
if !u.department.is_empty() && !departments.iter().any(|d| d == &u.department) {
|
||||
departments.push(u.department.clone());
|
||||
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) {
|
||||
for g in u.groups() {
|
||||
if !groups.iter().any(|x| *x == g) {
|
||||
groups.push(g.clone());
|
||||
}
|
||||
}
|
||||
@@ -611,7 +612,7 @@ fn h_admin_users(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
departments.sort();
|
||||
groups.sort();
|
||||
|
||||
let items: Vec<Value> = all.iter().map(users::view).collect();
|
||||
let items: Vec<Value> = all.iter().map(accounts::view).collect();
|
||||
|
||||
http::ok(
|
||||
r,
|
||||
@@ -629,7 +630,7 @@ fn h_admin_user_create(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();
|
||||
|
||||
match users::create(
|
||||
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(""),
|
||||
@@ -641,10 +642,10 @@ fn h_admin_user_create(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
Ok(user) => {
|
||||
util::log_notice(&format!(
|
||||
"[api] 创建账号 {} name={} role={} dept={}",
|
||||
user.username, user.display_name, user.role, user.department
|
||||
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, users::view(&user), "账号创建成功")
|
||||
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);
|
||||
@@ -659,7 +660,7 @@ fn h_admin_user_display(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
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, users::view(&u), "已更新展示名"),
|
||||
Ok(u) => http::ok(r, accounts::view(&u), "已更新展示名"),
|
||||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
@@ -673,7 +674,7 @@ fn h_admin_user_profile(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
// display_name 缺省 = 不动(避免「只改部门却把姓名清空」这类误伤)
|
||||
let display_name = p.get("display_name").map(String::as_str);
|
||||
|
||||
match users::set_profile(
|
||||
match accounts::set_profile(
|
||||
&username,
|
||||
p.get("email").map(String::as_str).unwrap_or(""),
|
||||
p.get("department").map(String::as_str).unwrap_or(""),
|
||||
@@ -683,10 +684,10 @@ fn h_admin_user_profile(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
Ok(u) => {
|
||||
util::log_notice(&format!(
|
||||
"[api] 更新身份 {username} email={} dept={} groups={:?}",
|
||||
u.email, u.department, u.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, users::view(&u), "已更新身份信息")
|
||||
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),
|
||||
}
|
||||
@@ -701,11 +702,11 @@ fn h_admin_user_role(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
if role != "admin" && role != "user" {
|
||||
return http::fail(r, HTTPStatus::BAD_REQUEST, "角色只能是 admin 或 user");
|
||||
}
|
||||
match users::set_role(&username, role) {
|
||||
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, users::view(&u), "已更新角色")
|
||||
http::ok(r, accounts::view(&u), "已更新角色")
|
||||
}
|
||||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||||
}
|
||||
@@ -735,7 +736,7 @@ fn h_admin_user_batch(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
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 users::batch_update(&usernames, &add_groups, &remove_groups, department, role, unlock) {
|
||||
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}",
|
||||
@@ -777,7 +778,7 @@ 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 users::unlock(&username) {
|
||||
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(), "");
|
||||
@@ -968,7 +969,7 @@ fn h_me(r: *mut ngx_http_request_t, actor: Actor) -> Status {
|
||||
return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或缺失,请在请求头携带 X-API-Key");
|
||||
};
|
||||
|
||||
let mut v = users::view(&user);
|
||||
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()));
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
//! 审计日志(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,
|
||||
"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<Value> {
|
||||
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<Value> = Vec::new();
|
||||
for line in text.lines().rev() {
|
||||
if out.len() >= limit {
|
||||
break;
|
||||
}
|
||||
let Ok(v) = serde_json::from_str::<Value>(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",
|
||||
];
|
||||
@@ -9,7 +9,9 @@
|
||||
//! 本插件**不持有**账号数据——只读 `ipass_core::users`,写入一律走内核。
|
||||
//! 这是「SSO 与域名 / LLM 共用同一份 `users.json`、同一把 API Key」的落点。
|
||||
|
||||
mod accounts;
|
||||
mod api;
|
||||
mod audit;
|
||||
mod captcha;
|
||||
mod otp;
|
||||
pub mod oauth;
|
||||
@@ -17,6 +19,8 @@ mod oauth_clients;
|
||||
mod oauth_keys;
|
||||
mod oauth_state;
|
||||
mod rsa;
|
||||
mod storex;
|
||||
mod utilx;
|
||||
|
||||
use core::ptr;
|
||||
use core::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -94,7 +98,7 @@ impl HttpRequestHandler for IapHandler {
|
||||
type Output = Status;
|
||||
|
||||
fn handler(request: &mut ngx::http::Request) -> Self::Output {
|
||||
if !ipass_core::loc::enabled(request, ipass_core::loc::Switch::Iap) {
|
||||
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;
|
||||
|
||||
@@ -42,7 +42,7 @@ use ngx::core::{Buffer, Status};
|
||||
use ngx::ffi::ngx_http_request_t;
|
||||
use ngx::http::HTTPStatus;
|
||||
|
||||
use ipass_core::audit;
|
||||
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,
|
||||
@@ -50,9 +50,11 @@ use crate::oauth_keys::{
|
||||
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;
|
||||
|
||||
// ===========================================================================
|
||||
@@ -482,9 +484,9 @@ fn sso_payload(u: &User) -> String {
|
||||
format!(
|
||||
"{}\n{}\n{}\n{}\n{}",
|
||||
u.username,
|
||||
u.email,
|
||||
u.groups.join(","),
|
||||
u.department,
|
||||
u.email(),
|
||||
u.groups().join(","),
|
||||
u.department(),
|
||||
if u.display_name.is_empty() {
|
||||
u.username.clone()
|
||||
} else {
|
||||
@@ -649,7 +651,7 @@ pub fn authorize(r: *mut ngx_http_request_t) -> Status {
|
||||
None => {
|
||||
// 未登录 → 302 到登录页,登录后跳回本授权地址
|
||||
let back = current_url(r);
|
||||
let loc = format!("{}/login?redirect={}", issuer(), util::url_encode(&back));
|
||||
let loc = format!("{}/login?redirect={}", issuer(), utilx::url_encode(&back));
|
||||
return redirect(r, &loc);
|
||||
}
|
||||
};
|
||||
@@ -672,7 +674,7 @@ pub fn authorize(r: *mut ngx_http_request_t) -> Status {
|
||||
|
||||
let mut loc = format!("{redirect_uri}?code={code}");
|
||||
if !state_param.is_empty() {
|
||||
loc.push_str(&format!("&state={}", util::url_encode(&state_param)));
|
||||
loc.push_str(&format!("&state={}", utilx::url_encode(&state_param)));
|
||||
}
|
||||
redirect(r, &loc)
|
||||
}
|
||||
@@ -801,7 +803,7 @@ fn token_impl(r: *mut ngx_http_request_t, bare: bool) -> Status {
|
||||
return oauth_error(r, HTTPStatus(423), "account_locked", "账号已锁定,请稍后重试");
|
||||
}
|
||||
if !util::verify_password(&pass, &user.salt, &user.pwd_hash) {
|
||||
let _ = users::record_login_failure(&uname, now);
|
||||
let _ = accounts::record_login_failure(&uname, now);
|
||||
return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "密码错误");
|
||||
}
|
||||
// TOTP 第二因子:password grant 同样不允许绕过
|
||||
@@ -811,7 +813,7 @@ fn token_impl(r: *mut ngx_http_request_t, bare: bool) -> Status {
|
||||
return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "动态验证码不正确或已过期");
|
||||
}
|
||||
}
|
||||
let _ = users::clear_login_failure(&uname);
|
||||
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)
|
||||
}
|
||||
@@ -841,7 +843,7 @@ fn issue_tokens(
|
||||
) -> Status {
|
||||
let user = users::get(sub);
|
||||
let (email, name, groups, department) = match &user {
|
||||
Some(u) => (u.email.clone(), if u.display_name.is_empty() { u.username.clone() } else { u.display_name.clone() }, u.groups.clone(), u.department.clone()),
|
||||
Some(u) => (u.email().to_owned(), if u.display_name.is_empty() { u.username.clone() } else { u.display_name.clone() }, u.groups(), u.department().to_owned()),
|
||||
None => (String::new(), sub.to_owned(), vec![], String::new()),
|
||||
};
|
||||
let (Some(access), Some(refresh)) = (
|
||||
@@ -1107,13 +1109,13 @@ pub fn login_post(r: *mut ngx_http_request_t) -> Status {
|
||||
|
||||
// 账号维度锁定:与管理台登录(api::h_login)同一套阈值与文案
|
||||
if user.is_locked(now0) {
|
||||
let remain = user.locked_until - 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 _ = users::record_login_failure(&username, now0);
|
||||
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);
|
||||
}
|
||||
@@ -1290,11 +1292,11 @@ const LOGIN_STYLE: &str = r#"
|
||||
/// `redirect` / `username` / `password` 三个字段名与表单 `action="/login"` 是对外
|
||||
/// 契约(e2e 与接入方都在依赖),改样式时不要动。
|
||||
fn login_html(redirect: &str, error: &str) -> String {
|
||||
let red = util::html_escape(redirect);
|
||||
let red = utilx::html_escape(redirect);
|
||||
let err = if error.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("<div class=\"err\">{}</div>", util::html_escape(error))
|
||||
format!("<div class=\"err\">{}</div>", utilx::html_escape(error))
|
||||
};
|
||||
// 图形验证码块:仅 OAUTH_CAPTCHA=1 时注入。页面 JS 从 /api/captcha 取码
|
||||
// 注入 SVG,提交时携带 captcha_id / captcha_code(一次性,失败需刷新)。
|
||||
@@ -1328,7 +1330,7 @@ fn login_html(redirect: &str, error: &str) -> String {
|
||||
{
|
||||
Some(host) => format!(
|
||||
"<div class=\"target\">登录成功后将返回 <b>{}</b></div>",
|
||||
util::html_escape(host)
|
||||
utilx::html_escape(host)
|
||||
),
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::oauth_keys::{
|
||||
KEY_OAUTH_CLIENT_PREFIX, KEY_OAUTH_CODE_PREFIX, KEY_OAUTH_SESS_PREFIX,
|
||||
};
|
||||
use ipass_core::state;
|
||||
use ipass_core::store;
|
||||
use crate::storex;
|
||||
|
||||
// ===========================================================================
|
||||
// 数据模型(原内核 `models::OAuthClient`;属插件个性,迁到本插件)
|
||||
@@ -64,7 +64,7 @@ impl OAuthClient {
|
||||
|
||||
/// 读取注册表文件(内核只提供带锁原子读,不认识结构)。
|
||||
pub fn read_oauth_clients() -> OAuthClientTable {
|
||||
store::read_plugin::<OAuthClientTable>("oauth_clients.json")
|
||||
storex::read_plugin::<OAuthClientTable>("oauth_clients.json")
|
||||
}
|
||||
|
||||
/// 加锁「读-改-写」注册表文件,闭包返回新值;`Err` 不落盘。
|
||||
@@ -74,7 +74,7 @@ where
|
||||
{
|
||||
let mut table = read_oauth_clients();
|
||||
let out = f(&mut table)?;
|
||||
store::write_plugin("oauth_clients.json", &table)?;
|
||||
storex::write_plugin("oauth_clients.json", &table)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::accounts::UserExt;
|
||||
use ipass_core::models::User;
|
||||
use ipass_core::users;
|
||||
use ipass_core::util;
|
||||
@@ -234,8 +235,8 @@ pub fn secret(user: &User) -> String {
|
||||
/// 启用前可重复 setup 重取。
|
||||
pub fn setup(username: &str) -> Result<(String, String), String> {
|
||||
let sec = gen_secret();
|
||||
users::update_extra(username, |extra| {
|
||||
extra.insert(EXTRA_TOTP_SECRET.to_owned(), Value::String(sec.clone()));
|
||||
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);
|
||||
@@ -254,8 +255,8 @@ pub fn enable(username: &str, code: &str, now: i64) -> Result<User, String> {
|
||||
if !verify(&sec, code, now as u64) {
|
||||
return Err("动态验证码不正确或已过期".to_owned());
|
||||
}
|
||||
users::update_extra(username, |extra| {
|
||||
extra.insert(EXTRA_TOTP_ENABLED.to_owned(), Value::Bool(true));
|
||||
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())
|
||||
@@ -263,9 +264,9 @@ pub fn enable(username: &str, code: &str, now: i64) -> Result<User, String> {
|
||||
|
||||
/// 解绑:删除种子与启用标记。返回更新后的账号。
|
||||
pub fn disable(username: &str) -> Result<User, String> {
|
||||
users::update_extra(username, |extra| {
|
||||
extra.remove(EXTRA_TOTP_SECRET);
|
||||
extra.remove(EXTRA_TOTP_ENABLED);
|
||||
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())
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! 插件自有数据文件的存储扩展(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<T: serde::de::DeserializeOwned + Default>(name: &str) -> T {
|
||||
store::read_json(&plugin_path(name), T::default())
|
||||
}
|
||||
|
||||
pub fn write_plugin<T: serde::Serialize>(name: &str, data: &T) -> Result<(), String> {
|
||||
store::write_json(&plugin_path(name), data)
|
||||
}
|
||||
|
||||
/// 加锁「读-改-写」一个插件自有 JSON 文件。
|
||||
///
|
||||
/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。
|
||||
/// `T` 由调用方给出(读失败回退 `Default`,写回的是闭包改后的完整模型)。
|
||||
pub fn update_plugin<T, F>(name: &str, f: F) -> Result<T, String>
|
||||
where
|
||||
T: serde::de::DeserializeOwned + serde::Serialize + Default,
|
||||
F: FnOnce(&mut T) -> Result<T, String>,
|
||||
{
|
||||
let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?;
|
||||
let mut data = read_plugin(name);
|
||||
let out = f(&mut data)?;
|
||||
write_plugin(name, &data)?;
|
||||
Ok(out)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//! 插件自有的字符串工具(内核 `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
|
||||
}
|
||||
Reference in new issue
Block a user