refactor(api): introduce v1 response contract

This commit is contained in:
2026-07-21 13:45:04 +08:00
parent 1d35fcf4a1
commit 7803b2faf0
13 changed files with 303 additions and 48 deletions

View File

@@ -0,0 +1,18 @@
package httpx
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// IdentityParam 只接受 UUIDv7 路径参数,避免把内部自增 ID 暴露为外部标识。
func IdentityParam(c *gin.Context, name string) (string, bool) {
identity, err := uuid.Parse(c.Param(name))
if err != nil || identity.Version() != 7 {
Error(c, http.StatusBadRequest, "invalid_request", "请求参数无效")
return "", false
}
return identity.String(), true
}

View File

@@ -0,0 +1,21 @@
package httpx
import "github.com/gin-gonic/gin"
// ErrorBody 描述稳定错误契约中的机器码和可执行中文信息。
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
}
// ErrorEnvelope 统一包装所有对外 HTTP 错误。
type ErrorEnvelope struct {
Error ErrorBody `json:"error"`
}
// Error 中止当前请求并返回标准错误结构,避免向客户端泄露内部错误细节。
func Error(c *gin.Context, status int, code, message string) {
c.AbortWithStatusJSON(status, ErrorEnvelope{
Error: ErrorBody{Code: code, Message: message},
})
}

View File

@@ -0,0 +1,61 @@
package httpx
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestErrorUsesStableEnvelope(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
Error(ctx, http.StatusBadRequest, "invalid_request", "请求参数无效")
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.JSONEq(t, `{"error":{"code":"invalid_request","message":"请求参数无效"}}`, recorder.Body.String())
require.True(t, ctx.IsAborted())
}
func TestIdentityParamAcceptsUUIDV7(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "projectId", Value: "018f0c9a-7b3c-7cc1-98c8-0242ac120002"}}
identity, ok := IdentityParam(ctx, "projectId")
require.True(t, ok)
require.Equal(t, "018f0c9a-7b3c-7cc1-98c8-0242ac120002", identity)
require.False(t, ctx.IsAborted())
}
func TestIdentityParamRejectsNonUUIDV7(t *testing.T) {
tests := []struct {
name string
value string
}{
{name: "internal numeric ID", value: "42"},
{name: "UUID v4", value: "550e8400-e29b-41d4-a716-446655440000"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Params = gin.Params{{Key: "projectId", Value: tt.value}}
identity, ok := IdentityParam(ctx, "projectId")
require.False(t, ok)
require.Empty(t, identity)
require.Equal(t, http.StatusBadRequest, recorder.Code)
require.JSONEq(t, `{"error":{"code":"invalid_request","message":"请求参数无效"}}`, recorder.Body.String())
})
}
}

View File

