- 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
273 lines
13 KiB
Rust
273 lines
13 KiB
Rust
//! 自助密码重置(对齐 MaxKey 密码找回)。
|
||
//!
|
||
//! 两个公开端点,无需登录:
|
||
//!
|
||
//! * `POST /api/public/forgot-password` —— 凭账号名 / 邮箱申请重置,签发一次性
|
||
//! token(存共享内存,不落 `users.json`,避免出现在管理台视图里),并「发信」。
|
||
//! * `POST /api/public/reset-password` —— 凭 token + 新口令完成重置。
|
||
//! * `GET /forgot` / `GET /reset?token=…` —— 上面两个 API 的**终端用户页面**
|
||
//! (没有页面时,发给用户的邮件链接会指向 POST 端点,点开必然失败)。
|
||
//!
|
||
//! token 用共享内存 `pwdrst:<token> → username` 存储,带 TTL,单次有效(用后即删)。
|
||
//! 「发信」是可配置抽象:默认只写日志;设 `PASSWORD_RESET_TOKEN_SINK` 把 token
|
||
//! 落到本地文件(本地联调 / e2e 取用);生产可接 SMTP / webhook(见 sender 分支)。
|
||
|
||
use ngx::ffi::ngx_http_request_t;
|
||
|
||
use crate::compat as http;
|
||
use ipass_core::state;
|
||
use ipass_core::users;
|
||
use ipass_core::util;
|
||
use ngx::core::Status;
|
||
use ngx::http::HTTPStatus;
|
||
|
||
use crate::accounts::{self, UserExt};
|
||
use crate::audit;
|
||
use crate::oauth;
|
||
use crate::utilx;
|
||
|
||
/// 重置 token 共享内存前缀:`pwdrst:<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)),
|
||
// 终端用户页面(GET)。放在这里而不是主路由表:同属「密码重置」这一族。
|
||
("GET", "/forgot") => Some((g, h_forgot_page)),
|
||
("GET", "/reset") => Some((g, h_reset_page)),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// token 有效期:可由 `PASSWORD_RESET_TTL` 覆盖(秒)。
|
||
fn reset_ttl() -> i64 {
|
||
match std::env::var("PASSWORD_RESET_TTL") {
|
||
Ok(v) => v.trim().parse::<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();
|
||
// 注意:必须指向 **GET 页面**,不能直接指向 POST 端点(点开会是 405/空响应)。
|
||
let link = format!("{base}/reset?token={token}");
|
||
util::log_notice(&format!("[reset] 密码重置链接 user={user} {link}"));
|
||
|
||
if let Ok(sink) = std::env::var("PASSWORD_RESET_TOKEN_SINK") {
|
||
// 本地联调 / e2e:把 token 落到文件,便于脚本取出(不含 PII,仅 token)
|
||
let _ = std::fs::write(&sink, format!("{token}\n"));
|
||
}
|
||
}
|
||
|
||
/// `POST /api/public/forgot-password`:账号名或邮箱。
|
||
///
|
||
/// 安全:无论账号是否存在都返回同样的成功文案,避免账号枚举。
|
||
fn h_forgot_password(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status {
|
||
let p = http::params(r);
|
||
let ident = p
|
||
.get("username")
|
||
.or_else(|| p.get("email"))
|
||
.map(String::as_str)
|
||
.unwrap_or("")
|
||
.to_owned();
|
||
let ip = http::remote_addr(r);
|
||
let ua = http::header(r, "user-agent").unwrap_or_default();
|
||
|
||
if ident.is_empty() {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, "请提供账号名或邮箱");
|
||
}
|
||
|
||
// 按账号名或邮箱定位用户
|
||
let found = users::get(&ident).or_else(|| {
|
||
let lower = ident.to_ascii_lowercase();
|
||
users::all().into_iter().find(|u| u.email().to_ascii_lowercase() == lower)
|
||
});
|
||
|
||
if let Some(u) = found {
|
||
let token = util::gen_key();
|
||
let exp = util::now() + reset_ttl();
|
||
state::put(KEY_PWD_RESET, token.as_bytes(), u.username.as_bytes(), exp);
|
||
send_reset(&u.username, &token);
|
||
audit::log("pwd.forgot", &u.username, &u.username, true, &ip, &ua, "");
|
||
} else {
|
||
audit::log("pwd.forgot", &ident, &ident, false, &ip, &ua, "no such account");
|
||
}
|
||
|
||
http::ok(r, serde_json::json!({}), "若账号存在,重置链接已发送")
|
||
}
|
||
|
||
/// `POST /api/public/reset-password`:token + 新口令。
|
||
fn h_reset_password(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status {
|
||
let p = http::params(r);
|
||
let token = p.get("token").map(String::as_str).unwrap_or("").to_owned();
|
||
let password = p.get("password").map(String::as_str).unwrap_or("").to_owned();
|
||
let ip = http::remote_addr(r);
|
||
let ua = http::header(r, "user-agent").unwrap_or_default();
|
||
|
||
if token.is_empty() || password.is_empty() {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, "token 与新口令均必填");
|
||
}
|
||
if let Err(e) = accounts::check_password(&password) {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, &e);
|
||
}
|
||
|
||
let Some((username, exp)) = state::get(KEY_PWD_RESET, token.as_bytes()) else {
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, "token 无效或已使用");
|
||
};
|
||
if exp > 0 && exp <= util::now() {
|
||
state::remove(KEY_PWD_RESET, token.as_bytes());
|
||
return http::fail(r, HTTPStatus::BAD_REQUEST, "token 已过期,请重新申请");
|
||
}
|
||
|
||
match users::set_password(&username, &password) {
|
||
Ok(()) => {
|
||
// 单次有效:消费即删
|
||
state::remove(KEY_PWD_RESET, token.as_bytes());
|
||
audit::log("pwd.reset", &username, &username, true, &ip, &ua, "");
|
||
http::ok(r, serde_json::json!({}), "密码已重置,请用新口令登录")
|
||
}
|
||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||
}
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 终端用户页面(自助密码重置的「另一半」)
|
||
// ===========================================================================
|
||
//
|
||
// 只有 API 没有页面时,用户拿到的邮件链接会指向一个 POST 端点——点开必然
|
||
// 405/400。所以这里补两个 GET 页面:
|
||
// GET /forgot 输入账号名/邮箱,申请重置
|
||
// GET /reset?token=… 凭一次性 token 设置新口令
|
||
// 页面用 fetch 提交,不依赖跨请求表单 POST(token 也就不会出现在地址栏历史里
|
||
// 之外的任何地方)。
|
||
|
||
/// 两个页面共用的样式:与登录页同一套配色(深蓝渐变底 + 白卡片 + 蓝色主按钮)。
|
||
const PAGE_STYLE: &str = r#"
|
||
*{box-sizing:border-box}
|
||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px;
|
||
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
|
||
background:radial-gradient(1100px 560px at 50% -12%,#1e3a8a 0%,#0f172a 58%,#0b1220 100%);color:#1f2937}
|
||
.card{width:100%;max-width:400px;background:#fff;border-radius:16px;padding:34px 30px 24px;
|
||
box-shadow:0 20px 60px rgba(2,6,23,.45)}
|
||
.brand{display:flex;align-items:center;gap:11px;margin-bottom:20px}
|
||
.mark{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,#2563eb,#38bdf8);
|
||
display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;
|
||
font-size:12px;letter-spacing:.5px;flex:0 0 auto}
|
||
h1{font-size:16px;margin:0}
|
||
.sub{color:#6b7280;font-size:12px;margin-top:2px}
|
||
label{display:block;font-size:12.5px;color:#6b7280;margin:0 0 6px}
|
||
input[type=text],input[type=password]{width:100%;padding:10px 12px;margin:0 0 14px;
|
||
border:1px solid #cbd5e1;border-radius:8px;font-size:13.5px;outline:none;
|
||
transition:border-color .15s,box-shadow .15s}
|
||
input[type=text]:focus,input[type=password]:focus{border-color:#2563eb;
|
||
box-shadow:0 0 0 3px rgba(37,99,235,.12)}
|
||
button{width:100%;padding:11px;border:0;border-radius:8px;background:#2563eb;color:#fff;
|
||
font-size:15px;font-weight:600;cursor:pointer;transition:.15s;font-family:inherit}
|
||
button:hover{background:#1d4ed8}
|
||
button:disabled{opacity:.6;cursor:not-allowed}
|
||
.msg{border-radius:8px;padding:9px 12px;font-size:12.5px;margin-bottom:16px;display:none}
|
||
.msg.ok{background:#e7f6ec;color:#15803d;border:1px solid #bfe3cb;display:block}
|
||
.msg.err{background:#fdecec;color:#b91c1c;border:1px solid #f7cfcf;display:block}
|
||
.foot{margin-top:16px;padding-top:14px;border-top:1px dashed #e3e8ef;
|
||
color:#6b7280;font-size:12px;text-align:center}
|
||
.foot a{color:#2563eb;text-decoration:none}
|
||
"#;
|
||
|
||
/// 找回密码页。用占位符替换而不是 `format!`:页面里有大量 JS 花括号,
|
||
/// 走 `format!` 得把每一个都写成 `{{`/`}}`,改起来极易出错。
|
||
const FORGOT_PAGE: &str = r#"<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>找回密码 · 统一认证</title><style>__STYLE__</style></head>
|
||
<body><div class="card">
|
||
<div class="brand"><div class="mark">SSO</div>
|
||
<div><h1>找回密码</h1><div class="sub">输入账号名或邮箱,系统会发送一次性重置链接</div></div></div>
|
||
<div class="msg" id="m"></div>
|
||
<form id="f">
|
||
<label for="u">账号名 / 邮箱</label>
|
||
<input id="u" type="text" placeholder="zhangsan 或 [email protected]" autofocus required>
|
||
<button type="submit" id="b">发送重置链接</button></form>
|
||
<div class="foot"><a href="/login">返回登录</a></div>
|
||
</div>
|
||
<script>
|
||
document.getElementById('f').addEventListener('submit',function(e){e.preventDefault();
|
||
var b=document.getElementById('b'),m=document.getElementById('m');
|
||
b.disabled=true;b.textContent='发送中…';
|
||
fetch('/api/public/forgot-password',{method:'POST',headers:{'Content-Type':'application/json'},
|
||
body:JSON.stringify({username:document.getElementById('u').value.trim()})})
|
||
.then(function(r){return r.json()}).then(function(j){
|
||
m.className='msg '+(j.code===200?'ok':'err');m.textContent=j.msg||'已提交';
|
||
if(j.code===200){document.getElementById('f').reset();}})
|
||
.catch(function(){m.className='msg err';m.textContent='网络错误,请稍后重试';})
|
||
.then(function(){b.disabled=false;b.textContent='发送重置链接';});});
|
||
</script></body></html>"#;
|
||
|
||
/// 重置口令页。`__TOKEN__` 为一次性 token(HTML 转义后填入隐藏域)。
|
||
const RESET_PAGE: &str = r#"<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>重置密码 · 统一认证</title><style>__STYLE__</style></head>
|
||
<body><div class="card">
|
||
<div class="brand"><div class="mark">SSO</div>
|
||
<div><h1>设置新密码</h1><div class="sub">凭重置链接设置新口令,该链接仅可使用一次</div></div></div>
|
||
<div class="msg __MSG_CLS__" id="m">__MSG__</div>
|
||
<form id="f" __FORM_HIDDEN__>
|
||
<label for="p1">新密码</label>
|
||
<input id="p1" type="password" placeholder="至少 8 位" autocomplete="new-password" required>
|
||
<label for="p2">确认新密码</label>
|
||
<input id="p2" type="password" placeholder="再输一次" autocomplete="new-password" required>
|
||
<input type="hidden" id="tk" value="__TOKEN__">
|
||
<button type="submit" id="b">保存新密码</button></form>
|
||
<div class="foot"><a href="/login">返回登录</a></div>
|
||
</div>
|
||
<script>
|
||
document.getElementById('f').addEventListener('submit',function(e){e.preventDefault();
|
||
var b=document.getElementById('b'),m=document.getElementById('m');
|
||
var p1=document.getElementById('p1').value,p2=document.getElementById('p2').value;
|
||
if(p1.length<8){m.className='msg err';m.textContent='新密码至少 8 位';return;}
|
||
if(p1!==p2){m.className='msg err';m.textContent='两次输入的新密码不一致';return;}
|
||
b.disabled=true;b.textContent='提交中…';
|
||
fetch('/api/public/reset-password',{method:'POST',headers:{'Content-Type':'application/json'},
|
||
body:JSON.stringify({token:document.getElementById('tk').value,password:p1})})
|
||
.then(function(r){return r.json()}).then(function(j){
|
||
m.className='msg '+(j.code===200?'ok':'err');m.textContent=j.msg||'已提交';
|
||
if(j.code===200){document.getElementById('f').style.display='none';}})
|
||
.catch(function(){m.className='msg err';m.textContent='网络错误,请稍后重试';})
|
||
.then(function(){b.disabled=false;b.textContent='保存新密码';});});
|
||
</script></body></html>"#;
|
||
|
||
fn forgot_html() -> String {
|
||
FORGOT_PAGE.replace("__STYLE__", PAGE_STYLE)
|
||
}
|
||
|
||
fn reset_html(token: &str, error: &str) -> String {
|
||
let empty = token.trim().is_empty();
|
||
let (cls, hidden) = if empty { ("err", "hidden") } else { ("", "") };
|
||
let msg = if empty { "链接不完整或已失效,请重新申请" } else { error };
|
||
RESET_PAGE
|
||
.replace("__STYLE__", PAGE_STYLE)
|
||
.replace("__TOKEN__", &utilx::html_escape(token))
|
||
.replace("__MSG_CLS__", cls)
|
||
.replace("__MSG__", &utilx::html_escape(msg))
|
||
.replace("__FORM_HIDDEN__", hidden)
|
||
}
|
||
|
||
/// `GET /forgot` —— 找回密码页(登录页有「忘记密码?」链接指过来)。
|
||
fn h_forgot_page(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status {
|
||
http::send_ct(r, HTTPStatus::OK, &forgot_html(), "text/html; charset=utf-8")
|
||
}
|
||
|
||
/// `GET /reset?token=…` —— 凭一次性 token 设置新口令页。
|
||
///
|
||
/// token 为空时直接在页面上给出提示(不发往服务端),其余情况即使 token 无效
|
||
/// 也照常渲染表单——真正的校验在 POST 时做,避免把「token 是否存在」暴露成页面差异。
|
||
fn h_reset_page(r: *mut ngx_http_request_t, _actor: crate::api::Actor) -> Status {
|
||
let p = http::params(r);
|
||
let token = p.get("token").map(String::as_str).unwrap_or("").to_owned();
|
||
http::send_ct(r, HTTPStatus::OK, &reset_html(&token, ""), "text/html; charset=utf-8")
|
||
}
|