feat(telegram): split connector into home validator + remote bot
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 1s
CI / deploy (pull_request) Failing after 2m6s
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 53s
CI / gate (pull_request) Successful in 1s
CI / deploy (pull_request) Failing after 2m6s
Move all Telegram egress off the main host. The single connector held the bot token, long-polled Telegram and answered the gateway/backend over the trusted internal network, so the whole component (including login validation) shared fate with its VPN sidecar. Split it into two binaries that share the token: - cmd/validator (home, no VPN): Mini App initData + Login Widget HMAC only, never calls the Bot API. The gateway dials it for Telegram auth, so game login is now independent of Telegram reachability. - cmd/bot (remote): Bot API long-poll + sendMessage, the only component reaching Telegram. It holds no inbound port — it dials the gateway over a new reverse mTLS bot-link (pkg/proto/botlink/v1) and executes the send commands the gateway pushes. The gateway funnels sends to the bot-link: out-of-app push is fire-and-forget (at-most-once, dropped if no bot is connected); the backend admin broadcasts reach a gateway-served relay that forwards them and awaits the bot's ack (SendToUser/SendToGameChannel contract preserved). mTLS (pkg/mtls) is the one inter-service link that leaves the trusted segment; validator<->gateway and the relay stay plaintext internal. The bot is Telegram-rate-limited. One bot now; the gateway bot registry, an owns_updates flag and per-command ids leave seams for N later. Webhook rejected (one URL per token, adds inbound + a static address). The unified test contour runs the split (the bot keeps its VPN sidecar and dials the gateway by its internal name; bot-link certs from deploy/gen-certs.sh, generated in CI). The prod wiring — the bot on a separate host (no VPN), the gateway bot-link port published, PROD_ certs with scheduled rotation, an SSH deploy of both hosts together — is the deferred final stage (PRERELEASE.md TX, Stage 18). Docs: ARCHITECTURE, PRERELEASE (phase TX), platform/telegram + gateway + backend + deploy READMEs, FUNCTIONAL(+ru), CLAUDE.md, .env.example.
This commit is contained in:
@@ -13,6 +13,7 @@ import (
|
||||
tgbot "github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"go.uber.org/zap"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
// Config configures the bot wrapper.
|
||||
@@ -25,6 +26,10 @@ type Config struct {
|
||||
TestEnv bool
|
||||
// MiniAppURL is the base URL of the Mini App launch button.
|
||||
MiniAppURL string
|
||||
// SendRatePerSecond caps outbound sends (Notify and SendText) to respect the
|
||||
// Telegram Bot API flood limits; 0 disables the limiter. The burst equals the
|
||||
// per-second rate.
|
||||
SendRatePerSecond int
|
||||
}
|
||||
|
||||
// Bot wraps a Telegram Bot API client and the Mini App launch URL.
|
||||
@@ -32,6 +37,9 @@ type Bot struct {
|
||||
api *tgbot.Bot
|
||||
miniAppURL string
|
||||
log *zap.Logger
|
||||
// limiter throttles outbound sends to stay under the Bot API flood limits; nil
|
||||
// disables throttling.
|
||||
limiter *rate.Limiter
|
||||
}
|
||||
|
||||
// New builds the bot wrapper, registering the /start handler and a default handler
|
||||
@@ -42,6 +50,9 @@ func New(cfg Config, log *zap.Logger) (*Bot, error) {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
t := &Bot{miniAppURL: cfg.MiniAppURL, log: log}
|
||||
if cfg.SendRatePerSecond > 0 {
|
||||
t.limiter = rate.NewLimiter(rate.Limit(cfg.SendRatePerSecond), cfg.SendRatePerSecond)
|
||||
}
|
||||
|
||||
opts := []tgbot.Option{
|
||||
tgbot.WithDefaultHandler(t.handleStart),
|
||||
@@ -85,6 +96,9 @@ func (t *Bot) Run(ctx context.Context) {
|
||||
// Notify sends a notification message with a Mini App launch button that opens the
|
||||
// app at startParam (empty opens the lobby).
|
||||
func (t *Bot) Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
if err := t.throttle(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := t.api.SendMessage(ctx, &tgbot.SendMessageParams{
|
||||
ChatID: chatID,
|
||||
Text: text,
|
||||
@@ -95,10 +109,22 @@ func (t *Bot) Notify(ctx context.Context, chatID int64, text, buttonText, startP
|
||||
|
||||
// SendText sends a plain text message with no markup (admin use).
|
||||
func (t *Bot) SendText(ctx context.Context, chatID int64, text string) error {
|
||||
if err := t.throttle(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := t.api.SendMessage(ctx, &tgbot.SendMessageParams{ChatID: chatID, Text: text})
|
||||
return err
|
||||
}
|
||||
|
||||
// throttle blocks until the rate limiter admits one send, or ctx is cancelled. It
|
||||
// is a no-op when no limiter is configured.
|
||||
func (t *Bot) throttle(ctx context.Context) error {
|
||||
if t.limiter == nil {
|
||||
return nil
|
||||
}
|
||||
return t.limiter.Wait(ctx)
|
||||
}
|
||||
|
||||
// handleStart replies to /start (with an optional deep-link payload) and to any
|
||||
// other message with a Mini App launch button.
|
||||
func (t *Bot) handleStart(ctx context.Context, api *tgbot.Bot, update *models.Update) {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/keepalive"
|
||||
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
// clientKeepaliveTime is how often the bot pings the gateway to hold the WAN
|
||||
// connection open (kept above the gateway's MinTime to avoid an enforcement ban).
|
||||
clientKeepaliveTime = 30 * time.Second
|
||||
// clientKeepaliveTimeout bounds the wait for a keepalive ping reply.
|
||||
clientKeepaliveTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// ClientConfig configures the bot's dial side of the reverse bot-link.
|
||||
type ClientConfig struct {
|
||||
// GatewayAddr is the gateway bot-link endpoint to dial.
|
||||
GatewayAddr string
|
||||
// InstanceID identifies this bot to the gateway.
|
||||
InstanceID string
|
||||
// OwnsUpdates reports whether this bot runs the exclusive getUpdates long-poll.
|
||||
OwnsUpdates bool
|
||||
// Creds is the transport credentials for the dial (mutual TLS in production,
|
||||
// built from pkg/mtls).
|
||||
Creds credentials.TransportCredentials
|
||||
// ReconnectDelay is the pause before re-dialing after the stream ends.
|
||||
ReconnectDelay time.Duration
|
||||
}
|
||||
|
||||
// Client maintains the long-lived bot-link to the gateway, executing the commands
|
||||
// it receives and re-dialing after any break.
|
||||
type Client struct {
|
||||
cfg ClientConfig
|
||||
exec *Executor
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// NewClient builds the bot-link client over the executor.
|
||||
func NewClient(cfg ClientConfig, exec *Executor, log *zap.Logger) *Client {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &Client{cfg: cfg, exec: exec, log: log}
|
||||
}
|
||||
|
||||
// Run dials the gateway and keeps the bot-link open, re-dialing after each break,
|
||||
// until ctx is cancelled. The gRPC connection auto-reconnects the transport; this
|
||||
// loop re-opens the Link stream on top of it.
|
||||
func (c *Client) Run(ctx context.Context) error {
|
||||
conn, err := grpc.NewClient(c.cfg.GatewayAddr,
|
||||
grpc.WithTransportCredentials(c.cfg.Creds),
|
||||
grpc.WithStatsHandler(otelgrpc.NewClientHandler()),
|
||||
grpc.WithKeepaliveParams(keepalive.ClientParameters{
|
||||
Time: clientKeepaliveTime,
|
||||
Timeout: clientKeepaliveTimeout,
|
||||
PermitWithoutStream: true,
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
client := botlinkv1.NewBotLinkClient(conn)
|
||||
|
||||
for ctx.Err() == nil {
|
||||
if err := c.serve(ctx, client); err != nil && ctx.Err() == nil {
|
||||
c.log.Warn("bot-link stream ended", zap.Error(err))
|
||||
}
|
||||
if !sleep(ctx, c.cfg.ReconnectDelay) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// serve opens one Link stream, registers with a Hello, then executes commands and
|
||||
// replies with an Ack each until the stream ends.
|
||||
func (c *Client) serve(ctx context.Context, client botlinkv1.BotLinkClient) error {
|
||||
stream, err := client.Link(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := stream.Send(&botlinkv1.FromBot{Msg: &botlinkv1.FromBot_Hello{Hello: &botlinkv1.Hello{
|
||||
InstanceId: c.cfg.InstanceID,
|
||||
OwnsUpdates: c.cfg.OwnsUpdates,
|
||||
}}}); err != nil {
|
||||
return err
|
||||
}
|
||||
c.log.Info("bot-link connected", zap.String("gateway", c.cfg.GatewayAddr), zap.Bool("owns_updates", c.cfg.OwnsUpdates))
|
||||
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := msg.GetCommand()
|
||||
if cmd == nil {
|
||||
continue
|
||||
}
|
||||
delivered, herr := c.exec.Handle(ctx, cmd)
|
||||
ack := &botlinkv1.Ack{CommandId: cmd.GetCommandId(), Delivered: delivered}
|
||||
if herr != nil {
|
||||
ack.Error = herr.Error()
|
||||
}
|
||||
if err := stream.Send(&botlinkv1.FromBot{Msg: &botlinkv1.FromBot_Ack{Ack: ack}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sleep waits for d or until ctx is cancelled, reporting whether it waited the full
|
||||
// duration.
|
||||
func sleep(ctx context.Context, d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
)
|
||||
|
||||
// testLinkServer registers one bot, pushes a single Notify command, and records the
|
||||
// Ack the client returns.
|
||||
type testLinkServer struct {
|
||||
botlinkv1.UnimplementedBotLinkServer
|
||||
acks chan *botlinkv1.Ack
|
||||
}
|
||||
|
||||
func (s *testLinkServer) Link(stream grpc.BidiStreamingServer[botlinkv1.FromBot, botlinkv1.ToBot]) error {
|
||||
hello, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if hello.GetHello() == nil {
|
||||
return fmt.Errorf("first message was not Hello")
|
||||
}
|
||||
if err := stream.Send(&botlinkv1.ToBot{Command: &botlinkv1.Command{
|
||||
CommandId: "c1",
|
||||
Payload: &botlinkv1.Command_Notify{Notify: &telegramv1.NotifyRequest{
|
||||
ExternalId: "12345", Kind: "your_turn",
|
||||
Payload: yourTurnPayload("7c9e6679-7425-40de-944b-e07fc1f90ae7"), Language: "en",
|
||||
}},
|
||||
}}); err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
msg, err := stream.Recv()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ack := msg.GetAck(); ack != nil {
|
||||
s.acks <- ack
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClientServesCommands verifies the bot client dials, registers, executes a
|
||||
// pushed command through the executor, and acks it.
|
||||
func TestClientServesCommands(t *testing.T) {
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
ts := &testLinkServer{acks: make(chan *botlinkv1.Ack, 1)}
|
||||
srv := grpc.NewServer()
|
||||
botlinkv1.RegisterBotLinkServer(srv, ts)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
sender := &fakeSender{}
|
||||
client := NewClient(ClientConfig{
|
||||
GatewayAddr: lis.Addr().String(),
|
||||
InstanceID: "test",
|
||||
Creds: insecure.NewCredentials(),
|
||||
ReconnectDelay: 50 * time.Millisecond,
|
||||
}, NewExecutor(sender, 0, nil), nil)
|
||||
|
||||
go func() { _ = client.Run(t.Context()) }()
|
||||
|
||||
select {
|
||||
case ack := <-ts.acks:
|
||||
if ack.GetCommandId() != "c1" || !ack.GetDelivered() {
|
||||
t.Errorf("ack = %+v, want command_id c1 delivered=true", ack)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("server received no ack")
|
||||
}
|
||||
// The channel receive above happens-after the client wrote the sender call.
|
||||
if len(sender.notify) != 1 || sender.notify[0].chatID != 12345 {
|
||||
t.Errorf("sender notify calls = %+v, want one call to chat 12345", sender.notify)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Package botlink is the bot side of the reverse Telegram channel: the bot dials
|
||||
// the gateway over mTLS (pkg/proto/botlink/v1), opens one long-lived Link stream,
|
||||
// and executes the send Commands the gateway pushes, replying with an Ack per
|
||||
// command. It keeps the Bot API token and egress on the remote bot host with no
|
||||
// inbound port. See docs/ARCHITECTURE.md.
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/render"
|
||||
)
|
||||
|
||||
// Sender delivers Telegram messages to a chat. *bot.Bot implements it.
|
||||
type Sender interface {
|
||||
// Notify sends a notification with a Mini App launch button to chatID.
|
||||
Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error
|
||||
// SendText sends a plain text message to chatID.
|
||||
SendText(ctx context.Context, chatID int64, text string) error
|
||||
}
|
||||
|
||||
// Executor turns a bot-link Command into a Bot API send. The delivered flag mirrors
|
||||
// the former connector semantics (false when the kind is not rendered out-of-app,
|
||||
// the user never started the bot, or no channel is configured); a returned error is
|
||||
// an unexpected or malformed failure carried back in the Ack error field, distinct
|
||||
// from a clean not-delivered.
|
||||
type Executor struct {
|
||||
sender Sender
|
||||
channelID int64
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// NewExecutor builds the executor over a bot sender and the optional game channel.
|
||||
func NewExecutor(sender Sender, channelID int64, log *zap.Logger) *Executor {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &Executor{sender: sender, channelID: channelID, log: log}
|
||||
}
|
||||
|
||||
// Handle dispatches one command to the matching Bot API send.
|
||||
func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, error) {
|
||||
switch p := cmd.GetPayload().(type) {
|
||||
case *botlinkv1.Command_Notify:
|
||||
return e.notify(ctx, p.Notify)
|
||||
case *botlinkv1.Command_SendToUser:
|
||||
return e.sendToUser(ctx, p.SendToUser)
|
||||
case *botlinkv1.Command_SendToChannel:
|
||||
return e.sendToChannel(ctx, p.SendToChannel)
|
||||
default:
|
||||
return false, fmt.Errorf("botlink: empty command")
|
||||
}
|
||||
}
|
||||
|
||||
// notify renders an out-of-app push and sends it with a Mini App launch button.
|
||||
func (e *Executor) notify(ctx context.Context, req *telegramv1.NotifyRequest) (bool, error) {
|
||||
msg, ok := render.Render(req.GetKind(), req.GetPayload(), req.GetLanguage())
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := e.sender.Notify(ctx, chat, msg.Text, msg.ButtonText, msg.StartParam); err != nil {
|
||||
e.log.Warn("notify delivery failed", zap.String("kind", req.GetKind()), zap.Error(err))
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// sendToUser sends an admin text message to one user.
|
||||
func (e *Executor) sendToUser(ctx context.Context, req *telegramv1.SendToUserRequest) (bool, error) {
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := e.sender.SendText(ctx, chat, req.GetText()); err != nil {
|
||||
e.log.Warn("send to user failed", zap.Error(err))
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// sendToChannel posts an admin text message to the bot's game channel.
|
||||
func (e *Executor) sendToChannel(ctx context.Context, req *telegramv1.SendToGameChannelRequest) (bool, error) {
|
||||
if e.channelID == 0 {
|
||||
return false, fmt.Errorf("botlink: game channel is not configured")
|
||||
}
|
||||
if err := e.sender.SendText(ctx, e.channelID, req.GetText()); err != nil {
|
||||
e.log.Warn("send to channel failed", zap.Error(err))
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// parseChatID converts a Telegram identity external_id into a numeric chat id.
|
||||
func parseChatID(externalID string) (int64, error) {
|
||||
id, err := strconv.ParseInt(externalID, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid external_id %q", externalID)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package botlink
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
|
||||
"scrabble/pkg/fbs/scrabblefb"
|
||||
botlinkv1 "scrabble/pkg/proto/botlink/v1"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
)
|
||||
|
||||
// fakeSender records the delivery calls the executor makes.
|
||||
type fakeSender struct {
|
||||
notify []notifyCall
|
||||
text []textCall
|
||||
err error
|
||||
}
|
||||
|
||||
type notifyCall struct {
|
||||
chatID int64
|
||||
text, buttonText, startParam string
|
||||
}
|
||||
type textCall struct {
|
||||
chatID int64
|
||||
text string
|
||||
}
|
||||
|
||||
func (f *fakeSender) Notify(_ context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
f.notify = append(f.notify, notifyCall{chatID, text, buttonText, startParam})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeSender) SendText(_ context.Context, chatID int64, text string) error {
|
||||
f.text = append(f.text, textCall{chatID, text})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func yourTurnPayload(gameID string) []byte {
|
||||
b := flatbuffers.NewBuilder(0)
|
||||
gid := b.CreateString(gameID)
|
||||
scrabblefb.YourTurnEventStart(b)
|
||||
scrabblefb.YourTurnEventAddGameId(b, gid)
|
||||
b.Finish(scrabblefb.YourTurnEventEnd(b))
|
||||
return b.FinishedBytes()
|
||||
}
|
||||
|
||||
func notifyCmd(externalID, kind string, payload []byte, language string) *botlinkv1.Command {
|
||||
return &botlinkv1.Command{Payload: &botlinkv1.Command_Notify{Notify: &telegramv1.NotifyRequest{
|
||||
ExternalId: externalID, Kind: kind, Payload: payload, Language: language,
|
||||
}}}
|
||||
}
|
||||
|
||||
func TestExecutorNotifyDelivers(t *testing.T) {
|
||||
const gameID = "7c9e6679-7425-40de-944b-e07fc1f90ae7"
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), notifyCmd("12345", "your_turn", yourTurnPayload(gameID), "en"))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered {
|
||||
t.Fatal("expected delivered=true")
|
||||
}
|
||||
if len(sender.notify) != 1 {
|
||||
t.Fatalf("notify calls = %d, want 1", len(sender.notify))
|
||||
}
|
||||
if got := sender.notify[0]; got.chatID != 12345 || got.startParam != "g"+gameID {
|
||||
t.Errorf("notify call = %+v, want chatID 12345 startParam g%s", got, gameID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorNotifySkipsUnrenderedKind(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
delivered, err := exec.Handle(context.Background(), notifyCmd("12345", "opponent_moved", nil, "en"))
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if delivered {
|
||||
t.Error("expected delivered=false for an unrendered kind")
|
||||
}
|
||||
if len(sender.notify) != 0 {
|
||||
t.Errorf("sender called %d times, want 0", len(sender.notify))
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorNotifyInvalidExternalID(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), notifyCmd("not-a-number", "your_turn", yourTurnPayload("g"), "en")); err == nil {
|
||||
t.Error("expected an error for a non-numeric external_id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorSendToUser(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 0, nil)
|
||||
cmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToUser{SendToUser: &telegramv1.SendToUserRequest{ExternalId: "999", Text: "hi"}}}
|
||||
delivered, err := exec.Handle(context.Background(), cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered || len(sender.text) != 1 || sender.text[0].chatID != 999 || sender.text[0].text != "hi" {
|
||||
t.Errorf("send to user = %v / calls %+v", delivered, sender.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorSendToChannel(t *testing.T) {
|
||||
channelCmd := &botlinkv1.Command{Payload: &botlinkv1.Command_SendToChannel{SendToChannel: &telegramv1.SendToGameChannelRequest{Text: "news"}}}
|
||||
|
||||
t.Run("unconfigured", func(t *testing.T) {
|
||||
exec := NewExecutor(&fakeSender{}, 0, nil)
|
||||
if _, err := exec.Handle(context.Background(), channelCmd); err == nil {
|
||||
t.Error("expected an error when no channel is configured")
|
||||
}
|
||||
})
|
||||
t.Run("configured", func(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
exec := NewExecutor(sender, 555, nil)
|
||||
delivered, err := exec.Handle(context.Background(), channelCmd)
|
||||
if err != nil {
|
||||
t.Fatalf("handle: %v", err)
|
||||
}
|
||||
if !delivered || len(sender.text) != 1 || sender.text[0].chatID != 555 {
|
||||
t.Errorf("send to channel: %+v", sender.text)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
// Package config loads the Telegram connector's environment configuration.
|
||||
// Package config loads the environment configuration for the two Telegram
|
||||
// platform binaries: the home validator (HMAC of Mini App / Login Widget data, no
|
||||
// Telegram egress) and the remote bot (Bot API long-poll + sendMessage, dialing
|
||||
// the gateway over the reverse mTLS bot-link). The bot token lives in both
|
||||
// processes — the validator needs it only as the HMAC secret (ARCHITECTURE.md §12).
|
||||
package config
|
||||
|
||||
import (
|
||||
@@ -6,73 +10,173 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
)
|
||||
|
||||
// Config is the Telegram connector's runtime configuration, read from the
|
||||
// environment. The bot token lives only in this process (ARCHITECTURE.md §12).
|
||||
type Config struct {
|
||||
// Token is the Telegram Bot API token (TELEGRAM_BOT_TOKEN, required). It both
|
||||
// authenticates the Bot API client and is the HMAC secret for Mini App initData
|
||||
// and Login Widget validation.
|
||||
// ValidatorConfig is the home validator's runtime configuration.
|
||||
type ValidatorConfig struct {
|
||||
// Token is the Telegram Bot API token (TELEGRAM_BOT_TOKEN, required). The
|
||||
// validator uses it only as the HMAC secret for Mini App initData and Login
|
||||
// Widget validation; it never calls the Bot API.
|
||||
Token string
|
||||
// GameChannelID is the chat id of the bot's game channel for SendToGameChannel
|
||||
// (TELEGRAM_GAME_CHANNEL_ID, optional; 0 disables channel posts).
|
||||
GameChannelID int64
|
||||
// GRPCAddr is the listen address of the connector gRPC server that gateway and
|
||||
// backend call (TELEGRAM_GRPC_ADDR, default :9091).
|
||||
// GRPCAddr is the listen address of the validator gRPC server the gateway calls
|
||||
// (TELEGRAM_VALIDATOR_GRPC_ADDR, default :9091).
|
||||
GRPCAddr string
|
||||
// MiniAppURL is the HTTPS origin of the Mini App registered with BotFather; it
|
||||
// is the base of every launch button, to which a deep-link adds a startapp
|
||||
// query parameter (TELEGRAM_MINIAPP_URL, required).
|
||||
MiniAppURL string
|
||||
// APIBaseURL overrides the Bot API host (TELEGRAM_API_BASE_URL, optional;
|
||||
// default https://api.telegram.org) — used for a local mock or a self-hosted
|
||||
// Bot API server.
|
||||
APIBaseURL string
|
||||
// TestEnv routes the Bot API client to Telegram's test environment
|
||||
// (.../bot<token>/test/METHOD) (TELEGRAM_TEST_ENV=true, default false).
|
||||
TestEnv bool
|
||||
// LogLevel is the zap log level (TELEGRAM_LOG_LEVEL, default info).
|
||||
LogLevel string
|
||||
// Telemetry configures the OpenTelemetry providers (shared bootstrap).
|
||||
Telemetry pkgtel.Config
|
||||
}
|
||||
|
||||
// Load reads the connector configuration from the environment, applying defaults
|
||||
// and validating the required fields.
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
Token: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
||||
GRPCAddr: envOr("TELEGRAM_GRPC_ADDR", ":9091"),
|
||||
MiniAppURL: os.Getenv("TELEGRAM_MINIAPP_URL"),
|
||||
APIBaseURL: os.Getenv("TELEGRAM_API_BASE_URL"),
|
||||
TestEnv: os.Getenv("TELEGRAM_TEST_ENV") == "true",
|
||||
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
|
||||
// BotConfig is the remote bot's runtime configuration.
|
||||
type BotConfig struct {
|
||||
// Token is the Telegram Bot API token (TELEGRAM_BOT_TOKEN, required).
|
||||
Token string
|
||||
// GameChannelID is the chat id of the bot's game channel for the admin channel
|
||||
// post (TELEGRAM_GAME_CHANNEL_ID, optional; 0 disables channel posts).
|
||||
GameChannelID int64
|
||||
// MiniAppURL is the HTTPS origin of the Mini App registered with BotFather; it is
|
||||
// the base of every launch button (TELEGRAM_MINIAPP_URL, required).
|
||||
MiniAppURL string
|
||||
// APIBaseURL overrides the Bot API host (TELEGRAM_API_BASE_URL, optional;
|
||||
// default https://api.telegram.org).
|
||||
APIBaseURL string
|
||||
// TestEnv routes the Bot API client to Telegram's test environment
|
||||
// (TELEGRAM_TEST_ENV=true, default false).
|
||||
TestEnv bool
|
||||
// OwnsUpdates reports whether this bot runs the exclusive getUpdates long-poll
|
||||
// (TELEGRAM_OWNS_UPDATES, default true). Exactly one bot per token must own it.
|
||||
OwnsUpdates bool
|
||||
// SendRatePerSecond caps outbound Bot API sends to respect Telegram flood limits
|
||||
// (TELEGRAM_SEND_RATE_PER_SECOND, default 25; 0 disables the limiter).
|
||||
SendRatePerSecond int
|
||||
// BotLink configures the reverse mTLS channel the bot dials.
|
||||
BotLink BotLinkClientConfig
|
||||
// LogLevel is the zap log level (TELEGRAM_LOG_LEVEL, default info).
|
||||
LogLevel string
|
||||
// Telemetry configures the OpenTelemetry providers (shared bootstrap).
|
||||
Telemetry pkgtel.Config
|
||||
}
|
||||
|
||||
// BotLinkClientConfig is the bot's dial side of the reverse bot-link.
|
||||
type BotLinkClientConfig struct {
|
||||
// GatewayAddr is the gateway bot-link endpoint to dial (TELEGRAM_GATEWAY_ADDR,
|
||||
// required), e.g. "gateway.example.com:9443".
|
||||
GatewayAddr string
|
||||
// ServerName is the gateway certificate's expected SNI / CN
|
||||
// (TELEGRAM_BOTLINK_SERVER_NAME, required).
|
||||
ServerName string
|
||||
// InstanceID identifies this bot to the gateway (TELEGRAM_INSTANCE_ID, default
|
||||
// the hostname).
|
||||
InstanceID string
|
||||
// CertFile, KeyFile and CAFile are the bot client certificate, its key and the
|
||||
// CA bundle that signs the gateway server certificate (required).
|
||||
CertFile string
|
||||
KeyFile string
|
||||
CAFile string
|
||||
// ReconnectDelay is the pause before re-dialing after the stream ends
|
||||
// (TELEGRAM_BOTLINK_RECONNECT_DELAY, default 2s).
|
||||
ReconnectDelay time.Duration
|
||||
}
|
||||
|
||||
const (
|
||||
defaultValidatorGRPCAddr = ":9091"
|
||||
defaultBotReconnectDelay = 2 * time.Second
|
||||
defaultSendRatePerSecond = 25
|
||||
)
|
||||
|
||||
// LoadValidator reads the validator configuration from the environment.
|
||||
func LoadValidator() (ValidatorConfig, error) {
|
||||
cfg := ValidatorConfig{
|
||||
Token: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
||||
GRPCAddr: envOr("TELEGRAM_VALIDATOR_GRPC_ADDR", defaultValidatorGRPCAddr),
|
||||
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
|
||||
}
|
||||
if v := strings.TrimSpace(os.Getenv("TELEGRAM_GAME_CHANNEL_ID")); v != "" {
|
||||
id, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("config: TELEGRAM_GAME_CHANNEL_ID %q: %w", v, err)
|
||||
}
|
||||
cfg.GameChannelID = id
|
||||
tel, err := loadTelemetry("scrabble-telegram-validator")
|
||||
if err != nil {
|
||||
return ValidatorConfig{}, err
|
||||
}
|
||||
tel := pkgtel.DefaultConfig("scrabble-telegram")
|
||||
cfg.Telemetry = tel
|
||||
if cfg.Token == "" {
|
||||
return ValidatorConfig{}, fmt.Errorf("config: TELEGRAM_BOT_TOKEN is required")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadBot reads the bot configuration from the environment.
|
||||
func LoadBot() (BotConfig, error) {
|
||||
cfg := BotConfig{
|
||||
Token: os.Getenv("TELEGRAM_BOT_TOKEN"),
|
||||
MiniAppURL: os.Getenv("TELEGRAM_MINIAPP_URL"),
|
||||
APIBaseURL: os.Getenv("TELEGRAM_API_BASE_URL"),
|
||||
TestEnv: os.Getenv("TELEGRAM_TEST_ENV") == "true",
|
||||
OwnsUpdates: os.Getenv("TELEGRAM_OWNS_UPDATES") != "false",
|
||||
SendRatePerSecond: defaultSendRatePerSecond,
|
||||
LogLevel: envOr("TELEGRAM_LOG_LEVEL", "info"),
|
||||
BotLink: BotLinkClientConfig{
|
||||
GatewayAddr: os.Getenv("TELEGRAM_GATEWAY_ADDR"),
|
||||
ServerName: os.Getenv("TELEGRAM_BOTLINK_SERVER_NAME"),
|
||||
InstanceID: envOr("TELEGRAM_INSTANCE_ID", hostname()),
|
||||
CertFile: os.Getenv("TELEGRAM_BOTLINK_TLS_CERT"),
|
||||
KeyFile: os.Getenv("TELEGRAM_BOTLINK_TLS_KEY"),
|
||||
CAFile: os.Getenv("TELEGRAM_BOTLINK_TLS_CA"),
|
||||
},
|
||||
}
|
||||
var err error
|
||||
if cfg.GameChannelID, err = envInt64("TELEGRAM_GAME_CHANNEL_ID", 0); err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
if cfg.SendRatePerSecond, err = envInt("TELEGRAM_SEND_RATE_PER_SECOND", defaultSendRatePerSecond); err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
if cfg.BotLink.ReconnectDelay, err = envDuration("TELEGRAM_BOTLINK_RECONNECT_DELAY", defaultBotReconnectDelay); err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
tel, err := loadTelemetry("scrabble-telegram-bot")
|
||||
if err != nil {
|
||||
return BotConfig{}, err
|
||||
}
|
||||
cfg.Telemetry = tel
|
||||
|
||||
if cfg.Token == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOT_TOKEN is required")
|
||||
}
|
||||
if cfg.MiniAppURL == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_MINIAPP_URL is required")
|
||||
}
|
||||
if cfg.BotLink.GatewayAddr == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_GATEWAY_ADDR is required")
|
||||
}
|
||||
if cfg.BotLink.ServerName == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOTLINK_SERVER_NAME is required")
|
||||
}
|
||||
if cfg.BotLink.CertFile == "" || cfg.BotLink.KeyFile == "" || cfg.BotLink.CAFile == "" {
|
||||
return BotConfig{}, fmt.Errorf("config: TELEGRAM_BOTLINK_TLS_CERT, _KEY and _CA are required")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// loadTelemetry builds the shared OpenTelemetry config with the given default
|
||||
// service name, applying the TELEGRAM_* overrides and validating the result.
|
||||
func loadTelemetry(defaultService string) (pkgtel.Config, error) {
|
||||
tel := pkgtel.DefaultConfig(defaultService)
|
||||
tel.ServiceName = envOr("TELEGRAM_SERVICE_NAME", tel.ServiceName)
|
||||
tel.TracesExporter = envOr("TELEGRAM_OTEL_TRACES_EXPORTER", tel.TracesExporter)
|
||||
tel.MetricsExporter = envOr("TELEGRAM_OTEL_METRICS_EXPORTER", tel.MetricsExporter)
|
||||
cfg.Telemetry = tel
|
||||
if cfg.Token == "" {
|
||||
return Config{}, fmt.Errorf("config: TELEGRAM_BOT_TOKEN is required")
|
||||
if err := tel.Validate(); err != nil {
|
||||
return pkgtel.Config{}, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
if cfg.MiniAppURL == "" {
|
||||
return Config{}, fmt.Errorf("config: TELEGRAM_MINIAPP_URL is required")
|
||||
return tel, nil
|
||||
}
|
||||
|
||||
// hostname returns the machine hostname, or "telegram-bot" when it cannot be read.
|
||||
func hostname() string {
|
||||
if h, err := os.Hostname(); err == nil && h != "" {
|
||||
return h
|
||||
}
|
||||
if err := cfg.Telemetry.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("config: %w", err)
|
||||
}
|
||||
return cfg, nil
|
||||
return "telegram-bot"
|
||||
}
|
||||
|
||||
// envOr returns the environment value for key, or def when it is unset or empty.
|
||||
@@ -82,3 +186,45 @@ func envOr(key, def string) string {
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// envInt parses the environment variable named key as an int, returning fallback
|
||||
// when unset and an error when set but malformed.
|
||||
func envInt(key string, fallback int) (int, error) {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config: %s %q: %w", key, v, err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// envInt64 parses the environment variable named key as an int64, returning
|
||||
// fallback when unset and an error when set but malformed.
|
||||
func envInt64(key string, fallback int64) (int64, error) {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config: %s %q: %w", key, v, err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// envDuration parses the environment variable named key as a Go duration,
|
||||
// returning fallback when unset and an error when set but malformed.
|
||||
func envDuration(key string, fallback time.Duration) (time.Duration, error) {
|
||||
v := strings.TrimSpace(os.Getenv(key))
|
||||
if v == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("config: %s %q: %w", key, v, err)
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
@@ -6,71 +6,110 @@ import (
|
||||
pkgtel "scrabble/pkg/telemetry"
|
||||
)
|
||||
|
||||
// setRequired sets the required connector variables (the bot token + the Mini App
|
||||
// URL) so Load reaches the telemetry checks.
|
||||
func setRequired(t *testing.T) {
|
||||
// setBotRequired sets every required bot variable so LoadBot reaches the optional
|
||||
// parsing and telemetry checks.
|
||||
func setBotRequired(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "test-token")
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "bot-token")
|
||||
t.Setenv("TELEGRAM_MINIAPP_URL", "https://example.org/app")
|
||||
t.Setenv("TELEGRAM_GATEWAY_ADDR", "gateway.example.org:9443")
|
||||
t.Setenv("TELEGRAM_BOTLINK_SERVER_NAME", "gateway.example.org")
|
||||
t.Setenv("TELEGRAM_BOTLINK_TLS_CERT", "/certs/bot.crt")
|
||||
t.Setenv("TELEGRAM_BOTLINK_TLS_KEY", "/certs/bot.key")
|
||||
t.Setenv("TELEGRAM_BOTLINK_TLS_CA", "/certs/ca.crt")
|
||||
}
|
||||
|
||||
// TestLoadBot verifies the bot parsing: the token is read and the game channel id is
|
||||
// parsed when present.
|
||||
func TestLoadBot(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_MINIAPP_URL", "https://example.org/app")
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "bot-token")
|
||||
t.Setenv("TELEGRAM_GAME_CHANNEL_ID", "-100111")
|
||||
c, err := Load()
|
||||
// TestLoadValidator verifies the validator reads the token, defaults its address
|
||||
// and names its telemetry service.
|
||||
func TestLoadValidator(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "secret")
|
||||
c, err := LoadValidator()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
t.Fatalf("LoadValidator: %v", err)
|
||||
}
|
||||
if c.Token != "secret" {
|
||||
t.Errorf("Token = %q, want secret", c.Token)
|
||||
}
|
||||
if c.GRPCAddr != defaultValidatorGRPCAddr {
|
||||
t.Errorf("GRPCAddr = %q, want %q", c.GRPCAddr, defaultValidatorGRPCAddr)
|
||||
}
|
||||
if c.Telemetry.ServiceName != "scrabble-telegram-validator" {
|
||||
t.Errorf("ServiceName = %q, want scrabble-telegram-validator", c.Telemetry.ServiceName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadValidatorRequiresToken verifies the validator fails without a token.
|
||||
func TestLoadValidatorRequiresToken(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "")
|
||||
if _, err := LoadValidator(); err == nil {
|
||||
t.Fatal("LoadValidator: expected an error without a token, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadBot verifies the bot parses the token, channel id and owns_updates and
|
||||
// names its telemetry service.
|
||||
func TestLoadBot(t *testing.T) {
|
||||
setBotRequired(t)
|
||||
t.Setenv("TELEGRAM_GAME_CHANNEL_ID", "-100111")
|
||||
c, err := LoadBot()
|
||||
if err != nil {
|
||||
t.Fatalf("LoadBot: %v", err)
|
||||
}
|
||||
if c.Token != "bot-token" || c.GameChannelID != -100111 {
|
||||
t.Errorf("config = token %q / channel %d, want bot-token / -100111", c.Token, c.GameChannelID)
|
||||
}
|
||||
if !c.OwnsUpdates {
|
||||
t.Error("OwnsUpdates = false, want true by default")
|
||||
}
|
||||
if c.SendRatePerSecond != defaultSendRatePerSecond {
|
||||
t.Errorf("SendRatePerSecond = %d, want %d", c.SendRatePerSecond, defaultSendRatePerSecond)
|
||||
}
|
||||
if c.Telemetry.ServiceName != "scrabble-telegram-bot" {
|
||||
t.Errorf("ServiceName = %q, want scrabble-telegram-bot", c.Telemetry.ServiceName)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadOptionalChannel verifies the game channel id defaults to 0 when unset.
|
||||
func TestLoadOptionalChannel(t *testing.T) {
|
||||
setRequired(t)
|
||||
c, err := Load()
|
||||
// TestLoadBotOwnsUpdatesOptOut verifies TELEGRAM_OWNS_UPDATES=false disables the
|
||||
// long-poll ownership.
|
||||
func TestLoadBotOwnsUpdatesOptOut(t *testing.T) {
|
||||
setBotRequired(t)
|
||||
t.Setenv("TELEGRAM_OWNS_UPDATES", "false")
|
||||
c, err := LoadBot()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
t.Fatalf("LoadBot: %v", err)
|
||||
}
|
||||
if c.GameChannelID != 0 {
|
||||
t.Errorf("GameChannelID = %d, want 0", c.GameChannelID)
|
||||
if c.OwnsUpdates {
|
||||
t.Error("OwnsUpdates = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRequiresBot verifies Load fails when no bot token is configured.
|
||||
func TestLoadRequiresBot(t *testing.T) {
|
||||
t.Setenv("TELEGRAM_MINIAPP_URL", "https://example.org/app")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load: expected an error when no bot token is set, got nil")
|
||||
// TestLoadBotRequired verifies LoadBot fails when a required variable is missing.
|
||||
func TestLoadBotRequired(t *testing.T) {
|
||||
cases := []string{
|
||||
"TELEGRAM_BOT_TOKEN",
|
||||
"TELEGRAM_MINIAPP_URL",
|
||||
"TELEGRAM_GATEWAY_ADDR",
|
||||
"TELEGRAM_BOTLINK_SERVER_NAME",
|
||||
"TELEGRAM_BOTLINK_TLS_CERT",
|
||||
}
|
||||
for _, missing := range cases {
|
||||
t.Run(missing, func(t *testing.T) {
|
||||
setBotRequired(t)
|
||||
t.Setenv(missing, "")
|
||||
if _, err := LoadBot(); err == nil {
|
||||
t.Fatalf("LoadBot: expected an error without %s, got nil", missing)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadTelemetryDefaults verifies the connector telemetry defaults: the
|
||||
// "scrabble-telegram" service name and both exporters off.
|
||||
func TestLoadTelemetryDefaults(t *testing.T) {
|
||||
setRequired(t)
|
||||
c, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if c.Telemetry.ServiceName != "scrabble-telegram" {
|
||||
t.Errorf("Telemetry.ServiceName = %q, want scrabble-telegram", c.Telemetry.ServiceName)
|
||||
}
|
||||
if c.Telemetry.TracesExporter != pkgtel.ExporterNone || c.Telemetry.MetricsExporter != pkgtel.ExporterNone {
|
||||
t.Errorf("exporters = %q/%q, want none/none", c.Telemetry.TracesExporter, c.Telemetry.MetricsExporter)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRejectsUnsupportedExporter verifies an exporter outside the supported
|
||||
// set fails validation.
|
||||
// TestLoadRejectsUnsupportedExporter verifies an exporter outside the supported set
|
||||
// fails validation (the validator path).
|
||||
func TestLoadRejectsUnsupportedExporter(t *testing.T) {
|
||||
setRequired(t)
|
||||
t.Setenv("TELEGRAM_BOT_TOKEN", "secret")
|
||||
t.Setenv("TELEGRAM_OTEL_TRACES_EXPORTER", "jaeger")
|
||||
if _, err := Load(); err == nil {
|
||||
t.Fatal("Load: expected an error for an unsupported exporter, got nil")
|
||||
if _, err := LoadValidator(); err == nil {
|
||||
t.Fatal("LoadValidator: expected an error for an unsupported exporter, got nil")
|
||||
}
|
||||
_ = pkgtel.ExporterNone
|
||||
}
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
// Package connector implements the Telegram gRPC service (pkg/proto/telegram/v1):
|
||||
// the gateway calls ValidateInitData (Mini App auth) and Notify (out-of-app push);
|
||||
// the admin surface calls SendToUser and SendToGameChannel. The generic
|
||||
// methods address a recipient by the identity external_id, so a future platform
|
||||
// connector can implement the same service.
|
||||
//
|
||||
// The connector hosts a single bot. ValidateInitData/ValidateLoginWidget verify
|
||||
// launch data against its token; Notify renders the message in the recipient's
|
||||
// interface language (the single bot needs no routing); the admin methods deliver
|
||||
// through that bot.
|
||||
package connector
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
"scrabble/platform/telegram/internal/render"
|
||||
)
|
||||
|
||||
// Sender delivers Telegram messages to a chat. *bot.Bot implements it.
|
||||
type Sender interface {
|
||||
// Notify sends a notification with a Mini App launch button to chatID.
|
||||
Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error
|
||||
// SendText sends a plain text message to chatID.
|
||||
SendText(ctx context.Context, chatID int64, text string) error
|
||||
}
|
||||
|
||||
// BotRuntime is the configured bot: its sender, game channel id, and the two HMAC
|
||||
// validators bound to its token.
|
||||
type BotRuntime struct {
|
||||
// Sender delivers messages through the bot.
|
||||
Sender Sender
|
||||
// ChannelID is the bot's game channel (0 disables channel posts).
|
||||
ChannelID int64
|
||||
// InitValidator verifies Mini App initData signed by the bot's token.
|
||||
InitValidator initdata.Validator
|
||||
// WidgetValidator verifies Login Widget data signed by the bot's token.
|
||||
WidgetValidator loginwidget.Validator
|
||||
}
|
||||
|
||||
// Server implements telegramv1.TelegramServer over the single configured bot.
|
||||
type Server struct {
|
||||
telegramv1.UnimplementedTelegramServer
|
||||
bot BotRuntime
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
// NewServer builds the gRPC service from the configured bot.
|
||||
func NewServer(bot BotRuntime, log *zap.Logger) *Server {
|
||||
if log == nil {
|
||||
log = zap.NewNop()
|
||||
}
|
||||
return &Server{bot: bot, log: log}
|
||||
}
|
||||
|
||||
// ValidateInitData verifies Mini App launch data against the bot's token and returns
|
||||
// the user identity.
|
||||
func (s *Server) ValidateInitData(ctx context.Context, req *telegramv1.ValidateInitDataRequest) (*telegramv1.ValidateInitDataResponse, error) {
|
||||
u, err := s.bot.InitValidator.Validate(req.GetInitData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateInitDataResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LanguageCode: u.LanguageCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateLoginWidget verifies Login Widget authorization data against the bot's
|
||||
// token and returns the user identity, for attaching a Telegram identity to an
|
||||
// existing account.
|
||||
func (s *Server) ValidateLoginWidget(ctx context.Context, req *telegramv1.ValidateLoginWidgetRequest) (*telegramv1.ValidateLoginWidgetResponse, error) {
|
||||
u, err := s.bot.WidgetValidator.Validate(req.GetData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateLoginWidgetResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Notify renders and delivers an out-of-app notification through the bot. The message
|
||||
// is rendered in the recipient's interface language (req language). It reports
|
||||
// delivered=false (without an error) when the kind is not pushed out-of-app or the
|
||||
// bot could not deliver (e.g. the user never started it), so the gateway treats a
|
||||
// fallback miss as best-effort.
|
||||
func (s *Server) Notify(ctx context.Context, req *telegramv1.NotifyRequest) (*telegramv1.NotifyResponse, error) {
|
||||
msg, ok := render.Render(req.GetKind(), req.GetPayload(), req.GetLanguage())
|
||||
if !ok {
|
||||
return &telegramv1.NotifyResponse{Delivered: false}, nil
|
||||
}
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if err := s.bot.Sender.Notify(ctx, chat, msg.Text, msg.ButtonText, msg.StartParam); err != nil {
|
||||
s.log.Warn("notify delivery failed", zap.String("kind", req.GetKind()), zap.Error(err))
|
||||
return &telegramv1.NotifyResponse{Delivered: false}, nil
|
||||
}
|
||||
return &telegramv1.NotifyResponse{Delivered: true}, nil
|
||||
}
|
||||
|
||||
// SendToUser sends an arbitrary admin message to one user through the bot.
|
||||
func (s *Server) SendToUser(ctx context.Context, req *telegramv1.SendToUserRequest) (*telegramv1.SendResponse, error) {
|
||||
chat, err := parseChatID(req.GetExternalId())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
if err := s.bot.Sender.SendText(ctx, chat, req.GetText()); err != nil {
|
||||
s.log.Warn("send to user failed", zap.Error(err))
|
||||
return &telegramv1.SendResponse{Delivered: false}, nil
|
||||
}
|
||||
return &telegramv1.SendResponse{Delivered: true}, nil
|
||||
}
|
||||
|
||||
// SendToGameChannel posts an arbitrary admin message to the bot's game channel.
|
||||
func (s *Server) SendToGameChannel(ctx context.Context, req *telegramv1.SendToGameChannelRequest) (*telegramv1.SendResponse, error) {
|
||||
if s.bot.ChannelID == 0 {
|
||||
return nil, status.Error(codes.FailedPrecondition, "game channel is not configured")
|
||||
}
|
||||
if err := s.bot.Sender.SendText(ctx, s.bot.ChannelID, req.GetText()); err != nil {
|
||||
s.log.Warn("send to channel failed", zap.Error(err))
|
||||
return &telegramv1.SendResponse{Delivered: false}, nil
|
||||
}
|
||||
return &telegramv1.SendResponse{Delivered: true}, nil
|
||||
}
|
||||
|
||||
// parseChatID converts a Telegram identity external_id into a numeric chat id.
|
||||
func parseChatID(externalID string) (int64, error) {
|
||||
id, err := strconv.ParseInt(externalID, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid external_id %q", externalID)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package connector
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
flatbuffers "github.com/google/flatbuffers/go"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"scrabble/pkg/fbs/scrabblefb"
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
)
|
||||
|
||||
// stubValidator returns a fixed user / error from Validate.
|
||||
type stubValidator struct {
|
||||
user initdata.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubValidator) Validate(string) (initdata.User, error) { return s.user, s.err }
|
||||
|
||||
// stubWidgetValidator returns a fixed user / error from the Login Widget Validate.
|
||||
type stubWidgetValidator struct {
|
||||
user loginwidget.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubWidgetValidator) Validate(string) (loginwidget.User, error) { return s.user, s.err }
|
||||
|
||||
// fakeSender records the delivery calls the server makes.
|
||||
type fakeSender struct {
|
||||
notify []notifyCall
|
||||
text []textCall
|
||||
err error
|
||||
}
|
||||
|
||||
type notifyCall struct {
|
||||
chatID int64
|
||||
text, buttonText, startParam string
|
||||
}
|
||||
type textCall struct {
|
||||
chatID int64
|
||||
text string
|
||||
}
|
||||
|
||||
func (f *fakeSender) Notify(_ context.Context, chatID int64, text, buttonText, startParam string) error {
|
||||
f.notify = append(f.notify, notifyCall{chatID, text, buttonText, startParam})
|
||||
return f.err
|
||||
}
|
||||
|
||||
func (f *fakeSender) SendText(_ context.Context, chatID int64, text string) error {
|
||||
f.text = append(f.text, textCall{chatID, text})
|
||||
return f.err
|
||||
}
|
||||
|
||||
// botRT assembles the bot runtime for a test.
|
||||
func botRT(sender Sender, channelID int64, iv initdata.Validator, wv loginwidget.Validator) BotRuntime {
|
||||
return BotRuntime{Sender: sender, ChannelID: channelID, InitValidator: iv, WidgetValidator: wv}
|
||||
}
|
||||
|
||||
func yourTurnPayload(gameID string) []byte {
|
||||
b := flatbuffers.NewBuilder(0)
|
||||
gid := b.CreateString(gameID)
|
||||
scrabblefb.YourTurnEventStart(b)
|
||||
scrabblefb.YourTurnEventAddGameId(b, gid)
|
||||
b.Finish(scrabblefb.YourTurnEventEnd(b))
|
||||
return b.FinishedBytes()
|
||||
}
|
||||
|
||||
func TestValidateInitData(t *testing.T) {
|
||||
want := initdata.User{ExternalID: "42", Username: "neo", FirstName: "Thomas", LanguageCode: "en-GB"}
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{user: want}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{InitData: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" || resp.GetLanguageCode() != "en-GB" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(botRT(&fakeSender{}, 0, stubValidator{err: initdata.ErrInvalidInitData}, stubWidgetValidator{}), nil)
|
||||
if _, err := bad.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLoginWidget(t *testing.T) {
|
||||
want := loginwidget.User{ExternalID: "42", Username: "neo", FirstName: "Thomas"}
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{user: want}), nil)
|
||||
resp, err := srv.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{Data: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{err: loginwidget.ErrInvalidLoginWidget}), nil)
|
||||
if _, err := bad.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyDelivers(t *testing.T) {
|
||||
const gameID = "7c9e6679-7425-40de-944b-e07fc1f90ae7"
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.Notify(context.Background(), &telegramv1.NotifyRequest{
|
||||
ExternalId: "12345", Kind: "your_turn", Payload: yourTurnPayload(gameID), Language: "en",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("notify: %v", err)
|
||||
}
|
||||
if !resp.GetDelivered() {
|
||||
t.Fatal("expected delivered=true")
|
||||
}
|
||||
if len(sender.notify) != 1 {
|
||||
t.Fatalf("notify calls = %d, want 1", len(sender.notify))
|
||||
}
|
||||
if got := sender.notify[0]; got.chatID != 12345 || got.startParam != "g"+gameID {
|
||||
t.Errorf("notify call = %+v, want chatID 12345 startParam g%s", got, gameID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifySkipsUnrenderedKind(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.Notify(context.Background(), &telegramv1.NotifyRequest{
|
||||
ExternalId: "12345", Kind: "opponent_moved", Language: "en",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("notify: %v", err)
|
||||
}
|
||||
if resp.GetDelivered() {
|
||||
t.Error("expected delivered=false for an unrendered kind")
|
||||
}
|
||||
if len(sender.notify) != 0 {
|
||||
t.Errorf("sender called %d times, want 0", len(sender.notify))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyInvalidExternalID(t *testing.T) {
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
_, err := srv.Notify(context.Background(), &telegramv1.NotifyRequest{
|
||||
ExternalId: "not-a-number", Kind: "your_turn", Payload: yourTurnPayload("g"), Language: "en",
|
||||
})
|
||||
if status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendToUser(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.SendToUser(context.Background(), &telegramv1.SendToUserRequest{ExternalId: "999", Text: "hi"})
|
||||
if err != nil {
|
||||
t.Fatalf("send to user: %v", err)
|
||||
}
|
||||
if !resp.GetDelivered() || len(sender.text) != 1 || sender.text[0].chatID != 999 || sender.text[0].text != "hi" {
|
||||
t.Errorf("send to user = %v / calls %+v", resp.GetDelivered(), sender.text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendToGameChannel(t *testing.T) {
|
||||
t.Run("unconfigured", func(t *testing.T) {
|
||||
srv := NewServer(botRT(&fakeSender{}, 0, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
_, err := srv.SendToGameChannel(context.Background(), &telegramv1.SendToGameChannelRequest{Text: "x"})
|
||||
if status.Code(err) != codes.FailedPrecondition {
|
||||
t.Errorf("err code = %v, want FailedPrecondition", status.Code(err))
|
||||
}
|
||||
})
|
||||
t.Run("configured", func(t *testing.T) {
|
||||
sender := &fakeSender{}
|
||||
srv := NewServer(botRT(sender, 555, stubValidator{}, stubWidgetValidator{}), nil)
|
||||
resp, err := srv.SendToGameChannel(context.Background(), &telegramv1.SendToGameChannelRequest{Text: "news"})
|
||||
if err != nil {
|
||||
t.Fatalf("send to channel: %v", err)
|
||||
}
|
||||
if !resp.GetDelivered() || len(sender.text) != 1 || sender.text[0].chatID != 555 {
|
||||
t.Errorf("send to channel: %+v", sender.text)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// Package validator implements the home-side Telegram validator gRPC service: it
|
||||
// verifies Mini App initData and Login Widget data with the bot token's HMAC and
|
||||
// never calls the Bot API. The gateway calls it during the auth.telegram and
|
||||
// link.telegram edge operations. It holds the token only as the HMAC secret, so it
|
||||
// can run on the main host with no VPN and no Telegram egress (ARCHITECTURE.md §12).
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
)
|
||||
|
||||
// Server implements the validation subset of telegramv1.TelegramServer; the
|
||||
// delivery methods (Notify, SendToUser, SendToGameChannel) are intentionally
|
||||
// unimplemented here — those run on the remote bot over the bot-link.
|
||||
type Server struct {
|
||||
telegramv1.UnimplementedTelegramServer
|
||||
initValidator initdata.Validator
|
||||
widgetValidator loginwidget.Validator
|
||||
}
|
||||
|
||||
// NewServer builds the validator from the two HMAC validators bound to the token.
|
||||
func NewServer(iv initdata.Validator, wv loginwidget.Validator) *Server {
|
||||
return &Server{initValidator: iv, widgetValidator: wv}
|
||||
}
|
||||
|
||||
// ValidateInitData verifies Mini App launch data against the bot's token and
|
||||
// returns the user identity.
|
||||
func (s *Server) ValidateInitData(_ context.Context, req *telegramv1.ValidateInitDataRequest) (*telegramv1.ValidateInitDataResponse, error) {
|
||||
u, err := s.initValidator.Validate(req.GetInitData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateInitDataResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
LanguageCode: u.LanguageCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateLoginWidget verifies Login Widget authorization data against the bot's
|
||||
// token and returns the user identity, for attaching a Telegram identity to an
|
||||
// existing account.
|
||||
func (s *Server) ValidateLoginWidget(_ context.Context, req *telegramv1.ValidateLoginWidgetRequest) (*telegramv1.ValidateLoginWidgetResponse, error) {
|
||||
u, err := s.widgetValidator.Validate(req.GetData())
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
return &telegramv1.ValidateLoginWidgetResponse{
|
||||
ExternalId: u.ExternalID,
|
||||
Username: u.Username,
|
||||
FirstName: u.FirstName,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package validator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
telegramv1 "scrabble/pkg/proto/telegram/v1"
|
||||
"scrabble/platform/telegram/internal/initdata"
|
||||
"scrabble/platform/telegram/internal/loginwidget"
|
||||
)
|
||||
|
||||
// stubValidator returns a fixed user / error from Validate.
|
||||
type stubValidator struct {
|
||||
user initdata.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubValidator) Validate(string) (initdata.User, error) { return s.user, s.err }
|
||||
|
||||
// stubWidgetValidator returns a fixed user / error from the Login Widget Validate.
|
||||
type stubWidgetValidator struct {
|
||||
user loginwidget.User
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubWidgetValidator) Validate(string) (loginwidget.User, error) { return s.user, s.err }
|
||||
|
||||
func TestValidateInitData(t *testing.T) {
|
||||
want := initdata.User{ExternalID: "42", Username: "neo", FirstName: "Thomas", LanguageCode: "en-GB"}
|
||||
srv := NewServer(stubValidator{user: want}, stubWidgetValidator{})
|
||||
resp, err := srv.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{InitData: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" || resp.GetLanguageCode() != "en-GB" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(stubValidator{err: initdata.ErrInvalidInitData}, stubWidgetValidator{})
|
||||
if _, err := bad.ValidateInitData(context.Background(), &telegramv1.ValidateInitDataRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLoginWidget(t *testing.T) {
|
||||
want := loginwidget.User{ExternalID: "42", Username: "neo", FirstName: "Thomas"}
|
||||
srv := NewServer(stubValidator{}, stubWidgetValidator{user: want})
|
||||
resp, err := srv.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{Data: "x"})
|
||||
if err != nil {
|
||||
t.Fatalf("validate: %v", err)
|
||||
}
|
||||
if resp.GetExternalId() != "42" || resp.GetUsername() != "neo" || resp.GetFirstName() != "Thomas" {
|
||||
t.Errorf("resp = %+v, want %+v", resp, want)
|
||||
}
|
||||
|
||||
bad := NewServer(stubValidator{}, stubWidgetValidator{err: loginwidget.ErrInvalidLoginWidget})
|
||||
if _, err := bad.ValidateLoginWidget(context.Background(), &telegramv1.ValidateLoginWidgetRequest{}); status.Code(err) != codes.InvalidArgument {
|
||||
t.Errorf("err code = %v, want InvalidArgument", status.Code(err))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user