Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7962 fix(wecom): re-read the installation permission at every file delivery stage (#7951)
Xichang(Seacen) Zhao06835b8f5060
diff --git a/server/internal/integrations/wecom/attachment_revocation_db_test.go b/server/internal/integrations/wecom/attachment_revocation_db_test.gonew file mode 100644index 0000000000..8ff3c6f6eb--- /dev/null+++ b/server/internal/integrations/wecom/attachment_revocation_db_test.go@@ -0,0 +1,98 @@+package wecom++// attachment_revocation_db_test.go — the attachment worker re-reads the+// installation's permission from the DATABASE, not from a double, at each frame+// it writes. The tests beside it (attachment_revocation_test.go) prove the+// ordering with a double that can change its answer; this one proves the guard+// is wired to the real row, so a person revoking the bot mid-upload — an UPDATE+// on channel_installation — is what stops the file and silences the notice.++import (+ "context"+ "log/slog"+ "testing"+ "time"++ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// attachmentsFromMemory is the real *db.Queries with the one lookup that would+// need a chat_message and an attachment row answered from memory. The+// permission read — the thing under test — still goes to the database.+type attachmentsFromMemory struct {+ *db.Queries+ rows []db.Attachment+}++func (a attachmentsFromMemory) ListAttachmentsByChatMessage(context.Context, db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {+ return a.rows, nil+}++func TestSendAttachments_ARevokeInTheDatabaseMidUploadStopsTheFileAndTheNotice(t *testing.T) {+ pool := twoReplicaDB(t)++ // Fixtures delete in reverse creation order, so no teardown chain to keep+ // in step (AGENTS.md Testing rules).+ f := dbfx.New(pool, "", "")+ tag := uuidStringPub(mustTestUUID(t))[:8]+ f.WorkspaceID = f.Workspace(t, "revoke "+tag, "revoke-"+tag)+ f.UserID = f.User(t, "Revoke "+tag, "revoke-"+tag+"@example.com")+ agentID := f.Agent(t, "revoke-agent-"+tag, "", dbfx.Cols{"runtime_mode": "local"})+ instID := f.Insert(t, "channel_installation", dbfx.Cols{+ "workspace_id": f.WorkspaceID,+ "agent_id": agentID,+ "channel_type": "wecom",+ "status": "active",+ "installer_user_id": f.UserID,+ })+ inst, err := util.ParseUUID(instID)+ if err != nil {+ t.Fatalf("parse installation id: %v", err)+ }++ // Five chunks at the ladder's middle step of three in flight: the fourth+ // and fifth have to wait for a slot, and that wait is where the revocation+ // lands.+ data := fiveChunks()+ conn := newMediaConn()+ arrived, release := conn.holdChunks()+ sender := conn.newSender()+ reg := newSendersRegistry()+ reg.set(inst, sender)+ q := attachmentsFromMemory{Queries: db.New(pool), rows: []db.Attachment{{+ ID: mustTestUUID(t), Filename: "big.bin", ContentType: "application/octet-stream",+ Url: "u", SizeBytes: int64(len(data)),+ }}}+ o := NewOutbound(q, reg, nil, slog.Default(), WithAttachments(&fakeObjectStore{key: "u", data: data}))++ done := make(chan struct{})+ go func() {+ defer close(done)+ o.sendAttachments(context.Background(), mustTestUUID(t), mustTestUUID(t),+ attachmentTarget{InstallationID: inst, ChatID: "CHAT_1", ChatType: chatTypeSingleInt}, true)+ }()+ awaitChunks(t, arrived, 3)++ // The person removes the bot: one row flips in the database. Nothing else+ // in the process is told.+ f.Exec(t, `UPDATE channel_installation SET status = 'revoked' WHERE id = $1`, instID)+ release()++ select {+ case <-done:+ case <-time.After(15 * time.Second):+ t.Fatal("the attachment worker never returned")+ }+ if n := len(conn.cmdFrames(cmdUploadMediaChunk)); n != 3 {+ t.Errorf("%d chunk frames on the wire, want 3: chunks kept going after the row said revoked", n)+ }+ if n := len(conn.cmdFrames(cmdUploadMediaFinish)); n != 0 {+ t.Errorf("%d finish frames on the wire, want 0", n)+ }+ // Not the file, and not the "a file could not be sent" notice either.+ if n := len(conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Errorf("%d messages sent into a chat whose owner had removed the bot, want 0", n)+ }+}diff --git a/server/internal/integrations/wecom/attachment_revocation_test.go b/server/internal/integrations/wecom/attachment_revocation_test.gonew file mode 100644index 0000000000..0dcebcdd96--- /dev/null+++ b/server/internal/integrations/wecom/attachment_revocation_test.go@@ -0,0 +1,364 @@+package wecom++// attachment_revocation_test.go — the whole attachment worker+// (Outbound.sendAttachments) against an installation that is revoked, or whose+// permission cannot be read, while a delivery is in flight.+//+// One rule: once the permission is gone, NOTHING more is written to WeCom for+// that installation — not a chunk, not the file message, not the sentence that+// says a file failed. These tests run the worker, because the notice is only+// reachable from there; calling sendAttachment alone never exercises it.+//+// Each test holds one of the waits a frame can sit in (the socket's writer,+// the chat's turn, the acknowledgments of chunks already out), changes the+// permission while the frame is in it, and counts what reached the socket.+// The sender-level versions of the same orderings are in media_upload_test.go.++import (+ "context"+ "errors"+ "log/slog"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// revocableQueries is fakeOutboundQueries with an installation whose status the+// test can change after the delivery has started — the UPDATE a person's+// removing the bot performs. It answers the way production does: by id, and+// pgx.ErrNoRows for any other.+type revocableQueries struct {+ *fakeOutboundQueries+ id pgtype.UUID+ revoked atomic.Bool+ unreadable atomic.Bool+ // stalled makes the read hang until its context ends, the way a database+ // that has stopped answering does.+ stalled atomic.Bool+}++func (r *revocableQueries) GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ if r.stalled.Load() {+ <-ctx.Done()+ return db.ChannelInstallation{}, ctx.Err()+ }+ if arg.ID != r.id || arg.ChannelType != channelTypeWecom {+ return db.ChannelInstallation{}, pgx.ErrNoRows+ }+ if r.unreadable.Load() {+ return db.ChannelInstallation{}, errors.New("wecom test: database is unwell")+ }+ status := InstallationActive+ if r.revoked.Load() {+ status = InstallationRevoked+ }+ return db.ChannelInstallation{ID: r.id, Status: string(status)}, nil+}++type revocationRig struct {+ o *Outbound+ q *revocableQueries+ conn *mediaConn+ sender *wsSender+ mx *countingMetrics+ to attachmentTarget+}++// newRevocationRig delivers one file of the given bytes to one chat.+func newRevocationRig(t *testing.T, data []byte) *revocationRig {+ t.Helper()+ inner := oneAttachmentQueries(t, db.Attachment{+ ID: mustTestUUID(t), Filename: "big.bin", ContentType: "application/octet-stream",+ Url: "https://cdn.example/obj/big", SizeBytes: int64(len(data)),+ })+ r := &revocationRig{+ q: &revocableQueries{fakeOutboundQueries: inner, id: mustTestUUID(t)},+ conn: newMediaConn(),+ mx: newCountingMetrics(),+ }+ r.sender = r.conn.newSender()+ reg := newSendersRegistry()+ reg.set(r.q.id, r.sender)+ r.o = NewOutbound(r.q, reg, nil, slog.Default(),+ WithOutboundMetrics(r.mx), WithAttachments(&fakeObjectStore{key: "obj/big", data: data}))+ r.o.spawn = func(f func()) { f() }+ r.to = attachmentTarget{InstallationID: r.q.id, ChatID: "CHAT_1", ChatType: chatTypeSingleInt, SessionID: testSessionID}+ return r+}++// run starts the whole worker, as the spawned goroutine would run it.+func (r *revocationRig) run(t *testing.T) <-chan struct{} {+ return r.runCtx(t, context.Background())+}++func (r *revocationRig) runCtx(t *testing.T, ctx context.Context) <-chan struct{} {+ done := make(chan struct{})+ go func() {+ defer close(done)+ r.o.sendAttachments(ctx, mustParseTaskUUID(t, testMessageID), mustParseTaskUUID(t, testWorkspaceID), r.to, true)+ }()+ return done+}++func (r *revocationRig) mustFinish(t *testing.T, done <-chan struct{}) {+ t.Helper()+ select {+ case <-done:+ case <-time.After(15 * time.Second):+ t.Fatal("the attachment worker never returned")+ }+}++func awaitChunks(t *testing.T, arrived <-chan struct{}, n int) {+ t.Helper()+ for i := 0; i < n; i++ {+ select {+ case <-arrived:+ case <-time.After(10 * time.Second):+ t.Fatalf("chunk %d never reached the socket", i+1)+ }+ }+}++// fiveChunks runs three at a time, so the fourth and fifth wait for a slot.+func fiveChunks() []byte { return make([]byte, mediaChunkBytes*4+1) }++// Review scenario 1, through the worker: the writer is held, the fourth chunk+// queues for it, permission goes while it queues, the writer frees. The+// permission check that preceded the wait had said yes; the chunk must not go.+func TestSendAttachments_AChunkQueuedForTheWriterIsNotWrittenAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newRevocationRig(t, fiveChunks())+ arrived, release := r.conn.holdChunks()+ done := r.run(t)+ awaitChunks(t, arrived, 3)++ // Three chunks are out and unanswered, so the fourth has not been+ // dispatched. Take the writer, then let the acks through: the fourth is+ // dispatched into a held writer.+ if err := r.sender.lockWriter(context.Background()); err != nil {+ t.Fatal(err)+ }+ release()+ settle()+ r.q.revoked.Store(true)+ r.sender.unlockWriter()+ r.mustFinish(t, done)++ if n := len(r.conn.cmdFrames(cmdUploadMediaChunk)); n != 3 {+ t.Errorf("%d chunk frames on the wire, want 3: a chunk queued for the writer went out after the revoke", n)+ }+ if n := len(r.conn.cmdFrames(cmdUploadMediaFinish)); n != 0 {+ t.Errorf("%d finish frames, want 0", n)+ }+ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Errorf("%d send frames, want 0 — neither the file nor a notice about it", n)+ }+ if got := r.mx.get("attachment_dropped"); got != 1 {+ t.Errorf("attachment_dropped = %d, want 1", got)+ }+}++// Review scenario 2, through the worker: the upload and every check before the+// final send are done, the file message queues for the chat's turn behind+// another message, permission goes, the turn comes.+func TestSendAttachments_TheFileMessageQueuedForTheChatIsNotSentAfterTheRevoke(t *testing.T) {+ t.Parallel()+ r := newRevocationRig(t, []byte("DATA"))+ releaseChat, err := r.sender.chats.acquire(context.Background(), r.to.ChatID)+ if err != nil {+ t.Fatal(err)+ }+ done := r.run(t)+ waitFor(t, "the upload to be sealed", func() bool {+ return len(r.conn.cmdFrames(cmdUploadMediaFinish)) == 1+ })+ settle() // the file message is now parked on the chat's turn+ r.q.revoked.Store(true)+ releaseChat()+ r.mustFinish(t, done)++ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Errorf("%d send frames, want 0 — the file message went out after the revoke, or a notice followed it", n)+ }+ if got := r.mx.get("attachment_dropped"); got != 1 {+ t.Errorf("attachment_dropped = %d, want 1", got)+ }+}++// Review scenario 3, through the worker, once for each way the permission can+// be lost: with chunks in flight the permission goes, their acknowledgments+// arrive, and the worker finds out. The guard stops what is left; the notice+// that "a file could not be sent" is a write into the chat and is stopped by+// the same guard.+func TestSendAttachments_LosingThePermissionMidUploadIsSilent(t *testing.T) {+ t.Parallel()+ for _, tc := range []struct {+ name string+ lose func(*revocableQueries)+ }{+ {"revoked", func(q *revocableQueries) { q.revoked.Store(true) }},+ // A row that cannot be read is not a row that says yes.+ {"unreadable", func(q *revocableQueries) { q.unreadable.Store(true) }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ r := newRevocationRig(t, fiveChunks())+ arrived, release := r.conn.holdChunks()+ done := r.run(t)+ awaitChunks(t, arrived, 3)+ tc.lose(r.q)+ release()+ r.mustFinish(t, done)++ if n := len(r.conn.cmdFrames(cmdUploadMediaChunk)); n != 3 {+ t.Errorf("%d chunk frames, want 3", n)+ }+ if n := len(r.conn.cmdFrames(cmdUploadMediaFinish)); n != 0 {+ t.Errorf("%d finish frames, want 0", n)+ }+ if got := markdownSends(t, r.conn); len(got) != 0 {+ t.Errorf("told the user %q after the permission was gone", got)+ }+ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Errorf("%d send frames, want 0", n)+ }+ if got := r.mx.get("attachment_dropped"); got != 1 {+ t.Errorf("attachment_dropped = %d, want 1 — the file is still accounted for", got)+ }+ })+ }+}++// The rig's notice path is live: with the permission intact each of these exits+// does tell the user, and with it gone none does. The control is what stops the+// silent half passing because the notice was never reachable from the setup.+//+// One case per call to tellUser in sendAttachments, because "the failure+// notice" is five places and the permission has to hold at every one.+func TestSendAttachments_EveryNoticeToTheUserNeedsThePermission(t *testing.T) {+ // Not parallel: the slot-wait case takes the package's attachmentSlots.+ for _, exit := range []struct {+ name string+ arrange func(t *testing.T, r *revocationRig) context.Context+ }{+ {"the attachment lookup failed", func(_ *testing.T, r *revocationRig) context.Context {+ r.q.attachmentsErr = errors.New("wecom test: lookup failed")+ return context.Background()+ }},+ {"too many deliveries are pending", func(_ *testing.T, r *revocationRig) context.Context {+ r.o.pendingMu.Lock()+ r.o.pendingAttachments = maxPendingAttachmentDeliveries+ r.o.pendingMu.Unlock()+ return context.Background()+ }},+ {"the budget ran out waiting for a slot", func(t *testing.T, _ *revocationRig) context.Context {+ for i := 0; i < maxConcurrentAttachmentDeliveries; i++ {+ attachmentSlots <- struct{}{}+ }+ t.Cleanup(func() {+ for i := 0; i < maxConcurrentAttachmentDeliveries; i++ {+ <-attachmentSlots+ }+ })+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ return ctx+ }},+ {"the upload was refused", func(_ *testing.T, r *revocationRig) context.Context {+ r.conn.refuse[cmdUploadMediaInit] = 40058+ return context.Background()+ }},+ {"the file message was refused", func(_ *testing.T, r *revocationRig) context.Context {+ r.conn.refuse[cmdSendMsg] = 40058+ return context.Background()+ }},+ } {+ for _, perm := range []struct {+ name string+ lose func(*revocableQueries)+ notice int+ }{+ {"permission intact", func(*revocableQueries) {}, 1},+ {"revoked", func(q *revocableQueries) { q.revoked.Store(true) }, 0},+ {"unreadable", func(q *revocableQueries) { q.unreadable.Store(true) }, 0},+ } {+ t.Run(exit.name+"/"+perm.name, func(t *testing.T) {+ r := newRevocationRig(t, []byte("DATA"))+ ctx := exit.arrange(t, r)+ perm.lose(r.q)+ r.mustFinish(t, r.runCtx(t, ctx))++ // Every markdown push in this rig is a notice: the file itself+ // is a media frame, and no answer text is sent. Counted by+ // frame rather than by wording, so it holds in whatever+ // language the notice is written.+ notices := len(markdownSends(t, r.conn))+ if notices != perm.notice {+ t.Errorf("%d notices to the user, want %d", notices, perm.notice)+ }+ if perm.notice == 0 {+ if n := len(r.conn.cmdFrames(cmdSendMsg)); n != 0 {+ t.Errorf("%d send frames after the permission was gone, want 0", n)+ }+ }+ })+ }+ }+}++// A delivery whose permission cannot be read from the start writes nothing at+// all: not the upload's first frame either.+func TestSendAttachments_AnUnreadablePermissionWritesNothingFromTheStart(t *testing.T) {+ t.Parallel()+ r := newRevocationRig(t, []byte("DATA"))+ r.q.unreadable.Store(true)+ r.mustFinish(t, r.run(t))+ if n := frameCount(r.conn); n != 0 {+ t.Errorf("%d frames reached the socket with an unreadable permission, want 0", n)+ }+}++// Wiring, not behaviour: the guard exists to be installed by the production+// worker, and the tests above install nothing themselves — they call+// sendAttachments, which is what the spawned goroutine calls. This pins the+// last step: that the spawn in deliverAttachmentsByID reaches it.+func TestDeliverAttachments_TheSpawnedWorkerIsGuarded(t *testing.T) {+ t.Parallel()+ r := newRevocationRig(t, []byte("DATA"))+ r.q.revoked.Store(true)+ r.o.deliverAttachmentsByID(testMessageID, testWorkspaceID, r.to, true)+ if n := frameCount(r.conn); n != 0 {+ t.Errorf("%d frames reached the socket from the spawned worker with the installation revoked, want 0", n)+ }+ if got := r.mx.get("attachment_dropped"); got != 1 {+ t.Errorf("attachment_dropped = %d, want 1 — the worker must have run for this test to mean anything", got)+ }+}++// The guard runs while the socket's writer is held, so a permission read that+// never answers must end by itself and refuse the frame. Without the bound the+// read would sit on the writer for as long as the caller's context lasts —+// minutes, here — and the ping loop and every other send on this socket would+// queue behind it.+func TestAttachmentWriteGuard_AReadThatNeverAnswersEndsAndRefuses(t *testing.T) {+ t.Parallel()+ r := newRevocationRig(t, []byte("DATA"))+ r.q.stalled.Store(true)++ got := make(chan error, 1)+ go func() { got <- r.o.attachmentWriteGuard(r.q.id)(context.Background()) }() // no deadline of its own+ select {+ case err := <-got:+ if !errors.Is(err, errMediaPermissionWithdrawn) {+ t.Fatalf("guard = %v, want a refusal", err)+ }+ case <-time.After(permissionReadBudget + 2*time.Second):+ t.Fatalf("the permission read was still waiting after %s; the writer it runs under would be held that long", permissionReadBudget+2*time.Second)+ }+}diff --git a/server/internal/integrations/wecom/media_upload_test.go b/server/internal/integrations/wecom/media_upload_test.goindex 01236efadd..a92c3411e9 100644--- a/server/internal/integrations/wecom/media_upload_test.go+++ b/server/internal/integrations/wecom/media_upload_test.go@@ -14,6 +14,7 @@ import ("errors""strings""sync"+ "sync/atomic""testing""time")@@ -47,6 +48,12 @@ type mediaConn struct {// measurement would report the harness rather than the code.chunkArrived chan struct{}chunkRelease chan struct{}++ // onWrite, when set, is called with the cmd of every frame once it has+ // been recorded, before its verdict goes back. It lets a test act at an+ // exact point in a send — revoke between a refused first attempt and the+ // retry — without a sleep standing in for the ordering.+ onWrite func(cmd string)}func newMediaConn() *mediaConn {@@ -90,7 +97,11 @@ func (c *mediaConn) WriteMessage(_ int, data []byte) error {body = json.RawMessage(`{"media_id":"` + c.mediaID + `"}`)}arrived, release := c.chunkArrived, c.chunkRelease+ onWrite := c.onWritec.mu.Unlock()+ if onWrite != nil {+ onWrite(env.Cmd)+ }if s == nil {return nil // no verdict comes back@@ -452,3 +463,284 @@ func TestOutboundMediaValidate_RejectsUnsendableMedia(t *testing.T) {t.Error("media with no filename was accepted — the name is the only format hint WeCom gets")}}++// ---- the write guard: asked at the write, not before the wait ----+//+// withWriteGuard puts a permission question in the context; writeCtx asks it+// with the writer in hand. These tests are about WHERE it is asked. A guard+// asked before a wait is a verdict about an earlier moment, and each test+// below holds one of the waits open, changes the answer while a frame sits in+// it, and counts what reached the socket.++// errTestWithdrawn is what a guard answers once the person has taken the+// connection back.+var errTestWithdrawn = errors.New("wecom test: the installation was withdrawn")++// guardUnless answers errTestWithdrawn once revoked is set.+func guardUnless(revoked *atomic.Bool) func(context.Context) error {+ return func(context.Context) error {+ if revoked.Load() {+ return errTestWithdrawn+ }+ return nil+ }+}++// settle gives a goroutine that is about to park in a wait the time to get+// there. Not an ordering the assertions rest on — a goroutine that is late+// reaches the same guard after the same change — only what makes the test+// aim at the wait it names.+func settle() { time.Sleep(100 * time.Millisecond) }++func frameCount(c *mediaConn) int {+ c.mu.Lock()+ defer c.mu.Unlock()+ return len(c.frames)+}++// The ordering itself, asserted directly: the guard runs while the writer is+// held, and a frame it refuses leaves nothing on the socket.+func TestWriteGuard_RunsWithTheWriterInHandAndAStoppedFrameIsNotWritten(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ sender := conn.newSender()++ var asked atomic.Int32+ ctx := withWriteGuard(context.Background(), func(context.Context) error {+ asked.Add(1)+ if sender.tryLockWriter() {+ sender.unlockWriter()+ t.Error("the guard ran without the writer: a wait could still sit between the verdict and the socket")+ }+ return errTestWithdrawn+ })++ _, err := sender.request(ctx, cmdSendMsg, map[string]any{"chatid": "C"})+ if !errors.Is(err, errTestWithdrawn) {+ t.Fatalf("request = %v, want the guard's refusal", err)+ }+ if !errors.Is(err, errNotAttempted) {+ t.Errorf("request = %v: a frame stopped before the socket must say so, or the classifiers read it as unknown", err)+ }+ if asked.Load() != 1 {+ t.Errorf("guard asked %d times, want 1", asked.Load())+ }+ if n := frameCount(conn); n != 0 {+ t.Errorf("%d frames on the wire, want 0", n)+ }+}++// Scenario 1 of the review, first stage: the writer is held, the frame queues+// for it, permission goes while it waits, the writer frees. The verdict taken+// before the wait said yes; the one taken after it says no, and only that one+// is about the moment of the write.+func TestUploadMedia_AWithdrawalWhileQueuedForTheWriterWritesNothing(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ sender := conn.newSender()+ var revoked atomic.Bool++ if err := sender.lockWriter(context.Background()); err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() {+ _, err := sender.uploadMedia(withWriteGuard(context.Background(), guardUnless(&revoked)), outboundMedia{+ Kind: mediaTypeFile, Filename: "a.bin", Data: []byte("D"),+ })+ done <- err+ }()+ settle()+ revoked.Store(true)+ sender.unlockWriter()++ select {+ case err := <-done:+ if !errors.Is(err, errTestWithdrawn) {+ t.Fatalf("uploadMedia = %v, want the withdrawal", err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("uploadMedia never returned")+ }+ if n := frameCount(conn); n != 0 {+ t.Errorf("%d frames reached the socket after the withdrawal, want 0", n)+ }+}++// A caller whose context ends while its frame queues for the writer writes+// nothing — and says it wrote nothing. Before, the wait ran on+// context.Background(): the frame went out after its caller had given up and+// the caller was told the outcome was unknown.+func TestRequest_ACallerThatGivesUpWhileQueuedForTheWriterWritesNothing(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ sender := conn.newSender()++ if err := sender.lockWriter(context.Background()); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() {+ _, err := sender.request(ctx, cmdSendMsg, map[string]any{"chatid": "C"})+ done <- err+ }()+ settle()+ cancel()+ select {+ case err := <-done:+ if !errors.Is(err, errNotAttempted) || !errors.Is(err, context.Canceled) {+ t.Fatalf("request = %v, want errNotAttempted wrapping the cancellation", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("request kept waiting for the writer after its caller gave up")+ }+ sender.unlockWriter()+ settle()+ if n := frameCount(conn); n != 0 {+ t.Errorf("%d frames on the wire from a caller that had given up, want 0", n)+ }+}++// What did NOT change: write() has no context and waits for the writer however+// long it takes — the ping, the handshake and the pong depend on that.+func TestWrite_WithoutAContextStillWaitsForTheWriter(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ sender := conn.newSender()++ if err := sender.lockWriter(context.Background()); err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() { done <- sender.write(map[string]any{"cmd": cmdPing, "headers": frameHeaders{ReqID: "P"}}) }()+ select {+ case err := <-done:+ t.Fatalf("write returned %v while the writer was held", err)+ case <-time.After(150 * time.Millisecond):+ }+ sender.unlockWriter()+ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("write = %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("write never got the writer")+ }+ if n := frameCount(conn); n != 1 {+ t.Errorf("%d frames, want the 1 ping", n)+ }+}++// Five chunks run three at a time, so the fourth and fifth have to wait for a+// slot. A withdrawal landing in that wait stops them.+func TestUploadMediaChunks_AWithdrawalDuringTheSlotWaitStopsTheNextChunk(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ arrived, release := conn.holdChunks()+ sender := conn.newSender()+ var revoked atomic.Bool++ data := make([]byte, mediaChunkBytes*4+1)+ done := make(chan error, 1)+ go func() {+ _, err := sender.uploadMedia(withWriteGuard(context.Background(), guardUnless(&revoked)), outboundMedia{+ Kind: mediaTypeFile, Filename: "big.bin", Data: data,+ })+ done <- err+ }()++ for i := 0; i < 3; i++ {+ select {+ case <-arrived:+ case <-time.After(10 * time.Second):+ t.Fatalf("only %d chunks reached the socket, want 3 in flight", i)+ }+ }+ select {+ case <-arrived:+ t.Fatal("a fourth chunk went out with three unanswered")+ case <-time.After(250 * time.Millisecond):+ }++ revoked.Store(true)+ release()++ select {+ case err := <-done:+ if !errors.Is(err, errTestWithdrawn) {+ t.Fatalf("uploadMedia = %v, want the withdrawal", err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("uploadMedia never finished")+ }+ if n := len(conn.cmdFrames(cmdUploadMediaChunk)); n != 3 {+ t.Errorf("chunk frames = %d, want 3 — a chunk went on the wire after the withdrawal", n)+ }+ if n := len(conn.cmdFrames(cmdUploadMediaFinish)); n != 0 {+ t.Errorf("finish frames = %d, want 0 — a stopped upload must not be sealed", n)+ }+}++// The file message queues for the chat's turn behind another message. A+// withdrawal during that wait stops it; the chat lock is the second of the+// waits a verdict taken ahead of sendMedia could not see.+func TestSendMedia_AWithdrawalWhileQueuedForTheChatWritesNothing(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ sender := conn.newSender()+ var revoked atomic.Bool++ releaseChat, err := sender.chats.acquire(context.Background(), "CHAT_1")+ if err != nil {+ t.Fatal(err)+ }+ done := make(chan error, 1)+ go func() {+ done <- sender.sendMedia(withWriteGuard(context.Background(), guardUnless(&revoked)),+ "CHAT_1", chatTypeSingleInt, mediaSend{Kind: mediaTypeFile, MediaID: "M"})+ }()+ settle()+ revoked.Store(true)+ releaseChat()++ select {+ case err := <-done:+ if !errors.Is(err, errTestWithdrawn) {+ t.Fatalf("sendMedia = %v, want the withdrawal", err)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("sendMedia never returned")+ }+ if n := frameCount(conn); n != 0 {+ t.Errorf("%d frames reached the socket after the withdrawal, want 0", n)+ }+}++// The third wait: a throttled push sleeps before its one retry. Permission goes+// during the sleep; the retry is a new frame and is asked again.+func TestSendMedia_AWithdrawalDuringTheThrottleBackoffSendsNoSecondFrame(t *testing.T) {+ t.Parallel()+ conn := newMediaConn()+ sender := conn.newSender()+ sender.retryBackoff = 20 * time.Millisecond+ conn.refuse[cmdSendMsg] = errCodeAPIConcurrencyLimit+ var revoked atomic.Bool+ // The first attempt has already passed its guard when its frame is+ // recorded; the person withdraws while its refusal is on the way back.+ conn.onWrite = func(cmd string) {+ if cmd == cmdSendMsg {+ revoked.Store(true)+ }+ }++ err := sender.sendMedia(withWriteGuard(context.Background(), guardUnless(&revoked)),+ "CHAT_1", chatTypeSingleInt, mediaSend{Kind: mediaTypeFile, MediaID: "M"})+ if !errors.Is(err, errTestWithdrawn) {+ t.Fatalf("sendMedia = %v, want the withdrawal", err)+ }+ if n := len(conn.cmdFrames(cmdSendMsg)); n != 1 {+ t.Errorf("send frames = %d, want 1 — the retry was written after the withdrawal", n)+ }+}diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.goindex db7486bf3e..59aa18c6e1 100644--- a/server/internal/integrations/wecom/outbound.go+++ b/server/internal/integrations/wecom/outbound.go@@ -1056,3 +1056,68 @@ func inboxStringField(v any) string {func uuidStringPub(u pgtype.UUID) string {return util.UUIDToString(u)}++// installationCheck is what one permission read established. Three outcomes,+// because collapsing them is how the first version of this gate lost answers:+// a lookup that failed and a row that says revoked are the same refusal for THIS+// attempt and opposite facts about every later one.+type installationCheck int++const (+ // installationOK — active. Write.+ installationOK installationCheck = iota+ // installationGone — revoked, or the row is not there. Final: nobody may+ // write to it again, and an answer held for it is not owed to anyone.+ installationGone+ // installationUnreadable — the read itself failed. Nothing is established.+ // Refuse this attempt either way; what differs is what the caller owes+ // afterwards. An answer must NOT be reported finished — it is still the only+ // copy and still this subscriber's to deliver. An attachment has nowhere to+ // report to and nothing to lose by waiting: the file stays in object storage+ // and the user can ask again, so the delivery simply stops.+ installationUnreadable+)++// String names the outcomes for the log, so a line saying a delivery stopped+// also says whether anything is coming back — gone is final, unreadable is this+// read and no more. Same reason deliveryState carries one (outbound_media.go).+func (c installationCheck) String() string {+ switch c {+ case installationOK:+ return "ok"+ case installationGone:+ return "gone"+ case installationUnreadable:+ return "unreadable"+ default:+ return "invalid"+ }+}++// mayStillWrite reads the installation's permission for one attempt.+//+// The three-way split follows the convention the rest of this file already+// keeps: pgx.ErrNoRows is a fact, every other error is a failed question. The+// gate that preceded this returned a bool and answered "no" to both, so a+// database blip on one attempt confirmed a one-shot chat:done as handled and+// threw the answer away.+func (o *Outbound) mayStillWrite(ctx context.Context, id pgtype.UUID) installationCheck {+ if !id.Valid {+ return installationGone+ }+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{+ ID: id,+ ChannelType: channelTypeWecom,+ })+ switch {+ case err == nil:+ case errors.Is(err, pgx.ErrNoRows):+ return installationGone+ default:+ return installationUnreadable+ }+ if inst.Status != string(InstallationActive) {+ return installationGone+ }+ return installationOK+}diff --git a/server/internal/integrations/wecom/outbound_media.go b/server/internal/integrations/wecom/outbound_media.goindex b7cd47fc07..0cf8ccc7ed 100644--- a/server/internal/integrations/wecom/outbound_media.go+++ b/server/internal/integrations/wecom/outbound_media.go@@ -225,6 +225,13 @@ func (o *Outbound) deliverAttachmentsByID(rawMessageID, rawWorkspaceID string, t// waiting. Rationing this stage ahead of the lookup would either stay silent// about a file that was dropped or warn about a file that never existed.func (o *Outbound) sendAttachments(ctx context.Context, messageID, workspaceID pgtype.UUID, to attachmentTarget, carriesTheReply bool) {+ // Everything this function writes — every frame of every file, and every+ // sentence to the user about one — is put to the installation's permission+ // at the moment it is written. A revocation is a person withdrawing the+ // connection; the object reads, the upload, the chat's turn and a retry's+ // backoff can each take long enough for it to land, and the failure notice+ // is a write into that chat like any other.+ ctx = withWriteGuard(ctx, o.attachmentWriteGuard(to.InstallationID))// replyFailed records this reply's single outcome, but only when the files// ARE the reply. When words already landed the reply is settled and only// the per-file counters move.@@ -397,14 +404,56 @@ func (o *Outbound) tellUser(ctx context.Context, to attachmentTarget, text strinreturn}if err := sender.sendTextCtx(ctx, to.ChatID, to.ChatType, text); err != nil {+ if errors.Is(err, errMediaPermissionWithdrawn) {+ // Silence is the intended outcome: the connection was withdrawn+ // (or cannot be confirmed), and a notice is a write into that chat.+ o.logger.InfoContext(ctx, "wecom outbound: notice about the file not sent, permission withdrawn",+ "error", err, "installation_id", uuidStringPub(to.InstallationID))+ return+ }o.logger.WarnContext(ctx, "wecom outbound: could not tell the user about the file","error", err, "installation_id", uuidStringPub(to.InstallationID))}}+// errMediaPermissionWithdrawn marks a write the attachment path refused because+// the installation was revoked, or could not be read, after the delivery began.+var errMediaPermissionWithdrawn = errors.New("wecom: media delivery stopped, permission withdrawn")++// permissionReadBudget bounds one permission read. The read runs while the+// socket's writer is held (see attachmentWriteGuard), so a database that has+// stopped answering must cost a refused frame and not a socket that nobody can+// ping.+const permissionReadBudget = 3 * time.Second++// attachmentWriteGuard is the permission check for every frame the attachment+// path writes — upload init, each chunk and its retry, finish, the file+// message and any retry of it, and the notices to the user. It is installed in+// the context (withWriteGuard) and run by the ws layer with the writer in+// hand, so it is asked at the last moment before a byte leaves and not at the+// moment a stage began waiting.+//+// The three outcomes of mayStillWrite collapse to one refusal here, which is+// right for a write: revoked, gone and unreadable are all "do not write now".+// What differs is only what is owed afterwards, and an attachment owes nothing+// — the file stays in object storage, and the user can ask again.+func (o *Outbound) attachmentWriteGuard(id pgtype.UUID) func(context.Context) error {+ return func(ctx context.Context) error {+ ctx, cancel := context.WithTimeout(ctx, permissionReadBudget)+ defer cancel()+ if check := o.mayStillWrite(ctx, id); check != installationOK {+ return fmt.Errorf("wecom: installation may no longer be written to (%s): %w", check, errMediaPermissionWithdrawn)+ }+ return nil+ }+}+// sendAttachment carries one file from object storage into the chat, and// reports what is known about where it ended up. The error is for the log; the// state is what the user is told.+//+// ctx must carry attachmentWriteGuard (sendAttachments puts it there): that is+// what keeps a revoked installation from being written to.func (o *Outbound) sendAttachment(ctx context.Context, sender *wsSender, row db.Attachment, to attachmentTarget) (deliveryState, error) {// The recorded size is checked before a single byte is fetched. An// oversize attachment is refused either way — readObject re-checks what itdiff --git a/server/internal/integrations/wecom/ws_sender.go b/server/internal/integrations/wecom/ws_sender.goindex 4dfb5aa053..1cee08ccdc 100644--- a/server/internal/integrations/wecom/ws_sender.go+++ b/server/internal/integrations/wecom/ws_sender.go@@ -810,7 +810,7 @@ func (s *wsSender) request(ctx context.Context, cmd string, body map[string]any)}defer s.cancelReply(reqID, w)- if err := s.write(map[string]any{+ if err := s.writeCtx(ctx, map[string]any{"cmd": cmd,"headers": frameHeaders{ReqID: reqID},"body": body,@@ -916,6 +916,23 @@ func (s *wsSender) respondStreamFrame(ctx context.Context, reqID, streamID, cont// caller must not hold sendMu on wecomChannel — nothing here reaches back// into the Channel.func (s *wsSender) write(frame map[string]any) error {+ return s.writeCtx(context.Background(), frame)+}++// writeCtx is write for a caller that has a context of its own — request, which+// every upload step and every aibot_send_msg goes through. The wait for the+// writer ends when ctx does, and a context that has ended by the time the+// writer is in hand writes nothing.+//+// Both failures wrap errNotAttempted: they are raised before any byte could+// leave, which is exactly the fact that mark carries. request's own pre-write+// check says the same thing about a context that was already over on entry;+// this is the same fact about one that ended while the frame queued.+//+// The second check exists because lockWriter's select is a coin toss when the+// writer frees up in the same instant ctx ends: a caller can be handed the+// writer after it has given up.+func (s *wsSender) writeCtx(ctx context.Context, frame map[string]any) error {payload, err := json.Marshal(frame)if err != nil {return fmt.Errorf("wecom: marshal frame: %w", err)@@ -926,12 +943,60 @@ func (s *wsSender) write(frame map[string]any) error {// writer is a nil check when tracing is off, and two log lines when it is// on, against a socket write already in the same section.t := traceOutFields(s.log, frame)- ctx := context.Background()if err := s.lockWriter(ctx); err != nil {- return err+ return fmt.Errorf("%w: %w", errNotAttempted, err)}defer s.unlockWriter()- return s.writeLocked(ctx, payload, t)+ if err := ctx.Err(); err != nil {+ return fmt.Errorf("%w: %w", errNotAttempted, err)+ }+ // Asked HERE, with the writer in hand: every wait this frame had in front+ // of it — the writer's, and for a message the chat's turn and any retry+ // backoff above us — is behind it, and nothing sits between this line and+ // the socket but the write.+ if guard := writeGuardFrom(ctx); guard != nil {+ if err := guard(ctx); err != nil {+ return fmt.Errorf("%w: %w", errNotAttempted, err)+ }+ }+ // The socket deadline stays the connection's own. A caller's deadline+ // bounded the waits above, but write() has never let it shorten the write+ // itself, and a request that arrives with little time left should not+ // start failing mid-frame — an outcome that reads as unknown — for want of+ // it. Values survive WithoutCancel; the deadline does not.+ return s.writeLocked(context.WithoutCancel(ctx), payload, t)+}++// writeGuardKey carries a caller's write guard in a context.+type writeGuardKey struct{}++// withWriteGuard returns a context whose frames are each put to guard at the+// moment they are about to be written. A non-nil answer stops that frame; the+// socket sees nothing of it.+//+// It travels in the context because the thing it guards is the write, and the+// write is several calls away from anyone who knows whether it is still+// allowed: a chunk, an upload step or a message each reach writeLocked through+// a writer wait, a chat-lock wait or a retry backoff, and a verdict taken+// before any of those is a verdict about an earlier moment. Asking here asks+// at the only point that has no wait left in front of it.+//+// What the guard checks is the caller's policy. This layer only runs it. A+// ctx that carries none behaves exactly as before.+//+// It covers what goes through request — the upload steps and aibot_send_msg,+// text or media. Stream frames take their own path (writeStreamFrame) and do+// not consult it; nothing puts a guard on those today.+//+// The guard runs while the writer is held, so it must be quick: whatever it+// waits for, the ping loop and every other send on this socket wait for too.+func withWriteGuard(ctx context.Context, guard func(context.Context) error) context.Context {+ return context.WithValue(ctx, writeGuardKey{}, guard)+}++func writeGuardFrom(ctx context.Context) func(context.Context) error {+ g, _ := ctx.Value(writeGuardKey{}).(func(context.Context) error)+ return g}// writeStreamFrame is write() for a stream frame: the same serialized push,