Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7710 fix(channel): refuse an inbound turn from a member who may not run the agent (#8838)
Xichang(Seacen) Zhao4e2afed72013
diff --git a/server/internal/integrations/channel/engine/invoke_gate_db_test.go b/server/internal/integrations/channel/engine/invoke_gate_db_test.gonew file mode 100644index 0000000000..e17fd47117--- /dev/null+++ b/server/internal/integrations/channel/engine/invoke_gate_db_test.go@@ -0,0 +1,171 @@+package engine++import (+ "context"+ "errors"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/service"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// A FAILED permission lookup is not a denial, and the difference is not+// cosmetic: a denial marks the message processed, so the platform's redelivery+// is thrown away and the sender is told they lack a permission they have.+//+// The router tests next door stub MemberMayInvokeAgent at the interface, so+// they can only prove the Router does the right thing with an error it is+// handed. What they cannot see is whether the real policy ever produces one —+// and for two of its three queries it did not, returning a plain false.+//+// So this drives the REAL service.TaskService against a real database, with+// one query failed at the SQL boundary.+func TestRouter_RealServiceLookupFailure_ReleasesInsteadOfDenying(t *testing.T) {+ pool := invokeGateTestDB(t)++ for _, tc := range []struct {+ name string+ // sql is the fragment identifying the query to fail. Each is a query+ // that used to swallow its error inside the policy.+ sql string+ what string+ }{+ {+ name: "the agent's invocation targets cannot be listed",+ sql: "FROM agent_invocation_target",+ what: "a public_to agent's target list",+ },+ {+ name: "the sender's workspace membership cannot be read",+ sql: "FROM member",+ what: "whether the sender is a workspace member",+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ agentID, senderID := seedPublicToAgent(t, pool)++ h := newHarness(t)+ h.ident.id = ResolvedIdentity{UserID: senderID}+ h.inst.inst.AgentID = agentID+ // The real policy, reached through the real service, with one+ // query failing the way an unreachable database fails it.+ h.router = NewRouter(h.issues,+ &service.TaskService{Queries: db.New(failQuery{inner: pool, match: tc.sql})},+ h.reader, RouterConfig{Logger: discardLogger(), Lifecycle: h.lifecycle})+ // A fresh Router holds no resolver sets, and Handle answers that+ // with an error too — which would look exactly like the failure+ // this test is trying to observe.+ h.router.Register(channel.TypeFeishu, ResolverSet{+ Installation: h.inst, Identity: h.ident, Dedup: h.dedup,+ Session: h.binder, Audit: h.audit, Replier: h.replier,+ Typing: h.typing, Media: h.media, OriginType: "lark_chat",+ })++ err := h.router.Handle(context.Background(), p2pMessage(t))++ if err == nil {+ t.Fatalf("Handle returned nil when %s could not be read; the Router cannot tell "++ "a failed lookup from a refusal unless the policy reports one", tc.what)+ }+ if h.dedup.marks() != 0 {+ t.Errorf("marked %d time(s): the message is now consumed, so the platform's redelivery "++ "is discarded and this turn is lost for good", h.dedup.marks())+ }+ if h.dedup.releases() != 1 {+ t.Errorf("releases = %d, want 1", h.dedup.releases())+ }+ if r, _ := h.audit.last(); r == DropReasonInvokeDenied {+ t.Error("audited as invocation_not_allowed: a database that did not answer is not a verdict " ++ "about this member's permissions")+ }+ if waitFor(200*time.Millisecond, func() bool {+ for _, res := range h.replier.calls() {+ if res.Outcome == OutcomeInvokeDenied {+ return true+ }+ }+ return false+ }) {+ t.Error("the sender was told they may not run the agent, which may well be false — " ++ "nothing here established that")+ }+ })+ }+}++// failQuery fails one query and passes the rest through, which is what lets+// GetAgent succeed and the failure land inside the policy itself.+type failQuery struct {+ inner db.DBTX+ match string+}++var errInjected = errors.New("injected: database unreachable")++func (f failQuery) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {+ if strings.Contains(sql, f.match) {+ return pgconn.CommandTag{}, errInjected+ }+ return f.inner.Exec(ctx, sql, args...)+}++func (f failQuery) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ if strings.Contains(sql, f.match) {+ return nil, errInjected+ }+ return f.inner.Query(ctx, sql, args...)+}++func (f failQuery) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ if strings.Contains(sql, f.match) {+ return errRow{}+ }+ return f.inner.QueryRow(ctx, sql, args...)+}++type errRow struct{}++func (errRow) Scan(...any) error { return errInjected }++// seedPublicToAgent builds the one shape where the two swallowed queries are+// reached at all: a public_to agent the sender does not own.+func seedPublicToAgent(t *testing.T, pool *pgxpool.Pool) (agentID, senderID pgtype.UUID) {+ t.Helper()+ tag := strings.ReplaceAll(uuid.NewString(), "-", "")[:10]+ f := dbfx.New(pool, "", "")+ f.WorkspaceID = f.Workspace(t, "invoke-gate "+tag, "invoke-gate-"+tag)+ f.UserID = f.User(t, "Owner "+tag, "owner-"+tag+"@example.com")+ sender := f.User(t, "Sender "+tag, "sender-"+tag+"@example.com")+ agent := f.Agent(t, "gated-agent-"+tag, "", dbfx.Cols{"permission_mode": "public_to"})+ return uuidFromString(t, agent), uuidFromString(t, sender)+}++func invokeGateTestDB(t *testing.T) *pgxpool.Pool {+ t.Helper()+ dsn := os.Getenv("DATABASE_URL")+ if dsn == "" {+ dsn = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"+ }+ ctx := context.Background()+ pool, err := pgxpool.New(ctx, dsn)+ if err != nil {+ t.Skipf("no database: %v", err)+ }+ if err := pool.Ping(ctx); err != nil {+ pool.Close()+ t.Skipf("database not reachable: %v", err)+ }+ t.Cleanup(pool.Close)+ return pool+}diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex 5be5d0ba6b..cd8aeb9e80 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -31,6 +31,10 @@ const (OutcomeIssueUsage Outcome = "issue_usage"OutcomeAgentOffline Outcome = "agent_offline"OutcomeAgentArchived Outcome = "agent_archived"+ // OutcomeInvokeDenied — the sender may not run this agent. The web chat+ // refuses the same person at the same point; this is that verdict on the+ // channel side.+ OutcomeInvokeDenied Outcome = "invoke_denied")// DropReason enumerates the drop-audit categories. Values match the legacy@@ -44,6 +48,7 @@ const (DropReasonDuplicate DropReason = "duplicate"DropReasonRevokedInstallation DropReason = "revoked_installation"DropReasonInvalidEvent DropReason = "invalid_event"+ DropReasonInvokeDenied DropReason = "invocation_not_allowed")// Result is the typed verdict the Router produces for one inbound message,@@ -423,6 +428,15 @@ type TaskEnqueuer interface {FinalizeChatTaskEnqueue(ctx context.Context, task db.AgentTaskQueue)PromoteChannelChatTasksIfMediaReady(ctx context.Context, sessionID pgtype.UUID) errorPromoteDeferredChannelIssueTask(ctx context.Context, taskID pgtype.UUID) error+ // MemberMayInvokeAgent applies the invocation policy by agent id: the+ // Router has the installation's agent id, not the loaded row.+ //+ // An agent that no longer exists admits nobody, and so does a member who is+ // not a target — both are (false, nil). A query that FAILED is an error,+ // never false, because the Router reads false as "tell this person no" and+ // marks the message processed. The scheduled triggers use the fail-closed+ // wrapper instead; they can wait for the next tick, a person cannot.+ MemberMayInvokeAgent(ctx context.Context, agentID, userID pgtype.UUID) (bool, error)}// SessionReader reads the rows the debounced flush + /issue identifier need.diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 7e4199c9c1..d049cb5a50 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -25,7 +25,7 @@ import (// channel.InboundMessage and calls Handle, which routes by ChannelType to that// platform's registered resolver set and runs the same ordered pipeline for// every platform — installation route → two-phase dedup → group @bot filter →-// identity + membership → ensure session → append+mark → /issue → durable+// identity + membership → invoke permission → ensure session → append+mark → /issue → durable// debounced run trigger + detached media binding — then drives the detached// outbound replier + typing indicator.//@@ -371,6 +371,26 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe}}+ // 4b. Invoke permission (MUL-3963): the same verdict the web chat applies+ // before it opens a session. It judges the SENDER, never the installer+ // who owns a group's route, and it runs before anything is stored — so+ // a refused turn reaches no Chat, no /issue, and no later run's context.+ allowed, err := r.tasks.MemberMayInvokeAgent(ctx, inst.AgentID, identity.UserID)+ if err != nil {+ // Release rather than mark: a lookup that did not answer is not a+ // denial, and the redelivery is this message's remaining chance.+ return Result{}, finalizeRelease, fmt.Errorf("check invoke permission: %w", err)+ }+ if !allowed {+ _ = set.Audit.RecordDrop(ctx, inst.ID, msg, DropReasonInvokeDenied)+ return Result{+ Outcome: OutcomeInvokeDenied,+ DropReason: DropReasonInvokeDenied,+ InstallationID: inst.ID,+ Sender: msg.Source.SenderID,+ }, finalizeMark, nil+ }+// 5-6. Resolve the current Chat route, then either append normally or// atomically create the next Chat route with its optional first turn.sessionCreator := identity.UserIDdiff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 73c6e9b030..5de2571f24 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -321,6 +321,8 @@ func (f *fakeIssues) PublishAttachmentsChanged(context.Context, db.Issue, pgtype}type fakeTasks struct {+ denyInvoke bool+ invokeErr errormu sync.Mutexcalled boolcallCount int@@ -352,6 +354,16 @@ func (f *fakeTasks) PromoteDeferredChannelIssueTask(_ context.Context, taskID pgreturn nil}+// MemberMayInvokeAgent answers the invoke gate. Defaults to allowing, which is+// what every test written before the gate existed assumes; a test that drives+// the refusal sets denyInvoke or invokeErr.+func (f *fakeTasks) MemberMayInvokeAgent(context.Context, pgtype.UUID, pgtype.UUID) (bool, error) {+ if f.invokeErr != nil {+ return false, f.invokeErr+ }+ return !f.denyInvoke, nil+}+func (f *fakeTasks) EnqueueChannelChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool, contextRevision int64, bindingID pgtype.UUID, routeRevision int64) (db.AgentTaskQueue, error) {f.mu.Lock()defer f.mu.Unlock()@@ -605,6 +617,62 @@ func TestRouter_GroupNotAddressed_Drops(t *testing.T) {}}+// A refused sender is refused BEFORE anything is stored. That ordering is the+// whole point: the web chat applies this verdict before it opens a session, and+// a channel that applied it later would still have written the member's message+// into somebody else's agent's context.+func TestRouter_SenderWhoMayNotInvoke_IsRefusedBeforeAnythingIsStored(t *testing.T) {+ h := newHarness(t)+ h.tasks.denyInvoke = true++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if r, _ := h.audit.last(); r != DropReasonInvokeDenied {+ t.Fatalf("audit = %q, want invocation_not_allowed", r)+ }+ if h.dedup.marks() != 1 {+ t.Fatalf("a refusal is final for this message, so it marks: got %d", h.dedup.marks())+ }+ if h.media.calls() != 0 {+ t.Fatal("a refused turn must not resolve media — that is work done for a run that will not happen")+ }+ h.binder.mu.Lock()+ ensures := h.binder.ensureCalls+ h.binder.mu.Unlock()+ if ensures != 0 {+ t.Fatalf("ensured %d sessions for a refused sender; the refusal has to land before the Chat exists", ensures)+ }+ if !waitFor(time.Second, func() bool {+ for _, r := range h.replier.calls() {+ if r.Outcome == OutcomeInvokeDenied {+ return true+ }+ }+ return false+ }) {+ t.Fatal("the sender was never told; silence reads as a broken bot")+ }+}++// A lookup that did not answer is not a denial. It releases, so the platform's+// redelivery is still this message's chance — marking here would turn one+// database blip into permanent silence for a member who may run the agent.+func TestRouter_InvokeCheckError_Releases(t *testing.T) {+ h := newHarness(t)+ h.tasks.invokeErr = errors.New("database is down")++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err == nil {+ t.Fatal("a failed permission lookup must surface as an error")+ }+ if h.dedup.marks() != 0 {+ t.Fatalf("marked %d times; an unanswered lookup must not consume the claim", h.dedup.marks())+ }+ if h.dedup.releases() != 1 {+ t.Fatalf("releases = %d, want 1", h.dedup.releases())+ }+}+func TestRouter_UnboundSender_NeedsBinding(t *testing.T) {h := newHarness(t)h.ident.err = ErrSenderUnbounddiff --git a/server/internal/integrations/wecom/inbound_media_bind_db_test.go b/server/internal/integrations/wecom/inbound_media_bind_db_test.goindex 2971e81440..fc84818e2f 100644--- a/server/internal/integrations/wecom/inbound_media_bind_db_test.go+++ b/server/internal/integrations/wecom/inbound_media_bind_db_test.go@@ -183,6 +183,11 @@ func (b *bindTestTasks) PromoteChannelChatTasksIfMediaReady(context.Context, pgtb.promoted++return nil}+func (*bindTestTasks) MemberMayInvokeAgent(context.Context, pgtype.UUID, pgtype.UUID) (bool, error) {+ // This rig is about media binding, not permission; the sender may run it.+ return true, nil+}+func (*bindTestTasks) PromoteDeferredChannelIssueTask(context.Context, pgtype.UUID) error {return nil}diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.goindex 31a52c1234..93bc8557b0 100644--- a/server/internal/integrations/wecom/replier.go+++ b/server/internal/integrations/wecom/replier.go@@ -27,6 +27,7 @@ const (freshPendingText = "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。"chatStartedText = "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。"issueUsageText = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"+ invokeDeniedText = "⚠️ 你没有权限运行该智能体。如需使用,请联系它的所有者。")// OutboundReplier implements engine.OutboundReplier for WeCom.@@ -131,6 +132,11 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallr.logger.WarnContext(ctx, "wecom replier: issue usage reply failed","installation_id", util.UUIDToString(inst.ID), "error", err)}+ case engine.OutcomeInvokeDenied:+ if err := r.sendInvokeDenied(ctx, inst, msg); err != nil {+ r.logger.WarnContext(ctx, "wecom replier: invoke-denied notice failed",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ }case engine.OutcomeIngested:// Only a /issue-created message warrants a confirmation; a plain// chat message stays silent (the agent's own reply lands via@@ -212,6 +218,21 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Resreturn nil}+// sendInvokeDenied tells a member the agent is not theirs to run.+//+// A 1:1 is answered in place. A GROUP trigger is answered in the sender's own+// 1:1 and the room hears nothing: a line there would tell everyone present both+// which member was refused and that the agent is someone's private one. The+// sender is bound by definition at this point — the identity check is what+// produced the user id this verdict was read for — so a 1:1 route to them+// exists.+func (r *OutboundReplier) sendInvokeDenied(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) error {+ if aibotChatTypeFromChannel(msg.Source.ChatType) != chatTypeGroupInt {+ return r.post(ctx, inst, msg, invokeDeniedText)+ }+ return r.postPrivate(ctx, inst, msg.Source.SenderID, invokeDeniedText)+}+// postPrivate delivers text to a single user's 1:1 chat (chat_type=1),// regardless of which room triggered the message. Used for bearer-credential// content (the binding link) that must never land in a group.diff --git a/server/internal/service/agent_invocation.go b/server/internal/service/agent_invocation.goindex ae936bf540..63808cd204 100644--- a/server/internal/service/agent_invocation.go+++ b/server/internal/service/agent_invocation.go@@ -2,45 +2,75 @@ package serviceimport ("context"+ "errors"+ "fmt"++ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")-// CanMemberInvokeAgent applies the existing invocation policy for durable triggers.+// CanMemberInvokeAgent applies the existing invocation policy for durable+// triggers, failing closed: a lookup that did not answer reads as "no".+//+// That is the right default for a trigger that fires on its own schedule —+// autopilot and issue wakeups can wait for the next tick. A caller that is+// answering a person right now wants the error instead, so it can retry rather+// than tell them they have no permission: use memberMayInvokeAgent.func CanMemberInvokeAgent(ctx context.Context, queries *db.Queries, agent db.Agent, memberUserID pgtype.UUID, workspaceID pgtype.UUID) bool {+ allowed, err := memberMayInvokeAgent(ctx, queries, agent, memberUserID, workspaceID)+ return err == nil && allowed+}++// memberMayInvokeAgent is the policy itself, with query failures kept apart+// from denials.+//+// (false, nil) is a real verdict: no user id, not the owner of a private+// agent, or a public_to agent this member is not a target of — including the+// member row simply not being there, which is what pgx.ErrNoRows means here.+//+// (false, err) is "we do not know". Collapsing the two is what turns one+// transient database error into a message the platform will never redeliver+// and a person told they lack a permission they have.+func memberMayInvokeAgent(ctx context.Context, queries *db.Queries, agent db.Agent, memberUserID pgtype.UUID, workspaceID pgtype.UUID) (bool, error) {userID := util.UUIDToString(memberUserID)if userID == "" {- return false+ return false, nil}if util.UUIDToString(agent.OwnerID) == userID {- return true+ return true, nil}if agent.PermissionMode != "public_to" {- return false+ return false, nil}targets, err := queries.ListAgentInvocationTargets(ctx, agent.ID)if err != nil {- return false+ return false, fmt.Errorf("list agent invocation targets: %w", err)}isWorkspaceMember := false- if _, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{+ switch _, err := queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{UserID: memberUserID,WorkspaceID: workspaceID,- }); err == nil {+ }); {+ case err == nil:isWorkspaceMember = true+ case errors.Is(err, pgx.ErrNoRows):+ // Not a member. A fact, not a failure.+ default:+ return false, fmt.Errorf("load workspace member: %w", err)}for _, t := range targets {switch t.TargetType {case "workspace":if isWorkspaceMember {- return true+ return true, nil}case "member":if util.UUIDToString(t.TargetID) == userID {- return true+ return true, nil}}}- return false+ return false, nil}diff --git a/server/internal/service/reason_code_test.go b/server/internal/service/reason_code_test.goindex d4491c23bc..566a8458ef 100644--- a/server/internal/service/reason_code_test.go+++ b/server/internal/service/reason_code_test.go@@ -168,7 +168,7 @@ func TestAgentReadinessVerdict(t *testing.T) {if fresh.Reason != dispatch.ReasonRuntimeOffline {t.Errorf("install in flight: reason = %q, want %q", fresh.Reason, dispatch.ReasonRuntimeOffline)}- stale := runtimeVerdict(installingRow(time.Now().Add(-runtimeInstallClaimWindow - time.Minute)), db.Agent{OwnerID: ownerA})+ stale := runtimeVerdict(installingRow(time.Now().Add(-runtimeInstallClaimWindow-time.Minute)), db.Agent{OwnerID: ownerA})if !stale.Blocked() || stale.Reason != dispatch.ReasonRuntimeProfileMissing {t.Fatalf("stale install claim: got %+v, want blocked/runtime_profile_missing", stale)}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 3b3e0e9c85..784fe785f7 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1844,6 +1844,29 @@ type PreparedChatTaskEnqueue struct {runtimeOverlay runtimeMCPOverlayData}+// MemberMayInvokeAgent reports whether userID may trigger runs for agentID.+//+// CanMemberInvokeAgent keyed by id rather than by row: channel inbound has the+// installation's agent id and no reason to load the agent itself. It asks this+// before storing a sender's message, so a member the web chat would refuse+// cannot reach the agent through a bot either.+//+// An agent that no longer exists admits nobody — that is a verdict, not a+// failure. Every other query failure comes back as an error, so an unreachable+// database is never read as a denial: the caller releases its dedup claim and+// the platform's redelivery is still the message's chance. CanMemberInvokeAgent+// is the fail-closed wrapper the scheduled triggers use instead.+func (s *TaskService) MemberMayInvokeAgent(ctx context.Context, agentID, userID pgtype.UUID) (bool, error) {+ agent, err := s.Queries.GetAgent(ctx, agentID)+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ if err != nil {+ return false, fmt.Errorf("load agent: %w", err)+ }+ return memberMayInvokeAgent(ctx, s.Queries, agent, userID, agent.WorkspaceID)+}+// PrepareChatTaskEnqueue performs reads and optional external integration work// before the caller opens a transaction. BuildTaskOverlay may perform network// I/O and must never run while /new holds route-rotation locks.