Files
3x-ui/internal/web/service/inbound_tuic_test.go
T
Egor 0054e671f8 feat(tuic): implement native in-process Go TUIC v5 server (#6577)
* feat(tuic): implement native in-process Go TUIC v5 server

- Implement native TUIC v5 protocol server on pure Go using quic-go
- Bridge decrypted TCP/UDP traffic into Xray-core via loopback SOCKS5 inbound
- Support full Xray routing rules (geosite/geoip) and cascading outbounds
- Implement atomic per-client traffic accounting with TotalGB and ExpiryTime
- Add automatic legacy cleanup for older Rust tuic-server binaries, configs, and orphaned processes
- Eliminate external Rust tuic-server downloads from install/CI scripts

* fix(tuic): address traffic accounting, client reload, and socket lifecycle issues

* fix(service): update checkTuicSocksReverseConflict to use bindAddr for listenOverlaps

* fix(tuic): resolve traffic double-accounting, UDP fragmentation, and socket lifecycle issues

* feat(tuic): complete native Go integration and address audit findings

- Integrate an isolated QUIC fork pinned to a specific commit
- Preserve original QUIC dependencies for Xray, Hysteria and Gin
- Apply BBR, CUBIC and Reno to server connections and exported client profiles
- Bridge Xray BBR with correct monotonic time and congestion type conversions
- Handle congestion sender recreation after PMTU changes
- Update congestion control for new connections without restarting the listener
- Preserve existing connections and their selected congestion controller
- Apply per-inbound log levels through the shared panel logger
- Add lifecycle, authentication and TCP/UDP relay events without exposing secrets
- Rate-limit repeated authentication and relay warnings
- Support native and QUIC UDP relay modes on the same listener
- Recover UDP associations after relay worker failures
- Fix TCP relay cancellation, idle shutdown and half-close handling
- Close active sessions when client credentials are revoked or disabled
- Track traffic by immutable client statistics IDs across email and UUID changes
- Prevent ambiguous accounting and duplicate UUIDs within TUIC inbounds
- Persist pending traffic in a durable shutdown journal
- Replay journal batches transactionally without duplicate accounting
- Report server shutdown failures through the shared logger
- Preserve legacy flat and nested TUIC settings compatibility
- Normalize congestion controller values consistently across backend and frontend
- Preserve controller, UDP mode and SNI in client links and subscriptions
- Separate client profile options from server settings in the TUIC form
- Keep certificate path autofill explicit when changing client SNI
- Align UDP packet size validation with protocol limits
- Simplify and localize TUIC field hints and certificate autofill messages
- Add controller, TCP/UDP, logging and live settings update tests
- Add accounting identity, journal replay and shutdown regression tests
- Add relay recovery, session revocation and legacy frontend form tests

* fix(service): alias the TUIC duplicate-UUID subquery for PostgreSQL < 16

syncInboundClients runs a COUNT(*) FROM (subquery) for every client sync,
whatever the protocol. PostgreSQL before 16 rejects a FROM subquery with
no alias, so on the distro PostgreSQL install.sh provisions (14 on Ubuntu
22.04, 15 on Debian 12) every client add or edit failed with SQLSTATE
42601. Reproduced against postgres:15 with the new env-gated test.

* fix(database): create tuic_traffic_receipts through the model migration

AddTuicTrafficBatch issued CREATE TABLE IF NOT EXISTS at runtime, a schema
change outside db.go. The table was invisible to allModels and
migrationModels, so x-ui migrate-db dropped the receipts and a retained
journal could be counted twice after a SQLite to PostgreSQL move. It is
now a GORM model in both lists, and the insert uses OnConflict DoNothing.

* chore(tuic): skip the ICMP-dependent relay test on Windows, drop dead collectors

Go disables SIO_UDP_CONNRESET on Windows, so a dead UDP bridge never fails
a read there and TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure
was red on every Windows run. Server.CollectTotalTraffic and
Manager.CollectTraffic had no caller.

* refactor(tuic): serve TUIC on apernet/quic-go instead of a personal fork

The native server depended on github.com/poise52/quic-go, a personal fork
of apernet/quic-go patched only to pick the congestion controller before
the handshake. That put a second QUIC/TLS stack in the binary that no
upstream security fix reaches. apernet/quic-go is already in the graph
through xray-core and exposes SetCongestionControl, so BBR is now installed
on each accepted connection with Xray's own congestion.UseBBR; the
cross-module BBR adapter is gone.

apernet ships New Reno as its only built-in sender, so a cubic setting is
served as new_reno server-side (clients still get cubic in their profile).
The test inspectors now read the sender under congestionMutex, which the
post-handshake install writes under.

Linux loopback, single stream through Xray: 2428 -> 3383 Mbit/s (bbr).

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-10-03 02:56:02 +02:00

338 lines
10 KiB
Go

package service
import (
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/tuic"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
func TestInjectTuicSocks(t *testing.T) {
cfg := &xray.Config{}
inbounds := []*model.Inbound{
{
Id: 5,
Tag: "tuic-in-5",
Protocol: model.TUIC,
Enable: true,
Settings: `{
"certificate": "dummy-cert",
"private_key": "dummy-key",
"clients": [
{"uuid": "a0000000-0000-0000-0000-000000000001", "password": "pass1", "email": "user1@example.com", "enable": true}
]
}`,
},
}
injectTuicSocks(cfg, inbounds)
if len(cfg.InboundConfigs) != 1 {
t.Fatalf("expected 1 injected SOCKS inbound, got %d", len(cfg.InboundConfigs))
}
sc := cfg.InboundConfigs[0]
if sc.Tag != "tuic-in-5" {
t.Fatalf("expected tag tuic-in-5, got %s", sc.Tag)
}
if sc.Protocol != "socks" {
t.Fatalf("expected protocol socks, got %s", sc.Protocol)
}
expectedPort := tuic.SOCKSPortForInbound(5)
if sc.Port != expectedPort {
t.Fatalf("expected port %d, got %d", expectedPort, sc.Port)
}
if string(sc.Listen) != `"127.0.0.1"` {
t.Fatalf("expected listen 127.0.0.1, got %s", sc.Listen)
}
if string(sc.Sniffing) != tuicEgressSniffingSettings {
t.Fatalf("expected sniffing settings %s, got %s", tuicEgressSniffingSettings, sc.Sniffing)
}
var parsedSettings struct {
Auth string `json:"auth"`
UDP bool `json:"udp"`
}
if err := json.Unmarshal(sc.Settings, &parsedSettings); err != nil {
t.Fatalf("failed to unmarshal settings: %v", err)
}
if parsedSettings.Auth != "noauth" || !parsedSettings.UDP {
t.Fatalf("expected auth=noauth, udp=true, got %+v", parsedSettings)
}
}
func TestCheckTuicSocksConflict(t *testing.T) {
setupConflictDB(t)
// Seed TUIC inbound with ID 10
tuicIb := &model.Inbound{
Id: 10,
Tag: "tuic-10",
Protocol: model.TUIC,
Enable: true,
Listen: "0.0.0.0",
Port: 8443,
Settings: `{"clients":[{"uuid":"a0000000-0000-0000-0000-000000000001","password":"p","email":"u@test.com"}]}`,
}
if err := database.GetDB().Create(tuicIb).Error; err != nil {
t.Fatalf("failed to seed TUIC inbound: %v", err)
}
relayPort := tuic.SOCKSPortForInbound(10)
// Try to create a new TCP inbound on that relayPort on 127.0.0.1
newIb := &model.Inbound{
Tag: "colliding-inbound",
Protocol: model.Mixed,
Enable: true,
Listen: "127.0.0.1",
Port: relayPort,
}
detail, err := checkTuicSocksConflict(database.GetDB(), newIb, 0, transportTCP)
if err != nil {
t.Fatalf("checkTuicSocksConflict error: %v", err)
}
if detail == nil {
t.Fatalf("expected conflict on port %d, got none", relayPort)
}
if detail.Tag != "tuic-10" {
t.Fatalf("expected conflict tag tuic-10, got %s", detail.Tag)
}
}
func TestCheckTuicSocksReverseConflict(t *testing.T) {
setupConflictDB(t)
targetPort := tuic.SOCKSPortForInbound(20)
// Seed existing inbound on targetPort on 127.0.0.1
existing := &model.Inbound{
Id: 99,
Tag: "existing-on-relay-port",
Protocol: model.Mixed,
Enable: true,
Listen: "127.0.0.1",
Port: targetPort,
}
if err := database.GetDB().Create(existing).Error; err != nil {
t.Fatalf("failed to seed existing inbound: %v", err)
}
detail, err := checkTuicSocksReverseConflict(database.GetDB(), 20)
if err != nil {
t.Fatalf("checkTuicSocksReverseConflict error: %v", err)
}
if detail == nil {
t.Fatalf("expected reverse conflict for id 20 on port %d, got none", targetPort)
}
if detail.Tag != "existing-on-relay-port" {
t.Fatalf("expected tag existing-on-relay-port, got %s", detail.Tag)
}
}
func TestDesiredTuicInstances(t *testing.T) {
setupConflictDB(t)
ib := &model.Inbound{
Id: 30,
Tag: "tuic-desired-test",
Protocol: model.TUIC,
Enable: true,
Listen: "0.0.0.0",
Port: 9443,
Settings: `{
"certificate": "cert",
"private_key": "key",
"clients": [
{"uuid": "a0000000-0000-0000-0000-000000000001", "password": "p1", "email": "active@test.com", "enable": true},
{"uuid": "a0000000-0000-0000-0000-000000000002", "password": "p2", "email": "disabled@test.com", "enable": true}
]
}`,
}
if err := database.GetDB().Create(ib).Error; err != nil {
t.Fatalf("failed to seed inbound: %v", err)
}
// Add client traffic entry disabling disabled@test.com
ct := &xray.ClientTraffic{
InboundId: 30,
Email: "disabled@test.com",
Enable: false,
}
if err := database.GetDB().Create(ct).Error; err != nil {
t.Fatalf("failed to seed client traffic: %v", err)
}
svc := &InboundService{}
instances, err := svc.DesiredTuicInstances()
if err != nil {
t.Fatalf("DesiredTuicInstances failed: %v", err)
}
found := false
for _, inst := range instances {
if inst.Id == 30 {
found = true
if len(inst.Clients) != 1 || inst.Clients[0].Email != "active@test.com" {
t.Fatalf("expected only active@test.com, got %+v", inst.Clients)
}
}
}
if !found {
t.Fatal("expected to find instance for inbound 30")
}
}
func TestCheckForwardedPortsConflict_CollidesWithTuicSocksPort(t *testing.T) {
setupConflictDB(t)
seedInboundConflict(t, "tuic-1", "0.0.0.0", 8443, model.TUIC, ``, `{"clients":[{"uuid":"u","password":"p","email":"e"}]}`)
var tuicInbound model.Inbound
if err := database.GetDB().Where("tag = ?", "tuic-1").First(&tuicInbound).Error; err != nil {
t.Fatalf("read seeded row: %v", err)
}
relayPort := tuic.SOCKSPortForInbound(tuicInbound.Id)
svc := &InboundService{}
ctx, err := svc.loadPortConflictContext(database.GetDB(), nil)
if err != nil {
t.Fatalf("loadPortConflictContext: %v", err)
}
hit := svc.checkForwardedPortsConflict(ctx, fmt.Sprintf("%d", relayPort))
if !strings.Contains(hit, "SOCKS5") {
t.Fatalf("expected a collision naming the TUIC inbound's SOCKS5 relay port, got %q", hit)
}
}
func TestCheckTuicSocksConflict_DisabledInboundRetainsReservation(t *testing.T) {
setupConflictDB(t)
seedInboundConflict(t, "tuic-disabled", "0.0.0.0", 8443, model.TUIC, ``, `{"clients":[{"uuid":"u","password":"p","email":"e"}]}`)
var tuicIb model.Inbound
if err := database.GetDB().Where("tag = ?", "tuic-disabled").First(&tuicIb).Error; err != nil {
t.Fatalf("read seeded row: %v", err)
}
if err := database.GetDB().Model(&tuicIb).Update("enable", false).Error; err != nil {
t.Fatalf("disable inbound: %v", err)
}
relayPort := tuic.SOCKSPortForInbound(tuicIb.Id)
testIb := &model.Inbound{
Tag: "conflict-test",
Protocol: model.VLESS,
Listen: "127.0.0.1",
Port: relayPort,
Enable: true,
}
conflict, err := checkTuicSocksConflict(database.GetDB(), testIb, 0, transportTCP)
if err != nil {
t.Fatalf("checkTuicSocksConflict: %v", err)
}
if conflict == nil {
t.Fatal("expected conflict on disabled TUIC inbound's SOCKS port, got nil")
}
if conflict.InboundID != tuicIb.Id {
t.Fatalf("expected conflict with inbound %d, got %d", tuicIb.Id, conflict.InboundID)
}
}
func TestCheckTuicSocksRelayCollision(t *testing.T) {
setupConflictDB(t)
// Seed first TUIC inbound with ID 1
ib1 := &model.Inbound{
Id: 1,
Tag: "tuic-1",
Protocol: model.TUIC,
Enable: true,
Listen: "0.0.0.0",
Port: 8443,
Settings: `{"clients":[{"uuid":"a0000000-0000-0000-0000-000000000001","password":"p","email":"u1@test.com"}]}`,
}
if err := database.GetDB().Create(ib1).Error; err != nil {
t.Fatalf("seed ib1: %v", err)
}
// ID 1001 wraps to the same relay port (64001) as ID 1
conflict, err := checkTuicSocksRelayCollision(database.GetDB(), 1001)
if err != nil {
t.Fatalf("checkTuicSocksRelayCollision: %v", err)
}
if conflict == nil {
t.Fatal("expected collision between ID 1001 and ID 1, got nil")
}
if conflict.InboundID != 1 {
t.Fatalf("expected collision with inbound 1, got %d", conflict.InboundID)
}
}
func TestTuicSocksSelfConflict(t *testing.T) {
ib := &model.Inbound{
Protocol: model.TUIC,
Listen: "127.0.0.1",
Port: tuic.SOCKSPortForInbound(5),
}
errStr := tuicSocksSelfConflict(ib, 5)
if errStr == "" {
t.Fatal("expected self conflict error string, got empty")
}
if !strings.Contains(errStr, "own SOCKS5 relay port") {
t.Fatalf("unexpected error string: %s", errStr)
}
// Different port should not conflict
ib.Port = 9999
if diff := tuicSocksSelfConflict(ib, 5); diff != "" {
t.Fatalf("expected no conflict for different port, got %s", diff)
}
}
func TestInboundTuicServerParsesLegacyFlatSettings(t *testing.T) {
server := inboundTuicServer(string(model.TUIC), `{"certificate":"/cert.pem","private_key":"/secret-key.pem","congestion_control":" CuBiC ","udp_relay_mode":"quic","sni":"profile.example"}`)
if server == nil {
t.Fatal("expected legacy flat TUIC settings")
}
if server.CongestionControl != "cubic" || server.UDPRelayMode != "quic" || server.SNI != "profile.example" {
t.Fatalf("legacy flat fields were not normalized: %+v", server)
}
if server.PrivateKey != "" {
t.Fatal("client preview exposed the inbound private key")
}
}
func TestNormalizeTuicSettingsCanonicalizesCongestionAndPacketLimit(t *testing.T) {
ib := &model.Inbound{Protocol: model.TUIC, Settings: `{"congestion_control":"RENO","max_udp_relay_packet_size":65507,"server":{"congestion_control":" CuBiC ","max_udp_relay_packet_size":65500}}`}
if err := normalizeTuicSettings(ib); err != nil {
t.Fatalf("normalizeTuicSettings: %v", err)
}
var got struct {
CongestionControl string `json:"congestion_control"`
MaxPacketSize int `json:"max_udp_relay_packet_size"`
Server struct {
CongestionControl string `json:"congestion_control"`
MaxPacketSize int `json:"max_udp_relay_packet_size"`
} `json:"server"`
}
if err := json.Unmarshal([]byte(ib.Settings), &got); err != nil {
t.Fatalf("unmarshal normalized settings: %v", err)
}
if got.CongestionControl != "new_reno" || got.Server.CongestionControl != "cubic" {
t.Fatalf("congestion controllers were not canonicalized: %+v", got)
}
if got.MaxPacketSize != 65245 || got.Server.MaxPacketSize != 65245 {
t.Fatalf("packet limits were not clamped: %+v", got)
}
ib.Settings = `{"server":{"congestion_control":"experimental"}}`
if err := normalizeTuicSettings(ib); err == nil {
t.Fatal("unsupported congestion controller was accepted")
}
}