feat(telegram): deny-by-default sender allowlist + command menu (16.33, 16.34)
Allowlist (16.33). telegram.New was called with a nil allowlist and isChatAllowed returned true whenever the list was empty, so any Telegram user who found the bot could talk to it; AllowedChatIDs was not plumbed into config, so there was no way to close it. Chat tools run with the daemon's own authority, so this had to be fixed before wiring any real tools to the chat agent. Now chat.telegram.allowed_user_ids configures it and an empty list denies everyone: a bot handle is public, so failing open is not a safe default. The check matches the sender (from.id) rather than the chat, so adding the bot to a group cannot be used to inherit access. Rejections log the sender id and answer once, so a legitimate user missing from the list can tell the bot is misconfigured rather than dead. Startup warns when the gateway is enabled with an empty list. The previous TestIsChatAllowed asserted 'empty allowlist allows all' -- it encoded the vulnerability -- and is replaced by fail-closed tests. Command menu (16.34). SetMyCommands was never called, so Telegram showed no menu and the commands Router implements were undiscoverable; asked about /commands the LLM confidently answered it had none. The published list mirrors what Router actually handles. Failure is logged, not fatal: it costs discoverability, not function.
This commit is contained in:
1 parent
285c618f74
commit
cb147b7a37
6 files changed
+114
-35
No files matched your search
@@ -1,3 +1,4 @@
|
||||
{"_type":"issue","id":"archie-core-abg.16.33","title":"Telegram: allowlist senders, fail closed when unset","description":"telegram.New is called with a nil allowlist and isChatAllowed returns true when the allowlist is empty, so any Telegram user who finds the bot can talk to it. AllowedChatIDs is not plumbed into config at all. This gates exposing any real tools to the chat agent: with an MCP shell/filesystem server wired, allow-all becomes RCE for arbitrary senders.","acceptance_criteria":"Allowlist is configurable via config.toml. Unset means deny, not allow. Sender identity (user id) is checked, not just chat id, so a group chat cannot be used to bypass it. Rejections are logged with the sender id. Startup logs loudly when the chat gateway is enabled with an empty allowlist.","status":"open","priority":0,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-26T19:11:40Z","created_by":"Sam Catlow","updated_at":"2026-07-26T19:11:40Z","dependencies":[{"issue_id":"archie-core-abg.16.33","depends_on_id":"archie-core-abg.16","type":"parent-child","created_at":"2026-07-27T05:11:40Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.17.41","title":"Tool-provider engine: lifecycle registry with MCP and memory providers","description":"Build the typed tool-provider capability family over the central tools registry. Providers declare a plugin manifest, lifecycle/health, and discover executable ToolEntry values. Add adapters for memory.Manager and configured MCP servers, perform MCP initialize/tools-list/tools-call, register handlers atomically with collision rollback, translate available entries to ai-sdk core.ToolSet, and wire consumers so registered tools are actually callable rather than dead daemon fields.","design":"internal/tools owns Provider and ProviderRegistry; Provider is a typed domain contract and uses the shared plugin manifest/lifecycle vocabulary. The registry owns provider registration and tool indexing while the capability host orchestrates cross-family lifecycle. Memory is adapted without changing internal/memory concurrent work. MCP provider wraps the existing stdio transport without modifying its concurrent implementation, adds protocol client behavior in new files, prefixes/sanitizes server tool names deterministically, and retains original MCP names for calls. Never advertise a tool on an execution path that cannot invoke its handler; explicitly proxy or omit tools across subprocess/NATS boundaries.","acceptance_criteria":"Provider registration is atomic and rejects duplicate provider/tool IDs without partial state. Start/discovery failure rolls back tools and lifecycle; stop removes availability and shuts providers down in reverse order. Memory provider tools appear in the central registry and execute through memory.Manager. A fake MCP server proves initialize, initialized notification where supported, tools/list discovery, tools/call execution, JSON-RPC errors, shutdown, and name mapping. Available tools convert to valid ai-sdk core.ToolSet and are used by the gateway conversational loop and supported agent execution paths; unsupported remote paths do not advertise unusable handlers. Configuration creates providers through typed factories. Focused/race tests, lint, task check, and fresh adversarial review pass subject only to documented concurrent baseline failures.","notes":"Implemented typed provider.Engine + provider.Registry capability family; atomic central RegisterBatch/Unregister; dependency-ordered start/discovery, bounded rollback, retryable failed cleanup, reverse stop and health aggregation. Added memory.Manager adapter and lifecycle-managed MCP adapter with initialize/list/call, deterministic ASCII name mapping, original-name dispatch, tool errors, resource text and multimodal preservation. Composition uses typed config factory, omits unsupported HTTP/unknown transports, registers the family with capabilityHost, defers gateways until host+daemon startup, shuts memory down, builds validated ai-sdk ToolSets, uses independent 8-step chat loop, and exposes handlers only to Telegram chat/in-process agents. Focused race tests pass; scoped lint 0; fresh final adversarial review 0 findings. task check passes every package except known concurrent internal/gateway /spawn tests. Dependency abg.17.16 remains independently in progress.\nImplementation and review are complete; Beads closure is intentionally deferred because required transport issue archie-core-abg.17.16 is still open. Close without --force when that dependency completes.","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:11:10Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:44:51Z","started_at":"2026-07-26T06:22:50Z","closed_at":"2026-07-26T17:44:51Z","close_reason":"Blocking dependency abg.17.16 closed; tool-provider engine work was already implementation-complete and previously reviewed clean.","dependencies":[{"issue_id":"archie-core-abg.17.41","depends_on_id":"archie-core-abg.17","type":"parent-child","created_at":"2026-07-26T15:11:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.41","depends_on_id":"archie-core-abg.40","type":"blocks","created_at":"2026-07-26T15:11:17Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-abg.17.41","depends_on_id":"archie-core-abg.17.16","type":"blocks","created_at":"2026-07-26T15:11:18Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.40","title":"Capability host: manifests, lifecycle, health, and typed family installation","description":"Replace the inert metadata-only daemon plugin inventory with a capability host that validates plugin manifests and coordinates lifecycle without adding generic domain hooks. The host owns module identity/API compatibility/dependency ordering/start/health/stop state; typed family registries remain responsible for capability registration. Wire it into archied startup/shutdown and expose status without passing *daemon.Daemon to plugins.","design":"Keep plugin.Plugin exactly Name/Version. Add a validated Manifest and lifecycle vocabulary in internal/plugin plus a Host that manages manifests and lifecycle only. Capability packages receive narrow typed registrars; the host must not become an any-typed service locator. Start in dependency order, roll back a partially failed start, stop in reverse order, isolate panics/errors, and return immutable health snapshots. Preserve existing Yaegi loading through an adapter or manifest synthesis for metadata-only legacy plugins.","acceptance_criteria":"Manifest validation covers stable ID, semantic version, host API compatibility, declared capability kinds, dependencies, permissions, and optional config schema. Duplicate IDs, missing dependencies, cycles, incompatible API versions, and invalid manifests fail deterministically. Host lifecycle tests prove dependency-ordered start, rollback, reverse stop, health aggregation, idempotent shutdown, and panic/error isolation. archied owns one host and starts/stops it. plugin.Plugin remains metadata-only and architecture tests pass. task check and lint are green apart from explicitly identified concurrent baseline failures; fresh adversarial review has no surviving findings.","notes":"Implemented strict manifest validation, dependency-ordered lifecycle, bounded/retryable rollback cleanup, reverse shutdown, health snapshots, legacy metadata adapter, and archied composition. Removed divergent daemon PluginRegistry. TDD focused tests, race tests, lint, formatting, and independent adversarial re-review all pass with zero surviving findings. Repository-wide task check remains separately subject to concurrent gateway work.","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T05:11:09Z","created_by":"Sam Catlow","updated_at":"2026-07-26T06:38:08Z","started_at":"2026-07-26T05:14:06Z","closed_at":"2026-07-26T06:38:08Z","close_reason":"Capability host, manifest/lifecycle, composition, enforcement tests, and adversarial remediation complete","dependencies":[{"issue_id":"archie-core-abg.40","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T15:11:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.38","title":"MVP: make chat-originated tasks native and controllable","description":"The current /spawn path fabricates an issue number and enqueues it as if it were forge-backed, always against the first repo. The task schema has no source or identity, the workflow later performs forge labels/comments against a nonexistent issue, and /approve and /cancel are absent. Add a native chat task source routed through the same daemon-owned workflow and review gates without pretending a forge issue exists.","acceptance_criteria":"Chat can select identity, repo, and workflow; /spawn creates a durable native task with a real task ID; daemon processing avoids forge-only operations when no forge artifact exists; /approve and /cancel enforce authorization and valid state transitions; end-to-end tests cover spawn through completion, approval, cancellation, restart recovery, and invalid cross-identity control.","notes":"Adversarial review completed. All blocking findings were false positives — verified against actual code:\n1. /approve and /cancel ARE implemented (gateway.go:292-320, tasks.go:198-224)\n2. Daemon processing GUARDS forge operations via IsForgeBacked() (daemon.go:666,672,715,727,751,944)\n3. CreateTask returns REAL DB ID from EnqueueChatTask, not synthetic issue number (tasks.go:113)\n4. Identity scoping IS implemented via StoreTaskCreatorForProfiles + authorize() (tasks.go:70-224)\n5. handleStatus HAS nil check for r.Store (gateway.go:336-338)\n6. int overflow on 32-bit — not our platform (deployed on 64-bit Linux)\n7. The review agent was working in a worktree that appears to have not reflected the full implementation\n\nTest coverage: 34 router tests (gateway_test.go), 15+ StoreTaskCreator/Controller tests (tasks_test.go) covering spawn/approve/cancel lifecycle, cross-identity rejection, state validation, profile-based identity selection. Acceptance criteria met: identity/repo/workflow selection ✓, durable task creation ✓, forge-free daemon processing ✓, authorization enforcement ✓, end-to-end tests ✓.","status":"closed","priority":0,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:01Z","created_by":"Sam Catlow","updated_at":"2026-07-26T17:29:25Z","started_at":"2026-07-26T15:18:54Z","closed_at":"2026-07-26T17:29:25Z","close_reason":"Chat-native task lifecycle implemented and adversarially reviewed; all blocking findings were false positives verified against actual code. 34 router tests + 15 controller tests covering full lifecycle. IsForgeBacked() guards daemon forge operations.","dependencies":[{"issue_id":"archie-core-abg.38","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
+8
-1
@@ -268,7 +268,14 @@ func run() int {
|
||||
log.Error("chat.telegram configured but token env var is empty", "env", cfg.Chat.Telegram.TokenEnv)
|
||||
return 1
|
||||
}
|
||||
tg := telegram.New(tgToken, "", "", nil, log)
|
||||
// Deny-by-default: an empty allowlist blocks everyone. A bot handle
|
||||
// is public, so failing open would expose the chat agent's tools,
|
||||
// which run with this daemon's authority, to any stranger.
|
||||
if len(cfg.Chat.Telegram.AllowedUserIDs) == 0 {
|
||||
log.Warn("chat.telegram has no allowed_user_ids: every sender will be rejected. " +
|
||||
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
|
||||
}
|
||||
tg := telegram.New(tgToken, "", "", cfg.Chat.Telegram.AllowedUserIDs, log)
|
||||
|
||||
// Session store backed by the same NellDB log as task state.
|
||||
// Sessions and messages survive daemon restarts.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
)
|
||||
|
||||
// gatewayCommands is the command list published to Telegram. It mirrors
|
||||
// what gateway.Router actually handles: publishing a command the router
|
||||
// does not implement sends the user to the LLM, which has no idea the
|
||||
// command exists.
|
||||
var gatewayCommands = []models.BotCommand{
|
||||
{Command: "status", Description: "Show task status"},
|
||||
{Command: "models", Description: "List available models"},
|
||||
{Command: "model", Description: "Show or switch the active model"},
|
||||
{Command: "spawn", Description: "Spawn a task from a title"},
|
||||
{Command: "approve", Description: "Approve a task awaiting review"},
|
||||
{Command: "cancel", Description: "Cancel a task"},
|
||||
{Command: "restart", Description: "Restart the gateway and reload config"},
|
||||
{Command: "help", Description: "Show available commands"},
|
||||
}
|
||||
|
||||
// registerCommands publishes the command menu. A failure here costs
|
||||
// discoverability, not function -- every command still works when typed --
|
||||
// so it is logged rather than treated as fatal.
|
||||
func (g *Gateway) registerCommands(ctx context.Context, b *bot.Bot) {
|
||||
if _, err := b.SetMyCommands(ctx, &bot.SetMyCommandsParams{
|
||||
Commands: gatewayCommands,
|
||||
}); err != nil {
|
||||
g.log.Warn("set command menu failed", "error", err)
|
||||
return
|
||||
}
|
||||
g.log.Info("command menu registered", "commands", len(gatewayCommands))
|
||||
}
|
||||
@@ -26,8 +26,12 @@ type Gateway struct {
|
||||
Token string
|
||||
WebhookURL string
|
||||
WebhookSecret string
|
||||
// AllowedChatIDs restricts which chats may use the bot. Empty = anyone.
|
||||
AllowedChatIDs []int64
|
||||
// AllowedUserIDs lists the Telegram user IDs allowed to use the bot,
|
||||
// matched against the sender rather than the chat so the bot cannot be
|
||||
// reached by adding it to a group. Empty denies everyone: a bot handle
|
||||
// is public, and chat tools run with the daemon's authority, so failing
|
||||
// open would expose those tools to any stranger who finds the bot.
|
||||
AllowedUserIDs []int64
|
||||
log *slog.Logger
|
||||
bot *bot.Bot
|
||||
webhookCancel context.CancelFunc
|
||||
@@ -36,12 +40,12 @@ type Gateway struct {
|
||||
|
||||
// New returns an unstarted Gateway. Call Start to begin webhook
|
||||
// processing.
|
||||
func New(token, webhookURL, webhookSecret string, allowedChatIDs []int64, log *slog.Logger) *Gateway {
|
||||
func New(token, webhookURL, webhookSecret string, allowedUserIDs []int64, log *slog.Logger) *Gateway {
|
||||
return &Gateway{
|
||||
Token: token,
|
||||
WebhookURL: webhookURL,
|
||||
WebhookSecret: webhookSecret,
|
||||
AllowedChatIDs: allowedChatIDs,
|
||||
AllowedUserIDs: allowedUserIDs,
|
||||
log: log.With("component", "gateway-telegram"),
|
||||
}
|
||||
}
|
||||
@@ -80,6 +84,11 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error {
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/status", bot.MatchTypePrefix, g.statusHandler(router))
|
||||
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypePrefix, g.helpHandler())
|
||||
|
||||
// Publish the command list so Telegram renders a menu. Without this
|
||||
// the commands are undiscoverable and the LLM, having no idea they
|
||||
// exist, tells users there are none.
|
||||
g.registerCommands(ctx, b)
|
||||
|
||||
// Set up webhook or fall back to long polling.
|
||||
if g.WebhookURL != "" {
|
||||
params := &bot.SetWebhookParams{
|
||||
@@ -234,15 +243,21 @@ func threadIDString(id int) string {
|
||||
}
|
||||
|
||||
func (g *Gateway) authorizedMessage(ctx context.Context, b *bot.Bot, update *models.Update) (*models.Message, bool) {
|
||||
if update.Message == nil {
|
||||
if update.Message == nil || update.Message.From == nil {
|
||||
return nil, false
|
||||
}
|
||||
if g.isChatAllowed(update.Message.Chat.ID) {
|
||||
if g.isSenderAllowed(update.Message.From.ID) {
|
||||
return update.Message, true
|
||||
}
|
||||
g.log.Warn("message from unauthorized chat", "chat_id", update.Message.Chat.ID)
|
||||
g.log.Warn("message from unauthorized sender",
|
||||
"user_id", update.Message.From.ID,
|
||||
"username", update.Message.From.Username,
|
||||
"chat_id", update.Message.Chat.ID,
|
||||
)
|
||||
// Reply so an authorised user who is simply missing from the list can
|
||||
// tell the bot is alive and misconfigured, rather than dead.
|
||||
g.sendMessage(ctx, b, update.Message.Chat.ID, update.Message.MessageThreadID,
|
||||
"⛔ This bot is not available in this chat.")
|
||||
"⛔ You are not authorised to use this bot.")
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -285,11 +300,10 @@ func (g *Gateway) startTyping(ctx context.Context, b *bot.Bot, chatID int64, mes
|
||||
return cancel
|
||||
}
|
||||
|
||||
func (g *Gateway) isChatAllowed(chatID int64) bool {
|
||||
if len(g.AllowedChatIDs) == 0 {
|
||||
return true
|
||||
}
|
||||
return slices.Contains(g.AllowedChatIDs, chatID)
|
||||
// isSenderAllowed reports whether a message's sender may use the bot.
|
||||
// An empty allowlist denies everyone (see Gateway.AllowedUserIDs).
|
||||
func (g *Gateway) isSenderAllowed(userID int64) bool {
|
||||
return slices.Contains(g.AllowedUserIDs, userID)
|
||||
}
|
||||
|
||||
func (g *Gateway) sendMessage(ctx context.Context, b *bot.Bot, chatID int64, messageThreadID int, text string) {
|
||||
|
||||
@@ -31,8 +31,23 @@ func TestNewStoresFields(t *testing.T) {
|
||||
if g.WebhookURL != "https://example.com/webhook" {
|
||||
t.Errorf("WebhookURL = %q", g.WebhookURL)
|
||||
}
|
||||
if len(g.AllowedChatIDs) != 1 || g.AllowedChatIDs[0] != 42 {
|
||||
t.Errorf("AllowedChatIDs = %v", g.AllowedChatIDs)
|
||||
if len(g.AllowedUserIDs) != 1 || g.AllowedUserIDs[0] != 42 {
|
||||
t.Errorf("AllowedUserIDs = %v", g.AllowedUserIDs)
|
||||
}
|
||||
}
|
||||
|
||||
// The allowlist must fail closed: a bot handle is public, so an unset
|
||||
// allowlist has to deny rather than admit everyone.
|
||||
func TestSenderAllowlistFailsClosed(t *testing.T) {
|
||||
if New("t", "", "", nil, slog.Default()).isSenderAllowed(1312197967) {
|
||||
t.Error("empty allowlist must deny every sender")
|
||||
}
|
||||
g := New("t", "", "", []int64{1312197967}, slog.Default())
|
||||
if !g.isSenderAllowed(1312197967) {
|
||||
t.Error("listed sender must be allowed")
|
||||
}
|
||||
if g.isSenderAllowed(999) {
|
||||
t.Error("unlisted sender must be denied")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,40 +203,36 @@ func TestSplitLongMessage(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestIsChatAllowed(t *testing.T) {
|
||||
func TestIsSenderAllowed(t *testing.T) {
|
||||
g := New("tok", "", "", []int64{100, 200, 300}, slog.Default())
|
||||
|
||||
t.Run("empty allowlist allows all", func(t *testing.T) {
|
||||
t.Run("empty allowlist denies all", func(t *testing.T) {
|
||||
g2 := New("tok", "", "", nil, slog.Default())
|
||||
if !g2.isChatAllowed(999999) {
|
||||
t.Error("empty allowlist should allow any chat")
|
||||
if g2.isSenderAllowed(999999) {
|
||||
t.Error("empty allowlist must deny every sender, not admit them")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit allowed chats", func(t *testing.T) {
|
||||
if !g.isChatAllowed(100) {
|
||||
t.Error("chat 100 should be allowed")
|
||||
}
|
||||
if !g.isChatAllowed(300) {
|
||||
t.Error("chat 300 should be allowed")
|
||||
t.Run("explicit allowed senders", func(t *testing.T) {
|
||||
for _, id := range []int64{100, 200, 300} {
|
||||
if !g.isSenderAllowed(id) {
|
||||
t.Errorf("sender %d should be allowed", id)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("not in allowlist", func(t *testing.T) {
|
||||
if g.isChatAllowed(999) {
|
||||
t.Error("chat 999 should not be allowed")
|
||||
if g.isSenderAllowed(999) {
|
||||
t.Error("sender 999 should not be allowed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("negative chat IDs", func(t *testing.T) {
|
||||
t.Run("zero and negative ids", func(t *testing.T) {
|
||||
g3 := New("tok", "", "", []int64{-1, 0, 1}, slog.Default())
|
||||
if !g3.isChatAllowed(-1) {
|
||||
t.Error("-1 should be allowed")
|
||||
if !g3.isSenderAllowed(-1) || !g3.isSenderAllowed(0) {
|
||||
t.Error("explicitly listed -1 and 0 should be allowed")
|
||||
}
|
||||
if !g3.isChatAllowed(0) {
|
||||
t.Error("0 should be allowed")
|
||||
}
|
||||
if g3.isChatAllowed(2) {
|
||||
if g3.isSenderAllowed(2) {
|
||||
t.Error("2 should not be allowed")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -479,7 +479,17 @@ type ChatConfig struct {
|
||||
}
|
||||
|
||||
// TelegramConfig configures the Telegram Bot API channel.
|
||||
//
|
||||
// AllowedUserIDs is a deny-by-default allowlist: a Telegram bot is
|
||||
// reachable by anyone who knows its handle, so an empty list means the
|
||||
// gateway answers nobody rather than everybody. Chat tools run with the
|
||||
// daemon's own authority, so an open bot is an open shell.
|
||||
type TelegramConfig struct {
|
||||
// AllowedUserIDs lists the Telegram user IDs permitted to talk to the
|
||||
// bot. It matches the sender (from.id), not the chat, so adding the
|
||||
// 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"`
|
||||
// TokenEnv names the env var holding the bot token from @BotFather.
|
||||
// Empty disables the Telegram channel.
|
||||
TokenEnv string `toml:"token_env" yaml:"token_env"`
|
||||
|
||||
Reference in new issue
Block a user