Files
37duAutomation/desktop/controlplane/apis/config_push.py
T
puddy 8a196d6c87 feat: 重构控制面安全机制与分页规范
本次提交包含多项安全加固和体验优化:
1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据
2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼
3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456
4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享
5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件
6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域
7. 插件管理、凭证管理等列表接口支持分页和搜索
8. 强制初始密码修改,未改密前禁止使用管理功能
9. 定时任务触发被拒日志节流,避免授权失效时刷屏
10. 健康检查接口移除环境信息泄露,返回固定响应
2026-09-23 15:19:54 +08:00

163 lines
8.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""客户端敏感凭证中心化拉取(服务端侧):公钥登记 / 敏感凭证加密拉取 / 明文源管理。
- 凭证明文源存服务端 MySQL `client_creds.creds`(JSON: {key: plaintext}),
明文源只由管理员经「敏感凭证」页面(/creds/manage 查看 + /creds/seed 保存)录入;
register 仅登记执行机 RSA 公钥,不自动填充默认值。
- 拉取 GET /api/admin/creds:**仅管理员可拉**(解析身份后校验 is_admin),服务端用该账号
上报的 RSA 公钥把每个明文值 OAEP 加密为 base64 返回;客户端本机私钥解密。
- 钉钉扫码 URL 已改由控制面代理构造(/api/dingtalk/login-url),执行机不再消费下发的钉钉值,
链路保留供未来每账号敏感值下发能力使用。
- 仅含钉钉开放平台凭证;HR/OA 平台登录账号由客户端本地加密存储(platform_accounts),不经服务端。
"""
from __future__ import annotations
import json
from fastapi import APIRouter, Header, HTTPException, Query
from controlplane import schemas
from controlplane.core.auth import _cloud_account, _identity, _require_admin
from controlplane.core.crypto import rsa_encrypt
from controlplane.core.db import _audit, _db, _now
from controlplane.core.paging import count_rows, page_bounds
router = APIRouter()
# 与 webhost/backend/core/creds_sync.py 的敏感键白名单保持一致(双重保障:下发限定范围)。
# 仅下发钉钉开放平台凭证;HR/OA 平台登录账号改由执行机本地加密存储(platform_accounts),不经中心机。
_ALLOWED_KEYS = (
"DINGTALK_APPKEY", "DINGTALK_APPSECRET", "DINGTALK_AGENT_ID", "DINGTALK_CORP_ID",
)
@router.post("/api/admin/creds/register")
def creds_register(b: schemas.CredsRegisterIn,
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")) -> dict:
"""登记/更新某账号的 RSA 公钥(明文源不变)。
鉴权双轨(对齐方案"admin 或云令牌关联账号"):
- 管理员(X-Admin-Token)可为任意账号登记;
- 登录云令牌(Bearer)账号只能登记本人公钥(公钥本身公开,本人登记安全)。
"""
try:
_require_admin(x_admin_token, x_api_token)
except HTTPException:
_self = _cloud_account(authorization)
if not _self or _self != b.account.strip():
raise HTTPException(401, "登录态无效或已过期,请重新登录")
account = b.account.strip()
pem = b.pubkey_pem.strip()
if not account or not pem:
raise HTTPException(400, "account 与 pubkey_pem 不能为空")
with _db() as conn:
row = conn.execute(
"SELECT creds FROM client_creds WHERE account = %s", (account,)).fetchone()
# 明文源只由管理员 seed 创建/更新:register 仅登记公钥,保留现有明文源(无则空)
existing = (row["creds"] if row else None) or "{}"
conn.execute(
"INSERT INTO client_creds(account, pubkey_pem, creds, updated_at) VALUES (%s, %s, %s, %s) "
"ON DUPLICATE KEY UPDATE pubkey_pem = VALUES(pubkey_pem), "
"creds = VALUES(creds), updated_at = VALUES(updated_at)",
(account, pem, existing, _now()))
conn.commit()
return {"ok": True, "account": account}
@router.post("/api/admin/creds/seed")
def creds_seed(b: schemas.CredsSeedIn,
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
"""录入/更新某账号的敏感凭证明文源(管理员,只允许白名单内键)。
仅当 pubkey_pem 非空时才需要用现有公钥给新增值加密留档;这里统一存明文源,
/creds 下发时实时用该账号公钥加密,故无需在此预加密。
"""
login = _require_admin(x_admin_token, x_api_token)
account = b.account.strip()
if not account:
raise HTTPException(400, "account 不能为空")
allowed = {k: v for k, v in b.values.items() if k in _ALLOWED_KEYS}
with _db() as conn:
row = conn.execute(
"SELECT pubkey_pem FROM client_creds WHERE account = %s", (account,)).fetchone()
if row:
conn.execute(
"UPDATE client_creds SET creds = %s, updated_at = %s WHERE account = %s",
(json.dumps(allowed, ensure_ascii=False), _now(), account))
else:
conn.execute(
"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(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 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 {
"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),
}
@router.get("/api/admin/creds")
def creds_fetch(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:
"""下发敏感凭证(**仅管理员可拉**)。鉴权:登录云令牌(Bearer) → 签名票据 → X-Admin-User。
解析出账号后校验 is_admin=1,非管理员一律 403(员工无法拉取,堵住越权窃取口子)。
用账号上报的 RSA 公钥把每个明文值 OAEP 加密为 base64;无公钥或无明文源返回空。
"""
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:
admin = conn.execute(
"SELECT is_admin FROM accounts WHERE account = %s", (account,)).fetchone()
if not admin or not admin["is_admin"]:
raise HTTPException(403, "仅管理员可拉取敏感凭证")
with _db() as conn:
row = conn.execute(
"SELECT pubkey_pem, creds FROM client_creds WHERE account = %s", (account,)).fetchone()
if not row or not row["pubkey_pem"]:
return {"account": account, "creds": {}}
try:
source = json.loads(row["creds"] or "{}")
encrypted = {k: rsa_encrypt(row["pubkey_pem"], v)
for k, v in source.items() if v is not None}
except Exception as e: # noqa: BLE001
raise HTTPException(500, f"凭证加密失败: {e}") from e
with _db() as conn:
conn.execute("UPDATE client_creds SET updated_at = %s WHERE account = %s",
(_now(), account))
conn.commit()
return {"account": account, "creds": encrypted}