Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.26.2
require (
github.com/coder/websocket v1.8.14
github.com/creack/pty v1.1.24
github.com/gsd-build/protocol-go v0.33.0
github.com/gsd-build/protocol-go v0.34.0
github.com/spf13/cobra v1.10.2
gopkg.in/natefinch/lumberjack.v2 v2.2.1
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6p
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/gsd-build/protocol-go v0.33.0 h1:/UBKhB5bcW7QVvGNDH0h7KZIaVVqvE9/OtYi0uH4RrI=
github.com/gsd-build/protocol-go v0.33.0/go.mod h1:vECSwMFp59Ihu5ZH4aLF5fuW9zJ4a3ZXCYngmzfBn8s=
github.com/gsd-build/protocol-go v0.34.0 h1:Au69NlKq4NULgmUvleNod+PUVa1AVy9HjGyO5o+7TMI=
github.com/gsd-build/protocol-go v0.34.0/go.mod h1:vECSwMFp59Ihu5ZH4aLF5fuW9zJ4a3ZXCYngmzfBn8s=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand Down
187 changes: 162 additions & 25 deletions internal/browser/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package browser

import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
Expand Down Expand Up @@ -58,9 +59,49 @@ type Grant struct {
GrantID string
BrowserID string
SessionID string
ChannelID string
TaskID string
}

func (m *Manager) Ensure(ctx context.Context, req EnsureRequest) (Grant, error) {
if grant, ok := m.GrantForTask(req.TaskID); ok {
return grant, nil
}
if grant, ok := m.GrantForSession(req.SessionID); ok {
return grant, nil
}
if req.GrantID == "" {
return Grant{}, fmt.Errorf("browser grant missing")
}
if req.SessionID == "" {
return Grant{}, fmt.Errorf("browser session missing")
}
if req.ExpiresAt == "" {
return Grant{}, fmt.Errorf("browser grant expiry missing")
}
if err := m.Open(ctx, &protocol.BrowserSessionOpen{
Type: protocol.MsgTypeBrowserSessionOpen,
RequestID: fmt.Sprintf("browser_lazy_%d", time.Now().UnixNano()),
GrantID: req.GrantID,
SessionID: req.SessionID,
ProjectID: req.ProjectID,
TaskID: req.TaskID,
ChannelID: req.ChannelID,
MachineID: req.MachineID,
Mode: "clean",
ExpiresAt: req.ExpiresAt,
}); err != nil {
return Grant{}, err
}
if grant, ok := m.GrantForTask(req.TaskID); ok {
return grant, nil
}
if grant, ok := m.GrantForSession(req.SessionID); ok {
return grant, nil
}
return Grant{}, fmt.Errorf("browser grant unavailable after open")
}

func (m *Manager) Open(ctx context.Context, msg *protocol.BrowserSessionOpen) error {
expiresAt, err := time.Parse(time.RFC3339Nano, msg.ExpiresAt)
if err != nil {
Expand Down Expand Up @@ -278,6 +319,7 @@ func (m *Manager) grantForStateLocked(state *sessionState) (Grant, bool) {
GrantID: state.openRequest.GrantID,
BrowserID: state.browserID,
SessionID: state.openRequest.SessionID,
ChannelID: state.openRequest.ChannelID,
TaskID: state.openRequest.TaskID,
}, true
}
Expand Down Expand Up @@ -463,36 +505,41 @@ func (m *Manager) removeStateLocked(state *sessionState) {
}

func (m *Manager) Tool(ctx context.Context, msg *protocol.BrowserToolCall) error {
_, err := m.ToolResult(ctx, msg)
return err
}

func (m *Manager) ToolResult(ctx context.Context, msg *protocol.BrowserToolCall) (ToolResult, error) {
m.mu.Lock()
state, ok := m.byID[msg.BrowserID]
if !ok {
m.mu.Unlock()
return fmt.Errorf("browser session not found")
return ToolResult{}, fmt.Errorf("browser session not found")
}
if time.Now().After(state.expiresAt) {
m.mu.Unlock()
return fmt.Errorf("browser grant expired")
return ToolResult{}, fmt.Errorf("browser grant expired")
}
if state.owner != OwnerAgent {
m.mu.Unlock()
return fmt.Errorf("browser control belongs to %s", state.owner)
return ToolResult{}, fmt.Errorf("browser control belongs to %s", state.owner)
}
req := state.openRequest
risk := classifyBrowserTool(msg.Method, msg.ParamsJSON)
if msg.Method == "vault_save" {
summary := browserToolSummary(msg.Method, risk)
if isCredentialBrowserTool(msg.Method, risk) {
m.mu.Unlock()
if err := m.sender.Send(ctx, &protocol.BrowserToolResult{
Type: protocol.MsgTypeBrowserToolResult,
BrowserID: msg.BrowserID,
GrantID: msg.GrantID,
TaskID: msg.TaskID,
ToolUseID: msg.ToolUseID,
_ = m.sendToolStarted(ctx, msg, req, risk, summary)
_ = m.sendToolUpdated(ctx, msg, req, "rejected", summary, nil)
result := ToolResult{
OK: false,
Error: "agent-initiated vault_save is not allowed",
}); err != nil {
return fmt.Errorf("send browser vault_save rejection: %w", err)
Error: "browser credential methods are not available to agents",
ErrorCode: "feature_not_enabled",
}
if err := m.sendToolResult(ctx, msg, req, result); err != nil {
return result, fmt.Errorf("send browser credential method rejection: %w", err)
}
return fmt.Errorf("agent-initiated vault_save is not allowed")
return result, fmt.Errorf("browser credential methods are not available to agents")
}
if browserRiskRequiresApproval(risk) {
previousOwner := state.owner
Expand All @@ -501,6 +548,8 @@ func (m *Manager) Tool(ctx context.Context, msg *protocol.BrowserToolCall) error
state.controlVersion++
nextVersion := state.controlVersion
m.mu.Unlock()
_ = m.sendToolStarted(ctx, msg, req, risk, summary)
_ = m.sendToolUpdated(ctx, msg, req, "approval_required", summary, nil)
requestID := fmt.Sprintf("browser_sensitive_%d", time.Now().UnixNano())
if err := m.sender.Send(ctx, &protocol.BrowserSensitiveActionRequest{
Type: protocol.MsgTypeBrowserSensitiveActionRequest,
Expand All @@ -522,27 +571,115 @@ func (m *Manager) Tool(ctx context.Context, msg *protocol.BrowserToolCall) error
current.controlVersion = previousVersion
}
m.mu.Unlock()
return fmt.Errorf("send browser sensitive action request: %w", err)
return ToolResult{}, fmt.Errorf("send browser sensitive action request: %w", err)
}
return fmt.Errorf("browser action requires approval: %s", risk)
return ToolResult{OK: false, Error: "browser action requires approval", ErrorCode: "approval_required"}, fmt.Errorf("browser action requires approval: %s", risk)
}
m.mu.Unlock()
if err := m.sendToolStarted(ctx, msg, req, risk, summary); err != nil {
return ToolResult{}, err
}
result, err := m.service.Tool(ctx, msg.BrowserID, msg.Method, msg.ParamsJSON)
if err != nil {
return err
result = ToolResult{OK: false, Error: err.Error(), ErrorCode: "browser_tool_failed"}
_ = m.sendToolUpdated(ctx, msg, req, "error", summary, nil)
_ = m.sendToolResult(ctx, msg, req, result)
return result, err
}
status := "ok"
if !result.OK {
status = "error"
}
if err := m.sendToolUpdated(ctx, msg, req, status, summary, result.ResultJSON); err != nil {
return result, err
}
return result, m.sendToolResult(ctx, msg, req, result)
}

func (m *Manager) sendToolStarted(ctx context.Context, msg *protocol.BrowserToolCall, req OpenRequest, risk BrowserRisk, summary string) error {
return m.sender.Send(ctx, &protocol.BrowserToolCallStarted{
Type: protocol.MsgTypeBrowserToolCallStarted,
BrowserID: msg.BrowserID,
GrantID: msg.GrantID,
SessionID: req.SessionID,
ChannelID: req.ChannelID,
TaskID: msg.TaskID,
ToolUseID: msg.ToolUseID,
Method: msg.Method,
Category: string(risk),
Summary: summary,
Metadata: safeToolMetadata(msg.Method, msg.ParamsJSON),
At: time.Now().UTC().Format(time.RFC3339Nano),
})
}

func (m *Manager) sendToolUpdated(ctx context.Context, msg *protocol.BrowserToolCall, req OpenRequest, status string, summary string, metadata json.RawMessage) error {
return m.sender.Send(ctx, &protocol.BrowserToolCallUpdated{
Type: protocol.MsgTypeBrowserToolCallUpdated,
BrowserID: msg.BrowserID,
GrantID: msg.GrantID,
SessionID: req.SessionID,
ChannelID: req.ChannelID,
TaskID: msg.TaskID,
ToolUseID: msg.ToolUseID,
Status: status,
Summary: summary,
Metadata: metadata,
At: time.Now().UTC().Format(time.RFC3339Nano),
})
}

func (m *Manager) sendToolResult(ctx context.Context, msg *protocol.BrowserToolCall, req OpenRequest, result ToolResult) error {
return m.sender.Send(ctx, &protocol.BrowserToolResult{
Type: protocol.MsgTypeBrowserToolResult,
BrowserID: msg.BrowserID,
GrantID: msg.GrantID,
TaskID: msg.TaskID,
ToolUseID: msg.ToolUseID,
OK: result.OK,
ResultJSON: result.ResultJSON,
Error: result.Error,
Type: protocol.MsgTypeBrowserToolResult,
BrowserID: msg.BrowserID,
GrantID: msg.GrantID,
SessionID: req.SessionID,
ChannelID: req.ChannelID,
TaskID: msg.TaskID,
ToolUseID: msg.ToolUseID,
OK: result.OK,
ResultJSON: result.ResultJSON,
Error: result.Error,
ErrorCode: result.ErrorCode,
Sensitivity: "public",
RedactionStatus: "not_needed",
})
}

func browserApprovalSummary(method string, risk BrowserRisk) string {
return fmt.Sprintf("Run browser method %s (%s)", method, risk)
}

func browserToolSummary(method string, risk BrowserRisk) string {
return fmt.Sprintf("Run browser method %s (%s)", method, risk)
}

func isCredentialBrowserTool(method string, risk BrowserRisk) bool {
if risk == BrowserRiskCredentialAuth {
return true
}
switch method {
case "save_state", "restore_state", "vault_save", "vault_login", "vault_list":
return true
default:
return false
}
}

func safeToolMetadata(method string, params json.RawMessage) json.RawMessage {
if method != "navigate" || len(params) == 0 {
return nil
}
var payload struct {
URL string `json:"url"`
}
if err := json.Unmarshal(params, &payload); err != nil || payload.URL == "" {
return nil
}
data, err := json.Marshal(map[string]string{"url": payload.URL})
if err != nil {
return nil
}
return data
}
84 changes: 82 additions & 2 deletions internal/browser/manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ func TestManagerBlocksSensitiveToolUntilApproval(t *testing.T) {
GrantID: "grant_1",
TaskID: "task_1",
ToolUseID: "tool_1",
Method: "vault_login",
Method: "fill_form",
})

if err == nil {
Expand All @@ -283,6 +283,86 @@ func TestManagerBlocksSensitiveToolUntilApproval(t *testing.T) {
}
}

func TestManagerSendsToolLifecycleEventsAndResultContext(t *testing.T) {
service := &fakeService{}
sender := &recordingSender{}
m := NewManager(ManagerOptions{Service: service, Sender: sender, FrameInterval: time.Hour})
openBrowserForTest(t, m, "browser_1")

err := m.Tool(context.Background(), &protocol.BrowserToolCall{
Type: protocol.MsgTypeBrowserToolCall,
BrowserID: "browser_1",
GrantID: "grant_1",
TaskID: "task_1",
ToolUseID: "tool_1",
Method: "navigate",
ParamsJSON: json.RawMessage(`{"url":"https://example.com"}`),
})
if err != nil {
t.Fatalf("tool: %v", err)
}

var started *protocol.BrowserToolCallStarted
var updated *protocol.BrowserToolCallUpdated
var result *protocol.BrowserToolResult
for _, msg := range sender.snapshot() {
switch typed := msg.(type) {
case *protocol.BrowserToolCallStarted:
started = typed
case *protocol.BrowserToolCallUpdated:
updated = typed
case *protocol.BrowserToolResult:
result = typed
}
}
if started == nil || started.SessionID != "session_1" || started.ChannelID != "channel_1" || started.Category != string(BrowserRiskInspection) {
t.Fatalf("started = %+v", started)
}
if updated == nil || updated.Status != "ok" || updated.SessionID != "session_1" || updated.ChannelID != "channel_1" {
t.Fatalf("updated = %+v", updated)
}
if result == nil || !result.OK || result.SessionID != "session_1" || result.ChannelID != "channel_1" || result.RedactionStatus != "not_needed" {
t.Fatalf("result = %+v", result)
}
}

func TestManagerRejectsCredentialMethodsWithoutApproval(t *testing.T) {
service := &fakeService{}
sender := &recordingSender{}
m := NewManager(ManagerOptions{Service: service, Sender: sender, FrameInterval: time.Hour})
openBrowserForTest(t, m, "browser_1")

err := m.Tool(context.Background(), &protocol.BrowserToolCall{
Type: protocol.MsgTypeBrowserToolCall,
BrowserID: "browser_1",
GrantID: "grant_1",
TaskID: "task_1",
ToolUseID: "tool_1",
Method: "vault_login",
})
if err == nil {
t.Fatal("expected credential method rejection")
}
if sender.hasType(protocol.MsgTypeBrowserSensitiveActionRequest) {
t.Fatalf("credential method should not request approval")
}
var result *protocol.BrowserToolResult
for _, msg := range sender.snapshot() {
if typed, ok := msg.(*protocol.BrowserToolResult); ok {
result = typed
}
}
if result == nil || result.OK || result.ErrorCode != "feature_not_enabled" {
t.Fatalf("result = %+v", result)
}
service.mu.Lock()
toolCalls := service.toolCalls
service.mu.Unlock()
if toolCalls != 0 {
t.Fatalf("credential method reached service")
}
}

func TestManagerRollsBackApprovalOwnerWhenRequestSendFails(t *testing.T) {
service := &fakeService{}
m := NewManager(ManagerOptions{Service: service, Sender: &recordingSender{}, FrameInterval: time.Hour})
Expand All @@ -295,7 +375,7 @@ func TestManagerRollsBackApprovalOwnerWhenRequestSendFails(t *testing.T) {
GrantID: "grant_1",
TaskID: "task_1",
ToolUseID: "tool_1",
Method: "vault_login",
Method: "fill_form",
})

if err == nil {
Expand Down
Loading