@@ -2,6 +2,7 @@ package httpx
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
@@ -13,10 +14,12 @@ type RouteRegistrar interface {
Register(router gin.IRouter)
}
// NewRouter 创建仅暴露 /api/v1 业务契约的公开路由。
func NewRouter(cfg config.Config, registrars ...RouteRegistrar) *gin.Engine {
return newRouter(cfg, nil, registrars...)
}
// NewProtectedRouter 为 /api/v1 业务路由启用签名 session 校验。
func NewProtectedRouter(cfg config.Config, tokenVerifier func(string) (uint, error), registrars ...RouteRegistrar) *gin.Engine {
return newRouter(cfg, tokenVerifier, registrars...)
}
@@ -28,14 +31,14 @@ func newRouter(cfg config.Config, tokenVerifier func(string) (uint, error), regi
router := gin.New()
router.Use(gin.Recovery())
router.Use(cors())
router.Use(cors(cfg))
router.GET("/healthz", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
api := router.Group("/api")
api := router.Group("/api/v1")
api.GET("/status", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"timestamp_ms": time.Now().UnixMilli()})
c.JSON(http.StatusOK, gin.H{"timestamp": time.Now().UTC().Format(time.RFC3339Nano)})
})
if tokenVerifier != nil {
api.Use(auth.RequireUser(tokenVerifier))
@@ -47,22 +50,27 @@ func newRouter(cfg config.Config, tokenVerifier func(string) (uint, error), regi
return router
}
func cors() gin.HandlerFunc {
allowedOrigins := map[string]bool{
"http://localhost:5173": true,
"http://127.0.0.1:5173": true,
"http://localhost:4173": true,
"http://127.0.0.1:4173": true,
"http://localhost:4174": true,
"http://127.0.0.1:4174": true,
"http://localhost:4175": true,
"http://127.0.0.1:4175": true,
"http://tauri.localhost": true,
func cors(cfg config.Config) gin.HandlerFunc {
origins := cfg.AllowedOrigins
if len(origins) == 0 && (cfg.Env == "development" || cfg.Env == "dev" || cfg.Env == "test") {
origins = []string{
"http://localhost:5173",
"http://127.0.0.1:5173",
"http://tauri.localhost",
}
}
// 非开发环境在未配置来源时默认拒绝跨域,防止意外开放浏览器访问。
allowedOrigins := make(map[string]struct{}, len(origins))
for _, origin := range origins {
if origin = strings.TrimSpace(origin); origin != "" {
allowedOrigins[origin] = struct{}{}
}
}
return func(c *gin.Context) {
origin := c.GetHeader("Origin")
if allowedOrigins[origin] {
if _, ok := allowedOrigins[origin]; ok {
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Vary", "Origin")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")

View File

@@ -23,9 +23,9 @@ func TestHealthz(t *testing.T) {
require.JSONEq(t, `{"status":"ok"}`, rec.Body.String())
}
func TestNewRouterRegistersFeatureRoutesUnderAPI(t *testing.T) {
func TestNewRouterRegistersFeatureRoutesUnderAPIV1(t *testing.T) {
router := NewRouter(config.Config{Env: "test"}, testRegistrar{})
req := httptest.NewRequest(http.MethodGet, "/api/ping", nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -34,7 +34,27 @@ func TestNewRouterRegistersFeatureRoutesUnderAPI(t *testing.T) {
require.JSONEq(t, `{"pong":true}`, rec.Body.String())
}
func TestAPIStatusReturnsChangingTimestampMillisecondsWithoutAuth(t *testing.T) {
func TestStatusLivesUnderAPIV1(t *testing.T) {
router := NewRouter(config.Config{Env: "test"})
req := httptest.NewRequest(http.MethodGet, "/api/v1/status", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusOK, recorder.Code)
}
func TestLegacyAPIRouteIsNotExposed(t *testing.T) {
router := NewRouter(config.Config{Env: "test"}, testRegistrar{})
req := httptest.NewRequest(http.MethodGet, "/api/ping", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusNotFound, recorder.Code)
}
func TestAPIStatusReturnsChangingRFC3339UTCTimestampWithoutAuth(t *testing.T) {
router := NewProtectedRouter(config.Config{Env: "test"}, func(token string) (uint, error) {
return 0, http.ErrNoCookie
})
@@ -43,13 +63,14 @@ func TestAPIStatusReturnsChangingTimestampMillisecondsWithoutAuth(t *testing.T)
time.Sleep(2 * time.Millisecond)
second := getStatusTimestamp(t, router)
require.Greater(t, first, int64(0))
require.Greater(t, second, first)
require.Equal(t, time.UTC, first.Location())
require.Equal(t, time.UTC, second.Location())
require.True(t, second.After(first))
}
func TestRouterAddsCORSHeadersForLocalWebClient(t *testing.T) {
router := NewRouter(config.Config{Env: "test"}, testRegistrar{})
req := httptest.NewRequest(http.MethodGet, "/api/ping", nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
req.Header.Set("Origin", "http://localhost:5173")
rec := httptest.NewRecorder()
@@ -60,11 +81,45 @@ func TestRouterAddsCORSHeadersForLocalWebClient(t *testing.T) {
require.Contains(t, rec.Header().Get("Access-Control-Allow-Headers"), "Authorization")
}
func TestAPIV1LoginRemainsPublic(t *testing.T) {
router := NewProtectedRouter(config.Config{Env: "test"}, func(token string) (uint, error) {
return 0, http.ErrNoCookie
}, loginRegistrar{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
}
func TestRouterUsesConfiguredCORSOrigins(t *testing.T) {
router := NewRouter(config.Config{Env: "test", AllowedOrigins: []string{"https://workbench.example.com"}}, testRegistrar{})
req := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
req.Header.Set("Origin", "https://workbench.example.com")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, "https://workbench.example.com", rec.Header().Get("Access-Control-Allow-Origin"))
}
func TestRouterRejectsUnconfiguredCORSOrigin(t *testing.T) {
router := NewRouter(config.Config{Env: "production", AllowedOrigins: []string{"https://workbench.example.com"}}, testRegistrar{})
req := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
req.Header.Set("Origin", "https://attacker.example.com")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Empty(t, rec.Header().Get("Access-Control-Allow-Origin"))
}
func TestRouterHandlesCORSPreflightBeforeAuth(t *testing.T) {
router := NewProtectedRouter(config.Config{Env: "test"}, func(token string) (uint, error) {
return 0, http.ErrNoCookie
}, testRegistrar{})
req := httptest.NewRequest(http.MethodOptions, "/api/ping", nil)
req := httptest.NewRequest(http.MethodOptions, "/api/v1/ping", nil)
req.Header.Set("Origin", "http://localhost:5173")
req.Header.Set("Access-Control-Request-Method", "GET")
req.Header.Set("Access-Control-Request-Headers", "Authorization")
@@ -85,17 +140,27 @@ func (testRegistrar) Register(router gin.IRouter) {
})
}
func getStatusTimestamp(t *testing.T, router http.Handler) int64 {
type loginRegistrar struct{}
func (loginRegistrar) Register(router gin.IRouter) {
router.POST("/auth/login", func(c *gin.Context) {
c.Status(http.StatusOK)
})
}
func getStatusTimestamp(t *testing.T, router http.Handler) time.Time {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/status", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
var payload struct {
TimestampMS int64 `json:"timestamp_ms"`
Timestamp string `json:"timestamp"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
return payload.TimestampMS
timestamp, err := time.Parse(time.RFC3339Nano, payload.Timestamp)
require.NoError(t, err)
return timestamp
}