Files
3x-ui/internal/web/service/tgbot/tgbot_draft_render_test.go
T
BlindMaster24 1691c9ca2a fix(tgbot): keep the add-client draft with the chat that owns it (#6499)
* fix(tgbot): keep the add-client draft with the chat that owns it

The wizard held one package-level draft for the whole bot. Its steps run on
the ten-goroutine worker pool, so two admins adding a client at the same time
wrote into the same form: whichever step ran last decided the email, the
limits and the attached inbounds of a client the other chat went on to
create, and the attach picker mutated one shared slice from several
goroutines at once as well.

Each chat now gets its own draft, reached only through the chat that owns it
and held for the duration of a step, so a client is created from the values
its own chat collected.

* fix(tgbot): take the wizard's draft lock only for the wizard

A queued report tap held one of the ten worker slots while it waited on the
chat's draft, and every chat that reached answerCallback grew the draft map
even when the admin gate rejected it. Both follow from acquiring the draft
before the gate; the wizard's own steps are the only callers that read it.

The draft is now looked up under the same admin-and-wizard check, addClient
takes the draft its caller locked instead of looking it up again, a submit
drops the entry, and StopBot clears the map with the conversation states.
2026-09-13 19:48:54 +02:00

147 lines
4.5 KiB
Go

package tgbot
import (
"encoding/json"
"html"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/web/locale"
"github.com/mymmrac/telego"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
// clientDraftTestChatID is a chat id no other test drives, so the draft this
// test fills cannot leak into them.
const clientDraftTestChatID = -9001
// Regression test: the draft is sent with ParseMode HTML, so Markdown markers
// were rendered literally and an unescaped value could break the whole message.
func TestClientDraftMessageRendersHTML(t *testing.T) {
draft := addClientDrafts.forChat(clientDraftTestChatID)
t.Cleanup(func() { addClientDrafts.reset(clientDraftTestChatID) })
draft.email = "a@b.c"
draft.comment = "<b>promo</b> & <10 GB>"
draft.tgID = "42"
draft.totalGB, draft.limitIP, draft.expiryTime = 0, 0, 0
draft.receiverInboundIDs = nil
out := (&Tgbot{}).BuildClientDraftMessage(draft)
if !strings.Contains(out, "<b>New client draft</b>") {
t.Errorf("draft title is not HTML markup: %q", out)
}
if strings.Contains(out, "*New client draft*") || strings.Contains(out, "`") {
t.Errorf("draft still carries Markdown markers: %q", out)
}
if strings.Contains(out, "<b>promo</b>") {
t.Errorf("raw comment markup reached the message: %q", out)
}
if !strings.Contains(out, html.EscapeString(draft.comment)) {
t.Errorf("comment is not HTML-escaped: %q", out)
}
}
// botPromptLocalizer renders the two prompts the callback tests drive, with the
// templates the translation files carry; without it I18n returns the bare key.
func botPromptLocalizer(t *testing.T) {
t.Helper()
bundle := i18n.NewBundle(language.MustParse("en-US"))
bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
_ = bundle.AddMessages(language.MustParse("en-US"),
&i18n.Message{ID: "tgbot.messages.email_prompt", Other: "📧 Default Email: {{ .ClientEmail }}\n\nEnter your email."},
&i18n.Message{ID: "tgbot.messages.comment_prompt", Other: "💬 Default Comment: {{ .ClientComment }}\n\nEnter your comment."},
)
orig := locale.LocalizerBot
t.Cleanup(func() { locale.LocalizerBot = orig })
locale.LocalizerBot = i18n.NewLocalizer(bundle, "en-US")
}
// promptTexts serves the methods these prompts touch and returns the text of
// every sendMessage, so a test can check what Telegram would actually parse.
func promptTexts(t *testing.T) (string, func() []string) {
t.Helper()
var mu sync.Mutex
var texts []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
result := any(true)
if r.URL.Path == "/bot"+testBotToken+"/sendMessage" {
var payload struct {
Text string `json:"text"`
}
_ = json.Unmarshal(body, &payload)
mu.Lock()
texts = append(texts, payload.Text)
mu.Unlock()
result = map[string]any{"message_id": 1, "date": 0, "chat": map[string]any{"id": 1, "type": "private"}}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "result": result})
}))
t.Cleanup(srv.Close)
return srv.URL, func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), texts...)
}
}
// Regression test: the wizard's own prompts are HTML-parsed as well, so the
// draft value they echo has to be escaped exactly like the draft card.
func TestAddClientPromptsEscapeDraftValues(t *testing.T) {
botPromptLocalizer(t)
url, texts := promptTexts(t)
swapTestBot(t, url)
draft := addClientDrafts.forChat(1)
origRunning := isRunning
t.Cleanup(func() {
addClientDrafts.reset(1)
isRunning = origRunning
})
isRunning = true
cases := []struct {
name string
data string
value string
}{
{"email prompt", "add_client_ch_default_email", "long<name>@example.com"},
{"comment prompt", "add_client_ch_default_comment", "promo <b>tag</b>"},
}
tb := &Tgbot{}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
draft.email, draft.comment = tc.value, tc.value
tb.answerCallback(&telego.CallbackQuery{
ID: "q1",
From: telego.User{ID: 1},
Data: tc.data,
Message: &telego.Message{Chat: telego.Chat{ID: 1}},
}, true) // admin
sent := texts()
if len(sent) == 0 {
t.Fatalf("no prompt was sent for %s", tc.data)
}
got := sent[len(sent)-1]
if strings.Contains(got, tc.value) {
t.Errorf("prompt = %q, want the draft value escaped", got)
}
if !strings.Contains(got, html.EscapeString(tc.value)) {
t.Errorf("prompt = %q, want it to contain %q", got, html.EscapeString(tc.value))
}
})
}
}