保存证书校验后台任务及独立结果的修复前基线
校验结果事务持久化、三库迁移及前端详情接线已实现,完整回归仍在执行。审查发现前端校验幂等键包含路径分隔符,下一批补回归并修复;本提交不是正式发布或生产验收结论。
This commit is contained in:
1 parent
fce5a84dd4
commit
24a9683c43
27 files changed
+803
-23
No files matched your search
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
|
||||
)
|
||||
|
||||
@@ -21,6 +22,7 @@ type TaskCompletion struct {
|
||||
StartedAt *time.Time
|
||||
FinishedAt time.Time
|
||||
Report *deployment.Report
|
||||
Validation *certificate.ValidationResult
|
||||
AuditAction string
|
||||
Retry bool
|
||||
WithoutAttempt bool
|
||||
@@ -41,7 +43,7 @@ func (r *SQLTaskRepository) FinishTaskAttempt(ctx context.Context, completion Ta
|
||||
default:
|
||||
return errors.New("任务终态无效")
|
||||
}
|
||||
if completion.WithoutAttempt && (completion.AttemptID != "" || completion.Report != nil || completion.Retry || (completion.Status != "failed" && completion.Status != "cancelled")) {
|
||||
if completion.WithoutAttempt && (completion.AttemptID != "" || completion.Report != nil || completion.Validation != nil || completion.Retry || (completion.Status != "failed" && completion.Status != "cancelled")) {
|
||||
return errors.New("无活动尝试的收尾参数无效")
|
||||
}
|
||||
if completion.Retry && (completion.Status != "failed" || completion.AuditAction != "") {
|
||||
@@ -82,6 +84,11 @@ func (r *SQLTaskRepository) FinishTaskAttempt(ctx context.Context, completion Ta
|
||||
return err
|
||||
}
|
||||
}
|
||||
if completion.Validation != nil {
|
||||
if err := r.recordCompletionValidation(ctx, tx, completion); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if completion.AuditAction != "" {
|
||||
if err := r.recordCompletionAudit(ctx, tx, completion); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
// TaskValidationResult 仅保存已校验的公开元数据,不包含证书路径和私钥。
|
||||
type TaskValidationResult struct {
|
||||
TaskID string `json:"task_id"`
|
||||
AttemptID string `json:"attempt_id"`
|
||||
AttemptNumber int `json:"attempt_number"`
|
||||
Validation certificate.ValidationResult `json:"validation"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type TaskValidationReader interface {
|
||||
ListVisibleTaskValidations(context.Context, string, string) ([]TaskValidationResult, error)
|
||||
}
|
||||
|
||||
func (r *SQLTaskRepository) recordCompletionValidation(ctx context.Context, tx *sql.Tx, completion TaskCompletion) error {
|
||||
if completion.Report != nil || completion.Status != "success" || completion.Retry {
|
||||
return errors.New("校验元数据只能随独立校验任务成功提交")
|
||||
}
|
||||
var attemptNumber int
|
||||
var taskType string
|
||||
if err := tx.QueryRowContext(ctx, r.query(`SELECT attempts.attempt_number, tasks.task_type
|
||||
FROM task_attempts attempts JOIN tasks ON tasks.id = attempts.task_id
|
||||
WHERE attempts.id = ? AND tasks.id = ?`), completion.AttemptID, completion.TaskID).Scan(&attemptNumber, &taskType); err != nil {
|
||||
return fmt.Errorf("读取校验结果所属任务失败:%w", err)
|
||||
}
|
||||
if taskType != "certificate_validate" {
|
||||
return errors.New("校验结果不能保存到其他类型任务")
|
||||
}
|
||||
content, err := json.Marshal(completion.Validation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("序列化校验结果失败:%w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, r.query(`INSERT INTO task_validation_results
|
||||
(task_id, attempt_id, attempt_number, validation_json, created_at) VALUES (?, ?, ?, ?, ?)`),
|
||||
completion.TaskID, completion.AttemptID, attemptNumber, string(content), completion.FinishedAt.UTC()); err != nil {
|
||||
return fmt.Errorf("保存校验结果失败:%w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *SQLTaskRepository) ListVisibleTaskValidations(ctx context.Context, actorID, taskID string) ([]TaskValidationResult, error) {
|
||||
if r == nil || r.db == nil {
|
||||
return nil, errors.New("数据库连接不能为空")
|
||||
}
|
||||
predicate, args := taskVisibilityPredicate("tasks", domain.PermissionTaskRead)
|
||||
args[0] = strings.TrimSpace(actorID)
|
||||
args = append(args, strings.TrimSpace(taskID))
|
||||
rows, err := r.db.QueryContext(ctx, r.query(`SELECT results.task_id, results.attempt_id, results.attempt_number,
|
||||
results.validation_json, results.created_at FROM task_validation_results results
|
||||
JOIN tasks ON tasks.id = results.task_id WHERE `+predicate+` AND results.task_id = ? ORDER BY results.attempt_number`), args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询任务校验结果失败:%w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]TaskValidationResult, 0)
|
||||
for rows.Next() {
|
||||
var item TaskValidationResult
|
||||
var content string
|
||||
if err := rows.Scan(&item.TaskID, &item.AttemptID, &item.AttemptNumber, &content, &item.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("读取任务校验结果失败:%w", err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(content), &item.Validation); err != nil {
|
||||
return nil, fmt.Errorf("解析任务校验结果失败:%w", err)
|
||||
}
|
||||
item.CreatedAt = item.CreatedAt.UTC()
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("读取任务校验结果列表失败:%w", err)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
|
||||
)
|
||||
|
||||
func TestTaskValidationPersistsAndEnforcesVisibility(t *testing.T) {
|
||||
repo, db := newTaskRepositoryTest(t)
|
||||
defer db.Close()
|
||||
completion := seedTaskCompletion(t, repo)
|
||||
if _, err := db.ExecContext(t.Context(), `UPDATE tasks SET task_type = 'certificate_validate' WHERE id = ?`, completion.TaskID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.ExecContext(t.Context(), `INSERT INTO users (id, username, password_hash, role, status)
|
||||
VALUES ('reader', 'reader', 'test-only', 'user', 'active'), ('outsider', 'outsider', 'test-only', 'user', 'active')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.ExecContext(t.Context(), `INSERT INTO project_members (project_id, user_id, role) VALUES ('default', 'reader', 'read_only')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
completion.Stage = "certificate_validate"
|
||||
completion.AuditAction = "certificate_validate"
|
||||
completion.Validation = &certificate.ValidationResult{
|
||||
Domains: []string{"example.test", "*.example.test"}, SerialNumber: "1234",
|
||||
FingerprintSHA256: "test-fingerprint", NotBefore: time.Now().UTC().Truncate(time.Second),
|
||||
NotAfter: time.Now().UTC().Add(24 * time.Hour).Truncate(time.Second), ChainLength: 2,
|
||||
}
|
||||
if err := repo.FinishTaskAttempt(t.Context(), completion); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader := NewSQLTaskRepository(db)
|
||||
items, err := reader.ListVisibleTaskValidations(t.Context(), "reader", completion.TaskID)
|
||||
if err != nil || len(items) != 1 || items[0].AttemptID != completion.AttemptID || items[0].AttemptNumber != 1 {
|
||||
t.Fatalf("重建仓储后校验结果丢失:%+v %v", items, err)
|
||||
}
|
||||
got := items[0].Validation
|
||||
if len(got.Domains) != 2 || got.SerialNumber != "1234" || got.FingerprintSHA256 != "test-fingerprint" || got.ChainLength != 2 || !got.NotAfter.Equal(completion.Validation.NotAfter) {
|
||||
t.Fatalf("校验详情不完整:%+v", got)
|
||||
}
|
||||
for _, actor := range []string{"outsider", "", "missing"} {
|
||||
items, err := reader.ListVisibleTaskValidations(t.Context(), actor, completion.TaskID)
|
||||
if err != nil || len(items) != 0 {
|
||||
t.Fatalf("无权限账户读取校验结果:%s %+v %v", actor, items, err)
|
||||
}
|
||||
}
|
||||
if _, err := db.ExecContext(t.Context(), `DELETE FROM project_members WHERE user_id = 'reader'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, err = reader.ListVisibleTaskValidations(t.Context(), "reader", completion.TaskID)
|
||||
if err != nil || len(items) != 0 {
|
||||
t.Fatalf("撤权后仍可读取校验结果:%+v %v", items, err)
|
||||
}
|
||||
reports, err := repo.ListTaskDeploymentReports(t.Context(), completion.TaskID)
|
||||
if err != nil || len(reports) != 0 {
|
||||
t.Fatalf("校验结果被伪装成部署报告:%+v %v", reports, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskValidationFailureRollsBackAllRecords(t *testing.T) {
|
||||
for _, scenario := range []string{"result_insert", "audit_insert", "wrong_task_type", "mixed_report", "failed_status", "foreign_attempt"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
repo, db := newTaskRepositoryTest(t)
|
||||
defer db.Close()
|
||||
completion := seedTaskCompletion(t, repo)
|
||||
completion.Validation = &certificate.ValidationResult{Domains: []string{"example.test"}}
|
||||
completion.AuditAction = "certificate_validate"
|
||||
if scenario != "wrong_task_type" {
|
||||
if _, err := db.ExecContext(t.Context(), `UPDATE tasks SET task_type = 'certificate_validate' WHERE id = ?`, completion.TaskID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
switch scenario {
|
||||
case "result_insert", "audit_insert":
|
||||
table := "task_validation_results"
|
||||
if scenario == "audit_insert" {
|
||||
table = "audit_logs"
|
||||
}
|
||||
if _, err := db.ExecContext(t.Context(), `CREATE TRIGGER reject_validation BEFORE INSERT ON `+table+` BEGIN SELECT RAISE(ABORT, 'injected failure'); END`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "mixed_report":
|
||||
completion.Report = completionTestReport()
|
||||
case "failed_status":
|
||||
completion.Status = "failed"
|
||||
case "foreign_attempt":
|
||||
completion.AttemptID = "missing-attempt"
|
||||
}
|
||||
if err := repo.FinishTaskAttempt(t.Context(), completion); err == nil {
|
||||
t.Fatal("无效校验结果或写入失败必须回滚终态")
|
||||
}
|
||||
task, err := repo.GetTask(t.Context(), completion.TaskID)
|
||||
if err != nil || task.Status != "running" || task.FinishedAt != nil {
|
||||
t.Fatalf("失败后任务被部分提交:%+v %v", task, err)
|
||||
}
|
||||
attempts, err := repo.ListAttempts(t.Context(), completion.TaskID)
|
||||
if err != nil || len(attempts) != 1 || attempts[0].Status != "running" || attempts[0].FinishedAt != nil {
|
||||
t.Fatalf("失败后尝试被部分提交:%+v %v", attempts, err)
|
||||
}
|
||||
for _, table := range []string{"task_validation_results", "task_deployment_reports", "task_deployment_results", "audit_logs"} {
|
||||
var count int
|
||||
if err := db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM `+table+` WHERE task_id = ?`, completion.TaskID).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("失败后出现部分记录:%s %d %v", table, count, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user