本次提交包含多项安全加固和体验优化: 1. 分离管理密钥与传输凭证,避免持 API Token 者伪造管理员票据 2. 钉钉回调地址增加白名单校验,防止开放重定向钓鱼 3. 初始管理员密码改为随机生成并日志记录,移除硬编码 123456 4. 新增登录防爆破计数表,支持 MySQL 多 worker 共享 5. 统一分页规范,新增 usePagedList composable 和 PagerBar 组件 6. 控制面 CORS 收敛为白名单,避免公网环境下任意站点跨域 7. 插件管理、凭证管理等列表接口支持分页和搜索 8. 强制初始密码修改,未改密前禁止使用管理功能 9. 定时任务触发被拒日志节流,避免授权失效时刷屏 10. 健康检查接口移除环境信息泄露,返回固定响应
178 lines
9.1 KiB
Python
178 lines
9.1 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""钉钉扫码路由:找建账号 / OAuth 扫码页 + 回调 / 内嵌二维码(DDLogin)。
|
||
|
||
- 账号建立/鉴权统一走 /api/admin/dingtalk/auth(find-or-create,仅底座 X-API-Token 可调);
|
||
- /scan→/cb 与 /sns 仅为可信扫码入口,仅换取身份不建号(建号仍由 auth 把关)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ipaddress
|
||
import re
|
||
import secrets
|
||
from urllib.parse import quote, urlencode, urlparse
|
||
|
||
from fastapi import APIRouter, Header, HTTPException, Query
|
||
from fastapi.responses import RedirectResponse
|
||
|
||
from controlplane import config, schemas
|
||
from controlplane.core.auth import _check_token, _sign_admin_token
|
||
from controlplane.core.crypto import _hash_password
|
||
from controlplane.core.db import _db
|
||
from controlplane.core.dingtalk import _dingtalk_sns_userinfo, _dingtalk_userinfo
|
||
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:
|
||
"""钉钉扫码身份 → 找建统一账号(仅底座 X-API-Token 可调)。
|
||
|
||
返回 {ok, account, nickname, is_admin, created, must_change_pwd, token}。
|
||
created=True 表示本次新建;must_change_pwd=True 表示当前为默认密码,前端须提示改密。
|
||
"""
|
||
_check_token(x_api_token)
|
||
account = d.account.strip()
|
||
if not account or not account.isprintable() or re.search(r"[\s]", account):
|
||
raise HTTPException(400, "工号不能为空且不可包含空白字符")
|
||
nickname = (d.nickname or "").strip()
|
||
ding_uid = (d.dingtalk_uid or "").strip()
|
||
with _db() as conn:
|
||
row = conn.execute(
|
||
"SELECT account, is_admin, must_change_pwd, nickname, status FROM accounts WHERE account = %s",
|
||
(account,)).fetchone()
|
||
if row:
|
||
# 已存在:顺带同步昵称(钉钉名),但不改密码/权限;原有 must_change_pwd 保留
|
||
if not row["status"]:
|
||
raise HTTPException(403, "账号已停用,请联系管理员")
|
||
if nickname and nickname != (row["nickname"] or ""):
|
||
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
|
||
(nickname, account))
|
||
conn.commit()
|
||
return {"ok": True, "account": account,
|
||
"nickname": nickname or (row["nickname"] or ""),
|
||
"is_admin": bool(row["is_admin"]),
|
||
"created": False, "must_change_pwd": bool(row["must_change_pwd"]),
|
||
"token": _sign_admin_token(account)}
|
||
# 不存在:自动建号(空壳),初始密码取覆盖值或默认值,强制改密
|
||
pwd = (d.password.strip() if d.password else config.DINGTALK_DEFAULT_PASSWORD)
|
||
if len(pwd) < 6:
|
||
raise HTTPException(400, "初始密码至少 6 位")
|
||
_hex, _salt = _hash_password(pwd)
|
||
conn.execute(
|
||
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
|
||
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
|
||
(account, _hex, _salt, nickname, ding_uid))
|
||
conn.commit()
|
||
# 钉钉工作通知(异步,失败不阻断建号):新用户收默认账号密码,管理员收权限开通提醒
|
||
notify_account_created(account, nickname, pwd, ding_uid, source="钉钉扫码")
|
||
return {"ok": True, "account": account, "nickname": nickname,
|
||
"is_admin": False, "created": True, "must_change_pwd": True,
|
||
"token": _sign_admin_token(account)}
|
||
|
||
|
||
# ==================== 钉钉真实扫码(OAuth):扫码页 + 回调换取身份 ====================
|
||
# 流程:部署机扫码按钮 → 本机 /api/admin/dingtalk/scan → 跳钉钉登录页(redirect_uri=本中心机回调)
|
||
# → 用户扫码确认 → 钉钉回调 /api/admin/dingtalk/cb?code → 换 token 拉工号/姓名 →
|
||
# 302 回部署机(state 中带回的 back)携带身份 → 部署机静默建会话。
|
||
@router.get("/api/admin/dingtalk/scan")
|
||
def dingtalk_scan(back: str = Query(..., description="扫码成功后的回跳地址")) -> RedirectResponse:
|
||
"""扫码入口: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 _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({
|
||
"redirect_uri": f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb",
|
||
"response_type": "code",
|
||
"client_id": config.DINGTALK_APP_KEY,
|
||
"scope": "openid",
|
||
"prompt": "consent",
|
||
"state": back})
|
||
return RedirectResponse(login_url)
|
||
|
||
|
||
@router.get("/api/admin/dingtalk/cb")
|
||
def dingtalk_cb(code: str = Query(...), state: str = Query(...)) -> RedirectResponse:
|
||
"""钉钉回调:换 token 拉工号/姓名后,302 回部署机(state 里的回跳地址)携带身份。"""
|
||
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 ""})
|
||
sep = "&" if "?" in state else "?"
|
||
return RedirectResponse(f"{state}{sep}{qs}")
|
||
|
||
|
||
@router.post("/api/admin/dingtalk/sns")
|
||
def dingtalk_sns(d: schemas.SnsIn) -> dict:
|
||
"""内嵌二维码扫码换取身份:loginTmpCode → 工号/姓名/unionid。
|
||
|
||
与 /scan→/cb 同为可信扫码入口,仅换取身份(不建号),故与链接授权链路一致不强制 X-API-Token;
|
||
账号创建仍由 /api/admin/dingtalk(find-or-create, _check_token)把关。
|
||
"""
|
||
if not d.code.strip():
|
||
raise HTTPException(400, "缺少扫码截图码")
|
||
return _dingtalk_sns_userinfo(d.code.strip())
|
||
|
||
|
||
@router.get("/api/admin/dingtalk/inline_qr")
|
||
def dingtalk_inline_qr(back: str = Query(default="", description="(兼容保留,内嵌不直接跳转)")) -> dict:
|
||
"""构造内嵌二维码(DDLogin)所需的 goto:登录页在本页内渲染二维码,不弹新窗口。"""
|
||
if not config.DINGTALK_APP_KEY:
|
||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||
if not config.DINGTALK_CALLBACK:
|
||
raise HTTPException(503, "未配置中心机回调域名(DINGTALK_CALLBACK)")
|
||
auth_url = ("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=%s"
|
||
"&response_type=code&scope=snsapi_login&state=%s&redirect_uri=%s") % (
|
||
config.DINGTALK_APP_KEY, secrets.token_hex(8),
|
||
quote(f"{config.DINGTALK_CALLBACK}/api/admin/dingtalk/cb"))
|
||
return {"goto": quote(auth_url)}
|
||
|
||
|
||
@router.get("/api/dingtalk/login-url")
|
||
def dingtalk_login_url(back: str = Query(...),
|
||
state: str = Query(default=""),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""构造钉钉扫码授权 URL(执行机代理调用):执行机无需自带钉钉应用凭证。
|
||
|
||
back 为执行机本机回跳地址(如 http://localhost:8799/auth/done),state 由执行机生成防回跳伪造;
|
||
扫码后钉钉跳回 back,执行机再拿 code 走 /auth/exchange 换身份。
|
||
"""
|
||
_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 _safe_back_url(back):
|
||
raise HTTPException(400, "回跳地址非法(仅允许回环/内网/控制面域名)")
|
||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||
"redirect_uri": back,
|
||
"response_type": "code",
|
||
"client_id": config.DINGTALK_APP_KEY,
|
||
"scope": "openid",
|
||
"prompt": "consent",
|
||
"state": state or back})
|
||
return {"url": login_url} |