- source/rust → rust/ - source/conf → conf/ - source/www → www/ - source/data-seed → data-seed/ - source/data → data/ - scripts/ 保留(语义不对应 ipass deploy/) - /build/ 加入 .gitignore(本机 nginx 源码树) - README.md 目录树同步 + build 路径 /tmp/sso-build → ./build - Cargo.toml path 依赖 '../../deps/ipass' → '../deps/ipass' - CLAUDE.md 同步路径示例 cargo check 通过(52s);release build 通过(1m26s),产物 libsso_gateway.dylib
1071 lines
47 KiB
Rust
1071 lines
47 KiB
Rust
//! 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<Value> = 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<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().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<Value> = 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<String> {
|
||
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<String> {
|
||
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<Value> = 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")
|
||
}
|