接入托管域名HTTP验证与隔离挑战并补充回归用例

This commit is contained in:
xuans committed 2026-10-04 02:37:00 +08:00
1 parent e829d665ca
commit 5128b25e88
33 files changed
+1096 -76

No files matched your search

@@ -0,0 +1,33 @@
package httpapi
import (
"net/http"
"github.com/gin-gonic/gin"
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
)
func (s *Server) authorizeDomainChallenge(c *gin.Context, item domain.Domain) bool {
if item.ChallengeType == domain.ChallengeHTTP01 {
return true
}
if s.currentDNSProvider() == dnsprovider.Aliyun && !s.authorizeDNSCredentialUse(c, item.ProjectID) {
return false
}
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), append([]string{item.Name}, item.SANs...)...); err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
return false
}
return true
}
func (s *Server) authorizeIssueChallenge(c *gin.Context, item domain.Domain) bool {
kind, err := domain.NormalizeChallengeType(item.ChallengeType, append([]string{item.Name}, item.SANs...))
if err != nil {
s.writeError(c, http.StatusBadRequest, "证书验证方式无效", err)
return false
}
return kind == domain.ChallengeHTTP01 || s.authorizeDNSCredentialUse(c, item.ResourceScope.Normalize().ProjectID)
}
@@ -0,0 +1,112 @@
package httpapi
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/deployment"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/httpchallenge"
"git.pcux.cn/xuans/Scert/backend/internal/repository"
)
func TestHTTPChallengeProductionHandler(t *testing.T) {
store := httpchallenge.NewStore()
lease, err := store.NewLease(t.Context(), []string{"issued.example.com"})
if err != nil {
t.Fatal(err)
}
defer lease.Close()
const token = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"
if err := lease.Present(t.Context(), "issued.example.com", token, token+"."+token); err != nil {
t.Fatal(err)
}
server := New(Dependencies{Config: readyTestConfig(t.TempDir()), HTTPChallenges: store})
for _, tc := range []struct {
host, path string
status int
}{
{"issued.example.com", token, 200},
{"other.example.com", token, 404},
{"issued.example.com", "unknown", 404},
{"issued.example.com", token + "/", 404},
} {
w := httptest.NewRecorder()
server.Handler().ServeHTTP(w, httptest.NewRequest("GET", "http://"+tc.host+httpchallenge.PathPrefix+tc.path, nil))
if w.Code != tc.status || w.Header().Get("Location") != "" || w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("正式挑战路由错误:%d %s", w.Code, w.Body.String())
}
}
server.httpChallenges = nil
w := httptest.NewRecorder()
server.Handler().ServeHTTP(w, httptest.NewRequest("GET", "http://issued.example.com"+httpchallenge.PathPrefix+token, nil))
if w.Code != 404 {
t.Fatal("缺失挑战存储时未拒绝")
}
}
func TestHTTPDomainCreateAndUpdateBypassDNSOnly(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.DNS.Provider = "aliyun"
repo := &stubDomainRepository{loaded: domain.Domain{ID: "domain-1", Name: "example.com", ChallengeType: domain.ChallengeHTTP01}}
server := New(Dependencies{
Config: cfg, Repository: repo,
ProjectDomains: projectDomainRepositoryStub{DomainRepository: repo},
ProjectResources: projectResourceReaderStub{domains: repo},
})
for _, tc := range []struct {
method, path, body string
status int
}{
{"POST", "/api/v1/domains", `{"name":"example.com","certificate_type":"single","challenge_type":"http-01"}`, 201},
{"POST", "/api/v1/domains", `{"name":"example.com","certificate_type":"san","sans":["*.example.com"],"challenge_type":"http-01"}`, 400},
{"POST", "/api/v1/domains", `{"name":"example.com","certificate_type":"single","challenge_type":"unknown"}`, 400},
{"PUT", "/api/v1/domains/domain-1", `{"name":"example.com","certificate_type":"single"}`, 200},
} {
w := httptest.NewRecorder()
serveAdminHTTP(server, w, httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body)))
if w.Code != tc.status {
t.Fatalf("域名接口状态 %d,预期 %d:%s", w.Code, tc.status, w.Body.String())
}
}
if repo.created.ChallengeType != domain.ChallengeHTTP01 || repo.updated.ChallengeType != domain.ChallengeHTTP01 {
t.Fatal("HTTP 验证方式未保存或旧客户端覆盖了现有方式")
}
}
func TestHTTPTaskAuthorizationRetainsProjectPermissions(t *testing.T) {
for _, denied := range []domain.ProjectPermission{domain.PermissionDNSCredentialUse, domain.PermissionCertificateManage, domain.PermissionDeploymentExecute} {
t.Run(string(denied), func(t *testing.T) {
repo := &stubDomainRepository{loaded: domain.Domain{ID: "domain-1", Name: "example.com", ChallengeType: domain.ChallengeHTTP01, ResourceScope: domain.ResourceScope{ProjectID: "project-a"}}}
calls := 0
server := New(Dependencies{
Config: readyTestConfig(t.TempDir()), Repository: repo,
ProjectResources: projectResourceReaderStub{domains: repo},
ProjectMembers: permissionProjectMemberRepository{allow: func(permission domain.ProjectPermission) error {
if permission == denied {
return repository.ErrProjectAccessDenied
}
return nil
}},
IssueCertificate: func(context.Context, string) (certificate.IssueResult, deployment.Report, error) {
calls++
return certificate.IssueResult{}, deployment.Report{}, nil
},
})
w := httptest.NewRecorder()
serveAdminHTTP(server, w, httptest.NewRequest(http.MethodPost, "/api/v1/domains/domain-1/issue", nil))
want := denied == domain.PermissionDNSCredentialUse
if (calls == 1) != want {
t.Fatalf("HTTP 签发项目授权错误:%d %s", w.Code, w.Body.String())
}
err := server.authorizeCertificateTaskExecution(t.Context(), repository.Task{DomainID: "domain-1", ProjectID: "project-a", ScopeType: repository.ScopeProject, OperatorID: "actor", TaskType: "certificate_issue"}, repository.TaskAttempt{})
if (err == nil) != want {
t.Fatal("执行前授权与验证方式不匹配:", err)
}
})
}
}
+35 -15
View File
@@ -25,6 +25,7 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
"git.pcux.cn/xuans/Scert/backend/internal/domain"
"git.pcux.cn/xuans/Scert/backend/internal/firewall"
"git.pcux.cn/xuans/Scert/backend/internal/httpchallenge"
"git.pcux.cn/xuans/Scert/backend/internal/logging"
"git.pcux.cn/xuans/Scert/backend/internal/repository"
)
@@ -39,6 +40,7 @@ type readinessSecretReader interface {
}
type Dependencies struct {
HTTPChallenges *httpchallenge.Store
Config config.Config
ConfigPath string
FrontendDir string
@@ -83,6 +85,7 @@ type Dependencies struct {
}
type Server struct {
httpChallenges *httpchallenge.Store
configMu sync.RWMutex
config config.Config
configPath string
@@ -161,8 +164,9 @@ func New(deps Dependencies) *Server {
frontendDir = filepath.Join(deps.Config.Paths.Install, "web")
}
server := &Server{
httpListening: make(chan struct{}),
config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger,
httpChallenges: deps.HTTPChallenges,
httpListening: make(chan struct{}),
config: deps.Config, configPath: deps.ConfigPath, frontendDir: filepath.Clean(frontendDir), logger: deps.Logger,
repository: deps.Repository, setupDNS: deps.SetupDNS, secrets: deps.Secrets, firewall: deps.Firewall, router: router,
servers: deps.Servers,
users: deps.Users,
@@ -260,7 +264,14 @@ func (s *Server) registerRoutes() {
}
func (s *Server) Handler() http.Handler {
return s.router
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 在路由纠正、访问日志及登录检查前接管挑战,未知令牌不能落入前端页面。
if strings.HasPrefix(r.URL.Path, strings.TrimSuffix(httpchallenge.PathPrefix, "/")) {
s.httpChallenges.ServeHTTP(w, r)
return
}
s.router.ServeHTTP(w, r)
})
}
func (s *Server) ListenAndServe() error {
@@ -329,7 +340,7 @@ func (s *Server) prepareHTTPServer() (*http.Server, error) {
if err != nil {
return nil, fmt.Errorf("加载 HTTPS 证书与私钥失败:%w", err)
}
server := newHTTPServer(address, s.router)
server := newHTTPServer(address, s.Handler())
server.TLSConfig.GetCertificate = s.getTLSCertificate
s.httpMu.Lock()
if s.httpStopped {
@@ -412,6 +423,7 @@ type domainRequest struct {
AutoRenew *bool `json:"auto_renew"`
ACMEEnvironment string `json:"acme_environment"`
DNSProvider string `json:"dns_provider"`
ChallengeType *string `json:"challenge_type"`
}
type serverRequest struct {
@@ -634,11 +646,7 @@ func (s *Server) createDomain(c *gin.Context) {
if !s.authorizeDomainMutation(c, item.ProjectID) {
return
}
if s.currentDNSProvider() == dnsprovider.Aliyun && !s.authorizeDNSCredentialUse(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)
if !s.authorizeDomainChallenge(c, item) {
return
}
if err := s.projectDomains.CreateProjectDomain(c.Request.Context(), c.GetString(authenticatedActorKey), item); err != nil {
@@ -673,16 +681,16 @@ func (s *Server) updateDomain(c *gin.Context) {
if !s.authorizeDomainMutation(c, existing.ProjectID) {
return
}
if s.currentDNSProvider() == dnsprovider.Aliyun && !s.authorizeDNSCredentialUse(c, existing.ProjectID) {
return
if request.ChallengeType == nil {
request.ChallengeType = &existing.ChallengeType
}
item, err := newDomainFromRequest(request)
if err != nil {
s.writeError(c, http.StatusBadRequest, "域名配置无效", err)
return
}
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), append([]string{item.Name}, item.SANs...)...); err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
item.ResourceScope = existing.ResourceScope
if !s.authorizeDomainChallenge(c, item) {
return
}
item.ID = existing.ID
@@ -722,7 +730,19 @@ func newDomainFromRequest(request domainRequest) (domain.Domain, error) {
if acmeEnvironment == "" {
acmeEnvironment = domain.ACMEEnvironmentStaging
}
return domain.NewDomainWithOptions(request.Name, domain.CertificateType(request.CertificateType), request.SANs, autoRenew, acmeEnvironment, request.DNSProvider)
item, err := domain.NewDomainWithOptions(request.Name, domain.CertificateType(request.CertificateType), request.SANs, autoRenew, acmeEnvironment, request.DNSProvider)
if err != nil {
return domain.Domain{}, err
}
value := ""
if request.ChallengeType != nil {
value = *request.ChallengeType
}
item.ChallengeType, err = domain.NormalizeChallengeType(value, append([]string{item.Name}, item.SANs...))
if item.ChallengeType == domain.ChallengeHTTP01 {
item.DNSProvider = ""
}
return item, err
}
func (s *Server) deleteDomain(c *gin.Context) {
@@ -758,7 +778,7 @@ func (s *Server) authorizeSynchronousCertificateIssue(c *gin.Context) bool {
s.writeProjectResourceError(c, err)
return false
}
return s.authorizeDNSCredentialUse(c, resource.ResourceScope.Normalize().ProjectID)
return s.authorizeIssueChallenge(c, resource)
}
func (s *Server) issueDomain(c *gin.Context) {
+13 -3
View File
@@ -94,7 +94,7 @@ func (s *Server) submitPreparedDomainTask(c *gin.Context, taskType string, prepa
s.writeError(c, http.StatusInternalServerError, "检查证书部署权限失败", err)
return
}
if taskType == "certificate_issue" && !s.authorizeDNSCredentialUse(c, resource.ResourceScope.Normalize().ProjectID) {
if taskType == "certificate_issue" && !s.authorizeIssueChallenge(c, resource) {
return
}
s.issueTaskMu.Lock()
@@ -577,8 +577,18 @@ func (s *Server) retryTask(c *gin.Context) {
return
}
}
if item.TaskType == "certificate_issue" && !s.authorizeDNSCredentialUse(c, projectID) {
return
if item.TaskType == "certificate_issue" {
if !s.requireProjectResourceReader(c) {
return
}
resource, err := s.projectResources.GetVisibleDomain(c.Request.Context(), actorID, item.DomainID)
if err != nil {
s.writeProjectResourceError(c, err)
return
}
if !s.authorizeIssueChallenge(c, resource) {
return
}
}
startedAt := time.Now().UTC()
retryTask, attempt, err := reader.RetryVisibleTask(c.Request.Context(), actorID, taskID, &startedAt)
@@ -24,7 +24,14 @@ func (s *Server) authorizeCertificateTaskExecution(ctx context.Context, task rep
permissions := []domain.ProjectPermission{domain.PermissionDeploymentExecute}
switch task.TaskType {
case "certificate_issue":
permissions = append(permissions, domain.PermissionCertificateManage, domain.PermissionDNSCredentialUse)
permissions = append(permissions, domain.PermissionCertificateManage)
kind, err := domain.NormalizeChallengeType(resource.ChallengeType, append([]string{resource.Name}, resource.SANs...))
if err != nil {
return err
}
if kind == domain.ChallengeDNS01 {
permissions = append(permissions, domain.PermissionDNSCredentialUse)
}
case "certificate_deploy":
case "certificate_restore":
permissions = append(permissions, domain.PermissionPrivateKeyRead)