refreshTokenHandler_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package pub
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. "perms-system-server/internal/response"
  9. "perms-system-server/internal/svc"
  10. "perms-system-server/internal/testutil"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/stretchr/testify/require"
  13. )
  14. // TC-0800: handler 薄层契约 —— RefreshTokenHandler 在 Authorization header 缺失时,
  15. // 必须把错误透传成 401 "未登录" / 或等价业务错误 (绝不能 200 或 5xx)。
  16. // 同时不应把内部实现细节泄露到 Msg 里。
  17. func TestRefreshTokenHandler_MissingAuthorizationHeader(t *testing.T) {
  18. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  19. handler := RefreshTokenHandler(svcCtx)
  20. req := httptest.NewRequest(http.MethodPost, "/api/auth/refreshToken", strings.NewReader("{}"))
  21. req.Header.Set("Content-Type", "application/json")
  22. rr := httptest.NewRecorder()
  23. handler.ServeHTTP(rr, req)
  24. var body response.Body
  25. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  26. assert.NotEqual(t, 200, body.ErrorCode, "缺 Authorization 必须报错而非 200")
  27. assert.True(t, body.ErrorCode == 401 || body.ErrorCode == 400,
  28. "缺 Authorization 必须是 401/400; 实际 code=%d msg=%q", body.ErrorCode, body.ErrorMessage)
  29. assert.NotContains(t, strings.ToLower(body.ErrorMessage), "sql", "错误文案不得泄露 SQL 实现细节")
  30. assert.NotContains(t, strings.ToLower(body.ErrorMessage), "redis", "错误文案不得泄露 Redis 实现细节")
  31. }
  32. // TC-0801: handler 薄层契约 —— RefreshTokenHandler 在 Authorization 带非法值时 401, 且不 panic。
  33. func TestRefreshTokenHandler_GarbageBearerToken(t *testing.T) {
  34. svcCtx := svc.NewServiceContext(testutil.GetTestConfig())
  35. handler := RefreshTokenHandler(svcCtx)
  36. req := httptest.NewRequest(http.MethodPost, "/api/auth/refreshToken", strings.NewReader("{}"))
  37. req.Header.Set("Content-Type", "application/json")
  38. req.Header.Set("Authorization", "Bearer garbage.token.value")
  39. rr := httptest.NewRecorder()
  40. handler.ServeHTTP(rr, req)
  41. var body response.Body
  42. require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body))
  43. assert.False(t, body.Success)
  44. assert.Equal(t, 401, body.ErrorCode,
  45. "非法 refresh token 必须 401, 而不是 500 panic 或 200; 实际 code=%d msg=%q", body.ErrorCode, body.ErrorMessage)
  46. }