Files
archipelago/connectors/telegram/telegram_test.go
T

127 lines
4.2 KiB
Go

package main
import (
"context"
json "encoding/json/v2"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/samcharles93/archipelago/sdk/connector"
)
const fakeToken = "123:plainly-fake" //nolint:gosec // a fake bot token the test checks never leaks
// fakeBot serves one batch of updates, then nothing, and records the replies
// to taps.
type fakeBot struct {
mu sync.Mutex
updates string
served bool
replies []string
// idle is called when the batch has been served and fetched past.
idle func()
}
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, "/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)
}
})
}
}
// 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)
}
}