feat(sso): MaxKey 迁移 P1/P2 —— SCIM/CAS/LDAP/同步连接器/自助密码重置/归属地
- 新增 plugin-sso 模块(零新增 crate):scim.rs(SCIM 2.0)、cas.rs(CAS 1.0/2.0)、 ldap.rs(LDAP/AD,手写 BER/ASN.1 Simple Bind)、sync.rs(钉钉/企微/飞书手动触发同步)、 reset.rs(自助密码重置)、geo.rs(登录 IP 归属地) - api.rs 兜底路由按 scim→cas→reset→sync 分发兄弟模块;h_login 集成 LDAP(未启用零行为变化) - 修 http::redirect 空 body 触发 NGX_ERROR(CAS 302 无 Location 的根因) - nginx.conf / nginx.test.conf 补 env SYNC_* / PASSWORD_RESET_*(worker 可见) - 新增第 7 套 e2e tests/maxkey-p1p2-e2e.sh(21 项),harness 接入 [7/7];七套全绿 rc=0 - 修脚本 $var 紧跟全角字符被并入变量名的 shell 坑(tests + scripts) - 文档同步:maxkey-migration-analysis(P1/P2 状态) / roadmap(v4) / CLAUDE.md / README.md
This commit is contained in:
1 parent
f3aabb3405
commit
4a780a4ce7
20 files changed
+1986
-37
No files matched your search
@@ -25,6 +25,12 @@ env ADMIN_INIT_PASSWORD; # 播种管理员口令,仅首次启动用
|
||||
env OAUTH_SIGNING_SECRET; # HS256 对称密钥;不设则每次重启令牌全失效
|
||||
env OAUTH_ISSUER; # 令牌 iss 与 discovery 的 issuer,必须等于对外访问地址
|
||||
env OAUTH_COOKIE_DOMAIN; # 跨子域 SSO 用,如 .example.com
|
||||
# P1/P2 新增模块的 worker 可见环境变量(nginx 默认剥离全部 env,必须显式白名单)
|
||||
env SYNC_DINGTALK_URL; # 同步连接器:钉钉用户目录源地址
|
||||
env SYNC_WORKWECHAT_URL; # 同步连接器:企业微信用户目录源地址
|
||||
env SYNC_FEISHU_URL; # 同步连接器:飞书用户目录源地址
|
||||
env PASSWORD_RESET_TOKEN_SINK;# 自助密码重置:token 落盘路径(不设则仅日志输出)
|
||||
env PASSWORD_RESET_TTL; # 自助密码重置:token 有效期秒(可选,缺省 1800)
|
||||
|
||||
events {
|
||||
worker_connections 2048;
|
||||
|
||||
@@ -33,6 +33,16 @@ env OAUTH_SIGNING_SECRET;
|
||||
env OAUTH_ISSUER;
|
||||
env OAUTH_COOKIE_DOMAIN;
|
||||
|
||||
# P1/P2 新增模块的 worker 可见环境变量(nginx 默认剥离全部 env,必须显式白名单)。
|
||||
# 同步连接器:各 provider 的用户目录 URL(未声明则走各平台默认开放端点)。
|
||||
env SYNC_DINGTALK_URL;
|
||||
env SYNC_WORKWECHAT_URL;
|
||||
env SYNC_FEISHU_URL;
|
||||
# 自助密码重置:token 落盘路径(未声明则仅在日志输出,不落盘)。
|
||||
env PASSWORD_RESET_TOKEN_SINK;
|
||||
# 自助密码重置:token 有效期秒(可选,缺省 1800)。
|
||||
env PASSWORD_RESET_TTL;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
@@ -152,6 +152,36 @@ pub fn params(r: *mut ngx_http_request_t) -> HashMap<String, String> {
|
||||
map
|
||||
}
|
||||
|
||||
/// 读取并解析请求体为 JSON(`Content-Type: application/json` 时)。
|
||||
///
|
||||
/// 非 JSON 体或解析失败返回 `None`——调用方据此回退到 `params` 或报错。
|
||||
/// SCIM / CAS / 同步连接器 / 自助密码重置等需要嵌套 JSON(数组、对象)的
|
||||
/// 端点用它取代 `params`(后者只认标量值)。
|
||||
pub fn json_body(r: *mut ngx_http_request_t) -> Option<Value> {
|
||||
let body = unsafe { collect_body(r) };
|
||||
if body.is_empty() {
|
||||
return None;
|
||||
}
|
||||
serde_json::from_slice::<Value>(&body).ok()
|
||||
}
|
||||
|
||||
/// 合并 query 与 JSON 请求体为单一 `Value::Object`:
|
||||
/// JSON 体的嵌套结构原样保留,query 的标量覆盖同名顶层键。
|
||||
///
|
||||
/// SCIM/PATCH 等既可能走 form 也可能走 JSON 的场景统一入口。
|
||||
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(&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)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 响应
|
||||
// ===========================================================================
|
||||
@@ -198,6 +228,49 @@ pub fn send(r: *mut ngx_http_request_t, status: HTTPStatus, body: &str) -> Statu
|
||||
send_with(r, status, body, &[])
|
||||
}
|
||||
|
||||
/// 发送带自定义 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)])
|
||||
}
|
||||
|
||||
/// 统一成功响应:`{code:200, msg, data}`
|
||||
pub fn ok(r: *mut ngx_http_request_t, data: Value, msg: &str) -> Status {
|
||||
let body = json!({ "code": 200, "msg": msg, "data": data }).to_string();
|
||||
|
||||
@@ -46,7 +46,7 @@ pub enum Actor {
|
||||
|
||||
impl Actor {
|
||||
/// 操作者名称:审计日志用
|
||||
fn admin_name(&self) -> &str {
|
||||
pub(crate) fn admin_name(&self) -> &str {
|
||||
match self {
|
||||
Actor::Admin(u) => &u.username,
|
||||
Actor::User(u) => &u.username,
|
||||
@@ -56,13 +56,13 @@ impl Actor {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Guard {
|
||||
pub(crate) enum Guard {
|
||||
Public,
|
||||
User,
|
||||
Admin,
|
||||
}
|
||||
|
||||
type Handler = fn(*mut ngx_http_request_t, Actor) -> Status;
|
||||
pub(crate) type Handler = fn(*mut ngx_http_request_t, Actor) -> Status;
|
||||
|
||||
/// 路由表。刻意用精确匹配而非正则——接口路径是固定的,
|
||||
/// 正则只会引入「写错锚点导致前缀误匹配」的风险。
|
||||
@@ -144,7 +144,25 @@ fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> {
|
||||
("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),
|
||||
_ => return None,
|
||||
|
||||
// ---- SCIM 2.0 身份供给(路径含 {id} 变量,走前缀匹配)----------
|
||||
// ---- CAS 1.0/2.0 协议端点(精确 GET,走独立路由)----------------
|
||||
// ---- 自助密码重置(公开端点,精确 POST)------------------------
|
||||
_ => {
|
||||
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);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(entry)
|
||||
}
|
||||
@@ -323,7 +341,41 @@ fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
}
|
||||
}
|
||||
|
||||
let Some(user) = users::get(&username) else {
|
||||
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, "账号不存在");
|
||||
@@ -343,7 +395,7 @@ fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
);
|
||||
}
|
||||
|
||||
if !util::verify_password(&password, &user.salt, &user.pwd_hash) {
|
||||
if !authenticated {
|
||||
state::bump_login_fail(&ip, now);
|
||||
// 账号维度累计:达到阈值即锁定(用户必然存在,失败只可能是锁不可用)
|
||||
let mut detail = "密码错误".to_owned();
|
||||
|
||||
@@ -51,6 +51,7 @@ pub fn log(action: &str, actor: &str, target: &str, ok: bool, ip: &str, ua: &str
|
||||
"target": target,
|
||||
"ok": ok,
|
||||
"ip": ip,
|
||||
"region": crate::geo::lookup(ip),
|
||||
"ua": ua,
|
||||
"detail": detail,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! 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 同形(忽略代理链)。
|
||||
//!
|
||||
//! 鉴权全部 `Guard::Public`:login 自己读会话、validate 靠 ticket,都不依赖调用方会话。
|
||||
|
||||
use ngx::ffi::ngx_http_request_t;
|
||||
|
||||
use ipass_core::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:<ticket>`
|
||||
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-<random>`。
|
||||
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<String> {
|
||||
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 cookie = http::header(r, "cookie");
|
||||
let Some(user) = session::authenticate(cookie.as_deref()) 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");
|
||||
};
|
||||
|
||||
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<user>` / `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();
|
||||
|
||||
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();
|
||||
|
||||
match consume_ticket(&ticket, &service, now) {
|
||||
Some(user) => {
|
||||
let body = format!(
|
||||
"<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\n\
|
||||
\x20 <cas:authenticationSuccess>\n\
|
||||
\x20\x20 <cas:user>{user}</cas:user>\n\
|
||||
\x20 </cas:authenticationSuccess>\n\
|
||||
</cas:serviceResponse>\n"
|
||||
);
|
||||
http::send_ct(r, HTTPStatus::OK, &body, "application/xml; charset=utf-8")
|
||||
}
|
||||
None => {
|
||||
let body = format!(
|
||||
"<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\n\
|
||||
\x20 <cas:authenticationFailure code='INVALID_TICKET'>ticket 无效或已过期</cas:authenticationFailure>\n\
|
||||
</cas:serviceResponse>\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)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! 登录 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(""), "未知");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
//! 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::<u16>().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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
// 最小字节(补码),小正整数走一个字节
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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()
|
||||
}
|
||||
@@ -13,7 +13,13 @@ mod accounts;
|
||||
mod api;
|
||||
mod audit;
|
||||
mod captcha;
|
||||
mod cas;
|
||||
mod geo;
|
||||
mod ldap;
|
||||
mod scim;
|
||||
mod otp;
|
||||
mod reset;
|
||||
mod sync;
|
||||
pub mod oauth;
|
||||
mod oauth_clients;
|
||||
mod oauth_keys;
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
//! 自助密码重置(对齐 MaxKey 密码找回)。
|
||||
//!
|
||||
//! 两个公开端点,无需登录:
|
||||
//!
|
||||
//! * `POST /api/public/forgot-password` —— 凭账号名 / 邮箱申请重置,签发一次性
|
||||
//! token(存共享内存,不落 `users.json`,避免出现在管理台视图里),并「发信」。
|
||||
//! * `POST /api/public/reset-password` —— 凭 token + 新口令完成重置。
|
||||
//!
|
||||
//! token 用共享内存 `pwdrst:<token> → username` 存储,带 TTL,单次有效(用后即删)。
|
||||
//! 「发信」是可配置抽象:默认只写日志;设 `PASSWORD_RESET_TOKEN_SINK` 把 token
|
||||
//! 落到本地文件(本地联调 / e2e 取用);生产可接 SMTP / webhook(见 sender 分支)。
|
||||
|
||||
use ngx::ffi::ngx_http_request_t;
|
||||
|
||||
use ipass_core::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;
|
||||
|
||||
/// 重置 token 共享内存前缀:`pwdrst:<token> → 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)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// token 有效期:可由 `PASSWORD_RESET_TTL` 覆盖(秒)。
|
||||
fn reset_ttl() -> i64 {
|
||||
match std::env::var("PASSWORD_RESET_TTL") {
|
||||
Ok(v) => v.trim().parse::<i64>().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();
|
||||
let link = format!("{base}/api/public/reset-password?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),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
//! 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 ipass_core::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::<Vec<_>>(),
|
||||
"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::<Vec<_>>(),
|
||||
"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<String>,
|
||||
}
|
||||
|
||||
fn parse_user_body(body: &Value) -> Result<ScimUserInput, String> {
|
||||
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<String> = 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<Value> = 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<Value> = 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<String> = None;
|
||||
let mut email: Option<String> = None;
|
||||
let mut mobile: Option<String> = None;
|
||||
let mut add_groups: Vec<String> = Vec::new();
|
||||
let mut remove_groups: Vec<String> = Vec::new();
|
||||
let mut replace_groups: Option<Vec<String>> = 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<String> = 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<String, Vec<String>> {
|
||||
let mut map: std::collections::BTreeMap<String, Vec<String>> = 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<Value> = 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<String> = 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<String> = 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<String> = 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<String> = map.get(&id).cloned().unwrap_or_default();
|
||||
let add: Vec<String> = wanted.iter().filter(|w| !current.iter().any(|c| c == *w)).cloned().collect();
|
||||
let remove: Vec<String> = 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, "不支持的方法")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! 同步连接器(对齐 MaxKey `maxkey-synchronizer`:钉钉 / 企微 / 飞书)。
|
||||
//!
|
||||
//! **手动触发端点**:`POST /api/admin/sync/<provider>`,由外部 cron / 运维脚本调用,
|
||||
//! 不引入后台进程(与「零常驻依赖」硬约束一致)。
|
||||
//!
|
||||
//! 流程:从配置好的用户目录源拉取成员列表 → 归一化为内部账号字段 → upsert 进
|
||||
//! `users.json`。每个 provider 的拉取地址由 `SYNC_<PROVIDER>_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/<provider>`(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<String> {
|
||||
// 仅支持 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::<u16>().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::<usize>().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<String> {
|
||||
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::<Value>(&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<String> = 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<String> = 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}"),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user