mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 16:04:50 +03:00
fda676e62a
Replace full inbound hydration in Show Info with owner-scoped, no-store reads of one display client or up to 50 WireGuard/AmneziaWG peers. Preserve absolute peer numbering, Host/node endpoint projection, selected tab and IP logs across live traffic updates; keep edit and clone on full detail. Stream ordered NDJSON pages from a single stored inbound snapshot for explicit Export All Peers. Generate an ordered ZIP64 archive with existing client config/link generators; validate page offsets, protocol and total, and reject incomplete or cancelled exports. Renew the per-page HTTP write deadline through the original response writer before gzip wrapping, keeping ordinary endpoint timeouts unchanged. Validated on head0f853351: all 12 CI jobs and Docs CI passed, including 2,350 frontend tests, bounded-info Chromium stories, live-traffic and archive regressions, Go/race, PostgreSQL, and node/Xray E2E. The final review also verified a conflict-free test merge with main38452eac, matching regenerated API contracts and passing focused controller tests, including the real HTTP deadline regression for identity and gzip. The author's synthetic 50,000-peer fixture reduces the uncompressed Show Info response from 2,650,526 to 3,184 bytes. Stored JSON still requires a linear scan per page; explicit ZIP export retains archive data in browser memory. Slow individual writes and reverse-proxy timeouts remain operational limits. No production latency or memory guarantee is implied. Fixes #7330.
322 lines
11 KiB
Go
322 lines
11 KiB
Go
package controller
|
|
|
|
import (
|
|
"compress/gzip"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
gingzip "github.com/gin-contrib/gzip"
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-contrib/sessions/cookie"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/session"
|
|
)
|
|
|
|
func newInboundInfoTestRouter(t *testing.T, middleware ...gin.HandlerFunc) *gin.Engine {
|
|
t.Helper()
|
|
cleanup, err := testpg.IsolatePackage("inbound_info")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(cleanup)
|
|
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
|
router := gin.New()
|
|
router.Use(middleware...)
|
|
router.Use(sessions.Sessions("3x-ui", cookie.NewStore([]byte("inbound-info-test-secret"))))
|
|
router.Use(func(c *gin.Context) {
|
|
if c.Query("anonymous") != "true" {
|
|
session.SetAPIAuthUser(c, &model.User{Id: 1})
|
|
}
|
|
})
|
|
NewInboundController(router.Group("/panel/api/inbounds"))
|
|
return router
|
|
}
|
|
|
|
type delayedExportListener struct {
|
|
net.Listener
|
|
delay time.Duration
|
|
}
|
|
|
|
func (l delayedExportListener) Accept() (net.Conn, error) {
|
|
conn, err := l.Listener.Accept()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &delayedExportConn{Conn: conn, delay: l.delay}, nil
|
|
}
|
|
|
|
type delayedExportConn struct {
|
|
net.Conn
|
|
firstWrite sync.Once
|
|
delay time.Duration
|
|
}
|
|
|
|
func (c *delayedExportConn) Write(p []byte) (int, error) {
|
|
c.firstWrite.Do(func() { time.Sleep(c.delay) })
|
|
return c.Conn.Write(p)
|
|
}
|
|
|
|
func TestInboundPeerExportOutlastsServerWriteTimeout(t *testing.T) {
|
|
router := newInboundInfoTestRouter(t, CaptureInboundPeerExportWriter("/"), gingzip.Gzip(gingzip.DefaultCompression))
|
|
var payload strings.Builder
|
|
payload.WriteString(`{"secretKey":"server-key","clients":[`)
|
|
for i := range 103 {
|
|
if i > 0 {
|
|
payload.WriteByte(',')
|
|
}
|
|
fmt.Fprintf(&payload, `{"email":"client-%05d","privateKey":"secret-%05d"}`, i, i)
|
|
}
|
|
payload.WriteString(`]}`)
|
|
inbound := model.Inbound{UserId: 1, Protocol: model.WireGuard, Tag: "slow-peer-export", Port: 50134, Settings: payload.String()}
|
|
if err := database.GetDB().Create(&inbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
const serverTimeout = 200 * time.Millisecond
|
|
for _, encoding := range []string{"identity", "gzip"} {
|
|
t.Run(encoding, func(t *testing.T) {
|
|
server := httptest.NewUnstartedServer(router)
|
|
server.Config.WriteTimeout = serverTimeout
|
|
// Delay the first network write beyond the server's regular deadline.
|
|
server.Listener = delayedExportListener{Listener: server.Listener, delay: 2 * serverTimeout}
|
|
server.Start()
|
|
defer server.Close()
|
|
client := server.Client()
|
|
client.Timeout = 5 * time.Second
|
|
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("%s/panel/api/inbounds/%d/peerExport", server.URL, inbound.Id), nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Accept-Encoding", encoding)
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
t.Fatalf("export failed after the regular write timeout: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK || resp.Header.Get("Cache-Control") != "no-store" {
|
|
t.Fatalf("export response: status %d, headers %v", resp.StatusCode, resp.Header)
|
|
}
|
|
|
|
var body io.Reader = resp.Body
|
|
if encoding == "gzip" {
|
|
if resp.Header.Get("Content-Encoding") != "gzip" {
|
|
t.Fatal("export did not retain gzip compression")
|
|
}
|
|
compressed, err := gzip.NewReader(body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer compressed.Close()
|
|
body = compressed
|
|
}
|
|
d := json.NewDecoder(body)
|
|
received := 0
|
|
for {
|
|
var page service.InboundInfoPage
|
|
err := d.Decode(&page)
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
if err != nil || page.PeerOffset != received || page.TotalPeers != 103 {
|
|
t.Fatalf("export lost its position at %d: %v", received, err)
|
|
}
|
|
received += checkInboundPeerPage(t, page, received)
|
|
}
|
|
if received != 103 {
|
|
t.Fatalf("export returned %d peers, want 103", received)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func getInboundInfoTestResponse(router *gin.Engine, tail string) *httptest.ResponseRecorder {
|
|
out := httptest.NewRecorder()
|
|
router.ServeHTTP(out, httptest.NewRequest(http.MethodGet, "/panel/api/inbounds/"+tail, nil))
|
|
return out
|
|
}
|
|
|
|
func decodeInboundInfoPage(t *testing.T, out *httptest.ResponseRecorder) service.InboundInfoPage {
|
|
t.Helper()
|
|
var resp struct {
|
|
Success bool
|
|
Obj service.InboundInfoPage
|
|
}
|
|
if err := json.Unmarshal(out.Body.Bytes(), &resp); err != nil || !resp.Success || resp.Obj.Inbound == nil {
|
|
t.Fatalf("inbound info returned HTTP %d: %s (%v)", out.Code, out.Body, err)
|
|
}
|
|
return resp.Obj
|
|
}
|
|
|
|
func TestInboundInfoReturnsOnlyTheDisplayedClient(t *testing.T) {
|
|
router := newInboundInfoTestRouter(t)
|
|
inbound := model.Inbound{
|
|
UserId: 1, Protocol: model.VLESS, Tag: "info-standard", Port: 50133,
|
|
Settings: `{"decryption":"none","clients":[{"email":"selected@test","id":"selected-id"},{"email":"other@test","password":"other-secret"}]}`,
|
|
}
|
|
if err := database.GetDB().Create(&inbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
id := strconv.Itoa(inbound.Id)
|
|
for _, route := range []string{"/info", "/peerExport"} {
|
|
out := getInboundInfoTestResponse(router, id+route+"?anonymous=true")
|
|
if out.Code != http.StatusUnauthorized || out.Body.Len() != 0 {
|
|
t.Fatalf("unauthenticated %s returned HTTP %d: %s", route, out.Code, out.Body)
|
|
}
|
|
}
|
|
if out := getInboundInfoTestResponse(router, id+"/peerExport"); out.Code == http.StatusOK {
|
|
t.Fatalf("regular inbound returned a peer export: %s", out.Body)
|
|
}
|
|
full := getInboundInfoTestResponse(router, "get/"+id)
|
|
if !strings.Contains(full.Body.String(), "other-secret") {
|
|
t.Fatalf("full inbound fixture did not expose the unselected field: %s", full.Body)
|
|
}
|
|
info := getInboundInfoTestResponse(router, id+"/info")
|
|
if info.Code != http.StatusOK || !strings.Contains(info.Body.String(), "selected-id") ||
|
|
strings.Contains(info.Body.String(), "other-secret") || strings.Contains(info.Body.String(), "other@test") {
|
|
t.Fatalf("info HTTP %d returned %s", info.Code, info.Body)
|
|
}
|
|
}
|
|
|
|
func TestInboundInfoPagesAndExportPreserveTunnelPeerOrder(t *testing.T) {
|
|
router := newInboundInfoTestRouter(t)
|
|
sizes := []int{103}
|
|
if os.Getenv("XUI_SCALE_TEST") != "" {
|
|
sizes = append(sizes, 1000, 10000, 50000)
|
|
}
|
|
for _, protocol := range []model.Protocol{model.WireGuard, model.AmneziaWG} {
|
|
for _, size := range sizes {
|
|
t.Run(fmt.Sprintf("%s/%d", protocol, size), func(t *testing.T) {
|
|
var payload strings.Builder
|
|
payload.WriteString(`{"secretKey":"server-key","clients":[`)
|
|
for i := range size {
|
|
if i > 0 {
|
|
payload.WriteByte(',')
|
|
}
|
|
fmt.Fprintf(&payload, `{"email":"client-%05d","privateKey":"secret-%05d"}`, i, i)
|
|
}
|
|
payload.WriteString(`],"peers":[{"privateKey":"legacy-secret"}]}`)
|
|
inbound := model.Inbound{UserId: 1, Protocol: protocol, Tag: fmt.Sprintf("%s-%d", protocol, size), Port: 50134, Settings: payload.String()}
|
|
if err := database.GetDB().Create(&inbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
id := strconv.Itoa(inbound.Id)
|
|
out := getInboundInfoTestResponse(router, id+"/info?page=2")
|
|
page := decodeInboundInfoPage(t, out)
|
|
if page.PeerOffset != 50 || page.TotalPeers != size || strings.Contains(out.Body.String(), "legacy-secret") {
|
|
t.Fatalf("unexpected page metadata: offset=%d count=%d", page.PeerOffset, page.TotalPeers)
|
|
}
|
|
if n := checkInboundPeerPage(t, page, 50); n != 50 {
|
|
t.Fatalf("second page returned %d peers", n)
|
|
}
|
|
if os.Getenv("XUI_SCALE_TEST") != "" {
|
|
full := getInboundInfoTestResponse(router, "get/"+id)
|
|
t.Logf("raw HTTP bodies with %d peers: info page %d bytes, full inbound %d bytes", size, out.Body.Len(), full.Body.Len())
|
|
}
|
|
export := getInboundInfoTestResponse(router, id+"/peerExport")
|
|
if export.Code != http.StatusOK || export.Header().Get("Content-Type") != "application/x-ndjson" {
|
|
t.Fatalf("peer export response=%d type=%q", export.Code, export.Header().Get("Content-Type"))
|
|
}
|
|
d := json.NewDecoder(export.Body)
|
|
received := 0
|
|
for {
|
|
var exported service.InboundInfoPage
|
|
err := d.Decode(&exported)
|
|
if errors.Is(err, io.EOF) {
|
|
break
|
|
}
|
|
if err != nil || exported.TotalPeers != size || exported.PeerOffset != received {
|
|
t.Fatalf("peer export lost its position at %d: %v", received, err)
|
|
}
|
|
received += checkInboundPeerPage(t, exported, received)
|
|
}
|
|
if received != size {
|
|
t.Fatalf("export returned %d peers, want %d", received, size)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func checkInboundPeerPage(t *testing.T, page service.InboundInfoPage, start int) int {
|
|
t.Helper()
|
|
var fields struct {
|
|
Clients []struct {
|
|
Email string
|
|
PrivateKey string
|
|
}
|
|
SecretKey string
|
|
}
|
|
if err := json.Unmarshal([]byte(page.Inbound.Settings), &fields); err != nil || fields.SecretKey != "server-key" ||
|
|
len(fields.Clients) == 0 || len(fields.Clients) > 50 {
|
|
t.Fatalf("bad tunnel page: %d peers, key %q (%v)", len(fields.Clients), fields.SecretKey, err)
|
|
}
|
|
for i, c := range fields.Clients {
|
|
if c.Email != fmt.Sprintf("client-%05d", start+i) || c.PrivateKey != fmt.Sprintf("secret-%05d", start+i) {
|
|
t.Fatalf("wrong peer at position %d: %+v", start+i, c)
|
|
}
|
|
}
|
|
return len(fields.Clients)
|
|
}
|
|
|
|
func TestInboundInfoLegacyMalformedAndOwnerScope(t *testing.T) {
|
|
router := newInboundInfoTestRouter(t)
|
|
for _, tc := range []struct {
|
|
name string
|
|
owner int
|
|
settings string
|
|
total int
|
|
}{
|
|
{name: "legacy peers", owner: 1, settings: `{"clients":[],"peers":[null,{"publicKey":"legacy-public","privateKey":"legacy-private"}]}`, total: 1},
|
|
{name: "empty", owner: 1, settings: `{"clients":[],"peers":[]}`, total: 0},
|
|
{name: "malformed", owner: 1, settings: `{"clients":[{"password":"broken-secret"}]`, total: 0},
|
|
{name: "foreign owner", owner: 2, settings: `{"peers":[{"privateKey":"foreign-secret"}]}`, total: 0},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
inbound := model.Inbound{UserId: tc.owner, Protocol: model.WireGuard, Tag: tc.name, Port: 50135, Settings: tc.settings}
|
|
if err := database.GetDB().Create(&inbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
id := strconv.Itoa(inbound.Id)
|
|
response := getInboundInfoTestResponse(router, id+"/info")
|
|
exported := getInboundInfoTestResponse(router, id+"/peerExport")
|
|
if tc.owner != 1 {
|
|
if strings.Contains(response.Body.String(), "foreign-secret") || strings.Contains(response.Body.String(), `"success":true`) ||
|
|
exported.Code == http.StatusOK || strings.Contains(exported.Body.String(), "foreign-secret") {
|
|
t.Fatalf("foreign inbound exposed by info or export: %s / %s", response.Body, exported.Body)
|
|
}
|
|
return
|
|
}
|
|
page := decodeInboundInfoPage(t, response)
|
|
if page.TotalPeers != tc.total {
|
|
t.Fatalf("total=%d, want %d", page.TotalPeers, tc.total)
|
|
}
|
|
if tc.total == 1 {
|
|
if !strings.Contains(page.Inbound.Settings, "legacy-private") || exported.Code != http.StatusOK ||
|
|
!strings.Contains(exported.Body.String(), "legacy-private") {
|
|
t.Fatalf("legacy peer lost: %s / %s", page.Inbound.Settings, exported.Body)
|
|
}
|
|
} else if strings.Contains(response.Body.String(), "broken-secret") || exported.Code == http.StatusOK {
|
|
t.Fatalf("malformed settings exposed: %s / %s", response.Body, exported.Body)
|
|
}
|
|
})
|
|
}
|
|
}
|