[PR #6442] [MERGED] fix(tgbot): handle deleted inbounds on stale get_clients_for_* taps #6269

Closed
opened 2026-11-02 04:07:32 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6442
Author: @BlindMaster24
Created: 9/9/2026
Status: ✅ Merged
Merged: 9/10/2026
Merged by: @MHSanaei

Base: main ← Head: fix/tgbot-stale-button-panic


📝 Commits (2)

  • c3fce6d fix(tgbot): close stale-inbound TOCTOU and contain handler panics
  • 0ffa841 Merge branch 'main' into fix/tgbot-stale-button-panic

📊 Changes

3 files changed (+176 additions, -43 deletions)

View changed files

📝 internal/web/service/tgbot/tgbot_inbound.go (+1 -6)
📝 internal/web/service/tgbot/tgbot_router.go (+47 -37)
➕ internal/web/service/tgbot/tgbot_stale_button_test.go (+128 -0)

📄 Description

Summary

Stale get_clients_for_sub / get_clients_for_individual / get_clients_for_qr inline-keyboard taps no longer crash the panel when the inbound is deleted in the window between the callback's two GetInbound reads.

Why

The three get_clients_for_* callback cases fetched the inbound a second time with the error discarded:

clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_sub_links")
if err != nil { ... }
inbound, _ := t.inboundService.GetInbound(inboundIdInt)   // error discarded
t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB)

The first lookup (inside getInboundClientsFor) already guarded a missing inbound; the panic needed the TOCTOU window between the two reads — the row vanishing (delete + concurrent tap, or a transient DB failure) between keyboard build and Remark deref. Because answerCallback runs on a bare goroutine with no recover(), that panic killed the entire panel process, not just the bot.

