From b6ec42f15ac744d34815a86834cfd56605b2f899 Mon Sep 17 00:00:00 2001 From: shiv Date: Thu, 26 Nov 2026 22:24:28 +0530 Subject: [PATCH] fix(chatbridge): address review notes on the bridge core - Require https for base_url. The bot token travels in the URL path and the responses are the updates the bridge acts on, so plain http is accepted only with ARTEX_NOTIFY_ALLOW_LOCAL=1, for a local test server. - Cut replies by UTF-16 code units, which is how Telegram counts its 4096 limit, so emoji-heavy text is no longer rejected. A cut never splits a character. - Cap a server-sent retry_after at the backoff ceiling (1 minute). - Pause one second after an empty poll, so a self-hosted Bot API that ignores the long-poll timeout cannot spin the loop. - When the refused-chat memory is full, start over instead of muting every new chat, which also muted the operator's own chat. Saving the configuration of the same bot keeps the memory. - Fix two stale comments that said an empty allowlist keeps the bridge off (migration 0015 is unreleased, so editing its comment is safe). Co-authored-by: krad <222954346+dar1k0@users.noreply.github.com> --- chatbridge/router.go | 25 ++++++++++++-- chatbridge/router_test.go | 23 ++++++++++++- chatbridge/telegram.go | 46 ++++++++++++++++++++----- chatbridge/telegram_test.go | 52 +++++++++++++++++++++++++++-- db/migrations/0015_chat_bridges.sql | 9 ++--- docs/chat-bridge.md | 13 +++++--- notify/http.go | 4 +++ server/chatbridge.go | 18 ++++++++-- server/chatbridge_test.go | 18 +++++++++- server/server.go | 4 +-- 10 files changed, 183 insertions(+), 29 deletions(-) diff --git a/chatbridge/router.go b/chatbridge/router.go index 2e48077c..ef10630b 100644 --- a/chatbridge/router.go +++ b/chatbridge/router.go @@ -141,14 +141,33 @@ func (r *Router) refuse(chatID string) (Decision, string) { return DecisionMuted, "" } if len(r.refused) >= maxRefusedChats { - // A flood of distinct chats: stop answering any new one rather than - // grow without bound or forget earlier refusals. - return DecisionMuted, "" + // A flood of distinct chats: start over rather than grow without + // bound. Muting every new chat instead would also mute the operator's + // own chat, which then never learns its ID. The cost is that a chat + // refused before the reset can get one more refusal. + clear(r.refused) } r.refused[chatID] = true return DecisionRefused, "This chat is not allowed to use this ARTEX bot. If it is yours, add chat ID " + chatID + " to the allowlist in ARTEX (System → Chat bot)." } +// KeepRefusals carries the refusal memory of a previous router over, so +// saving the configuration of the same bot does not refuse every stranger a +// second time. Call it before the router is in use. +func (r *Router) KeepRefusals(prev *Router) { + if prev == nil || prev == r { + return + } + prev.mu.Lock() + defer prev.mu.Unlock() + r.mu.Lock() + defer r.mu.Unlock() + r.refused = make(map[string]bool, len(prev.refused)) + for id := range prev.refused { + r.refused[id] = true + } +} + func (r *Router) help() string { var b strings.Builder b.WriteString("ARTEX bot commands:\n/help - this list") diff --git a/chatbridge/router_test.go b/chatbridge/router_test.go index 5d4ea434..4a8c22c1 100644 --- a/chatbridge/router_test.go +++ b/chatbridge/router_test.go @@ -70,12 +70,33 @@ func TestRouteRefusalMemoryIsBounded(t *testing.T) { for i := 0; i < maxRefusedChats; i++ { r.Route(context.Background(), KindTelegram, nil, msg("c"+itoa(i), "hi")) } - if d, reply := r.Route(context.Background(), KindTelegram, nil, msg("brand-new", "hi")); d != DecisionMuted || reply != "" { + // Past the cap the memory starts over: a new chat (it may be the + // operator's own) still gets its refusal with the chat ID. + if d, reply := r.Route(context.Background(), KindTelegram, nil, msg("brand-new", "hi")); d != DecisionRefused || !strings.Contains(reply, "brand-new") { t.Fatalf("over the cap: got %v %q", d, reply) } if len(r.refused) > maxRefusedChats { t.Fatalf("refused set grew to %d", len(r.refused)) } + if d, _ := r.Route(context.Background(), KindTelegram, nil, msg("brand-new", "again")); d != DecisionMuted { + t.Fatalf("after the reset: got %v, want muted", d) + } +} + +func TestRouterKeepRefusals(t *testing.T) { + prev := testRouter() + prev.Route(context.Background(), KindTelegram, nil, msg("555", "hi")) + next := testRouter() + next.KeepRefusals(prev) + if d, reply := next.Route(context.Background(), KindTelegram, nil, msg("555", "hi")); d != DecisionMuted || reply != "" { + t.Fatalf("carried refusal: got %v %q", d, reply) + } + if d, _ := next.Route(context.Background(), KindTelegram, nil, msg("556", "hi")); d != DecisionRefused { + t.Fatalf("new chat: got %v", d) + } + if d, _ := prev.Route(context.Background(), KindTelegram, nil, msg("556", "hi")); d != DecisionRefused { + t.Fatalf("the previous router must not share the new memory: got %v", d) + } } func TestRouteDropsStaleAndBotAndEmpty(t *testing.T) { diff --git a/chatbridge/telegram.go b/chatbridge/telegram.go index dd602158..9567d9fb 100644 --- a/chatbridge/telegram.go +++ b/chatbridge/telegram.go @@ -8,11 +8,12 @@ import ( "fmt" "io" "net/http" + "net/url" "regexp" "strconv" "strings" "time" - "unicode/utf8" + "unicode/utf16" "github.com/Autumn-27/artex/notify" ) @@ -28,8 +29,9 @@ const ( telegramClientWindow = telegramPollWindow + 15*time.Second // telegramPollLimit caps one getUpdates batch. telegramPollLimit = 50 - // telegramTextLimit is the Bot API message limit (4096 characters). The - // reply is cut a little earlier to leave room for the ellipsis. + // telegramTextLimit is where a reply is cut, in UTF-16 code units: the Bot + // API limit is 4096 characters counted in UTF-16, and the cut is a little + // earlier to leave a margin. telegramTextLimit = 4000 // telegramBodyLimit caps a response body; 50 text updates fit well inside. telegramBodyLimit = 1 << 20 @@ -68,6 +70,13 @@ func (telegramTransport) Validate(cfg map[string]any) error { if err := notify.ValidateEndpointURL(base); err != nil { return fmt.Errorf("invalid API URL: %w", err) } + // The token is in the URL path, and the responses are the updates the + // bridge acts on: over plain http both could be read or forged on the + // network path. http is only for a local test server, behind the same + // opt-in as other local targets. + if u, err := url.Parse(base); err == nil && strings.EqualFold(u.Scheme, "http") && !notify.AllowLocalTargets() { + return fmt.Errorf("the API URL must use https (http is allowed only with %s=1, for a local test server)", notify.AllowLocalTargetsEnv) + } } return nil } @@ -157,7 +166,7 @@ func (t telegramTransport) Send(ctx context.Context, cfg map[string]any, chatID, } body := map[string]any{ "chat_id": chatID, - "text": truncateRunes(text, telegramTextLimit), + "text": truncateUTF16(text, telegramTextLimit), // Plain text on purpose: no parse_mode, so agent output can never be // rejected for a stray markup character or render as a link. "link_preview_options": map[string]any{"is_disabled": true}, @@ -255,11 +264,30 @@ func cfgString(cfg map[string]any, key string) string { return strings.TrimSpace(s) } -// truncateRunes cuts s to at most n runes, marking the cut. -func truncateRunes(s string, n int) string { - if utf8.RuneCountInString(s) <= n { +// truncateUTF16 cuts s to at most n UTF-16 code units, marking the cut. +// Telegram counts the message limit in UTF-16 units, so a character outside +// the Basic Multilingual Plane (most emoji) counts twice. The cut never +// splits a character. +func truncateUTF16(s string, n int) string { + if utf16Len(s) <= n { return s } - r := []rune(s) - return string(r[:n-1]) + "…" + used := 0 + for i, r := range s { + // range yields U+FFFD for invalid UTF-8, so RuneLen is 1 or 2 here. + w := utf16.RuneLen(r) + if used+w > n-1 { // n-1: one unit is kept for the ellipsis + return s[:i] + "…" + } + used += w + } + return s +} + +func utf16Len(s string) int { + n := 0 + for _, r := range s { + n += utf16.RuneLen(r) + } + return n } diff --git a/chatbridge/telegram_test.go b/chatbridge/telegram_test.go index 8973c398..fe448c01 100644 --- a/chatbridge/telegram_test.go +++ b/chatbridge/telegram_test.go @@ -79,6 +79,45 @@ func TestTelegramValidate(t *testing.T) { if err := tr.Validate(map[string]any{"bot_token": testToken}); err != nil { t.Fatalf("valid config refused: %v", err) } + if err := tr.Validate(map[string]any{"bot_token": testToken, "base_url": "https://bot-api.example.com"}); err != nil { + t.Fatalf("https base_url refused: %v", err) + } +} + +func TestTelegramValidateRequiresHTTPS(t *testing.T) { + tr := telegramTransport{} + cfg := map[string]any{"bot_token": testToken, "base_url": "http://bot-api.example.com"} + t.Setenv(notify.AllowLocalTargetsEnv, "") + if err := tr.Validate(cfg); err == nil || !strings.Contains(err.Error(), "https") { + t.Fatalf("plain http base_url: err = %v, want an https error", err) + } + t.Setenv(notify.AllowLocalTargetsEnv, "1") + if err := tr.Validate(cfg); err != nil { + t.Fatalf("plain http with the local opt-in: %v", err) + } +} + +func TestTruncateUTF16(t *testing.T) { + cases := []struct { + in string + n int + want string + }{ + {"hello", 5, "hello"}, + {"hello!", 5, "hell…"}, + {"éééééé", 5, "éééé…"}, + // An emoji is two UTF-16 units and is never split. + {"ab😀cd", 5, "ab😀…"}, + {"ab😀cd", 4, "ab…"}, + } + for _, c := range cases { + if got := truncateUTF16(c.in, c.n); got != c.want { + t.Errorf("truncateUTF16(%q, %d) = %q, want %q", c.in, c.n, got, c.want) + } + if got := truncateUTF16(c.in, c.n); utf16Len(got) > c.n { + t.Errorf("truncateUTF16(%q, %d) is %d units", c.in, c.n, utf16Len(got)) + } + } } func TestTelegramPollParsesAndSendsOffset(t *testing.T) { @@ -124,8 +163,17 @@ func TestTelegramSendIsPlainTextAndTruncated(t *testing.T) { t.Fatal("replies must be sent as plain text") } text, _ := body["text"].(string) - if n := len([]rune(text)); n != telegramTextLimit || !strings.HasSuffix(text, "…") { - t.Fatalf("text has %d runes, suffix %q", n, text[len(text)-3:]) + if n := utf16Len(text); n != telegramTextLimit || !strings.HasSuffix(text, "…") { + t.Fatalf("text has %d UTF-16 units, suffix %q", n, text[len(text)-3:]) + } + + // Emoji count twice toward Telegram's limit. + if err := (telegramTransport{}).Send(context.Background(), cfg, "100", strings.Repeat("😀", telegramTextLimit)); err != nil { + t.Fatal(err) + } + text, _ = f.bodies["sendMessage"]["text"].(string) + if n := utf16Len(text); n > telegramTextLimit || !strings.HasSuffix(text, "…") { + t.Fatalf("emoji text has %d UTF-16 units, over the limit %d", n, telegramTextLimit) } if body["chat_id"] != "100" { t.Fatalf("chat_id = %v", body["chat_id"]) diff --git a/db/migrations/0015_chat_bridges.sql b/db/migrations/0015_chat_bridges.sql index b7ca83da..53e4e9ed 100644 --- a/db/migrations/0015_chat_bridges.sql +++ b/db/migrations/0015_chat_bridges.sql @@ -3,10 +3,11 @@ -- part of a task archive. -- -- config is sealed at rest by db/secrets.go (it holds the bot token) and --- masked in API responses. allowed_chats is the mandatory allowlist of chat --- ids, a JSON array of strings; the server refuses to enable a bridge while --- it is empty. poll_offset is the transport's update cursor, committed before --- an update is acted on so a restart never replays a command. +-- masked in API responses. allowed_chats is the allowlist of chat ids, a JSON +-- array of strings. Only listed chats are served; an empty list serves none +-- and only tells each chat its ID. poll_offset is the transport's update +-- cursor, committed before an update is acted on so a restart never replays +-- a command. -- -- config_version grows on every save. The poller writes its cursor only for -- the version it read, so a cursor of the old bot can never land on a row diff --git a/docs/chat-bridge.md b/docs/chat-bridge.md index 2f164e0e..475cd579 100644 --- a/docs/chat-bridge.md +++ b/docs/chat-bridge.md @@ -26,14 +26,17 @@ Outbound notifications (pushing findings to a chat) are a separate feature under ## Security model - **Only allowlisted chats are served.** A chat that is not listed gets one refusal line, naming its - chat ID, and is then ignored for the life of the process. An empty allowlist serves no chat at all; - that is the state a new bot starts in while you collect chat IDs. Allowing a group allows every - member of that group. + chat ID, and is then ignored. The bot remembers up to 1024 refused chats, across saves of the same + bot; past that it starts over, so a chat may be refused one more time but a new chat always learns + its ID. An empty allowlist serves no chat at all; that is the state a new bot starts in while you + collect chat IDs. Allowing a group allows every member of that group. - **No inbound port.** The bot uses long polling (`getUpdates`) over outbound HTTPS. - **The token is a secret.** It is encrypted at rest with `keys/secret.key` like other stored secrets, shown masked in the UI and API, and never written to logs or error messages (errors keep only the scheme and host of the API address). Changing the API address requires entering the - token again, so a stored token is never sent to a new host. + token again, so a stored token is never sent to a new host. The API address must use `https`: + the token travels in the URL path, and the replies are the updates the bot acts on. Plain `http` + is accepted only with `ARTEX_NOTIFY_ALLOW_LOCAL=1`, for a local test server. - **Same network guard as notifications.** Calls refuse loopback and link-local addresses (including cloud metadata) unless `ARTEX_NOTIFY_ALLOW_LOCAL=1`, and never follow a cross-host redirect. - **No replays.** The update cursor is committed before a batch is acted on, so a crash loses a @@ -59,5 +62,5 @@ All routes require the administrator JWT. `config` follows the notification channel convention: a masked value sent back unchanged keeps the stored secret, and an empty string clears a field. Telegram's fields are `bot_token` and the -optional `base_url` (for a self-hosted Bot API server). The live `status.state` is `off`, +optional `base_url` (an `https` address of a self-hosted Bot API server). The live `status.state` is `off`, `connecting`, `online` or `error`, with `last_error` when it fails. diff --git a/notify/http.go b/notify/http.go index 5056cbf1..41e70cf1 100644 --- a/notify/http.go +++ b/notify/http.go @@ -324,3 +324,7 @@ func RedactTransportError(err error) string { return redactTransportError(err) } // ValidateEndpointURL checks a configured platform address the way the // channels do: http(s) only, a host, and no loopback or link-local literal. func ValidateEndpointURL(raw string) error { return validateHTTPURL(raw) } + +// AllowLocalTargets reports whether ARTEX_NOTIFY_ALLOW_LOCAL is set, the +// explicit opt-in for local and test endpoints. +func AllowLocalTargets() bool { return allowLocalTargets() } diff --git a/server/chatbridge.go b/server/chatbridge.go index 6de9ee29..58c48b42 100644 --- a/server/chatbridge.go +++ b/server/chatbridge.go @@ -33,6 +33,8 @@ const ( chatBridgeMinRetry = 2 * time.Second chatBridgeMaxRetry = time.Minute chatBridgeSendWait = 15 * time.Second + // chatBridgeEmptyPollWait is the pause after a poll that returned nothing. + chatBridgeEmptyPollWait = time.Second ) // chatBridgeStatus is the live state shown in the UI ("bot online"). @@ -200,6 +202,7 @@ func (r *chatBridgeRunner) step(ctx context.Context, kind string) time.Duration r.mu.Lock() known := st.sig == sig && st.router != nil router := st.router + prevBot := st.status.Bot r.mu.Unlock() if !known { r.setState(kind, "connecting") @@ -207,7 +210,12 @@ func (r *chatBridgeRunner) step(ctx context.Context, kind string) time.Duration if err != nil { return r.fail(kind, err) } + prev := router router = &chatbridge.Router{BotUserName: me.UserName, Commands: r.commands(kind)} + if prevBot != nil && prevBot.ID == me.ID { + // Same bot, new settings: chats it already refused stay refused. + router.KeepRefusals(prev) + } r.mu.Lock() st.sig, st.router = sig, router st.status.Bot = &me @@ -234,7 +242,10 @@ func (r *chatBridgeRunner) step(ctx context.Context, kind string) time.Duration var ra *chatbridge.RetryAfterError if errors.As(err, &ra) { r.fail(kind, err) - return ra.After + // The wait comes from the server. Cap it so a broken or hostile + // API address cannot park the bridge for hours; polling early + // only earns another 429 with a fresh retry_after. + return min(max(ra.After, chatBridgeMinRetry), chatBridgeMaxRetry) } return r.fail(kind, err) } @@ -243,7 +254,10 @@ func (r *chatBridgeRunner) step(ctx context.Context, kind string) time.Duration st.status.State, st.status.LastPollAt, st.retry = "online", &now, 0 r.mu.Unlock() if len(updates) == 0 { - return 0 + // A real long poll returns empty only after its window, so this + // pause costs nothing there; it keeps a self-hosted Bot API that + // ignores the timeout from spinning the loop. + return chatBridgeEmptyPollWait } next := b.PollOffset diff --git a/server/chatbridge_test.go b/server/chatbridge_test.go index 3720aae8..2151cb9f 100644 --- a/server/chatbridge_test.go +++ b/server/chatbridge_test.go @@ -160,6 +160,15 @@ func TestChatBridgeRunnerStep(t *testing.T) { } } + // Saving the same bot's configuration keeps the refusal memory: a chat + // refused before the save is not refused a second time. + r.Reload(fakeBridgeKind) + fake.updates = []chatbridge.Update{{ID: 32, ChatID: "777", UserID: "8", Text: "hello?", Date: time.Now()}} + r.step(ctx, fakeBridgeKind) + if got := fake.sent["777"]; len(got) != 1 { + t.Fatalf("after a save, refused chat replies = %q, want no second refusal", got) + } + // Disabling turns the bridge off. if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{Kind: fakeBridgeKind, Enabled: false, Config: json.RawMessage(`{}`)}, false); err != nil { t.Fatal(err) @@ -205,9 +214,16 @@ func TestChatBridgeRunnerBackoff(t *testing.T) { if st := r.Status(fakeBridgeKind); st.State != "error" || st.LastError == "" { t.Fatalf("status = %+v", st) } + // A retry_after from the server is capped. + fake.pollErr = &chatbridge.RetryAfterError{After: 3 * time.Hour, Msg: "rate limited"} + if wait := r.step(ctx, fakeBridgeKind); wait != chatBridgeMaxRetry { + t.Fatalf("huge retry-after wait = %v, want the cap %v", wait, chatBridgeMaxRetry) + } r.Reload(fakeBridgeKind) fake.pollErr = nil - if wait := r.step(ctx, fakeBridgeKind); wait != 0 || r.Status(fakeBridgeKind).State != "online" { + // An empty poll pauses briefly, so an API that ignores the long-poll + // timeout cannot spin the loop. + if wait := r.step(ctx, fakeBridgeKind); wait != chatBridgeEmptyPollWait || r.Status(fakeBridgeKind).State != "online" { t.Fatalf("after reload: wait %v status %+v", wait, r.Status(fakeBridgeKind)) } } diff --git a/server/server.go b/server/server.go index 74450e7b..dfee4fce 100644 --- a/server/server.go +++ b/server/server.go @@ -292,8 +292,8 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi // Vulnerability IM push delivery engine. Sits beside the Scheduler but independent: push latency demands (3s) // differ from the triggers' business cadence, and neither's failures drag the other down — a stuck push must not affect agent triggers. go newNotifier(s).Run(s.ctx) - // Inbound chat bridges: an operator drives ARTEX from a chat app. Off until a bridge is enabled - // with a non-empty chat allowlist; long polling only, so no inbound port is opened. + // Inbound chat bridges: an operator drives ARTEX from a chat app. Off until a bridge is enabled, + // and only allowlisted chats are served; long polling only, so no inbound port is opened. s.chatBridges = newChatBridgeRunner(m.pg) go s.chatBridges.Run(s.ctx) logSink.SetDB(ctx, m.pg) // restore last 100 log rows and enable async persistence