fix(installer): harden admin smoke and rollback cleanup

This commit is contained in:
2026-09-07 22:39:30 +05:00
parent bf10810cfc
commit 079094591b
15 changed files with 1095 additions and 261 deletions
+91
View File
@@ -18,6 +18,7 @@ import (
"github.com/gin-gonic/gin"
"hy2xs-admin/credential"
"hy2xs-admin/dao"
"hy2xs-admin/middleware"
"hy2xs-admin/model/constant"
"hy2xs-admin/model/dto"
"hy2xs-admin/model/entity"
@@ -460,6 +461,96 @@ func postLogin(t *testing.T, body any) (int, apiResult) {
return postLoginRaw(t, payload, false)
}
// postLoginThroughFilter воспроизводит реальную внешнюю дверь login API:
// scanner filter выполняется раньше DTO и контроллера. Именно этой связки не
// было в тестах до RC3, поэтому backend и smoke были зелёными по отдельности,
// а настоящий installer получал 403 на стандартный curl User-Agent.
func postLoginThroughFilter(t *testing.T, body any, userAgent string) (int, apiResult) {
t.Helper()
payload, err := json.Marshal(body)
if err != nil {
t.Fatalf("не удалось собрать тело запроса: %v", err)
}
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(gin.Recovery(), middleware.FilterHandler())
engine.POST("/api/auth/login", Login)
request := httptest.NewRequest(http.MethodPost, "/api/auth/login", bytes.NewReader(payload))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("User-Agent", userAgent)
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, request)
var result apiResult
if recorder.Body.Len() > 0 {
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
t.Fatalf("middleware вернул не JSON: %s", recorder.Body.String())
}
}
return recorder.Code, result
}
// Полный wire-path RC3: стандартный UA curl действительно блокируется, а
// выделенный UA установщика проходит тот же middleware до authentication logic.
func TestLoginWirePathRespectsScannerFilterAndInstallerUserAgent(t *testing.T) {
newAuthTestDB(t, "hy2xsadmin", "bootstrap-password")
status, blocked := postLoginThroughFilter(t, map[string]any{
"username": "hy2xsadmin",
"pass": "bootstrap-password",
}, "curl/8.10.1")
if status != http.StatusForbidden || blocked.Code != http.StatusForbidden {
t.Fatalf("scanner-like curl не заблокирован: HTTP %d, ответ %+v", status, blocked)
}
status, accepted := postLoginThroughFilter(t, map[string]any{
"username": "hy2xsadmin",
"pass": "bootstrap-password",
}, "HY2XS-Installer/1.0")
if status != http.StatusOK || accepted.Code != constant.CodeSuccess {
t.Fatalf("UA установщика не дошёл до успешного входа: HTTP %d, ответ %+v", status, accepted)
}
var issued struct {
AccessToken string `json:"accessToken"`
}
if err := json.Unmarshal(accepted.Data, &issued); err != nil || issued.AccessToken == "" {
t.Fatalf("успешная wire-проба не выдала токен: %s", string(accepted.Data))
}
_, rejected := postLoginThroughFilter(t, map[string]any{
"username": "hy2xsadmin",
"pass": "wrong-password",
}, "HY2XS-Installer/1.0")
var invalidCredentials bool
for _, reason := range rejected.Errors {
invalidCredentials = invalidCredentials || reason.Code == constant.ErrCodeInvalidCredentials
}
if rejected.Code != constant.CodeSysError || !invalidCredentials {
t.Fatalf("negative wire-проба не дошла до auth logic: %+v", rejected)
}
}
// `password` не является скрытым alias: иначе orchestrator и frontend могли бы
// незаметно разойтись по двум разным HTTP-контрактам.
func TestLoginWirePathRejectsPasswordAlias(t *testing.T) {
newAuthTestDB(t, "hy2xsadmin", "bootstrap-password")
_, result := postLoginThroughFilter(t, map[string]any{
"username": "hy2xsadmin",
"password": "bootstrap-password",
}, "HY2XS-Installer/1.0")
var passRequired bool
for _, reason := range result.Errors {
passRequired = passRequired || (reason.Field == "pass" && reason.Code == constant.ErrCodeRequired)
}
if result.Code != constant.CodeInvalidError || !passRequired {
t.Fatalf("alias password не отклонён как отсутствие wire-поля pass: %+v", result)
}
}
// Регрессия RC2 целиком: вход bootstrap-учёткой обязан выдать токен.
func TestLoginEndpointIssuesTokenForValidCredentials(t *testing.T) {
newAuthTestDB(t, "hy2xsadmin", "bootstrap-password")