Files
3x-ui/internal/web/service/client_external_link_test.go
T
jason zhang abd320994a Add per-client external link controls (#5650)
* Add enable toggle for external client links

* Document external link enable API fields

* Extend external client link metadata

* Fix external subscription cache status updates

* fix(sub): address the review on per-client external link controls

Blocking: the expiry filter dropped legacy rows. expiry_time was added
without a default, so AutoMigrate makes it nullable and backfills NULL,
and `expiry_time = 0 OR expiry_time > ?` is false for NULL under
three-valued logic — every external link written before the upgrade
vanished from all subscriptions. Add `default:0` on expiry_time and
last_fetch_at, make the predicate NULL-tolerant, and backfill the NULLs
a pre-fix build could already have written.

Rework fetch-status recording. It ran inside the singleflight in-flight
window, so every goroutine parked on the shared fetch waited for a DB
write to commit on the public, unauthenticated subscription path — and
because it was keyed on the row id, waiters and cache hits recorded
nothing, leaving rows that lost the race stuck on "Not fetched yet"
forever. fetchSubscriptionLinks now reports whether it did the network
fetch and expandEntry records afterwards, off the serving path, keyed on
kind+value so every row sharing the URL is stamped by the one fetch.
Keying on value also closes the recycled-rowid hazard: saves delete and
re-insert rows, and SQLite reuses rowids, so an in-flight write could
land on an unrelated client's row. The write no longer discards its
error either.

Drop the inert id round-trip. The panel never sent it, and the byId
branch was guarded by the exact kind+value equality that byKindValue
already keys on, so it could not change an outcome. Matching on
kind+value alone is what actually preserves fetch status across saves.

Reject a negative expiryTime instead of storing a row that is silently
invisible in every subscription — elsewhere a negative expiryTime means
"a duration from first use", so an API caller reusing that convention
got no error and no links.

Drop the ~50 lines of .client-form-* / .client-inbounds-field CSS that
no component renders; it is leftover from the WireGuard PR this one was
split from.

i18n: reuse the already-translated pages.inbounds.leaveBlankToNeverExpire
instead of shipping an English duplicate under pages.clients, and
translate namePrefix, lastFetchAt, lastFetchError and neverFetched into
all 12 non-English locales.

Cover the persistence path that had no test: the fetch-status writer over
a real DB against a failing then a succeeding server, a cache hit writing
nothing, and the negative-expiry rejection.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-08-18 13:55:04 +02:00

125 lines
4.1 KiB
Go

package service
import (
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func externalLinkBool(v bool) *bool {
return &v
}
func TestSetExternalLinksPersistsEnableState(t *testing.T) {
setupBulkDB(t)
db := database.GetDB()
svc := &ClientService{}
rec := model.ClientRecord{Email: "links@example.com", SubID: "sub-links", UUID: "uuid", Enable: true}
if err := db.Create(&rec).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := svc.SetExternalLinksForRecord(rec.Id, []ExternalLinkInput{
{Kind: model.ExternalLinkKindLink, Value: "trojan://pw@example.com:443#on", Remark: "Primary", Enable: externalLinkBool(true), ExpiryTime: 1767225600000},
{Kind: model.ExternalLinkKindSubscription, Value: "https://provider.example/sub", Remark: "Provider", Enable: externalLinkBool(false), NamePrefix: "[zjh] "},
{Kind: model.ExternalLinkKindLink, Value: "trojan://pw@example.net:443#default"},
}); err != nil {
t.Fatalf("set external links: %v", err)
}
rows, err := svc.GetExternalLinksForRecord(rec.Id)
if err != nil {
t.Fatalf("get external links: %v", err)
}
if len(rows) != 3 {
t.Fatalf("rows = %d, want 3", len(rows))
}
if rows[0].Enable == nil || *rows[0].Enable != true {
t.Fatalf("first row enable = %#v, want true", rows[0].Enable)
}
if rows[1].Enable == nil || *rows[1].Enable != false {
t.Fatalf("second row enable = %#v, want false", rows[1].Enable)
}
if rows[2].Enable == nil || *rows[2].Enable != true {
t.Fatalf("omitted enable should default true, got %#v", rows[2].Enable)
}
if rows[0].Remark != "Primary" || rows[0].ExpiryTime != 1767225600000 {
t.Fatalf("first row fields not persisted: %#v", rows[0])
}
if rows[1].Remark != "Provider" || rows[1].NamePrefix != "[zjh] " {
t.Fatalf("subscription fields not persisted: %#v", rows[1])
}
}
func TestSetExternalLinksPreservesFetchStatus(t *testing.T) {
setupBulkDB(t)
db := database.GetDB()
svc := &ClientService{}
rec := model.ClientRecord{Email: "status@example.com", SubID: "sub-status", UUID: "uuid", Enable: true}
if err := db.Create(&rec).Error; err != nil {
t.Fatalf("create client: %v", err)
}
row := model.ClientExternalLink{
ClientId: rec.Id,
Kind: model.ExternalLinkKindSubscription,
Value: "https://provider.example/sub",
Remark: "old",
LastFetchAt: 1767220000000,
LastFetchError: "timeout",
SortIndex: 0,
}
if err := db.Create(&row).Error; err != nil {
t.Fatalf("create external link: %v", err)
}
if err := svc.SetExternalLinksForRecord(rec.Id, []ExternalLinkInput{
{Kind: row.Kind, Value: row.Value, Remark: "new", Enable: externalLinkBool(true)},
}); err != nil {
t.Fatalf("set external links: %v", err)
}
rows, err := svc.GetExternalLinksForRecord(rec.Id)
if err != nil {
t.Fatalf("get external links: %v", err)
}
if len(rows) != 1 {
t.Fatalf("rows = %d, want 1", len(rows))
}
if rows[0].LastFetchAt != row.LastFetchAt || rows[0].LastFetchError != row.LastFetchError {
t.Fatalf("fetch status not preserved: %#v", rows[0])
}
if rows[0].Remark != "new" {
t.Fatalf("editable fields not updated: %#v", rows[0])
}
}
func TestSetExternalLinksRejectsNegativeExpiry(t *testing.T) {
setupBulkDB(t)
db := database.GetDB()
svc := &ClientService{}
rec := model.ClientRecord{Email: "negative@example.com", SubID: "sub-negative", UUID: "uuid", Enable: true}
if err := db.Create(&rec).Error; err != nil {
t.Fatalf("create client: %v", err)
}
err := svc.SetExternalLinksForRecord(rec.Id, []ExternalLinkInput{
{Kind: model.ExternalLinkKindLink, Value: "trojan://pw@example.com:443#neg", ExpiryTime: -86400000},
})
want := "external link expiryTime must be 0 (never) or a future unix millisecond timestamp: trojan://pw@example.com:443#neg\n"
if err == nil || err.Error() != want {
t.Fatalf("err = %v, want %q", err, want)
}
rows, err := svc.GetExternalLinksForRecord(rec.Id)
if err != nil {
t.Fatalf("get external links: %v", err)
}
if len(rows) != 0 {
t.Fatalf("rows = %d, want the rejected save to persist nothing", len(rows))
}
}