完善任务审计范围快照与身份关联并同步整改进度
新增三库第13号迁移和历史范围回填,保留已删除资源的任务与审计。补充仓储、调用链、身份来源及迁移失败重试回归,同步任务清单、支持矩阵和运维边界。项目成员授权与生产验收仍待完成。
This commit is contained in:
1 parent
5237e8d810
commit
0ccdb14b26
34 files changed
+989
-48
No files matched your search
@@ -79,7 +79,7 @@ func (s *Server) authLogin(c *gin.Context) {
|
||||
account, userID, passwordHash, err := s.authenticateAccount(c.Request.Context(), request, cfg)
|
||||
if err != nil {
|
||||
s.recordLoginFailure(key)
|
||||
s.recordAuthAudit(c, "登录失败", "failed", "登录凭据校验失败")
|
||||
s.recordAuthAudit(c, "", "登录失败", "failed", "登录凭据校验失败")
|
||||
s.writeError(c, http.StatusUnauthorized, "账号或密码错误", nil)
|
||||
return
|
||||
}
|
||||
@@ -120,7 +120,7 @@ func (s *Server) authLogin(c *gin.Context) {
|
||||
}
|
||||
s.authMu.Unlock()
|
||||
s.setAuthCookie(c, token, expiresAt)
|
||||
s.recordAuthAudit(c, "登录成功", "success", "用户登录成功")
|
||||
s.recordAuthAudit(c, userID, "登录成功", "success", "用户登录成功")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authenticated": true,
|
||||
"account": account.Username,
|
||||
@@ -339,12 +339,13 @@ func (s *Server) clearLoginFailures(key string) {
|
||||
s.loginMu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) recordAuthAudit(c *gin.Context, action, status, message string) {
|
||||
func (s *Server) recordAuthAudit(c *gin.Context, operatorID, action, status, message string) {
|
||||
if s.audit == nil {
|
||||
return
|
||||
}
|
||||
if err := s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: action, ResourceType: "auth", ResourceID: "login", Status: status, Message: message,
|
||||
OperatorID: operatorID,
|
||||
Action: action, ResourceType: "auth", ResourceID: "login", Status: status, Message: message,
|
||||
}); err != nil && s.logger != nil {
|
||||
s.logger.Warn("保存登录审计日志失败", "error", err)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ func (s *Server) restoreCertificateVersion(c *gin.Context) {
|
||||
}
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "failed",
|
||||
OperatorID: s.currentOperatorID(c),
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "failed",
|
||||
Message: "恢复证书历史版本失败",
|
||||
})
|
||||
}
|
||||
@@ -32,7 +33,8 @@ func (s *Server) restoreCertificateVersion(c *gin.Context) {
|
||||
}
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "success",
|
||||
OperatorID: s.currentOperatorID(c),
|
||||
Action: "certificate_version_restore", ResourceType: "certificate", ResourceID: c.Param("id"), Status: "success",
|
||||
Message: "已恢复证书历史版本:" + version,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
func TestHistoryScopeLoginAuditUsesVerifiedAccount(t *testing.T) {
|
||||
server, _, audit, closeDB := newTaskAPITestServer(t, nil)
|
||||
defer closeDB()
|
||||
server.config.Admin.Username = "owner"
|
||||
server.config.Admin.PasswordHash = httpUserPasswordHash(t, "OwnerPass123")
|
||||
otherCookie := httpUserSessionCookie(server, "other-actor", repository.UserRoleAdmin)
|
||||
for _, tc := range []struct {
|
||||
name, password, actor string
|
||||
cookie *http.Cookie
|
||||
status int
|
||||
}{
|
||||
{"fresh-login", "OwnerPass123", "primary-super-admin", nil, http.StatusOK},
|
||||
{"different-session", "OwnerPass123", "primary-super-admin", otherCookie, http.StatusOK},
|
||||
{"failed-login", "Incorrect123", "", otherCookie, http.StatusUnauthorized},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"owner","password":"`+tc.password+`"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if tc.cookie != nil {
|
||||
request.AddCookie(tc.cookie)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != tc.status {
|
||||
t.Fatalf("登录响应错误:%d,%s", response.Code, response.Body.String())
|
||||
}
|
||||
logs, err := audit.ListAuditLogs(t.Context(), 1)
|
||||
if err != nil || len(logs) != 1 {
|
||||
t.Fatalf("登录审计缺失:%+v,%v", logs, err)
|
||||
}
|
||||
if logs[0].OperatorID != tc.actor || logs[0].ScopeType != repository.ScopeSystem || logs[0].ProjectID != "" {
|
||||
t.Fatalf("登录审计误用旧会话或丢失已验证身份:%+v", logs[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryScopeUserAuditSurvivesSessionInvalidation(t *testing.T) {
|
||||
server, _, audit, closeDB := newTaskAPITestServer(t, nil)
|
||||
defer closeDB()
|
||||
cookie := httpUserSessionCookie(server, "self-admin", repository.UserRoleSuperAdmin)
|
||||
response := serveUserRequest(server, cookie, http.MethodPut, "/api/v1/users/self-admin",
|
||||
`{"username":"self-admin","email":"self-admin@example.test","password":"Updated123","role":"super_admin","status":"active"}`)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("更新自身账户失败:%d,%s", response.Code, response.Body.String())
|
||||
}
|
||||
logs, err := audit.ListAuditLogs(t.Context(), 1)
|
||||
if err != nil || len(logs) != 1 || logs[0].OperatorID != "self-admin" || logs[0].ScopeType != repository.ScopeSystem {
|
||||
t.Fatalf("会话失效后丢失实际操作者:%+v,%v", logs, err)
|
||||
}
|
||||
after := serveUserRequest(server, cookie, http.MethodGet, "/api/v1/users", "")
|
||||
if after.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("审计身份快照不得恢复失效会话:%d", after.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoryScopePasswordAuditSurvivesSessionInvalidation(t *testing.T) {
|
||||
server, _, audit, closeDB := newTaskAPITestServer(t, nil)
|
||||
defer closeDB()
|
||||
cookie := httpUserSessionCookie(server, "password-user", repository.UserRoleUser)
|
||||
response := performChangePasswordRequest(t, server, cookie,
|
||||
`{"current_password":"FixturePass123","new_password":"Updated123","confirm_password":"Updated123"}`)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("修改密码失败:%d,%s", response.Code, response.Body.String())
|
||||
}
|
||||
logs, err := audit.ListAuditLogs(t.Context(), 1)
|
||||
if err != nil || len(logs) != 1 || logs[0].OperatorID != "password-user" || logs[0].ScopeType != repository.ScopeSystem {
|
||||
t.Fatalf("改密后丢失审计操作者:%+v,%v", logs, err)
|
||||
}
|
||||
if after := authSessionRequest(server, cookie); after.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("改密审计不得恢复旧会话:%d", after.Code)
|
||||
}
|
||||
}
|
||||
@@ -137,7 +137,7 @@ func (s *Server) changeDatabaseUserPassword(c *gin.Context, session authSession,
|
||||
func (s *Server) finishPasswordChange(c *gin.Context, userID, message string) {
|
||||
s.invalidateUserSessions(userID)
|
||||
s.clearAuthCookie(c)
|
||||
s.recordAuthAudit(c, "修改密码", "success", "当前登录账号修改密码成功")
|
||||
s.recordAuthAudit(c, userID, "修改密码", "success", "当前登录账号修改密码成功")
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"authenticated": false,
|
||||
"requires_login": true,
|
||||
|
||||
@@ -6,6 +6,13 @@ import (
|
||||
)
|
||||
|
||||
// 归属由服务端会话填写,不能从请求体接受操作者或项目授权声明。
|
||||
func (s *Server) currentOperatorID(c *gin.Context) string {
|
||||
if session, ok := s.currentAuthSession(c); ok {
|
||||
return session.UserID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) newResourceScope(c *gin.Context) domain.ResourceScope {
|
||||
scope := domain.ResourceScope{ProjectID: domain.DefaultProjectID}
|
||||
if session, ok := s.currentAuthSession(c); ok {
|
||||
|
||||
@@ -25,7 +25,8 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
domainID := strings.TrimSpace(c.Param("id"))
|
||||
if _, err := s.repository.GetByID(c.Request.Context(), domainID); err != nil {
|
||||
resource, err := s.repository.GetByID(c.Request.Context(), domainID)
|
||||
if err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "域名不存在", err)
|
||||
return
|
||||
@@ -66,7 +67,9 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
task := repository.Task{
|
||||
ID: domain.NewID(), DomainID: domainID, TaskType: "certificate_issue", Status: "queued", Stage: "queued",
|
||||
HistoryScope: repository.HistoryScope{ScopeType: repository.ScopeProject, ProjectID: resource.ResourceScope.Normalize().ProjectID},
|
||||
OperatorID: s.currentOperatorID(c),
|
||||
ID: domain.NewID(), DomainID: domainID, TaskType: "certificate_issue", Status: "queued", Stage: "queued",
|
||||
Message: "等待执行证书申请", IdempotencyKey: idempotencyKey, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := s.tasks.CreateTask(c.Request.Context(), task); err != nil {
|
||||
@@ -91,6 +94,7 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
_ = s.tasks.FinishAttempt(context.Background(), attempt.ID, "failed", failureMessage, &finished)
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(context.Background(), repository.AuditLog{
|
||||
TaskID: task.ID, OperatorID: task.OperatorID,
|
||||
Action: "certificate_issue", ResourceType: "domain", ResourceID: domainID,
|
||||
Status: "error", Message: failureMessage,
|
||||
})
|
||||
@@ -144,6 +148,7 @@ func (s *Server) issueDomainAsTask(c *gin.Context) {
|
||||
auditStatus = "error"
|
||||
}
|
||||
_ = s.audit.CreateAuditLog(context.Background(), repository.AuditLog{
|
||||
TaskID: task.ID, OperatorID: task.OperatorID,
|
||||
Action: "certificate_issue", ResourceType: "domain", ResourceID: domainID, Status: auditStatus, Message: message,
|
||||
})
|
||||
}
|
||||
@@ -226,6 +231,7 @@ func (s *Server) cancelTask(c *gin.Context) {
|
||||
item.UpdatedAt = finished
|
||||
if s.audit != nil {
|
||||
_ = s.audit.CreateAuditLog(context.Background(), repository.AuditLog{
|
||||
TaskID: taskID, OperatorID: s.currentOperatorID(c),
|
||||
Action: "task_cancel", ResourceType: "task", ResourceID: taskID, Status: "success", Message: item.Message,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ func newTaskAPITestServer(t *testing.T, issue func(context.Context, string) (cer
|
||||
IssueCertificate: issue,
|
||||
Tasks: taskRepo,
|
||||
Audit: auditRepo,
|
||||
Users: repository.NewSQLUserRepository(db.DB, cfg.Database.Driver),
|
||||
})
|
||||
return server, taskRepo, auditRepo, func() { _ = db.Close() }
|
||||
}
|
||||
@@ -74,6 +75,13 @@ func TestTaskAPIRecordsSuccessfulIssueAndAudit(t *testing.T) {
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
t.Fatalf("审计日志记录错误:%+v %v", logs, err)
|
||||
}
|
||||
wantScope := repository.HistoryScope{ScopeType: repository.ScopeProject, ProjectID: domain.DefaultProjectID}
|
||||
if items[0].HistoryScope != wantScope || attempts[0].HistoryScope != wantScope || logs[0].HistoryScope != wantScope {
|
||||
t.Fatalf("请求任务、尝试与审计范围不一致:%+v %+v %+v", items[0], attempts[0], logs[0])
|
||||
}
|
||||
if items[0].OperatorID != "test-admin" || logs[0].OperatorID != "test-admin" || logs[0].TaskID != items[0].ID {
|
||||
t.Fatalf("服务端会话操作者或审计任务关联缺失:%+v %+v", items[0], logs[0])
|
||||
}
|
||||
|
||||
list := httptest.NewRecorder()
|
||||
serveAdminHTTP(server, list, httptest.NewRequest(http.MethodGet, "/api/v1/tasks?limit=10", nil))
|
||||
@@ -215,7 +223,7 @@ func TestTaskAPICannotCancelManagementTaskWithoutExecutionControl(t *testing.T)
|
||||
|
||||
func TestTaskAPICanCancelRunningIssue(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
server, taskRepo, _, closeDB := newTaskAPITestServer(t, func(ctx context.Context, id string) (certificate.IssueResult, deployment.Report, error) {
|
||||
server, taskRepo, auditRepo, closeDB := newTaskAPITestServer(t, func(ctx context.Context, id string) (certificate.IssueResult, deployment.Report, error) {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
return certificate.IssueResult{DomainID: id}, deployment.Report{}, ctx.Err()
|
||||
@@ -254,6 +262,15 @@ func TestTaskAPICanCancelRunningIssue(t *testing.T) {
|
||||
if err != nil || item.Status != "cancelled" {
|
||||
t.Fatalf("任务取消状态没有持久化:%+v %v", item, err)
|
||||
}
|
||||
logs, err := auditRepo.ListAuditLogs(t.Context(), 10)
|
||||
if err != nil || len(logs) != 2 {
|
||||
t.Fatalf("取消和申请收尾审计缺失:%+v,%v", logs, err)
|
||||
}
|
||||
for _, entry := range logs {
|
||||
if entry.TaskID != item.ID || entry.OperatorID != "test-admin" || entry.HistoryScope != item.HistoryScope {
|
||||
t.Fatalf("取消审计关联错误:%+v", entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskAPIReplaysIdempotentIssue(t *testing.T) {
|
||||
@@ -362,12 +379,12 @@ func TestAuditLogResponseUsesDashboardFieldNames(t *testing.T) {
|
||||
}
|
||||
var previousID int64
|
||||
for i, item := range payload.Items {
|
||||
for _, field := range []string{"id", "action", "resource_type", "resource_id", "status", "message", "created_at"} {
|
||||
for _, field := range []string{"id", "action", "resource_type", "resource_id", "status", "message", "created_at", "scope_type", "project_id", "task_id", "operator_id"} {
|
||||
if _, ok := item[field]; !ok {
|
||||
t.Fatal(field, response.Body.String())
|
||||
}
|
||||
}
|
||||
if len(item) != 7 {
|
||||
if len(item) != 11 {
|
||||
t.Fatal(response.Body.String())
|
||||
}
|
||||
var id int64
|
||||
@@ -377,6 +394,7 @@ func TestAuditLogResponseUsesDashboardFieldNames(t *testing.T) {
|
||||
previousID = id
|
||||
for field, expected := range map[string]string{
|
||||
"action": "login", "resource_type": "auth", "resource_id": "admin",
|
||||
"scope_type": "system", "project_id": "", "task_id": "", "operator_id": "",
|
||||
"status": []string{"error", "success"}[i], "message": "login", "created_at": createdAt.Format(time.RFC3339),
|
||||
} {
|
||||
var actual string
|
||||
|
||||
@@ -123,7 +123,7 @@ func (s *Server) createUser(c *gin.Context) {
|
||||
s.writeError(c, userErrorStatus(err), "创建用户失败", err)
|
||||
return
|
||||
}
|
||||
s.recordUserAudit(c, "创建用户", "success", item.ID)
|
||||
s.recordUserAudit(c, s.currentOperatorID(c), "创建用户", "success", item.ID)
|
||||
c.JSON(http.StatusCreated, item)
|
||||
}
|
||||
|
||||
@@ -183,12 +183,14 @@ func (s *Server) updateUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
// 更新自身账户会使原会话失效,审计身份必须在写入前从已验证会话读取。
|
||||
operatorID := s.currentOperatorID(c)
|
||||
if err := s.users.UpdateUser(c.Request.Context(), item); err != nil {
|
||||
s.writeError(c, userErrorStatus(err), "更新用户失败", err)
|
||||
return
|
||||
}
|
||||
s.invalidateUserSessions(id)
|
||||
s.recordUserAudit(c, "更新用户", "success", id)
|
||||
s.recordUserAudit(c, operatorID, "更新用户", "success", id)
|
||||
c.JSON(http.StatusOK, item)
|
||||
}
|
||||
|
||||
@@ -222,6 +224,7 @@ func (s *Server) deleteUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
}
|
||||
operatorID := s.currentOperatorID(c)
|
||||
if err := s.users.DeleteUser(c.Request.Context(), id); err != nil {
|
||||
if errors.Is(err, repository.ErrSuperAdminProtected) {
|
||||
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||
@@ -235,7 +238,7 @@ func (s *Server) deleteUser(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
s.invalidateUserSessions(id)
|
||||
s.recordUserAudit(c, "删除用户", "success", id)
|
||||
s.recordUserAudit(c, operatorID, "删除用户", "success", id)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -286,12 +289,13 @@ func userFromRequest(request userRequest, id string) (repository.User, error) {
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (s *Server) recordUserAudit(c *gin.Context, action, status, id string) {
|
||||
func (s *Server) recordUserAudit(c *gin.Context, operatorID, action, status, id string) {
|
||||
if s.audit == nil {
|
||||
return
|
||||
}
|
||||
if err := s.audit.CreateAuditLog(c.Request.Context(), repository.AuditLog{
|
||||
Action: action, ResourceType: "user", ResourceID: id, Status: status, Message: action,
|
||||
OperatorID: operatorID,
|
||||
Action: action, ResourceType: "user", ResourceID: id, Status: status, Message: action,
|
||||
}); err != nil && s.logger != nil {
|
||||
s.logger.Warn("保存用户审计日志失败", "error", err)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user