feat(channels): wire ConfigSchema/ValidateConfig into a startup validation loop
Every chat gateway (Telegram, email, webhook) implemented channels.Channel's ConfigSchema/ValidateConfig contract but nothing ever called it, so a misconfigured gateway would only fail once it tried to start rather than at boot. setupEmailGateway/setupWebhookGateway now call ValidateConfig before registering a start function and return false (fatal boot error, matching setupTelegramGateway's existing convention) on failure; telegram_setup.go does the same for the already-constructed *telegram.Gateway. Fixed telegram.Gateway.ValidateConfig/ConfigSchema along the way: it only recognised token_env, but chat.telegram.token (a secret reference) is an equally valid, already-precedent-ordered credential source per resolveTelegramToken. Wiring the old validator unmodified would have rejected every Token-only deployment. Also corrected ConfigSchema's stale allowed_chat_ids property name to the real allowed_user_ids toml key.
This commit is contained in:
1 parent
04d690322a
commit
7c68e1d436
5 files changed
+150
-14
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user