fix: 修复代码审查中发现的P0/P1/P2问题
修复内容: 1. P0-01/P0-02: IAM Handler硬编码userID=1问题 - getUserIDFromContext现在从认证中间件的context获取真实userID - 添加middleware.GetOperatorID公开函数 - CheckScope方法添加未认证检查 2. P1-01: 审计服务幂等竞态条件 - 重构锁保护范围,整个检查和插入过程在锁保护下 - 使用defer确保锁正确释放 3. P1-02: 幂等中间件响应码硬编码 - 添加statusCapturingResponseWriter包装器 - 捕获实际的状态码和响应体用于幂等记录 4. P2-01: 事件ID时间戳冲突 - generateEventID改用UUID替代时间戳 5. P2-02: ListScopes硬编码 - 使用model.PredefinedScopes替代硬编码列表 所有supply-api测试通过
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"lijiaoqiao/supply-api/internal/iam/service"
|
||||
"lijiaoqiao/supply-api/internal/middleware"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
@@ -695,6 +696,8 @@ func TestIAMHandler_CheckScope_HasScope(t *testing.T) {
|
||||
})
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/v1/iam/check-scope?scope=platform:read", nil)
|
||||
ctx := middleware.WithOperatorID(context.Background(), 1)
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
// act
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -728,6 +731,8 @@ func TestIAMHandler_CheckScope_NoScope(t *testing.T) {
|
||||
})
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/v1/iam/check-scope?scope=platform:write", nil)
|
||||
ctx := middleware.WithOperatorID(context.Background(), 1)
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
// act
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -1153,6 +1158,8 @@ func TestIAMHandler_handleCheckScope_GET(t *testing.T) {
|
||||
handler := NewIAMHandler(svc)
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/v1/iam/check-scope?scope=platform:read", nil)
|
||||
ctx := middleware.WithOperatorID(context.Background(), 1)
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
// act
|
||||
rec := httptest.NewRecorder()
|
||||
@@ -1227,12 +1234,15 @@ func TestRequireScope(t *testing.T) {
|
||||
// getUserIDFromContext 测试
|
||||
|
||||
func TestGetUserIDFromContext(t *testing.T) {
|
||||
// act
|
||||
// act - 没有设置时返回0
|
||||
ctx := context.Background()
|
||||
userID := getUserIDFromContext(ctx)
|
||||
assert.Equal(t, int64(0), userID)
|
||||
|
||||
// assert - 默认返回1
|
||||
assert.Equal(t, int64(1), userID)
|
||||
// act - 设置operatorID时返回正确的值
|
||||
ctx = middleware.WithOperatorID(context.Background(), 123)
|
||||
userID = getUserIDFromContext(ctx)
|
||||
assert.Equal(t, int64(123), userID)
|
||||
}
|
||||
|
||||
// toRoleResponse 测试
|
||||
|
||||
Reference in New Issue
Block a user