mirror of
https://gitee.com/xmz7891/ykxmz.git
synced 2026-10-18 14:50:45 +00:00
上一版把明文密码换成随机生成时,引入了三个问题。都是我自己的补丁
造成的,而且症状都像"功能坏了",实际是环境和脚本的问题。
== 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 历史里还有,等用户确认后重写)。
248 lines
9.4 KiB
Python
248 lines
9.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""模拟浏览器:管理页的"删除"按钮为什么没反应。
|
|
|
|
用户反馈:"中转站那边输入密码以后,这个删除键没反应,是个幽灵按键"
|
|
|
|
浏览器实际做的是:
|
|
1. POST /admin/login 拿 lr_admin Cookie
|
|
2. GET / 看管理页
|
|
3. 点删除 -> fetch('/v1/admin/delete', {method POST, body {deviceId}})
|
|
浏览器会自动带上 Cookie
|
|
|
|
所以这个测试完全照这个路径走一遍,看断在哪。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import http.cookiejar
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
_UA = {"User-Agent": "LanRemote/1.4.0"}
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
PORT = 8097
|
|
BASE = f"http://127.0.0.1:{PORT}"
|
|
|
|
passed = 0
|
|
failed = 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 管理页密码**不再硬编码**。
|
|
#
|
|
# 以前这里写着明文密码,而 relay.py 里也把它当默认密码 ——
|
|
# 仓库要推到公开的 Gitee/EzHub,等于把管理台钥匙挂门上,
|
|
# 而且 git 历史删不掉。
|
|
#
|
|
# 现在按优先级取:
|
|
# 1. 环境变量 RELAY_ADMIN_PASSWORD
|
|
# 2. _build/relay_info.json 里的 adminPassword(本地测试用)
|
|
# 3. 本机 8080 中转实际用的 data/admin_password.txt
|
|
# 拿不到就跳过需要登录的用例,而不是编一个假密码硬试。
|
|
# ---------------------------------------------------------------------------
|
|
# ---- 测试专用管理密码 ----------------------------------------------------
|
|
# 测试要登录它自己启动的中转,但密码是那边随机的 —— 两边对不上就会
|
|
# 全部 401(表现成"功能坏了",实际是环境没打通)。
|
|
#
|
|
# 这里生成一个**本次运行专用**的随机密码,写进环境变量;
|
|
# 测试启动中转用的是 dict(os.environ),所以会自动传给中转。
|
|
#
|
|
# 为什么不用写死的:写死就又变成"密码进仓库"了,白改一场。
|
|
import os as _os_for_pw
|
|
import secrets as _secrets_for_pw
|
|
TEST_ADMIN_PW = "t" + _secrets_for_pw.token_hex(12)
|
|
_os_for_pw.environ["RELAY_ADMIN_PASSWORD"] = TEST_ADMIN_PW
|
|
_os_for_pw.environ.setdefault("RELAY_ADMIN_USER", "xmz7891")
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _admin_password() -> str:
|
|
import json as _json
|
|
import os as _os
|
|
from pathlib import Path as _Path
|
|
|
|
pw = (_os.environ.get("RELAY_ADMIN_PASSWORD") or "").strip()
|
|
if pw:
|
|
return pw
|
|
root = _Path(__file__).resolve().parent.parent
|
|
info = root / "_build" / "relay_info.json"
|
|
try:
|
|
data = _json.loads(info.read_text(encoding="utf-8"))
|
|
pw = str(data.get("adminPassword") or "").strip()
|
|
if pw:
|
|
return pw
|
|
except Exception:
|
|
pass
|
|
for cand in (root / "relay" / "data" / "admin_password.txt",
|
|
_Path("/root/lanremote-relay/data/admin_password.txt")):
|
|
try:
|
|
if cand.is_file():
|
|
return cand.read_text(encoding="utf-8").strip()
|
|
except Exception:
|
|
continue
|
|
return ""
|
|
|
|
|
|
|
|
def check(name, ok, detail=""):
|
|
global passed, failed
|
|
if ok:
|
|
passed += 1
|
|
print(" [PASS] " + name)
|
|
else:
|
|
failed += 1
|
|
print(" [FAIL] " + name + " " + str(detail))
|
|
|
|
|
|
def main() -> int:
|
|
work = Path(tempfile.mkdtemp(prefix="admin_button_"))
|
|
relay = None
|
|
try:
|
|
data = work / "data"
|
|
data.mkdir(parents=True, exist_ok=True)
|
|
env = dict(os.environ)
|
|
env.update({
|
|
"RELAY_PORT": str(PORT), "RELAY_BIND": "127.0.0.1",
|
|
"RELAY_DATA": str(data), "RELAY_POLL": "6",
|
|
"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1",
|
|
})
|
|
relay = subprocess.Popen(
|
|
[sys.executable, "-u", str(ROOT / "relay" / "relay.py")], env=env,
|
|
stdout=open(work / "relay.log", "wb"), stderr=subprocess.STDOUT)
|
|
up = False
|
|
for _ in range(40):
|
|
time.sleep(0.5)
|
|
try:
|
|
req = urllib.request.Request(BASE + "/v1/health", headers=_UA)
|
|
with urllib.request.urlopen(req, timeout=2) as resp:
|
|
if resp.status == 200:
|
|
up = True
|
|
break
|
|
except Exception: # noqa: BLE001
|
|
continue
|
|
check("本地中转起来了", up)
|
|
if not up:
|
|
print((work / "relay.log").read_text(encoding="utf-8",
|
|
errors="replace")[-500:])
|
|
return 1
|
|
|
|
# 造两台设备
|
|
for i in (1, 2):
|
|
body = json.dumps({"deviceId": f"pc-{i}", "code": f"11111{i}",
|
|
"name": f"电脑{i}", "version": "1.4.0"}
|
|
).encode()
|
|
req = urllib.request.Request(
|
|
BASE + "/v1/agent/register", data=body, method="POST",
|
|
headers={**_UA, "Content-Type": "application/json"})
|
|
urllib.request.urlopen(req, timeout=10).read()
|
|
|
|
# ---------------- 模拟浏览器 ----------------
|
|
jar = http.cookiejar.CookieJar()
|
|
opener = urllib.request.build_opener(
|
|
urllib.request.HTTPCookieProcessor(jar))
|
|
|
|
print()
|
|
print("一、登录拿 Cookie")
|
|
form = urllib.parse.urlencode({"username": "xmz7891", "password": _admin_password()}).encode()
|
|
req = urllib.request.Request(BASE + "/admin/login", data=form,
|
|
method="POST", headers=_UA)
|
|
req.add_header("Content-Type", "application/x-www-form-urlencoded")
|
|
try:
|
|
opener.open(req, timeout=20).read()
|
|
except urllib.error.HTTPError:
|
|
pass
|
|
cookies = [c.name for c in jar]
|
|
check("种下了 lr_admin Cookie", "lr_admin" in cookies, cookies)
|
|
|
|
print()
|
|
print("二、拉管理页,检查删除按钮的 HTML/JS")
|
|
req = urllib.request.Request(BASE + "/zhongzhuanzhan", headers=_UA)
|
|
html = opener.open(req, timeout=20).read().decode("utf-8", "replace")
|
|
|
|
# 删除按钮的 class 改过(del -> "btn del"),
|
|
# 用 data-device 判定更稳 —— 删除按钮一定带它。
|
|
check("有删除按钮", "data-device" in html and "删除" in html)
|
|
check("删除全部按钮在", "delAll" in html)
|
|
has_fetch = "/v1/admin/delete" in html
|
|
check("JS 里的删除接口路径正确", has_fetch,
|
|
re.findall(r"fetch\('[^']+'", html)[:4])
|
|
|
|
# 抽出来看看那段 JS 长什么样(容易出错的地方)
|
|
js_start = html.find("<script>")
|
|
js_end = html.find("</script>", js_start)
|
|
script = html[js_start:js_end] if js_start >= 0 else ""
|
|
print(f" JS 长度 {len(script)} 字符")
|
|
# 花括号有没有配平(f-string 里双写 {{ }},容易多写或少写)
|
|
opens = script.count("{")
|
|
closes = script.count("}")
|
|
check("JS 花括号配平(f-string 双写容易错)", opens == closes,
|
|
f"{{ {opens} vs }} {closes}")
|
|
|
|
print()
|
|
print("三、用 Cookie 调删除接口(浏览器就是这么调的)")
|
|
body = json.dumps({"deviceId": "pc-1"}).encode()
|
|
req = urllib.request.Request(BASE + "/v1/admin/delete", data=body,
|
|
method="POST", headers=_UA)
|
|
req.add_header("Content-Type", "application/json")
|
|
try:
|
|
resp = opener.open(req, timeout=20)
|
|
result = json.loads(resp.read().decode("utf-8"))
|
|
status = resp.status
|
|
except urllib.error.HTTPError as exc:
|
|
status = exc.code
|
|
raw = exc.read().decode("utf-8", "replace")
|
|
try:
|
|
result = json.loads(raw)
|
|
except Exception: # noqa: BLE001
|
|
result = {"raw": raw[:150]}
|
|
|
|
check("带 Cookie 的删除请求被接受(不是 401/403)",
|
|
status == 200, f"HTTP {status} {result}")
|
|
check("删除成功", result.get("ok") is True, result)
|
|
|
|
print()
|
|
print("四、删完全部接口也要能用")
|
|
req = urllib.request.Request(BASE + "/v1/admin/delete_all",
|
|
data=b"{}", method="POST", headers=_UA)
|
|
req.add_header("Content-Type", "application/json")
|
|
try:
|
|
resp = opener.open(req, timeout=20)
|
|
result2 = json.loads(resp.read().decode("utf-8"))
|
|
status2 = resp.status
|
|
except urllib.error.HTTPError as exc:
|
|
status2 = exc.code
|
|
result2 = {"raw": exc.read().decode("utf-8", "replace")[:150]}
|
|
check("delete_all 带 Cookie 也能用", status2 == 200, f"HTTP {status2}")
|
|
check("delete_all 成功", result2.get("ok") is True, result2)
|
|
|
|
print()
|
|
print("=" * 62)
|
|
print(f"通过 {passed} 项,失败 {failed} 项")
|
|
return 0 if failed == 0 else 1
|
|
finally:
|
|
if relay is not None:
|
|
try:
|
|
relay.terminate()
|
|
relay.wait(timeout=8)
|
|
except Exception: # noqa: BLE001
|
|
try:
|
|
relay.kill()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
time.sleep(0.5)
|
|
shutil.rmtree(work, ignore_errors=True)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|