精简: 去掉 Telegram 机器人+通知: tgbot 包/stats-notify 与 hash 清理 job/登录通知/backuptotgbot/testTgBot/全部 tg* 设置/locale Bot 本地化/SecretClears 机制; 连带清理 Swagger/外部流量/邮件/2FA 的残留测试
This commit is contained in:
@@ -2,10 +2,10 @@ package controller
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
@@ -289,13 +289,13 @@ func (a *AgentController) listTokens(c *gin.Context) {
|
||||
out := make([]gin.H, 0, len(agents))
|
||||
for _, ag := range agents {
|
||||
out = append(out, gin.H{
|
||||
"id": ag.Id,
|
||||
"token_prefix": ag.TokenPrefix,
|
||||
"name": ag.Name,
|
||||
"node_id": ag.NodeID,
|
||||
"last_seen": ag.LastSeen,
|
||||
"has_egress": ag.Outbounds != "" || ag.RoutingRules != "",
|
||||
"created_at": ag.CreatedAt,
|
||||
"id": ag.Id,
|
||||
"token_prefix": ag.TokenPrefix,
|
||||
"name": ag.Name,
|
||||
"node_id": ag.NodeID,
|
||||
"last_seen": ag.LastSeen,
|
||||
"has_egress": ag.Outbounds != "" || ag.RoutingRules != "",
|
||||
"created_at": ag.CreatedAt,
|
||||
})
|
||||
}
|
||||
jsonObj(c, out, nil)
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -25,7 +24,6 @@ type APIController struct {
|
||||
xraySettingController *XraySettingController
|
||||
userService panel.UserService
|
||||
apiTokenService panel.ApiTokenService
|
||||
Tgbot tgbot.Tgbot
|
||||
}
|
||||
|
||||
// NewAPIController creates a new APIController instance and initializes its routes.
|
||||
@@ -219,10 +217,4 @@ func (a *APIController) initRouter(g *gin.RouterGroup) {
|
||||
NewSubBalancerController(api)
|
||||
|
||||
// Extra routes
|
||||
api.POST("/backuptotgbot", a.BackuptoTgbot)
|
||||
}
|
||||
|
||||
// BackuptoTgbot sends a backup of the panel data to Telegram bot admins.
|
||||
func (a *APIController) BackuptoTgbot(c *gin.Context) {
|
||||
a.Tgbot.SendBackupToAdmins()
|
||||
}
|
||||
|
||||
@@ -1,46 +1,11 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWithServerBasePath(t *testing.T) {
|
||||
spec := []byte(`{"openapi":"3.0.3","info":{"title":"x"},"servers":[{"url":"/","description":"old"}],"paths":{"/p":{"get":{"summary":"s"}}}}`)
|
||||
|
||||
out, err := withServerBasePath(spec, "/test/")
|
||||
if err != nil {
|
||||
t.Fatalf("withServerBasePath: %v", err)
|
||||
}
|
||||
|
||||
var doc map[string]any
|
||||
if err := json.Unmarshal(out, &doc); err != nil {
|
||||
t.Fatalf("unmarshal result: %v", err)
|
||||
}
|
||||
|
||||
servers, ok := doc["servers"].([]any)
|
||||
if !ok || len(servers) != 1 {
|
||||
t.Fatalf("servers = %v, want one entry", doc["servers"])
|
||||
}
|
||||
srv, _ := servers[0].(map[string]any)
|
||||
if srv["url"] != "/test" {
|
||||
t.Errorf("server url = %v, want /test (trailing slash trimmed)", srv["url"])
|
||||
}
|
||||
|
||||
if doc["openapi"] != "3.0.3" {
|
||||
t.Errorf("openapi field not preserved: %v", doc["openapi"])
|
||||
}
|
||||
if _, ok := doc["paths"].(map[string]any)["/p"]; !ok {
|
||||
t.Errorf("paths content not preserved verbatim")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithServerBasePathInvalidJSON(t *testing.T) {
|
||||
if _, err := withServerBasePath([]byte("not json"), "/test/"); err == nil {
|
||||
t.Errorf("expected error on invalid spec, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPWAHeadInjectionUsesRuntimeBasePath(t *testing.T) {
|
||||
tests := []struct {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/middleware"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -27,7 +26,6 @@ type IndexController struct {
|
||||
|
||||
settingService service.SettingService
|
||||
userService panel.UserService
|
||||
tgbot tgbot.Tgbot
|
||||
}
|
||||
|
||||
// NewIndexController creates a new IndexController and initializes its routes.
|
||||
@@ -75,17 +73,9 @@ func (a *IndexController) login(c *gin.Context) {
|
||||
|
||||
remoteIP := getRemoteIp(c)
|
||||
safeUser := template.HTMLEscapeString(form.Username)
|
||||
timeStr := time.Now().Format("2006-01-02 15:04:05")
|
||||
if blockedUntil, ok := defaultLoginLimiter.allow(remoteIP, form.Username); !ok {
|
||||
reason := "too many failed attempts"
|
||||
logger.Warningf("failed login: username=%q, IP=%q, reason=%q, blocked_until=%s", safeUser, remoteIP, reason, blockedUntil.Format(time.RFC3339))
|
||||
a.tgbot.UserLoginNotify(tgbot.LoginAttempt{
|
||||
Username: safeUser,
|
||||
IP: remoteIP,
|
||||
Time: timeStr,
|
||||
Status: tgbot.LoginFail,
|
||||
Reason: reason,
|
||||
})
|
||||
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
|
||||
return
|
||||
}
|
||||
@@ -99,25 +89,12 @@ func (a *IndexController) login(c *gin.Context) {
|
||||
} else {
|
||||
logger.Warningf("failed login: username=%q, IP=%q, reason=%q", safeUser, remoteIP, reason)
|
||||
}
|
||||
a.tgbot.UserLoginNotify(tgbot.LoginAttempt{
|
||||
Username: safeUser,
|
||||
IP: remoteIP,
|
||||
Time: timeStr,
|
||||
Status: tgbot.LoginFail,
|
||||
Reason: reason,
|
||||
})
|
||||
pureJsonMsg(c, http.StatusOK, false, I18nWeb(c, "pages.login.toasts.wrongUsernameOrPassword"))
|
||||
return
|
||||
}
|
||||
|
||||
defaultLoginLimiter.registerSuccess(remoteIP, form.Username)
|
||||
logger.Infof("%s logged in successfully, Ip Address: %s\n", safeUser, remoteIP)
|
||||
a.tgbot.UserLoginNotify(tgbot.LoginAttempt{
|
||||
Username: safeUser,
|
||||
IP: remoteIP,
|
||||
Time: timeStr,
|
||||
Status: tgbot.LoginSuccess,
|
||||
})
|
||||
|
||||
if err := session.SetLoginUser(c, user); err != nil {
|
||||
logger.Warning("Unable to save session:", err)
|
||||
|
||||
@@ -176,9 +176,9 @@ func (a *NodeController) add(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
jsonMsgObj(c, I18nWeb(c, "pages.nodes.toasts.add"), gin.H{
|
||||
"node": view,
|
||||
"agentToken": token,
|
||||
"nodeType": "agent",
|
||||
"node": view,
|
||||
"agentToken": token,
|
||||
"nodeType": "agent",
|
||||
}, nil)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -70,7 +70,6 @@ func (a *SettingController) initRouter(g *gin.RouterGroup) {
|
||||
g.POST("/apiTokens/create", a.createApiToken)
|
||||
g.POST("/apiTokens/delete/:id", a.deleteApiToken)
|
||||
g.POST("/apiTokens/setEnabled/:id", a.setApiTokenEnabled)
|
||||
g.POST("/testTgBot", a.testTgBot)
|
||||
}
|
||||
|
||||
func (a *SettingController) validateRegex(c *gin.Context) {
|
||||
@@ -119,13 +118,7 @@ func (a *SettingController) updateSetting(c *gin.Context) {
|
||||
}
|
||||
allSetting := &form.AllSetting
|
||||
oldPanelOutbound, _ := a.settingService.GetPanelOutbound()
|
||||
oldTgEnable, _ := a.settingService.GetTgbotEnabled()
|
||||
oldTgToken, _ := a.settingService.GetTgBotToken()
|
||||
oldTgChatId, _ := a.settingService.GetTgBotChatId()
|
||||
oldTgAPIServer, _ := a.settingService.GetTgBotAPIServer()
|
||||
err := a.settingService.UpdateAllSetting(allSetting, service.SecretClears{
|
||||
TgBotToken: form.ClearTgBotToken,
|
||||
})
|
||||
err := a.settingService.UpdateAllSetting(allSetting)
|
||||
if err == nil && form.PanelOutbound != oldPanelOutbound {
|
||||
// The egress bridge lives in the generated config; reconcile the
|
||||
// running core. One SOCKS inbound plus one routing rule — both
|
||||
@@ -134,16 +127,6 @@ func (a *SettingController) updateSetting(c *gin.Context) {
|
||||
logger.Warning("apply panel outbound change failed:", applyErr)
|
||||
}
|
||||
}
|
||||
// UpdateAllSetting already restored a redacted-blank token, so allSetting.TgBotToken is the effective value to compare.
|
||||
if err == nil && reloadTgbotFunc != nil {
|
||||
tgChanged := oldTgEnable != allSetting.TgBotEnable ||
|
||||
(allSetting.TgBotEnable && (oldTgToken != allSetting.TgBotToken ||
|
||||
oldTgChatId != allSetting.TgBotChatId ||
|
||||
oldTgAPIServer != allSetting.TgBotAPIServer))
|
||||
if tgChanged {
|
||||
reloadTgbotFunc()
|
||||
}
|
||||
}
|
||||
jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
|
||||
}
|
||||
|
||||
@@ -256,33 +239,3 @@ func (a *SettingController) setApiTokenEnabled(c *gin.Context) {
|
||||
}
|
||||
jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), a.apiTokenService.SetEnabledExpectedScope(id, form.ExpectedScope, form.Enabled))
|
||||
}
|
||||
|
||||
func (a *SettingController) testTgBot(c *gin.Context) {
|
||||
enabled, err := a.settingService.GetTgbotEnabled()
|
||||
if err != nil || !enabled {
|
||||
jsonMsg(c, I18nWeb(c, "pages.settings.tgBotNotEnabled"), errors.New("telegram bot disabled"))
|
||||
return
|
||||
}
|
||||
// Import tgbot package would create a circular dependency, so we call
|
||||
// the test through the global function registered at startup.
|
||||
if testTgFunc != nil {
|
||||
if err := testTgFunc(); err != nil {
|
||||
jsonMsg(c, I18nWeb(c, "pages.settings.tgTestFailed")+": "+err.Error(), err)
|
||||
return
|
||||
}
|
||||
jsonMsg(c, I18nWeb(c, "pages.settings.tgTestSuccess"), nil)
|
||||
return
|
||||
}
|
||||
jsonMsg(c, I18nWeb(c, "pages.settings.tgBotNotRunning"), errors.New("bot not started"))
|
||||
}
|
||||
|
||||
// testTgFunc is set from web layer to test Telegram sending without circular imports.
|
||||
var testTgFunc func() error
|
||||
|
||||
// SetTestTgFunc registers the function used to test Telegram sending.
|
||||
func SetTestTgFunc(fn func() error) { testTgFunc = fn }
|
||||
|
||||
// reloadTgbotFunc is wired from the web layer; importing tgbot here would be a circular dependency.
|
||||
var reloadTgbotFunc func()
|
||||
|
||||
func SetReloadTgbotFunc(fn func()) { reloadTgbotFunc = fn }
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
@@ -14,7 +13,6 @@ import (
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
)
|
||||
|
||||
func TestValidateRegex(t *testing.T) {
|
||||
@@ -89,84 +87,3 @@ func TestAPITokenMutationRoutesEnforceExpectedScope(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// GHSA-xqqw-jqqv-99h6: a save that keeps 2FA enabled must not be able to
|
||||
// rebind the authenticator without presenting a current code.
|
||||
func TestUpdateSettingRequiresCodeToReplaceTwoFactorToken(t *testing.T) {
|
||||
t.Setenv("XUI_DB_FOLDER", t.TempDir())
|
||||
if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
|
||||
t.Fatalf("InitDB: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = database.CloseDB() })
|
||||
|
||||
settingService := service.SettingService{}
|
||||
if err := settingService.SetTwoFactorToken("ORIGINALSECRET234567"); err != nil {
|
||||
t.Fatalf("seed token: %v", err)
|
||||
}
|
||||
if err := settingService.SetTwoFactorEnable(true); err != nil {
|
||||
t.Fatalf("seed enable: %v", err)
|
||||
}
|
||||
|
||||
post := func(t *testing.T, mutate func(map[string]any)) string {
|
||||
t.Helper()
|
||||
base, err := settingService.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllSetting: %v", err)
|
||||
}
|
||||
raw, err := json.Marshal(base)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
body := map[string]any{}
|
||||
if err := json.Unmarshal(raw, &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
mutate(body)
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal payload: %v", err)
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
NewSettingController(router.Group("/panel/api"))
|
||||
req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/update", strings.NewReader(string(payload)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp := httptest.NewRecorder()
|
||||
router.ServeHTTP(resp, req)
|
||||
return resp.Body.String()
|
||||
}
|
||||
|
||||
t.Run("rebind without code is rejected", func(t *testing.T) {
|
||||
got := post(t, func(body map[string]any) {
|
||||
body["twoFactorEnable"] = true
|
||||
body["twoFactorToken"] = "ATTACKERSECRET567890"
|
||||
})
|
||||
if !strings.Contains(got, `"success":false`) {
|
||||
t.Fatalf("rebind without a 2FA code was accepted: %s", got)
|
||||
}
|
||||
stored, err := settingService.GetTwoFactorToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GetTwoFactorToken: %v", err)
|
||||
}
|
||||
if stored != "ORIGINALSECRET234567" {
|
||||
t.Fatalf("stored 2FA secret = %q, want it unchanged", stored)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ordinary save with redacted token still succeeds", func(t *testing.T) {
|
||||
got := post(t, func(body map[string]any) {
|
||||
body["twoFactorEnable"] = true
|
||||
body["twoFactorToken"] = ""
|
||||
})
|
||||
if !strings.Contains(got, `"success":true`) {
|
||||
t.Fatalf("normal settings save was rejected: %s", got)
|
||||
}
|
||||
stored, err := settingService.GetTwoFactorToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GetTwoFactorToken: %v", err)
|
||||
}
|
||||
if stored != "ORIGINALSECRET234567" {
|
||||
t.Fatalf("stored 2FA secret = %q, want it preserved", stored)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user