mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 22:14:50 +03:00
fix(traffic): require a URI for external traffic notifications (#7263)
External Traffic Inform could be saved enabled with a blank URI. Every traffic tick then built the full payload and POSTed it nowhere, logging one "missing port in address" warning per tick (about 17,000 a day in the report). Refuse the save when the switch is on and the URI is empty. A database that already holds that state skips the notification before the payload is built and warns once per episode, naming why the destination was refused without echoing a malformed URI. Local traffic counters and last-online times are still committed on the skip path. Fixes #7261
This commit is contained in:
Symlink
+1
@@ -0,0 +1 @@
|
||||
/Users/sanaei/Documents/GitHub/3x-ui/frontend/node_modules
|
||||
@@ -4,10 +4,18 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/valyala/fasthttp"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
func stallingListener(t *testing.T) (addr string, release func()) {
|
||||
@@ -89,3 +97,75 @@ func TestInformSkippedWhenNothingToReport(t *testing.T) {
|
||||
t.Fatal("an empty payload must return before touching settings or the network")
|
||||
}
|
||||
}
|
||||
|
||||
func TestXrayTrafficSkipsInvalidExternalInformWithoutLosingCommittedDeltas(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
db := database.GetDB()
|
||||
client := xray.ClientTraffic{Email: "legacy-inform@example.test", Enable: true}
|
||||
if err := db.Create(&client).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var dials atomic.Int32
|
||||
oldClient := externalInformClient
|
||||
externalInformClient = &fasthttp.Client{Dial: func(string) (net.Conn, error) {
|
||||
dials.Add(1)
|
||||
return nil, errors.New("unexpected notification dial")
|
||||
}}
|
||||
t.Cleanup(func() { externalInformClient = oldClient })
|
||||
|
||||
job := NewXrayTrafficJob()
|
||||
const warning = "Skipping external traffic notification: "
|
||||
skipWarnings := func() []string {
|
||||
var reasons []string
|
||||
for _, line := range logger.GetLogs(10240, "WARNING") {
|
||||
if _, reason, found := strings.Cut(line, warning); found {
|
||||
reasons = append(reasons, reason)
|
||||
}
|
||||
}
|
||||
return reasons
|
||||
}
|
||||
countWarnings := func() int { return len(skipWarnings()) }
|
||||
before := countWarnings()
|
||||
run := func(enabled bool, uri, sampleID string) {
|
||||
t.Helper()
|
||||
if err := job.settingService.SetExternalTrafficInformEnable(enabled); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := job.settingService.SetExternalTrafficInformURI(uri); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job.pending = &xrayTrafficSample{id: sampleID, clients: []*xray.ClientTraffic{{Email: client.Email, Up: 11, Down: 7}}}
|
||||
job.Run()
|
||||
}
|
||||
run(true, "https://user:synthetic-secret@example.test:bad/traffic", "malformed")
|
||||
run(true, " \t ", "whitespace")
|
||||
run(true, "", "empty")
|
||||
if got := countWarnings() - before; got != 1 {
|
||||
t.Errorf("warnings during one invalid episode = %d, want 1", got)
|
||||
}
|
||||
|
||||
run(false, "", "disabled")
|
||||
run(true, "http://127.0.0.1/traffic", "blocked")
|
||||
if got := countWarnings() - before; got != 2 {
|
||||
t.Errorf("warnings across two invalid episodes = %d, want 2", got)
|
||||
}
|
||||
// GetLogs returns newest first: a rejected destination must say why it was rejected.
|
||||
if reasons := skipWarnings(); len(reasons) == 0 || reasons[0] != "blocked private/internal address 127.0.0.1" {
|
||||
t.Errorf("blocked destination warning = %q, want the private-address reason", reasons)
|
||||
}
|
||||
for _, line := range logger.GetLogs(32, "WARNING") {
|
||||
if strings.Contains(line, "ExternalTrafficInformURI") && strings.Contains(line, "synthetic-secret") {
|
||||
t.Error("external inform diagnostic disclosed the synthetic credential")
|
||||
}
|
||||
}
|
||||
if got := dials.Load(); got != 0 {
|
||||
t.Errorf("invalid configurations caused %d network dials, want 0", got)
|
||||
}
|
||||
if err := db.First(&client, client.Id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if client.Up != 55 || client.Down != 35 || client.LastOnline <= 0 {
|
||||
t.Errorf("stored counters and activity = (%d, %d, %d), want (55, 35, positive last online)", client.Up, client.Down, client.LastOnline)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,8 @@ type XrayTrafficJob struct {
|
||||
outboundService outbound.OutboundService
|
||||
runMu sync.Mutex
|
||||
pending *xrayTrafficSample
|
||||
|
||||
externalInformInvalidLogged bool
|
||||
}
|
||||
|
||||
type xrayTrafficSample struct {
|
||||
@@ -129,10 +131,12 @@ func (j *XrayTrafficJob) Run() {
|
||||
if needRestart {
|
||||
j.xrayService.SetToNeedRestart()
|
||||
}
|
||||
if ExternalTrafficInformEnable, err := j.settingService.GetExternalTrafficInformEnable(); ExternalTrafficInformEnable {
|
||||
j.informTrafficToExternalAPI(traffics, clientTraffics)
|
||||
} else if err != nil {
|
||||
if enabled, err := j.settingService.GetExternalTrafficInformEnable(); err != nil {
|
||||
logger.Warning("get ExternalTrafficInformEnable failed:", err)
|
||||
} else if enabled {
|
||||
j.informTrafficToExternalAPI(traffics, clientTraffics)
|
||||
} else {
|
||||
j.externalInformInvalidLogged = false
|
||||
}
|
||||
|
||||
// Live online statistics require a running core. The committed sample does not.
|
||||
@@ -256,6 +260,22 @@ func (j *XrayTrafficJob) Run() {
|
||||
}
|
||||
}
|
||||
|
||||
// externalInformDestination never echoes a malformed URI: url.Parse errors quote it,
|
||||
// credentials included. Destination checks name only the host, so those pass through.
|
||||
func externalInformDestination(raw string) (destination, skipReason string) {
|
||||
clean, err := service.SanitizeHTTPURL(raw)
|
||||
if err != nil {
|
||||
return "", "ExternalTrafficInformURI is not a valid http(s) URL"
|
||||
}
|
||||
if clean == "" {
|
||||
return "", "ExternalTrafficInformURI is empty"
|
||||
}
|
||||
if clean, err = service.SanitizePublicHTTPURL(clean, false); err != nil {
|
||||
return "", err.Error()
|
||||
}
|
||||
return clean, ""
|
||||
}
|
||||
|
||||
func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) {
|
||||
if len(inboundTraffics) == 0 && len(clientTraffics) == 0 {
|
||||
return
|
||||
@@ -265,11 +285,15 @@ func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traf
|
||||
logger.Warning("get ExternalTrafficInformURI failed:", err)
|
||||
return
|
||||
}
|
||||
informURL, err = service.SanitizePublicHTTPURL(informURL, false)
|
||||
if err != nil {
|
||||
logger.Warning("ExternalTrafficInformURI blocked:", err)
|
||||
informURL, skipReason := externalInformDestination(informURL)
|
||||
if skipReason != "" {
|
||||
if !j.externalInformInvalidLogged {
|
||||
logger.Warning("Skipping external traffic notification: " + skipReason)
|
||||
j.externalInformInvalidLogged = true
|
||||
}
|
||||
return
|
||||
}
|
||||
j.externalInformInvalidLogged = false
|
||||
requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
|
||||
if err != nil {
|
||||
logger.Warning("parse client/inbound traffic failed:", err)
|
||||
|
||||
@@ -1956,13 +1956,14 @@ func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting,
|
||||
}
|
||||
|
||||
func validateSettingsURLs(allSetting *entity.AllSetting) error {
|
||||
if allSetting.ExternalTrafficInformURI != "" {
|
||||
u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
|
||||
if err != nil {
|
||||
return common.NewError("external traffic inform URI is invalid:", err)
|
||||
}
|
||||
allSetting.ExternalTrafficInformURI = u
|
||||
informURI, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
|
||||
if err != nil {
|
||||
return common.NewError("external traffic inform URI is invalid:", err)
|
||||
}
|
||||
if allSetting.ExternalTrafficInformEnable && informURI == "" {
|
||||
return errors.New("external traffic inform URI is required when enabled")
|
||||
}
|
||||
allSetting.ExternalTrafficInformURI = informURI
|
||||
if allSetting.TgBotAPIServer != "" {
|
||||
u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
)
|
||||
|
||||
func TestSaveExternalTrafficInformRequiresURIWhenEnabled(t *testing.T) {
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
s := new(SettingService)
|
||||
const endpoint = "https://example.test/traffic"
|
||||
for _, tc := range []struct {
|
||||
name, uri, wantURI, wantError string
|
||||
enabled bool
|
||||
}{
|
||||
{name: "disabled with no URI"},
|
||||
{name: "enabled with a valid URI", enabled: true, uri: " " + endpoint + " ", wantURI: endpoint},
|
||||
{name: "enabled with an empty URI", enabled: true, wantURI: endpoint, wantError: "external traffic inform URI is required when enabled"},
|
||||
{name: "enabled with a whitespace URI", enabled: true, uri: " \t ", wantURI: endpoint, wantError: "external traffic inform URI is required when enabled"},
|
||||
{name: "disable and clear"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
settings, err := s.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings.ExternalTrafficInformEnable, settings.ExternalTrafficInformURI = tc.enabled, tc.uri
|
||||
err = s.UpdateAllSetting(settings, SecretClears{})
|
||||
if tc.wantError == "" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if err == nil || err.Error() != tc.wantError {
|
||||
t.Errorf("save error = %v, want %q", err, tc.wantError)
|
||||
}
|
||||
stored, err := s.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.ExternalTrafficInformEnable != tc.enabled || stored.ExternalTrafficInformURI != tc.wantURI {
|
||||
t.Errorf("stored settings = (%t, %q), want (%t, %q)", stored.ExternalTrafficInformEnable, stored.ExternalTrafficInformURI, tc.enabled, tc.wantURI)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user