fix: code compliance audit and fix across all services
NestJS (6 services): implement @RequirePermission decorator with SetMetadata+Reflector, register APP_GUARD globally, fix as assertions to type guards, add explicit return types, fix import type for express, fix /metrics implicit any, replace native Error with ApplicationError, remove typeorm remnants, register LifecycleService. teacher-bff: add logger, ApplicationError, GlobalErrorFilter, forward real userId to downstream, log downstream failures, migrate health controller to shared/health. Go (2 services): interface to any, doc comments, CORS dev whitelist, JWT secret fail-fast, push-gateway internal API auth, metrics and readyz endpoints, remove dead code. Python (2 services): lifespan return type, dev_mode to bool, data-ana APIRouter, ai POST body model, ClickHouse async wrapping.
This commit is contained in:
@@ -1,24 +1,44 @@
|
||||
package config
|
||||
|
||||
import "os"
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Config 持有 push-gateway 运行时配置
|
||||
type Config struct {
|
||||
Port string
|
||||
JWTSecret string
|
||||
DevMode bool
|
||||
RedisURL string
|
||||
OTLPEndpoint string
|
||||
Port string
|
||||
JWTSecret string
|
||||
DevMode bool
|
||||
RedisURL string
|
||||
OTLPEndpoint string
|
||||
InternalAPIKey string
|
||||
}
|
||||
|
||||
// Load 从环境变量加载配置并提供默认值
|
||||
// devJWTSecret 是 DevMode 下的默认 JWT 密钥(仅用于本地联调,生产必须配置 JWT_SECRET)
|
||||
const devJWTSecret = "p1-dev-secret-change-in-production"
|
||||
|
||||
// Load 从环境变量加载配置。
|
||||
// 非 DevMode 下若 JWT_SECRET 未配置则 fatal 退出;DevMode 下使用默认密钥并打印 warning。
|
||||
func Load() *Config {
|
||||
devMode := getEnv("DEV_MODE", "false") == "true"
|
||||
jwtSecret := getEnv("JWT_SECRET", "")
|
||||
if jwtSecret == "" {
|
||||
if devMode {
|
||||
log.Println("warning: JWT_SECRET not set, using dev default (DEV_MODE=true)")
|
||||
jwtSecret = devJWTSecret
|
||||
} else {
|
||||
log.Fatal("JWT_SECRET must be set in non-dev mode")
|
||||
}
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Port: getEnv("PUSH_GATEWAY_PORT", "8081"),
|
||||
JWTSecret: getEnv("JWT_SECRET", "p1-dev-secret-change-in-production"),
|
||||
DevMode: getEnv("DEV_MODE", "false") == "true",
|
||||
RedisURL: getEnv("REDIS_URL", ""),
|
||||
OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318"),
|
||||
Port: getEnv("PUSH_GATEWAY_PORT", "8081"),
|
||||
JWTSecret: jwtSecret,
|
||||
DevMode: devMode,
|
||||
RedisURL: getEnv("REDIS_URL", ""),
|
||||
OTLPEndpoint: getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318"),
|
||||
InternalAPIKey: getEnv("INTERNAL_API_KEY", ""),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,17 @@ func NewHub() *Hub {
|
||||
}
|
||||
}
|
||||
|
||||
// ClientCount 返回当前在线连接总数(供 /readyz 探针使用)
|
||||
func (h *Hub) ClientCount() int {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
count := 0
|
||||
for _, conns := range h.clients {
|
||||
count += len(conns)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Register 注册一个用户连接,返回 Connection 供调用方持有
|
||||
func (h *Hub) Register(userID string, conn *websocket.Conn) *Connection {
|
||||
c := &Connection{
|
||||
|
||||
@@ -3,6 +3,7 @@ package ws
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -25,16 +26,20 @@ var upgrader = websocket.Upgrader{
|
||||
},
|
||||
}
|
||||
|
||||
// internalAPIKeyHeader 是内部 API 鉴权请求头名称
|
||||
const internalAPIKeyHeader = "X-Internal-Key"
|
||||
|
||||
// Handler 处理 WebSocket 升级与内部推送 API
|
||||
type Handler struct {
|
||||
hub *hub.Hub
|
||||
jwtSecret string
|
||||
devMode bool
|
||||
hub *hub.Hub
|
||||
jwtSecret string
|
||||
devMode bool
|
||||
internalAPIKey string
|
||||
}
|
||||
|
||||
// NewHandler 创建 Handler 实例
|
||||
func NewHandler(h *hub.Hub, jwtSecret string, devMode bool) *Handler {
|
||||
return &Handler{hub: h, jwtSecret: jwtSecret, devMode: devMode}
|
||||
func NewHandler(h *hub.Hub, jwtSecret string, devMode bool, internalAPIKey string) *Handler {
|
||||
return &Handler{hub: h, jwtSecret: jwtSecret, devMode: devMode, internalAPIKey: internalAPIKey}
|
||||
}
|
||||
|
||||
// HandleWebSocket 升级 HTTP 为 WebSocket,保持长连接并处理心跳
|
||||
@@ -47,6 +52,7 @@ func (h *Handler) HandleWebSocket(c *gin.Context) {
|
||||
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
log.Printf("[ws] upgrade failed, user=%s: %v", userID, err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
@@ -58,6 +64,7 @@ func (h *Handler) HandleWebSocket(c *gin.Context) {
|
||||
go func() {
|
||||
for msg := range connPtr.Outgoing() {
|
||||
if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
|
||||
log.Printf("[ws] write failed, user=%s: %v", userID, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -67,6 +74,9 @@ func (h *Handler) HandleWebSocket(c *gin.Context) {
|
||||
for {
|
||||
_, msg, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
if !websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
|
||||
log.Printf("[ws] read failed, user=%s: %v", userID, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
if strings.ToLower(string(msg)) == "ping" {
|
||||
@@ -77,6 +87,14 @@ func (h *Handler) HandleWebSocket(c *gin.Context) {
|
||||
|
||||
// PushHandler 接收来自 Msg 服务的定向推送请求
|
||||
func (h *Handler) PushHandler(c *gin.Context) {
|
||||
if !h.checkInternalAPIKey(c) {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false,
|
||||
"error": gin.H{"code": "UNAUTHORIZED", "message": "invalid or missing internal api key"},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
UserID string `json:"userId"`
|
||||
Event string `json:"event"`
|
||||
@@ -103,6 +121,14 @@ func (h *Handler) PushHandler(c *gin.Context) {
|
||||
|
||||
// BroadcastHandler 接收来自 Msg 服务的广播请求
|
||||
func (h *Handler) BroadcastHandler(c *gin.Context) {
|
||||
if !h.checkInternalAPIKey(c) {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false,
|
||||
"error": gin.H{"code": "UNAUTHORIZED", "message": "invalid or missing internal api key"},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Event string `json:"event"`
|
||||
Data map[string]any `json:"data"`
|
||||
@@ -122,6 +148,19 @@ func (h *Handler) BroadcastHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"success": true})
|
||||
}
|
||||
|
||||
// checkInternalAPIKey 校验内部 API 请求头 X-Internal-Key。
|
||||
// DevMode 下跳过校验;非 DevMode 下要求 INTERNAL_API_KEY 已配置且与请求头匹配。
|
||||
func (h *Handler) checkInternalAPIKey(c *gin.Context) bool {
|
||||
if h.devMode {
|
||||
return true
|
||||
}
|
||||
if h.internalAPIKey == "" {
|
||||
log.Println("[ws] internal api key not configured, rejecting request")
|
||||
return false
|
||||
}
|
||||
return c.GetHeader(internalAPIKeyHeader) == h.internalAPIKey
|
||||
}
|
||||
|
||||
// authenticate 校验 WebSocket 连接的 JWT 或 dev token
|
||||
func (h *Handler) authenticate(c *gin.Context) (string, error) {
|
||||
tokenStr := c.Query("token")
|
||||
|
||||
Reference in New Issue
Block a user