Files
miti99bot/internal/server/router.go
T
tiennm99 31f4e22c4d 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

123 lines
3.9 KiB
Go

package server
import (
"context"
"crypto/subtle"
"errors"
"net/http"
"regexp"
"runtime/debug"
"strings"
"github.com/go-telegram/bot"
"github.com/tiennm99/miti99bot/internal/log"
"github.com/tiennm99/miti99bot/internal/modules"
"github.com/tiennm99/miti99bot/internal/telegram"
)
// cronNameRe limits cron path segments to a safe alphabet so log injection via
// the route is impossible (newlines, ANSI escapes, etc. are rejected at the
// router boundary). Same shape as Telegram command names.
var cronNameRe = regexp.MustCompile(`^[a-z0-9_]{1,32}$`)
// cronAuthHeader is the shared-secret header EventBridge Scheduler attaches when
// invoking /cron/{name}.
const cronAuthHeader = "X-Cron-Token"
// Config wires the router's runtime dependencies.
type Config struct {
Bot *bot.Bot
Registry *modules.Registry
WebhookSecret string
// CronSecret protects /cron/{name} against unauthenticated calls; EventBridge
// Scheduler attaches it as the X-Cron-Token header. Empty means /cron/{name}
// is fully disabled (404).
CronSecret string
}
// New builds the application's HTTP handler. Routes:
//
// GET / → health
// POST /webhook → Telegram update intake (constant-time secret check)
// POST /cron/{name} → EventBridge Scheduler entry (shared-secret check)
//
// Anything else is 404. All routes pass through LogRequests so every
// request emits a structured `req` log line (CloudWatch Logs consumes them
// for 5xx-rate alerts and per-route latency).
func New(cfg Config) http.Handler {
mux := http.NewServeMux()
mux.Handle("/", HealthHandler())
mux.Handle("/webhook", telegram.WebhookHandler(cfg.Bot, cfg.WebhookSecret))
mux.Handle("/cron/", cronHandler(cfg.Registry, cfg.CronSecret))
return LogRequests(mux)
}
func cronHandler(reg *modules.Registry, secret string) http.HandlerFunc {
secretBytes := []byte(secret)
cronDisabled := secret == ""
return func(w http.ResponseWriter, r *http.Request) {
// Rejection paths use bare status codes (no response body) so a
// scanner hitting /cron/ can't fingerprint the route from the
// response text. Status codes remain distinct for CloudWatch
// metric filters; structured log lines carry the reason for
// operator triage.
if cronDisabled {
w.WriteHeader(http.StatusNotFound)
return
}
if r.Method != http.MethodPost {
log.Warn("cron rejected", "reason", "method", "method", r.Method)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
got := []byte(r.Header.Get(cronAuthHeader))
if subtle.ConstantTimeCompare(got, secretBytes) != 1 {
log.Warn("cron rejected", "reason", "secret_mismatch")
w.WriteHeader(http.StatusUnauthorized)
return
}
name := strings.TrimPrefix(r.URL.Path, "/cron/")
if !cronNameRe.MatchString(name) {
log.Warn("cron rejected", "reason", "bad_name", "name", name)
w.WriteHeader(http.StatusNotFound)
return
}
log.Info("cron triggered", "route", "/cron", "name", name)
ctx, cancel := context.WithTimeout(r.Context(), defaultCronTimeout)
defer cancel()
// Recover panics with cron-name context BEFORE the LogRequests
// middleware's safety-net recover sees them — otherwise CloudWatch
// would just show "middleware recovered panic" with no clue which
// scheduled job blew up. EventBridge sees 500 either way.
var dispatchErr error
func() {
defer func() {
if rec := recover(); rec != nil {
log.Error("cron handler panic",
"route", "/cron",
"name", name,
"panic", rec,
"stack", string(debug.Stack()))
dispatchErr = errors.New("cron handler panicked")
}
}()
dispatchErr = modules.DispatchScheduled(ctx, name, reg)
}()
if dispatchErr != nil {
if errors.Is(dispatchErr, modules.ErrCronNotFound) {
w.WriteHeader(http.StatusNotFound)
return
}
log.Error("cron failed", "route", "/cron", "name", name, "err", dispatchErr)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
}