完善阿里云权限与会话回归测试

This commit is contained in:
xuans committed 2026-09-16 04:09:07 +08:00
1 parent 50ece6093b
commit bbabc35cbf
25 files changed
+502 -250

No files matched your search

+14 -8
View File
@@ -43,20 +43,25 @@ func (s *Server) checkAliyunDNSDomain(c *gin.Context) {
s.writeError(c, http.StatusBadRequest, "当前系统 DNS 服务商不是阿里云,无法进行阿里云 RAM 权限考证", nil)
return
}
// 必须先在本地拒绝受保护域,不能为无效请求读取凭据或触发云端探测。
if err := dnsprovider.ValidateAliyunTargetDomains(provider, []string{targetDomain}); err != nil {
c.JSON(http.StatusOK, gin.H{"verified": false, "domain": targetDomain, "message": err.Error()})
return
}
credentials, err := s.readDNSCredentials(c.Request.Context(), credentialRef)
if err != nil {
s.writeError(c, http.StatusInternalServerError, "读取阿里云 DNS 凭据失败", err)
return
}
if s.aliyunChecker == nil {
s.writeError(c, http.StatusNotImplemented, "阿里云权限探测器未装载", nil)
credentials, err = dnsprovider.ValidateCredentials(dnsprovider.Aliyun, credentials)
if err != nil {
s.writeError(c, http.StatusBadRequest, "阿里云 DNS 凭据无效", err)
return
}
if err := dnsprovider.ValidateAliyunTargetDomains(provider, []string{targetDomain}); err != nil {
c.JSON(http.StatusOK, gin.H{"verified": false, "domain": targetDomain, "message": err.Error()})
if s.aliyunChecker == nil {
s.writeError(c, http.StatusNotImplemented, "阿里云权限探测器未装载", nil)
return
}
report, verifyErr := s.aliyunChecker.Verify(c.Request.Context(), targetDomain, credentials)
@@ -101,6 +106,10 @@ func (s *Server) validateDomainAliyunAuthorization(ctx context.Context, domainNa
if !setupReady {
return errors.New("系统初始化尚未完成,不能验证域名授权")
}
// 在读取凭据、构造阿里云客户端或发起任何云 API 请求前检查整张订单。
if err := dnsprovider.ValidateAliyunTargetDomains(provider, domainNames); err != nil {
return err
}
if s.aliyunChecker == nil {
return errors.New("阿里云权限探测器未装载,不能确认域名授权")
}
@@ -112,9 +121,6 @@ func (s *Server) validateDomainAliyunAuthorization(ctx context.Context, domainNa
if _, err := dnsprovider.ValidateCredentials(dnsprovider.Aliyun, credentials); err != nil {
return fmt.Errorf("阿里云 DNS 凭据无效,不能确认域名授权:%w", err)
}
if err := dnsprovider.ValidateAliyunTargetDomains(provider, domainNames); err != nil {
return err
}
for _, domainName := range domainNames {
if err := s.aliyunChecker.VerifyDomain(ctx, dnsprovider.Aliyun, domainName, credentials); err != nil {
diagnosis := dnsprovider.DiagnoseAliyunError(err, domainName)
@@ -12,15 +12,13 @@ import (
)
type fakeAliyunScopeChecker struct {
allowedZones []string
}
func (f *fakeAliyunScopeChecker) Discover(ctx context.Context, credentials map[string]string) (dnsprovider.AuthorizationReport, error) {
// 模拟 RAM 账号处于最小资源限制模式,无全局枚举权限
return dnsprovider.AuthorizationReport{}, errors.New("SDKError: Code: Forbidden.NoPermission")
allowedZones []string
verifyCalls int
verifyDomainCalls int
}
func (f *fakeAliyunScopeChecker) Verify(ctx context.Context, requestedDomain string, credentials map[string]string) (dnsprovider.AuthorizationReport, error) {
f.verifyCalls++
report := dnsprovider.AuthorizationReport{
Provider: dnsprovider.Aliyun,
RequestedDomain: requestedDomain,
@@ -38,6 +36,7 @@ func (f *fakeAliyunScopeChecker) Verify(ctx context.Context, requestedDomain str
}
func (f *fakeAliyunScopeChecker) VerifyDomain(ctx context.Context, providerID, requestedDomain string, credentials map[string]string) error {
f.verifyDomainCalls++
for _, zone := range f.allowedZones {
if requestedDomain == zone || strings.HasSuffix(requestedDomain, "."+zone) {
return nil
@@ -47,7 +46,8 @@ func (f *fakeAliyunScopeChecker) VerifyDomain(ctx context.Context, providerID, r
}
type fakeSecretReaderStore struct {
data map[string]map[string]string
data map[string]map[string]string
getCalls int
}
func (s *fakeSecretReaderStore) Put(ctx context.Context, ref string, val map[string]string) error {
@@ -64,13 +64,14 @@ func (s *fakeSecretReaderStore) Delete(ctx context.Context, ref string) error {
}
func (s *fakeSecretReaderStore) Get(ctx context.Context, ref string) (map[string]string, error) {
s.getCalls++
if val, ok := s.data[ref]; ok {
return val, nil
}
return nil, errors.New("secret not found")
}
func TestAliyunScopeAPIsAndDomainValidation(t *testing.T) {
func TestAliyunDomainCheckUsesOnlyCurrentTargetAndProtectsPCUX(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.SetupReady = true
cfg.DNS.Provider = "aliyun"
@@ -81,8 +82,6 @@ func TestAliyunScopeAPIsAndDomainValidation(t *testing.T) {
"secret://dns/aliyun/ref1": {
"access_key_id": "LTAI_test",
"access_key_secret": "test_secret",
"managed_zones": "solit.cn,unauth.com,forbidden.cn",
"allowed_domains": "solit.cn,*.solit.cn,unauth.com,forbidden.cn",
},
},
}
@@ -99,20 +98,17 @@ func TestAliyunScopeAPIsAndDomainValidation(t *testing.T) {
AliyunChecker: checker,
})
// 1. 测试 GET /api/v1/dns/aliyun/scope(受限模式报告)
// 旧的授权范围枚举接口已移除,不能重新引入账户域名发现能力。
{
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/dns/aliyun/scope", nil)
serveAdminHTTP(server, w, req)
if w.Code != http.StatusOK {
t.Fatalf("GET /api/v1/dns/aliyun/scope status = %d; want 200, body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "resource_scoped") {
t.Fatalf("expected resource_scoped policy mode, got: %s", w.Body.String())
if w.Code != http.StatusNotFound {
t.Fatalf("已移除的授权范围接口状态码 = %d,期望 404,响应:%s", w.Code, w.Body.String())
}
}
// 2. 测试 POST /api/v1/dns/aliyun/check 验证授权域名(如 solit.cn)
// 对用户刚输入的域名使用当前 RAM 凭据执行验证,不依赖手工范围字段。
{
w := httptest.NewRecorder()
body := strings.NewReader(`{"domain":"solit.cn"}`)
@@ -122,50 +118,35 @@ func TestAliyunScopeAPIsAndDomainValidation(t *testing.T) {
t.Fatalf("POST check solit.cn status = %d; body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `"verified":true`) {
t.Fatalf("solit.cn 应验证通过: %s", w.Body.String())
t.Fatalf("solit.cn 应验证通过:%s", w.Body.String())
}
if store.getCalls != 1 || checker.verifyCalls != 1 {
t.Fatalf("正常域名必须仅读取一次凭据并验证一次:读取=%d,验证=%d", store.getCalls, checker.verifyCalls)
}
}
// 3. 测试 POST /api/v1/dns/aliyun/check 验证未授权域名(如 unauth.com)
// pcux.cn 必须先本地拒绝,不能读取凭据或调用云端探测器。
{
w := httptest.NewRecorder()
body := strings.NewReader(`{"domain":"unauth.com"}`)
body := strings.NewReader(`{"domain":"pcux.cn"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/dns/aliyun/check", body)
serveAdminHTTP(server, w, req)
if w.Code != http.StatusOK {
t.Fatalf("POST check unauth.com status = %d; body=%s", w.Code, w.Body.String())
t.Fatalf("POST check pcux.cn 状态码 = %d,响应:%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `"verified":false`) {
t.Fatalf("unauth.com 应验证失败: %s", w.Body.String())
t.Fatalf("pcux.cn 应被本地拒绝:%s", w.Body.String())
}
if !strings.Contains(w.Body.String(), "acs:alidns:*:*:domain/unauth.com") {
t.Fatalf("应包含明确的 RAM 策略建议: %s", w.Body.String())
if store.getCalls != 1 || checker.verifyCalls != 1 || checker.verifyDomainCalls != 0 {
t.Fatalf("保护域不能触发凭据读取或云端探测:读取=%d,检查=%d,域名检查=%d", store.getCalls, checker.verifyCalls, checker.verifyDomainCalls)
}
}
// 4. 测试 POST /api/v1/domains 添加授权域名(例如 *.solit.cn)
{
w := httptest.NewRecorder()
body := strings.NewReader(`{"name":"test.solit.cn","certificate_type":"single"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/domains", body)
serveAdminHTTP(server, w, req)
if w.Code != http.StatusCreated {
t.Fatalf("创建授权域名应成功,got status = %d; body=%s", w.Code, w.Body.String())
}
if err := server.validateDomainAliyunAuthorization(t.Context(), "pcux.cn"); err == nil {
t.Fatal("直接校验 pcux.cn 必须被拒绝")
}
// 5. 测试 POST /api/v1/domains 添加未授权域名(例如 forbidden.cn),应被前置阻断
{
w := httptest.NewRecorder()
body := strings.NewReader(`{"name":"forbidden.cn","certificate_type":"single"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/domains", body)
serveAdminHTTP(server, w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("添加未授权域名应被 400 阻断,got status = %d; body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "acs:alidns:*:*:domain/forbidden.cn") {
t.Fatalf("阻断提示应包含针对该域名的 RAM 授权指导,got: %s", w.Body.String())
}
if store.getCalls != 1 || checker.verifyDomainCalls != 0 {
t.Fatalf("直接校验保护域不能读取凭据或调用探测:读取=%d,域名检查=%d", store.getCalls, checker.verifyDomainCalls)
}
}
@@ -203,21 +184,25 @@ func TestAliyunDomainAuthorizationFailsClosed(t *testing.T) {
}
}
func TestAliyunDomainAPIRejectsPartiallyUnauthorizedSAN(t *testing.T) {
func TestAliyunDomainAPIRejectsProtectedSANWithoutSideEffects(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.DNS.Provider = dnsprovider.Aliyun
cfg.DNS.CredentialRef = "secret://dns/test"
store := &fakeSecretReaderStore{data: map[string]map[string]string{
cfg.DNS.CredentialRef: {"access_key_id": "test-id", "access_key_secret": "test-secret"},
}}
checker := &fakeAliyunScopeChecker{allowedZones: []string{"example.com"}}
repo := &stubDomainRepository{}
server := New(Dependencies{
Config: cfg, Repository: &stubDomainRepository{},
Secrets: &fakeSecretReaderStore{data: map[string]map[string]string{
cfg.DNS.CredentialRef: {"access_key_id": "test-id", "access_key_secret": "test-secret", "managed_zones": "example.com", "allowed_domains": "example.com"},
}},
AliyunChecker: &fakeAliyunScopeChecker{allowedZones: []string{"example.com"}},
Config: cfg, Repository: 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":["example.org"]}`))
req := httptest.NewRequest(http.MethodPost, "/api/v1/domains", strings.NewReader(`{"name":"example.com","certificate_type":"san","sans":["pcux.cn"]}`))
serveAdminHTTP(server, w, req)
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "example.org") {
t.Fatalf("部分 SAN 未授权应整单拒绝:%d %s", w.Code, w.Body.String())
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "pcux.cn") {
t.Fatalf("包含保护 SAN 的整单应被拒绝:%d %s", w.Code, w.Body.String())
}
if repo.created.ID != "" || store.getCalls != 0 || checker.verifyDomainCalls != 0 {
t.Fatalf("保护 SAN 被拒绝时不得持久化、读取凭据或探测:已创建=%t,读取=%d,检查=%d", repo.created.ID != "", store.getCalls, checker.verifyDomainCalls)
}
}
+1
View File
@@ -198,6 +198,7 @@ func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
delete(s.authSessions, token)
s.authMu.Unlock()
}
s.clearAuthCookie(c)
return authSession{}, false
}
if !s.authSessionAccountIsValid(c.Request.Context(), session) {
@@ -83,13 +83,13 @@ func TestHTTPLoginBurstRejectsBeforeAccountLookup(t *testing.T) {
func TestSessionCannotReviveAfterSlowAccountLookup(t *testing.T) {
users := &pausedSessionRepository{
started: make(chan struct{}), release: make(chan struct{}),
user: repository.User{ID: "operator", Username: "operator", PasswordHash: "test-hash", Role: repository.UserRoleUser, Status: repository.UserStatusActive},
user: repository.User{ID: "operator", Username: "operator", Email: "operator@example.test", PasswordHash: "test-hash", Role: repository.UserRoleUser, Status: repository.UserStatusActive},
}
s := New(Dependencies{Config: readyTestConfig(t.TempDir()), Users: users})
now := time.Now()
s.now = func() time.Time { return now }
s.authSessions["slow"] = authSession{
UserID: users.user.ID, Username: users.user.Username, PasswordHash: users.user.PasswordHash, Role: users.user.Role,
UserID: users.user.ID, Username: users.user.Username, Email: users.user.Email, PasswordHash: users.user.PasswordHash, Role: users.user.Role,
ExpiresAt: now.Add(time.Minute), AbsoluteExpiresAt: now.Add(time.Hour),
}
done := make(chan *httptest.ResponseRecorder, 1)
+10 -2
View File
@@ -15,7 +15,7 @@ func TestIncompleteSessionsFailClosed(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.Admin.Username = "admin"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
for _, field := range []string{"user_id", "username", "hash", "role", "absolute", "inverted"} {
for _, field := range []string{"user_id", "username", "email", "hash", "role", "absolute", "inverted"} {
t.Run(field, func(t *testing.T) {
s := New(Dependencies{Config: cfg})
cookie := loginAuthTest(t, s, "admin", "AdminPass123", false).Result().Cookies()[0]
@@ -25,6 +25,8 @@ func TestIncompleteSessionsFailClosed(t *testing.T) {
session.UserID = ""
case "username":
session.Username = ""
case "email":
session.Email = ""
case "hash":
session.PasswordHash = ""
case "role":
@@ -35,12 +37,17 @@ func TestIncompleteSessionsFailClosed(t *testing.T) {
session.AbsoluteExpiresAt = session.ExpiresAt.Add(-time.Second)
}
s.authSessions[cookie.Value] = session
if response := authSessionRequest(s, cookie); response.Code != http.StatusUnauthorized {
response := authSessionRequest(s, cookie)
if response.Code != http.StatusUnauthorized {
t.Fatal("不完整会话必须拒绝")
}
if _, ok := s.authSessions[cookie.Value]; ok {
t.Fatal("失效会话必须移除")
}
cookies := response.Result().Cookies()
if len(cookies) != 1 || cookies[0].Name != authCookieName || cookies[0].MaxAge != -1 {
t.Fatalf("失效会话必须清理认证 Cookie:%+v", cookies)
}
})
}
}
@@ -146,6 +153,7 @@ func TestLoginAttemptTableSaturationRecoversAfterWindow(t *testing.T) {
func TestLoginBlockExpiresAndUserSessionQuotaRecovers(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.Admin.Username = "admin"
cfg.Admin.Email = "admin@example.test"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
s := New(Dependencies{Config: cfg})
now := time.Now()
@@ -48,7 +48,7 @@ func TestSessionCapacityDoesNotEvictActiveSessions(t *testing.T) {
server.now = func() time.Time { return now }
for index := 0; index < authStateCapacity; index++ {
server.authSessions[fmt.Sprint(index)] = authSession{
UserID: fmt.Sprint(index), Username: "operator", PasswordHash: "test-hash", Role: repository.UserRoleUser,
UserID: fmt.Sprint(index), Username: "operator", Email: "operator@example.test", PasswordHash: "test-hash", Role: repository.UserRoleUser,
ExpiresAt: now.Add(time.Minute), AbsoluteExpiresAt: now.Add(time.Hour),
}
}
@@ -42,6 +42,7 @@ func newRestoreAPITestServer(t *testing.T, restore func(context.Context, string,
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Admin.Username = "admin"
cfg.Admin.Email = "admin@example.test"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "RestoreTest123")
server := New(Dependencies{
Config: cfg,
+6 -2
View File
@@ -14,7 +14,7 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/secretstore"
)
const readinessDNSReference = "secret://dns/cloudflare/readiness-test"
const readinessDNSReference = "secret://dns/aliyun/readiness-test"
func TestReadinessRejectsIncompleteSetup(t *testing.T) {
cfg := config.Default(t.TempDir())
@@ -155,6 +155,7 @@ func readinessConfig(t *testing.T) config.Config {
directory := t.TempDir()
cfg := config.Default(directory)
cfg.SetupReady = true
cfg.DNS.Provider = "aliyun"
cfg.DNS.CredentialRef = readinessDNSReference
cfg.Server.TLSCert = filepath.Join(directory, "server.crt")
cfg.Server.TLSKey = filepath.Join(directory, "server.key")
@@ -173,7 +174,10 @@ func readinessStore(t *testing.T) *secretstore.Store {
if err != nil {
t.Fatalf("打开测试敏感信息存储失败:%v", err)
}
if err := store.Put(t.Context(), readinessDNSReference, map[string]string{"api_token": "readiness-test-token"}); err != nil {
if err := store.Put(t.Context(), readinessDNSReference, map[string]string{
"access_key_id": "readiness-test-id",
"access_key_secret": "readiness-test-secret",
}); err != nil {
t.Fatalf("写入测试 DNS 凭据失败:%v", err)
}
return store
-1
View File
@@ -12,7 +12,6 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
)
type settingsView struct {
@@ -369,6 +369,7 @@ func TestRenewalAPIHidesWorkflowErrors(t *testing.T) {
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Admin.Username = "admin"
cfg.Admin.Email = "admin@example.test"
cfg.Admin.PasswordHash = mustTestPasswordHash(t, "Password123")
server := New(Dependencies{
Config: cfg,
+8 -1
View File
@@ -140,7 +140,14 @@ func httpUserSessionCookie(server *Server, userID, role string) *http.Cookie {
if err != nil {
panic(err)
}
user := repository.User{ID: userID, Username: userID, Role: role, Status: repository.UserStatusActive, PasswordHash: string(hash)}
user := repository.User{
ID: userID,
Username: userID,
Email: userID + "@example.test",
Role: role,
Status: repository.UserStatusActive,
PasswordHash: string(hash),
}
if userID == "primary-super-admin" {
user.Username = server.config.Admin.Username
user.Email = server.config.Admin.Email