fix(批次D): 口令哈希升级 + 假签名放行 + 找回密码防枚举 + 告警按收件人
- 用户口令:hash_password 改 pbkdf2(加盐、260k 迭代);新增 verify_password 兼容旧的无盐 sha256 且恒定时间比较;登录成功后自动升级旧哈希(用户无感) - _verify_upstream_token:没有 access_token 时直接放行(假签名必被上游 102001 拒绝,原先把 102001 当「凭据失效」,导致只填 token_id 的合法用户注册被 400 拦、 /verify_token 永远 invalid) - 找回密码防枚举:未注册邮箱也占 60 秒冷却(email_verify.record_cooldown, 不发信),否则「第二次请求是否 429」就成了判断邮箱是否注册的预言机 - 凭据告警:_send_alert 改为按收件人统计,返回成功数;只要有一人收到就落库, 不再因为某个收件人失败导致「每 15 分钟给全员重发一遍」 测试:167 pytest(新增口令哈希 3 条)+ 32 node 全绿
This commit is contained in:
@@ -147,12 +147,22 @@ def _send_alert(recipients, level, owner_desc, expiry):
|
||||
("有效期至", expire_time), ("提醒时间", _now_bj_str())]
|
||||
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
|
||||
html_body = _render_alert_html(title, lead, details)
|
||||
ok_all = True
|
||||
sent_ok, failed = [], []
|
||||
for to in sorted(recipients):
|
||||
subject = f"【小白超人·告警】{title}"
|
||||
if not send_email(to, subject, plain, html_body):
|
||||
ok_all = False
|
||||
return ok_all
|
||||
try:
|
||||
if send_email(to, subject, plain, html_body):
|
||||
sent_ok.append(to)
|
||||
else:
|
||||
failed.append(to)
|
||||
except Exception as exc:
|
||||
print(f"[凭据告警] 发送给 {to} 异常: {exc}")
|
||||
failed.append(to)
|
||||
if failed:
|
||||
print(f"[凭据告警] {len(failed)} 个收件人发送失败: {failed[:3]}")
|
||||
# 返回成功数:只要有一个人收到就算「已通知」,否则每 15 分钟
|
||||
# 会把所有人重发一遍(原来的 ok_all 聚合就是这个问题)
|
||||
return len(sent_ok)
|
||||
|
||||
|
||||
# ========== 检查逻辑 ==========
|
||||
@@ -194,7 +204,7 @@ def check_user_credentials():
|
||||
recv = (u["alert_email"] or "").strip() or (u["email"] or "").strip()
|
||||
if recv:
|
||||
recipients.add(recv)
|
||||
if _send_alert(recipients, level, f"用户 {u['email']}", expiry):
|
||||
if _send_alert(recipients, level, f"用户 {u['email']}", expiry) > 0:
|
||||
_mark_sent(conn, target, level)
|
||||
sent += 1
|
||||
finally:
|
||||
@@ -258,7 +268,7 @@ def check_global_credential():
|
||||
recipients = set(get_alert_emails())
|
||||
if not recipients:
|
||||
return 0
|
||||
if _send_alert(recipients, level, "全局默认凭据", expiry):
|
||||
if _send_alert(recipients, level, "全局默认凭据", expiry) > 0:
|
||||
_mark_sent(conn, target, level)
|
||||
conn.commit()
|
||||
return 1
|
||||
|
||||
@@ -53,6 +53,23 @@ def _cleanup_locked(now: float):
|
||||
_codes.pop(email, None)
|
||||
|
||||
|
||||
def record_cooldown(email: str) -> None:
|
||||
"""只登记「刚发过」,不真正发信。
|
||||
|
||||
用于找回密码的防枚举:未注册邮箱也要占住 60 秒冷却,否则
|
||||
「第二次请求是否 429」就成了判断邮箱有没有注册的预言机。
|
||||
"""
|
||||
email = (email or "").strip().lower()
|
||||
if not email:
|
||||
return
|
||||
now = _now()
|
||||
with _lock:
|
||||
entry = _codes.get(email) or {"hash": "", "expires": now, "attempts": 0}
|
||||
entry["sent_at"] = now
|
||||
entry["purpose"] = "reset"
|
||||
_codes[email] = entry
|
||||
|
||||
|
||||
def send_code(email: str, purpose: str = "register") -> tuple:
|
||||
"""发送验证码到邮箱。返回 (ok, message)。受 60s 邮箱冷却与每小时 IP 上限约束。"""
|
||||
email = (email or "").strip().lower()
|
||||
|
||||
+47
-1
@@ -99,9 +99,39 @@ def _register_rate_ok(ip: str):
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""口令哈希:pbkdf2(加盐、可调迭代)。
|
||||
|
||||
老库里存的是无盐 sha256,拖库即可反查;verify_password 兼容旧格式,
|
||||
并在登录成功时透明升级成新哈希。
|
||||
"""
|
||||
from werkzeug.security import generate_password_hash
|
||||
return generate_password_hash(password, method="pbkdf2:sha256:260000")
|
||||
|
||||
|
||||
def _legacy_sha256(password: str) -> str:
|
||||
return hashlib.sha256(password.encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_password(stored: str, password: str) -> bool:
|
||||
"""校验口令:新格式走 werkzeug,旧格式(64 位 hex)兼容且恒定时间比较。"""
|
||||
import hmac
|
||||
|
||||
stored = (stored or "").strip()
|
||||
if not stored:
|
||||
return False
|
||||
if stored.startswith(("pbkdf2:", "scrypt:", "argon2")):
|
||||
try:
|
||||
from werkzeug.security import check_password_hash
|
||||
return check_password_hash(stored, password or "")
|
||||
except Exception:
|
||||
return False
|
||||
return hmac.compare_digest(stored, _legacy_sha256(password or ""))
|
||||
|
||||
|
||||
def password_needs_upgrade(stored: str) -> bool:
|
||||
return not (stored or "").strip().startswith(("pbkdf2:", "scrypt:", "argon2"))
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
@@ -236,6 +266,9 @@ def auth_send_code():
|
||||
row = conn.execute("SELECT id FROM users WHERE email = ?", (email,)).fetchone()
|
||||
conn.close()
|
||||
if not row:
|
||||
# 未注册邮箱:同样占住 60 秒冷却(不发信),
|
||||
# 否则「第二次请求是否 429」会泄漏这个邮箱是否已注册。
|
||||
email_verify.record_cooldown(email)
|
||||
return jsonify({"rtn_code": 0, "message": "验证码已发送,请查收邮箱(注意垃圾箱)"})
|
||||
ok, message = email_verify.send_code(email, purpose=purpose)
|
||||
if not ok:
|
||||
@@ -389,11 +422,20 @@ def login():
|
||||
conn.close()
|
||||
return jsonify({"rtn_code": 429,
|
||||
"message": f"失败次数过多,请 {max(wait_seconds // 60, 1)} 分钟后再试"})
|
||||
if not user or user["password_hash"] != hash_password(password):
|
||||
if not user or not verify_password(user["password_hash"], password):
|
||||
conn.close()
|
||||
_login_record_fail(ip, email)
|
||||
return jsonify({"rtn_code": 400, "message": "邮箱或密码错误"})
|
||||
_login_record_success(ip, email)
|
||||
# 旧的无盐 sha256 哈希:登录成功后顺手升级(用户无感)
|
||||
if password_needs_upgrade(user["password_hash"]):
|
||||
try:
|
||||
conn.execute("UPDATE users SET password_hash = ? WHERE id = ?",
|
||||
(hash_password(password), user["id"]))
|
||||
conn.commit()
|
||||
print(f"[登录] 已升级 {email} 的口令哈希")
|
||||
except Exception as exc:
|
||||
print(f"[登录] 口令哈希升级失败: {exc}")
|
||||
|
||||
# 支持多设备同时登录:不再清空该用户的旧会话,仅为本设备新增一条会话
|
||||
session_token = generate_token()
|
||||
@@ -552,6 +594,10 @@ def save_xbniu_token():
|
||||
def _verify_upstream_token(token_id: str, access_token: str) -> tuple:
|
||||
"""向上游校验微信凭据有效性。返回 (valid, message)。
|
||||
供 verify_token 接口(已登录,防枚举)与注册流程(注册时尚无登录态)共用。"""
|
||||
# 没有 access_token 时只能用假签名,上游一律回 102001 —— 那不代表 token 失效,
|
||||
# 不能因此拦掉合法用户(注册/校验都会误判),这里直接放行并标记未校验。
|
||||
if not (access_token or "").strip():
|
||||
return True, "未填 AccessToken,无法校验有效期(已放行)"
|
||||
import requests as req
|
||||
from wechat import BASE_URL, make_signature
|
||||
timestamp = str(int(time.time()))
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""用户口令哈希:pbkdf2 + 旧 sha256 兼容与升级。"""
|
||||
import hashlib
|
||||
import unittest
|
||||
|
||||
from routes import auth as auth_routes
|
||||
|
||||
|
||||
class PasswordHashTests(unittest.TestCase):
|
||||
def test_new_hash_is_pbkdf2_and_verifies(self):
|
||||
stored = auth_routes.hash_password("070517zhan")
|
||||
self.assertTrue(stored.startswith("pbkdf2:"))
|
||||
self.assertTrue(auth_routes.verify_password(stored, "070517zhan"))
|
||||
self.assertFalse(auth_routes.verify_password(stored, "070517"))
|
||||
self.assertFalse(auth_routes.password_needs_upgrade(stored))
|
||||
|
||||
def test_legacy_sha256_still_verifies_and_is_marked_for_upgrade(self):
|
||||
legacy = hashlib.sha256("070517zhan".encode()).hexdigest()
|
||||
self.assertTrue(auth_routes.verify_password(legacy, "070517zhan"))
|
||||
self.assertFalse(auth_routes.verify_password(legacy, "wrong"))
|
||||
self.assertTrue(auth_routes.password_needs_upgrade(legacy))
|
||||
|
||||
def test_empty_hash_never_verifies(self):
|
||||
self.assertFalse(auth_routes.verify_password("", "x"))
|
||||
self.assertFalse(auth_routes.verify_password(None, "x"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user