chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,200 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// AskRequest raises an ask_user prompt.
|
||||
type AskRequest struct {
|
||||
TenantID uint64
|
||||
UserID string
|
||||
SessionID string
|
||||
AssistantMessageID string
|
||||
RequestID string
|
||||
ToolCallID string
|
||||
EventBus *event.EventBus
|
||||
Question types.AskUserPromptRequest
|
||||
// Snapshot, when set, lets the run suspend after the hot wait.
|
||||
Snapshot []byte
|
||||
SnapshotVersion int
|
||||
}
|
||||
|
||||
// Answer is how an ask_user prompt ended.
|
||||
type Answer struct {
|
||||
owner string
|
||||
answered bool
|
||||
PromptID string
|
||||
Answered bool
|
||||
Response types.AskUserPromptResponse
|
||||
Reason string
|
||||
TimedOut bool
|
||||
Canceled bool
|
||||
// Suspended is set when the run must end and wait for the answer.
|
||||
Suspended *types.PromptSuspension
|
||||
}
|
||||
|
||||
// UserAsker is the surface the ask_user tool uses (mockable in tests).
|
||||
type UserAsker interface {
|
||||
AskUser(ctx context.Context, req AskRequest) (Answer, error)
|
||||
// ResumeAnswer is the answer carried by the prompt a resumed run was
|
||||
// suspended on.
|
||||
ResumeAnswer(ctx context.Context, prompt *types.AgentPrompt, bus *event.EventBus) Answer
|
||||
}
|
||||
|
||||
var _ UserAsker = (*Gate)(nil)
|
||||
|
||||
// AskUser shows the question and waits for the answer, the timeout, or the
|
||||
// suspension of the run.
|
||||
func (g *Gate) AskUser(ctx context.Context, req AskRequest) (Answer, error) {
|
||||
if g == nil {
|
||||
return Answer{}, fmt.Errorf("ask user: nil gate")
|
||||
}
|
||||
if req.EventBus == nil {
|
||||
return Answer{}, fmt.Errorf("ask user: EventBus is nil")
|
||||
}
|
||||
request, err := json.Marshal(req.Question)
|
||||
if err != nil {
|
||||
return Answer{}, fmt.Errorf("encode question: %w", err)
|
||||
}
|
||||
wait := g.timeout
|
||||
var suspend *hitl.SuspendSpec
|
||||
if req.Snapshot != nil {
|
||||
wait = g.hotWait
|
||||
suspend = &hitl.SuspendSpec{Snapshot: req.Snapshot, SnapshotVersion: req.SnapshotVersion}
|
||||
}
|
||||
out, err := g.broker.Await(ctx, hitl.Spec{
|
||||
Suspend: suspend,
|
||||
FallbackTimeout: g.timeout,
|
||||
Prompt: &types.AgentPrompt{
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
RequestID: req.RequestID,
|
||||
Kind: types.AgentPromptKindAskUser,
|
||||
ToolCallID: req.ToolCallID,
|
||||
Request: types.JSON(request),
|
||||
},
|
||||
Timeout: wait,
|
||||
TimeoutReason: "no answer in time",
|
||||
Emit: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
waitSec := promptWaitSeconds(p, wait, g.timeout)
|
||||
return req.EventBus.Emit(ctx, event.Event{
|
||||
ID: p.ID + "-prompt-required",
|
||||
Type: event.EventAgentPromptRequired,
|
||||
SessionID: req.SessionID,
|
||||
Data: event.AgentPromptRequiredData{
|
||||
PendingID: p.ID,
|
||||
Kind: types.AgentPromptKindAskUser,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
Request: request,
|
||||
TimeoutSeconds: waitSec,
|
||||
HotWaitSeconds: waitSec,
|
||||
Suspendable: p.Suspendable,
|
||||
RequestedAtUnix: time.Now().Unix(),
|
||||
ToolCallID: req.ToolCallID,
|
||||
RequestID: req.RequestID,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
"pending_id": p.ID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
})
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return Answer{}, fmt.Errorf("ask user: %w", err)
|
||||
}
|
||||
if out.Suspended {
|
||||
return Answer{
|
||||
PromptID: out.Prompt.ID,
|
||||
Suspended: &types.PromptSuspension{
|
||||
Detached: out.Detached,
|
||||
PromptID: out.Prompt.ID,
|
||||
Kind: types.AgentPromptKindAskUser,
|
||||
ExpiresAt: out.ExpiresAt,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
a := askAnswer(out)
|
||||
g.consumeAnswer(ctx, &a, req.EventBus, req.SessionID, req.AssistantMessageID, req.RequestID)
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// ResumeAnswer implements UserAsker.
|
||||
func (g *Gate) ResumeAnswer(ctx context.Context, prompt *types.AgentPrompt, bus *event.EventBus) Answer {
|
||||
a := askAnswer(hitl.Outcome{Prompt: prompt, Answered: true})
|
||||
g.consumeAnswer(ctx, &a, bus, prompt.SessionID, prompt.AssistantMessageID, prompt.RequestID)
|
||||
return a
|
||||
}
|
||||
|
||||
func (g *Gate) consumeAnswer(
|
||||
ctx context.Context, a *Answer, bus *event.EventBus, sessionID, assistantMessageID, requestID string,
|
||||
) {
|
||||
consumed, consumeErr := g.broker.Consume(ctx, a.PromptID, types.AgentPromptDone, a.owner)
|
||||
if !consumed && a.answered {
|
||||
a.Answered = false
|
||||
a.Response = types.AskUserPromptResponse{}
|
||||
a.Reason = "answer is no longer owned or was already consumed"
|
||||
if consumeErr == nil {
|
||||
a.Suspended = &types.PromptSuspension{
|
||||
PromptID: a.PromptID, Kind: types.AgentPromptKindAskUser, Detached: true,
|
||||
}
|
||||
return
|
||||
}
|
||||
a.Reason = "could not confirm the user answer"
|
||||
}
|
||||
if bus == nil {
|
||||
return
|
||||
}
|
||||
var response json.RawMessage
|
||||
if a.Answered {
|
||||
response, _ = json.Marshal(a.Response)
|
||||
}
|
||||
_ = bus.Emit(context.WithoutCancel(ctx), event.Event{
|
||||
ID: a.PromptID + "-prompt-resolved",
|
||||
Type: event.EventAgentPromptResolved,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentPromptResolvedData{
|
||||
PendingID: a.PromptID,
|
||||
Kind: types.AgentPromptKindAskUser,
|
||||
Answered: a.Answered,
|
||||
Response: response,
|
||||
Reason: a.Reason,
|
||||
TimedOut: a.TimedOut,
|
||||
Canceled: a.Canceled,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": assistantMessageID,
|
||||
},
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
func askAnswer(out hitl.Outcome) Answer {
|
||||
a := Answer{
|
||||
owner: out.Prompt.OwnerInstance, answered: out.Answered, PromptID: out.Prompt.ID,
|
||||
Reason: out.Reason, TimedOut: out.TimedOut, Canceled: out.Canceled,
|
||||
}
|
||||
if !out.Answered {
|
||||
return a
|
||||
}
|
||||
if err := json.Unmarshal(out.Prompt.Response, &a.Response); err != nil {
|
||||
a.Reason = "unreadable answer"
|
||||
return a
|
||||
}
|
||||
a.Answered = !a.Response.Declined
|
||||
if a.Response.Declined {
|
||||
a.Reason = "the user declined to answer"
|
||||
}
|
||||
return a
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/config"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func askRequest(bus *event.EventBus) AskRequest {
|
||||
return AskRequest{
|
||||
TenantID: 1, UserID: "user:u1", SessionID: "s1", AssistantMessageID: "m1", ToolCallID: "tc1",
|
||||
EventBus: bus,
|
||||
Question: types.AskUserPromptRequest{Question: "which env?", Options: []string{"dev", "prod"}},
|
||||
}
|
||||
}
|
||||
|
||||
func answerPrompt(g *Gate, id, response string) (hitl.Resolution, error) {
|
||||
return g.ResolveResponse(context.Background(), hitl.ResolveRequest{
|
||||
TenantID: 1, UserID: "user:u1", SessionID: "s1", Kind: types.AgentPromptKindAskUser,
|
||||
PromptID: id, Response: json.RawMessage(response),
|
||||
})
|
||||
}
|
||||
|
||||
func TestGate_AskUserAnsweredLive(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 5}}, nil, nil)
|
||||
invalid := make(chan error, 1)
|
||||
bus.On(event.EventAgentPromptRequired, func(_ context.Context, evt event.Event) error {
|
||||
data := evt.Data.(event.AgentPromptRequiredData)
|
||||
assert.Equal(t, types.AgentPromptKindAskUser, data.Kind)
|
||||
assert.JSONEq(t, `{"question":"which env?","options":["dev","prod"]}`, string(data.Request))
|
||||
assert.False(t, data.Suspendable)
|
||||
go func() {
|
||||
_, err := answerPrompt(g, data.PendingID, `{"selected":["staging"]}`)
|
||||
invalid <- err
|
||||
_, _ = answerPrompt(g, data.PendingID, `{"selected":["prod"]}`)
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
var resolved event.AgentPromptResolvedData
|
||||
bus.On(event.EventAgentPromptResolved, func(_ context.Context, evt event.Event) error {
|
||||
resolved = evt.Data.(event.AgentPromptResolvedData)
|
||||
return nil
|
||||
})
|
||||
|
||||
a, err := g.AskUser(context.Background(), askRequest(bus))
|
||||
require.NoError(t, err)
|
||||
require.ErrorIs(t, <-invalid, ErrInvalidDecision, "an answer outside the options is rejected")
|
||||
require.True(t, a.Answered)
|
||||
assert.Equal(t, []string{"prod"}, a.Response.Selected)
|
||||
assert.True(t, resolved.Answered)
|
||||
assert.JSONEq(t, `{"selected":["prod"]}`, string(resolved.Response))
|
||||
|
||||
row, err := g.broker.Store().Get(context.Background(), a.PromptID)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, types.AgentPromptDone, row.Status)
|
||||
}
|
||||
|
||||
func TestGate_AskUserDeclined(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 5}}, nil, nil)
|
||||
bus.On(event.EventAgentPromptRequired, func(_ context.Context, evt event.Event) error {
|
||||
id := evt.Data.(event.AgentPromptRequiredData).PendingID
|
||||
go func() { _, _ = answerPrompt(g, id, `{"declined":true}`) }()
|
||||
return nil
|
||||
})
|
||||
a, err := g.AskUser(context.Background(), askRequest(bus))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, a.Answered)
|
||||
assert.Contains(t, a.Reason, "declined")
|
||||
}
|
||||
|
||||
func TestGate_AskUserSuspendsThenResumes(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{
|
||||
ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 1,
|
||||
}}, nil, nil)
|
||||
req := askRequest(event.NewEventBus())
|
||||
req.Snapshot, req.SnapshotVersion = []byte(`{"version":1}`), 1
|
||||
a, err := g.AskUser(context.Background(), req)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, a.Suspended)
|
||||
assert.Equal(t, types.AgentPromptKindAskUser, a.Suspended.Kind)
|
||||
|
||||
_, err = g.ResolveResponse(context.Background(), hitl.ResolveRequest{
|
||||
TenantID: 1, UserID: "user:someone-else", SessionID: "s1", Kind: types.AgentPromptKindAskUser,
|
||||
PromptID: a.PromptID, Response: json.RawMessage(`{"selected":["dev"]}`),
|
||||
})
|
||||
require.ErrorIs(t, err, ErrUserMismatch)
|
||||
|
||||
res, err := answerPrompt(g, a.PromptID, `{"selected":["dev"]}`)
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Resume)
|
||||
|
||||
got := g.ResumeAnswer(context.Background(), res.Prompt, event.NewEventBus())
|
||||
require.True(t, got.Answered)
|
||||
assert.Equal(t, []string{"dev"}, got.Response.Selected)
|
||||
}
|
||||
|
||||
func TestGate_ResolveResponseRefusesOAuth(t *testing.T) {
|
||||
g := NewGate(nil, nil, nil)
|
||||
_, err := g.ResolveResponse(context.Background(), hitl.ResolveRequest{
|
||||
TenantID: 1, UserID: "user:u1", Kind: types.AgentPromptKindMCPOAuth,
|
||||
PromptID: "p1", Response: json.RawMessage(`{"authorized":true}`),
|
||||
})
|
||||
require.ErrorIs(t, err, ErrInvalidDecision)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type consumeFailureStore struct{ hitl.Store }
|
||||
|
||||
func (s consumeFailureStore) Transition(ctx context.Context, id string, tr types.AgentPromptTransition) (bool, error) {
|
||||
if tr.To == types.AgentPromptExecuting || tr.To == types.AgentPromptDone {
|
||||
return false, errors.New("consume unavailable")
|
||||
}
|
||||
return s.Store.Transition(ctx, id, tr)
|
||||
}
|
||||
|
||||
func TestConsumeFailureDoesNotDetachOrAuthorizeRun(t *testing.T) {
|
||||
for _, kind := range []string{types.AgentPromptKindToolApproval, types.AgentPromptKindAskUser} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
store := consumeFailureStore{hitl.NewMemoryStore()}
|
||||
g := NewGate(nil, nil, hitl.NewBroker(store, nil))
|
||||
response := types.JSON(`{"approved":true,"modified_args":{"dangerous":true}}`)
|
||||
if kind == types.AgentPromptKindAskUser {
|
||||
response = types.JSON(`{"text":"staging"}`)
|
||||
}
|
||||
prompt := &types.AgentPrompt{
|
||||
ID: "p", Kind: kind, Status: types.AgentPromptAnswered, OwnerInstance: "owner", Response: response,
|
||||
}
|
||||
require.NoError(t, store.Create(ctx, prompt))
|
||||
bus := event.NewEventBus()
|
||||
var emitted bool
|
||||
bus.On(event.EventToolApprovalResolved, func(_ context.Context, e event.Event) error {
|
||||
emitted = true
|
||||
require.False(t, e.Data.(event.ToolApprovalResolvedData).Approved)
|
||||
return nil
|
||||
})
|
||||
bus.On(event.EventAgentPromptResolved, func(_ context.Context, e event.Event) error {
|
||||
emitted = true
|
||||
require.False(t, e.Data.(event.AgentPromptResolvedData).Answered)
|
||||
return nil
|
||||
})
|
||||
if kind == types.AgentPromptKindToolApproval {
|
||||
decision := g.ResumeDecision(ctx, prompt, bus)
|
||||
require.False(t, decision.Approved)
|
||||
require.Empty(t, decision.ModifiedArgs)
|
||||
require.Nil(t, decision.Suspended,
|
||||
"storage failure must complete normally, not detach and strand the message")
|
||||
require.Contains(t, decision.Reason, "could not confirm")
|
||||
} else {
|
||||
answer := g.ResumeAnswer(ctx, prompt, bus)
|
||||
require.False(t, answer.Answered)
|
||||
require.Empty(t, answer.Response)
|
||||
require.Nil(t, answer.Suspended)
|
||||
require.Contains(t, answer.Reason, "could not confirm")
|
||||
}
|
||||
require.True(t, emitted, "the client must learn that the interaction ended")
|
||||
row, err := store.Get(ctx, "p")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptFailed, row.Status)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOAuthConsumeFailureReportsFailureWithoutRetryingTool(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
store := consumeFailureStore{hitl.NewMemoryStore()}
|
||||
g := NewGate(nil, nil, hitl.NewBroker(store, nil))
|
||||
bus := event.NewEventBus()
|
||||
var promptID string
|
||||
var emitted bool
|
||||
bus.On(event.EventMCPOAuthRequired, func(_ context.Context, e event.Event) error {
|
||||
promptID = e.Data.(event.MCPOAuthRequiredData).PendingID
|
||||
return g.Resolve(ctx, ResolveRequest{
|
||||
TenantID: 1, PendingID: promptID, Kind: types.AgentPromptKindMCPOAuth, Decision: Decision{Approved: true},
|
||||
})
|
||||
})
|
||||
bus.On(event.EventMCPOAuthResolved, func(_ context.Context, e event.Event) error {
|
||||
emitted = true
|
||||
require.False(t, e.Data.(event.MCPOAuthResolvedData).Authorized)
|
||||
return nil
|
||||
})
|
||||
decision, err := g.RequestOAuthAndWait(ctx, OAuthPendingRequest{
|
||||
TenantID: 1, SessionID: "s", ServiceID: "svc", EventBus: bus, WaitTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.False(t, decision.Approved)
|
||||
require.Contains(t, decision.Reason, "could not confirm")
|
||||
require.True(t, emitted)
|
||||
row, err := store.Get(ctx, promptID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptFailed, row.Status)
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
// Package approval implements human-in-the-loop gating for dangerous MCP tool calls (issue #1173).
|
||||
//
|
||||
// Gate owns the per-tool policy (enabled / requires approval) and adapts tool
|
||||
// approvals and in-conversation MCP OAuth to the generic prompt broker in
|
||||
// package hitl, which handles persistence, waiting and cross-replica resolve.
|
||||
package approval
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/agent/policy"
|
||||
"academy/internal/config"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Checker answers per-tool MCP policy questions used during registration and execution.
|
||||
type Checker interface {
|
||||
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
}
|
||||
|
||||
// Decision is the outcome of a pending tool approval.
|
||||
type Decision struct {
|
||||
owner string // execution token of the waiter or resumed run
|
||||
answered bool
|
||||
// PendingID identifies the prompt the decision belongs to; callers that
|
||||
// execute an approved call report back with MarkExecuted(PendingID).
|
||||
PendingID string
|
||||
Approved bool
|
||||
ModifiedArgs json.RawMessage // optional JSON object; when set and Approved, replaces original args
|
||||
Reason string
|
||||
TimedOut bool
|
||||
ContextCanceled bool
|
||||
// AllowInSession, on approval, also allows later calls with the same
|
||||
// grant in the session.
|
||||
AllowInSession bool
|
||||
// Granted marks an approval given earlier in the session: no prompt was
|
||||
// raised, so there is no PendingID.
|
||||
Granted bool
|
||||
// Suspended is set when no decision arrived during the in-memory wait
|
||||
// and the prompt now outlives the run; the call must not execute.
|
||||
Suspended *types.PromptSuspension
|
||||
}
|
||||
|
||||
// PendingRequest carries everything needed to block and notify the UI.
|
||||
type PendingRequest struct {
|
||||
TenantID uint64
|
||||
UserID string // owner of the session that initiated the call (used for Resolve authorization); empty disables user check
|
||||
SessionID string
|
||||
AssistantMessageID string
|
||||
RequestID string
|
||||
EventBus *event.EventBus
|
||||
ServiceID string
|
||||
ServiceName string
|
||||
MCPToolName string // name on MCP server
|
||||
RegisteredToolName string // registry name e.g. mcp_svc_tool
|
||||
Description string
|
||||
Args json.RawMessage
|
||||
ToolCallID string
|
||||
// Grant, when set, names the kind of call for matching remembered
|
||||
// grants; see types.ToolApprovalPromptRequest. GrantRisk is the call's
|
||||
// risk, empty meaning write: only a write may be remembered from the
|
||||
// card, while a standing grant may also cover a destructive call.
|
||||
Grant string
|
||||
GrantScope string
|
||||
GrantRisk policy.Risk
|
||||
// Snapshot, when set, is the run state to resume from: the wait is cut
|
||||
// to the hot-wait window and then suspends instead of timing out.
|
||||
Snapshot []byte
|
||||
SnapshotVersion int
|
||||
}
|
||||
|
||||
// MCPApproval is the surface used by MCPTool (mockable in tests).
|
||||
type MCPApproval interface {
|
||||
// Action is the policy action of calling tool; the caller decides it
|
||||
// under the run's access level.
|
||||
Action(ctx context.Context, tenantID uint64, serviceID string, tool *types.MCPTool) policy.Action
|
||||
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error)
|
||||
// ResumeDecision is the decision carried by the answered prompt a resumed
|
||||
// run was suspended on.
|
||||
ResumeDecision(ctx context.Context, prompt *types.AgentPrompt, bus *event.EventBus) Decision
|
||||
// MarkExecuted records that an approved call has finished running, so an
|
||||
// approval is never mistaken for one still in flight.
|
||||
MarkExecuted(ctx context.Context, pendingID string)
|
||||
}
|
||||
|
||||
// BuiltinApproval confirms built-in tool calls that change user data. It has
|
||||
// no per-tool policy: every call it is asked about needs the user's answer.
|
||||
type BuiltinApproval interface {
|
||||
RequestBuiltinApproval(ctx context.Context, req PendingRequest) (Decision, error)
|
||||
ResumeDecision(ctx context.Context, prompt *types.AgentPrompt, bus *event.EventBus) Decision
|
||||
MarkExecuted(ctx context.Context, pendingID string)
|
||||
}
|
||||
|
||||
var _ BuiltinApproval = (*Gate)(nil)
|
||||
|
||||
// OAuthPendingRequest carries everything needed to prompt the user to authorize
|
||||
// an OAuth-enabled MCP service mid-conversation and block until they do.
|
||||
type OAuthPendingRequest struct {
|
||||
TenantID uint64
|
||||
UserID string // session owner; required for Resolve authorization
|
||||
SessionID string
|
||||
AssistantMessageID string
|
||||
RequestID string
|
||||
EventBus *event.EventBus
|
||||
ServiceID string
|
||||
ServiceName string
|
||||
MCPToolName string
|
||||
ToolCallID string
|
||||
// WaitTimeout overrides the gate's default wait timeout when > 0. The wait
|
||||
// is always bounded (either by this value, the gate default, or ctx
|
||||
// cancellation) so the blocked goroutine never leaks.
|
||||
WaitTimeout time.Duration
|
||||
}
|
||||
|
||||
// ResolveRequest is a user decision on a tool approval or OAuth prompt.
|
||||
// SessionID, when set, must match the prompt. Kind selects how Decision is
|
||||
// encoded and must match the prompt; empty means a tool approval.
|
||||
type ResolveRequest struct {
|
||||
TenantID uint64
|
||||
UserID string
|
||||
SessionID string
|
||||
Kind string
|
||||
PendingID string
|
||||
Decision Decision
|
||||
}
|
||||
|
||||
var _ MCPApproval = (*Gate)(nil)
|
||||
|
||||
// Gate applies per-tool MCP policy and raises approval / OAuth prompts.
|
||||
type Gate struct {
|
||||
checker Checker
|
||||
timeout time.Duration
|
||||
hotWait time.Duration // in-memory wait before a suspendable approval suspends the run
|
||||
broker *hitl.Broker
|
||||
failClose bool // when true, policy read errors require approval instead of skipping it
|
||||
grants GrantStore
|
||||
}
|
||||
|
||||
// Errors returned by Resolve; they alias the prompt broker's errors.
|
||||
var (
|
||||
ErrPendingNotFound = hitl.ErrPromptNotFound
|
||||
ErrTenantMismatch = hitl.ErrTenantMismatch
|
||||
ErrAlreadyResolved = hitl.ErrAlreadyResolved
|
||||
ErrUserMismatch = hitl.ErrUserMismatch
|
||||
ErrInvalidDecision = hitl.ErrInvalidResponse
|
||||
)
|
||||
|
||||
// UnattendedApprovalReason is the refusal of a tool approval raised in a run
|
||||
// nobody can answer (types.RunModeUnattended).
|
||||
const UnattendedApprovalReason = "it needs the user's approval, which nobody can give in this run"
|
||||
|
||||
// DeferredApprovalReason is the refusal of a tool approval raised in a
|
||||
// deferred run that cannot save its state to wait for the answer.
|
||||
const DeferredApprovalReason = "it needs the user's approval, and this run cannot wait for it"
|
||||
|
||||
// NewGate builds a gate. checker may be nil (disables gating). cfg may be nil
|
||||
// (defaults apply). broker may be nil (process-local prompts, single replica).
|
||||
func NewGate(cfg *config.Config, checker Checker, broker *hitl.Broker) *Gate {
|
||||
timeout := 10 * time.Minute
|
||||
hotWait := config.DefaultPromptHotWait
|
||||
if cfg != nil && cfg.Agent != nil {
|
||||
if cfg.Agent.ToolApprovalTimeoutSeconds > 0 {
|
||||
timeout = time.Duration(cfg.Agent.ToolApprovalTimeoutSeconds) * time.Second
|
||||
}
|
||||
hotWait = cfg.Agent.PromptHotWait()
|
||||
}
|
||||
if broker == nil {
|
||||
broker = hitl.NewBroker(nil, nil)
|
||||
}
|
||||
broker.RegisterKind(types.AgentPromptKindToolApproval, validateToolApprovalResponse)
|
||||
broker.RegisterKind(types.AgentPromptKindMCPOAuth, validateMCPOAuthResponse)
|
||||
broker.RegisterKind(types.AgentPromptKindAskUser, types.ValidateAskUserResponse)
|
||||
broker.RegisterKind(types.AgentPromptKindPageAction, types.ValidatePageActionResponse)
|
||||
// Default fail-close: if the checker errors, require approval (safer for a
|
||||
// HITL feature). Set ACADEMY_AGENT_TOOL_APPROVAL_FAIL_OPEN=true to revert.
|
||||
failClose := !strings.EqualFold(strings.TrimSpace(os.Getenv("ACADEMY_AGENT_TOOL_APPROVAL_FAIL_OPEN")), "true")
|
||||
return &Gate{checker: checker, timeout: timeout, hotWait: hotWait, broker: broker, failClose: failClose}
|
||||
}
|
||||
|
||||
// Verdict decides a call of an MCP tool under the run's access level: the
|
||||
// tool's risk comes from the workspace's policy and the service's
|
||||
// annotations, and a tool the workspace marked as requiring approval
|
||||
// always asks.
|
||||
func (g *Gate) Verdict(ctx context.Context, tenantID uint64, serviceID string, tool *types.MCPTool) policy.Verdict {
|
||||
rules := policy.Rules{Level: types.AccessLevelFromContext(ctx)}
|
||||
return policy.Decide(g.Action(ctx, tenantID, serviceID, tool), rules)
|
||||
}
|
||||
|
||||
// requiredByPolicy reports whether the workspace marked the tool as always
|
||||
// requiring approval, for checkers that know nothing about risk.
|
||||
func (g *Gate) requiredByPolicy(ctx context.Context, tenantID uint64, serviceID, toolName string) bool {
|
||||
ok, err := g.checker.IsRequired(ctx, tenantID, serviceID, toolName)
|
||||
if err != nil {
|
||||
return g.failedAction(ctx, err).Always
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// IsEnabled reports whether a per-tool MCP policy allows registration or
|
||||
// execution. An absent gate/checker keeps tools enabled (policy store is
|
||||
// optional). A missing tenant or tool identity is fail-closed: the caller
|
||||
// cannot attribute a tenant-scoped disable flag, so the tool is not allowed.
|
||||
func (g *Gate) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
if g == nil || g.checker == nil {
|
||||
return true, nil
|
||||
}
|
||||
if tenantID == 0 || serviceID == "" || toolName == "" {
|
||||
return false, nil
|
||||
}
|
||||
return g.checker.IsEnabled(ctx, tenantID, serviceID, toolName)
|
||||
}
|
||||
|
||||
// RequestAndWait emits a UI event, then blocks until Resolve, timeout, or ctx cancellation.
|
||||
func (g *Gate) RequestAndWait(ctx context.Context, req PendingRequest) (Decision, error) {
|
||||
if g == nil {
|
||||
return Decision{Approved: true}, nil
|
||||
}
|
||||
return g.awaitToolApproval(ctx, req)
|
||||
}
|
||||
|
||||
// RequestBuiltinApproval asks the user to approve a built-in tool call.
|
||||
// Unlike RequestAndWait it has no MCP policy to consult and never approves
|
||||
// on its own: without a broker or an event bus to reach the user, the call
|
||||
// is refused.
|
||||
func (g *Gate) RequestBuiltinApproval(ctx context.Context, req PendingRequest) (Decision, error) {
|
||||
if g == nil || g.broker == nil {
|
||||
return Decision{}, fmt.Errorf("tool approval is not available")
|
||||
}
|
||||
return g.awaitToolApproval(ctx, req)
|
||||
}
|
||||
|
||||
// offeredGrantScope is the scope the card offers to allow, which needs both
|
||||
// a grant to match later calls and a description for the user.
|
||||
func offeredGrantScope(req PendingRequest) string {
|
||||
if req.Grant == "" || req.grantRisk() != policy.RiskWrite {
|
||||
return ""
|
||||
}
|
||||
return req.GrantScope
|
||||
}
|
||||
|
||||
func grantRiskLabel(req PendingRequest) string {
|
||||
if req.Grant == "" {
|
||||
return ""
|
||||
}
|
||||
return string(req.grantRisk())
|
||||
}
|
||||
|
||||
func grantLabel(req PendingRequest) string {
|
||||
if req.Grant == "" {
|
||||
return ""
|
||||
}
|
||||
return req.GrantScope
|
||||
}
|
||||
|
||||
func (req PendingRequest) grantRisk() policy.Risk {
|
||||
if req.GrantRisk == "" {
|
||||
return policy.RiskWrite
|
||||
}
|
||||
return req.GrantRisk
|
||||
}
|
||||
|
||||
func (g *Gate) awaitToolApproval(ctx context.Context, req PendingRequest) (Decision, error) {
|
||||
granted, lapse := g.granted(ctx, req)
|
||||
if granted {
|
||||
return Decision{Approved: true, Granted: true}, nil
|
||||
}
|
||||
mode := types.RunModeFromContext(ctx)
|
||||
switch {
|
||||
case mode == types.RunModeUnattended:
|
||||
return Decision{Reason: UnattendedApprovalReason}, nil
|
||||
case mode == types.RunModeDeferred && req.Snapshot == nil:
|
||||
return Decision{Reason: DeferredApprovalReason}, nil
|
||||
}
|
||||
if req.EventBus == nil {
|
||||
return Decision{}, fmt.Errorf("tool approval: EventBus is nil")
|
||||
}
|
||||
|
||||
request, err := json.Marshal(types.ToolApprovalPromptRequest{
|
||||
ServiceID: req.ServiceID,
|
||||
ServiceName: req.ServiceName,
|
||||
MCPToolName: req.MCPToolName,
|
||||
RegisteredToolName: req.RegisteredToolName,
|
||||
Description: req.Description,
|
||||
Args: req.Args,
|
||||
Grant: req.Grant,
|
||||
GrantScope: offeredGrantScope(req),
|
||||
GrantLapsed: lapse,
|
||||
GrantRisk: grantRiskLabel(req),
|
||||
GrantLabel: grantLabel(req),
|
||||
})
|
||||
if err != nil {
|
||||
return Decision{}, fmt.Errorf("encode tool approval: %w", err)
|
||||
}
|
||||
var argsObj interface{}
|
||||
if len(req.Args) > 0 {
|
||||
_ = json.Unmarshal(req.Args, &argsObj)
|
||||
}
|
||||
wait, fallback := g.timeout, g.timeout
|
||||
var suspend *hitl.SuspendSpec
|
||||
if req.Snapshot != nil {
|
||||
wait = g.hotWait
|
||||
suspend = &hitl.SuspendSpec{Snapshot: req.Snapshot, SnapshotVersion: req.SnapshotVersion}
|
||||
}
|
||||
if mode == types.RunModeDeferred {
|
||||
// Nobody is watching: suspend at once, and never fall back to waiting.
|
||||
wait, fallback = 0, 0
|
||||
}
|
||||
out, err := g.broker.Await(ctx, hitl.Spec{
|
||||
Suspend: suspend,
|
||||
FallbackTimeout: fallback,
|
||||
Prompt: &types.AgentPrompt{
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
RequestID: req.RequestID,
|
||||
Kind: types.AgentPromptKindToolApproval,
|
||||
ToolCallID: req.ToolCallID,
|
||||
Request: types.JSON(request),
|
||||
},
|
||||
Timeout: wait,
|
||||
TimeoutReason: "approval timeout",
|
||||
Emit: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
timeoutSec := promptWaitSeconds(p, wait, g.timeout)
|
||||
return req.EventBus.Emit(ctx, event.Event{
|
||||
ID: p.ID + "-approval-required",
|
||||
Type: event.EventToolApprovalRequired,
|
||||
SessionID: req.SessionID,
|
||||
Data: event.ToolApprovalRequiredData{
|
||||
PendingID: p.ID,
|
||||
TenantID: req.TenantID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
ServiceID: req.ServiceID,
|
||||
ServiceName: req.ServiceName,
|
||||
MCPToolName: req.MCPToolName,
|
||||
RegisteredToolName: req.RegisteredToolName,
|
||||
Description: req.Description,
|
||||
Args: argsObj,
|
||||
ArgsJSON: string(req.Args),
|
||||
GrantScope: offeredGrantScope(req),
|
||||
GrantLapsed: lapse,
|
||||
TimeoutSeconds: timeoutSec,
|
||||
HotWaitSeconds: timeoutSec,
|
||||
Suspendable: p.Suspendable,
|
||||
RequestedAtUnix: time.Now().Unix(),
|
||||
ToolCallID: req.ToolCallID,
|
||||
RequestID: req.RequestID,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
"pending_id": p.ID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
})
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return Decision{}, fmt.Errorf("tool approval: %w", err)
|
||||
}
|
||||
if out.Suspended {
|
||||
// Still open: the run ends here and the decision resumes it later.
|
||||
return Decision{
|
||||
PendingID: out.Prompt.ID,
|
||||
Suspended: &types.PromptSuspension{
|
||||
Detached: out.Detached,
|
||||
PromptID: out.Prompt.ID,
|
||||
Kind: types.AgentPromptKindToolApproval,
|
||||
ExpiresAt: out.ExpiresAt,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
d := toolApprovalDecision(out)
|
||||
g.consumeDecision(ctx, &d, req.EventBus, out.Prompt)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// promptWaitSeconds is how long the UI should count down for p: the hot wait
|
||||
// while it can suspend, the full timeout once it fell back to a plain wait.
|
||||
func promptWaitSeconds(p *types.AgentPrompt, wait, fallback time.Duration) int {
|
||||
if !p.Suspendable {
|
||||
wait = fallback
|
||||
}
|
||||
return max(int(wait/time.Second), 1)
|
||||
}
|
||||
|
||||
// ResumeDecision turns the answered prompt a resumed run was suspended on
|
||||
// into the decision for its blocked call, as if RequestAndWait had just
|
||||
// returned it.
|
||||
func (g *Gate) ResumeDecision(ctx context.Context, prompt *types.AgentPrompt, bus *event.EventBus) Decision {
|
||||
d := toolApprovalDecision(hitl.Outcome{Prompt: prompt, Answered: true})
|
||||
g.consumeDecision(ctx, &d, bus, prompt)
|
||||
return d
|
||||
}
|
||||
|
||||
func (g *Gate) consumeDecision(ctx context.Context, d *Decision, bus *event.EventBus, prompt *types.AgentPrompt) {
|
||||
sessionID, assistantMessageID, requestID := prompt.SessionID, prompt.AssistantMessageID, prompt.RequestID
|
||||
// An approved call stays "executing" until MarkExecuted.
|
||||
consumeTo := types.AgentPromptDone
|
||||
if d.Approved {
|
||||
consumeTo = types.AgentPromptExecuting
|
||||
}
|
||||
consumed, consumeErr := g.broker.Consume(ctx, d.PendingID, consumeTo, d.owner)
|
||||
if !consumed && d.answered {
|
||||
d.Approved = false
|
||||
d.ModifiedArgs = nil
|
||||
d.Reason = "approval is no longer owned or was already consumed"
|
||||
if consumeErr == nil {
|
||||
d.Suspended = &types.PromptSuspension{
|
||||
PromptID: d.PendingID, Kind: types.AgentPromptKindToolApproval, Detached: true,
|
||||
}
|
||||
return
|
||||
}
|
||||
d.Reason = "could not confirm tool approval; tool was not executed"
|
||||
}
|
||||
if consumed {
|
||||
g.remember(ctx, *d, prompt)
|
||||
}
|
||||
if bus == nil {
|
||||
return
|
||||
}
|
||||
_ = bus.Emit(context.WithoutCancel(ctx), event.Event{
|
||||
ID: d.PendingID + "-approval-resolved",
|
||||
Type: event.EventToolApprovalResolved,
|
||||
SessionID: sessionID,
|
||||
Data: event.ToolApprovalResolvedData{
|
||||
PendingID: d.PendingID,
|
||||
Approved: d.Approved,
|
||||
Reason: d.Reason,
|
||||
TimedOut: d.TimedOut,
|
||||
Canceled: d.ContextCanceled,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": assistantMessageID,
|
||||
},
|
||||
RequestID: requestID,
|
||||
})
|
||||
}
|
||||
|
||||
// RequestOAuthAndWait emits an "MCP OAuth required" UI event, then blocks
|
||||
// until the user authorizes (delivered via Resolve), the wait times out, or
|
||||
// the request ctx is canceled. A returned Decision.Approved==true means the
|
||||
// user completed authorization and the tool call should be retried.
|
||||
//
|
||||
// Unlike RequestAndWait this does NOT consult the approval checker — it is
|
||||
// driven reactively by an authorization-required error from the MCP transport.
|
||||
func (g *Gate) RequestOAuthAndWait(ctx context.Context, req OAuthPendingRequest) (Decision, error) {
|
||||
if g == nil {
|
||||
return Decision{}, fmt.Errorf("oauth gate: nil gate")
|
||||
}
|
||||
if req.EventBus == nil {
|
||||
return Decision{}, fmt.Errorf("oauth gate: EventBus is nil")
|
||||
}
|
||||
|
||||
request, err := json.Marshal(types.MCPOAuthPromptRequest{
|
||||
ServiceID: req.ServiceID,
|
||||
ServiceName: req.ServiceName,
|
||||
MCPToolName: req.MCPToolName,
|
||||
})
|
||||
if err != nil {
|
||||
return Decision{}, fmt.Errorf("encode oauth prompt: %w", err)
|
||||
}
|
||||
waitTimeout := g.timeout
|
||||
if req.WaitTimeout > 0 {
|
||||
waitTimeout = req.WaitTimeout
|
||||
}
|
||||
timeoutSec := max(int(waitTimeout/time.Second), 1)
|
||||
|
||||
out, err := g.broker.Await(ctx, hitl.Spec{
|
||||
Prompt: &types.AgentPrompt{
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
RequestID: req.RequestID,
|
||||
Kind: types.AgentPromptKindMCPOAuth,
|
||||
ToolCallID: req.ToolCallID,
|
||||
Request: types.JSON(request),
|
||||
},
|
||||
Timeout: waitTimeout,
|
||||
TimeoutReason: "authorization timeout",
|
||||
Emit: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
return req.EventBus.Emit(ctx, event.Event{
|
||||
ID: p.ID + "-mcp-oauth-required",
|
||||
Type: event.EventMCPOAuthRequired,
|
||||
SessionID: req.SessionID,
|
||||
Data: event.MCPOAuthRequiredData{
|
||||
PendingID: p.ID,
|
||||
TenantID: req.TenantID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
ServiceID: req.ServiceID,
|
||||
ServiceName: req.ServiceName,
|
||||
MCPToolName: req.MCPToolName,
|
||||
TimeoutSeconds: timeoutSec,
|
||||
RequestedAtUnix: time.Now().Unix(),
|
||||
ToolCallID: req.ToolCallID,
|
||||
RequestID: req.RequestID,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
"pending_id": p.ID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
})
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return Decision{}, fmt.Errorf("oauth gate: %w", err)
|
||||
}
|
||||
|
||||
d := oauthDecision(out)
|
||||
consumed, consumeErr := g.broker.Consume(ctx, d.PendingID, types.AgentPromptDone, d.owner)
|
||||
if !consumed && d.answered {
|
||||
d.Approved = false
|
||||
d.Reason = "authorization is no longer owned or was already consumed"
|
||||
if consumeErr != nil {
|
||||
d.Reason = "could not confirm authorization; tool was not retried"
|
||||
}
|
||||
}
|
||||
_ = req.EventBus.Emit(context.WithoutCancel(ctx), event.Event{
|
||||
ID: d.PendingID + "-mcp-oauth-resolved",
|
||||
Type: event.EventMCPOAuthResolved,
|
||||
SessionID: req.SessionID,
|
||||
Data: event.MCPOAuthResolvedData{
|
||||
PendingID: d.PendingID,
|
||||
ServiceID: req.ServiceID,
|
||||
Authorized: d.Approved,
|
||||
Reason: d.Reason,
|
||||
TimedOut: d.TimedOut,
|
||||
Canceled: d.ContextCanceled,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
})
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// MarkExecuted records that an approved call has finished running.
|
||||
func (g *Gate) MarkExecuted(ctx context.Context, pendingID string) {
|
||||
if g == nil {
|
||||
return
|
||||
}
|
||||
g.broker.MarkExecuted(ctx, pendingID)
|
||||
}
|
||||
|
||||
// Resolve records a user decision on a pending prompt and wakes its waiter.
|
||||
// A suspended prompt answered this way is not resumed; use ResolveForResume.
|
||||
func (g *Gate) Resolve(ctx context.Context, req ResolveRequest) error {
|
||||
_, err := g.ResolveForResume(ctx, req)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResolveForResume records a user decision. When the prompt was suspended,
|
||||
// the returned resolution asks the caller to resume its run.
|
||||
func (g *Gate) ResolveForResume(ctx context.Context, req ResolveRequest) (hitl.Resolution, error) {
|
||||
if g == nil {
|
||||
return hitl.Resolution{}, fmt.Errorf("gate is nil")
|
||||
}
|
||||
kind := req.Kind
|
||||
if kind == "" {
|
||||
kind = types.AgentPromptKindToolApproval
|
||||
}
|
||||
var response any
|
||||
switch kind {
|
||||
case types.AgentPromptKindToolApproval:
|
||||
r := types.ToolApprovalPromptResponse{Approved: req.Decision.Approved, Reason: req.Decision.Reason}
|
||||
if r.Approved {
|
||||
r.ModifiedArgs = req.Decision.ModifiedArgs
|
||||
r.AllowInSession = req.Decision.AllowInSession
|
||||
}
|
||||
response = r
|
||||
case types.AgentPromptKindMCPOAuth:
|
||||
response = types.MCPOAuthPromptResponse{Authorized: req.Decision.Approved, Reason: req.Decision.Reason}
|
||||
default:
|
||||
return hitl.Resolution{}, fmt.Errorf("%w: unsupported prompt kind %q", ErrInvalidDecision, kind)
|
||||
}
|
||||
payload, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
return hitl.Resolution{}, err
|
||||
}
|
||||
return g.broker.Resolve(ctx, hitl.ResolveRequest{
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
SessionID: req.SessionID,
|
||||
Kind: kind,
|
||||
PromptID: req.PendingID,
|
||||
Response: payload,
|
||||
})
|
||||
}
|
||||
|
||||
// AnswerableKinds are the prompt kinds a user may answer with a raw
|
||||
// response. MCP OAuth is absent: only the OAuth callback may report an
|
||||
// authorization, never the user's own claim.
|
||||
var AnswerableKinds = map[string]bool{
|
||||
types.AgentPromptKindAskUser: true,
|
||||
types.AgentPromptKindToolApproval: true,
|
||||
types.AgentPromptKindPageAction: true,
|
||||
}
|
||||
|
||||
// ResolveResponse records a user's answer given as the kind's response
|
||||
// JSON. Authorization and validation are the same as ResolveForResume.
|
||||
func (g *Gate) ResolveResponse(ctx context.Context, req hitl.ResolveRequest) (hitl.Resolution, error) {
|
||||
if g == nil {
|
||||
return hitl.Resolution{}, fmt.Errorf("gate is nil")
|
||||
}
|
||||
if !AnswerableKinds[req.Kind] {
|
||||
return hitl.Resolution{}, fmt.Errorf("%w: prompt kind %q cannot be answered here", ErrInvalidDecision, req.Kind)
|
||||
}
|
||||
return g.broker.Resolve(ctx, req)
|
||||
}
|
||||
|
||||
func toolApprovalDecision(out hitl.Outcome) Decision {
|
||||
d := Decision{
|
||||
PendingID: out.Prompt.ID,
|
||||
owner: out.Prompt.OwnerInstance,
|
||||
answered: out.Answered,
|
||||
Reason: out.Reason,
|
||||
TimedOut: out.TimedOut,
|
||||
ContextCanceled: out.Canceled,
|
||||
}
|
||||
if !out.Answered {
|
||||
return d
|
||||
}
|
||||
var r types.ToolApprovalPromptResponse
|
||||
if err := json.Unmarshal(out.Prompt.Response, &r); err != nil {
|
||||
d.Reason = "unreadable approval response"
|
||||
return d
|
||||
}
|
||||
d.Approved, d.Reason = r.Approved, r.Reason
|
||||
if r.Approved && len(r.ModifiedArgs) > 0 {
|
||||
d.ModifiedArgs = r.ModifiedArgs
|
||||
}
|
||||
d.AllowInSession = r.Approved && r.AllowInSession
|
||||
return d
|
||||
}
|
||||
|
||||
func oauthDecision(out hitl.Outcome) Decision {
|
||||
d := Decision{
|
||||
PendingID: out.Prompt.ID,
|
||||
owner: out.Prompt.OwnerInstance,
|
||||
answered: out.Answered,
|
||||
Reason: out.Reason,
|
||||
TimedOut: out.TimedOut,
|
||||
ContextCanceled: out.Canceled,
|
||||
}
|
||||
if !out.Answered {
|
||||
return d
|
||||
}
|
||||
var r types.MCPOAuthPromptResponse
|
||||
if err := json.Unmarshal(out.Prompt.Response, &r); err != nil {
|
||||
d.Reason = "unreadable authorization response"
|
||||
return d
|
||||
}
|
||||
d.Approved, d.Reason = r.Authorized, r.Reason
|
||||
return d
|
||||
}
|
||||
|
||||
func validateToolApprovalResponse(request, response json.RawMessage) error {
|
||||
// Strict decoding with a required "approved": a misspelled or missing
|
||||
// field must not read as a rejection.
|
||||
var r struct {
|
||||
Approved *bool `json:"approved"`
|
||||
ModifiedArgs json.RawMessage `json:"modified_args,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
AllowInSession bool `json:"allow_in_session,omitempty"`
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(response))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&r); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Approved == nil {
|
||||
return errors.New(`"approved" is required`)
|
||||
}
|
||||
if r.AllowInSession {
|
||||
if !*r.Approved {
|
||||
return errors.New("allow_in_session is only allowed on approval")
|
||||
}
|
||||
var offered types.ToolApprovalPromptRequest
|
||||
if json.Unmarshal(request, &offered) != nil || offered.Grant == "" || offered.GrantScope == "" {
|
||||
return errors.New("this call cannot be allowed for the rest of the session")
|
||||
}
|
||||
}
|
||||
trimmed := strings.TrimSpace(string(r.ModifiedArgs))
|
||||
if trimmed == "" {
|
||||
return nil
|
||||
}
|
||||
if !*r.Approved {
|
||||
return errors.New("modified_args is only allowed on approval")
|
||||
}
|
||||
var probe map[string]any
|
||||
if err := json.Unmarshal(r.ModifiedArgs, &probe); err != nil || probe == nil {
|
||||
return errors.New("modified_args must be a non-null JSON object")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateMCPOAuthResponse(_, response json.RawMessage) error {
|
||||
var r types.MCPOAuthPromptResponse
|
||||
return json.Unmarshal(response, &r)
|
||||
}
|
||||
|
||||
// Adapter makes MCPToolApprovalService satisfy Checker without importing the service package here.
|
||||
type Adapter struct {
|
||||
Svc interface {
|
||||
IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error)
|
||||
Policy(ctx context.Context, tenantID uint64, serviceID, toolName string) (*types.MCPToolApproval, error)
|
||||
ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
_ Checker = (*Adapter)(nil)
|
||||
_ RiskChecker = (*Adapter)(nil)
|
||||
)
|
||||
|
||||
// Policy implements RiskChecker.
|
||||
func (a *Adapter) Policy(
|
||||
ctx context.Context, tenantID uint64, serviceID, toolName string,
|
||||
) (*types.MCPToolApproval, error) {
|
||||
if a == nil || a.Svc == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return a.Svc.Policy(ctx, tenantID, serviceID, toolName)
|
||||
}
|
||||
|
||||
// ObserveRisk implements RiskChecker.
|
||||
func (a *Adapter) ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error {
|
||||
if a == nil || a.Svc == nil {
|
||||
return nil
|
||||
}
|
||||
return a.Svc.ObserveRisk(ctx, tenantID, serviceID, toolName, risk)
|
||||
}
|
||||
|
||||
// IsRequired implements Checker.
|
||||
func (a *Adapter) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
if a == nil || a.Svc == nil {
|
||||
return false, nil
|
||||
}
|
||||
return a.Svc.IsRequired(ctx, tenantID, serviceID, toolName)
|
||||
}
|
||||
|
||||
// IsEnabled implements Checker.
|
||||
func (a *Adapter) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
if a == nil || a.Svc == nil {
|
||||
return true, nil
|
||||
}
|
||||
return a.Svc.IsEnabled(ctx, tenantID, serviceID, toolName)
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/policy"
|
||||
"academy/internal/config"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func resolveFor(g *Gate, tenantID uint64, userID, pendingID string, d Decision) error {
|
||||
return g.Resolve(context.Background(), ResolveRequest{
|
||||
TenantID: tenantID, UserID: userID, PendingID: pendingID, Decision: d,
|
||||
})
|
||||
}
|
||||
|
||||
type stubChecker struct {
|
||||
required bool
|
||||
err error
|
||||
enabled *bool
|
||||
enabledErr error
|
||||
}
|
||||
|
||||
func (s *stubChecker) IsRequired(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
return s.required, s.err
|
||||
}
|
||||
|
||||
func (s *stubChecker) Policy(context.Context, uint64, string, string) (*types.MCPToolApproval, error) {
|
||||
return &types.MCPToolApproval{RequireApproval: s.required}, s.err
|
||||
}
|
||||
|
||||
func (s *stubChecker) ObserveRisk(context.Context, uint64, string, string, string) error { return nil }
|
||||
|
||||
func (s *stubChecker) IsEnabled(ctx context.Context, tenantID uint64, serviceID, toolName string) (bool, error) {
|
||||
if s.enabledErr != nil {
|
||||
return false, s.enabledErr
|
||||
}
|
||||
if s.enabled == nil {
|
||||
return true, nil
|
||||
}
|
||||
return *s.enabled, nil
|
||||
}
|
||||
|
||||
func TestGate_RequestAndWait_Approve(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, &stubChecker{required: true}, nil)
|
||||
|
||||
ctx := attended()
|
||||
req := PendingRequest{
|
||||
TenantID: 1,
|
||||
SessionID: "s1",
|
||||
AssistantMessageID: "m1",
|
||||
EventBus: bus,
|
||||
ServiceID: "svc",
|
||||
ServiceName: "svcname",
|
||||
MCPToolName: "danger_tool",
|
||||
RegisteredToolName: "mcp_svcname_danger_tool",
|
||||
Description: "desc",
|
||||
Args: json.RawMessage(`{"a":1}`),
|
||||
ToolCallID: "tc1",
|
||||
}
|
||||
|
||||
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.ToolApprovalRequiredData)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, data.PendingID)
|
||||
go func() {
|
||||
_ = resolveFor(g, 1, "", data.PendingID, Decision{Approved: true, ModifiedArgs: json.RawMessage(`{"a":2}`)})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
|
||||
d, err := g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.True(t, d.Approved)
|
||||
require.JSONEq(t, `{"a":2}`, string(d.ModifiedArgs))
|
||||
}
|
||||
|
||||
func TestGate_RequestAndWait_Timeout(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, &stubChecker{required: true}, nil)
|
||||
ctx := attended()
|
||||
req := PendingRequest{
|
||||
TenantID: 1,
|
||||
SessionID: "s1",
|
||||
AssistantMessageID: "m1",
|
||||
EventBus: event.NewEventBus(),
|
||||
ServiceID: "svc",
|
||||
ServiceName: "svcname",
|
||||
MCPToolName: "t",
|
||||
RegisteredToolName: "mcp_svcname_t",
|
||||
Args: json.RawMessage(`{}`),
|
||||
}
|
||||
d, err := g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.False(t, d.Approved)
|
||||
require.True(t, d.TimedOut)
|
||||
}
|
||||
|
||||
func TestGate_UnattendedRunRefusesWithoutAsking(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 30}},
|
||||
&stubChecker{required: true}, nil)
|
||||
bus := event.NewEventBus()
|
||||
raised := 0
|
||||
bus.On(event.EventToolApprovalRequired, func(context.Context, event.Event) error {
|
||||
raised++
|
||||
return nil
|
||||
})
|
||||
req := PendingRequest{
|
||||
TenantID: 1, UserID: "u1", SessionID: "s1", AssistantMessageID: "m1", EventBus: bus,
|
||||
ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t",
|
||||
Args: json.RawMessage(`{}`),
|
||||
}
|
||||
ctx := types.WithRunMode(context.Background(), types.RunModeUnattended)
|
||||
|
||||
started := time.Now()
|
||||
d, err := g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.False(t, d.Approved)
|
||||
require.Equal(t, UnattendedApprovalReason, d.Reason)
|
||||
|
||||
d, err = g.RequestBuiltinApproval(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.False(t, d.Approved)
|
||||
require.Equal(t, UnattendedApprovalReason, d.Reason)
|
||||
|
||||
require.Less(t, time.Since(started), time.Second, "nothing waits for an answer")
|
||||
require.Zero(t, raised, "no card is shown to nobody")
|
||||
prompts, err := g.broker.SessionPrompts(context.Background(), "s1", []string{
|
||||
types.AgentPromptPending, types.AgentPromptAnswered, types.AgentPromptExpired,
|
||||
types.AgentPromptCanceled, types.AgentPromptSuspended,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, prompts, "no prompt is left pending")
|
||||
}
|
||||
|
||||
func TestGate_Verdict_NoChecker(t *testing.T) {
|
||||
g := NewGate(nil, nil, nil)
|
||||
require.Equal(t, policy.Allow, g.Verdict(context.Background(), 1, "x", &types.MCPTool{Name: "y"}))
|
||||
}
|
||||
|
||||
func TestGate_Resolve_NotFound(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 1}}, &stubChecker{required: true}, nil)
|
||||
err := resolveFor(g, 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, resolveFor(g, 999, "", data.PendingID, Decision{Approved: true}), ErrTenantMismatch)
|
||||
_ = resolveFor(g, 1, "", data.PendingID, Decision{Approved: false, Reason: "no"})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
d, err := g.RequestAndWait(attended(), 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, resolveFor(g, 1, "bob", data.PendingID, Decision{Approved: true}), ErrUserMismatch)
|
||||
_ = resolveFor(g, 1, "alice", data.PendingID, Decision{Approved: true})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
d, err := g.RequestAndWait(attended(), req)
|
||||
require.NoError(t, err)
|
||||
require.True(t, d.Approved)
|
||||
}
|
||||
|
||||
// TestGate_Resolve_EmptyUserIDRejectedWhenWaiterHasUser guards against the
|
||||
// previous fail-open short-circuit where an empty caller userID skipped the
|
||||
// per-user check entirely (allowing same-tenant cross-user approval).
|
||||
func TestGate_Resolve_EmptyUserIDRejectedWhenWaiterHasUser(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, resolveFor(g, 1, "", data.PendingID, Decision{Approved: true}), ErrUserMismatch)
|
||||
_ = resolveFor(g, 1, "alice", data.PendingID, Decision{Approved: false, Reason: "no"})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
d, err := g.RequestAndWait(attended(), req)
|
||||
require.NoError(t, err)
|
||||
require.False(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
|
||||
})
|
||||
|
||||
lateErr := make(chan error, 1)
|
||||
go func() {
|
||||
<-gotPending
|
||||
// 1s timeout + small slack: the prompt row outlives the wait and
|
||||
// records the timeout, so a late decision cannot reopen it.
|
||||
<-time.After(1500 * time.Millisecond)
|
||||
lateErr <- resolveFor(g, 1, "", pendingID, Decision{Approved: true})
|
||||
}()
|
||||
|
||||
d, err := g.RequestAndWait(attended(), PendingRequest{
|
||||
TenantID: 1, EventBus: bus, SessionID: "s",
|
||||
ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, d.TimedOut)
|
||||
require.ErrorIs(t, <-lateErr, ErrAlreadyResolved)
|
||||
|
||||
row, err := g.broker.Store().Get(context.Background(), pendingID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptExpired, row.Status)
|
||||
}
|
||||
|
||||
func TestGate_ApprovedCallStaysExecutingUntilMarked(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 5}},
|
||||
&stubChecker{required: true}, nil)
|
||||
bus := event.NewEventBus()
|
||||
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
|
||||
pendingID := evt.Data.(event.ToolApprovalRequiredData).PendingID
|
||||
go func() {
|
||||
require.ErrorIs(t,
|
||||
resolveFor(g, 1, "", pendingID, Decision{Approved: true, ModifiedArgs: json.RawMessage(`[1]`)}),
|
||||
ErrInvalidDecision)
|
||||
require.ErrorIs(t, g.Resolve(context.Background(), ResolveRequest{
|
||||
TenantID: 1, Kind: types.AgentPromptKindMCPOAuth, PendingID: pendingID,
|
||||
Decision: Decision{Approved: true},
|
||||
}), ErrPendingNotFound)
|
||||
require.NoError(t, resolveFor(g, 1, "", pendingID, Decision{Approved: true}))
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
|
||||
d, err := g.RequestAndWait(attended(), PendingRequest{
|
||||
TenantID: 1, EventBus: bus, SessionID: "s",
|
||||
ServiceID: "svc", MCPToolName: "t", Args: json.RawMessage(`{}`),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, d.Approved)
|
||||
|
||||
row, err := g.broker.Store().Get(context.Background(), d.PendingID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptExecuting, row.Status)
|
||||
var request types.ToolApprovalPromptRequest
|
||||
require.NoError(t, json.Unmarshal(row.Request, &request))
|
||||
require.Equal(t, "svc", request.ServiceID)
|
||||
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
row, err = g.broker.Store().Get(context.Background(), d.PendingID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptDone, row.Status)
|
||||
}
|
||||
|
||||
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 := resolveFor(g, 1, "", pendingID, Decision{Approved: true})
|
||||
err2 := resolveFor(g, 1, "", pendingID, Decision{Approved: false})
|
||||
resCh <- result{first: err1, second: err2}
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
|
||||
d, err := g.RequestAndWait(attended(), 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)
|
||||
require.ErrorIs(t, r.second, ErrAlreadyResolved)
|
||||
}
|
||||
|
||||
func boolPtr(v bool) *bool { return &v }
|
||||
|
||||
func TestGate_IsEnabled_NoCheckerKeepsToolsOn(t *testing.T) {
|
||||
g := NewGate(nil, nil, nil)
|
||||
enabled, err := g.IsEnabled(context.Background(), 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.True(t, enabled)
|
||||
}
|
||||
|
||||
func TestGate_IsEnabled_MissingTenantFailClosed(t *testing.T) {
|
||||
g := NewGate(nil, &stubChecker{}, nil)
|
||||
enabled, err := g.IsEnabled(context.Background(), 0, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.False(t, enabled)
|
||||
}
|
||||
|
||||
func TestGate_IsEnabled_HonorsChecker(t *testing.T) {
|
||||
g := NewGate(nil, &stubChecker{enabled: boolPtr(false)}, nil)
|
||||
enabled, err := g.IsEnabled(context.Background(), 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.False(t, enabled)
|
||||
}
|
||||
|
||||
func TestGate_IsEnabled_CheckerErrorPropagates(t *testing.T) {
|
||||
g := NewGate(nil, &stubChecker{enabledErr: context.DeadlineExceeded}, nil)
|
||||
enabled, err := g.IsEnabled(context.Background(), 1, "svc", "tool")
|
||||
require.Error(t, err)
|
||||
require.False(t, enabled)
|
||||
}
|
||||
|
||||
func TestAdapter_IsEnabled(t *testing.T) {
|
||||
a := &Adapter{Svc: &stubChecker{enabled: boolPtr(false)}}
|
||||
enabled, err := a.IsEnabled(context.Background(), 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.False(t, enabled)
|
||||
|
||||
empty := &Adapter{}
|
||||
enabled, err = empty.IsEnabled(context.Background(), 1, "svc", "tool")
|
||||
require.NoError(t, err)
|
||||
require.True(t, enabled)
|
||||
}
|
||||
|
||||
func TestGate_RequestAndWait_SuspendsAfterHotWait(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{
|
||||
ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 1,
|
||||
}}, &stubChecker{required: true}, nil)
|
||||
|
||||
var required event.ToolApprovalRequiredData
|
||||
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
|
||||
required = evt.Data.(event.ToolApprovalRequiredData)
|
||||
return nil
|
||||
})
|
||||
resolved := false
|
||||
bus.On(event.EventToolApprovalResolved, func(context.Context, event.Event) error {
|
||||
resolved = true
|
||||
return nil
|
||||
})
|
||||
|
||||
d, err := g.RequestAndWait(attended(), PendingRequest{
|
||||
TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", EventBus: bus,
|
||||
ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t",
|
||||
Args: json.RawMessage(`{}`), ToolCallID: "tc1",
|
||||
Snapshot: []byte(`{"version":1}`), SnapshotVersion: 1,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.False(t, d.Approved)
|
||||
require.False(t, d.TimedOut)
|
||||
require.NotNil(t, d.Suspended)
|
||||
require.Equal(t, d.PendingID, d.Suspended.PromptID)
|
||||
require.Equal(t, types.AgentPromptKindToolApproval, d.Suspended.Kind)
|
||||
require.NotNil(t, d.Suspended.ExpiresAt)
|
||||
|
||||
require.True(t, required.Suspendable)
|
||||
require.Equal(t, 1, required.HotWaitSeconds)
|
||||
require.False(t, resolved, "a suspended approval is still open")
|
||||
}
|
||||
|
||||
func TestGate_DeferredRunSuspendsAtOnce(t *testing.T) {
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{
|
||||
ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 30,
|
||||
}}, &stubChecker{required: true}, nil)
|
||||
ctx := types.WithRunMode(context.Background(), types.RunModeDeferred)
|
||||
req := PendingRequest{
|
||||
TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", EventBus: event.NewEventBus(),
|
||||
ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t",
|
||||
Args: json.RawMessage(`{}`), ToolCallID: "tc1",
|
||||
}
|
||||
|
||||
d, err := g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.False(t, d.Approved)
|
||||
require.Equal(t, DeferredApprovalReason, d.Reason, "without saved state the run cannot wait")
|
||||
|
||||
req.Snapshot, req.SnapshotVersion = []byte(`{"version":1}`), 1
|
||||
started := time.Now()
|
||||
d, err = g.RequestAndWait(ctx, req)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, d.Suspended)
|
||||
require.Less(t, time.Since(started), 5*time.Second, "a deferred run skips the hot wait")
|
||||
}
|
||||
|
||||
func TestGate_ResolveSuspendedThenResumeDecision(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{
|
||||
ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 1,
|
||||
}}, &stubChecker{required: true}, nil)
|
||||
d, err := g.RequestAndWait(attended(), PendingRequest{
|
||||
TenantID: 1, SessionID: "s1", AssistantMessageID: "m1", EventBus: bus,
|
||||
ServiceID: "svc", ServiceName: "svcname", MCPToolName: "t", RegisteredToolName: "mcp_svcname_t",
|
||||
Args: json.RawMessage(`{"a":1}`), ToolCallID: "tc1",
|
||||
Snapshot: []byte(`{"version":1}`), SnapshotVersion: 1,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, d.Suspended)
|
||||
|
||||
res, err := g.ResolveForResume(context.Background(), ResolveRequest{
|
||||
TenantID: 1, PendingID: d.PendingID,
|
||||
Decision: Decision{Approved: true, ModifiedArgs: json.RawMessage(`{"a":2}`)},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Resume)
|
||||
|
||||
var resolved event.ToolApprovalResolvedData
|
||||
resumeBus := event.NewEventBus()
|
||||
resumeBus.On(event.EventToolApprovalResolved, func(_ context.Context, evt event.Event) error {
|
||||
resolved = evt.Data.(event.ToolApprovalResolvedData)
|
||||
return nil
|
||||
})
|
||||
got := g.ResumeDecision(context.Background(), res.Prompt, resumeBus)
|
||||
require.True(t, got.Approved)
|
||||
require.JSONEq(t, `{"a":2}`, string(got.ModifiedArgs))
|
||||
require.Equal(t, d.PendingID, resolved.PendingID)
|
||||
require.True(t, resolved.Approved)
|
||||
require.False(t, g.ResumeDecision(context.Background(), res.Prompt, nil).Approved,
|
||||
"an approval can execute only once")
|
||||
|
||||
row, err := g.broker.Store().Get(context.Background(), d.PendingID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptExecuting, row.Status)
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
row, err = g.broker.Store().Get(context.Background(), d.PendingID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, types.AgentPromptDone, row.Status)
|
||||
}
|
||||
|
||||
func TestValidateToolApprovalResponse_IsStrict(t *testing.T) {
|
||||
for body, ok := range map[string]bool{
|
||||
`{"approved":true}`: true,
|
||||
`{"approved":false,"reason":"no"}`: true,
|
||||
`{"approved":true,"modified_args":{"q":"x"}}`: true,
|
||||
`{"decision":"approve"}`: false,
|
||||
`{}`: false,
|
||||
`{"approved":true,"extra":1}`: false,
|
||||
`{"approved":false,"modified_args":{"q":"x"}}`: false,
|
||||
`{"approved":true,"modified_args":null}`: false,
|
||||
`{"approved":true,"modified_args":["not","obj"]}`: false,
|
||||
} {
|
||||
err := validateToolApprovalResponse(nil, json.RawMessage(body))
|
||||
if ok {
|
||||
require.NoError(t, err, body)
|
||||
} else {
|
||||
require.Error(t, err, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnsweredPromptOnlyCurrentOwnerCanContinue(t *testing.T) {
|
||||
for _, kind := range []string{types.AgentPromptKindToolApproval, types.AgentPromptKindAskUser} {
|
||||
for _, accept := range []bool{true, false} {
|
||||
name := kind + "/decline"
|
||||
if accept {
|
||||
name = kind + "/accept"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
g := NewGate(nil, nil, nil)
|
||||
response := `{"approved":false}`
|
||||
if kind == types.AgentPromptKindAskUser {
|
||||
response = `{"declined":true}`
|
||||
if accept {
|
||||
response = `{"text":"staging"}`
|
||||
}
|
||||
} else if accept {
|
||||
response = `{"approved":true}`
|
||||
}
|
||||
current := &types.AgentPrompt{
|
||||
ID: "p", Kind: kind, Status: types.AgentPromptAnswered,
|
||||
OwnerInstance: "new-run", Response: types.JSON(response),
|
||||
}
|
||||
require.NoError(t, g.broker.Store().Create(ctx, current))
|
||||
stale := *current
|
||||
stale.OwnerInstance = "old-run"
|
||||
if kind == types.AgentPromptKindAskUser {
|
||||
denied := g.ResumeAnswer(ctx, &stale, nil)
|
||||
require.False(t, denied.Answered)
|
||||
require.NotNil(t, denied.Suspended)
|
||||
require.True(t, denied.Suspended.Detached)
|
||||
winner := g.ResumeAnswer(ctx, current, nil)
|
||||
require.Nil(t, winner.Suspended)
|
||||
require.Equal(t, accept, winner.Answered)
|
||||
duplicate := g.ResumeAnswer(ctx, current, nil)
|
||||
require.NotNil(t, duplicate.Suspended)
|
||||
require.True(t, duplicate.Suspended.Detached)
|
||||
} else {
|
||||
denied := g.ResumeDecision(ctx, &stale, nil)
|
||||
require.False(t, denied.Approved)
|
||||
require.NotNil(t, denied.Suspended)
|
||||
require.True(t, denied.Suspended.Detached)
|
||||
winner := g.ResumeDecision(ctx, current, nil)
|
||||
require.Nil(t, winner.Suspended)
|
||||
require.Equal(t, accept, winner.Approved)
|
||||
duplicate := g.ResumeDecision(ctx, current, nil)
|
||||
require.NotNil(t, duplicate.Suspended)
|
||||
require.True(t, duplicate.Suspended.Detached)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func attended() context.Context {
|
||||
return types.WithRunMode(context.Background(), types.RunModeAttended)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/policy"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// GrantStore keeps the approvals a user allowed to be remembered.
|
||||
type GrantStore interface {
|
||||
FindGrant(ctx context.Context, tenantID uint64, userID string, scope types.GrantScope, key string) (
|
||||
*types.AgentGrant, error)
|
||||
SaveGrant(ctx context.Context, grant *types.AgentGrant) error
|
||||
TouchGrant(ctx context.Context, id string, at time.Time) error
|
||||
}
|
||||
|
||||
// WithGrants makes the gate remember "allow for the rest" approvals in
|
||||
// store. Without one, every call asks.
|
||||
func (g *Gate) WithGrants(store GrantStore) *Gate {
|
||||
g.grants = store
|
||||
return g
|
||||
}
|
||||
|
||||
// grantScope is where grants of a run on ctx live: the scope the run set,
|
||||
// else the session of the call.
|
||||
func grantScope(ctx context.Context, sessionID string) (types.GrantScope, bool) {
|
||||
if scope, ok := types.GrantScopeFromContext(ctx); ok {
|
||||
return scope, true
|
||||
}
|
||||
if sessionID == "" {
|
||||
return types.GrantScope{}, false
|
||||
}
|
||||
return types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: sessionID}, true
|
||||
}
|
||||
|
||||
// granted reports whether the user already allowed calls with req's grant,
|
||||
// in the run's own scope or its standing one. When they had but it no
|
||||
// longer applies, lapse says why; a revoked grant is not reported, since the
|
||||
// user withdrew it. Any lookup failure asks again.
|
||||
func (g *Gate) granted(ctx context.Context, req PendingRequest) (ok bool, lapse string) {
|
||||
if g.grants == nil || req.Grant == "" || req.UserID == "" || req.TenantID == 0 {
|
||||
return false, ""
|
||||
}
|
||||
var scopes []types.GrantScope
|
||||
if scope, ok := grantScope(ctx, req.SessionID); ok {
|
||||
scopes = append(scopes, scope)
|
||||
}
|
||||
if scope, ok := types.StandingGrantScopeFromContext(ctx); ok {
|
||||
scopes = append(scopes, scope)
|
||||
}
|
||||
for _, scope := range scopes {
|
||||
ok, why := g.grantedIn(ctx, req, scope)
|
||||
if ok {
|
||||
return true, ""
|
||||
}
|
||||
if lapse == "" {
|
||||
lapse = why
|
||||
}
|
||||
}
|
||||
return false, lapse
|
||||
}
|
||||
|
||||
func (g *Gate) grantedIn(ctx context.Context, req PendingRequest, scope types.GrantScope) (bool, string) {
|
||||
grant, err := g.grants.FindGrant(ctx, req.TenantID, req.UserID, scope, req.Grant)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "tool approval: read grant: %v", err)
|
||||
return false, ""
|
||||
}
|
||||
if grant == nil {
|
||||
return false, ""
|
||||
}
|
||||
if !policy.Covers(policy.Risk(grant.Risk), req.grantRisk()) {
|
||||
logger.Infof(ctx, "tool approval: grant %s was approved for %s, not %s; asking",
|
||||
grant.ID, grant.Risk, req.grantRisk())
|
||||
return false, ""
|
||||
}
|
||||
now := time.Now()
|
||||
if lapse := grant.LapseAt(now, scope.BindingHash); lapse != "" {
|
||||
if lapse == types.AgentGrantLapseRevoked {
|
||||
return false, ""
|
||||
}
|
||||
logger.Infof(ctx, "tool approval: grant %s %s; asking again", grant.ID, lapse)
|
||||
return false, lapse
|
||||
}
|
||||
if err := g.grants.TouchGrant(ctx, grant.ID, now); err != nil {
|
||||
logger.Warnf(ctx, "tool approval: record grant use: %v", err)
|
||||
}
|
||||
if req.grantRisk() == policy.RiskDestructive {
|
||||
logger.GetLogger(ctx).WithFields(logger.Fields{
|
||||
"agent_action": req.Grant, "agent_grant_id": grant.ID, "agent_granted_destructive": true,
|
||||
"agent_acting_via": types.ActingViaFromContext(ctx),
|
||||
}).Info("agent policy decision")
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
// remember stores the grant an approved prompt allowed for the rest of the
|
||||
// run's scope.
|
||||
func (g *Gate) remember(ctx context.Context, d Decision, prompt *types.AgentPrompt) {
|
||||
if g.grants == nil || prompt == nil || !d.Approved || !d.AllowInSession {
|
||||
return
|
||||
}
|
||||
var request types.ToolApprovalPromptRequest
|
||||
if json.Unmarshal(prompt.Request, &request) != nil || request.Grant == "" {
|
||||
return
|
||||
}
|
||||
scope, ok := grantScope(ctx, prompt.SessionID)
|
||||
if !ok || prompt.TenantID == 0 || prompt.UserID == "" {
|
||||
return
|
||||
}
|
||||
grant := &types.AgentGrant{
|
||||
TenantID: prompt.TenantID, UserID: prompt.UserID,
|
||||
Scope: scope.Scope, ScopeID: scope.ScopeID, GrantKey: request.Grant,
|
||||
Label: request.GrantScope, BindingHash: scope.BindingHash, PromptID: prompt.ID,
|
||||
Risk: string(policy.RiskWrite),
|
||||
}
|
||||
if err := g.grants.SaveGrant(context.WithoutCancel(ctx), grant); err != nil {
|
||||
logger.Warnf(ctx, "tool approval: remember grant: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/agent/policy"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// RiskChecker reads and records the risk policy of MCP tools. A Checker that
|
||||
// does not implement it leaves every MCP tool at RiskWrite.
|
||||
type RiskChecker interface {
|
||||
// Policy returns the stored policy of a tool, or nil when it has none.
|
||||
Policy(ctx context.Context, tenantID uint64, serviceID, toolName string) (*types.MCPToolApproval, error)
|
||||
// ObserveRisk records a risk the service declared; the stored one only rises.
|
||||
ObserveRisk(ctx context.Context, tenantID uint64, serviceID, toolName string, risk string) error
|
||||
}
|
||||
|
||||
// DeclaredRisk is the risk a service's annotations give its tool. Only
|
||||
// readOnlyHint lowers it: MCP defaults destructiveHint to true, so reading
|
||||
// it would make every unannotated tool destructive. Destructive is set by
|
||||
// the workspace.
|
||||
func DeclaredRisk(tool *types.MCPTool) policy.Risk {
|
||||
if tool.DeclaresReadOnly() {
|
||||
return policy.RiskRead
|
||||
}
|
||||
return policy.RiskWrite
|
||||
}
|
||||
|
||||
// ToolRisk is the risk a stored policy and the service's declaration give a
|
||||
// tool. The workspace's explicit risk wins; otherwise the declaration counts
|
||||
// unless the service declared a higher risk before, so a service cannot
|
||||
// lower its own tool's risk without the workspace agreeing.
|
||||
func ToolRisk(row *types.MCPToolApproval, declared policy.Risk) policy.Risk {
|
||||
if row == nil {
|
||||
return declared
|
||||
}
|
||||
if explicit := policy.Risk(row.Risk); explicit.Valid() {
|
||||
return explicit
|
||||
}
|
||||
if observed := policy.Risk(row.ObservedRisk); observed.Above(declared) {
|
||||
return observed
|
||||
}
|
||||
return declared
|
||||
}
|
||||
|
||||
// PendingDowngrade reports whether the service now declares a lower risk
|
||||
// than the one in force, which only the workspace can accept.
|
||||
func PendingDowngrade(row *types.MCPToolApproval, declared policy.Risk) bool {
|
||||
return row != nil && !policy.Risk(row.Risk).Valid() && policy.Risk(row.ObservedRisk).Above(declared)
|
||||
}
|
||||
|
||||
// Action is the policy action of calling tool: its risk, and whether the
|
||||
// workspace marked it as always requiring approval.
|
||||
func (g *Gate) Action(ctx context.Context, tenantID uint64, serviceID string, tool *types.MCPTool) policy.Action {
|
||||
declared := DeclaredRisk(tool)
|
||||
if g == nil || g.checker == nil || tenantID == 0 || serviceID == "" || tool == nil || tool.Name == "" {
|
||||
return policy.Action{Risk: declared}
|
||||
}
|
||||
risks, ok := g.checker.(RiskChecker)
|
||||
if !ok {
|
||||
return policy.Action{Risk: policy.RiskWrite, Always: g.requiredByPolicy(ctx, tenantID, serviceID, tool.Name)}
|
||||
}
|
||||
row, err := risks.Policy(ctx, tenantID, serviceID, tool.Name)
|
||||
if err != nil {
|
||||
return g.failedAction(ctx, err)
|
||||
}
|
||||
if row == nil || declared.Above(policy.Risk(row.ObservedRisk)) {
|
||||
if err := risks.ObserveRisk(ctx, tenantID, serviceID, tool.Name, string(declared)); err != nil {
|
||||
logger.GetLogger(ctx).Warnf("record declared risk of MCP tool %s: %v", tool.Name, err)
|
||||
}
|
||||
}
|
||||
return policy.Action{Risk: ToolRisk(row, declared), Always: row != nil && row.RequireApproval}
|
||||
}
|
||||
|
||||
// failedAction is the action used when the tool's policy cannot be read.
|
||||
func (g *Gate) failedAction(ctx context.Context, err error) policy.Action {
|
||||
// Default fail-close: a transient DB error must NOT silently allow a
|
||||
// dangerous tool to run. Operators can opt into legacy behaviour via
|
||||
// ACADEMY_AGENT_TOOL_APPROVAL_FAIL_OPEN=true.
|
||||
if g.failClose {
|
||||
logger.GetLogger(ctx).Warnf("mcp tool approval check failed (fail-close: requiring approval): %v", err)
|
||||
return policy.Action{Risk: policy.RiskWrite, Always: true}
|
||||
}
|
||||
logger.GetLogger(ctx).Warnf("mcp tool approval check failed (fail-open: skip gate): %v", err)
|
||||
return policy.Action{Risk: policy.RiskWrite}
|
||||
}
|
||||
|
||||
// ToolRisks returns the risk of each tool of a service in one policy read,
|
||||
// without recording what the service declares.
|
||||
func (g *Gate) ToolRisks(
|
||||
ctx context.Context, tenantID uint64, serviceID string, tools []*types.MCPTool,
|
||||
) (map[string]policy.Risk, error) {
|
||||
rows := map[string]*types.MCPToolApproval{}
|
||||
if g != nil && g.checker != nil && tenantID != 0 && serviceID != "" {
|
||||
lister, ok := g.checker.(interface {
|
||||
ListByService(context.Context, uint64, string) ([]*types.MCPToolApproval, error)
|
||||
})
|
||||
if !ok {
|
||||
if adapter, isAdapter := g.checker.(*Adapter); isAdapter && adapter != nil {
|
||||
lister, ok = adapter.Svc.(interface {
|
||||
ListByService(context.Context, uint64, string) ([]*types.MCPToolApproval, error)
|
||||
})
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
list, err := lister.ListByService(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range list {
|
||||
if row != nil && row.TenantID == tenantID && row.ServiceID == serviceID {
|
||||
rows[row.ToolName] = row
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
risks := make(map[string]policy.Risk, len(tools))
|
||||
for _, tool := range tools {
|
||||
if tool != nil {
|
||||
risks[tool.Name] = ToolRisk(rows[tool.Name], DeclaredRisk(tool))
|
||||
}
|
||||
}
|
||||
return risks, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"academy/internal/agent/policy"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
type riskChecker struct {
|
||||
stubChecker
|
||||
row *types.MCPToolApproval
|
||||
observed []string
|
||||
}
|
||||
|
||||
func (c *riskChecker) Policy(context.Context, uint64, string, string) (*types.MCPToolApproval, error) {
|
||||
return c.row, c.err
|
||||
}
|
||||
|
||||
func (c *riskChecker) ObserveRisk(_ context.Context, _ uint64, _, _ string, risk string) error {
|
||||
c.observed = append(c.observed, risk)
|
||||
return nil
|
||||
}
|
||||
|
||||
func readOnlyTool(readOnly bool) *types.MCPTool {
|
||||
return &types.MCPTool{Name: "t", Annotations: &types.MCPToolAnnotations{ReadOnlyHint: &readOnly}}
|
||||
}
|
||||
|
||||
func TestDeclaredRiskReadsOnlyTheReadOnlyHint(t *testing.T) {
|
||||
destructive := true
|
||||
require.Equal(t, policy.RiskRead, DeclaredRisk(readOnlyTool(true)))
|
||||
require.Equal(t, policy.RiskWrite, DeclaredRisk(readOnlyTool(false)))
|
||||
require.Equal(t, policy.RiskWrite, DeclaredRisk(&types.MCPTool{Name: "t"}))
|
||||
require.Equal(t, policy.RiskWrite, DeclaredRisk(&types.MCPTool{
|
||||
Name: "t", Annotations: &types.MCPToolAnnotations{DestructiveHint: &destructive},
|
||||
}), "destructive is the workspace's call, not the service's")
|
||||
}
|
||||
|
||||
func TestToolRisk(t *testing.T) {
|
||||
require.Equal(t, policy.RiskRead, ToolRisk(nil, policy.RiskRead))
|
||||
raised := &types.MCPToolApproval{ObservedRisk: "write"}
|
||||
require.Equal(t, policy.RiskWrite, ToolRisk(raised, policy.RiskRead), "a service cannot lower its own risk")
|
||||
require.True(t, PendingDowngrade(raised, policy.RiskRead))
|
||||
require.Equal(t, policy.RiskWrite, ToolRisk(&types.MCPToolApproval{ObservedRisk: "read"}, policy.RiskWrite),
|
||||
"a raised declaration counts at once")
|
||||
explicit := &types.MCPToolApproval{Risk: "read", ObservedRisk: "write"}
|
||||
require.Equal(t, policy.RiskRead, ToolRisk(explicit, policy.RiskWrite), "the workspace's setting wins")
|
||||
require.False(t, PendingDowngrade(explicit, policy.RiskRead))
|
||||
}
|
||||
|
||||
func TestGateVerdictAppliesTheRunLevelToMCP(t *testing.T) {
|
||||
ctxAt := func(level types.AssistantAccessLevel) context.Context {
|
||||
return types.WithAccessLevel(context.Background(), level)
|
||||
}
|
||||
g := NewGate(nil, &riskChecker{}, nil)
|
||||
read, write := readOnlyTool(true), readOnlyTool(false)
|
||||
|
||||
require.Equal(t, policy.Allow, g.Verdict(ctxAt(types.AssistantAccessReadOnly), 1, "svc", read))
|
||||
require.Equal(t, policy.Deny, g.Verdict(ctxAt(types.AssistantAccessReadOnly), 1, "svc", write))
|
||||
require.Equal(t, policy.Ask, g.Verdict(ctxAt(types.AssistantAccessConfirm), 1, "svc", write))
|
||||
require.Equal(t, policy.Allow, g.Verdict(ctxAt(types.AssistantAccessAutoWrite), 1, "svc", write))
|
||||
require.Equal(t, policy.Allow, g.Verdict(context.Background(), 1, "svc", write),
|
||||
"a run without a level keeps the unconfigured agent's auto_write")
|
||||
|
||||
always := NewGate(nil, &riskChecker{row: &types.MCPToolApproval{RequireApproval: true}}, nil)
|
||||
require.Equal(t, policy.Ask, always.Verdict(ctxAt(types.AssistantAccessAutoWrite), 1, "svc", read))
|
||||
|
||||
destructive := NewGate(nil, &riskChecker{row: &types.MCPToolApproval{Risk: "destructive"}}, nil)
|
||||
require.Equal(t, policy.Ask, destructive.Verdict(ctxAt(types.AssistantAccessAutoWrite), 1, "svc", write))
|
||||
}
|
||||
|
||||
func TestGateVerdictRecordsOnlyRaisedDeclarations(t *testing.T) {
|
||||
ctx := types.WithAccessLevel(context.Background(), types.AssistantAccessConfirm)
|
||||
checker := &riskChecker{}
|
||||
g := NewGate(nil, checker, nil)
|
||||
|
||||
g.Verdict(ctx, 1, "svc", readOnlyTool(true))
|
||||
require.Equal(t, []string{"read"}, checker.observed, "a first declaration is recorded")
|
||||
|
||||
checker.row, checker.observed = &types.MCPToolApproval{ObservedRisk: "read"}, nil
|
||||
require.Equal(t, policy.Ask, g.Verdict(ctx, 1, "svc", readOnlyTool(false)))
|
||||
require.Equal(t, []string{"write"}, checker.observed, "a raised declaration is recorded")
|
||||
|
||||
checker.row, checker.observed = &types.MCPToolApproval{ObservedRisk: "write"}, nil
|
||||
require.Equal(t, policy.Ask, g.Verdict(ctx, 1, "svc", readOnlyTool(true)),
|
||||
"a lowered declaration waits for the workspace")
|
||||
require.Empty(t, checker.observed)
|
||||
}
|
||||
|
||||
func TestGateToolRisksReadsPoliciesInBulk(t *testing.T) {
|
||||
g := NewGate(nil, nil, nil)
|
||||
risks, err := g.ToolRisks(context.Background(), 1, "svc", []*types.MCPTool{readOnlyTool(true)})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, policy.RiskRead, risks["t"])
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// DefaultPageActionTimeout bounds how long a run waits for the browser. The
|
||||
// browser answers by itself, so a page that does not answer quickly is gone.
|
||||
const DefaultPageActionTimeout = 20 * time.Second
|
||||
|
||||
// PageActionRequest asks the user's browser to read or fill the open page.
|
||||
type PageActionRequest struct {
|
||||
TenantID uint64
|
||||
UserID string
|
||||
SessionID string
|
||||
AssistantMessageID string
|
||||
RequestID string
|
||||
ToolCallID string
|
||||
EventBus *event.EventBus
|
||||
Action types.PageActionPromptRequest
|
||||
// Timeout overrides DefaultPageActionTimeout when > 0.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// PageActionResult is how the browser answered.
|
||||
type PageActionResult struct {
|
||||
Answered bool
|
||||
Response types.PageActionPromptResponse
|
||||
Reason string
|
||||
TimedOut bool
|
||||
Canceled bool
|
||||
}
|
||||
|
||||
// PageActor is the surface the page tools use (mockable in tests).
|
||||
type PageActor interface {
|
||||
RequestPageAction(ctx context.Context, req PageActionRequest) (PageActionResult, error)
|
||||
}
|
||||
|
||||
var _ PageActor = (*Gate)(nil)
|
||||
|
||||
// RequestPageAction sends the action to the browser and waits for its answer.
|
||||
// The prompt never suspends the run: the page is read or filled now or not
|
||||
// at all.
|
||||
func (g *Gate) RequestPageAction(ctx context.Context, req PageActionRequest) (PageActionResult, error) {
|
||||
if g == nil {
|
||||
return PageActionResult{}, fmt.Errorf("page action: nil gate")
|
||||
}
|
||||
if req.EventBus == nil {
|
||||
return PageActionResult{}, fmt.Errorf("page action: EventBus is nil")
|
||||
}
|
||||
request, err := json.Marshal(req.Action)
|
||||
if err != nil {
|
||||
return PageActionResult{}, fmt.Errorf("encode page action: %w", err)
|
||||
}
|
||||
wait := req.Timeout
|
||||
if wait <= 0 {
|
||||
wait = DefaultPageActionTimeout
|
||||
}
|
||||
out, err := g.broker.Await(ctx, hitl.Spec{
|
||||
Prompt: &types.AgentPrompt{
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
RequestID: req.RequestID,
|
||||
Kind: types.AgentPromptKindPageAction,
|
||||
ToolCallID: req.ToolCallID,
|
||||
Request: types.JSON(request),
|
||||
},
|
||||
Timeout: wait,
|
||||
TimeoutReason: "the page did not respond",
|
||||
Emit: func(ctx context.Context, p *types.AgentPrompt) error {
|
||||
waitSec := max(int(wait/time.Second), 1)
|
||||
return req.EventBus.Emit(ctx, event.Event{
|
||||
ID: p.ID + "-prompt-required",
|
||||
Type: event.EventAgentPromptRequired,
|
||||
SessionID: req.SessionID,
|
||||
Data: event.AgentPromptRequiredData{
|
||||
PendingID: p.ID,
|
||||
Kind: types.AgentPromptKindPageAction,
|
||||
SessionID: req.SessionID,
|
||||
AssistantMessageID: req.AssistantMessageID,
|
||||
Request: request,
|
||||
TimeoutSeconds: waitSec,
|
||||
HotWaitSeconds: waitSec,
|
||||
RequestedAtUnix: time.Now().Unix(),
|
||||
ToolCallID: req.ToolCallID,
|
||||
RequestID: req.RequestID,
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"assistant_message_id": req.AssistantMessageID,
|
||||
"pending_id": p.ID,
|
||||
},
|
||||
RequestID: req.RequestID,
|
||||
})
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return PageActionResult{}, fmt.Errorf("page action: %w", err)
|
||||
}
|
||||
res := PageActionResult{Reason: out.Reason, TimedOut: out.TimedOut, Canceled: out.Canceled}
|
||||
if out.Suspended || !out.Answered {
|
||||
if out.Suspended && res.Reason == "" {
|
||||
res.Reason = "the run was taken over"
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
if err := json.Unmarshal(out.Prompt.Response, &res.Response); err != nil {
|
||||
res.Reason = "unreadable page response"
|
||||
return res, nil
|
||||
}
|
||||
consumed, consumeErr := g.broker.Consume(ctx, out.Prompt.ID, types.AgentPromptDone, out.Prompt.OwnerInstance)
|
||||
if !consumed {
|
||||
res.Response = types.PageActionPromptResponse{}
|
||||
res.Reason = "the page response could not be confirmed"
|
||||
if consumeErr == nil {
|
||||
res.Reason = "the page response was already used"
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
res.Answered = true
|
||||
return res, nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func pageActionRequest(bus *event.EventBus) PageActionRequest {
|
||||
return PageActionRequest{
|
||||
TenantID: 1, UserID: "user:u1", SessionID: "s1", AssistantMessageID: "m1", ToolCallID: "tc1",
|
||||
EventBus: bus, Action: types.PageActionPromptRequest{Action: types.PageActionRead},
|
||||
}
|
||||
}
|
||||
|
||||
func answerPageAction(g *Gate, id, response string) error {
|
||||
_, err := g.ResolveResponse(context.Background(), hitl.ResolveRequest{
|
||||
TenantID: 1, UserID: "user:u1", SessionID: "s1", Kind: types.AgentPromptKindPageAction,
|
||||
PromptID: id, Response: json.RawMessage(response),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func TestGate_PageActionAnswered(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(nil, nil, nil)
|
||||
invalid := make(chan error, 1)
|
||||
bus.On(event.EventAgentPromptRequired, func(_ context.Context, evt event.Event) error {
|
||||
data := evt.Data.(event.AgentPromptRequiredData)
|
||||
assert.Equal(t, types.AgentPromptKindPageAction, data.Kind)
|
||||
assert.Equal(t, "tc1", data.ToolCallID)
|
||||
assert.False(t, data.Suspendable)
|
||||
assert.JSONEq(t, `{"action":"read"}`, string(data.Request))
|
||||
go func() {
|
||||
invalid <- answerPageAction(g, data.PendingID, `{"applied":[{"ref":"e1"}]}`)
|
||||
_ = answerPageAction(g, data.PendingID, `{"location":"Docs","snapshot":"heading \"Docs\""}`)
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
|
||||
res, err := g.RequestPageAction(context.Background(), pageActionRequest(bus))
|
||||
require.NoError(t, err)
|
||||
require.ErrorIs(t, <-invalid, ErrInvalidDecision, "a read answered with a fill result is rejected")
|
||||
require.True(t, res.Answered)
|
||||
assert.Equal(t, "Docs", res.Response.Location)
|
||||
assert.Equal(t, `heading "Docs"`, res.Response.Snapshot)
|
||||
}
|
||||
|
||||
func TestGate_PageActionTimesOut(t *testing.T) {
|
||||
g := NewGate(nil, nil, nil)
|
||||
req := pageActionRequest(event.NewEventBus())
|
||||
req.Timeout = 50 * time.Millisecond
|
||||
res, err := g.RequestPageAction(context.Background(), req)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, res.Answered)
|
||||
assert.True(t, res.TimedOut)
|
||||
assert.Equal(t, "the page did not respond", res.Reason)
|
||||
}
|
||||
|
||||
func TestGate_PageActionRefusesAnotherUser(t *testing.T) {
|
||||
bus := event.NewEventBus()
|
||||
g := NewGate(nil, nil, nil)
|
||||
bus.On(event.EventAgentPromptRequired, func(_ context.Context, evt event.Event) error {
|
||||
id := evt.Data.(event.AgentPromptRequiredData).PendingID
|
||||
go func() {
|
||||
_, err := g.ResolveResponse(context.Background(), hitl.ResolveRequest{
|
||||
TenantID: 1, UserID: "user:intruder", SessionID: "s1", Kind: types.AgentPromptKindPageAction,
|
||||
PromptID: id, Response: json.RawMessage(`{"snapshot":"forged"}`),
|
||||
})
|
||||
assert.ErrorIs(t, err, ErrUserMismatch)
|
||||
_ = answerPageAction(g, id, `{"declined":true}`)
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
res, err := g.RequestPageAction(context.Background(), pageActionRequest(bus))
|
||||
require.NoError(t, err)
|
||||
require.True(t, res.Answered)
|
||||
assert.True(t, res.Response.Declined)
|
||||
assert.Empty(t, res.Response.Snapshot)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/agent/hitl"
|
||||
"academy/internal/agent/policy"
|
||||
"academy/internal/config"
|
||||
"academy/internal/event"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// memGrants is an in-memory GrantStore keyed like the agent_grants table.
|
||||
type memGrants struct {
|
||||
mu sync.Mutex
|
||||
grants map[string]*types.AgentGrant
|
||||
}
|
||||
|
||||
func newMemGrants() *memGrants { return &memGrants{grants: map[string]*types.AgentGrant{}} }
|
||||
|
||||
func memGrantKey(tenantID uint64, userID string, scope types.GrantScope, key string) string {
|
||||
return fmt.Sprint(tenantID, "|", userID, "|", scope.Scope, "|", scope.ScopeID, "|", key)
|
||||
}
|
||||
|
||||
func (m *memGrants) FindGrant(
|
||||
_ context.Context, tenantID uint64, userID string, scope types.GrantScope, key string,
|
||||
) (*types.AgentGrant, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if g, ok := m.grants[memGrantKey(tenantID, userID, scope, key)]; ok {
|
||||
copied := *g
|
||||
return &copied, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (m *memGrants) SaveGrant(_ context.Context, g *types.AgentGrant) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
copied := *g
|
||||
copied.ID = memGrantKey(g.TenantID, g.UserID, types.GrantScope{Scope: g.Scope, ScopeID: g.ScopeID}, g.GrantKey)
|
||||
copied.CreatedAt = time.Now()
|
||||
m.grants[copied.ID] = &copied
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memGrants) TouchGrant(_ context.Context, id string, at time.Time) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if g, ok := m.grants[id]; ok {
|
||||
g.LastUsedAt = &at
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *memGrants) revokeAll() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
now := time.Now()
|
||||
for _, g := range m.grants {
|
||||
g.RevokedAt = &now
|
||||
}
|
||||
}
|
||||
|
||||
// grantGate answers every approval it raises with answer and counts them.
|
||||
func grantGate(t *testing.T, answer Decision) (*Gate, *event.EventBus, *[]event.ToolApprovalRequiredData) {
|
||||
t.Helper()
|
||||
g := NewGate(&config.Config{Agent: &config.AgentConfig{ToolApprovalTimeoutSeconds: 2}}, nil, nil).
|
||||
WithGrants(newMemGrants())
|
||||
bus := event.NewEventBus()
|
||||
var raised []event.ToolApprovalRequiredData
|
||||
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
|
||||
data := evt.Data.(event.ToolApprovalRequiredData)
|
||||
raised = append(raised, data)
|
||||
go func() {
|
||||
_ = g.Resolve(context.Background(), ResolveRequest{
|
||||
TenantID: data.TenantID, UserID: "u1", PendingID: data.PendingID, Decision: answer,
|
||||
})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
return g, bus, &raised
|
||||
}
|
||||
|
||||
func grantRequest(bus *event.EventBus, session, grant string) PendingRequest {
|
||||
return PendingRequest{
|
||||
TenantID: 7, UserID: "u1", SessionID: session, EventBus: bus,
|
||||
ServiceName: "Academy", MCPToolName: "knowledge.update", RegisteredToolName: "run_operation",
|
||||
Args: json.RawMessage(`{}`), Grant: grant, GrantScope: "Update a document",
|
||||
}
|
||||
}
|
||||
|
||||
func approveAndRun(t *testing.T, g *Gate, req PendingRequest) Decision {
|
||||
t.Helper()
|
||||
d, err := g.RequestBuiltinApproval(attended(), req)
|
||||
require.NoError(t, err)
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
return d
|
||||
}
|
||||
|
||||
func TestSessionGrantSkipsLaterApprovalsOfTheSameKind(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true})
|
||||
grant := "knowledge.update knowledge_base:kb1"
|
||||
|
||||
first := approveAndRun(t, g, grantRequest(bus, "s1", grant))
|
||||
require.True(t, first.Approved)
|
||||
assert.False(t, first.Granted)
|
||||
assert.True(t, first.AllowInSession)
|
||||
require.Len(t, *raised, 1)
|
||||
assert.Equal(t, "Update a document", (*raised)[0].GrantScope, "the card offers the grant")
|
||||
|
||||
second := approveAndRun(t, g, grantRequest(bus, "s1", grant))
|
||||
assert.True(t, second.Approved)
|
||||
assert.True(t, second.Granted)
|
||||
assert.Empty(t, second.PendingID)
|
||||
assert.Len(t, *raised, 1, "an allowed kind of call does not ask again")
|
||||
|
||||
approveAndRun(t, g, grantRequest(bus, "s1", "knowledge.update knowledge_base:kb2"))
|
||||
approveAndRun(t, g, grantRequest(bus, "s2", grant))
|
||||
other := grantRequest(bus, "s1", grant)
|
||||
other.UserID = "u2"
|
||||
ctx, cancel := context.WithTimeout(attended(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
d, _ := g.RequestBuiltinApproval(ctx, other)
|
||||
assert.False(t, d.Approved, "u2's prompt is answered by nobody here")
|
||||
assert.Len(t, *raised, 4, "another knowledge base, session or user asks again")
|
||||
}
|
||||
|
||||
func TestApprovalWithoutSessionGrantAsksAgain(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true})
|
||||
grant := "knowledge.update knowledge_base:kb1"
|
||||
approveAndRun(t, g, grantRequest(bus, "s1", grant))
|
||||
d := approveAndRun(t, g, grantRequest(bus, "s1", grant))
|
||||
assert.False(t, d.Granted)
|
||||
assert.Len(t, *raised, 2)
|
||||
}
|
||||
|
||||
func TestRequestWithoutGrantCannotBeAllowedForTheSession(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true})
|
||||
ctx, cancel := context.WithTimeout(attended(), 300*time.Millisecond)
|
||||
defer cancel()
|
||||
d, err := g.RequestBuiltinApproval(ctx, grantRequest(bus, "s1", ""))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, d.Approved, "allowing what the card did not offer is refused, so the prompt stays open")
|
||||
require.Len(t, *raised, 1)
|
||||
assert.Empty(t, (*raised)[0].GrantScope, "no grant is offered")
|
||||
}
|
||||
|
||||
func TestAllowInSessionNeedsApprovalAndAnOfferedGrant(t *testing.T) {
|
||||
offered, _ := json.Marshal(types.ToolApprovalPromptRequest{Grant: "g", GrantScope: "scope"})
|
||||
notOffered, _ := json.Marshal(types.ToolApprovalPromptRequest{})
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
request []byte
|
||||
response string
|
||||
ok bool
|
||||
}{
|
||||
{"approve and allow", offered, `{"approved":true,"allow_in_session":true}`, true},
|
||||
{"plain approve", notOffered, `{"approved":true}`, true},
|
||||
{"reject and allow", offered, `{"approved":false,"allow_in_session":true}`, false},
|
||||
{"allow what was not offered", notOffered, `{"approved":true,"allow_in_session":true}`, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := validateToolApprovalResponse(tc.request, json.RawMessage(tc.response))
|
||||
if tc.ok {
|
||||
assert.NoError(t, err)
|
||||
} else {
|
||||
assert.Error(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectingDropsAllowInSession(t *testing.T) {
|
||||
g := NewGate(nil, nil, hitl.NewBroker(nil, nil))
|
||||
bus := event.NewEventBus()
|
||||
var pending string
|
||||
bus.On(event.EventToolApprovalRequired, func(_ context.Context, evt event.Event) error {
|
||||
pending = evt.Data.(event.ToolApprovalRequiredData).PendingID
|
||||
go func() {
|
||||
_ = g.Resolve(context.Background(), ResolveRequest{
|
||||
TenantID: 7, UserID: "u1", PendingID: pending,
|
||||
Decision: Decision{Approved: false, AllowInSession: true},
|
||||
})
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
d, err := g.RequestBuiltinApproval(attended(), grantRequest(bus, "s1", "g"))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, d.Approved)
|
||||
assert.False(t, d.AllowInSession)
|
||||
}
|
||||
|
||||
func TestGrantsBelongToTheRunScope(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true})
|
||||
grant := "mcp:svc/write#abc"
|
||||
root := types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: "root"}
|
||||
child := func() context.Context { return types.WithGrantScope(attended(), root) }
|
||||
|
||||
d, err := g.RequestBuiltinApproval(child(), grantRequest(bus, "child-1", grant))
|
||||
require.NoError(t, err)
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
require.Len(t, *raised, 1)
|
||||
|
||||
d, err = g.RequestBuiltinApproval(child(), grantRequest(bus, "child-2", grant))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, d.Granted, "a sibling child shares the root conversation's grant")
|
||||
d = approveAndRun(t, g, grantRequest(bus, "root", grant))
|
||||
assert.True(t, d.Granted, "so does the root conversation")
|
||||
assert.Len(t, *raised, 1)
|
||||
}
|
||||
|
||||
func TestRevokedOrRebindedGrantAsksAgain(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true})
|
||||
store := g.grants.(*memGrants)
|
||||
grant := "mcp:svc/write#abc"
|
||||
bound := func(binding string) context.Context {
|
||||
return types.WithGrantScope(attended(), types.GrantScope{
|
||||
Scope: types.AgentGrantScopeAutomation, ScopeID: "auto-1", BindingHash: binding,
|
||||
})
|
||||
}
|
||||
run := func(ctx context.Context) Decision {
|
||||
d, err := g.RequestBuiltinApproval(ctx, grantRequest(bus, "s", grant))
|
||||
require.NoError(t, err)
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
return d
|
||||
}
|
||||
run(bound("v1"))
|
||||
assert.True(t, run(bound("v1")).Granted)
|
||||
assert.False(t, run(bound("v2")).Granted, "a changed automation asks again")
|
||||
require.Len(t, *raised, 2)
|
||||
assert.Equal(t, types.AgentGrantLapseChanged, (*raised)[1].GrantLapsed, "the card says why it asks again")
|
||||
|
||||
store.revokeAll()
|
||||
assert.False(t, run(bound("v2")).Granted, "a revoked grant asks again")
|
||||
require.Len(t, *raised, 3)
|
||||
assert.Empty(t, (*raised)[2].GrantLapsed, "the user withdrew it, so nothing to explain")
|
||||
}
|
||||
|
||||
func TestStandingGrantsCoverOnlyWhatTheyWereApprovedFor(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true})
|
||||
store := g.grants.(*memGrants)
|
||||
standing := types.GrantScope{Scope: types.AgentGrantScopeAutomation, ScopeID: "auto-1", BindingHash: "v1"}
|
||||
runCtx := func() context.Context {
|
||||
ctx := types.WithGrantScope(attended(), types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: "run-1"})
|
||||
return types.WithStandingGrantScope(ctx, standing)
|
||||
}
|
||||
require.NoError(t, store.SaveGrant(context.Background(), &types.AgentGrant{
|
||||
TenantID: 7, UserID: "u1", Scope: standing.Scope, ScopeID: standing.ScopeID, BindingHash: "v1",
|
||||
GrantKey: "knowledge.delete knowledge_base:kb1", Risk: string(policy.RiskDestructive),
|
||||
}))
|
||||
require.NoError(t, store.SaveGrant(context.Background(), &types.AgentGrant{
|
||||
TenantID: 7, UserID: "u1", Scope: standing.Scope, ScopeID: standing.ScopeID, BindingHash: "v1",
|
||||
GrantKey: "mcp:svc/purge#abc", Risk: string(policy.RiskWrite),
|
||||
}))
|
||||
ask := func(grant string, risk policy.Risk) Decision {
|
||||
req := grantRequest(bus, "run-1", grant)
|
||||
req.GrantRisk = risk
|
||||
d, err := g.RequestBuiltinApproval(runCtx(), req)
|
||||
require.NoError(t, err)
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
return d
|
||||
}
|
||||
|
||||
assert.True(t, ask("knowledge.delete knowledge_base:kb1", policy.RiskDestructive).Granted,
|
||||
"a destructive call pre-approved for this knowledge base runs")
|
||||
assert.Empty(t, *raised)
|
||||
|
||||
assert.False(t, ask("knowledge.delete knowledge_base:kb2", policy.RiskDestructive).Granted,
|
||||
"another knowledge base asks")
|
||||
require.Len(t, *raised, 1)
|
||||
assert.Empty(t, (*raised)[0].GrantScope, "a destructive call is never offered for the rest of the run")
|
||||
|
||||
assert.False(t, ask("mcp:svc/purge#abc", policy.RiskDestructive).Granted,
|
||||
"a grant approved for a write does not cover the tool once it is destructive")
|
||||
assert.Len(t, *raised, 2)
|
||||
}
|
||||
|
||||
func TestApprovalsDuringAnAutomationRunStayInTheRun(t *testing.T) {
|
||||
g, bus, raised := grantGate(t, Decision{Approved: true, AllowInSession: true})
|
||||
standing := types.GrantScope{Scope: types.AgentGrantScopeAutomation, ScopeID: "auto-1"}
|
||||
run := func(session string) Decision {
|
||||
ctx := types.WithGrantScope(attended(), types.GrantScope{Scope: types.AgentGrantScopeSession, ScopeID: session})
|
||||
ctx = types.WithStandingGrantScope(ctx, standing)
|
||||
d, err := g.RequestBuiltinApproval(ctx, grantRequest(bus, session, "mcp:svc/write#abc"))
|
||||
require.NoError(t, err)
|
||||
g.MarkExecuted(context.Background(), d.PendingID)
|
||||
return d
|
||||
}
|
||||
run("run-1")
|
||||
assert.True(t, run("run-1").Granted, "the run remembers its own approval")
|
||||
assert.False(t, run("run-2").Granted, "the next run does not inherit it")
|
||||
assert.Len(t, *raised, 2)
|
||||
found, err := g.grants.FindGrant(context.Background(), 7, "u1", standing, "mcp:svc/write#abc")
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, found, "nothing approved during a run becomes a standing grant")
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
type enabledChecker interface {
|
||||
IsEnabled(context.Context, uint64, string, string) (bool, error)
|
||||
}
|
||||
|
||||
// BulkEnabledChecker avoids a query per tool when enumerating a directory.
|
||||
// Implementations return an explicit decision for each requested name.
|
||||
type BulkEnabledChecker interface {
|
||||
EnabledTools(context.Context, uint64, string, []string) (map[string]bool, error)
|
||||
}
|
||||
|
||||
// EnabledTools uses batch policies where available while retaining compatibility
|
||||
// with custom gates implementing only the original single-tool contract.
|
||||
func EnabledTools(
|
||||
ctx context.Context,
|
||||
checker enabledChecker,
|
||||
tenantID uint64,
|
||||
serviceID string,
|
||||
names []string,
|
||||
) (map[string]bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tenantID == 0 || serviceID == "" {
|
||||
return nil, fmt.Errorf("MCP policy identity is required")
|
||||
}
|
||||
if bulk, ok := checker.(BulkEnabledChecker); ok {
|
||||
return bulk.EnabledTools(ctx, tenantID, serviceID, names)
|
||||
}
|
||||
return enabledToolsIndividually(ctx, checker, tenantID, serviceID, names)
|
||||
}
|
||||
|
||||
func enabledToolsIndividually(
|
||||
ctx context.Context,
|
||||
checker enabledChecker,
|
||||
tenantID uint64,
|
||||
serviceID string,
|
||||
names []string,
|
||||
) (map[string]bool, error) {
|
||||
result := make(map[string]bool, len(names))
|
||||
for _, name := range names {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enabled := true
|
||||
if checker != nil {
|
||||
var err error
|
||||
enabled, err = checker.IsEnabled(ctx, tenantID, serviceID, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
result[name] = enabled
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// EnabledTools delegates directory policy checks to the configured checker.
|
||||
func (g *Gate) EnabledTools(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
serviceID string,
|
||||
names []string,
|
||||
) (map[string]bool, error) {
|
||||
if g == nil {
|
||||
return EnabledTools(ctx, nil, tenantID, serviceID, names)
|
||||
}
|
||||
return EnabledTools(ctx, g.checker, tenantID, serviceID, names)
|
||||
}
|
||||
|
||||
// EnabledTools reads service policies in one batch when supported by the service.
|
||||
func (a *Adapter) EnabledTools(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
serviceID string,
|
||||
names []string,
|
||||
) (map[string]bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tenantID == 0 || serviceID == "" {
|
||||
return nil, fmt.Errorf("MCP policy identity is required")
|
||||
}
|
||||
if a == nil || a.Svc == nil {
|
||||
return enabledToolsIndividually(ctx, nil, tenantID, serviceID, names)
|
||||
}
|
||||
lister, ok := a.Svc.(interface {
|
||||
ListByService(context.Context, uint64, string) ([]*types.MCPToolApproval, error)
|
||||
})
|
||||
if !ok {
|
||||
return enabledToolsIndividually(ctx, a, tenantID, serviceID, names)
|
||||
}
|
||||
rows, err := lister.ListByService(ctx, tenantID, serviceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := enabledToolsIndividually(ctx, nil, tenantID, serviceID, names)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row == nil || row.TenantID != tenantID || row.ServiceID != serviceID {
|
||||
continue
|
||||
}
|
||||
if _, requested := result[row.ToolName]; requested {
|
||||
result[row.ToolName] = row.Enabled
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package approval
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type batchPolicyService struct {
|
||||
stubChecker
|
||||
rows []*types.MCPToolApproval
|
||||
listErr error
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *batchPolicyService) ListByService(context.Context, uint64, string) ([]*types.MCPToolApproval, error) {
|
||||
s.reads++
|
||||
return s.rows, s.listErr
|
||||
}
|
||||
|
||||
func TestGateBatchPolicyScopesDefaultsAndFailures(t *testing.T) {
|
||||
svc := &batchPolicyService{rows: []*types.MCPToolApproval{
|
||||
{TenantID: 7, ServiceID: "svc", ToolName: "disabled", Enabled: false},
|
||||
{TenantID: 8, ServiceID: "svc", ToolName: "default", Enabled: false},
|
||||
{TenantID: 7, ServiceID: "other", ToolName: "default", Enabled: false},
|
||||
{TenantID: 7, ServiceID: "svc", ToolName: "not-requested", Enabled: true},
|
||||
}}
|
||||
gate := NewGate(nil, &Adapter{Svc: svc}, nil)
|
||||
ctx := context.Background()
|
||||
result, err := EnabledTools(ctx, gate, 7, "svc", []string{"default", "disabled"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]bool{"default": true, "disabled": false}, result)
|
||||
require.Equal(t, 1, svc.reads)
|
||||
_, err = gate.EnabledTools(ctx, 0, "svc", []string{"default"})
|
||||
require.Error(t, err)
|
||||
require.Equal(t, 1, svc.reads)
|
||||
canceled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
_, err = gate.EnabledTools(canceled, 7, "svc", []string{"default"})
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
require.Equal(t, 1, svc.reads)
|
||||
svc.listErr = errors.New("database unavailable")
|
||||
result, err = gate.EnabledTools(ctx, 7, "svc", []string{"default"})
|
||||
require.ErrorIs(t, err, svc.listErr)
|
||||
require.Nil(t, result)
|
||||
}
|
||||
|
||||
func TestGateBatchPolicyLegacyCheckerAndNoChecker(t *testing.T) {
|
||||
disabled := false
|
||||
gate := NewGate(nil, &Adapter{Svc: &stubChecker{enabled: &disabled}}, nil)
|
||||
result, err := gate.EnabledTools(context.Background(), 7, "svc", []string{"a", "b"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]bool{"a": false, "b": false}, result)
|
||||
result, err = NewGate(nil, nil, nil).EnabledTools(context.Background(), 7, "svc", []string{"a", "b"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, map[string]bool{"a": true, "b": true}, result)
|
||||
}
|
||||
Reference in new issue
Block a user