Files
3x-ui/internal/web/service/tgbot/tgbot_invite_test.go
T
pcxzs 7aa5fc085f feat(tgbot): access levels and /start account binding (#6518)
* feat(tgbot): gate the bot behind three user levels

Every Telegram account that found the bot could run /help, /status and
/usage, and tap any client button it could forge: nothing separated an
account no admin had bound from a customer.

Each update now resolves to stranger, client or admin, and commands are
allowlisted per level so a command added later stays admin-only until it
is listed. A stranger may run /start and /id only, and /start answers with
the ChatID an admin needs to bind it; a stranger's callbacks are answered
and dropped. Client detection reads the same tgId lookup as
clientOwnedByTgUser, so the level gate and the ownership check agree.

The bot also ignores everything outside private chats: authorization keys
on the sender while wizard state keys on the chat, and the two are the
same identity only in a private chat.

* feat(tgbot): bind Telegram accounts through /start deep links

Linking a customer meant the customer sending /id and an admin copying
the ChatID into the client by hand, which does not scale past a few
customers and is easy to get wrong.

The admin client card now offers an invite link, t.me/<bot>?start=<subId>,
and the first account to open it is bound through the existing
SetClientTelegramUserID. A subId already grants the subscription, so
binding gives the holder nothing the token did not. A subscription that
spans several clients binds all of them, and is refused if any part
belongs to another account; re-opening your own link is idempotent.
Unknown and already-claimed tokens share one reply, so the link cannot
be used to probe for valid subIds.

* fix(tgbot): harden invite claims after review

Review of the access-level and binding change found five problems:

- Concurrent claims of one link all read the client as unbound, all bound
  and all were told so, while only the last write held. Resolving and
  binding now share one lock, and a bind that fails part-way through a
  multi-client subscription undoes the bindings it already made.
- A subId has no minimum strength and the bot needs only its public
  username, so /start was an unthrottled guessing oracle. Non-admin claim
  attempts are capped at five per account per hour, the first refused one
  notifies the admins, and the Subscription ID field now says it doubles
  as the bot invite code.
- levelOf expanded every inbound's client JSON on every non-admin update.
  It now reads the indexed tg_id column of the clients table.
- A button tapped in a group chat was dropped unanswered and kept
  spinning, with nothing logged. It is answered now, and each ignored chat
  is logged once.
- The subId was pasted raw into the t.me link, so '#' or '&' truncated it
  and Telegram rejects anything outside A-Za-z0-9_-. The payload is now
  base64url, and a subId too long for the 64-character limit is refused.

* fix(tgbot): answer group chats again and make the claim race test bite

ignoredChat dropped every non-private chat because wizard state was
keyed by chat while authorization keyed on the sender. #6604 on main
re-keyed that state by (chat, user) so admins can drive the bot from a
group, so after the merge the drop only took the whole bot away from
those admins, report keyboards sent to a group included. The level gate
already keys on the sender, so group chats need no special case.

TestConcurrentClaimsBindOnlyOneAccount passed with inviteClaimMu
removed: the first claimant took the pool's idle connection and bound
before the rest had opened theirs, so no two ever raced. It now holds
the inbound write the binds need until every claimant has resolved,
and fails without the lock ("6 accounts told they bound").

TestCommandAllowed restated the commandsByLevel map; TestGateCommand
drives the same allowlist through gateCommand. TestIgnoredChat goes
with the code it pinned.

* docs(tgbot): document access levels and invite links

The command table still said /help and /status answer anyone. An
account no admin has linked now reaches only /start and /id, and a
customer is linked through the client card's Invite Link, whose token
is the Subscription ID. Updated in en, fa, ru and zh.

---------

Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
2026-09-27 13:33:29 +02:00

222 lines
7.6 KiB
Go

package tgbot
import (
"strings"
"sync"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mymmrac/telego"
)
func seedClientRecord(t *testing.T, email, subID string, tgID int64) {
t.Helper()
rec := &model.ClientRecord{Email: email, SubID: subID, TgID: tgID, Enable: true}
if err := database.GetDB().Create(rec).Error; err != nil {
t.Fatalf("seed client %s: %v", email, err)
}
}
// Binding is first-claim-wins: the owner re-tapping is idempotent, and no part of
// a subscription held by someone else is ever reassigned.
func TestResolveInviteToken(t *testing.T) {
tb, _ := newLinksCallbackTgbot(t, ownerMail)
seedClientRecord(t, "free@x", "sub-free", 0)
seedClientRecord(t, "held@x", "sub-held", 5150)
seedClientRecord(t, "shared-a@x", "sub-shared", 0)
seedClientRecord(t, "shared-b@x", "sub-shared", 0)
seedClientRecord(t, "part-mine@x", "sub-part-mine", 7000)
seedClientRecord(t, "part-free@x", "sub-part-mine", 0)
seedClientRecord(t, "part-free2@x", "sub-part-held", 0)
seedClientRecord(t, "part-held@x", "sub-part-held", 9999)
cases := []struct {
name string
token string
from int64
want inviteOutcome
records int
}{
{"unclaimed binds", "sub-free", 7000, inviteBindable, 1},
{"token is trimmed", " sub-free\n", 7000, inviteBindable, 1},
{"owner is idempotent", "sub-held", 5150, inviteAlreadyOwned, 1},
{"someone else's is refused", "sub-held", 7000, inviteTaken, 1},
{"shared subscription binds whole", "sub-shared", 7000, inviteBindable, 2},
{"finishing a partly owned one binds", "sub-part-mine", 7000, inviteBindable, 2},
{"partly held by another is refused", "sub-part-held", 7000, inviteTaken, 2},
{"unknown token", "sub-nope", 7000, inviteInvalid, 0},
{"empty token", "", 7000, inviteInvalid, 0},
{"missing sender", "sub-free", 0, inviteInvalid, 0},
}
for _, c := range cases {
got, records := tb.resolveInviteToken(c.token, c.from)
if got != c.want || len(records) != c.records {
t.Errorf("%s: got (%d, %d records), want (%d, %d records)", c.name, got, len(records), c.want, c.records)
}
}
}
func mustInvitePayload(t *testing.T, subID string) string {
t.Helper()
payload, ok := encodeInvitePayload(subID)
if !ok {
t.Fatalf("encodeInvitePayload(%q) refused", subID)
}
return payload
}
// newInviteTgbot seeds one unbound client whose subId is sub-invite.
func newInviteTgbot(t *testing.T, email string) (*Tgbot, func(string) int) {
t.Helper()
tb, calls := newLinksCallbackTgbot(t, email)
if err := database.GetDB().Model(&model.Inbound{}).Where("1 = 1").
Update("settings", `{"clients":[{"id":"6f1d2c3e-8a4b-4c5d-9e6f-7a8b9c0d1e2f","email":"`+email+`","subId":"sub-invite"}]}`).Error; err != nil {
t.Fatalf("unbind seeded client: %v", err)
}
seedClientRecord(t, email, "sub-invite", 0)
withAdmins(t, 1)
return tb, calls
}
// Regression test: a subId with URL metacharacters was pasted raw into the link,
// so Telegram truncated it; every legal subId that fits must survive the trip.
func TestInvitePayloadRoundTrip(t *testing.T) {
for _, subID := range []string{"a1B2c3D4e5F6g7H8", "team#1", "alice&bob", "x?y=z", "کاربر", strings.Repeat("s", 48)} {
payload, ok := encodeInvitePayload(subID)
if !ok {
t.Errorf("encodeInvitePayload(%q) refused", subID)
continue
}
if strings.Trim(payload, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") != "" {
t.Errorf("payload %q for %q has characters Telegram rejects", payload, subID)
}
if got, ok := decodeInvitePayload(payload); !ok || got != subID {
t.Errorf("round trip of %q = (%q, %v)", subID, got, ok)
}
}
if _, ok := encodeInvitePayload(strings.Repeat("s", 49)); ok {
t.Error("a subId past 64 payload characters must be refused, not truncated")
}
for _, payload := range []string{"", "not base64!", " "} {
if _, ok := decodeInvitePayload(payload); ok {
t.Errorf("decodeInvitePayload(%q) accepted", payload)
}
}
}
// Regression test: accounts opening one link at once all read TgID == 0, all bound
// and were all told so, while only the last write held; exactly one may succeed.
func TestConcurrentClaimsBindOnlyOneAccount(t *testing.T) {
tb, _ := newInviteTgbot(t, "raced@x")
payload := mustInvitePayload(t, "sub-invite")
claimants := []int64{8101, 8102, 8103, 8104, 8105, 8106}
outcomes := make([]inviteOutcome, len(claimants))
start := make(chan struct{})
var wg sync.WaitGroup
for i, id := range claimants {
wg.Add(1)
go func() {
defer wg.Done()
<-start
outcomes[i] = tb.claimInvite(id, id, payload)
}()
}
// Hold the inbound write every bind needs, so all claimants resolve before any
// bind lands; otherwise the first bind outruns the rest and hides the race.
hold := database.GetDB().Begin()
if err := hold.Exec("UPDATE inbounds SET remark = remark").Error; err != nil {
t.Fatalf("hold inbound write: %v", err)
}
close(start)
time.Sleep(300 * time.Millisecond)
if err := hold.Commit().Error; err != nil {
t.Fatalf("release inbound write: %v", err)
}
wg.Wait()
told, holders := 0, 0
for i, id := range claimants {
if outcomes[i] == inviteBindable {
told++
}
if tb.levelOf(id) == levelClient {
holders++
}
}
if told != 1 || holders != 1 {
t.Errorf("%d accounts told they bound, %d holding the client; want 1 and 1", told, holders)
}
}
// A stranger opening a valid invite link must come out of it a client.
func TestClaimInvitePromotesStrangerToClient(t *testing.T) {
const email = "invitee@x"
tb, calls := newInviteTgbot(t, email)
const newcomer = int64(8080)
if got := tb.levelOf(newcomer); got != levelStranger {
t.Fatalf("levelOf before claim = %d, want stranger", got)
}
tb.claimInvite(newcomer, newcomer, mustInvitePayload(t, "sub-invite"))
if got := tb.levelOf(newcomer); got != levelClient {
t.Errorf("levelOf after claim = %d, want client", got)
}
if n := calls("sendMessage"); n != 1 {
t.Errorf("sendMessage calls = %d, want 1 confirmation", n)
}
if outcome, _ := tb.resolveInviteToken("sub-invite", 9999); outcome != inviteTaken {
t.Errorf("second claimant outcome = %d, want taken", outcome)
}
}
// Guessing a subId must stay slow: past five attempts an hour an account is
// refused, and admins are told once per window rather than once per attempt.
func TestInviteAttemptLimit(t *testing.T) {
_, calls := newLinksCallbackTgbot(t, ownerMail)
withAdmins(t, 1, 2)
tb := &Tgbot{}
now := time.Unix(1_700_000_000, 0)
origNow, origBy := inviteAttemptsNow, inviteAttemptsBy
inviteAttemptsNow = func() time.Time { return now }
inviteAttemptsBy = map[int64]*inviteAttempts{}
t.Cleanup(func() { inviteAttemptsNow, inviteAttemptsBy = origNow, origBy })
guesser := &telego.User{ID: 6666, FirstName: "<b>x</b>"}
for i := 1; i <= inviteAttemptLimit; i++ {
if !tb.allowInviteAttempt(guesser) {
t.Fatalf("attempt %d refused, want allowed", i)
}
}
for range 3 {
if tb.allowInviteAttempt(guesser) {
t.Fatal("attempt past the limit allowed")
}
}
if n := calls("sendMessage"); n != 2 {
t.Errorf("sendMessage calls = %d, want 2: one notice per admin, once per window", n)
}
if !tb.allowInviteAttempt(&telego.User{ID: 7777}) {
t.Error("another account was refused by the guesser's limit")
}
now = now.Add(inviteAttemptWindow)
if !tb.allowInviteAttempt(guesser) {
t.Error("attempt after the window refused, want allowed")
}
}
func TestTgUserMentionEscapesName(t *testing.T) {
got := tgUserMention(&telego.User{ID: 42, FirstName: "<b>Eve</b>", Username: "eve"})
want := `<a href="tg://user?id=42">&lt;b&gt;Eve&lt;/b&gt;</a> @eve`
if got != want {
t.Errorf("tgUserMention = %q, want %q", got, want)
}
}