feat(admin): M2 WebUI 管理后台(鉴权+仪表盘+音色 CRUD)

新增 /admin 管理后台,Vue3 + axios 单文件 SPA。

新增:
- middleware/admin_auth.go: RequireAdmin 中间件
  复用 OPENAI_TTS_API_KEY(Bearer),密钥为空等同无鉴权;
  常量时间比较防计时攻击(用 common.SecureEqualString);
  401 + WWW-Authenticate 头 + JSON 错误体。
- controller/admin.go: 5 个 admin handler
  - GET /api/admin/overview: 模式/db路径/lock/版本/运行时间/音色数/内存
  - GET /api/admin/metrics: 鉴权版 Prometheus 文本(无鉴权版 /metrics 仍给 Prometheus)
  - GET /api/voices: 列表(含 disabled)
  - POST /api/voices: 新增,409 处理重复,400 处理字段不合法
  - DELETE /api/voices/{name}: 删除,409 处理被 default_speaker 引用
  - PATCH /api/voices/{name}/toggle: 启停
- router/admin.html: 单文件 SPA(18KB)
  登录页(单 input) + 仪表盘(metrics cards) + 音色 tab(表格+新增+启停+删除);
  hash 路由切 tab;axios 拦截器自动加 Bearer,401 回登录页;
  sessionStorage 存 key(关浏览器失效)。
- common/constants.go: SecureEqualString 提取到公共包
  controller/setup.go + middleware/admin_auth.go 共用,避免重复实现。

改造:
- router/router.go: 挂 /admin(/admin HTML 公开,鉴权由前端 JS 拦截)
  + /api/admin/{overview,metrics} + /api/voices{,/{name},/{name}/toggle}
  全部 API 端点套 RequireAdmin;正常模式 / → 302 /admin(M2 优先于 /dashboard)。
- main.go: 启动期调 SetAdminStore + SetMetricsTextWriter(避免 controller → metrics cycle)
- metrics/metrics.go: AdapterRecorder 用 SpeakerLabel 替代明文 speaker
  (这是第 4 处 speaker 泄漏,顺带补上;前面 3 处在 51bd7ae 已修)。
- controller/setup.go: 用 common.SecureEqualString 替自己的实现(去重)。

测试(都被 .gitignore 排除,本地保留):
- router/router_test.go: 更新 4 个 NotFound 测试路径(/admin 现是注册路由,不再 404)
- telemetry/labels_test.go: 已有 SpeakerLabel/MaskSpeaker 测试(M2 复用)

e2e 验证(本机跑通):
- /admin 200 HTML(无鉴权,前端 JS 拦截)
- /api/admin/overview 无 Bearer 401
- /api/admin/overview 错 Bearer 401
- /api/admin/overview 对 Bearer 200 + JSON
- /api/voices GET 200 + 2 voices
- /api/voices POST 201 + new voice
- /api/voices/{name} DELETE 200
- /api/voices/{name}/toggle PATCH 200 + updated voice
- 正常模式 / 302 /admin
- 启动日志 BYTEDANCE_TTS_SPEAKER 仍打码 S_G8****naJ1(前次 fix 生效)

二进制大小: 16MB → ~17MB(admin.html +5 个 handler + 中间件)

未 push(用户要求与 speaker fix 51bd7ae 一起发,等服务器测完 M1 后一起验证)
This commit is contained in:
sun
2026-08-29 21:53:19 +08:00
parent 51bd7ae37a
commit 70865a3cf4
8 changed files with 806 additions and 33 deletions
+73
View File
@@ -0,0 +1,73 @@
package middleware
import (
"log"
"net/http"
"strings"
"github.com/volcano-tts/tts-api/common"
"github.com/volcano-tts/tts-api/setting"
)
// RequireAdmin 是 /admin 路由的鉴权中间件,复用 OPENAI_TTS_API_KEY。
// 行为:
// - Auth.APIKeys 为空 → 所有请求放行(等同无鉴权)
// - Authorization 头 Bearer token 在列表中 → 放行
// - 其它 → 401 + JSON {error: 'unauthorized', code: 'admin_auth_failed'}
//
// 设计: 与现有 /v1/audio/speech 用的 setting.Auth 共享同一份 keys,
// 用户只用管一个 env 变量(OPENAI_TTS_API_KEY)。
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 预检: 跨域/OPTIONS 直接放行(让浏览器能发 preflight)
if r.Method == http.MethodOptions {
next.ServeHTTP(w, r)
return
}
keys := setting.Auth.APIKeys
if len(keys) == 0 {
// 没配 admin key,等同无鉴权
next.ServeHTTP(w, r)
return
}
auth := r.Header.Get("Authorization")
const prefix = "Bearer "
if !strings.HasPrefix(auth, prefix) {
denyAdmin(w, r)
return
}
token := strings.TrimSpace(auth[len(prefix):])
if !inAPIKeyList(token, keys) {
denyAdmin(w, r)
return
}
next.ServeHTTP(w, r)
})
}
// inAPIKeyList 用常量时间比较,防 token 计时攻击。
// 单个 key 也走同一条路径,无差别处理。
func inAPIKeyList(token string, keys []string) bool {
if token == "" {
return false
}
match := false
for _, k := range keys {
if common.SecureEqualString(token, k) {
match = true
// 不 break,继续遍历,保持时间恒定
}
}
return match
}
// denyAdmin 写 401 + JSON 错误体,记录客户端 IP。
func denyAdmin(w http.ResponseWriter, r *http.Request) {
log.Printf("[admin_auth] 鉴权失败 - 路径=%s 客户端=%s", r.URL.Path, GetClientIP(r))
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("WWW-Authenticate", `Bearer realm="tts-admin"`)
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"error":{"code":"admin_auth_failed","message":"unauthorized","type":"authentication_error"}}`))
}