feat: 重构控制面安全机制与分页规范
本次提交包含多项安全加固和体验优化: 1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据 2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼 3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456 4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享 5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件 6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域 7. 插件管理、凭证管理等列表接口支持分页和搜索 8. 强制初始密码修改,未改密前禁止使用管理功能 9. 定时任务触发被拒日志节流,避免授权失效时刷屏 10. 健康检查接口移除环境信息泄露,返回固定响应
This commit is contained in:
@@ -14,10 +14,11 @@ from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import _require_admin, _resolve_login
|
||||
from controlplane.core.auth import _identity, _require_admin, _revoke_account_tokens
|
||||
from controlplane.core.crypto import _hash_password
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.notify import notify_account_created
|
||||
from controlplane.core.paging import count_rows, page_bounds
|
||||
from controlplane.core.pkgutil import (
|
||||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||||
_validate_pkg_zip, _version_key,
|
||||
@@ -28,15 +29,24 @@ router = APIRouter()
|
||||
|
||||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||||
@router.get("/api/admin/accounts")
|
||||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def admin_accounts(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||||
"""账号列表(统一分页 + 服务端搜索 q:账号/昵称/部门模糊,含已授权插件/可登录平台)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = "", []
|
||||
if q.strip():
|
||||
where = " WHERE (account LIKE %s OR nickname LIKE %s OR dept LIKE %s)"
|
||||
args = ["%" + q.strip() + "%"] * 3
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM accounts" + where, args)
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd, "
|
||||
" avatar, status, created_at "
|
||||
"FROM accounts ORDER BY id")]
|
||||
"FROM accounts" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for a in rows:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
@@ -45,7 +55,7 @@ def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
(a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
return {"accounts": rows}
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/account")
|
||||
@@ -53,10 +63,12 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""新建账号:密码必填,可指定部门/昵称/是否管理员。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = a.account.strip()
|
||||
if not account or not a.password:
|
||||
raise HTTPException(400, "account 与 password 必填")
|
||||
if len(a.password) < 8:
|
||||
raise HTTPException(400, "密码至少 8 位")
|
||||
with _db() as conn:
|
||||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone()
|
||||
if exists:
|
||||
@@ -70,6 +82,8 @@ def admin_account_create(a: schemas.AccountCreateIn,
|
||||
conn.commit()
|
||||
# 钉钉工作通知(异步,失败不阻断建号):新用户收账号密码(按昵称解析),管理员收权限开通提醒
|
||||
notify_account_created(account, (a.nickname or "").strip(), a.password, source="管理台")
|
||||
_audit(login, "account-create", account,
|
||||
f"is_admin={int(a.is_admin)}, dept={(a.dept or '').strip()}")
|
||||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||||
|
||||
@@ -106,6 +120,12 @@ def admin_account_update(a: schemas.AccountUpdateIn,
|
||||
conn.execute("UPDATE accounts SET status = %s WHERE account = %s",
|
||||
(int(bool(a.status)), account))
|
||||
conn.commit()
|
||||
if a.status is not None and not a.status:
|
||||
# 停用账号即吊销其云令牌,防止残留会话继续使用(P1 安全债)
|
||||
_revoke_account_tokens(account)
|
||||
_audit(login, "account-update", account,
|
||||
f"dept={a.dept is not None}, nickname={a.nickname is not None}, "
|
||||
f"is_admin={a.is_admin is not None}, status={a.status is not None}")
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -114,10 +134,12 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""管理员重置任意账号密码(无需原密码)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = r.account.strip()
|
||||
if not account or not r.new_password:
|
||||
raise HTTPException(400, "account 与新密码必填")
|
||||
if len(r.new_password) < 8:
|
||||
raise HTTPException(400, "新密码至少 8 位")
|
||||
with _db() as conn:
|
||||
if not conn.execute("SELECT 1 FROM accounts WHERE account = %s", (account,)).fetchone():
|
||||
raise HTTPException(400, f"账号 {account} 不存在")
|
||||
@@ -125,6 +147,7 @@ def admin_account_reset(r: schemas.AccountResetIn,
|
||||
conn.execute("UPDATE accounts SET password_hash = %s, salt = %s WHERE account = %s",
|
||||
(_hex, _salt, account))
|
||||
conn.commit()
|
||||
_audit(login, "account-reset-pwd", account)
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -145,6 +168,9 @@ def admin_account_delete(d: schemas.AccountDelIn,
|
||||
# account_plugins / account_platforms 由外键 ON DELETE CASCADE 级联清理
|
||||
conn.execute("DELETE FROM accounts WHERE account = %s", (account,))
|
||||
conn.commit()
|
||||
# 删除账号即吊销其云令牌(防残留令牌继续解析,P1 安全债)
|
||||
_revoke_account_tokens(account)
|
||||
_audit(login, "account-delete", account)
|
||||
return {"ok": True, "account": account}
|
||||
|
||||
|
||||
@@ -155,17 +181,21 @@ _AVATAR_EXT = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
|
||||
@router.post("/api/admin/avatar")
|
||||
def admin_avatar_upload(file: UploadFile = File(...),
|
||||
account: str = Query(...),
|
||||
authorization: str = Header(default="", alias="Authorization"),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""上传账号头像:自服务传自己;管理员可传任意账号。覆盖旧头像。"""
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
login = _identity(authorization=authorization, x_admin_token=x_admin_token,
|
||||
x_api_token=x_api_token, x_admin_user=x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
account = account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
if not _SAFE_NAME_RE.match(account):
|
||||
raise HTTPException(400, "account 含非法字符(仅允许字母数字及 . _ -,防止文件名穿越)")
|
||||
if account != login:
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
ext = Path(file.filename or "").suffix.lower()
|
||||
@@ -216,7 +246,7 @@ def admin_grant(g: schemas.GrantIn,
|
||||
MySQL 版合并表:权限位(can_download/can_run)即存在 account_plugins 本身,
|
||||
不再有独立 plugin_grants 表;撤销即删除 account_plugins 行。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
plugin_id = g.plugin_id.strip()
|
||||
if not account or not plugin_id:
|
||||
@@ -237,8 +267,9 @@ def admin_grant(g: schemas.GrantIn,
|
||||
conn.execute("DELETE FROM account_plugins WHERE account = %s AND plugin_id = %s",
|
||||
(account, plugin_id))
|
||||
conn.commit()
|
||||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"can_download={g.can_download},can_run={g.can_run}")
|
||||
# 审计 actor 用操作者 login(可追溯"谁操作的"),target 为插件、detail 记录被授权账号
|
||||
_audit(login, "grant" if g.granted else "revoke-grant", plugin_id,
|
||||
f"account={account},can_download={g.can_download},can_run={g.can_run}")
|
||||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||||
|
||||
|
||||
@@ -247,7 +278,7 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = g.account.strip()
|
||||
platform_id = g.platform_id.strip()
|
||||
if not account or not platform_id:
|
||||
@@ -263,6 +294,8 @@ def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||||
conn.execute("DELETE FROM account_platforms WHERE account = %s AND platform_id = %s",
|
||||
(account, platform_id))
|
||||
conn.commit()
|
||||
# 审计 actor 用操作者 login,target 为平台、detail 记录被授权账号
|
||||
_audit(login, "grant-platform" if g.granted else "revoke-platform", platform_id, account)
|
||||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||||
|
||||
|
||||
@@ -273,7 +306,7 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = plugin_id.strip()
|
||||
name = name.strip() or plugin_id
|
||||
version = version.strip()
|
||||
@@ -284,7 +317,19 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||||
filename = f"{plugin_id}_v{version}.zip"
|
||||
target = config.PKG_DIR / filename
|
||||
content = await upload.read()
|
||||
# 流式读取并限长(最大 200MB,与控制面插件包上限一致),避免整包先读入内存(P1 安全债)
|
||||
_MAX_PKG_BYTES = 200 * 1024 * 1024
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > _MAX_PKG_BYTES:
|
||||
raise HTTPException(413, f"插件包超过大小上限({_MAX_PKG_BYTES // (1024 * 1024)}MB)")
|
||||
chunks.append(chunk)
|
||||
content = b"".join(chunks)
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
_validate_pkg_zip(content)
|
||||
@@ -330,6 +375,7 @@ async def admin_upload_plugin(upload: UploadFile = File(...),
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_audit(login, "plugin-publish", plugin_id, f"version={version}, filename={filename}")
|
||||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||||
|
||||
|
||||
@@ -338,7 +384,7 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
plugin_id = d.plugin_id.strip()
|
||||
if not plugin_id:
|
||||
raise HTTPException(400, "plugin_id 必填")
|
||||
@@ -357,6 +403,7 @@ def admin_plugin_delete(d: schemas.PluginDelIn,
|
||||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
_audit(login, "plugin-delete", plugin_id, f"files={len(files)}")
|
||||
return {"ok": True, "plugin_id": plugin_id}
|
||||
|
||||
|
||||
@@ -405,11 +452,46 @@ def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = %s", vals)
|
||||
conn.commit()
|
||||
_audit("", "plugin-patch", pid, ", ".join(
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])) or "clear_force")
|
||||
return {"ok": True, "plugin_id": pid}
|
||||
|
||||
|
||||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||||
@router.get("/api/admin/plugins")
|
||||
def admin_plugins(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""插件列表(统一分页 + 服务端搜索 q:ID/名称模糊;含状态/版本/强制更新/能力声明/版本历史/授权账号)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = "", []
|
||||
if q.strip():
|
||||
where = " WHERE (id LIKE %s OR name LIKE %s)"
|
||||
args = ["%" + q.strip() + "%"] * 2
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM plugins" + where, args)
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, description, category, icon, status, latest_version, "
|
||||
" force_min_version, force_deadline, manifest "
|
||||
"FROM plugins" + where + " ORDER BY id LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for p in rows:
|
||||
m = _load_manifest(p.pop("manifest"))
|
||||
p["manifest"] = m
|
||||
p["capabilities"] = m.get("capabilities") or []
|
||||
props = (m.get("fields") or {}).get("properties") or {}
|
||||
p["field_count"] = len(props)
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r) for r in conn.execute(
|
||||
"SELECT ap.account, a.nickname FROM account_plugins ap "
|
||||
"LEFT JOIN accounts a ON a.account = ap.account "
|
||||
"WHERE ap.plugin_id = %s ORDER BY ap.account", (p["id"],))]
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -430,31 +512,54 @@ def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"
|
||||
p["versions"] = [dict(r) for r in conn.execute(
|
||||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||||
"WHERE plugin_id = %s ORDER BY version", (p["id"],))]
|
||||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM account_plugins WHERE plugin_id = %s", (p["id"],))]
|
||||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, can_download, can_run FROM account_plugins "
|
||||
"WHERE plugin_id = %s", (p["id"],))}
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, is_admin, dept, nickname, avatar, status, created_at "
|
||||
"FROM accounts ORDER BY id")]
|
||||
for a in accounts:
|
||||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||||
"SELECT plugin_id FROM account_plugins WHERE account = %s", (a["account"],))]
|
||||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms WHERE account = %s", (a["account"],))]
|
||||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||||
"canRun": bool(dict(r)["can_run"])}
|
||||
for r in conn.execute(
|
||||
"SELECT plugin_id, can_download, can_run FROM account_plugins "
|
||||
"WHERE account = %s", (a["account"],))}
|
||||
admins = [dict(r)["account"] for r in conn.execute(
|
||||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||||
|
||||
|
||||
@router.get("/api/admin/grant_data")
|
||||
def admin_grant_data(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""授权页轻量数据:全部插件(id/name/status,一次查询无 N+1)+ 全部账号(含昵称/部门)。
|
||||
替代授权页对 /overview 全量聚合的依赖,插件/账号多时依然轻快。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
plugins = [dict(r) for r in conn.execute(
|
||||
"SELECT id, name, status FROM plugins ORDER BY id")]
|
||||
accounts = [dict(r) for r in conn.execute(
|
||||
"SELECT account, nickname, dept, status FROM accounts "
|
||||
"WHERE status = 1 ORDER BY account")]
|
||||
return {"plugins": plugins, "accounts": accounts}
|
||||
|
||||
|
||||
@router.get("/api/admin/account_grants")
|
||||
def admin_account_grants(account: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""某账号的现有授权明细:已授权插件(含 can_run/can_download)+ 已授权平台。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
account = account.strip()
|
||||
with _db() as conn:
|
||||
grants = [dict(r) for r in conn.execute(
|
||||
"SELECT plugin_id, can_run, can_download FROM account_plugins "
|
||||
"WHERE account = %s ORDER BY plugin_id", (account,))]
|
||||
platforms = [dict(r)["platform_id"] for r in conn.execute(
|
||||
"SELECT platform_id FROM account_platforms "
|
||||
"WHERE account = %s ORDER BY platform_id", (account,))]
|
||||
return {
|
||||
"plugins": [{"plugin_id": g["plugin_id"],
|
||||
"canRun": bool(g["can_run"]),
|
||||
"canDownload": bool(g["can_download"])} for g in grants],
|
||||
"platforms": platforms,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/admin/stats")
|
||||
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -520,18 +625,17 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||
"ORDER BY runs DESC LIMIT 8")]
|
||||
|
||||
# 最近运行列表
|
||||
recent = [dict(r) for r in conn.execute(
|
||||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||||
"FROM runtime_reports WHERE status <> 'start' "
|
||||
"ORDER BY id DESC LIMIT 20")]
|
||||
# 活跃用户排行
|
||||
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||||
for r in conn.execute(
|
||||
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||||
"ORDER BY runs DESC LIMIT 8")]
|
||||
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
for tu in top_users:
|
||||
tu["nickname"] = nick.get(tu["account"], "")
|
||||
for rc in recent:
|
||||
rc["nickname"] = nick.get(rc.get("account", ""), "")
|
||||
|
||||
now_day = datetime.now().strftime("%Y-%m-%d")
|
||||
return {
|
||||
@@ -543,56 +647,107 @@ def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||||
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||||
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||||
"recent": recent, "today": now_day,
|
||||
"today": now_day,
|
||||
}
|
||||
|
||||
|
||||
# ==================== 审计 / 运行上报(统一分页 + 服务端筛选) ====================
|
||||
def _audit_where(action: str, q: str) -> tuple[str, list]:
|
||||
"""审计筛选条件:action 精确 + q 模糊(账号/对象/详情)。"""
|
||||
where, args = [], []
|
||||
if action.strip():
|
||||
where.append("action = %s")
|
||||
args.append(action.strip())
|
||||
if q.strip():
|
||||
where.append("(account LIKE %s OR target LIKE %s OR detail LIKE %s)")
|
||||
args += ["%" + q.strip() + "%"] * 3
|
||||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||
|
||||
|
||||
def _report_where(status: str, q: str) -> tuple[str, list]:
|
||||
"""运行上报筛选条件:status 支持逗号分隔多值(如 done,success)+ q 模糊(账号/设备/插件/消息)。"""
|
||||
where, args = [], []
|
||||
if status.strip():
|
||||
vals = [s.strip() for s in status.split(",") if s.strip()]
|
||||
if len(vals) == 1:
|
||||
where.append("status = %s")
|
||||
args.append(vals[0])
|
||||
elif len(vals) > 1:
|
||||
where.append("status IN (%s)" % ", ".join(["%s"] * len(vals)))
|
||||
args += vals
|
||||
if q.strip():
|
||||
where.append("(account LIKE %s OR device_id LIKE %s OR plugin_id LIKE %s OR msg LIKE %s)")
|
||||
args += ["%" + q.strip() + "%"] * 4
|
||||
return (" WHERE " + " AND ".join(where)) if where else "", args
|
||||
|
||||
|
||||
@router.get("/api/admin/audit")
|
||||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_audit(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
action: str = Query(default=""),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||||
"""审计日志(统一分页 + 服务端筛选:action 操作类型、q 账号/对象/详情关键字,today 今日条数)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = _audit_where(action, q)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs" + where, args)
|
||||
today = count_rows(conn, "SELECT COUNT(*) AS c FROM audit_logs WHERE at >= CURDATE()")
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||||
"ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
"SELECT id, account, action, target, detail, at FROM audit_logs" + where +
|
||||
" ORDER BY id DESC LIMIT %s OFFSET %s", args + [limit, offset])]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"auditlogs": rows}
|
||||
return {"items": rows, "total": total, "today": today}
|
||||
|
||||
|
||||
@router.get("/api/admin/reports")
|
||||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_reports(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
status: str = Query(default=""),
|
||||
q: str = Query(default=""),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""运行上报记录(最新在前)。"""
|
||||
"""运行上报记录(统一分页 + 服务端筛选:status 状态、q 账号/设备/插件/消息,today 今日条数)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
where, args = _report_where(status, q)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports" + where, args)
|
||||
today = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports WHERE at >= CURDATE()")
|
||||
failed = count_rows(conn, "SELECT COUNT(*) AS c FROM runtime_reports "
|
||||
"WHERE status IN ('error','failed')")
|
||||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||||
"SELECT account, nickname FROM accounts")}
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||||
"FROM runtime_reports ORDER BY id DESC LIMIT %s", (limit,))]
|
||||
"SELECT id, account, device_id AS deviceId, plugin_id AS pluginId, version, status, msg, "
|
||||
"duration_sec AS durationSec, at "
|
||||
"FROM runtime_reports" + where + " ORDER BY id DESC LIMIT %s OFFSET %s",
|
||||
args + [limit, offset])]
|
||||
for r in rows:
|
||||
r["nickname"] = nick.get(r["account"], "")
|
||||
return {"reports": rows}
|
||||
return {"items": rows, "total": total, "today": today, "failed": failed}
|
||||
|
||||
|
||||
@router.get("/api/admin/devices")
|
||||
def admin_devices(limit: int = Query(default=200, ge=1, le=1000),
|
||||
def admin_devices(page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=1000),
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""执行机设备列表(按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
"""执行机设备列表(统一分页,按最近心跳倒序):环境信息 + Chrome 检测结果。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
with _db() as conn:
|
||||
total = count_rows(conn, "SELECT COUNT(*) AS c FROM devices")
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT device_id, account, hostname, os, ip, chrome_installed, chrome_version, "
|
||||
" chrome_ok, last_seen, status, created_at, updated_at "
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s", (limit,))]
|
||||
return {"devices": rows}
|
||||
"FROM devices ORDER BY last_seen DESC LIMIT %s OFFSET %s", (limit, offset))]
|
||||
return {"items": rows, "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/shell-release")
|
||||
@@ -606,7 +761,7 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
|
||||
供 agent CLI / 管理端从任意机器上传壳子安装包,执行机据此自动下载升级。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
version = version.strip()
|
||||
if not version:
|
||||
raise HTTPException(400, "version 不能为空")
|
||||
@@ -614,7 +769,19 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
raise HTTPException(400, "version 仅允许字母数字及 . _ -")
|
||||
config.SHELL_DIR.mkdir(parents=True, exist_ok=True)
|
||||
filename = f"setup-37du-host-{version}.exe"
|
||||
content = await upload.read()
|
||||
# 流式读取并限长(壳子安装包上限 1GB,防磁盘/内存耗尽,P1 安全债)
|
||||
_MAX_SHELL_BYTES = 1024 * 1024 * 1024
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > _MAX_SHELL_BYTES:
|
||||
raise HTTPException(413, f"壳子安装包超过大小上限({_MAX_SHELL_BYTES // (1024 * 1024)}MB)")
|
||||
chunks.append(chunk)
|
||||
content = b"".join(chunks)
|
||||
if not content:
|
||||
raise HTTPException(400, "上传内容为空")
|
||||
if not sha256:
|
||||
@@ -624,5 +791,5 @@ async def admin_shell_release(upload: UploadFile = File(...),
|
||||
json.dumps({"version": version, "filename": filename,
|
||||
"sha256": sha256, "notes": notes},
|
||||
ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
_audit("", "shell-release", filename)
|
||||
_audit(login, "shell-release", filename)
|
||||
return {"ok": True, "version": version, "filename": filename, "sha256": sha256}
|
||||
Reference in New Issue
Block a user