开发检查点:完成项目域名权限与事务审计接线
提交 P0-07 当前开发检查点,包含项目域名事务仓储、HTTP 路由接线、生产应用依赖及测试夹具调整。
This commit is contained in:
1 parent
ef6365591b
commit
5180c7d73f
11 files changed
+395
-36
No files matched your search
@@ -15,3 +15,10 @@ type DomainRepository interface {
|
||||
Delete(ctx context.Context, id string) error
|
||||
UpdateCertificateState(ctx context.Context, id, status string, expiresAt *time.Time) error
|
||||
}
|
||||
|
||||
// ProjectDomainRepository 在项目边界内执行域名资料变更,并将成功审计与业务写入放在同一事务。
|
||||
type ProjectDomainRepository interface {
|
||||
CreateProjectDomain(context.Context, string, domain.Domain) error
|
||||
UpdateProjectDomain(context.Context, string, domain.Domain) error
|
||||
DeleteProjectDomain(context.Context, string, string) error
|
||||
}
|
||||
@@ -150,6 +150,12 @@ func projectBindingReadError(err error) error {
|
||||
// 使用事务内的当前读取并持有账户、项目和现有成员行锁,避免撤权或停用后继续写入。
|
||||
// SQLite 使用自身事务串行写入保证;遇到并发升级失败时回滚,不绕过授权重试。
|
||||
func (r *SQLProjectMemberRepository) authorizeBindingTransaction(ctx context.Context, tx *sql.Tx, actorID, projectID string) error {
|
||||
return r.authorizeProjectTransaction(ctx, tx, actorID, projectID,
|
||||
domain.PermissionCertificateRead, domain.PermissionServerRead, domain.PermissionDeploymentExecute)
|
||||
}
|
||||
|
||||
// authorizeProjectTransaction 在同一事务内锁定账户、项目和成员关系,保证判权不会在业务写入前被撤回。
|
||||
func (r *SQLProjectMemberRepository) authorizeProjectTransaction(ctx context.Context, tx *sql.Tx, actorID, projectID string, required ...domain.ProjectPermission) error {
|
||||
var status, userRole, existingProject string
|
||||
if err := tx.QueryRowContext(ctx, Rebind(r.driver,
|
||||
`SELECT status, role FROM users WHERE id = ?`+r.resourceWriteLock()), actorID).Scan(&status, &userRole); err != nil {
|
||||
@@ -171,10 +177,12 @@ func (r *SQLProjectMemberRepository) authorizeBindingTransaction(ctx context.Con
|
||||
return fmt.Errorf("读取绑定操作权限失败:%w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
permissions := map[domain.ProjectPermission]bool{
|
||||
domain.PermissionCertificateRead: false,
|
||||
domain.PermissionServerRead: false,
|
||||
domain.PermissionDeploymentExecute: false,
|
||||
permissions := make(map[domain.ProjectPermission]bool, len(required))
|
||||
for _, permission := range required {
|
||||
if !permission.Valid() {
|
||||
return ErrProjectAccessDenied
|
||||
}
|
||||
permissions[permission] = false
|
||||
}
|
||||
for rows.Next() {
|
||||
var role domain.ProjectRole
|
||||
@@ -188,8 +196,8 @@ func (r *SQLProjectMemberRepository) authorizeBindingTransaction(ctx context.Con
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, allowed := range permissions {
|
||||
if !allowed {
|
||||
for _, permission := range required {
|
||||
if !permissions[permission] {
|
||||
return ErrProjectAccessDenied
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
var ErrProjectDomainBusy = errors.New("域名存在正在执行的任务,暂不能删除")
|
||||
|
||||
var _ ProjectDomainRepository = (*SQLProjectMemberRepository)(nil)
|
||||
|
||||
func (r *SQLProjectMemberRepository) CreateProjectDomain(ctx context.Context, actorID string, item domain.Domain) error {
|
||||
if err := r.ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
item.ResourceScope = item.ResourceScope.Normalize()
|
||||
payload, err := json.Marshal(item.SANs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码域名 SAN 失败:%w", err)
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始域名创建事务失败:%w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err := r.authorizeProjectTransaction(ctx, tx, actorID, item.ProjectID, domain.PermissionCertificateManage); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, Rebind(r.driver, `INSERT INTO domains
|
||||
(id, name, certificate_type, sans_json, auto_renew, acme_environment, dns_provider, status, expires_at, created_at, updated_at, project_id, owner_id, created_by, updated_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), item.ID, item.Name, item.CertificateType, string(payload), item.AutoRenew,
|
||||
item.ACMEEnvironment, item.DNSProvider, item.Status, nullableTime(item.ExpiresAt), item.CreatedAt, item.UpdatedAt,
|
||||
item.ProjectID, item.OwnerID, item.CreatedBy, item.UpdatedBy)
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存域名失败:%w", err)
|
||||
}
|
||||
if err := writeDomainAudit(ctx, tx, r.driver, "domain.create", item.ID, item.ProjectID, actorID, "创建域名"); err != nil {
|
||||
return err
|
||||
}
|
||||
return commitProjectDomain(tx, "提交域名创建事务失败")
|
||||
}
|
||||
|
||||
func (r *SQLProjectMemberRepository) UpdateProjectDomain(ctx context.Context, actorID string, item domain.Domain) error {
|
||||
if err := r.ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
payload, err := json.Marshal(item.SANs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("编码域名 SAN 失败:%w", err)
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始域名更新事务失败:%w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var stored domain.Domain
|
||||
var certificateType string
|
||||
if err := tx.QueryRowContext(ctx, Rebind(r.driver, `SELECT id, name, certificate_type, project_id FROM domains WHERE id = ?`+r.resourceWriteLock()), item.ID).
|
||||
Scan(&stored.ID, &stored.Name, &certificateType, &stored.ProjectID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return fmt.Errorf("读取待更新域名失败:%w", err)
|
||||
}
|
||||
stored.CertificateType = domain.CertificateType(certificateType)
|
||||
if err := r.authorizeProjectTransaction(ctx, tx, actorID, stored.ProjectID, domain.PermissionCertificateManage); err != nil {
|
||||
return err
|
||||
}
|
||||
item.ProjectID = stored.ProjectID
|
||||
if err := r.validateDomainPathsInTransaction(ctx, tx, item); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, Rebind(r.driver, `UPDATE domains SET
|
||||
name = ?, certificate_type = ?, sans_json = ?, auto_renew = ?, acme_environment = ?, dns_provider = ?, updated_at = ?, updated_by = ?
|
||||
WHERE id = ? AND project_id = ?`), item.Name, item.CertificateType, string(payload), item.AutoRenew, item.ACMEEnvironment,
|
||||
item.DNSProvider, item.UpdatedAt, item.UpdatedBy, item.ID, stored.ProjectID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("更新域名失败:%w", err)
|
||||
}
|
||||
if count, err := result.RowsAffected(); err != nil || count != 1 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
if err := writeDomainAudit(ctx, tx, r.driver, "domain.update", item.ID, stored.ProjectID, actorID, "更新域名"); err != nil {
|
||||
return err
|
||||
}
|
||||
return commitProjectDomain(tx, "提交域名更新事务失败")
|
||||
}
|
||||
|
||||
func (r *SQLProjectMemberRepository) DeleteProjectDomain(ctx context.Context, actorID, domainID string) error {
|
||||
if err := r.ensureDB(); err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始域名删除事务失败:%w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var projectID string
|
||||
if err := tx.QueryRowContext(ctx, Rebind(r.driver, `SELECT project_id FROM domains WHERE id = ?`+r.resourceWriteLock()), domainID).Scan(&projectID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
return fmt.Errorf("读取待删除域名失败:%w", err)
|
||||
}
|
||||
if err := r.authorizeProjectTransaction(ctx, tx, actorID, projectID, domain.PermissionCertificateManage); err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, Rebind(r.driver, `SELECT id FROM tasks
|
||||
WHERE domain_id = ? AND task_type IN ('certificate_issue', 'certificate_validate', 'certificate_deploy', 'certificate_import', 'certificate_restore')
|
||||
AND status IN ('queued', 'running')`+r.resourceWriteLock()), domainID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("检查域名任务失败:%w", err)
|
||||
}
|
||||
busy := rows.Next()
|
||||
rows.Close()
|
||||
if busy {
|
||||
return ErrProjectDomainBusy
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, Rebind(r.driver, `DELETE FROM domain_servers WHERE domain_id = ?`), domainID); err != nil {
|
||||
return fmt.Errorf("删除域名服务器关联失败:%w", err)
|
||||
}
|
||||
result, err := tx.ExecContext(ctx, Rebind(r.driver, `DELETE FROM domains WHERE id = ? AND project_id = ?`), domainID, projectID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除域名失败:%w", err)
|
||||
}
|
||||
if count, err := result.RowsAffected(); err != nil || count != 1 {
|
||||
return sql.ErrNoRows
|
||||
}
|
||||
if err := writeDomainAudit(ctx, tx, r.driver, "domain.delete", domainID, projectID, actorID, "删除域名"); err != nil {
|
||||
return err
|
||||
}
|
||||
return commitProjectDomain(tx, "提交域名删除事务失败")
|
||||
}
|
||||
|
||||
func (r *SQLProjectMemberRepository) validateDomainPathsInTransaction(ctx context.Context, tx *sql.Tx, item domain.Domain) error {
|
||||
rows, err := tx.QueryContext(ctx, Rebind(r.driver, serverSelectQualified+` INNER JOIN domain_servers ds ON ds.server_id = servers.id WHERE ds.domain_id = ? ORDER BY servers.id`+r.resourceWriteLock()), item.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("查询域名服务器路径失败:%w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
server, err := scanServer(rows)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if server.ProjectID != item.ProjectID {
|
||||
return ErrProjectAccessDenied
|
||||
}
|
||||
if err := validateServerDomainPaths(ctx, tx, r.driver, server, &item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func writeDomainAudit(ctx context.Context, tx *sql.Tx, driver, action, domainID, projectID, actorID, message string) error {
|
||||
result, err := tx.ExecContext(ctx, Rebind(driver, `INSERT INTO audit_logs
|
||||
(action, resource_type, resource_id, status, message, created_at, scope_type, project_id, task_id, operator_id)
|
||||
VALUES (?, 'domain', ?, 'success', ?, ?, 'project', ?, '', ?)`), action, domainID, message, time.Now().UTC(), projectID, actorID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("写入域名操作审计失败:%w", err)
|
||||
}
|
||||
if count, err := result.RowsAffected(); err != nil || count != 1 {
|
||||
return errors.New("域名操作审计未写入,业务变更已回滚")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func commitProjectDomain(tx *sql.Tx, message string) error {
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("%s:%w", message, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/config"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/database"
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestProjectDomainRepositorySQLite(t *testing.T) {
|
||||
cfg := config.Default(t.TempDir()).Database
|
||||
db, err := database.Open(t.Context(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
if err := database.Migrate(t.Context(), db.DB, cfg.Driver); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, user := range []struct{ id, role string }{
|
||||
{"root-domain", UserRoleSuperAdmin}, {"domain-manager", UserRoleUser}, {"domain-outsider", UserRoleUser},
|
||||
} {
|
||||
if _, err := db.DB.ExecContext(t.Context(), Rebind(cfg.Driver, `INSERT INTO users
|
||||
(id, username, password_hash, role, status) VALUES (?, ?, 'test-only-no-login', ?, 'active')`), user.id, user.id, user.role); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
projects := NewSQLProjectRepository(db.DB, cfg.Driver)
|
||||
if err := projects.CreateProject(t.Context(), domain.Project{ID: "domain-project", Name: "域名项目"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writer := NewSQLProjectMemberRepository(db.DB, cfg.Driver)
|
||||
if err := writer.GrantProjectRole(t.Context(), "root-domain", "domain-project", "domain-manager", domain.ProjectRoleCertificateAdmin); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item, err := domain.NewDomain("managed.example.test", domain.CertificateSingle, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item.ID = "managed-domain"
|
||||
item.ProjectID = "domain-project"
|
||||
if err := writer.CreateProjectDomain(t.Context(), "domain-manager", item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, err := NewSQLDomainRepository(db.DB, cfg.Driver).GetByID(t.Context(), item.ID)
|
||||
if err != nil || stored.ProjectID != item.ProjectID {
|
||||
t.Fatalf("项目域名未按真实归属保存:%+v,%v", stored, err)
|
||||
}
|
||||
if err := writer.CreateProjectDomain(t.Context(), "domain-outsider", item); !errors.Is(err, ErrProjectAccessDenied) {
|
||||
t.Fatalf("越权创建应拒绝:%v", err)
|
||||
}
|
||||
item.Name = "updated.example.test"
|
||||
if err := writer.UpdateProjectDomain(t.Context(), "domain-manager", item); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewSQLDomainRepository(db.DB, cfg.Driver).GetByID(t.Context(), item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskRepo := NewSQLTaskRepository(db.DB, cfg.Driver)
|
||||
if err := taskRepo.CreateTask(t.Context(), Task{HistoryScope: HistoryScope{ProjectID: item.ProjectID, ScopeType: ScopeProject}, ID: "domain-active-task", DomainID: item.ID, TaskType: "certificate_issue", Status: "running"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.DeleteProjectDomain(t.Context(), "domain-manager", item.ID); !errors.Is(err, ErrProjectDomainBusy) {
|
||||
t.Fatalf("在途任务下删除应拒绝:%v", err)
|
||||
}
|
||||
if _, err := db.DB.ExecContext(context.Background(), Rebind(cfg.Driver, `UPDATE tasks SET status = 'success' WHERE id = ?`), "domain-active-task"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writer.DeleteProjectDomain(t.Context(), "domain-manager", item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err := db.DB.QueryRowContext(t.Context(), Rebind(cfg.Driver, `SELECT COUNT(*) FROM audit_logs WHERE resource_id = ? AND status = 'success'`), item.ID).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 3 {
|
||||
t.Fatalf("域名成功操作审计数量错误:%d", count)
|
||||
}
|
||||
if _, err := NewSQLDomainRepository(db.DB, cfg.Driver).GetByID(t.Context(), item.ID); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("删除后域名应不存在:%v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user