feat(telegram): support secret refs for bot tokens (#705)
This commit is contained in:
1 parent
0653a9ed57
commit
c75ed44721
10 files changed
+134
-16
No files matched your search
@@ -140,6 +140,9 @@ class = "ollama"
|
||||
# shell snippets). The check command must write a releaseupdate.Snapshot JSON
|
||||
# document to stdout; configure the installer as well to show Approve/Defer.
|
||||
# [chat.telegram]
|
||||
# Preferred: resolve the bot token through a configured secret engine.
|
||||
# token = { engine = "bws", key = "TELEGRAM_BOT_TOKEN" }
|
||||
# Legacy compatibility: read the token from this environment variable.
|
||||
# token_env = "TELEGRAM_BOT_TOKEN" # env var holding the bot token from @BotFather
|
||||
# update_check_command = ["/usr/local/bin/archie-update-check"]
|
||||
# update_install_command = ["/usr/local/bin/archie-update-install"]
|
||||
|
||||
@@ -158,7 +158,7 @@ existing structure combines different owners.
|
||||
| `URL`, `TokenEnv` | `NATSConfig` | NATS transport settings with a secret reference replacing the environment-name field. |
|
||||
| `Image`, `MaxConcurrency`, `MaxUptime`, `VolumeTTL`, `PullPolicy`, `Network` | `ContainerConfig` | Mandatory managed-worker infrastructure settings and resource policy. The legacy `enabled` input is decode-only. |
|
||||
| model mappings, email, webhook, Telegram | `ChatConfig` | Separate channel instance settings plus channel-routing associations; there is no chat-wide settings owner. |
|
||||
| `AllowedUserIDs`, `TokenEnv`, update commands | Telegram config | Telegram adapter settings and access policy. Secret and policy fields are distinct. |
|
||||
| `AllowedUserIDs`, `Token` / `TokenEnv` (older form), update commands | Telegram config | Telegram adapter settings and access policy. `Token` is the preferred `secret.SecretRef`; `TokenEnv` remains a backwards-compatible fallback. |
|
||||
| listen/relay addresses | email config | Email adapter instance settings. |
|
||||
| webhook target | `Notify` | Notification adapter instance settings. |
|
||||
| web listen address | `Web` | Web transport settings. |
|
||||
|
||||
@@ -79,6 +79,12 @@ Configuration refers to identities by `IdentityID` and supplies external
|
||||
bindings and capability settings separately. Renaming an identity or changing an
|
||||
external account MUST NOT change ownership or historical attribution.
|
||||
|
||||
Secret-bearing channel bindings remain configuration concerns rather than
|
||||
identity data. In particular, `[chat.telegram].token` is a
|
||||
`secret.SecretRef` resolved by the application through the configured secret
|
||||
registry; the older `token_env` field remains a compatibility fallback. Neither
|
||||
form changes the identity that owns or performs a chat action.
|
||||
|
||||
## Persistence
|
||||
|
||||
Identity records are durable domain state. The Identity domain's repository is
|
||||
|
||||
@@ -319,11 +319,11 @@ func (b *boot) setupObservability() {
|
||||
b.bus = bus
|
||||
b.addCleanup(func() { bus.Close() })
|
||||
telegramDetail := ""
|
||||
if cfg.Chat.Telegram.TokenEnv != "" && len(cfg.Chat.Telegram.AllowedUserIDs) == 0 {
|
||||
if (cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "") && len(cfg.Chat.Telegram.AllowedUserIDs) == 0 {
|
||||
telegramDetail = "Token set, but the allowlist is empty -- the bot answers nobody."
|
||||
}
|
||||
b.channelManager = channelruntime.NewManager([]channelruntime.Descriptor{
|
||||
{ID: "telegram", Name: "Telegram", Configured: cfg.Chat.Telegram.TokenEnv != "", ReloadSupported: cfg.Chat.Telegram.TokenEnv != "", Detail: telegramDetail},
|
||||
{ID: "telegram", Name: "Telegram", Configured: cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "", ReloadSupported: cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "", Detail: telegramDetail},
|
||||
{ID: "email", Name: "Email", Configured: cfg.Chat.Email.ListenAddr != ""},
|
||||
{ID: "webhook", Name: "Webhook gateway", Configured: cfg.Chat.WebhookAddr != ""},
|
||||
})
|
||||
@@ -335,7 +335,7 @@ func (b *boot) setupObservability() {
|
||||
}
|
||||
b.web = &webui.Server{Store: b.st, Log: log.With("component", "webui"), LogFeed: b.logFeed, TaskLogs: b.taskLogs, Cfg: config.NewHolder(cfg), Channels: b.channelManager, Events: bus}
|
||||
b.web.UpdateReportPath = updateReportPath(cfg.WorkDir, "webui")
|
||||
if cfg.Chat.Telegram.TokenEnv != "" && len(cfg.Chat.Telegram.AllowedUserIDs) > 0 {
|
||||
if (cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "") && len(cfg.Chat.Telegram.AllowedUserIDs) > 0 {
|
||||
b.web.TelegramUpdateReportPath = updateReportPath(cfg.WorkDir, cfg.BotUser)
|
||||
b.web.TelegramUpdateChatID = cfg.Chat.Telegram.AllowedUserIDs[0]
|
||||
}
|
||||
@@ -512,7 +512,7 @@ func (b *boot) setupLLMAndChat(ctx context.Context) {
|
||||
// responder with Telegram while using a stable browser channel id.
|
||||
b.webRouter = gateway.NewRouter(b.st, nil, "web")
|
||||
b.webRouter.Version = fmt.Sprintf("Archie\nGateway: %s\nRuntime: %s", gatewayVersion, runtimeVersion)
|
||||
if cfg.Chat.Telegram.TokenEnv != "" {
|
||||
if cfg.Chat.Telegram.Token != (secret.SecretRef{}) || cfg.Chat.Telegram.TokenEnv != "" {
|
||||
b.webRouter.Restart = func(context.Context) error {
|
||||
if b.restartTelegram == nil {
|
||||
return fmt.Errorf("telegram gateway is not ready")
|
||||
@@ -541,7 +541,7 @@ func (b *boot) setupLLMAndChat(ctx context.Context) {
|
||||
token: func() string { return b.web.Token },
|
||||
},
|
||||
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore,
|
||||
Bus: b.bus, Log: log,
|
||||
Bus: b.bus, Log: log, Secrets: b.secrets,
|
||||
}
|
||||
b.webRouter.LLM, b.webRouter.LLMStream = makeChatLLMResponder(ctx, "web", webSetup, b.chatSessionStore, b.webRouter)
|
||||
b.webRouter.Titles = newChatTitleGenerator(webSetup)
|
||||
@@ -578,6 +578,7 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b
|
||||
token: func() string { return b.web.Token },
|
||||
},
|
||||
DefaultChatIdentity: b.defaultChatIdentity, SessionStore: b.chatSessionStore, Updates: b.updateService,
|
||||
Secrets: b.secrets,
|
||||
Bus: b.bus,
|
||||
RegisterRestart: func(request func() error) { b.restartTelegram = request }, Log: log,
|
||||
ChannelManager: b.channelManager, AgentStatus: b.agentStatus,
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/releaseannounce"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
"github.com/samcharles93/archie-core/internal/tools"
|
||||
)
|
||||
@@ -62,6 +63,17 @@ type telegramSetup struct {
|
||||
// recently observed archie-agent version (see daemon.AgentStatus).
|
||||
// Nil disables the agent component of RunningVersions.
|
||||
AgentStatus *daemon.AgentStatus
|
||||
Secrets *secret.Registry
|
||||
}
|
||||
|
||||
func resolveTelegramToken(cfg config.TelegramConfig, registry *secret.Registry) (string, error) {
|
||||
if cfg.Token != (secret.SecretRef{}) {
|
||||
return cfg.Token.Resolve(registry)
|
||||
}
|
||||
if cfg.TokenEnv == "" {
|
||||
return "", nil
|
||||
}
|
||||
return os.Getenv(cfg.TokenEnv), nil
|
||||
}
|
||||
|
||||
// setupTelegramGateway initialises the Telegram chat gateway when a
|
||||
@@ -69,12 +81,16 @@ type telegramSetup struct {
|
||||
// is configured) and ok=false to signal the caller must exit early.
|
||||
func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), ok bool) {
|
||||
cfg := s.Cfg.Get()
|
||||
if cfg.Chat.Telegram.TokenEnv == "" {
|
||||
if cfg.Chat.Telegram.Token == (secret.SecretRef{}) && cfg.Chat.Telegram.TokenEnv == "" {
|
||||
return nil, true
|
||||
}
|
||||
tgToken := os.Getenv(cfg.Chat.Telegram.TokenEnv)
|
||||
tgToken, err := resolveTelegramToken(cfg.Chat.Telegram, s.Secrets)
|
||||
if err != nil {
|
||||
s.Log.Error("chat.telegram token resolution failed", "err", err)
|
||||
return nil, false
|
||||
}
|
||||
if tgToken == "" {
|
||||
s.Log.Error("chat.telegram configured but token env var is empty", "env", cfg.Chat.Telegram.TokenEnv)
|
||||
s.Log.Error("chat.telegram configured but token is empty")
|
||||
return nil, false
|
||||
}
|
||||
if len(cfg.Chat.Telegram.AllowedUserIDs) == 0 {
|
||||
@@ -231,13 +247,12 @@ func makeTelegramReload(s telegramSetup) func(*telegram.Gateway) error {
|
||||
return fmt.Errorf("reload config: %w", err)
|
||||
}
|
||||
newCfg := doc.Config
|
||||
tokenEnv := newCfg.Chat.Telegram.TokenEnv
|
||||
if tokenEnv == "" {
|
||||
return fmt.Errorf("reload config: chat.telegram.token_env is unset")
|
||||
token, err := resolveTelegramToken(newCfg.Chat.Telegram, s.Secrets)
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload config: resolve telegram token: %w", err)
|
||||
}
|
||||
token := os.Getenv(tokenEnv)
|
||||
if token == "" {
|
||||
return fmt.Errorf("reload config: %s is empty", tokenEnv)
|
||||
return fmt.Errorf("reload config: chat.telegram token is empty")
|
||||
}
|
||||
g.Token = token
|
||||
g.AllowedUserIDs = newCfg.Chat.Telegram.AllowedUserIDs
|
||||
|
||||
@@ -1,14 +1,78 @@
|
||||
package archied
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/installtype"
|
||||
"github.com/samcharles93/archie-core/internal/releaseupdate"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
type telegramTestSecretEngine struct{}
|
||||
|
||||
func (telegramTestSecretEngine) Name() string { return "bws" }
|
||||
func (telegramTestSecretEngine) Version() string { return "test" }
|
||||
func (telegramTestSecretEngine) Resolve(key string) (string, error) {
|
||||
if key == "telegram-token" {
|
||||
return "token-from-bws", nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenPrefersSecretRef(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(telegramTestSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
|
||||
}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-bws" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-bws", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenFallsBackToTokenEnv(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
cfg := config.TelegramConfig{TokenEnv: "TELEGRAM_LEGACY_TOKEN"}
|
||||
t.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got != "token-from-env" {
|
||||
t.Fatalf("resolveTelegramToken = %q, want token-from-env", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveTelegramTokenDoesNotUseTokenEnvWhenSecretRefIsSet(t *testing.T) {
|
||||
registry := secret.NewRegistry()
|
||||
registry.Register(telegramTestSecretEngine{})
|
||||
cfg := config.TelegramConfig{
|
||||
Token: secret.SecretRef{Engine: "bws", Key: "telegram-token"},
|
||||
TokenEnv: "TELEGRAM_LEGACY_TOKEN",
|
||||
}
|
||||
os.Setenv("TELEGRAM_LEGACY_TOKEN", "token-from-env")
|
||||
t.Cleanup(func() { os.Unsetenv("TELEGRAM_LEGACY_TOKEN") })
|
||||
|
||||
got, err := resolveTelegramToken(cfg, registry)
|
||||
if err != nil {
|
||||
t.Fatalf("resolveTelegramToken returned error: %v", err)
|
||||
}
|
||||
if got == "token-from-env" {
|
||||
t.Fatal("resolveTelegramToken used TokenEnv despite Token being configured")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMakeUpdateServiceWiresInstallType is the regression test for
|
||||
// archie-core-522's fail-closed guarantee actually reaching production: a
|
||||
// Service built without InstallType always refuses to install (see
|
||||
|
||||
@@ -923,6 +923,9 @@ type TelegramConfig struct {
|
||||
// bot to a group does not grant that group's members access. Empty
|
||||
// denies everyone.
|
||||
AllowedUserIDs []int64 `toml:"allowed_user_ids" yaml:"allowed_user_ids"`
|
||||
// Token references the bot token through the configured secret engine.
|
||||
// It takes precedence over TokenEnv when both are set.
|
||||
Token secret.SecretRef `toml:"token" yaml:"token"`
|
||||
// TokenEnv names the env var holding the bot token from @BotFather.
|
||||
// Empty disables the Telegram channel.
|
||||
TokenEnv string `toml:"token_env" yaml:"token_env"`
|
||||
|
||||
@@ -213,6 +213,29 @@ func TestLoadForgeTokenTakesPrecedenceOverTokenEnv(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadTelegramTokenSecretRefAndLegacyFallback(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
contents := "bot_user = \"widget\"\n" +
|
||||
"[chat.telegram]\ntoken = { engine = \"bws\", key = \"TELEGRAM_BOT_TOKEN\" }\n" +
|
||||
"token_env = \"TELEGRAM_LEGACY_TOKEN\"\n" +
|
||||
"[[repos]]\nowner = \"acme\"\nname = \"app\"\n"
|
||||
if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg, err := loadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := secret.SecretRef{Engine: "bws", Key: "TELEGRAM_BOT_TOKEN"}
|
||||
if cfg.Chat.Telegram.Token != want {
|
||||
t.Errorf("Telegram.Token = %#v, want %#v", cfg.Chat.Telegram.Token, want)
|
||||
}
|
||||
if cfg.Chat.Telegram.TokenEnv != "TELEGRAM_LEGACY_TOKEN" {
|
||||
t.Errorf("Telegram.TokenEnv = %q, want TELEGRAM_LEGACY_TOKEN", cfg.Chat.Telegram.TokenEnv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// Sentinel errors for handleConfigUpdate status classification. The
|
||||
@@ -136,7 +137,7 @@ func channelStateDetail(state channels.State, configured bool) string {
|
||||
}
|
||||
|
||||
func telegramChannelView(t config.TelegramConfig) ChannelView {
|
||||
configured := strings.TrimSpace(t.TokenEnv) != ""
|
||||
configured := t.Token != (secret.SecretRef{}) || strings.TrimSpace(t.TokenEnv) != ""
|
||||
detail := "Not configured."
|
||||
if configured {
|
||||
n := len(t.AllowedUserIDs)
|
||||
|
||||
@@ -3,6 +3,8 @@ package webui
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
)
|
||||
|
||||
// SetupStep is one item in the dashboard's getting-started checklist.
|
||||
@@ -77,6 +79,6 @@ func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
// one is the honest signal here.
|
||||
func (s *Server) hasChannel() bool {
|
||||
cfg := s.Cfg.Get()
|
||||
return strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" ||
|
||||
return cfg.Chat.Telegram.Token != (secret.SecretRef{}) || strings.TrimSpace(cfg.Chat.Telegram.TokenEnv) != "" ||
|
||||
strings.TrimSpace(cfg.Chat.WebhookAddr) != ""
|
||||
}
|
||||
Reference in new issue
Block a user