开发检查点:完成项目域名权限与事务审计接线
提交 P0-07 当前开发检查点,包含项目域名事务仓储、HTTP 路由接线、生产应用依赖及测试夹具调整。
This commit is contained in:
1 parent
ef6365591b
commit
5180c7d73f
11 files changed
+395
-36
No files matched your search
@@ -194,7 +194,7 @@ func TestAliyunDomainAPIRejectsProtectedSANWithoutSideEffects(t *testing.T) {
|
||||
checker := &fakeAliyunScopeChecker{allowedZones: []string{"example.com"}}
|
||||
repo := &stubDomainRepository{}
|
||||
server := New(Dependencies{
|
||||
Config: cfg, Repository: repo, Secrets: store, AliyunChecker: checker,
|
||||
Config: cfg, Repository: repo, ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo}, Secrets: store, AliyunChecker: checker,
|
||||
})
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/domains", strings.NewReader(`{"name":"example.com","certificate_type":"san","sans":["pcux.cn"]}`))
|
||||
|
||||
@@ -24,8 +24,13 @@ func TestDomainResourceScopeAPI(t *testing.T) {
|
||||
if err := database.Migrate(t.Context(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, userID := range []string{"creator", "editor"} {
|
||||
if _, err := db.DB.ExecContext(t.Context(), `INSERT INTO users (id, username, password_hash, role, status) VALUES (?, ?, 'test-only-no-login', 'super_admin', 'active')`, userID, userID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
repo := repository.NewSQLDomainRepository(db.DB)
|
||||
server := New(Dependencies{Config: cfg, Repository: repo})
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectDomains: repository.NewSQLProjectMemberRepository(db.DB)})
|
||||
request := func(method, path, body, user string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
@@ -118,7 +118,7 @@ func TestHTTPServerUsesProductionTimeoutsAndTLSMinimum(t *testing.T) {
|
||||
func TestDomainAPIValidatesSANAndHidesInternalErrors(t *testing.T) {
|
||||
cfg := readyTestConfig(t.TempDir())
|
||||
repo := &stubDomainRepository{}
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectResources: projectResourceReaderStub{domains: repo}})
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectResources: projectResourceReaderStub{domains: repo}, ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo}})
|
||||
|
||||
invalid := httptest.NewRequest(http.MethodPost, "/api/v1/domains", strings.NewReader(`{"name":"example.com","certificate_type":"san","sans":["bad_domain"]}`))
|
||||
invalid.Header.Set("Content-Type", "application/json")
|
||||
@@ -150,7 +150,7 @@ func TestDomainAPIValidatesSANAndHidesInternalErrors(t *testing.T) {
|
||||
func TestDeleteMissingDomainReturnsNotFound(t *testing.T) {
|
||||
cfg := readyTestConfig(t.TempDir())
|
||||
repo := &stubDomainRepository{deleteErr: sql.ErrNoRows}
|
||||
server := New(Dependencies{Config: cfg, Repository: repo})
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo}})
|
||||
response := httptest.NewRecorder()
|
||||
serveAdminHTTP(server, response, httptest.NewRequest(http.MethodDelete, "/api/v1/domains/missing", nil))
|
||||
if response.Code != http.StatusNotFound || strings.Contains(response.Body.String(), "detail") {
|
||||
@@ -162,7 +162,7 @@ func TestUpdateDomainAPI(t *testing.T) {
|
||||
cfg := readyTestConfig(t.TempDir())
|
||||
loaded := domain.Domain{ID: "domain-1", Name: "example.com", CertificateType: domain.CertificateSingle, SANs: []string{"example.com"}, Status: "active"}
|
||||
repo := &stubDomainRepository{loaded: loaded}
|
||||
server := New(Dependencies{Config: cfg, Repository: repo})
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo}})
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/domains/domain-1", strings.NewReader(`{"name":"example.com","certificate_type":"san","sans":["www.example.com"],"auto_renew":false,"acme_environment":"production","dns_provider":"cloudflare"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -178,7 +178,7 @@ func TestUpdateDomainAPI(t *testing.T) {
|
||||
func TestCreateDomainConflictReturnsConflict(t *testing.T) {
|
||||
cfg := readyTestConfig(t.TempDir())
|
||||
repo := &stubDomainRepository{createErr: errors.New("UNIQUE constraint failed: domains.name")}
|
||||
server := New(Dependencies{Config: cfg, Repository: repo})
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo}})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/domains", strings.NewReader(`{"name":"example.com","certificate_type":"single"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
@@ -191,7 +191,8 @@ func TestCreateDomainConflictReturnsConflict(t *testing.T) {
|
||||
func TestUpdateDomainRejectsInvalidEnvironment(t *testing.T) {
|
||||
cfg := readyTestConfig(t.TempDir())
|
||||
loaded := domain.Domain{ID: "domain-1", Name: "example.com"}
|
||||
server := New(Dependencies{Config: cfg, Repository: &stubDomainRepository{loaded: loaded}})
|
||||
repo := &stubDomainRepository{loaded: loaded}
|
||||
server := New(Dependencies{Config: cfg, Repository: repo, ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo}})
|
||||
request := httptest.NewRequest(http.MethodPut, "/api/v1/domains/domain-1", strings.NewReader(`{"name":"example.com","certificate_type":"single","acme_environment":"invalid"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@@ -53,6 +52,7 @@ type Dependencies struct {
|
||||
ProjectLifecycle repository.ProjectLifecycleRepository
|
||||
ProjectResources repository.ProjectResourceReader
|
||||
ProjectBindings repository.ProjectBindingRepository
|
||||
ProjectDomains repository.ProjectDomainRepository
|
||||
SSHKeys *sshkey.Service
|
||||
DeploymentFactory deployment.ClientFactory
|
||||
SetupDNS setupDNSVerifier
|
||||
@@ -89,6 +89,7 @@ type Server struct {
|
||||
projectLifecycle repository.ProjectLifecycleRepository
|
||||
projectResources repository.ProjectResourceReader
|
||||
projectBindings repository.ProjectBindingRepository
|
||||
projectDomains repository.ProjectDomainRepository
|
||||
sshKeys *sshkey.Service
|
||||
deploymentFactory deployment.ClientFactory
|
||||
setupDNS setupDNSVerifier
|
||||
@@ -154,6 +155,7 @@ func New(deps Dependencies) *Server {
|
||||
projectLifecycle: deps.ProjectLifecycle,
|
||||
projectResources: deps.ProjectResources,
|
||||
projectBindings: deps.ProjectBindings,
|
||||
projectDomains: deps.ProjectDomains,
|
||||
sshKeys: deps.SSHKeys,
|
||||
deploymentFactory: deps.DeploymentFactory,
|
||||
issueCertificate: deps.IssueCertificate,
|
||||
@@ -206,9 +208,10 @@ func (s *Server) registerRoutes() {
|
||||
s.registerProjectResourceRoutes()
|
||||
s.registerProjectBindingRoutes()
|
||||
s.router.GET("/api/v1/projects", privateProjectResponse, s.requireAuthenticated, s.listVisibleProjects)
|
||||
adminAPI.POST("/domains", s.dnsOperation, s.createDomain)
|
||||
adminAPI.PUT("/domains/:id", s.dnsOperation, s.updateDomain)
|
||||
adminAPI.DELETE("/domains/:id", s.deleteDomain)
|
||||
domainAPI := s.router.Group("/api/v1", privateProjectResponse, s.requireAuthenticated)
|
||||
domainAPI.POST("/domains", s.dnsOperation, s.createDomain)
|
||||
domainAPI.PUT("/domains/:id", s.dnsOperation, s.updateDomain)
|
||||
domainAPI.DELETE("/domains/:id", s.deleteDomain)
|
||||
adminAPI.POST("/domains/:id/issue", s.longOperation(certificateTaskTimeout), s.issueDomain)
|
||||
adminAPI.GET("/tasks", s.listTasks)
|
||||
adminAPI.GET("/tasks/:id", s.getTask)
|
||||
@@ -524,6 +527,31 @@ func (s *Server) requireDomainRepository(c *gin.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) requireProjectDomainRepository(c *gin.Context) bool {
|
||||
if s.projectDomains != nil {
|
||||
return true
|
||||
}
|
||||
s.writeError(c, http.StatusServiceUnavailable, "项目域名服务尚未就绪", nil)
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) authorizeDomainMutation(c *gin.Context, projectID string) bool {
|
||||
authorizer, ok := s.projectDomains.(repository.ProjectAuthorizer)
|
||||
if !ok {
|
||||
s.writeError(c, http.StatusServiceUnavailable, "项目权限服务尚未就绪", nil)
|
||||
return false
|
||||
}
|
||||
if err := authorizer.AuthorizeProject(c.Request.Context(), c.GetString(authenticatedActorKey), projectID, domain.PermissionCertificateManage); err != nil {
|
||||
if errors.Is(err, repository.ErrProjectAccessDenied) {
|
||||
s.writeError(c, http.StatusForbidden, "无权管理此项目的域名", nil)
|
||||
} else {
|
||||
s.writeError(c, http.StatusInternalServerError, "检查项目域名权限失败", err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) listDomains(c *gin.Context) {
|
||||
if !s.requireProjectResourceReader(c) {
|
||||
return
|
||||
@@ -537,7 +565,7 @@ func (s *Server) listDomains(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (s *Server) createDomain(c *gin.Context) {
|
||||
if !s.requireDomainRepository(c) {
|
||||
if !s.requireProjectDomainRepository(c) {
|
||||
return
|
||||
}
|
||||
var request domainRequest
|
||||
@@ -550,12 +578,19 @@ func (s *Server) createDomain(c *gin.Context) {
|
||||
s.writeError(c, http.StatusBadRequest, "域名配置无效", err)
|
||||
return
|
||||
}
|
||||
item.ResourceScope = s.newResourceScope(c)
|
||||
if !s.authorizeDomainMutation(c, item.ProjectID) {
|
||||
return
|
||||
}
|
||||
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), append([]string{item.Name}, item.SANs...)...); err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, err.Error(), err)
|
||||
return
|
||||
}
|
||||
item.ResourceScope = s.newResourceScope(c)
|
||||
if err := s.repository.Create(c.Request.Context(), item); err != nil {
|
||||
if err := s.projectDomains.CreateProjectDomain(c.Request.Context(), c.GetString(authenticatedActorKey), item); err != nil {
|
||||
if errors.Is(err, repository.ErrProjectAccessDenied) {
|
||||
s.writeError(c, http.StatusForbidden, "无权管理此项目的域名", nil)
|
||||
return
|
||||
}
|
||||
if repository.IsConflict(err) {
|
||||
s.writeError(c, http.StatusConflict, "域名已经存在", err)
|
||||
return
|
||||
@@ -567,7 +602,7 @@ func (s *Server) createDomain(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (s *Server) updateDomain(c *gin.Context) {
|
||||
if !s.requireDomainRepository(c) {
|
||||
if !s.requireProjectDomainRepository(c) || !s.requireDomainRepository(c) {
|
||||
return
|
||||
}
|
||||
var request domainRequest
|
||||
@@ -584,6 +619,9 @@ func (s *Server) updateDomain(c *gin.Context) {
|
||||
s.writeError(c, http.StatusInternalServerError, "读取域名失败", err)
|
||||
return
|
||||
}
|
||||
if !s.authorizeDomainMutation(c, existing.ProjectID) {
|
||||
return
|
||||
}
|
||||
item, err := newDomainFromRequest(request)
|
||||
if err != nil {
|
||||
s.writeError(c, http.StatusBadRequest, "域名配置无效", err)
|
||||
@@ -598,7 +636,15 @@ func (s *Server) updateDomain(c *gin.Context) {
|
||||
item.CreatedAt = existing.CreatedAt
|
||||
item.Status = "pending"
|
||||
item.ExpiresAt = nil
|
||||
if err := s.repository.Update(c.Request.Context(), item); err != nil {
|
||||
if err := s.projectDomains.UpdateProjectDomain(c.Request.Context(), c.GetString(authenticatedActorKey), item); err != nil {
|
||||
if errors.Is(err, repository.ErrProjectAccessDenied) {
|
||||
s.writeError(c, http.StatusForbidden, "无权管理此项目的域名", nil)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, deployment.ErrSharedPathConflict) {
|
||||
s.writeError(c, http.StatusConflict, deployment.ErrSharedPathConflict.Error(), nil)
|
||||
return
|
||||
}
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "域名不存在", err)
|
||||
return
|
||||
@@ -626,24 +672,19 @@ func newDomainFromRequest(request domainRequest) (domain.Domain, error) {
|
||||
}
|
||||
|
||||
func (s *Server) deleteDomain(c *gin.Context) {
|
||||
if !s.requireDomainRepository(c) {
|
||||
if !s.requireProjectDomainRepository(c) {
|
||||
return
|
||||
}
|
||||
domainID := strings.TrimSpace(c.Param("id"))
|
||||
if s.tasks != nil {
|
||||
for _, taskType := range []string{"certificate_issue", "certificate_validate", "certificate_deploy", "certificate_import", "certificate_restore"} {
|
||||
_, err := s.tasks.FindActiveTaskByDomain(c.Request.Context(), domainID, taskType)
|
||||
if err == nil {
|
||||
s.writeError(c, http.StatusConflict, "域名存在正在执行的证书任务,请等待任务完成或取消后再删除", nil)
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
s.writeError(c, http.StatusInternalServerError, "检查域名任务状态失败", err)
|
||||
return
|
||||
}
|
||||
if err := s.projectDomains.DeleteProjectDomain(c.Request.Context(), c.GetString(authenticatedActorKey), domainID); err != nil {
|
||||
if errors.Is(err, repository.ErrProjectAccessDenied) {
|
||||
s.writeError(c, http.StatusForbidden, "无权管理此项目的域名", nil)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, repository.ErrProjectDomainBusy) {
|
||||
s.writeError(c, http.StatusConflict, err.Error(), nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := s.repository.Delete(c.Request.Context(), domainID); err != nil {
|
||||
if repository.IsNotFound(err) {
|
||||
s.writeError(c, http.StatusNotFound, "域名不存在", err)
|
||||
return
|
||||
|
||||
@@ -315,9 +315,13 @@ func TestServerAndDomainAssociationAPI(t *testing.T) {
|
||||
Users: repository.NewSQLUserRepository(db.DB),
|
||||
ProjectResources: repository.NewSQLProjectMemberRepository(db.DB),
|
||||
ProjectBindings: repository.NewSQLProjectMemberRepository(db.DB),
|
||||
ProjectDomains: repository.NewSQLProjectMemberRepository(db.DB),
|
||||
})
|
||||
// 此旧格式用例同样使用真实账户与项目成员,不能依赖全局管理员绕过绑定权限。
|
||||
_ = httpUserSessionCookie(server, "test-admin", repository.UserRoleAdmin)
|
||||
if _, err := db.DB.ExecContext(t.Context(), `INSERT OR IGNORE INTO users (id, username, password_hash, role, status) VALUES ('test-admin', 'test-admin', 'test-only-no-login', 'admin', 'active')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.DB.ExecContext(t.Context(), `INSERT INTO project_members (project_id, user_id, role) VALUES ('default', 'test-admin', 'project_admin')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -700,6 +704,9 @@ func TestDeleteDomainRejectsActiveCertificateTask(t *testing.T) {
|
||||
if err := database.Migrate(context.Background(), db.DB, "sqlite"); err != nil {
|
||||
t.Fatalf("数据库迁移失败:%v", err)
|
||||
}
|
||||
if _, err := db.DB.ExecContext(context.Background(), `INSERT OR IGNORE INTO users (id, username, password_hash, role, status) VALUES ('test-admin', 'test-admin', 'test-only-no-login', 'super_admin', 'active')`); err != nil {
|
||||
t.Fatalf("创建测试账户失败:%v", err)
|
||||
}
|
||||
|
||||
domainRepo := repository.NewSQLDomainRepository(db.DB)
|
||||
taskRepo := repository.NewSQLTaskRepository(db.DB)
|
||||
@@ -707,6 +714,7 @@ func TestDeleteDomainRejectsActiveCertificateTask(t *testing.T) {
|
||||
Config: cfg,
|
||||
Repository: domainRepo,
|
||||
Tasks: taskRepo,
|
||||
ProjectDomains: repository.NewSQLProjectMemberRepository(db.DB),
|
||||
})
|
||||
|
||||
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/domains", strings.NewReader(`{"name":"active-task.example.com","certificate_type":"single"}`))
|
||||
|
||||
@@ -12,6 +12,28 @@ import (
|
||||
"git.pcux.cn/xuans/Scert/backend/internal/repository"
|
||||
)
|
||||
|
||||
// projectDomainRepositoryStub 仅用于保留旧 HTTP 参数校验测试的存根行为;生产路由始终注入真实项目域名仓储。
|
||||
type projectDomainRepositoryStub struct {
|
||||
repository.DomainRepository
|
||||
authorizeErr error
|
||||
}
|
||||
|
||||
func (r projectDomainRepositoryStub) AuthorizeProject(context.Context, string, string, domain.ProjectPermission) error {
|
||||
return r.authorizeErr
|
||||
}
|
||||
|
||||
func (r projectDomainRepositoryStub) CreateProjectDomain(ctx context.Context, actorID string, item domain.Domain) error {
|
||||
return r.DomainRepository.Create(ctx, item)
|
||||
}
|
||||
|
||||
func (r projectDomainRepositoryStub) UpdateProjectDomain(ctx context.Context, actorID string, item domain.Domain) error {
|
||||
return r.DomainRepository.Update(ctx, item)
|
||||
}
|
||||
|
||||
func (r projectDomainRepositoryStub) DeleteProjectDomain(ctx context.Context, actorID, id string) error {
|
||||
return r.DomainRepository.Delete(ctx, id)
|
||||
}
|
||||
|
||||
// 仅供旧的响应格式与错误脱敏单元测试显式注入;权限验证使用真实 SQL 资源夹具。
|
||||
// 不在产品构造器或通用请求帮助函数中自动补齐,缺失依赖测试必须保持拒绝。
|
||||
type projectResourceReaderStub struct {
|
||||
|
||||
Reference in new issue
Block a user