What changed

  • Single-read design — getInboundClientsFor now receives the *model.Inbound row instead of re-reading the DB by ID; the between-reads window is removed rather than guarded. It is called from exactly one place, so the signature change breaks no other caller.
  • chooseInboundClient helper — fetches the inbound once, logs the failure (logger.Warning — a sick DB and a deleted inbound no longer look identical to an operator), answers a getInboundsFailed callback, and builds the keyboard. The three duplicated case bodies collapse to a one-liner each.
  • recover() barrier on all three handler paths — commands and callbacks run through runBotHandler (worker slot + recoverBotPanic), and the th.AnyMessage() free-text state machine (which runs inline on telego's dispatch goroutine, with no library-side recovery in telego v1.12.1) defers recoverBotPanic directly. No bot handler panic can take down the process; it logs via logger.Error instead.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Documentation
  • Tests only
  • Build / CI / tooling
  • Other

Areas affected

  • Frontend (UI / panel pages)
  • Backend (API endpoints, login, settings)
  • Xray config generation
  • Subscription (share links / Clash / JSON)
  • Statistics / traffic counters
  • Database / migrations
  • Install / upgrade script
  • Docker image
  • Multi-node (sub-nodes)
  • Telegram bot

How was this tested?

  • TestChooseInboundClientStaleInbound — drives chooseInboundClient against a test DB where inbound 42 does not exist, and asserts answerCallbackQuery was called exactly once (the error answer) via a counting mock Telegram API. Removing the guard fails the test with the nil panic itself; dropping only the sendCallbackAnswerTgBot call fails the count assertion.
  • TestGetInboundClientsForUsesProvidedInbound — pins that the keyboard builder consumes the caller-provided row (a reintroduced second DB read reopens the stale-row window). Asserts the built keyboard button text.
  • TestRunBotHandlerRecoversPanic — asserts a panicking handler is contained by runBotHandler; the panic escapes and fails the test without the recover().
  • Mock pattern follows tgbot_send_test.go (httptest + telego.WithAPIServer), throwaway SQLite via database.InitDB(t.TempDir()), std-lib only. gofmt-clean.
  • Full go test ./... requires GCC (CGo/SQLite) which is available on CI; the local Windows box has no C compiler.

Screenshots / recordings

N/A

Breaking changes

None — the happy path is unchanged; only the stale-tap path changed from a potential process crash to an answered error callback, and handler panics are now logged instead of fatal.

Checklist

  • I tested the change locally and confirmed the described behavior.
  • I added or updated tests for the new behavior.
  • go build ./... and the test suite pass locally. (requires GCC/MinGW — CI will verify)
  • For frontend changes: npm run lint, npm run typecheck, and npm run build pass.
  • I updated the Wiki / README / API docs if user-facing behavior changed.
  • My commits follow the project's existing message style.
  • I have no unrelated changes mixed into this PR.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/6442 **Author:** [@BlindMaster24](https://github.com/BlindMaster24) **Created:** 9/9/2026 **Status:** ✅ Merged **Merged:** 9/10/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `fix/tgbot-stale-button-panic` --- ### 📝 Commits (2) - [`c3fce6d`](https://github.com/MHSanaei/3x-ui/commit/c3fce6d50a7ef3abf278826636229b66ffd12558) fix(tgbot): close stale-inbound TOCTOU and contain handler panics - [`0ffa841`](https://github.com/MHSanaei/3x-ui/commit/0ffa841e0c1fcbd2e776cddd43174d3b4b1f62f7) Merge branch 'main' into fix/tgbot-stale-button-panic ### 📊 Changes **3 files changed** (+176 additions, -43 deletions) <details> <summary>View changed files</summary> 📝 `internal/web/service/tgbot/tgbot_inbound.go` (+1 -6) 📝 `internal/web/service/tgbot/tgbot_router.go` (+47 -37) ➕ `internal/web/service/tgbot/tgbot_stale_button_test.go` (+128 -0) </details> ### 📄 Description ## Summary Stale `get_clients_for_sub` / `get_clients_for_individual` / `get_clients_for_qr` inline-keyboard taps no longer crash the panel when the inbound is deleted in the window between the callback's two `GetInbound` reads. ## Why The three `get_clients_for_*` callback cases fetched the inbound a **second** time with the error discarded: ```go clientsKB, err := t.getInboundClientsFor(inboundIdInt, "client_sub_links") if err != nil { ... } inbound, _ := t.inboundService.GetInbound(inboundIdInt) // error discarded t.SendMsgToTgbot(chatId, t.I18nBot("tgbot.answers.chooseClient", "Inbound=="+inbound.Remark), clientsKB) ``` The first lookup (inside `getInboundClientsFor`) already guarded a missing inbound; the panic needed the TOCTOU window between the two reads — the row vanishing (delete + concurrent tap, or a transient DB failure) between keyboard build and `Remark` deref. Because `answerCallback` runs on a bare goroutine with no `recover()`, that panic killed the **entire panel process**, not just the bot. ## What changed - **Single-read design** — `getInboundClientsFor` now receives the `*model.Inbound` row instead of re-reading the DB by ID; the between-reads window is removed rather than guarded. It is called from exactly one place, so the signature change breaks no other caller. - **`chooseInboundClient` helper** — fetches the inbound once, logs the failure (`logger.Warning` — a sick DB and a deleted inbound no longer look identical to an operator), answers a `getInboundsFailed` callback, and builds the keyboard. The three duplicated case bodies collapse to a one-liner each. - **`recover()` barrier on all three handler paths** — commands and callbacks run through `runBotHandler` (worker slot + `recoverBotPanic`), and the `th.AnyMessage()` free-text state machine (which runs inline on telego's dispatch goroutine, with no library-side recovery in telego v1.12.1) defers `recoverBotPanic` directly. No bot handler panic can take down the process; it logs via `logger.Error` instead. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactoring (no behavior change) - [ ] Documentation - [ ] Tests only - [ ] Build / CI / tooling - [ ] Other ## Areas affected - [ ] Frontend (UI / panel pages) - [x] Backend (API endpoints, login, settings) - [ ] Xray config generation - [ ] Subscription (share links / Clash / JSON) - [ ] Statistics / traffic counters - [ ] Database / migrations - [ ] Install / upgrade script - [ ] Docker image - [ ] Multi-node (sub-nodes) - [x] Telegram bot ## How was this tested? - `TestChooseInboundClientStaleInbound` — drives `chooseInboundClient` against a test DB where inbound 42 does not exist, and **asserts `answerCallbackQuery` was called exactly once** (the error answer) via a counting mock Telegram API. Removing the guard fails the test with the nil panic itself; dropping only the `sendCallbackAnswerTgBot` call fails the count assertion. - `TestGetInboundClientsForUsesProvidedInbound` — pins that the keyboard builder consumes the caller-provided row (a reintroduced second DB read reopens the stale-row window). Asserts the built keyboard button text. - `TestRunBotHandlerRecoversPanic` — asserts a panicking handler is contained by `runBotHandler`; the panic escapes and fails the test without the `recover()`. - Mock pattern follows `tgbot_send_test.go` (`httptest` + `telego.WithAPIServer`), throwaway SQLite via `database.InitDB(t.TempDir())`, std-lib only. gofmt-clean. - Full `go test ./...` requires GCC (CGo/SQLite) which is available on CI; the local Windows box has no C compiler. ## Screenshots / recordings N/A ## Breaking changes None — the happy path is unchanged; only the stale-tap path changed from a potential process crash to an answered error callback, and handler panics are now logged instead of fatal. ## Checklist - [x] I tested the change locally and confirmed the described behavior. - [x] I added or updated tests for the new behavior. - [ ] `go build ./...` and the test suite pass locally. (requires GCC/MinGW — CI will verify) - [ ] For frontend changes: npm run lint, npm run typecheck, and npm run build pass. - [ ] I updated the Wiki / README / API docs if user-facing behavior changed. - [x] My commits follow the project's existing message style. - [x] I have no unrelated changes mixed into this PR. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:07:32 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#6269
No description provided.