handler_contract_audit_test.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package auth
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "time"
  11. "perms-system-server/internal/loaders"
  12. "perms-system-server/internal/middleware"
  13. userModel "perms-system-server/internal/model/user"
  14. "perms-system-server/internal/response"
  15. "perms-system-server/internal/svc"
  16. "perms-system-server/internal/testutil"
  17. "github.com/stretchr/testify/assert"
  18. "github.com/stretchr/testify/require"
  19. )
  20. func init() { response.Setup() }
  21. // TC-0796: handler 薄层契约 —— LogoutHandler 在无认证上下文(userId=0) 时必须返回 401,
  22. // 而不是 200 或 5xx。这把"handler 正确透传 logic 错误"的契约冻结住, 避免未来改造时
  23. // 意外把未登录请求吞成成功/崩溃。
  24. func TestLogoutHandler_UnauthorizedWhenNoUserCtx(t *testing.T) {
  25. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  26. handler := LogoutHandler(svcCtx)
  27. req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
  28. rr := httptest.NewRecorder()
  29. handler.ServeHTTP(rr, req)
  30. var body response.Body
  31. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  32. assert.Equal(t, 401, body.Code)
  33. assert.Contains(t, body.Msg, "未登录")
  34. }
  35. // TC-0797: handler 薄层契约 —— LogoutHandler 在有效认证上下文下必须 200 且无响应体(httpx.Ok);
  36. // 同时 DB 的 tokenVersion 必须被实际递增 (证明 handler 真的调用了 logic 而不是只返回 200)。
  37. func TestLogoutHandler_SuccessIncrementsTokenVersion(t *testing.T) {
  38. ctx := context.Background()
  39. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  40. conn := testutil.GetTestSqlConn()
  41. now := time.Now().Unix()
  42. res, err := svcCtx.SysUserModel.Insert(ctx, &userModel.SysUser{
  43. Username: "h_lo_" + testutil.UniqueId(), Password: testutil.HashPassword("pw"),
  44. Nickname: "h_lo", Avatar: sql.NullString{}, IsSuperAdmin: 2, MustChangePassword: 2,
  45. Status: 1, TokenVersion: 0, CreateTime: now, UpdateTime: now,
  46. })
  47. require.NoError(t, err)
  48. userId, _ := res.LastInsertId()
  49. t.Cleanup(func() { testutil.CleanTable(ctx, conn, "`sys_user`", userId) })
  50. handler := LogoutHandler(svcCtx)
  51. req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
  52. // 模拟 JWT middleware 已经注入 userDetails 的场景
  53. req = req.WithContext(middleware.WithUserDetails(req.Context(), &loaders.UserDetails{
  54. UserId: userId, Username: "h_lo", Status: 1,
  55. }))
  56. rr := httptest.NewRecorder()
  57. handler.ServeHTTP(rr, req)
  58. assert.Equal(t, http.StatusOK, rr.Code, "成功登出必须 200")
  59. u, err := svcCtx.SysUserModel.FindOne(ctx, userId)
  60. require.NoError(t, err)
  61. assert.Equal(t, int64(1), u.TokenVersion,
  62. "handler 必须真正触达 logic 层; tokenVersion 未递增说明 handler 伪装成功")
  63. }
  64. // TC-0798: handler 薄层契约 —— ChangePasswordHandler 在 body 非法 JSON 时必须 400,
  65. // 且错误文案定位到解析错误而不是"密码错误"之类的 logic 层语义。
  66. func TestChangePasswordHandler_MalformedBodyReturns400(t *testing.T) {
  67. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  68. handler := ChangePasswordHandler(svcCtx)
  69. req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{not-json"))
  70. req.Header.Set("Content-Type", "application/json")
  71. rr := httptest.NewRecorder()
  72. handler.ServeHTTP(rr, req)
  73. var body response.Body
  74. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  75. assert.Equal(t, 400, body.Code,
  76. "handler 必须把 httpx.Parse 的错误包成 400; 旧实现有时会被吞成 500")
  77. assert.NotContains(t, body.Msg, "原密码", "400 的文案不应提到 logic 层的业务字段语义")
  78. }
  79. // TC-0799: handler 薄层契约 —— ChangePasswordHandler 在缺必填字段时也必须 400,
  80. // 这是 goctl 生成代码最容易退化的地方 (把 optional 错设成 required 或反之)。
  81. func TestChangePasswordHandler_MissingFieldsReturns400(t *testing.T) {
  82. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  83. handler := ChangePasswordHandler(svcCtx)
  84. req := httptest.NewRequest(http.MethodPut, "/api/auth/password", strings.NewReader("{}"))
  85. req.Header.Set("Content-Type", "application/json")
  86. rr := httptest.NewRecorder()
  87. handler.ServeHTTP(rr, req)
  88. var body response.Body
  89. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  90. assert.Equal(t, 400, body.Code)
  91. // 必填字段缺失应该精确到字段名, 便于客户端自动纠错
  92. assert.True(t,
  93. strings.Contains(body.Msg, "oldPassword") || strings.Contains(body.Msg, "newPassword"),
  94. "缺字段文案必须点名到 oldPassword / newPassword; 实际: %q", body.Msg)
  95. }