unis-oa/backend/scripts/check_hub_password_change.py

450 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""守「统一身份要求先改密码」这一整条链路(对接指南 2.3.1 / 2.4 / 2.7)。
背景:Hub 的口令安全策略判定这个账号要先改密码时,登录**照样回 200 和一对令牌**,
但那把令牌是 ``scope=password_change`` 的受限会话——拿它认人、建号、复核 token 一律
撞 ``403``。文档给下游的做法是 302 去 Hub 的改密页(2.3.2),本系统改成在登录页自己
弹框(``app/service/hub_password.py``)。这条链路上有六处"只错过一次才会被发现"的坑,
这里用一台**进程内假 Hub** 逐条钉住::
cd backend && PYTHONPATH=. python3 scripts/check_hub_password_change.py
1. 受限会话**不建本地会话**:``POST /auth/login`` 回 401 + ``PASSWORD_CHANGE_REQUIRED``
加一枚一次性 handle,且不去调令牌复核(那把令牌调什么都 403)、不写登录日志;
2. 改密表单的规则从 ``GET /auth/security-policy`` 现取,**不写死 6..20**:Hub 把下限
收到 10 位,提示就跟着变;Hub 读不到规则时如实标 ``source=default``;
3. 提交改密打的是 ``POST /auth/me/password``,带的是**这次登录那把受限令牌**;
4. handle 用一次即废:同一个 handle 提交第二次必失败;
5. 提交前本地只自查长度,**内容**判定交给 Hub:``password_unchanged`` 要按机器码回
"新密码和现在用的是同一个",不能被翻成"长度不对";
6. 没被要求改密的正常登录一字不变:照旧复核 token、照旧换发本地会话。
连开发库(只建一个带时间戳的临时账号,跑完删干净),Hub 那侧全走假 Hub。
"""
from __future__ import annotations
import dataclasses
import json
import os
import pathlib
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any
HERE = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
FAILS: list[str] = []
PASSED = 0
def check(label: str, passed: bool, detail: object = "") -> None:
global PASSED
if passed:
PASSED += 1
print(f"[通过] {label}")
else:
FAILS.append(label)
print(f"[FAIL] {label}{f' -> {detail}' if detail else ''}")
class FakeHub:
"""按脚本回包的假 Hub。``script(path, ...)`` 给某个路径排一串响应,取完用最后一条。
每个请求都记下来(方法、路径、Authorization 头、报文),"这一步到底有没有真去打
Hub、带的是哪把令牌"就靠这份流水断言。
"""
def __init__(self) -> None:
self.requests: list[dict[str, Any]] = []
self.scripts: dict[str, list[tuple[int, dict[str, Any]]]] = {}
hub = self
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_POST(self): # noqa: N802
self._handle("POST")
def do_GET(self): # noqa: N802
self._handle("GET")
def _handle(self, method: str) -> None:
length = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(length) if length else b""
try:
body = json.loads(raw.decode("utf-8")) if raw else None
except ValueError:
body = raw.decode("utf-8", "replace")
hub.requests.append({
"method": method,
"path": self.path,
"token": self.headers.get("Authorization") or "",
"body": body,
})
queue = hub.scripts.get(self.path) or []
status, payload = queue.pop(0) if len(queue) > 1 else (
queue[0] if queue else (200, {}))
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args): # 别往 stdout 上刷屏
return
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.server.daemon_threads = True
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
def script(self, path: str, *items: tuple[int, dict[str, Any]]) -> None:
self.scripts[path] = list(items)
def hits(self, path: str) -> list[dict[str, Any]]:
return [row for row in self.requests if row["path"] == path]
def clear(self) -> None:
self.requests.clear()
@property
def base_url(self) -> str:
host, port = self.server.server_address[:2]
return f"http://{host}:{port}"
def close(self) -> None:
self.server.shutdown()
self.server.server_close()
# ------------------------------------------------------------------ 假 Hub 的几种回包
LIMITED = {
"password_change_required": True,
"password_change_reason": "first_login",
"password_change_url": "/auth/password-change/one-time-code",
"password_change_expires_at": "2026-11-18T10:17:43Z",
"password": {"password_change_required": True, "password_change_reason": "first_login",
"password_days_left": 90, "password_max_age_days": 90},
}
POLICY = {"requirements": {"min_length": 10, "max_length": 24, "strength_enabled": True,
"required_classes": 2, "reject_common_password": True,
"password_force_first_login": True, "password_max_age_days": 90}}
def login_ok(hub_user_id: int, account: str, **extra) -> tuple[int, dict[str, Any]]:
"""一次成功的 Hub 登录(裸 JSON,不套信封——对接指南 1.5)。"""
body: dict[str, Any] = {
"user": {"id": hub_user_id, "account": account, "display_name": "检查人员", "status": 1},
"tokens": {"access_token": "hub-limited-token", "refresh_token": "hub-refresh",
"expires_in": 900, "token_type": "Bearer"},
}
body.update(extra)
return 200, body
def main() -> int:
hub = FakeHub()
os.environ["OA_HUB_BASE_URL"] = hub.base_url
from app import hubconfig, models
from app.db import SessionLocal
from app.security import create_access_token, hash_password
from app.service import hub as hub_api
from app.service import hub_password
real_get = hubconfig.get
def use(**patch: object):
"""把生效配置换成改过几项的一份(其余照原样带着),跑完还原。"""
base = real_get()
hubconfig.get = lambda db=None, _p=patch: dataclasses.replace(base, **_p) # type: ignore[assignment]
use(hub_enabled=True, hub_login_mode="hub", hub_verify_token=True,
hub_sso_enabled=False, hub_base_url=hub.base_url,
hub_service_token="", hub_directory_key="", hub_password_managed_by_hub=True)
hub_api.reset_client()
hub_password.reset()
stamp = str(int(time_now()))
account = f"zzpwd{stamp}"
hub_user_id = 970000 + int(stamp[-5:])
created: list[int] = []
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app) # 不进 with:不跑 startup,本进程不起调度线程
def api(method: str, path: str, body: dict | None = None, token: str = ""):
headers = {"Authorization": f"Bearer {token}"} if token else {}
response = client.request(method, f"/api/v1{path}", json=body or {}, headers=headers)
try:
payload = response.json()
except ValueError:
payload = {}
return response.status_code, payload
db = SessionLocal()
try:
person = models.User(
account=account, display_name="检查人员", email="", mobile="",
password_hash=hash_password("zz-local-only"), role=models.ROLE_MEMBER,
status=models.UserStatus.ACTIVE, source=models.AccountSource.HUB,
hub_user_id=hub_user_id,
)
db.add(person)
db.commit()
db.refresh(person)
created.append(person.id)
local_token, _ = create_access_token(str(person.id))
# 假 Hub 先按"正常剧本"排好:一次被拦下的登录 + 一份 10 位起底的口令规则
hub.script("/auth/login", login_ok(hub_user_id, account, **LIMITED))
hub.script("/auth/security-policy", (200, POLICY))
hub.script("/api/v1/auth/token/verify", (200, {"code": "200", "data": {"active": True}}))
# --- 1) 被要求改密的登录:401 + handle,且不去复核 token、不建会话
hub.clear()
status, body = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
data = body.get("data") or {}
check("被要求改密时登录不放行(401)", status == 401, status)
check("给出稳定的 reason 供前端弹框",
body.get("reason") == hub_password.REASON_REQUIRED, body.get("reason"))
check("回一句为什么被拦下", bool(data.get("hint")) and "密码" in str(data.get("hint")), data)
check("回一枚一次性 handle", bool(data.get("handle")), data)
check("回显 Hub 的改密原因码", data.get("password_change_reason") == "first_login", data)
check("不给本地令牌(这一趟没建会话)", not body.get("access_token")
and "access_token" not in data, body)
check("受限会话不去调令牌复核(那把令牌调什么都 403)",
not hub.hits("/api/v1/auth/token/verify"), hub.requests)
# --- 2) 规则从 Hub 现取,不写死 6..20
rules = hub_password.password_rules()
check("改密表单的长度下限跟着 Hub 走", rules.get("min_length") == 10, rules)
check("规则来源标成 hub", rules.get("source") == "hub", rules)
check("有效期天数一并带回", rules.get("password_max_age_days") == 90, rules)
# 老版本 Hub 没这个接口(404):如实标 default,并且**不许把 Hub 判死**——
# 这一步最容易演变成"刚登录成功,接下来五秒全说服务没响应"(熔断误伤)。
hub.script("/auth/security-policy", (404, {"error": "not_found"}))
fallback = hub_password.password_rules()
check("Hub 没有这个接口时如实标 default", fallback.get("source") == "default", fallback)
check("读不到规则不抛错,回一份能画表单的底线",
bool(fallback.get("max_length")), fallback)
hub.script("/auth/login", login_ok(hub_user_id, account, **LIMITED))
status, body = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
check("读不到策略不该触发熔断:登录照旧打到 Hub",
status == 401 and body.get("reason") == hub_password.REASON_REQUIRED,
body)
# 规则恢复成 Hub 那一份,后面的步骤按 10 位起底判
hub.script("/auth/security-policy", (200, POLICY))
data = body.get("data") or {}
# --- 3) 太短:提交前就挡下,且不带 handle 去撞 Hub
status, body = api("POST", "/auth/password/hub",
{"handle": data["handle"], "new_password": "abc123",
"confirm_password": "abc123"})
check("长度不够当场挡下", status == 400, status)
check("挡下的话报的是长度问题", "至少 10 位" in str(body.get("message")), body)
check("长度不合格时不去打扰 Hub",
not hub.hits("/auth/me/password"), hub.requests)
check("挡下时把当前规则一并回给界面",
((body.get("data") or {}).get("rules") or {}).get("min_length") == 10, body)
# --- 4) 两次不一致
status, body = api("POST", "/auth/password/hub",
{"handle": data["handle"], "new_password": "New-Pass-Word-9",
"confirm_password": "New-Pass-Word-8"})
check("两次不一致挡在提交之前", status == 400 and body.get("reason") == "PASSWORD_MISMATCH",
body)
# --- 5) 正常提交:打的是 /auth/me/password,带的是这次登录那把受限令牌
hub.clear()
hub.script("/auth/me/password", (200, {"status": "ok"}))
status, body = api("POST", "/auth/password/hub",
{"handle": data["handle"], "new_password": "New-Pass-Word-9",
"confirm_password": "New-Pass-Word-9"})
sent = hub.hits("/auth/me/password")
check("改密成功", status == 200 and (body.get("data") or {}).get("changed") is True, body)
check("改完之后要人重新登录", "重新登录" in str((body.get("data") or {}).get("message")), body)
check("打的是 Hub 的自助改密接口", len(sent) == 1, hub.requests)
check("用的是这次登录那把受限令牌",
bool(sent) and sent[0]["token"] == "Bearer hub-limited-token",
sent and sent[0]["token"])
check("报文里只交新密码(被强制改密不问原密码)",
bool(sent) and sent[0]["body"] == {"new_password": "New-Pass-Word-9"},
sent and sent[0]["body"])
# --- 6) 改成之后引用作废;失败的那几次不作废(文档 2.3.2:只有校验通过的
# 提交才消费凭据,"两次输入不一致、密码太弱"都该原地重试,不必回登录页)
status, body = api("POST", "/auth/password/hub",
{"handle": data["handle"], "new_password": "Another-Pass-99",
"confirm_password": "Another-Pass-99"})
check("改成的那一次之后同一个 handle 作废",
status == 400 and body.get("reason") == hub_password.REASON_HANDLE_INVALID, body)
_, retry = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
handle_retry = (retry.get("data") or {}).get("handle") or ""
hub.script("/auth/me/password",
(400, {"error": "weak_password", "password_code": "password_classes",
"message": "密码至少要包含两类字符",
"password_requirements": {"min_length": 10, "max_length": 24,
"strength_enabled": True,
"required_classes": 2}}))
status, body = api("POST", "/auth/password/hub",
{"handle": handle_retry, "new_password": "lowercaselonger",
"confirm_password": "lowercaselonger"})
check("Hub 拒了这一次提交",
status == 400
and (body.get("data") or {}).get("password_code") == "password_classes", body)
hub.script("/auth/me/password", (200, {"status": "ok"}))
status, body = api("POST", "/auth/password/hub",
{"handle": handle_retry, "new_password": "New-Pass-Word-9",
"confirm_password": "New-Pass-Word-9"})
check("上一次失败没烧掉引用:人还在框里就能改对",
status == 200 and (body.get("data") or {}).get("changed") is True, body)
status, body = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
handle_live = (body.get("data") or {}).get("handle") or ""
hub.script("/auth/me/password",
(400, {"error": "weak_password", "password_code": "password_classes",
"message": "密码至少要包含两类字符",
"password_requirements": {"min_length": 10, "max_length": 24,
"strength_enabled": True,
"required_classes": 3}}))
api("POST", "/auth/password/hub", {"handle": handle_live, "new_password": "aaaaaaaaaa",
"confirm_password": "aaaaaaaaaa"})
status, body = api("POST", "/auth/password/hub",
{"handle": handle_live, "new_password": "bbbbbbbbbb",
"confirm_password": "bbbbbbbbbb"})
check("每一次失败都带上 Hub 当场生效的规则(界面照着重画提示)",
((body.get("data") or {}).get("rules") or {}).get("required_classes") == 3, body)
# --- 7) Hub 按机器码拒:password_unchanged 不能被说成长度问题
hub.script("/auth/login", login_ok(hub_user_id, account, **LIMITED))
_, again = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
handle2 = (again.get("data") or {}).get("handle") or ""
hub.script("/auth/me/password",
(400, {"error": "weak_password", "password_code": "password_unchanged",
"message": "新密码不能与当前密码相同,请换一个"}))
status, body = api("POST", "/auth/password/hub",
{"handle": handle2, "new_password": "Same-As-Current-1",
"confirm_password": "Same-As-Current-1"})
check("新密码就是当前密码时按机器码分支",
status == 400
and (body.get("data") or {}).get("password_code") == "password_unchanged", body)
check("这句话说的是「新密码和现在用的是同一个」",
"同一个" in str(body.get("message")), body.get("message"))
check("不把 password_unchanged 说成长度问题",
"长度" not in str(body.get("message")), body.get("message"))
# --- 8) 长度越界:把 Hub 的中文文案原样端上来,并回一份当时生效的规则
hub.script("/auth/login", login_ok(hub_user_id, account, **LIMITED))
_, again = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
handle3 = (again.get("data") or {}).get("handle") or ""
# 管理员把下限收到 12,而手上这份规则还是登录那一刻取的 10 位起:本地先放行、
# Hub 再拒——正是"不要在下游复刻一套校验"的那一处,最终按 Hub 的话回。
hub.script("/auth/me/password",
(400, {"error": "weak_password", "password_code": "password_length",
"message": "密码长度需在 12 到 24 位之间",
"password_requirements": {"min_length": 12, "max_length": 24,
"strength_enabled": True}}))
status, body = api("POST", "/auth/password/hub",
{"handle": handle3, "new_password": "Abcdefghij1",
"confirm_password": "Abcdefghij1"})
check("Hub 的长度拒绝原样带回",
status == 400 and (body.get("data") or {}).get("password_code") == "password_length",
body)
check("带回的是 Hub 那句长度提示", "12 到 24" in str(body.get("message")), body)
check("并把规则一并回给界面重画表单",
"rules" in (body.get("data") or {}), body)
# --- 8b) 重试次数有上限:引用落到旁人手里也不能无限次去试 Hub
hub.script("/auth/login", login_ok(hub_user_id, account, **LIMITED))
_, again = api("POST", "/auth/login", {"account": account, "password": "Old-Pass-1"})
handle_burn = (again.get("data") or {}).get("handle") or ""
hub.script("/auth/me/password",
(400, {"error": "weak_password", "password_code": "password_common",
"message": "这个密码太常见,换一个"}))
hub.clear()
voided = False
for _ in range(hub_password.MAX_ATTEMPTS + 3):
if voided:
break
status, last = api("POST", "/auth/password/hub",
{"handle": handle_burn, "new_password": "password123456",
"confirm_password": "password123456"})
voided = status == 400 and last.get("reason") == hub_password.REASON_HANDLE_INVALID
calls = len(hub.hits("/auth/me/password"))
check("重试次数用完之后引用作废", voided, "提交这么多次都还没作废")
check(f"打给 Hub 的次数被上限框住({calls} 次,上限 {hub_password.MAX_ATTEMPTS})",
0 < calls <= hub_password.MAX_ATTEMPTS, calls)
# --- 9) 没被要求改密的正常登录:行为一字不变
hub.clear()
hub.script("/auth/login", login_ok(hub_user_id, account))
hub.script("/api/v1/auth/token/verify",
(200, {"code": "200", "data": {"active": True, "user_id": hub_user_id}}))
status, body = api("POST", "/auth/login", {"account": account, "password": "Good-Pass-9"})
payload = body.get("data") or {}
check("不需要改密时照旧登录成功", status == 200 and bool(payload.get("access_token")), body)
check("照旧复核一次 token", len(hub.hits("/api/v1/auth/token/verify")) == 1, hub.requests)
check("换发的是本系统的会话", payload.get("via") == "hub", payload.get("via"))
# --- 10) 暂存不泄漏:被拦下的那些 handle 用不掉时也只是内存/缓存里过期的条目
pending = hub_password.stash(hub_api.password_state_of(dict(LIMITED)),
hub_api.HubPrincipal(access_token="t", account=account))
check("handle 是随机串,不含令牌原文", "t" != pending.handle and len(pending.handle) > 20,
pending.handle)
check("peek 不作废:连着两次读到的是同一把令牌",
hub_password.peek(pending.handle) is not None
and (hub_password.peek(pending.handle).access_token or "") == "t",
"第二次读不到或读串了")
hub_password.consume(pending.handle)
check("consume 之后读不到", hub_password.peek(pending.handle) is None, "作废了还读得到")
check("空 handle 认不出来", hub_password.peek("") is None, "空串居然取到了东西")
# 换 Hub 站点时那把暂存的令牌必须两份都清干净(进程内 + Redis 共享缓存):
# 只清一份的话,人换个副本点一下,上一个站点那把受限令牌又冒出来,被拿去改新站点的密码。
stale = hub_password.stash(
hub_api.password_state_of(dict(LIMITED)),
hub_api.HubPrincipal(access_token="old-site-token", account=account))
check("暂存那条先要读得到", hub_password.peek(stale.handle) is not None, "刚存的就读不到")
hub_api.reset_client()
check("换 Hub 配置之后暂存的令牌一起作废", hub_password.peek(stale.handle) is None,
"换站点之后旧令牌还读得到")
finally:
db.rollback()
for person_id in created:
row = db.get(models.User, person_id)
if row is not None:
db.delete(row)
db.commit()
from sqlalchemy import delete as sa_delete
db.execute(sa_delete(models.OperationLog).where(models.OperationLog.target == account))
db.commit()
db.close()
hubconfig.get = real_get # type: ignore[assignment]
hub_api.reset_client()
hub_password.reset()
hub.close()
print(f"\n通过 {PASSED} 项,失败 {len(FAILS)} 项")
if FAILS:
for label in FAILS:
print(f" - {label}")
return 1 if FAILS else 0
def time_now() -> float:
import time
return time.time()
if __name__ == "__main__":
raise SystemExit(main())