feat(frontend): add API integration playground

This commit is contained in:
wizardchen
2026-06-30 21:14:06 +08:00
committed by lyingbug
parent a24567a951
commit ee1014f87c
10 changed files with 1186 additions and 136 deletions
+130 -20
View File
@@ -5,8 +5,10 @@ import (
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
@@ -110,11 +112,28 @@ type apiPrincipalConfigResponse struct {
SignedTokenHeaderName string `json:"signed_token_header_name"`
RequireDirectHeader bool `json:"require_direct_header"`
HasHMACSecret bool `json:"has_hmac_secret"`
HMACSecret string `json:"hmac_secret,omitempty"`
}
type apiPrincipalTestTokenRequest struct {
ExternalUserID string `json:"external_user_id"`
ExpiresInSeconds int `json:"expires_in_seconds"`
}
type apiPrincipalTestTokenResponse struct {
Token string `json:"token"`
HeaderName string `json:"header_name"`
ExpiresInSeconds int `json:"expires_in_seconds"`
ExpiresAtUnix int64 `json:"expires_at_unix"`
ExternalUserID string `json:"external_user_id"`
}
const (
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
defaultAPIPrincipalDirectHeader = "X-External-User-ID"
defaultAPIPrincipalTokenHeader = "X-External-User-Token"
defaultAPIPrincipalTestTokenTTL = 15 * time.Minute
maxAPIPrincipalTestTokenTTL = time.Hour
maxAPIPrincipalExternalUserIDLen = 128
)
// defaultMaxOwnedTenantsPerUser is the cap applied when
@@ -539,20 +558,13 @@ func apiPrincipalConfigForResponse(cfg *types.APIPrincipalConfig) apiPrincipalCo
if mode == "" {
mode = types.APIPrincipalModeTenant
}
directHeader := strings.TrimSpace(cfg.DirectHeaderName)
if directHeader == "" {
directHeader = defaultAPIPrincipalDirectHeader
}
tokenHeader := strings.TrimSpace(cfg.SignedTokenHeaderName)
if tokenHeader == "" {
tokenHeader = defaultAPIPrincipalTokenHeader
}
return apiPrincipalConfigResponse{
Mode: mode,
DirectHeaderName: directHeader,
SignedTokenHeaderName: tokenHeader,
DirectHeaderName: defaultAPIPrincipalDirectHeader,
SignedTokenHeaderName: defaultAPIPrincipalTokenHeader,
RequireDirectHeader: cfg.RequireDirectHeader,
HasHMACSecret: strings.TrimSpace(cfg.HMACSecret) != "",
HMACSecret: strings.TrimSpace(cfg.HMACSecret),
}
}
@@ -645,17 +657,11 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
}
cfg := &types.APIPrincipalConfig{
Mode: req.Mode,
DirectHeaderName: strings.TrimSpace(req.DirectHeaderName),
SignedTokenHeaderName: strings.TrimSpace(req.SignedTokenHeaderName),
DirectHeaderName: defaultAPIPrincipalDirectHeader,
SignedTokenHeaderName: defaultAPIPrincipalTokenHeader,
RequireDirectHeader: req.RequireDirectHeader,
HMACSecret: hmacSecret,
}
if cfg.DirectHeaderName == "" {
cfg.DirectHeaderName = defaultAPIPrincipalDirectHeader
}
if cfg.SignedTokenHeaderName == "" {
cfg.SignedTokenHeaderName = defaultAPIPrincipalTokenHeader
}
if cfg.Mode == types.APIPrincipalModeSignedToken && strings.TrimSpace(cfg.HMACSecret) == "" {
c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))
return
@@ -677,6 +683,110 @@ func (h *TenantHandler) UpdateAPIPrincipalConfig(c *gin.Context) {
})
}
// CreateAPIPrincipalTestToken godoc
// @Summary 生成 API Playground 测试 JWT
// @Description 使用租户已保存的 HMAC 密钥签发短期外部用户 JWT(Owner)
// @Tags 租户管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Param request body handler.apiPrincipalTestTokenRequest true "测试 Token 参数"
// @Success 200 {object} map[string]interface{} "短期 JWT"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Router /tenants/{id}/api-principal-test-token [post]
func (h *TenantHandler) CreateAPIPrincipalTestToken(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
return
}
var req apiPrincipalTestTokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
externalUserID := strings.TrimSpace(req.ExternalUserID)
if err := validateAPIPrincipalExternalUserID(externalUserID); err != nil {
c.Error(errors.NewValidationError("external_user_id is invalid").WithDetails(err.Error()))
return
}
tenant, err := h.service.GetTenantByID(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
} else {
c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
}
return
}
cfg := tenant.APIPrincipalConfig
if cfg == nil || cfg.Mode != types.APIPrincipalModeSignedToken {
c.Error(errors.NewValidationError("signed_token mode is required"))
return
}
secret := strings.TrimSpace(cfg.HMACSecret)
if secret == "" {
c.Error(errors.NewValidationError("hmac_secret is required for signed_token mode"))
return
}
ttl := defaultAPIPrincipalTestTokenTTL
if req.ExpiresInSeconds > 0 {
ttl = time.Duration(req.ExpiresInSeconds) * time.Second
}
if ttl <= 0 || ttl > maxAPIPrincipalTestTokenTTL {
c.Error(errors.NewValidationError("expires_in_seconds must be between 1 and 3600"))
return
}
now := time.Now()
expiresAt := now.Add(ttl)
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": externalUserID,
"tenant_id": strconv.FormatUint(id, 10),
"aud": "weknora",
"iat": now.Unix(),
"exp": expiresAt.Unix(),
}).SignedString([]byte(secret))
if err != nil {
c.Error(errors.NewInternalServerError("Failed to create API principal test token").WithDetails(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": apiPrincipalTestTokenResponse{
Token: token,
HeaderName: defaultAPIPrincipalTokenHeader,
ExpiresInSeconds: int(ttl.Seconds()),
ExpiresAtUnix: expiresAt.Unix(),
ExternalUserID: externalUserID,
},
})
}
func validateAPIPrincipalExternalUserID(id string) error {
if id == "" {
return errors.NewValidationError("external_user_id is required")
}
if len(id) > maxAPIPrincipalExternalUserIDLen {
return errors.NewValidationError("external_user_id is too long")
}
for _, r := range id {
if r < 0x20 || r == 0x7f {
return errors.NewValidationError("external_user_id contains invalid characters")
}
}
return nil
}
// DeleteTenant godoc
// @Summary 删除租户
// @Description 删除指定的租户