diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 535c14d73..be3454843 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -658,18 +658,32 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b b.startGateways = append(b.startGateways, start) } - b.setupEmailGateway(ctx, cfg, log) - b.setupWebhookGateway(ctx, cfg, log) + if !b.setupEmailGateway(ctx, cfg, log) { + return false + } + if !b.setupWebhookGateway(ctx, cfg, log) { + return false + } return true } // setupEmailGateway registers the optional inbound email gateway when -// chat.email.listen_addr is configured. -func (b *boot) setupEmailGateway(ctx context.Context, cfg config.Config, log *slog.Logger) { +// chat.email.listen_addr is configured. It returns false when the +// configured gateway fails its own ConfigSchema validation, which the +// caller treats as a fatal boot error -- the same convention +// setupTelegramGateway already uses. +func (b *boot) setupEmailGateway(ctx context.Context, cfg config.Config, log *slog.Logger) bool { if cfg.Chat.Email.ListenAddr == "" { - return + return true } em := email.New(cfg.Chat.Email.ListenAddr, cfg.Chat.Email.RelayAddr, log) + if err := em.ValidateConfig(map[string]any{ + "listen_addr": cfg.Chat.Email.ListenAddr, + "relay_addr": cfg.Chat.Email.RelayAddr, + }); err != nil { + log.Error("chat.email config invalid", "err", err) + return false + } emRouter := gateway.NewRouter(b.stateStore, nil, "email") emRouter.Limiter = b.rateLimiter configureTaskCommands(emRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.stateStore.Tasks}, b.defaultChatIdentity) @@ -688,13 +702,17 @@ func (b *boot) setupEmailGateway(ctx context.Context, cfg config.Config, log *sl } }() }) + return true } // setupWebhookGateway registers the optional inbound webhook gateway when -// chat.webhook_addr is configured. -func (b *boot) setupWebhookGateway(ctx context.Context, cfg config.Config, log *slog.Logger) { +// chat.webhook_addr is configured. It returns false when the configured +// gateway fails its own ConfigSchema validation, which the caller treats +// as a fatal boot error -- the same convention setupTelegramGateway +// already uses. +func (b *boot) setupWebhookGateway(ctx context.Context, cfg config.Config, log *slog.Logger) bool { if cfg.Chat.WebhookAddr == "" { - return + return true } host, port := parseListenAddr(cfg.Chat.WebhookAddr, "0.0.0.0", 8644) secretValue, err := b.secrets.Resolve(cfg.Chat.Webhook.Secret) @@ -707,6 +725,13 @@ func (b *boot) setupWebhookGateway(ctx context.Context, cfg config.Config, log * webhookRoutes(cfg.Chat.Webhook, secretValue), log, ) + if err := wh.ValidateConfig(map[string]any{ + "host": host, + "port": port, + }); err != nil { + log.Error("chat.webhook config invalid", "err", err) + return false + } whRouter := gateway.NewRouter(b.stateStore, nil, "webhook") whRouter.Limiter = b.rateLimiter configureTaskCommands(whRouter, b.chatTasks, b.chatController, chatTaskListerAdapter{tasks: b.stateStore.Tasks}, b.defaultChatIdentity) @@ -725,6 +750,7 @@ func (b *boot) setupWebhookGateway(ctx context.Context, cfg config.Config, log * } }() }) + return true } // webhookRoutes translates the configured [chat.webhook] route into the diff --git a/internal/app/archied/telegram_setup.go b/internal/app/archied/telegram_setup.go index f8b020a6f..47474d9ad 100644 --- a/internal/app/archied/telegram_setup.go +++ b/internal/app/archied/telegram_setup.go @@ -71,6 +71,17 @@ type telegramSetup struct { RateLimiter *ratelimit.Limiter } +// telegramValidateConfigMap builds the map Gateway.ValidateConfig expects +// from the typed config, carrying whichever credential source is set +// (token takes precedence, matching resolveTelegramToken). +func telegramValidateConfigMap(cfg config.TelegramConfig) map[string]any { + m := map[string]any{"token_env": cfg.TokenEnv} + if cfg.Token != (secret.SecretRef{}) { + m["token"] = map[string]any{"engine": cfg.Token.Engine, "key": cfg.Token.Key} + } + return m +} + func resolveTelegramToken(cfg config.TelegramConfig, registry *secret.Registry) (string, error) { if cfg.Token != (secret.SecretRef{}) { return registry.Resolve(cfg.Token) @@ -103,6 +114,10 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o "Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.") } tg := telegram.New(tgToken, cfg.Chat.Telegram.AllowedUserIDs, s.Log) + if err := tg.ValidateConfig(telegramValidateConfigMap(cfg.Chat.Telegram)); err != nil { + s.Log.Error("chat.telegram config invalid", "err", err) + return nil, false + } if s.RegisterRestart != nil { s.RegisterRestart(tg.RequestRestart) } diff --git a/internal/app/archied/telegram_setup_regression_test.go b/internal/app/archied/telegram_setup_regression_test.go index d40fac9c0..e41424fb3 100644 --- a/internal/app/archied/telegram_setup_regression_test.go +++ b/internal/app/archied/telegram_setup_regression_test.go @@ -7,6 +7,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/secret" ) func TestBuildTelegramRouterWiresPersonas(t *testing.T) { @@ -25,3 +26,57 @@ func TestBuildTelegramRouterWiresPersonas(t *testing.T) { t.Fatalf("router.Personas = %p, want the configured registry %p", router.Personas, personas) } } + +// TestSetupTelegramGatewayAcceptsTokenRefWithoutTokenEnv is the regression +// guard for channels-telegram-5: wiring Gateway.ValidateConfig into the +// startup path without first fixing it to accept a Token secret ref (not +// just TokenEnv) would have rejected every deployment configured via +// chat.telegram.token, even though resolveTelegramToken already treats +// Token as taking precedence over TokenEnv. +func TestSetupTelegramGatewayAcceptsTokenRefWithoutTokenEnv(t *testing.T) { + registry := secret.NewRegistry() + registry.Register(telegramTestSecretEngine{}) + sessions := gateway.NewSessionStoreMemory() + t.Cleanup(func() { _ = sessions.Close() }) + + cfg := config.Config{Chat: config.ChatConfig{Telegram: config.TelegramConfig{ + Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"}, + // TokenEnv deliberately left empty. + }}} + + start, ok := setupTelegramGateway(context.Background(), telegramSetup{ + Cfg: config.NewHolder(cfg), + Secrets: registry, + SessionStore: sessions, + Log: slog.Default(), + }) + if !ok { + t.Fatal("setupTelegramGateway ok = false, want true: chat.telegram.token alone is a valid credential source") + } + if start == nil { + t.Fatal("setupTelegramGateway start = nil, want a start function") + } +} + +// TestSetupTelegramGatewayRejectsMissingCredential is the companion +// negative case: with neither token nor token_env resolvable to a +// non-empty value, ValidateConfig's wiring must still refuse to start. +func TestSetupTelegramGatewayRejectsMissingCredential(t *testing.T) { + registry := secret.NewRegistry() + sessions := gateway.NewSessionStoreMemory() + t.Cleanup(func() { _ = sessions.Close() }) + + cfg := config.Config{Chat: config.ChatConfig{Telegram: config.TelegramConfig{ + Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"}, + }}} + + _, ok := setupTelegramGateway(context.Background(), telegramSetup{ + Cfg: config.NewHolder(cfg), + Secrets: registry, // bws engine not registered: resolution fails, token stays empty + SessionStore: sessions, + Log: slog.Default(), + }) + if ok { + t.Fatal("setupTelegramGateway ok = true, want false: token cannot be resolved") + } +} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 617a0b21c..46195c436 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -832,32 +832,51 @@ func updateThreadID(update *models.Update) int { } // ConfigSchema returns the JSON Schema for the Telegram channel config. +// The bot token may be supplied either directly as token_env (an +// environment variable name) or as token (a secret reference object with +// engine/key); token takes precedence when both are set, matching +// resolveTelegramToken's own precedence. func (g *Gateway) ConfigSchema() json.RawMessage { return json.RawMessage(`{ "type": "object", - "required": ["token_env"], + "anyOf": [ + { "required": ["token_env"] }, + { "required": ["token"] } + ], "properties": { "token_env": { "type": "string", "description": "Environment variable holding the Telegram bot token from @BotFather" }, - "allowed_chat_ids": { + "token": { + "type": "object", + "description": "Secret reference for the bot token, resolved through the configured secret engine. Takes precedence over token_env.", + "properties": { + "engine": { "type": "string" }, + "key": { "type": "string" } + } + }, + "allowed_user_ids": { "type": "array", "items": { "type": "integer" }, - "description": "Restrict bot access to specific chat IDs" + "description": "Restrict bot access to specific Telegram user ids" } } }`) } -// ValidateConfig checks the Telegram channel configuration. +// ValidateConfig checks the Telegram channel configuration. A token is +// required, supplied either as token (a secret reference) or token_env +// (an environment variable name) -- either credential source is valid, +// matching resolveTelegramToken's precedence in the daemon's boot path. func (g *Gateway) ValidateConfig(cfg map[string]any) error { if cfg == nil { return fmt.Errorf("telegram config is required") } tokenEnv, _ := cfg["token_env"].(string) - if tokenEnv == "" { - return fmt.Errorf("telegram.token_env is required") + _, hasTokenRef := cfg["token"] + if tokenEnv == "" && !hasTokenRef { + return fmt.Errorf("telegram.token or telegram.token_env is required") } return nil } diff --git a/internal/channels/telegram/telegram_test.go b/internal/channels/telegram/telegram_test.go index a077331aa..3c806976e 100644 --- a/internal/channels/telegram/telegram_test.go +++ b/internal/channels/telegram/telegram_test.go @@ -629,3 +629,24 @@ func TestLaunchDropsPendingUpdatesBeforePolling(t *testing.T) { t.Error("launch() started long polling without dropping pending updates") } } + +func TestValidateConfigAcceptsTokenEnv(t *testing.T) { + g := New("token", nil, slog.Default()) + if err := g.ValidateConfig(map[string]any{"token_env": "TELEGRAM_BOT_TOKEN"}); err != nil { + t.Errorf("ValidateConfig with token_env set = %v, want nil", err) + } +} + +func TestValidateConfigAcceptsTokenRef(t *testing.T) { + g := New("token", nil, slog.Default()) + if err := g.ValidateConfig(map[string]any{"token": map[string]any{"engine": "env", "key": "TELEGRAM_BOT_TOKEN"}}); err != nil { + t.Errorf("ValidateConfig with a token secret ref set = %v, want nil: chat.telegram.token is an equally valid credential source to token_env", err) + } +} + +func TestValidateConfigRejectsNeitherCredential(t *testing.T) { + g := New("token", nil, slog.Default()) + if err := g.ValidateConfig(map[string]any{}); err == nil { + t.Error("ValidateConfig with neither token nor token_env set = nil, want an error") + } +}