Files
miti99bot/internal/modules/util/handlers_test.go
T
tiennm99 d77b478b67 refactor: audit-driven hygiene pass across modules and infra
Concurrency
- lolschedule: serialize subscriber Get→mutate→Put via state.subscribersMu;
  the single-slot list was previously losing writes under concurrent
  /lolschedule_subscribe.
- trading: PriceClient memoises its default *http.Client so /trade_stats
  reuses TLS connections across held tickers.

Observability
- server/log_middleware: defer the req log line and recover panics so a
  panicking cron handler still emits the structured req entry CloudWatch
  filters on for 5xx alerting.
- server/router (cron): inner recover with cron-name context captures the
  panicking job before the middleware's safety net does.
- telegram/webhook: rune-safe truncation in dispatch logs — Vietnamese,
  Korean, and emoji previews no longer ship as garbled bytes.
- lolschedule/api_client: same rune-safe fix for error-body log truncation.
- telegram/webhook: gate the post-recover WriteHeader(200) so a panicking
  handler that already touched w doesn't trigger superfluous-WriteHeader.

Correctness
- twentyq: clearGame error during solved-relaunch is logged instead of
  silently swallowed (was a permanent deadlock vector on KV failure).
- misc /mstats: KV read failure replies "Could not load stats. Try again
  later." to the user instead of returning into the dispatcher; matches the
  pattern other modules use.
- migrate_cf_data trading-audit-dump: surface f.Close error so a truncated
  JSONL never passes silently as a complete audit dump.

Operator ergonomics
- migrate_cf_data (all 4 subcommands): signal.NotifyContext for SIGINT /
  SIGTERM. Ctrl-C mid-Scan now propagates cleanly instead of leaving a
  half-converted DynamoDB table.
- ai/ratelimit: doc the Lambda-recycle memory bound to match keylock.Map
  so a future reviewer doesn't re-flag the unbounded map.

I/O-changing (user-approved)
- lolschedule daily push auto-prunes subscribers whose Telegram error
  matches a terminal marker (blocked / deactivated / chat gone). Transient
  errors keep the chat on the list. Subscribe message updated to mention
  the auto-cleanup.
- twentyq seed pool grown 50 → 178; repeat-collision threshold moves from
  ~9 plays to ~17 (birthday paradox).
- util /info flipped Public → Protected — chat/thread/sender IDs are no
  longer enumerable by every group member.
- cmd/server WriteTimeout 6min → 75s (cron 60s + 15s slack). No-op on
  Lambda; matters only for local non-Lambda runs.
- webhook + cron rejection paths drop response bodies (no fingerprintable
  text for internet scanners hitting the public Function URL). Status
  codes preserved for CloudWatch metrics; structured log lines carry the
  rejection reason for operator triage.

Tests added: TestTruncateRunes, TestRunDailyPush_PrunesDeadSubscribers,
TestIsTerminalSendError, TestInfo_DeniedToNonOwner,
TestInfo_DeniedToChannelMessageNoFrom, plus owner-allowed counterparts.
2026-05-16 13:35:00 +07:00

130 lines
4.0 KiB
Go

package util_test
import (
"context"
"strings"
"testing"
"github.com/go-telegram/bot/models"
"github.com/tiennm99/miti99bot/internal/modules"
"github.com/tiennm99/miti99bot/internal/modules/util"
"github.com/tiennm99/miti99bot/internal/storage"
"github.com/tiennm99/miti99bot/internal/testutil"
)
// installUtil builds a registry with the util module + auth that admits the
// supplied owner so /stickerid (private) dispatches.
func installUtil(t *testing.T, ownerID int64) *testutil.RecordingBot {
t.Helper()
rb := testutil.NewRecordingBot(t)
reg, err := modules.Build([]string{"util"},
map[string]modules.Factory{"util": util.New},
storage.NewMemoryProvider(), modules.BuildOptions{})
if err != nil {
t.Fatalf("Build: %v", err)
}
modules.Install(rb.Bot, reg, modules.Auth{BotOwnerID: ownerID})
return rb
}
func TestInfo_PrivateChat_OwnerAllowed(t *testing.T) {
// /info is Protected — sender must be the bot owner to get a reply.
rb := installUtil(t, 42)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewPrivateMessage(42, "/info"))
got := rb.LastSent().Text()
for _, want := range []string{"chat id: 42", "thread id: n/a", "sender id: 42"} {
if !strings.Contains(got, want) {
t.Errorf("info reply missing %q; got %q", want, got)
}
}
}
func TestInfo_GroupChat_OwnerAllowed(t *testing.T) {
rb := installUtil(t, 7)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewGroupMessage(-100, 7, "/info"))
got := rb.LastSent().Text()
for _, want := range []string{"chat id: -100", "sender id: 7"} {
if !strings.Contains(got, want) {
t.Errorf("info reply missing %q; got %q", want, got)
}
}
}
func TestInfo_DeniedToNonOwner(t *testing.T) {
// Non-admin sender → Protected denies silently (no reply, no leak of
// the command's existence).
rb := installUtil(t, 999)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewGroupMessage(-100, 7, "/info"))
if calls := rb.Sent(); len(calls) != 0 {
t.Errorf("non-owner /info replied: %+v", calls)
}
}
func TestInfo_DeniedToChannelMessageNoFrom(t *testing.T) {
// Channel posts have no From. Protected denies (no sender to check).
rb := installUtil(t, 0)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewChannelMessage(-200, "/info"))
if calls := rb.Sent(); len(calls) != 0 {
t.Errorf("channel-post /info replied: %+v", calls)
}
}
func TestHelp_RendersHTML(t *testing.T) {
rb := installUtil(t, 0)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewPrivateMessage(1, "/help"))
calls := rb.Sent()
if len(calls) == 0 {
t.Fatal("/help produced no reply")
}
got := calls[len(calls)-1]
if got.Form["parse_mode"] != string(models.ParseModeHTML) {
t.Errorf("/help parse_mode = %q, want HTML", got.Form["parse_mode"])
}
if !strings.Contains(got.Text(), "<b>util</b>") {
t.Errorf("/help body missing util section; got %q", got.Text())
}
}
func TestStickerID_NoReply_ShowsUsage(t *testing.T) {
rb := installUtil(t, 999)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewPrivateMessage(999, "/stickerid"))
got := rb.LastSent().Text()
if !strings.Contains(got, "Reply to a sticker") {
t.Errorf("stickerid usage missing; got %q", got)
}
}
func TestStickerID_WithStickerReply_EchoesFileID(t *testing.T) {
rb := installUtil(t, 999)
upd := testutil.NewPrivateMessage(999, "/stickerid")
upd.Message.ReplyToMessage = &models.Message{
Sticker: &models.Sticker{
FileID: "AAA-file-id",
FileUniqueID: "uniq",
SetName: "TestSet",
Emoji: "🎉",
},
}
rb.Bot.ProcessUpdate(context.Background(), upd)
got := rb.LastSent().Text()
for _, want := range []string{"AAA-file-id", "uniq", "TestSet", "🎉"} {
if !strings.Contains(got, want) {
t.Errorf("stickerid reply missing %q; got %q", want, got)
}
}
}
func TestStickerID_DeniedToNonOwner(t *testing.T) {
rb := installUtil(t, 999)
rb.Bot.ProcessUpdate(context.Background(), testutil.NewPrivateMessage(7, "/stickerid"))
if calls := rb.Sent(); len(calls) != 0 {
t.Errorf("non-owner /stickerid replied: %+v", calls)
}
}