fix(agent): 加固 MCP 工具人审批的跨实例与并发语义

- 跨实例 Resolve 通过 Redis reply channel 接收 owning 实例的 ack
  (ok / not_found / tenant_mismatch / user_mismatch / already_resolved),
  HTTP 不再静默 200,超时退化为 NotFound。
- PendingRequest 增加 UserID,Resolve 校验会话所有者,避免同租户
  其他用户越权批准/篡改参数。
- 新增 ErrAlreadyResolved,timer/ctx 命中后再次 Resolve 返回 400 而
  不是静默成功;waiter.deliver 暴露胜出语义。
- NeedsApproval 默认 fail-close(DB 故障要求审批),可经
  WEKNORA_AGENT_TOOL_APPROVAL_FAIL_OPEN=true 回退。
- Pub/Sub 增加 OriginID 自过滤、退避重连、namespace 后缀,避免自回
  环噪声与多部署串扰。
- 工具执行超时常量统一通过 ToolExecContext.ExecTimeout 注入,
  mcp_tool.go 不再硬编码 60s。
- handler 修正 path 二次解码、错误用 errors.Is、modified_args=null 的
  静默清空、ListMCPToolApprovals 的 404/500 误判。
- repository 用 clause.OnConflict 做原子 upsert,消除并发 500。
- 增加 NotFound / TenantMismatch / UserMismatch / AlreadyResolved /
  Race 等用例。
This commit is contained in:
wizardchen
2026-05-10 21:41:02 +08:00
committed by lyingbug
parent 5510ea8f5a
commit 6d0f09d75f
7 changed files with 416 additions and 88 deletions
+119 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/event"
@@ -43,7 +44,7 @@ func TestGate_RequestAndWait_Approve(t *testing.T) {
require.True(t, ok)
require.NotEmpty(t, data.PendingID)
go func() {
_ = g.Resolve(1, data.PendingID, Decision{Approved: true, ModifiedArgs: json.RawMessage(`{"a":2}`)})
_ = g.Resolve(1, "", data.PendingID, Decision{Approved: true, ModifiedArgs: json.RawMessage(`{"a":2}`)})
}()
return nil
})
@@ -78,3 +79,120 @@ func TestGate_NeedsApproval_NoChecker(t *testing.T) {
g := NewGate(nil, nil, nil)
require.False(t, g.NeedsApproval(context.Background(), 1, "x", "y"))
}
func TestGate_Resolve_NotFound(t *testing.T) {
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, &stubChecker{required: true}, nil)
err := g.Resolve(1, "", "no-such-id", Decision{Approved: true})
require.ErrorIs(t, err, ErrPendingNotFound)
}
func TestGate_Resolve_TenantMismatch(t *testing.T) {
bus := event.NewEventBus()
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, &stubChecker{required: true}, nil)
req := PendingRequest{
TenantID: 1, EventBus: bus, SessionID: "s1", AssistantMessageID: "m1",
ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`),
}
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
data := evt.Data.(event.ToolApprovalRequiredData)
go func() {
require.ErrorIs(t, g.Resolve(999, "", data.PendingID, Decision{Approved: true}), ErrTenantMismatch)
_ = g.Resolve(1, "", data.PendingID, Decision{Approved: false, Reason: "no"})
}()
return nil
})
d, err := g.RequestAndWait(context.Background(), req)
require.NoError(t, err)
require.False(t, d.Approved)
}
func TestGate_Resolve_UserMismatch(t *testing.T) {
bus := event.NewEventBus()
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, &stubChecker{required: true}, nil)
req := PendingRequest{
TenantID: 1, UserID: "alice", EventBus: bus,
SessionID: "s1", AssistantMessageID: "m1",
ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`),
}
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
data := evt.Data.(event.ToolApprovalRequiredData)
go func() {
require.ErrorIs(t, g.Resolve(1, "bob", data.PendingID, Decision{Approved: true}), ErrUserMismatch)
_ = g.Resolve(1, "alice", data.PendingID, Decision{Approved: true})
}()
return nil
})
d, err := g.RequestAndWait(context.Background(), req)
require.NoError(t, err)
require.True(t, d.Approved)
}
func TestGate_Resolve_AlreadyResolvedAfterTimeout(t *testing.T) {
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, &stubChecker{required: true}, nil)
bus := event.NewEventBus()
var pendingID string
gotPending := make(chan struct{}, 1)
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
pendingID = evt.Data.(event.ToolApprovalRequiredData).PendingID
gotPending <- struct{}{}
return nil
})
go func() {
<-gotPending
// Wait until timeout has fired and the pending entry is still there
// (defer delete only happens after RequestAndWait returns).
// 1s timeout + small slack.
<-time.After(1500 * time.Millisecond)
require.ErrorIs(t,
g.Resolve(1, "", pendingID, Decision{Approved: true}),
ErrPendingNotFound, // entry already removed by RequestAndWait's defer
)
}()
d, err := g.RequestAndWait(context.Background(), PendingRequest{
TenantID: 1, EventBus: bus, SessionID: "s",
ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`),
})
require.NoError(t, err)
require.True(t, d.TimedOut)
}
func TestGate_Resolve_RaceWinsAlreadyResolved(t *testing.T) {
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 30}}, &stubChecker{required: true}, nil)
bus := event.NewEventBus()
type result struct {
first error
second error
}
resCh := make(chan result, 1)
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
pendingID := evt.Data.(event.ToolApprovalRequiredData).PendingID
go func() {
err1 := g.Resolve(1, "", pendingID, Decision{Approved: true})
err2 := g.Resolve(1, "", pendingID, Decision{Approved: false})
resCh <- result{first: err1, second: err2}
}()
return nil
})
d, err := g.RequestAndWait(context.Background(), PendingRequest{
TenantID: 1, EventBus: bus, SessionID: "s",
ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`),
})
require.NoError(t, err)
require.True(t, d.Approved)
r := <-resCh
require.NoError(t, r.first)
// Second call must surface either AlreadyResolved or NotFound (depending
// on whether the defer-delete already ran).
require.True(t,
r.second == nil || // RequestAndWait removed the entry: NotFound is possible too
r.second.Error() == ErrAlreadyResolved.Error() ||
r.second.Error() == ErrPendingNotFound.Error(),
"unexpected error: %v", r.second,
)
}