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}
|
||||
@@ -10,8 +10,9 @@ from fastapi import APIRouter, Header, HTTPException
|
||||
|
||||
from controlplane import config, schemas
|
||||
from controlplane.core.auth import (
|
||||
_AUTH_FAILS, _auth_fail, _auth_gate, _check_token,
|
||||
_cloud_account, _issue_cloud_token, _resolve_login, _require_admin, _sign_admin_token,
|
||||
_auth_fail, _auth_gate, _auth_reset, _check_token,
|
||||
_cloud_account, _identity, _issue_cloud_token,
|
||||
_require_admin, _sign_admin_token,
|
||||
)
|
||||
from controlplane.core.crypto import _hash_password, _verify_password
|
||||
from controlplane.core.db import _db
|
||||
@@ -36,26 +37,28 @@ def admin_me(authorization: str = Header(default="", alias="Authorization"),
|
||||
身份来源依次:登录时签发的用户云令牌(Bearer) → 签名票据(X-Admin-Token) →
|
||||
底座注入的 X-Admin-User(仅当配了 CONTROLPLANE_TOKEN 时可信)。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
try:
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||
"must_change_pwd": False}
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT is_admin, dept, nickname, status, avatar FROM accounts WHERE account = %s",
|
||||
"SELECT is_admin, dept, nickname, status, avatar, must_change_pwd "
|
||||
"FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
# 账号停用:视为未登录(执行机/控制面前端据此自动登出)
|
||||
if not row or not row["status"]:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": ""}
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": "", "avatar": "",
|
||||
"must_change_pwd": False}
|
||||
return {"account": account,
|
||||
"is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] if row else "") or "",
|
||||
"nickname": (row["nickname"] if row else "") or "",
|
||||
"avatar": (row["avatar"] if row else "") or ""}
|
||||
"avatar": (row["avatar"] if row else "") or "",
|
||||
"must_change_pwd": bool(row["must_change_pwd"])}
|
||||
|
||||
|
||||
@router.get("/api/admin/platforms")
|
||||
@@ -85,7 +88,7 @@ def admin_auth(a: schemas.AuthIn,
|
||||
raise HTTPException(401, "账号或密码错误")
|
||||
if not row["status"]:
|
||||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||||
_AUTH_FAILS.pop(account, None)
|
||||
_auth_reset(account)
|
||||
_nickname = (row["nickname"] or "")
|
||||
return {"ok": True, "account": account, "is_admin": bool(row["is_admin"]),
|
||||
"dept": (row["dept"] or ""), "nickname": _nickname,
|
||||
@@ -102,14 +105,14 @@ def admin_password(p: schemas.PwdIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""自助修改密码:任何统一账号可改自己的密码(需旧密码校验通过)。"""
|
||||
login = _cloud_account(authorization)
|
||||
if not login:
|
||||
try:
|
||||
login = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
try:
|
||||
login = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
if not p.account.strip() or not p.new_password:
|
||||
raise HTTPException(400, "account 与新密码不能为空")
|
||||
if len(p.new_password) < 8:
|
||||
raise HTTPException(400, "新密码至少 8 位")
|
||||
if p.account != login:
|
||||
raise HTTPException(403, "只能修改自己的密码")
|
||||
with _db() as conn:
|
||||
@@ -153,7 +156,7 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
# 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT nickname, status, must_change_pwd FROM accounts WHERE account = %s",
|
||||
"SELECT nickname, status, must_change_pwd, is_admin FROM accounts WHERE account = %s",
|
||||
(account,)).fetchone()
|
||||
if row:
|
||||
if not row["status"]:
|
||||
@@ -163,6 +166,7 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
(nickname, account))
|
||||
conn.commit()
|
||||
created, must_change = False, bool(row["must_change_pwd"])
|
||||
is_admin = bool(row["is_admin"])
|
||||
else:
|
||||
# 自动建号(空壳):初始密码取默认值,强制首次改密
|
||||
pwd = config.DINGTALK_DEFAULT_PASSWORD
|
||||
@@ -172,9 +176,9 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
|
||||
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||||
(account, _hex, _salt, nickname, unionid))
|
||||
conn.commit()
|
||||
created, must_change = True, True
|
||||
created, must_change, is_admin = True, True, False
|
||||
notify_account_created(account, nickname, pwd, unionid, source="钉钉扫码")
|
||||
token = _issue_cloud_token(account, nickname)
|
||||
return {"token": token, "account": account, "nickname": nickname,
|
||||
"exists": True, "created": created, "must_change_pwd": must_change,
|
||||
"is_admin": False}
|
||||
"exists": not created, "created": created, "must_change_pwd": must_change,
|
||||
"is_admin": is_admin}
|
||||
@@ -14,12 +14,13 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
|
||||
from controlplane import schemas
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login, _require_admin
|
||||
from controlplane.core.auth import _cloud_account, _identity, _require_admin
|
||||
from controlplane.core.crypto import rsa_encrypt
|
||||
from controlplane.core.db import _db, _now
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.paging import count_rows, page_bounds
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -74,7 +75,7 @@ def creds_seed(b: schemas.CredsSeedIn,
|
||||
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
|
||||
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
|
||||
"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
account = b.account.strip()
|
||||
if not account:
|
||||
raise HTTPException(400, "account 不能为空")
|
||||
@@ -91,24 +92,34 @@ def creds_seed(b: schemas.CredsSeedIn,
|
||||
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, '', %s, %s)",
|
||||
(account, json.dumps(allowed, ensure_ascii=False), _now()))
|
||||
conn.commit()
|
||||
# 敏感明文源写入属高危操作,审计留痕(不记录明文值本身)
|
||||
_audit(login, "creds-seed", account, f"keys={sorted(allowed)}")
|
||||
return {"ok": True, "account": account, "seeded_keys": sorted(allowed)}
|
||||
|
||||
|
||||
@router.get("/api/admin/creds/manage")
|
||||
def creds_manage(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
def creds_manage(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:
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(管理员回显,供页面编辑;值仅管理台可见)。"""
|
||||
"""管理台:列出已注册账号及其敏感凭证明文源(统一分页,items/total;值仅管理台可见)。"""
|
||||
_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 client_creds")
|
||||
rows = conn.execute(
|
||||
"SELECT account, pubkey_pem, creds, updated_at FROM client_creds ORDER BY account").fetchall()
|
||||
"SELECT c.account, c.pubkey_pem, c.creds, c.updated_at, a.nickname "
|
||||
"FROM client_creds c LEFT JOIN accounts a ON a.account = c.account "
|
||||
"ORDER BY c.account LIMIT %s OFFSET %s", (limit, offset)).fetchall()
|
||||
return {
|
||||
"accounts": [{
|
||||
"items": [{
|
||||
"account": r["account"],
|
||||
"nickname": r["nickname"] or "",
|
||||
"has_pubkey": bool(r["pubkey_pem"]),
|
||||
"creds": json.loads(r["creds"] or "{}"),
|
||||
"updated_at": str(r["updated_at"] or ""),
|
||||
} for r in rows],
|
||||
"total": total,
|
||||
"allowed_keys": list(_ALLOWED_KEYS),
|
||||
}
|
||||
|
||||
@@ -123,12 +134,10 @@ def creds_fetch(authorization: str = Header(default="", alias="Authorization"),
|
||||
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
|
||||
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
|
||||
"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
try:
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
with _db() as conn:
|
||||
|
||||
@@ -6,9 +6,10 @@
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import secrets
|
||||
from urllib.parse import quote, urlencode
|
||||
from urllib.parse import quote, urlencode, urlparse
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from fastapi.responses import RedirectResponse
|
||||
@@ -23,6 +24,27 @@ from controlplane.core.notify import notify_account_created
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _safe_back_url(url: str) -> bool:
|
||||
"""回跳地址白名单:仅允许 http(s) + 回环 / 内网私有网段 / 配置的控制面域名。
|
||||
|
||||
防止开放重定向钓鱼(原实现仅校验 http(s) 前缀,可被引导到任意站点并携带身份信息)。
|
||||
"""
|
||||
if not url or not (url.startswith("http://") or url.startswith("https://")):
|
||||
return False
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
return True
|
||||
if config.DINGTALK_CALLBACK:
|
||||
cb_host = (urlparse(config.DINGTALK_CALLBACK).hostname or "").lower()
|
||||
if host == cb_host:
|
||||
return True
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
return bool(ip.is_loopback or ip.is_private)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
@router.post("/api/admin/dingtalk/auth")
|
||||
def admin_dingtalk_auth(d: schemas.DingTalkIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
@@ -80,8 +102,8 @@ def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳
|
||||
"""扫码入口:302 到钉钉扫码登录页;state 携带部署机回跳地址,扫码成功后由 /cb 带回。"""
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not _safe_back_url(back):
|
||||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名,防止开放重定向)")
|
||||
if not config.DINGTALK_CALLBACK:
|
||||
raise HTTPException(400, "未配置 DINGTALK_CALLBACK(钉钉后台登记的回调地址)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
@@ -97,8 +119,8 @@ def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||||
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||||
if not (state.startswith("http://") or state.startswith("https://")):
|
||||
raise HTTPException(400, "非法回跳地址")
|
||||
if not _safe_back_url(state):
|
||||
raise HTTPException(400, "非法回跳地址(仅允许回环/内网/控制面域名)")
|
||||
info = _dingtalk_userinfo(code)
|
||||
qs = urlencode({"account": info["account"] or "", "nickname": info["nickname"],
|
||||
"unionid": info["unionid"] or ""})
|
||||
@@ -144,8 +166,8 @@ def dingtalk_login_url(back: str = Query(...),
|
||||
_check_token(x_api_token)
|
||||
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
|
||||
raise HTTPException(503, "控制面未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
|
||||
if not (back.startswith("http://") or back.startswith("https://")):
|
||||
raise HTTPException(400, "回跳地址非法(防止开放重定向)")
|
||||
if not _safe_back_url(back):
|
||||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名)")
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": back,
|
||||
"response_type": "code",
|
||||
|
||||
@@ -8,11 +8,13 @@ from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from fastapi import APIRouter, Header, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from controlplane.core.auth import _check_token, _require_admin
|
||||
from controlplane.core.db import _db, _now
|
||||
from controlplane.core.db import _audit, _db, _now
|
||||
from controlplane.core.paging import page_bounds
|
||||
from controlplane.core.pkgutil import _version_key
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -46,19 +48,23 @@ def _rows_to_dicts(rows) -> list[dict]:
|
||||
|
||||
@router.get("/api/admin/file-sources")
|
||||
def file_sources_list(category: str = "",
|
||||
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:
|
||||
"""按 category 列出大文件源(可按 category 过滤,分组也可由 category 字段区分)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
"""按 category 列出大文件源(统一分页:先按版本号数值语义排序,再切片 items/total)。"""
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
with _db() as conn:
|
||||
if category.strip():
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources WHERE category = %s ORDER BY version, id",
|
||||
(category.strip(),)).fetchall()
|
||||
"SELECT * FROM file_sources WHERE category = %s", (category.strip(),)).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM file_sources ORDER BY category, version, id").fetchall()
|
||||
return {"category": category, "files": _rows_to_dicts(rows)}
|
||||
rows = conn.execute("SELECT * FROM file_sources").fetchall()
|
||||
# 版本号按数值语义排序("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||
rows = sorted(rows, key=lambda r: (_version_key(r["version"]), r["id"]), reverse=True)
|
||||
total = len(rows)
|
||||
limit, offset = page_bounds(page, page_size)
|
||||
return {"category": category, "items": _rows_to_dicts(rows[offset:offset + limit]), "total": total}
|
||||
|
||||
|
||||
@router.post("/api/admin/file-sources")
|
||||
@@ -66,7 +72,7 @@ def file_sources_upsert(b: FileSourceIn,
|
||||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||||
"""登记/覆盖一条大文件源(同一 category+version 去重)。"""
|
||||
_require_admin(x_admin_token, x_api_token)
|
||||
login = _require_admin(x_admin_token, x_api_token)
|
||||
category, version = b.category.strip(), b.version.strip()
|
||||
url = b.url.strip()
|
||||
if not category:
|
||||
@@ -92,6 +98,7 @@ def file_sources_upsert(b: FileSourceIn,
|
||||
b.notes.strip(), int(b.enabled), _now()))
|
||||
fid = cur.lastrowid
|
||||
conn.commit()
|
||||
_audit(login, "file-source-upsert", f"{category}@{version}", url)
|
||||
return {"ok": True, "id": fid, "category": category, "version": version}
|
||||
|
||||
|
||||
@@ -100,7 +107,7 @@ def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
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)
|
||||
fields, vals = [], []
|
||||
if b.enabled is not None:
|
||||
fields.append("enabled = %s"); vals.append(int(b.enabled))
|
||||
@@ -115,6 +122,7 @@ def file_sources_patch(fid: int, b: FileSourcePatch,
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
_audit(login, "file-source-patch", str(fid), f"enabled={b.enabled}, notes={b.notes is not None}")
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@@ -123,12 +131,13 @@ def file_sources_delete(fid: int,
|
||||
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)
|
||||
with _db() as conn:
|
||||
cur = conn.execute("DELETE FROM file_sources WHERE id = %s", (fid,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
raise HTTPException(404, "记录不存在")
|
||||
_audit(login, "file-source-delete", str(fid))
|
||||
return {"ok": True, "id": fid}
|
||||
|
||||
|
||||
@@ -141,13 +150,13 @@ def file_sources_public_latest(category: str,
|
||||
"""
|
||||
_check_token(x_api_token)
|
||||
with _db() as conn:
|
||||
rows = conn.execute(
|
||||
rows = [dict(r) for r in conn.execute(
|
||||
"SELECT id, category, version, filename, url, sha256, notes FROM file_sources "
|
||||
"WHERE category = %s AND enabled = 1 ORDER BY version DESC, id DESC LIMIT 1",
|
||||
(category.strip(),)).fetchall()
|
||||
"WHERE category = %s AND enabled = 1", (category.strip(),))]
|
||||
if not rows:
|
||||
return {"available": False, "category": category.strip()}
|
||||
r = rows[0]
|
||||
# 版本号按数值语义取最新("1.10" > "1.9"),避免字符串排序取错(P2 修复)
|
||||
r = max(rows, key=lambda r: (_version_key(r["version"]), r["id"]))
|
||||
return {
|
||||
"available": True,
|
||||
"category": r["category"], "version": r["version"],
|
||||
|
||||
@@ -4,11 +4,10 @@ from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from controlplane import config
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True, "db": "mysql", "host": config.MYSQL_HOST, "database": config.MYSQL_DB}
|
||||
"""健康检查:不泄露任何环境信息(原实现返回 MYSQL_HOST/库名,公网可探,P2 收敛)。"""
|
||||
return {"ok": True}
|
||||
@@ -13,7 +13,7 @@ import json
|
||||
from fastapi import APIRouter, Header, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from controlplane.core.auth import _cloud_account, _resolve_login
|
||||
from controlplane.core.auth import _identity
|
||||
from controlplane.core.db import _db, _now
|
||||
|
||||
router = APIRouter()
|
||||
@@ -23,18 +23,13 @@ class _BackupIn(BaseModel):
|
||||
data: dict = {}
|
||||
|
||||
|
||||
def _identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""解析请求身份;无效则抛 401。"""
|
||||
account = _cloud_account(authorization)
|
||||
if not account:
|
||||
try:
|
||||
account = _resolve_login(x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
account = ""
|
||||
if not account:
|
||||
def _require_identity(authorization: str = "", x_admin_token: str = "",
|
||||
x_api_token: str = "", x_admin_user: str = "") -> str:
|
||||
"""统一身份解析(core.auth._identity),无效则抛 401。"""
|
||||
try:
|
||||
return _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
except Exception:
|
||||
raise HTTPException(401, "登录态无效或已过期,请重新登录")
|
||||
return account
|
||||
|
||||
|
||||
@router.post("/api/schedules/backup")
|
||||
@@ -44,7 +39,7 @@ def sched_backup_save(b: _BackupIn,
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""覆盖保存某账号的定时任务全量配置(执行机变更后异步推送)。"""
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
payload = b.data if isinstance(b.data, dict) else {}
|
||||
if not isinstance(payload.get("schedules"), list):
|
||||
raise HTTPException(400, "data.schedules 必须为数组")
|
||||
@@ -63,7 +58,7 @@ def sched_backup_load(authorization: str = Header(default="", alias="Authorizati
|
||||
x_api_token: str = Header(default="", alias="X-API-Token"),
|
||||
x_admin_user: str = Header(default="", alias="X-Admin-User")) -> dict:
|
||||
"""读取某账号备份的定时任务全量配置(执行机启动时合并恢复缺失任务)。"""
|
||||
account = _identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
account = _require_identity(authorization, x_admin_token, x_api_token, x_admin_user)
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT data FROM schedule_backups WHERE account = %s", (account,)).fetchone()
|
||||
|
||||
Reference in New Issue
Block a user