Files
archipelago/connectors/telegram/telegram_test.go
T
sam 48019ec868
publish / publish (push) Successful in 1m22s
fix(telegram): a long message goes out in parts instead of failing for ever
The connector sent title and body as one sendMessage, so any notification
over Telegram's 4096 UTF-16 unit limit was refused with 'message is too
long' and, because a delivery is retried until the channel confirms it,
retried every ten minutes for ever without ever arriving. The chat channel
had its own splitter; both now share one in sdk/telegramtext, which counts
UTF-16 units rather than runes so an emoji-heavy body isn't over the limit
either.
2026-11-18 00:36:44 +11:00

199 lines
6.9 KiB
Go

package main
import (
"context"
json "encoding/json/v2"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"github.com/samcharles93/archipelago/sdk/connector"
"github.com/samcharles93/archipelago/sdk/telegramtext"
)
const fakeToken = "123:plainly-fake" //nolint:gosec // a fake bot token the test checks never leaks
// fakeBot serves one batch of updates, then nothing, records the replies to
// taps and the messages delivered, and refuses a message over Telegram's limit
// the way the Bot API does.
type fakeBot struct {
mu sync.Mutex
updates string
served bool
replies []string
sent []sentMessage
lastError string
// idle is called when the batch has been served and fetched past.
idle func()
}
// sentMessage is one sendMessage the fake bot accepted.
type sentMessage struct {
Text string
Button bool
}
func (f *fakeBot) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
switch {
case strings.HasSuffix(r.URL.Path, "/getUpdates"):
result := "[]"
if !f.served {
result, f.served = f.updates, true
} else if f.idle != nil {
f.idle()
}
_, _ = w.Write([]byte(`{"ok":true,"result":` + result + `}`))
case strings.HasSuffix(r.URL.Path, "/sendMessage"):
var body struct {
Text string `json:"text"`
ReplyMark map[string]any `json:"reply_markup"`
}
_ = json.UnmarshalRead(r.Body, &body)
if telegramtext.Units(body.Text) > telegramtext.MaxLen {
f.lastError = "sendMessage: Bad Request: message is too long"
_, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: message is too long"}`))
return
}
f.sent = append(f.sent, sentMessage{Text: body.Text, Button: body.ReplyMark != nil})
id := len(f.sent)
_, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":` + strconv.Itoa(id) + `}}`))
case strings.HasSuffix(r.URL.Path, "/answerCallbackQuery"):
var body struct {
Text string `json:"text"`
}
_ = json.UnmarshalRead(r.Body, &body)
f.replies = append(f.replies, body.Text)
_, _ = w.Write([]byte(`{"ok":true,"result":true}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}
func tap(updateID, userID, data string) string {
return `{"update_id":` + updateID + `,"callback_query":{"id":"q` + updateID + `","data":"` + data +
`","from":{"id":` + userID + `,"first_name":"Sam"}}}`
}
// TestOnlyAnAllowedUsersTapIsAnAnswer guards who may answer an approval: a tap
// becomes an approval.answer event only from a user the operator allowed and
// only for a well-formed button, and the cursor moves past every update so a
// refused tap isn't fetched again.
func TestOnlyAnAllowedUsersTapIsAnAnswer(t *testing.T) {
tests := []struct {
name string
update string
wantEvent string
wantReply string
}{
{name: "an allowed user's approve is an answer", update: tap("7", "42", "answer:yes:req-1"), wantEvent: `"approved":true`, wantReply: "Answer received."},
{name: "an allowed user's deny is an answer", update: tap("7", "42", "answer:no:req-1"), wantEvent: `"approved":false`, wantReply: "Answer received."},
{name: "a user who isn't allowed is refused", update: tap("7", "99", "answer:yes:req-1"), wantReply: "You're not allowed to answer this."},
{name: "a malformed button is refused", update: tap("7", "42", "answer:maybe:req-1"), wantReply: "That button is out of date."},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bot := &fakeBot{updates: "[" + tt.update + "]"}
srv := httptest.NewServer(bot)
defer srv.Close()
tg, err := newTelegram(connector.Config{
Settings: map[string]string{"user_ids": "42"}, Secrets: map[string]string{"bot.token": fakeToken},
})
if err != nil {
t.Fatal(err)
}
tg.api = srv.URL
ctx, cancel := context.WithCancel(t.Context())
bot.idle = cancel
var got []connector.Event
var cursor string
_ = tg.Listen(ctx, "", func(events []connector.Event, c string) error {
got, cursor = events, c
return nil
})
if cursor != "8" {
t.Fatalf("cursor = %q, want 8", cursor)
}
if tt.wantEvent == "" && len(got) != 0 {
t.Fatalf("got events %v, want none", got)
}
if tt.wantEvent != "" && (len(got) != 1 || got[0].Type != answerType || !strings.Contains(string(got[0].Fields), tt.wantEvent) ||
!strings.Contains(string(got[0].Fields), `"by":"telegram:42"`)) {
t.Fatalf("got events %v, want one answer with %s by telegram:42", got, tt.wantEvent)
}
if len(bot.replies) != 1 || bot.replies[0] != tt.wantReply {
t.Fatalf("replies = %q, want %q", bot.replies, tt.wantReply)
}
})
}
}
// TestALongMessageGoesOutInParts guards the delivery of a long notification: the
// Bot API refuses one message over 4096 UTF-16 code units, and a delivery the
// host can never complete is retried for ever, so the body goes out as several
// messages in order, with the request's buttons on the last one.
func TestALongMessageGoesOutInParts(t *testing.T) {
body := strings.Repeat("the findings run to a length no single message holds. ", 300)
bot := &fakeBot{}
srv := httptest.NewServer(bot)
defer srv.Close()
tg, err := newTelegram(connector.Config{
Settings: map[string]string{"user_ids": "42"}, Secrets: map[string]string{"bot.token": fakeToken},
})
if err != nil {
t.Fatal(err)
}
tg.api = srv.URL
input, err := json.Marshal(map[string]string{"title": "Investigation finished", "body": body, "approval_request_id": "req-1"})
if err != nil {
t.Fatal(err)
}
if _, err := tg.Deliver(t.Context(), "message", input, "k"); err != nil {
t.Fatalf("deliver: %v (bot said %q)", err, bot.lastError)
}
if len(bot.sent) < 2 {
t.Fatalf("sent %d messages, want the body split over several", len(bot.sent))
}
for i, m := range bot.sent {
if units := telegramtext.Units(m.Text); units > telegramtext.MaxLen {
t.Errorf("message %d is %d units, over the limit", i+1, units)
}
if last := i == len(bot.sent)-1; m.Button != last {
t.Errorf("message %d buttons = %v, want them on the last only", i+1, m.Button)
}
}
if got := strings.Join(textsOf(bot.sent), ""); got != "Investigation finished\n\n"+body {
t.Errorf("the parts carry %d characters, want the whole message in order", len(got))
}
}
func textsOf(sent []sentMessage) []string {
out := make([]string, 0, len(sent))
for _, m := range sent {
out = append(out, m.Text)
}
return out
}
// TestAFailedCallNeverShowsTheToken guards the bot token: it travels in the
// request URL, and a transport error must not carry that URL into a log.
func TestAFailedCallNeverShowsTheToken(t *testing.T) {
srv := httptest.NewServer(http.NotFoundHandler())
srv.Close()
tg, err := newTelegram(connector.Config{
Settings: map[string]string{"user_ids": "42"}, Secrets: map[string]string{"bot.token": fakeToken},
})
if err != nil {
t.Fatal(err)
}
tg.api = srv.URL
_, err = tg.Deliver(t.Context(), "message", []byte(`{"title":"hi"}`), "k")
if err == nil || strings.Contains(err.Error(), fakeToken) {
t.Fatalf("err = %v, want an error without the token", err)
}
}