package main import ( "context" json "encoding/json/v2" "maps" "net/http" "net/http/httptest" "slices" "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) } } // TestAChatMessageReachesOnlyAnAllowedUser guards the chat_message delivery: a // workflow names the chat, and a chat that isn't an allowed user's is refused // permanently, so the bot can't be made to message anyone else. func TestAChatMessageReachesOnlyAnAllowedUser(t *testing.T) { tests := []struct { name string chatID string wantSent []string wantErr bool }{ {name: "an allowed user's chat gets the text", chatID: "42", wantSent: []string{"cleaned web-1"}}, {name: "another chat is refused", chatID: "7", wantErr: true}, {name: "a chat id that isn't a number is refused", chatID: "ops", wantErr: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { 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{"chat_id": tt.chatID, "text": "cleaned web-1"}) if err != nil { t.Fatal(err) } _, err = tg.Deliver(t.Context(), "chat_message", input, "k") if tt.wantErr != (err != nil) || (err != nil && !connector.IsPermanent(err)) { t.Fatalf("deliver error = %v, want an error: %v, permanent", err, tt.wantErr) } if got := textsOf(bot.sent); !slices.Equal(got, tt.wantSent) { t.Fatalf("sent %q, want %q", got, tt.wantSent) } }) } } func startMessage(updateID, userID, text string) string { return `{"update_id":` + updateID + `,"message":{"text":"` + text + `","chat":{"id":` + userID + `},"from":{"id":` + userID + `,"first_name":"Sam","username":"sam"}}}` } // TestOnlyAnAllowedUsersStartCodeIsALink guards account linking: the event // names the sender as "telegram:", which core requires of this // connector, and carries the code unchanged. A user who isn't allowed, and a // /start with no code, emit nothing. func TestOnlyAnAllowedUsersStartCodeIsALink(t *testing.T) { tests := []struct { name string update string want string wantReply bool }{ { name: "an allowed user's code is a link", update: startMessage("7", "42", "/start c0de_-X"), want: `{"by":"telegram:42","code":"c0de_-X","name":"@sam","chat_id":"42"}`, }, { name: "a code addressed to the bot by name is a link", update: startMessage("7", "42", "/start@archie_bot c0de"), want: `{"by":"telegram:42","code":"c0de","name":"@sam","chat_id":"42"}`, }, {name: "a bare start is ignored", update: startMessage("7", "42", "/start")}, {name: "other text is ignored", update: startMessage("7", "42", "hello there")}, {name: "a user who isn't allowed is refused", update: startMessage("7", "99", "/start c0de"), wantReply: true}, } 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 _ = tg.Listen(ctx, "", func(events []connector.Event, _ string) error { got = events return nil }) if tt.want == "" { if len(got) != 0 { t.Fatalf("got events %v, want none", got) } if tt.wantReply != (len(bot.sent) == 1) { t.Fatalf("sent %v, want a refusal: %v", bot.sent, tt.wantReply) } return } if len(got) != 1 || got[0].Type != linkType { t.Fatalf("got events %v, want one %s", got, linkType) } var gotFields, wantFields map[string]string if err := json.Unmarshal(got[0].Fields, &gotFields); err != nil { t.Fatal(err) } if err := json.Unmarshal([]byte(tt.want), &wantFields); err != nil { t.Fatal(err) } if !maps.Equal(gotFields, wantFields) { t.Fatalf("fields = %v, want %v", gotFields, wantFields) } }) } }