修「去密码硬编码」那一步自己引入的三个 bug

上一版把明文密码换成随机生成时,引入了三个问题。都是我自己的补丁
造成的,而且症状都像"功能坏了",实际是环境和脚本的问题。

== bug 1:兜底替换把函数调用塞进了字符串 ==

fix_hardcoded_password.py 里有句兜底:
    text = text.replace(OLD, '_admin_password()')

而原代码是:
    {"username": "xmz7891", "password": "@<老密码>"}
                                            ^ @ 在引号**里面**

正则要求引号紧贴老密码,这里中间有个 @,所以没匹配上;
兜底替换就把老密码换成了函数调用,结果成了**字符串字面量**:

    {"username": "xmz7891", "password": "@_admin_password()"}

7 个文件被这样弄坏。它们拿这串东西当密码去登录,
当然登不上 -> 401「请先登录」-> 管理接口测试全红(12 项失败)。

教训:**批量替换里的兜底 str.replace 太危险**,它不看上下文。
替换完必须检查有没有"函数调用被引号包起来"这种形状。

== bug 2:测试和它自己起的中转对不上密码 ==

密码改成随机生成之后,测试分成两边:
  * 测试进程:_admin_password() 去环境变量/文件里找
  * 它启动的中转:找不到就随机生成一个
两边不一致 -> 登录失败。

修法:测试在**模块级**(import 时)生成一个本次运行专用的随机密码,
写进 os.environ["RELAY_ADMIN_PASSWORD"]。测试启动中转用的是
dict(os.environ),所以会自动传过去 —— 两边就是同一个密码。

用随机而不是写死:写死就又变成"密码进仓库"了,白改一场。

== bug 3:全新部署启动后没有密码文件 ==

admin_password() 原来只在有人访问登录页时才调用,于是全新部署
启动后 data/admin_password.txt 一直不存在,日志里也看不到密码,
管理员不知道该用什么登。

修法:main() 里在 admin_key() 后面补一句 admin_password(),
和钥匙一样的道理 —— 启动时生成并打印一次。

== 验证 ==

    管理页设备控制   23/23 通过
    管理页批删       24/24 通过
    管理页按钮       10/10 通过
    管理页 JS              通过
    管理页网络体检   15/15 通过
    密码随机生成     11/11 通过(含"老密码登不进去"、"两次部署密码不同")

工作区搜不到明文密码了(git 历史里还有,等用户确认后重写)。
This commit is contained in:
xmz7891
2026-10-07 20:56:53 +08:00
parent d424128483
commit 9b17129c49
12 changed files with 474 additions and 7 deletions
+140
View File
@@ -0,0 +1,140 @@
# -*- coding: utf-8 -*-
r'''修两件事:
== 1. 我自己的补丁把函数调用塞进了字符串里 ==
fix_hardcoded_password.py 里有个兜底替换:
text = text.replace(OLD, '_admin_password()')
而原代码是:
{"username": "xmz7891", "password": "@<老密码>"}
^ @ 在引号**里面**
正则 `"password"\s*:\s*"OLD"` 要求引号紧贴 OLD,这里中间有个 @,
所以没匹配上;然后兜底替换就把 OLD 换成了函数调用,
结果变成**字符串字面量**:
{"username": "xmz7891", "password": "@_admin_password()"}
7 个文件被这样弄坏。它们登录时拿这个当密码,
当然登不上 -> 401「请先登录」-> 管理接口测试全红。
教训:**做批量替换时,兜底的 `str.replace` 太危险** ——
它不管上下文。要么用带边界正则,要么替换后检查有没有
"函数调用被引号包起来" 这种形状。
== 2. relay 启动时没生成密码文件 ==
admin_password() 只在有人访问登录时才调用,所以全新部署启动后
data/admin_password.txt 一直不存在 —— 日志里也就看不到密码,
管理员不知道用什么登。
main() 里已经调了 admin_key()(同样道理),补上 admin_password()。
'''
from __future__ import annotations
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
# 被弄坏的形状:引号把函数调用包起来了
BROKEN = re.compile(r"""["']@?_admin_password\(\)["']""")
GOOD = "_admin_password()"
TARGETS = ["_tests/acceptance.py",
"_tests/test_admin_batch_delete.py",
"_tests/test_admin_button.py",
"_tests/test_admin_device_control.py",
"_tests/test_admin_js.py",
"_tests/test_admin_netcheck.py",
"_tests/test_relay_admin_login.py"]
def main() -> int:
changed = 0
failed = 0
print("── 1. 修被引号包起来的 _admin_password() ──")
for rel in TARGETS:
p = ROOT / rel
if not p.is_file():
print(" ✗ %s 不存在" % rel)
failed += 1
continue
text = p.read_text(encoding="utf-8")
if '@_admin_password()' not in text and '"_admin_password()"' not in text:
print(" • %s 本来就正常" % rel)
continue
before = text
# 只处理「引号里整个就是一个函数调用」这种
text = re.sub(r'"@_admin_password\(\)"', GOOD, text)
text = re.sub(r"'@_admin_password\(\)'", GOOD, text)
text = re.sub(r'"_admin_password\(\)"', GOOD, text)
text = re.sub(r"'_admin_password\(\)'", GOOD, text)
if text == before:
print(" ✗ %s 替换没生效" % rel)
failed += 1
continue
# 再确认没有残留
if '@_admin_password()' in text:
print(" ✗ %s 还有残留" % rel)
failed += 1
continue
p.write_text(text, encoding="utf-8", newline="\n")
print(" ✓ %s" % rel)
changed += 1
print()
print("── 2. relay.py 启动时生成密码文件 ──")
rp = ROOT / "relay" / "relay.py"
text = rp.read_text(encoding="utf-8")
if "admin_password() # 确保" in text or "pw = admin_password()" in text:
print(" • 已经调过了")
else:
# 在 main() 里 admin_key() 那行后面补一句
old = " key = admin_key()"
if old not in text:
print(" ✗ 找不到 main() 里 admin_key() 那行")
failed += 1
else:
new = (
" key = admin_key()\n"
" # 同样要**在这里**把密码也生成出来:\n"
" # admin_password() 原来只在有人访问登录页时才调用,\n"
" # 于是全新部署启动后 data/admin_password.txt 一直不存在,\n"
" # 日志里也看不到密码 —— 管理员不知道该用什么登录。\n"
" # 启动时就调一次,密码会随启动日志打印出来。\n"
" admin_password()"
)
text = text.replace(old, new, 1)
rp.write_text(text, encoding="utf-8", newline="\n")
print(" ✓ 已在 main() 里调用 admin_password()")
changed += 1
print()
print(" 改了 %d 处,失败 %d 处" % (changed, failed))
# 全局再扫一遍有没有「函数调用被引号包起来」的
print()
print("── 3. 全仓复查 ──")
bad = []
for pat in ("_tests/*.py", "_build/*.py", "relay/*.py"):
for f in ROOT.glob(pat):
try:
t = f.read_text(encoding="utf-8", errors="replace")
except Exception: # noqa: BLE001
continue
for m in BROKEN.finditer(t):
bad.append("%s" % f.relative_to(ROOT))
break
if bad:
print(" ⚠ 还有:%s" % bad)
return 1
print(" ✓ 没有了")
return 0 if failed == 0 else 1
if __name__ == "__main__":
sys.exit(main())