Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(wecom): prove control of the bot before the install reclaim destroys somebody’s row (MUL-5891) (#6594)
Xichang(Seacen) Zhao02d06229db4c
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 289b6f6b5c..7686881521 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -280,6 +280,11 @@ type Handler struct {// see wecom/binding.go). Nil disables the redeem endpoint (returns 503)// and the OutboundReplier's binding-prompt path.WecomBindingTokens WecomBindingRedeemer++ // WecomCredentialProbe overrides the install-time control check. Nil in+ // production, which gets the real handshake probe; tests inject a fake so+ // the install path runs without a socket.+ WecomCredentialProbe wecom.CredentialProbe// LLM is the basic LLM API layer (MUL-4238): a thin wrapper over the// OpenAI Go SDK backing server-internal one-shot LLM helpers such as chat// title generation. The generic passthrough endpoints were removed indiff --git a/server/internal/handler/wecom_web.go b/server/internal/handler/wecom_web.goindex dd6b492a07..4af9d12d5b 100644--- a/server/internal/handler/wecom_web.go+++ b/server/internal/handler/wecom_web.go@@ -186,6 +186,19 @@ func (h *Handler) RegisterWecomBYO(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusConflict, "this bot is connected to an archived agent in this workspace — restore that agent, or disconnect its bot, before connecting it here")case errors.Is(err, wecom.ErrBotOwnedByAnotherWorkspace):writeError(w, http.StatusConflict, "this bot is already connected to a different Multica workspace — disconnect it there before connecting it here")+ case errors.Is(err, wecom.ErrCredentialsRejected):+ // WeCom itself refused the pair. This is the one branch entitled+ // to blame the credentials, and the only one the admin can act on+ // by going back to the console.+ writeError(w, http.StatusBadRequest, "WeCom rejected this Bot ID and secret — check both on the WeCom admin console, and that the bot is a smart bot with the long connection enabled")+ case errors.Is(err, wecom.ErrCredentialsUnverifiable):+ // The deployment could not reach WeCom. Reporting this as a bad+ // credential sends the admin to rotate a secret that was fine —+ // and a rotated WeCom secret cannot be recovered. 503: nothing is+ // wrong with the input, the check could not be made.+ slog.Warn("wecom install could not verify the bot",+ "error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))+ writeError(w, http.StatusServiceUnavailable, "could not reach WeCom to verify this bot — the credentials were not changed; try again in a moment")default:slog.Warn("wecom install failed","error", err, "workspace_id", uuidToString(wsUUID), "agent_id", uuidToString(agentUUID))@@ -257,7 +270,16 @@ func (h *Handler) wecomInstallService() *wecom.InstallationService {if !ok || res == nil || res.Box == nil {return nil}- svc, err := wecom.NewInstallationService(h.Queries, h.TxStarter, res.Box)+ // The probe is what makes the reclaim inside Upsert safe to run against a+ // row this caller may not own. h.WecomCredentialProbe is a test seam;+ // production leaves it nil and NewInstallationService supplies the real+ // handshake. There is no wiring that leaves the check off — a nil probe is+ // a construction error there, not a fail-open mode.+ var opts []wecom.InstallationOption+ if h.WecomCredentialProbe != nil {+ opts = append(opts, wecom.WithCredentialProbe(h.WecomCredentialProbe))+ }+ svc, err := wecom.NewInstallationService(h.Queries, h.TxStarter, res.Box, opts...)if err != nil {return nil}diff --git a/server/internal/integrations/wecom/credential_probe.go b/server/internal/integrations/wecom/credential_probe.gonew file mode 100644index 0000000000..b20edc40a4--- /dev/null+++ b/server/internal/integrations/wecom/credential_probe.go@@ -0,0 +1,186 @@+package wecom++// credential_probe.go — proving the installer controls the bot.+//+// A BYO install used to persist whatever pair was pasted into the dialog. The+// bot id is not a secret: it is on the WeCom admin console, and any member of+// a workspace can read it back out of GET /wecom/installations. Only the+// secret proves anything, and nothing checked it.+//+// Two things followed, and neither needs an insider.+//+// The routing slot is global. channel_installation's unique index on+// (channel_type, config->>'app_id') has no workspace in it, so an admin of any+// workspace on the deployment could write a row claiming somebody else's bot+// id with a junk secret and hold that slot indefinitely. The rightful owner+// then hits a conflict naming a workspace they cannot see.+//+// Worse, the reclaim is keyed on the same unproven id. A bot the rightful+// owner has merely DISCONNECTED sits revoked, and a revoked row is what+// ReclaimDeadChannelInstallationByAppID hard-deletes — along with every user+// binding, session binding and pending token beneath it. So an outsider+// pasting a bot id they read off a list could destroy another workspace's+// bindings and force everyone there to re-link.+//+// The fix is the one both peers already use: prove control before persisting.+// DingTalk mints an access token (dingtalk/byo_install.go), Slack calls+// auth.test (slack/byo_install.go). WeCom has no REST surface, so the proof+// is the protocol's own handshake — dial, aibot_subscribe, read the verdict,+// hang up. A wrong secret is refused with a non-zero errcode, which is+// exactly the signal.+//+// The probe never runs against a bot somebody else is actively connected to.+// WeCom allows one live subscriber per bot, so a probe against a live slot+// would displace the rightful owner's connection, whose supervisor would+// reconnect and displace the probe in turn — and if the request is then+// refused, a rejected install has knocked a live bot offline for nothing.+// InstallationService.Upsert enforces this: it takes the slot's advisory lock,+// reads the current owner, and returns the conflict without probing for any+// live owner other than the caller's own row (see botSlotConflictErr). What+// reaches the probe is a free slot, a revoked row, an orphan, or a re-install+// of the caller's own bot — nothing anybody else is connected to.++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+)++// ErrCredentialsRejected is WeCom saying the pair is not valid: a wrong+// secret, a bot that no longer exists, a bot whose API mode is off. It is the+// answer that must reach the admin, because it is the one they can act on.+var ErrCredentialsRejected = errors.New("wecom: WeCom rejected this bot id and secret")++// ErrCredentialsUnverifiable is everything else — the dial failed, the+// handshake timed out, the network is down. Distinct from rejection on+// purpose: telling an admin their credentials are wrong when the deployment+// simply could not reach WeCom sends them to rotate a secret that was fine.+var ErrCredentialsUnverifiable = errors.New("wecom: could not reach WeCom to verify this bot")++// rejectionErrCodes are the WeCom global error codes (document/path/90313)+// documented as a refusal of the credential pair itself — the only answers+// entitled to tell an admin their Bot ID or secret is wrong.+//+// Everything else non-zero is ErrCredentialsUnverifiable, deliberately. WeCom+// only guarantees that 0 means success; the subscribe path is also under+// frequency and concurrency protection (45009, 45033), and the platform can+// fail on its own account. Reading any non-zero code as "wrong secret" pushes+// an admin to rotate a long-connection secret that was fine, and a rotated one+// cannot be recovered — the exact damage this file exists to prevent. So the+// list is a whitelist and the default is fail-closed: refuse the install, keep+// the stored credentials untouched, and say we could not verify.+//+// Codes only, never errmsg text: the message is human-facing Chinese prose+// that WeCom is free to reword.+var rejectionErrCodes = map[int]struct{}{+ 40001: {}, // 不合法的secret参数 — the secret does not match this bot+ 40013: {}, // 不合法的CorpID — the identity half of the pair is not valid+}++// credentialProbeTimeout bounds the whole probe. It has to cover a dial and+// one round trip and nothing else, and it is spent with the admin watching a+// spinner, so it is short. Sized off the connection's own two constants+// rather than invented.+const credentialProbeTimeout = handshakeTimeout + subscribeTimeout++// CredentialProbe proves a (bot_id, secret) pair is live. Exported because+// the handler holds one so a test can exercise the install path without a+// socket; production always gets the handshake probe.+type CredentialProbe interface {+ Probe(ctx context.Context, botID, secret string) error+}++// handshakeProbe is the production probe: one connection, one subscribe, no+// read loop, no registration, no sender published. Nothing else in the+// process learns it happened.+type handshakeProbe struct {+ dialer Dialer+ wsURL string+}++// NewHandshakeProbe builds the probe the install service uses. dialer and+// wsURL are test seams; production passes nil and "".+func NewHandshakeProbe(dialer Dialer, wsURL string) *handshakeProbe {+ if wsURL == "" {+ wsURL = DefaultWSURL+ }+ return &handshakeProbe{dialer: dialer, wsURL: wsURL}+}++func (p *handshakeProbe) Probe(ctx context.Context, botID, secret string) error {+ dialer := p.dialer+ if dialer == nil {+ dialer = defaultDialer+ }++ ctx, cancel := context.WithTimeout(ctx, credentialProbeTimeout)+ defer cancel()++ conn, _, err := dialer.DialContext(ctx, p.wsURL, nil)+ if err != nil {+ return fmt.Errorf("%w: dial: %v", ErrCredentialsUnverifiable, err)+ }+ defer conn.Close()++ // The read below does not observe ctx, so the deadline has to be on the+ // socket as well as on the context.+ if dl, ok := ctx.Deadline(); ok {+ _ = conn.SetWriteDeadline(dl)+ _ = conn.SetReadDeadline(dl)+ }++ reqID := newReqID()+ frame, err := json.Marshal(map[string]any{+ "cmd": cmdSubscribe,+ "headers": frameHeaders{ReqID: reqID},+ "body": subscribeBody(botID, secret),+ })+ if err != nil {+ return fmt.Errorf("%w: encode subscribe: %v", ErrCredentialsUnverifiable, err)+ }+ if err := conn.WriteMessage(websocketTextMessage, frame); err != nil {+ return fmt.Errorf("%w: send subscribe: %v", ErrCredentialsUnverifiable, err)+ }++ // Read until our own ack comes back. The server may push other frames+ // first; anything that is not the answer to this req_id is not ours.+ for {+ if err := ctx.Err(); err != nil {+ return fmt.Errorf("%w: %v", ErrCredentialsUnverifiable, err)+ }+ _, payload, err := conn.ReadMessage()+ if err != nil {+ return fmt.Errorf("%w: read subscribe ack: %v", ErrCredentialsUnverifiable, err)+ }+ var env frameEnvelope+ if err := json.Unmarshal(payload, &env); err != nil {+ continue+ }+ if env.Headers.ReqID != reqID {+ continue+ }+ if env.ErrCode != 0 {+ if _, rejected := rejectionErrCodes[env.ErrCode]; rejected {+ // The one answer the admin can act on, and the only branch+ // that blames their credentials.+ return fmt.Errorf("%w (errcode %d: %s)", ErrCredentialsRejected, env.ErrCode, env.ErrMsg)+ }+ // Unknown non-zero: throttling, a platform-side failure, or a code+ // WeCom added since. Fail closed rather than blame the secret. The+ // raw pair is logged here so an operator can see it even if the+ // caller only surfaces the sentinel, and carried on the error so+ // the handler's own log line has it too.+ slog.Warn("wecom credential probe: unrecognized subscribe errcode, treating as unverifiable",+ "errcode", env.ErrCode, "errmsg", env.ErrMsg)+ return fmt.Errorf("%w (subscribe returned errcode %d: %s)", ErrCredentialsUnverifiable, env.ErrCode, env.ErrMsg)+ }+ return nil+ }+}++// websocketTextMessage is gorilla's TextMessage without importing gorilla+// here — the probe writes one frame and this keeps its dependency surface to+// the Dialer interface the package already defines.+const websocketTextMessage = 1diff --git a/server/internal/integrations/wecom/credential_probe_test.go b/server/internal/integrations/wecom/credential_probe_test.gonew file mode 100644index 0000000000..aa527b2beb--- /dev/null+++ b/server/internal/integrations/wecom/credential_probe_test.go@@ -0,0 +1,265 @@+package wecom++// credential_probe_test.go — idx_channel_installation_type_appid is UNIQUE on+// (channel_type, config->>'app_id') with no workspace in it, so a bot id's+// routing slot is global. ReclaimDeadChannelInstallationByAppID then+// hard-deletes whoever holds it, plus every binding beneath. Bot ids are not+// secret. The only thing that can separate "the rightful owner rebinding"+// from "anyone who typed that id" is proof they hold the secret.+//+// These are the socket-level guards: what the probe does with the verdict WeCom+// sends back. The guards on WHEN the probe is allowed to run at all are DB-backed+// and live in installation_probe_db_test.go.++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/util/secretbox"+)++func testUUID(b byte) pgtype.UUID { return pgtype.UUID{Bytes: [16]byte{b}, Valid: true} }++// fakeProbe stands in for the handshake. Counters are mutex-guarded because+// the concurrency guards in installation_probe_db_test.go call it from several+// goroutines under -race.+type fakeProbe struct {+ mu sync.Mutex+ err error+ calls int+ gotBot string+ gotSec string++ // entered is closed on the first call and release, if non-nil, is waited+ // on before returning — the seam that lets a test hold one install inside+ // the probe while another one races it.+ entered chan struct{}+ release chan struct{}+ once sync.Once+}++func (f *fakeProbe) Probe(_ context.Context, botID, secret string) error {+ f.mu.Lock()+ f.calls+++ f.gotBot, f.gotSec = botID, secret+ err := f.err+ entered, release := f.entered, f.release+ f.mu.Unlock()++ if entered != nil {+ f.once.Do(func() { close(entered) })+ }+ if release != nil {+ <-release+ }+ return err+}++func (f *fakeProbe) callCount() int {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.calls+}++// ---- the verdict split ----++// ackConn is a wsConn that answers the subscribe frame with a fixed+// (errcode, errmsg) pair, echoing the caller's internally generated req_id.+type ackConn struct {+ mu sync.Mutex+ errCode int+ errMsg string+ ack []byte+ acked bool+ closed bool+}++func (c *ackConn) WriteMessage(_ int, data []byte) error {+ var env frameEnvelope+ if err := json.Unmarshal(data, &env); err != nil || env.Cmd != cmdSubscribe {+ return nil+ }+ c.mu.Lock()+ defer c.mu.Unlock()+ c.ack, _ = json.Marshal(frameEnvelope{+ Headers: frameHeaders{ReqID: env.Headers.ReqID},+ ErrCode: c.errCode,+ ErrMsg: c.errMsg,+ })+ return nil+}++func (c *ackConn) ReadMessage() (int, []byte, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ if c.ack != nil && !c.acked {+ c.acked = true+ return websocket.TextMessage, c.ack, nil+ }+ return 0, nil, errors.New("no more frames")+}++func (c *ackConn) SetReadDeadline(time.Time) error { return nil }+func (c *ackConn) SetWriteDeadline(time.Time) error { return nil }+func (c *ackConn) Close() error {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.closed = true+ return nil+}++type ackDialer struct{ conn wsConn }++func (d ackDialer) DialContext(context.Context, string, http.Header) (wsConn, *http.Response, error) {+ return d.conn, nil, nil+}++// Only the codes WeCom documents as a refusal of the pair may be reported to+// the admin as a wrong credential. Everything else non-zero fails closed as+// unverifiable: WeCom guarantees nothing about non-zero codes except that they+// are not success, the subscribe path is rate-limited, and telling an admin to+// rotate a long-connection secret that was fine destroys it — it cannot be+// recovered.+func TestProbeClassifiesSubscribeErrCodes(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ errCode int+ errMsg string+ want error // nil means the probe must succeed+ }{+ {name: "success", errCode: 0, errMsg: "ok", want: nil},+ {name: "invalid secret is a rejection", errCode: 40001, errMsg: "invalid secret", want: ErrCredentialsRejected},+ {name: "invalid corpid is a rejection", errCode: 40013, errMsg: "invalid corpid", want: ErrCredentialsRejected},+ {name: "rate limited is not a rejection", errCode: 45009, errMsg: "api freq out of limit", want: ErrCredentialsUnverifiable},+ {name: "concurrency limited is not a rejection", errCode: 45033, errMsg: "api concurrency out of limit", want: ErrCredentialsUnverifiable},+ {name: "system error is not a rejection", errCode: -1, errMsg: "system busy", want: ErrCredentialsUnverifiable},+ {name: "unknown code is not a rejection", errCode: 999999, errMsg: "something new", want: ErrCredentialsUnverifiable},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ conn := &ackConn{errCode: tc.errCode, errMsg: tc.errMsg}+ p := NewHandshakeProbe(ackDialer{conn: conn}, "wss://example.test/ws")++ err := p.Probe(context.Background(), "bot-1", "secret-1")++ if tc.want == nil {+ if err != nil {+ t.Fatalf("errcode %d: Probe = %v, want nil", tc.errCode, err)+ }+ return+ }+ if !errors.Is(err, tc.want) {+ t.Fatalf("errcode %d: Probe = %v, want %v", tc.errCode, err, tc.want)+ }+ // The opposite verdict must not also match, or the split this file+ // exists for is not a split.+ other := ErrCredentialsRejected+ if tc.want == ErrCredentialsRejected {+ other = ErrCredentialsUnverifiable+ }+ if errors.Is(err, other) {+ t.Fatalf("errcode %d: Probe = %v, which also matches %v", tc.errCode, err, other)+ }+ })+ }+}++// Whatever the verdict, the raw code and message travel with the error so the+// handler's log line names the code an operator would need to widen the+// whitelist.+func TestProbeCarriesRawErrCodeOnUnverifiable(t *testing.T) {+ t.Parallel()++ conn := &ackConn{errCode: 45009, errMsg: "api freq out of limit"}+ p := NewHandshakeProbe(ackDialer{conn: conn}, "wss://example.test/ws")++ err := p.Probe(context.Background(), "bot-1", "secret-1")+ if err == nil {+ t.Fatal("Probe = nil, want an unverifiable error")+ }+ if got := err.Error(); !strings.Contains(got, "45009") || !strings.Contains(got, "api freq out of limit") {+ t.Fatalf("error %q does not carry the raw errcode and errmsg", got)+ }+}++// ---- the probe cannot be turned off ----++// Proof of control gates a statement that hard-deletes another workspace's+// installation and every binding under it. A service that can be built without+// a probe reopens exactly that path on the next wiring mistake, so nil is a+// construction error rather than a fail-open mode.+func TestNewInstallationServiceRefusesNilProbe(t *testing.T) {+ t.Parallel()++ box, err := secretbox.New(make([]byte, secretbox.KeySize))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ if _, err := NewInstallationService(nil, nil, box, WithCredentialProbe(nil)); !errors.Is(err, ErrProbeRequired) {+ t.Fatalf("NewInstallationService with an explicit nil probe = %v, want ErrProbeRequired", err)+ }+}++// Omitting the option is not a way to omit the check: the constructor supplies+// the real handshake probe.+func TestNewInstallationServiceDefaultsToTheRealProbe(t *testing.T) {+ t.Parallel()++ box, err := secretbox.New(make([]byte, secretbox.KeySize))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ svc, err := NewInstallationService(nil, nil, box)+ if err != nil {+ t.Fatalf("NewInstallationService: %v", err)+ }+ if svc.probe == nil {+ t.Fatal("probe is nil — an install would reach the reclaim with an unproven credential")+ }+ if _, ok := svc.probe.(*handshakeProbe); !ok {+ t.Fatalf("probe is %T, want the real *handshakeProbe", svc.probe)+ }+}++// A service assembled by struct literal (a test helper, a future caller that+// skips the constructor) must still refuse rather than silently install+// unverified credentials.+func TestUpsertRefusesWithoutAProbe(t *testing.T) {+ t.Parallel()++ svc := &InstallationService{}+ _, err := svc.Upsert(context.Background(), InstallationParams{+ WorkspaceID: testUUID(1),+ AgentID: testUUID(2),+ InstallerUserID: testUUID(3),+ BotID: "somebody-elses-bot",+ Secret: "a-guess",+ })+ if !errors.Is(err, ErrProbeRequired) {+ t.Fatalf("Upsert without a probe = %v, want ErrProbeRequired", err)+ }+}++func TestWithCredentialProbeSetsIt(t *testing.T) {+ t.Parallel()++ p := &fakeProbe{}+ svc := &InstallationService{}+ WithCredentialProbe(p)(svc)+ if svc.probe != p {+ t.Fatal("WithCredentialProbe did not install the probe")+ }+}diff --git a/server/internal/integrations/wecom/installation.go b/server/internal/integrations/wecom/installation.goindex 8de634ec68..ee283cdbfc 100644--- a/server/internal/integrations/wecom/installation.go+++ b/server/internal/integrations/wecom/installation.go@@ -46,17 +46,60 @@ type InstallationService struct {store *Storetx engine.TxStarterbox *secretbox.Box++ // probe proves the caller holds the bot's live credentials before the+ // reclaim below acts on them. Never nil: NewInstallationService defaults it+ // to the real handshake probe and refuses an explicit nil, and Upsert+ // refuses to run without one. Proof of control is a security invariant, so+ // there is no fail-open setting for it — a deployment that cannot reach+ // WeCom at install time gets a 503 and retries, it does not get to install+ // unverified credentials over somebody else's row.+ probe CredentialProbe+}++// InstallationOption configures the service at construction.+type InstallationOption func(*InstallationService)++// WithCredentialProbe overrides the control check. Production omits it and+// gets NewHandshakeProbe(nil, ""); tests pass a fake. Passing nil is an error+// at construction, not a way to turn the check off.+func WithCredentialProbe(p CredentialProbe) InstallationOption {+ return func(s *InstallationService) { s.probe = p }}+// ErrProbeRequired is returned when a service would otherwise be built — or+// run — without a credential probe. Proof of control gates a statement that+// hard-deletes another workspace's installation and every binding under it, so+// a nil probe is a wiring bug, not a deployment mode. Fail closed at+// construction so the mistake surfaces at boot rather than on the first+// install.+var ErrProbeRequired = errors.New("wecom: InstallationService requires a non-nil CredentialProbe")+// NewInstallationService binds the service to a queries handle, a transaction-// starter (so the reclaim-then-upsert runs atomically), and a secretbox keyed-// for at-rest encryption. Returns an error when the box is nil; callers should-// surface it (do not fall back to plaintext).-func NewInstallationService(queries *db.Queries, tx engine.TxStarter, box *secretbox.Box) (*InstallationService, error) {+// starter (so the lock-read-probe-reclaim-upsert sequence runs atomically), and+// a secretbox keyed for at-rest encryption. Returns an error when the box is+// nil; callers should surface it (do not fall back to plaintext).+//+// The credential probe defaults to the real handshake against WeCom. Callers+// that must not open a socket (tests) pass WithCredentialProbe with a fake;+// there is no option that leaves the check off.+func NewInstallationService(queries *db.Queries, tx engine.TxStarter, box *secretbox.Box, opts ...InstallationOption) (*InstallationService, error) {if box == nil {return nil, errors.New("wecom: InstallationService requires a non-nil secretbox.Box")}- return &InstallationService{store: NewStore(queries), tx: tx, box: box}, nil+ svc := &InstallationService{+ store: NewStore(queries),+ tx: tx,+ box: box,+ probe: NewHandshakeProbe(nil, ""),+ }+ for _, o := range opts {+ o(svc)+ }+ if svc.probe == nil {+ return nil, ErrProbeRequired+ }+ return svc, nil}// Upsert creates or refreshes an installation row. The conflict key on@@ -64,10 +107,76 @@ func NewInstallationService(queries *db.Queries, tx engine.TxStarter, box *secre// re-running Upsert against an existing (workspace, agent, wecom) triple// rotates every field on the row and flips status back to 'active'. The// returned Installation reflects the post-write DB state.+//+// The whole sequence — lock the bot's routing slot, read its current owner,+// refuse or probe, reclaim, write — runs inside one transaction. Order is the+// point:+//+// - idx_channel_installation_type_appid is UNIQUE on+// (channel_type, config->>'app_id') with NO workspace in it, so a bot id's+// routing slot is global across the deployment, and+// ReclaimDeadChannelInstallationByAppID hard-deletes whoever holds it along+// with every user binding, chat-session binding and pending token beneath.+// Bot ids are not secret — every member talking to the bot can read one —+// so the reclaim has to be gated on proof that the caller controls the bot.+// That is the probe.+//+// - But the probe is itself a side effect on the live platform: it subscribes,+// and WeCom allows exactly one live subscriber per bot, so subscribing+// displaces whoever is connected. Running it before knowing who owns the+// slot means a request that is about to be REFUSED still knocks the rightful+// owner offline — repeat it and it is a denial of service against a bot the+// caller was never permitted to touch. So the owner read comes first, and a+// request that cannot succeed returns its conflict having touched nothing,+// locally or at WeCom.+//+// - Both steps read state that a concurrent install or reconnect can change+// underneath them, so they are serialized on the slot itself+// (LockChannelInstallationAppIDSlot, a transaction-level advisory lock). A+// pre-read outside the transaction would leave the TOCTOU window open.func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams) (Installation, error) {if err := validateInstallationParams(p); err != nil {return Installation{}, err}+ if s.probe == nil {+ // Belt and braces for a service built by struct literal rather than+ // NewInstallationService. Nothing may reach the reclaim unproven, so+ // this is checked before anything else that could fail first and hide+ // it.+ return Installation{}, ErrProbeRequired+ }+ if s.tx == nil {+ return Installation{}, errors.New("wecom: InstallationService requires a transaction starter")+ }++ tx, err := s.tx.Begin(ctx)+ if err != nil {+ return Installation{}, fmt.Errorf("wecom: begin install tx: %w", err)+ }+ defer func() { _ = tx.Rollback(ctx) }()+ qtx := s.store.WithTx(tx)++ // The serialization boundary. Held until commit/rollback, so every step+ // below sees one consistent answer for who owns this bot.+ if err := qtx.Queries.LockChannelInstallationAppIDSlot(ctx, db.LockChannelInstallationAppIDSlotParams{+ ChannelType: channelTypeWecom,+ AppID: p.BotID,+ }); err != nil {+ return Installation{}, fmt.Errorf("wecom: lock bot routing slot: %w", err)+ }++ // Who holds the slot right now — read inside the lock, before anything+ // external happens.+ if err := botSlotConflictErr(ctx, qtx, p); err != nil {+ return Installation{}, err+ }++ // Nothing live is at stake now: the slot is free, revoked, orphaned, or+ // already this caller's own. Prove control before the reclaim acts on it.+ if err := s.probe.Probe(ctx, p.BotID, p.Secret); err != nil {+ return Installation{}, err+ }+sealed, err := s.box.Seal([]byte(p.Secret))if err != nil {return Installation{}, fmt.Errorf("wecom: encrypt secret: %w", err)@@ -80,7 +189,7 @@ func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams)return Installation{}, err}- // Reclaim-then-upsert, atomically. UpsertChannelInstallation conflicts on+ // Reclaim-then-upsert. UpsertChannelInstallation conflicts on// (workspace_id, agent_id, channel_type), but the (channel_type, app_id)// slot is guarded by idx_channel_installation_type_appid. Disconnect only// flips status to 'revoked' — it does not free the row — so without a@@ -92,18 +201,11 @@ func (s *InstallationService) Upsert(ctx context.Context, p InstallationParams)// by a DIFFERENT (workspace, agent), or an orphan whose workspace/agent was// deleted) and clears its dependent rows in the same statement, while// leaving a LIVE owner (active or archived agent) in place to trip the- // index below — which botOwnerConflictErr turns into an accurate 409.- // Mirrors slack/install.go's persistInstall.- if s.tx == nil {- return Installation{}, errors.New("wecom: InstallationService requires a transaction starter")- }- tx, err := s.tx.Begin(ctx)- if err != nil {- return Installation{}, fmt.Errorf("wecom: begin install tx: %w", err)- }- defer func() { _ = tx.Rollback(ctx) }()- qtx := s.store.WithTx(tx)-+ // index below. botSlotConflictErr has already refused every live owner+ // above, so reaching that unique violation now means the slot changed hands+ // despite the lock; botOwnerConflictErr still turns it into an accurate 409+ // rather than a raw Postgres string. Mirrors slack/install.go's+ // persistInstall.if _, err := qtx.Queries.ReclaimDeadChannelInstallationByAppID(ctx, db.ReclaimDeadChannelInstallationByAppIDParams{ChannelType: channelTypeWecom,AppID: p.BotID,@@ -164,6 +266,60 @@ var (// pgUniqueViolation is Postgres' unique_violation SQLSTATE.const pgUniqueViolation = "23505"+// botSlotConflictErr answers one question: may this install act on the+// (wecom, bot_id) routing slot at all? It returns the sentinel to refuse with,+// or nil to proceed. MUST be called inside the transaction holding+// LockChannelInstallationAppIDSlot — outside it the answer is a guess that a+// concurrent install or reconnect can invalidate before it is used.+//+// It is the gate in front of BOTH side effects Upsert can produce: the probe's+// subscribe (which displaces whoever is connected to this bot at WeCom) and the+// reclaim's hard delete (which takes the row and its bindings). A refusal here+// costs the caller nothing and the current owner nothing.+//+// The classification mirrors ReclaimDeadChannelInstallationByAppID's own+// definition of "dead", so the two cannot drift into disagreeing about which+// rows are takeable:+//+// no row → the slot is free.+// orphan → the workspace or agent row is gone; the reclaim frees+// it and nothing is connected to it.+// revoked → the owner's explicit "I'm done with this bot"; the+// reclaim takes it (or, if it is this caller's own row,+// the upsert reactivates it in place).+// active, ours → a re-install or secret rotation of a bot this+// (workspace, agent) already holds. Not a conflict:+// the upsert refreshes it in place and the reclaim+// spares it.+// active, somebody → refused. This is the case the whole gate exists for.+// else's+func botSlotConflictErr(ctx context.Context, qtx *Store, p InstallationParams) error {+ owner, err := qtx.Queries.GetChannelInstallationSlotOwnerByAppID(ctx, db.GetChannelInstallationSlotOwnerByAppIDParams{+ ChannelType: channelTypeWecom,+ AppID: p.BotID,+ })+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ return fmt.Errorf("wecom: read bot routing slot owner: %w", err)+ }+ switch {+ case !owner.WorkspaceExists || !owner.AgentExists:+ return nil+ case owner.Status == string(InstallationRevoked):+ return nil+ case owner.WorkspaceID == p.WorkspaceID && owner.AgentID == p.AgentID:+ return nil+ case owner.WorkspaceID != p.WorkspaceID:+ return ErrBotOwnedByAnotherWorkspace+ case owner.AgentArchivedAt.Valid:+ return ErrBotOwnedByArchivedAgent+ default:+ return ErrBotOwnedBySameWorkspace+ }+}+// botOwnerConflictErr names who holds the (wecom, bot_id) routing slot so the// handler can tell the admin where to go, mirroring slack's owner-conflict// classification. Read after the upsert failed, so a slot that has since beendiff --git a/server/internal/integrations/wecom/installation_probe_db_test.go b/server/internal/integrations/wecom/installation_probe_db_test.gonew file mode 100644index 0000000000..81d279b037--- /dev/null+++ b/server/internal/integrations/wecom/installation_probe_db_test.go@@ -0,0 +1,312 @@+package wecom++// installation_probe_db_test.go — the guards on WHEN the credential probe is+// allowed to run.+//+// The probe is not a read. It subscribes, and WeCom allows exactly one live+// subscriber per bot, so subscribing displaces whoever is connected. Running it+// before knowing who owns the bot's routing slot means a request that is about+// to be REFUSED still knocks the rightful owner offline first: their supervisor+// reconnects, the caller repeats the request, and an install nobody is+// permitted to make becomes a denial of service against a live bot.+//+// So these assert a count of zero. Every conflict — another agent here, an+// archived agent, another workspace — must be decided from the row, with+// nothing sent to WeCom and nothing written locally.+//+// DB-backed because the decision reads channel_installation JOINed to workspace+// and agent under a transaction-level advisory lock; a fake queries layer would+// assert the mock, not the behaviour. They skip when no migrated database is+// reachable (CI has one). Fixtures are disjoint from installation_reclaim_test.go.++import (+ "context"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgxpool"++ "github.com/multica-ai/multica/server/internal/util/secretbox"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++const (+ wcPrbWS = "5c09e201-0000-4000-8000-000000000001"+ wcPrbOtherWS = "5c09e201-0000-4000-8000-000000000002"+ wcPrbRuntime = "5c09e201-0000-4000-8000-000000000003"+ wcPrbOtherRT = "5c09e201-0000-4000-8000-000000000004"+ wcPrbAgentA = "5c09e201-0000-4000-8000-00000000000a"+ wcPrbAgentB = "5c09e201-0000-4000-8000-00000000000b"+ wcPrbAgentArc = "5c09e201-0000-4000-8000-00000000000c"+ wcPrbAgentOth = "5c09e201-0000-4000-8000-00000000000d"+ wcPrbInstall = "5c09e201-0000-4000-8000-000000000005"++ wcPrbBotActive = "bot_prb_active"+ wcPrbBotArchived = "bot_prb_archived"+ wcPrbBotForeign = "bot_prb_foreign"+ wcPrbBotRevoked = "bot_prb_revoked"+ wcPrbBotFree = "bot_prb_free"+)++func newProbeSvc(t *testing.T, pool *pgxpool.Pool, probe CredentialProbe) *InstallationService {+ t.Helper()+ box, err := secretbox.New(make([]byte, secretbox.KeySize))+ if err != nil {+ t.Fatalf("secretbox.New: %v", err)+ }+ svc, err := NewInstallationService(db.New(pool), pool, box, WithCredentialProbe(probe))+ if err != nil {+ t.Fatalf("NewInstallationService: %v", err)+ }+ return svc+}++func seedProbeOwners(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {+ t.Helper()+ exec := func(q string, args ...any) {+ if _, err := pool.Exec(ctx, q, args...); err != nil {+ t.Fatalf("seed probe owner: %v", err)+ }+ }+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'wecom probe', 'wecom-probe', '') ON CONFLICT (id) DO NOTHING`, wcPrbWS)+ exec(`INSERT INTO workspace (id, name, slug, description) VALUES ($1, 'wecom probe other', 'wecom-probe-other', '') ON CONFLICT (id) DO NOTHING`, wcPrbOtherWS)+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)+VALUES ($1, $2, 'wecom probe runtime', 'local', 'multica_daemon') ON CONFLICT (id) DO NOTHING`, wcPrbRuntime, wcPrbWS)+ exec(`INSERT INTO agent_runtime (id, workspace_id, name, runtime_mode, provider)+VALUES ($1, $2, 'wecom probe other runtime', 'local', 'multica_daemon') ON CONFLICT (id) DO NOTHING`, wcPrbOtherRT, wcPrbOtherWS)+ for _, a := range []string{wcPrbAgentA, wcPrbAgentB} {+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)+VALUES ($1, $2, $3, 'local', $4) ON CONFLICT (id) DO NOTHING`, a, wcPrbWS, "wecom probe "+a, wcPrbRuntime)+ }+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id, archived_at)+VALUES ($1, $2, $3, 'local', $4, now()) ON CONFLICT (id) DO NOTHING`, wcPrbAgentArc, wcPrbWS, "wecom probe archived", wcPrbRuntime)+ exec(`INSERT INTO agent (id, workspace_id, name, runtime_mode, runtime_id)+VALUES ($1, $2, $3, 'local', $4) ON CONFLICT (id) DO NOTHING`, wcPrbAgentOth, wcPrbOtherWS, "wecom probe foreign", wcPrbOtherRT)+}++func cleanProbe(ctx context.Context, pool *pgxpool.Pool) {+ apps := []string{wcPrbBotActive, wcPrbBotArchived, wcPrbBotForeign, wcPrbBotRevoked, wcPrbBotFree}+ _, _ = pool.Exec(ctx, `DELETE FROM channel_installation WHERE config->>'app_id' = ANY($1)`, apps)+ _, _ = pool.Exec(ctx, `DELETE FROM workspace WHERE id = ANY($1)`, []string{wcPrbWS, wcPrbOtherWS})+}++func insertProbeInstall(t *testing.T, ctx context.Context, pool *pgxpool.Pool, ws, agent, app, status string) {+ t.Helper()+ if _, err := pool.Exec(ctx, `+INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, installer_user_id, status)+VALUES ($1, $2, 'wecom', jsonb_build_object('app_id', $3::text, 'bot_id', $3::text, 'app_secret_encrypted', ''), $4, $5)`,+ ws, agent, app, wcPrbInstall, status); err != nil {+ t.Fatalf("insert install app=%s status=%s: %v", app, status, err)+ }+}++func probeParams(ws, agent, app string) InstallationParams {+ return InstallationParams{+ WorkspaceID: mustUUID(ws),+ AgentID: mustUUID(agent),+ InstallerUserID: mustUUID(wcPrbInstall),+ BotID: app,+ Secret: "the-callers-guess",+ }+}++func setupProbe(t *testing.T) (context.Context, *pgxpool.Pool) {+ t.Helper()+ pool := reclaimTestDB(t)+ ctx := context.Background()+ cleanProbe(ctx, pool)+ seedProbeOwners(t, ctx, pool)+ t.Cleanup(func() { cleanProbe(ctx, pool) })+ return ctx, pool+}++// installationRowID reads the primary key currently holding a bot's slot, so a+// test can prove the victim's row is the SAME row afterwards — not a+// replacement written by the reclaim.+func installationRowID(t *testing.T, ctx context.Context, pool *pgxpool.Pool, app string) string {+ t.Helper()+ var id string+ if err := pool.QueryRow(ctx, `SELECT id::text FROM channel_installation WHERE config->>'app_id' = $1`, app).Scan(&id); err != nil {+ t.Fatalf("read installation id for %s: %v", app, err)+ }+ return id+}++// The one this PR is for. A live owner holds the bot; somebody else installs it.+// The request must be refused having sent NOTHING to WeCom: one subscribe is+// enough to displace the rightful owner's connection, and a request that is+// refused anyway has no business producing an external side effect.+func TestUpsert_DoesNotProbeWhenAnActiveOwnerHoldsTheBot(t *testing.T) {+ ctx, pool := setupProbe(t)+ insertProbeInstall(t, ctx, pool, wcPrbWS, wcPrbAgentA, wcPrbBotActive, "active")+ victim := installationRowID(t, ctx, pool, wcPrbBotActive)++ // The correct secret, deliberately: the point is that even a caller who+ // WOULD pass the probe must not reach it, because they still lose on+ // ownership and the subscribe would have kicked the live bot for nothing.+ probe := &fakeProbe{}+ svc := newProbeSvc(t, pool, probe)++ _, err := svc.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentB, wcPrbBotActive))+ if !errors.Is(err, ErrBotOwnedBySameWorkspace) {+ t.Fatalf("Upsert = %v, want ErrBotOwnedBySameWorkspace", err)+ }+ if n := probe.callCount(); n != 0 {+ t.Fatalf("the probe subscribed %d time(s) on a refused install — WeCom allows one live subscriber per bot, so this disconnects the rightful owner and a repeat is a denial of service against a bot the caller may not touch", n)+ }+ if got := installationRowID(t, ctx, pool, wcPrbBotActive); got != victim {+ t.Fatalf("the live owner's installation row changed (%s → %s); a refused install must not touch it", victim, got)+ }+}++// Same rule for an archived owner: archive is reversible, the bot stays owned,+// and the row still names a bot that may be connected.+func TestUpsert_DoesNotProbeWhenAnArchivedOwnerHoldsTheBot(t *testing.T) {+ ctx, pool := setupProbe(t)+ insertProbeInstall(t, ctx, pool, wcPrbWS, wcPrbAgentArc, wcPrbBotArchived, "active")++ probe := &fakeProbe{}+ svc := newProbeSvc(t, pool, probe)++ _, err := svc.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentB, wcPrbBotArchived))+ if !errors.Is(err, ErrBotOwnedByArchivedAgent) {+ t.Fatalf("Upsert = %v, want ErrBotOwnedByArchivedAgent", err)+ }+ if n := probe.callCount(); n != 0 {+ t.Fatalf("the probe subscribed %d time(s) against an archived owner's bot; a refused install must reach WeCom zero times", n)+ }+}++// And for an owner in a workspace the caller cannot see — the case where the+// caller has no way to even know what they just disconnected.+func TestUpsert_DoesNotProbeWhenAnotherWorkspaceHoldsTheBot(t *testing.T) {+ ctx, pool := setupProbe(t)+ insertProbeInstall(t, ctx, pool, wcPrbOtherWS, wcPrbAgentOth, wcPrbBotForeign, "active")+ victim := installationRowID(t, ctx, pool, wcPrbBotForeign)++ probe := &fakeProbe{}+ svc := newProbeSvc(t, pool, probe)++ _, err := svc.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentB, wcPrbBotForeign))+ if !errors.Is(err, ErrBotOwnedByAnotherWorkspace) {+ t.Fatalf("Upsert = %v, want ErrBotOwnedByAnotherWorkspace", err)+ }+ if n := probe.callCount(); n != 0 {+ t.Fatalf("the probe subscribed %d time(s) against a bot owned by another workspace; a refused install must reach WeCom zero times", n)+ }+ if got := installationRowID(t, ctx, pool, wcPrbBotForeign); got != victim {+ t.Fatalf("the other workspace's installation row changed (%s → %s)", victim, got)+ }+}++// The probe still runs where it is meant to: a revoked owner's row is what+// ReclaimDeadChannelInstallationByAppID hard-deletes, bindings and all, so+// taking it over is exactly the act that needs proof of control. A rejected+// pair leaves the row standing.+func TestUpsert_ProbesAndRefusesBeforeReclaimingARevokedOwner(t *testing.T) {+ ctx, pool := setupProbe(t)+ insertProbeInstall(t, ctx, pool, wcPrbWS, wcPrbAgentA, wcPrbBotRevoked, "revoked")+ victim := installationRowID(t, ctx, pool, wcPrbBotRevoked)++ probe := &fakeProbe{err: ErrCredentialsRejected}+ svc := newProbeSvc(t, pool, probe)++ _, err := svc.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentB, wcPrbBotRevoked))+ if !errors.Is(err, ErrCredentialsRejected) {+ t.Fatalf("Upsert = %v, want ErrCredentialsRejected", err)+ }+ if n := probe.callCount(); n != 1 {+ t.Fatalf("probe called %d time(s), want 1 — a revoked row is the case proof of control exists for", n)+ }+ if got := installationRowID(t, ctx, pool, wcPrbBotRevoked); got != victim {+ t.Fatalf("the revoked owner's row was destroyed on a rejected install (%s → %s)", victim, got)+ }+}++// A free slot: probe once, then install.+func TestUpsert_ProbesOnceOnAFreeSlot(t *testing.T) {+ ctx, pool := setupProbe(t)++ probe := &fakeProbe{}+ svc := newProbeSvc(t, pool, probe)++ got, err := svc.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentA, wcPrbBotFree))+ if err != nil {+ t.Fatalf("Upsert on a free slot = %v, want success", err)+ }+ if got.Status != InstallationActive {+ t.Fatalf("status = %q, want active", got.Status)+ }+ if n := probe.callCount(); n != 1 {+ t.Fatalf("probe called %d time(s), want 1", n)+ }+}++// The serialization boundary. Two installs race for the same bot: the winner is+// inside the probe, holding the slot's advisory lock, when the loser arrives.+// The loser must WAIT for the lock rather than read a stale "nobody owns this"+// and subscribe — a second subscribe would displace the winner's connection at+// WeCom, and the loser is going to be refused anyway. A pre-read outside the+// transaction leaves exactly this window open.+func TestUpsert_ConcurrentInstallDoesNotSubscribeBehindTheWinner(t *testing.T) {+ ctx, pool := setupProbe(t)++ winnerProbe := &fakeProbe{entered: make(chan struct{}), release: make(chan struct{})}+ loserProbe := &fakeProbe{}+ winner := newProbeSvc(t, pool, winnerProbe)+ loser := newProbeSvc(t, pool, loserProbe)++ var wg sync.WaitGroup+ winnerErr := make(chan error, 1)+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := winner.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentA, wcPrbBotFree))+ winnerErr <- err+ }()++ select {+ case <-winnerProbe.entered:+ case <-time.After(10 * time.Second):+ t.Fatal("the first install never reached the probe")+ }++ loserErr := make(chan error, 1)+ wg.Add(1)+ go func() {+ defer wg.Done()+ _, err := loser.Upsert(ctx, probeParams(wcPrbWS, wcPrbAgentB, wcPrbBotFree))+ loserErr <- err+ }()++ // Give the second install every chance to overtake. It must be parked on+ // the advisory lock, not talking to WeCom.+ time.Sleep(500 * time.Millisecond)+ if n := loserProbe.callCount(); n != 0 {+ t.Errorf("the racing install subscribed %d time(s) while another install held the bot's slot — that displaces the connection the winner is about to establish", n)+ }++ close(winnerProbe.release)++ if err := <-winnerErr; err != nil {+ t.Fatalf("first install = %v, want success", err)+ }+ select {+ case err := <-loserErr:+ if !errors.Is(err, ErrBotOwnedBySameWorkspace) {+ t.Fatalf("racing install = %v, want ErrBotOwnedBySameWorkspace", err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("the racing install never returned")+ }+ wg.Wait()++ if n := loserProbe.callCount(); n != 0 {+ t.Fatalf("the racing install subscribed %d time(s) in total; a refused install must reach WeCom zero times", n)+ }+ if n := winnerProbe.callCount(); n != 1 {+ t.Fatalf("the winning install probed %d time(s), want 1", n)+ }+}diff --git a/server/internal/integrations/wecom/installation_reclaim_test.go b/server/internal/integrations/wecom/installation_reclaim_test.goindex 42eefcb77e..875128fe92 100644--- a/server/internal/integrations/wecom/installation_reclaim_test.go+++ b/server/internal/integrations/wecom/installation_reclaim_test.go@@ -59,17 +59,23 @@ func reclaimTestDB(t *testing.T) *pgxpool.Pool {return pool}-func newReclaimSvc(t *testing.T, pool *pgxpool.Pool) *InstallationService {+// newReclaimSvc builds the service with a probe that always succeeds. The+// probe is mandatory (see credential_probe.go) and these tests are about the+// reclaim, not the proof of control, so the fake stands in for "the caller does+// hold this bot's secret". The returned fake lets a test assert how many times+// WeCom would have been contacted.+func newReclaimSvc(t *testing.T, pool *pgxpool.Pool) (*InstallationService, *fakeProbe) {t.Helper()box, err := secretbox.New(make([]byte, secretbox.KeySize))if err != nil {t.Fatalf("secretbox.New: %v", err)}- svc, err := NewInstallationService(db.New(pool), pool, box)+ probe := &fakeProbe{}+ svc, err := NewInstallationService(db.New(pool), pool, box, WithCredentialProbe(probe))if err != nil {t.Fatalf("NewInstallationService: %v", err)}- return svc+ return svc, probe}func seedReclaimOwners(t *testing.T, ctx context.Context, pool *pgxpool.Pool) {@@ -130,19 +136,20 @@ func mustUUID(s string) pgtype.UUID {return u}-func setupReclaim(t *testing.T) (context.Context, *pgxpool.Pool, *InstallationService) {+func setupReclaim(t *testing.T) (context.Context, *pgxpool.Pool, *InstallationService, *fakeProbe) {t.Helper()pool := reclaimTestDB(t)ctx := context.Background()cleanReclaim(ctx, pool)seedReclaimOwners(t, ctx, pool)t.Cleanup(func() { cleanReclaim(ctx, pool) })- return ctx, pool, newReclaimSvc(t, pool)+ svc, probe := newReclaimSvc(t, pool)+ return ctx, pool, svc, probe}// A revoked owner on a DIFFERENT agent must be reclaimed so the bot can move.func TestUpsert_TakesOverRevokedOwnerOnDifferentAgent(t *testing.T) {- ctx, pool, svc := setupReclaim(t)+ ctx, pool, svc, probe := setupReclaim(t)insertWecomInstall(t, ctx, pool, wcRclBotRevoked, wcRclAgentA, "revoked")got, err := svc.Upsert(ctx, params(wcRclBotRevoked, wcRclAgentB))@@ -160,36 +167,47 @@ func TestUpsert_TakesOverRevokedOwnerOnDifferentAgent(t *testing.T) {if n != 1 {t.Errorf("expected exactly one row for the bot after takeover, got %d", n)}+ // Taking over a revoked row hard-deletes it and every binding beneath, so+ // it is exactly the act that has to be preceded by proof of control.+ if n := probe.callCount(); n != 1 {+ t.Errorf("probe called %d time(s) before reclaiming a revoked owner, want 1", n)+ }}// A LIVE (active) owner on another agent must still be refused with an accurate// same-workspace conflict — reclaim must not steal a live slot.func TestUpsert_RefusesLiveOwnerOnDifferentAgent(t *testing.T) {- ctx, pool, svc := setupReclaim(t)+ ctx, pool, svc, probe := setupReclaim(t)insertWecomInstall(t, ctx, pool, wcRclBotLive, wcRclAgentA, "active")_, err := svc.Upsert(ctx, params(wcRclBotLive, wcRclAgentB))if !errors.Is(err, ErrBotOwnedBySameWorkspace) {t.Fatalf("live owner should be refused with ErrBotOwnedBySameWorkspace, got: %v", err)}+ if n := probe.callCount(); n != 0 {+ t.Errorf("probe called %d time(s) on a refused install; a live owner is decided from the row, without touching WeCom", n)+ }}// An ARCHIVED agent is still a live owner (not dead) — reclaim leaves it, and// the conflict is reported as the archived-agent case.func TestUpsert_RefusesArchivedOwner(t *testing.T) {- ctx, pool, svc := setupReclaim(t)+ ctx, pool, svc, probe := setupReclaim(t)insertWecomInstall(t, ctx, pool, wcRclBotArchived, wcRclAgentArc, "active")_, err := svc.Upsert(ctx, params(wcRclBotArchived, wcRclAgentB))if !errors.Is(err, ErrBotOwnedByArchivedAgent) {t.Fatalf("archived owner should be refused with ErrBotOwnedByArchivedAgent, got: %v", err)}+ if n := probe.callCount(); n != 0 {+ t.Errorf("probe called %d time(s) on a refused install; an archived owner is decided from the row, without touching WeCom", n)+ }}// Reconnecting the same bot to the SAME agent is an in-place refresh, never a// conflict (it hits the (workspace, agent, channel_type) ON CONFLICT).func TestUpsert_SameAgentReconnectInPlace(t *testing.T) {- ctx, pool, svc := setupReclaim(t)+ ctx, pool, svc, probe := setupReclaim(t)insertWecomInstall(t, ctx, pool, wcRclBotSame, wcRclAgentA, "revoked")got, err := svc.Upsert(ctx, params(wcRclBotSame, wcRclAgentA))@@ -206,4 +224,9 @@ func TestUpsert_SameAgentReconnectInPlace(t *testing.T) {if n != 1 {t.Errorf("expected one row after in-place reconnect, got %d", n)}+ // The caller's own row: still probed, because this is the secret-rotation+ // path and the only connection a subscribe can displace is their own.+ if n := probe.callCount(); n != 1 {+ t.Errorf("probe called %d time(s) on a same-agent reconnect, want 1", n)+ }}diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex 45f2850424..52cbb262e3 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -1071,6 +1071,60 @@ func (q *Queries) GetChannelInstallationOwnerByAppID(ctx context.Context, arg Gereturn i, err}+const getChannelInstallationSlotOwnerByAppID = `-- name: GetChannelInstallationSlotOwnerByAppID :one+SELECT ci.id, ci.workspace_id, ci.agent_id, ci.status,+ a.archived_at AS agent_archived_at,+ (a.id IS NOT NULL)::boolean AS agent_exists,+ (w.id IS NOT NULL)::boolean AS workspace_exists+FROM channel_installation ci+LEFT JOIN agent a ON a.id = ci.agent_id+LEFT JOIN workspace w ON w.id = ci.workspace_id+WHERE ci.channel_type = $1+ AND ci.config ->> 'app_id' = $2::text+`++type GetChannelInstallationSlotOwnerByAppIDParams struct {+ ChannelType string `json:"channel_type"`+ AppID string `json:"app_id"`+}++type GetChannelInstallationSlotOwnerByAppIDRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ Status string `json:"status"`+ AgentArchivedAt pgtype.Timestamptz `json:"agent_archived_at"`+ AgentExists bool `json:"agent_exists"`+ WorkspaceExists bool `json:"workspace_exists"`+}++// Everything the install path needs to classify the current holder of a+// (channel_type, config->>'app_id') slot BEFORE it acts on it, in one read.+// Distinct from GetChannelInstallationOwnerByAppID, which is the after-the-fact+// "name the conflict" read and INNER JOINs the agent away.+//+// Here the joins are LEFT so an ORPHAN row survives the read: with no FKs+// (MUL-3515 §4) an installation outlives a deleted workspace or agent, and the+// caller has to tell "orphan, reclaimable" apart from "live owner, refuse".+// workspace_exists / agent_exists carry that; status and agent_archived_at+// carry the rest of ReclaimDeadChannelInstallationByAppID's own definition of+// dead, so the caller can predict what the reclaim would do without running it.+// pgx.ErrNoRows means the slot is free.+func (q *Queries) GetChannelInstallationSlotOwnerByAppID(ctx context.Context, arg GetChannelInstallationSlotOwnerByAppIDParams) (GetChannelInstallationSlotOwnerByAppIDRow, error) {+ row := q.db.QueryRow(ctx, getChannelInstallationSlotOwnerByAppID, arg.ChannelType, arg.AppID)+ var i GetChannelInstallationSlotOwnerByAppIDRow+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.Status,+ &i.AgentArchivedAt,+ &i.AgentExists,+ &i.WorkspaceExists,+ )+ return i, err+}+const getChannelOutboundCardByTask = `-- name: GetChannelOutboundCardByTask :oneSELECT id, chat_session_id, task_id, channel_type, channel_chat_id, channel_card_message_id, status, last_patched_at, created_at FROM channel_outbound_card_messageWHERE task_id = $1@@ -1326,6 +1380,35 @@ func (q *Queries) ListChannelInstallationsByWorkspace(ctx context.Context, arg Lreturn items, nil}+const lockChannelInstallationAppIDSlot = `-- name: LockChannelInstallationAppIDSlot :exec+SELECT pg_advisory_xact_lock(+ hashtext($1::text),+ hashtext($2::text)+)+`++type LockChannelInstallationAppIDSlotParams struct {+ ChannelType string `json:"channel_type"`+ AppID string `json:"app_id"`+}++// Serializes everything an install does to one (channel_type, config->>'app_id')+// routing slot: read the current owner, decide, reclaim, upsert. Taken as the+// first statement of the install transaction and released by COMMIT/ROLLBACK,+// so the owner read below cannot go stale under a concurrent install or+// reconnect — a plain read-then-write leaves a TOCTOU window in which two+// callers both see "no live owner" and both go on to touch the slot.+//+// Two-key form: the first key namespaces by channel so a feishu app_id and a+// wecom bot id that hash alike do not serialize against each other. hashtext+// collisions inside one channel only cost extra serialization, never+// correctness. pg_advisory_xact_lock (not pg_try_) so a second caller waits+// its turn rather than failing.+func (q *Queries) LockChannelInstallationAppIDSlot(ctx context.Context, arg LockChannelInstallationAppIDSlotParams) error {+ _, err := q.db.Exec(ctx, lockChannelInstallationAppIDSlot, arg.ChannelType, arg.AppID)+ return err+}+const markChannelInboundDedupProcessed = `-- name: MarkChannelInboundDedupProcessed :execrowsUPDATE channel_inbound_message_dedupSET processed_at = now()diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex e52b0470fa..9f71212aad 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -115,6 +115,47 @@ JOIN agent a ON a.id = ci.agent_idWHERE ci.channel_type = sqlc.arg('channel_type')AND ci.config ->> 'app_id' = sqlc.arg('app_id')::text;+-- name: LockChannelInstallationAppIDSlot :exec+-- Serializes everything an install does to one (channel_type, config->>'app_id')+-- routing slot: read the current owner, decide, reclaim, upsert. Taken as the+-- first statement of the install transaction and released by COMMIT/ROLLBACK,+-- so the owner read below cannot go stale under a concurrent install or+-- reconnect — a plain read-then-write leaves a TOCTOU window in which two+-- callers both see "no live owner" and both go on to touch the slot.+--+-- Two-key form: the first key namespaces by channel so a feishu app_id and a+-- wecom bot id that hash alike do not serialize against each other. hashtext+-- collisions inside one channel only cost extra serialization, never+-- correctness. pg_advisory_xact_lock (not pg_try_) so a second caller waits+-- its turn rather than failing.+SELECT pg_advisory_xact_lock(+ hashtext(sqlc.arg('channel_type')::text),+ hashtext(sqlc.arg('app_id')::text)+);++-- name: GetChannelInstallationSlotOwnerByAppID :one+-- Everything the install path needs to classify the current holder of a+-- (channel_type, config->>'app_id') slot BEFORE it acts on it, in one read.+-- Distinct from GetChannelInstallationOwnerByAppID, which is the after-the-fact+-- "name the conflict" read and INNER JOINs the agent away.+--+-- Here the joins are LEFT so an ORPHAN row survives the read: with no FKs+-- (MUL-3515 §4) an installation outlives a deleted workspace or agent, and the+-- caller has to tell "orphan, reclaimable" apart from "live owner, refuse".+-- workspace_exists / agent_exists carry that; status and agent_archived_at+-- carry the rest of ReclaimDeadChannelInstallationByAppID's own definition of+-- dead, so the caller can predict what the reclaim would do without running it.+-- pgx.ErrNoRows means the slot is free.+SELECT ci.id, ci.workspace_id, ci.agent_id, ci.status,+ a.archived_at AS agent_archived_at,+ (a.id IS NOT NULL)::boolean AS agent_exists,+ (w.id IS NOT NULL)::boolean AS workspace_exists+FROM channel_installation ci+LEFT JOIN agent a ON a.id = ci.agent_id+LEFT JOIN workspace w ON w.id = ci.workspace_id+WHERE ci.channel_type = sqlc.arg('channel_type')+ AND ci.config ->> 'app_id' = sqlc.arg('app_id')::text;+-- name: ReclaimDeadChannelInstallationByAppID :one-- Rebind cleanup gate. Frees the (channel_type, config->>'app_id') routing slot-- so a valid new agent can (re)bind a bot whose previous owner is DEAD, and, in