fix: harden runtime against panics/races, close path-traversal and fail-open gaps

- Runtime.Run rejects concurrent invocations instead of racing on shared state; panics in tools, hooks, and permission checkers are recovered and surfaced as errors/denials instead of crashing the loop
- AgentSpec.Loop now actually overrides RuntimeDeps.AgentLoop per-agent, as documented
- session.Store validates agent ID / session key as single path components, preventing traversal outside the session directory
- ValidatePathInWorkDir resolves symlinks on the target itself, not just its parent, closing a workspace-escape gap
- bash tool now fails closed on an unrecognized ExecPolicy.Level instead of allowing everything
- browser tool rejects unknown actions instead of silently no-op'ing

Bump README to v0.3.4 and document the AgentSpec.Loop override semantics.
This commit is contained in:
sausheong committed 2026-08-02 10:14:20 +08:00
1 parent 445614757b
commit eb4fa67976
15 files changed
+421 -37

No files matched your search

+1
View File
@@ -4,6 +4,7 @@
!/developer.md !/developer.md
!/examples/*/kb/ !/examples/*/kb/
!/examples/*/kb/*.md !/examples/*/kb/*.md
/docs/
# Other prose/document formats # Other prose/document formats
*.txt *.txt
+6 -3
View File
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
token budgeting needed to run a multi-provider agent in production. BYO token budgeting needed to run a multi-provider agent in production. BYO
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins. concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
> **Status: v0.1.0.** First tagged release. The `runtime` API > **Status: v0.3.4.** Latest tagged release. The `runtime` API
> surface may still shift in the v0.x line — pin your version. > surface may still shift in the v0.x line — pin your version.
## Why Harness ## Why Harness
@@ -229,6 +229,9 @@ them via `LoopConfig`:
`LoopConfig` field values win over env vars when set. Set the field `LoopConfig` field values win over env vars when set. Set the field
to its zero value (or omit it) to fall back to env, then to defaults. to its zero value (or omit it) to fall back to env, then to defaults.
`RuntimeDeps.AgentLoop` supplies shared process defaults;
non-zero fields and non-nil hooks in `AgentSpec.Loop` override those
defaults for that agent.
Everything else (provider API keys, model selection, workspace path, Everything else (provider API keys, model selection, workspace path,
skill paths, etc.) is your config's responsibility — harness reads skill paths, etc.) is your config's responsibility — harness reads
@@ -373,12 +376,12 @@ a real failure.
## Status ## Status
`v0.1.0` is the first tagged release. The v0.x line follows Go `v0.3.4` is the latest tagged release. The v0.x line follows Go
module semver: minor bumps may break API, patch bumps are bug-fix module semver: minor bumps may break API, patch bumps are bug-fix
only. Pin your dependency: only. Pin your dependency:
```bash ```bash
go get github.com/sausheong/harness@v0.1.0 go get github.com/sausheong/harness@v0.3.4
``` ```
Likely sources of v0.x churn before a v1.0.0: Likely sources of v0.x churn before a v1.0.0:
+39 -1
View File
@@ -166,6 +166,8 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
} }
} }
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
rt := &Runtime{ rt := &Runtime{
LLM: inputs.Provider, LLM: inputs.Provider,
Tools: inputs.Tools, Tools: inputs.Tools,
@@ -186,7 +188,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
Permission: deps.Permission, Permission: deps.Permission,
Compaction: inputs.Compaction, Compaction: inputs.Compaction,
IngestSource: inputs.IngestSource, IngestSource: inputs.IngestSource,
AgentLoop: deps.AgentLoop, AgentLoop: loop,
StaticSystemPrompt: staticPrompt, StaticSystemPrompt: staticPrompt,
CalibratorStore: deps.CalibratorStore, CalibratorStore: deps.CalibratorStore,
mcpClients: mcpClients, mcpClients: mcpClients,
@@ -206,3 +208,39 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
return rt, nil return rt, nil
} }
// mergeLoopConfig applies the per-agent non-zero settings over the shared
// defaults. LoopConfig intentionally uses zero values as "inherit/default",
// so this preserves existing RuntimeDeps.AgentLoop behavior while making the
// documented AgentSpec.Loop override effective.
func mergeLoopConfig(base, override LoopConfig) LoopConfig {
out := base
if override.MaxToolConcurrency > 0 {
out.MaxToolConcurrency = override.MaxToolConcurrency
}
if override.MaxAgentDepth > 0 {
out.MaxAgentDepth = override.MaxAgentDepth
}
if override.StreamingTools {
out.StreamingTools = true
}
if override.MaxToolResultLen > 0 {
out.MaxToolResultLen = override.MaxToolResultLen
}
if override.Hooks.OnUserPromptSubmit != nil {
out.Hooks.OnUserPromptSubmit = override.Hooks.OnUserPromptSubmit
}
if override.Hooks.OnSessionStart != nil {
out.Hooks.OnSessionStart = override.Hooks.OnSessionStart
}
if override.Hooks.BeforeToolUse != nil {
out.Hooks.BeforeToolUse = override.Hooks.BeforeToolUse
}
if override.Hooks.AfterToolUse != nil {
out.Hooks.AfterToolUse = override.Hooks.AfterToolUse
}
if override.Hooks.OnStop != nil {
out.Hooks.OnStop = override.Hooks.OnStop
}
return out
}
+34
View File
@@ -1,6 +1,7 @@
package runtime package runtime
import ( import (
"context"
"testing" "testing"
"github.com/sausheong/harness/tool" "github.com/sausheong/harness/tool"
@@ -38,6 +39,39 @@ func TestBuildRuntimeMinimalSpecSafe(t *testing.T) {
require.NotEmpty(t, rt.StaticSystemPrompt) require.NotEmpty(t, rt.StaticSystemPrompt)
} }
func TestBuildRuntimeMergesSpecLoopOverSharedDefaults(t *testing.T) {
baseCalled := false
specCalled := false
baseStop := func(context.Context, string) { baseCalled = true }
specStop := func(context.Context, string) { specCalled = true }
rt, err := BuildRuntime(
RuntimeDeps{AgentLoop: LoopConfig{
MaxToolConcurrency: 3,
MaxAgentDepth: 2,
MaxToolResultLen: 8000,
Hooks: LifecycleHooks{OnStop: baseStop},
}},
RuntimeInputs{},
AgentSpec{
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
Loop: LoopConfig{
MaxToolConcurrency: 7,
StreamingTools: true,
Hooks: LifecycleHooks{OnStop: specStop},
},
},
)
require.NoError(t, err)
assert.Equal(t, 7, rt.AgentLoop.MaxToolConcurrency)
assert.Equal(t, 2, rt.AgentLoop.MaxAgentDepth, "zero spec fields inherit shared defaults")
assert.Equal(t, 8000, rt.AgentLoop.MaxToolResultLen)
assert.True(t, rt.AgentLoop.StreamingTools)
require.NotNil(t, rt.AgentLoop.Hooks.OnStop)
rt.AgentLoop.Hooks.OnStop(context.Background(), "completed")
assert.False(t, baseCalled)
assert.True(t, specCalled)
}
func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) { func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
// Caller composes memoryFiles however they want — typical patterns // Caller composes memoryFiles however they want — typical patterns
// include walking AGENTS.md from workspace + $HOME, building from a // include walking AGENTS.md from workspace + $HOME, building from a
+35 -18
View File
@@ -132,6 +132,11 @@ type Runtime struct {
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is // AgentSpec.MCPServers. Released by Close. Untouched when MCP is
// not used. // not used.
mcpClients []*mcp.Client mcpClients []*mcp.Client
// runMu enforces the Runtime contract that one session exchange runs at a
// time. TryLock lets a second caller receive a normal error instead of
// corrupting the shared event channel and run-scoped state.
runMu sync.Mutex
} }
// Close releases external resources owned by the Runtime — currently // Close releases external resources owned by the Runtime — currently
@@ -272,12 +277,17 @@ func isFileTool(name string) bool {
// Run executes the agent loop for a user message, returning a channel of events. // Run executes the agent loop for a user message, returning a channel of events.
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) { func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
r.events = make(chan AgentEvent, 100) if !r.runMu.TryLock() {
return nil, fmt.Errorf("runtime is already running")
}
events := make(chan AgentEvent, 100)
r.events = events
tr := TraceFrom(ctx) tr := TraceFrom(ctx)
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images)) tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
go func() { go func() {
defer close(r.events) defer close(events)
defer r.runMu.Unlock()
defer tr.Summary() defer tr.Summary()
// Flush the per-session calibrator once at Run end (all exit paths: // Flush the per-session calibrator once at Run end (all exit paths:
@@ -298,8 +308,15 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
// right reason without an explicit assignment at that exit. // right reason without an explicit assignment at that exit.
stopReason := "max_turns" stopReason := "max_turns"
if hook := r.AgentLoop.Hooks.OnStop; hook != nil { if hook := r.AgentLoop.Hooks.OnStop; hook != nil {
defer func() { hook(ctx, stopReason) }() defer func() { callOnStopHook(ctx, hook, stopReason) }()
} }
defer func() {
if recovered := recover(); recovered != nil {
stopReason = "error"
err := recoveredPanicError("runtime", recovered)
r.emit(AgentEvent{Type: EventError, Error: err})
}
}()
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the // OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
// session sees them. Returning err aborts Run with EventError. // session sees them. Returning err aborts Run with EventError.
@@ -812,7 +829,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}) })
}() }()
return r.events, nil return events, nil
} }
// recoverFromPreTokenError attempts the same recovery the synchronous // recoverFromPreTokenError attempts the same recovery the synchronous
@@ -895,28 +912,28 @@ func (r *Runtime) dispatchTool(
// BeforeToolUse fires before the PermissionChecker. A hook denial // BeforeToolUse fires before the PermissionChecker. A hook denial
// has the same observable shape as a Permission.Check denial. // has the same observable shape as a Permission.Check denial.
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil { if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
d, err := hook(ctx, tc.Name, tc.Input) d, err := callBeforeToolHook(ctx, hook, tc.Name, tc.Input)
if err != nil { if err != nil {
res := r.appendDenialResult(tc.ID, err.Error(), kgThread) res := r.appendDenialResult(tc.ID, err.Error(), kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res) callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
} }
return res, false return res, false
} }
if !d.Allow { if !d.Allow {
res := r.appendDenialResult(tc.ID, d.Reason, kgThread) res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res) callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
} }
return res, false return res, false
} }
} }
if r.Permission != nil { if r.Permission != nil {
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny { if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
res := r.appendDenialResult(tc.ID, d.Reason, kgThread) res := r.appendDenialResult(tc.ID, d.Reason, kgThread)
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res) callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
} }
return res, false return res, false
} }
@@ -926,7 +943,7 @@ func (r *Runtime) dispatchTool(
return r.appendAbortedResult(tc.ID, kgThread), true return r.appendAbortedResult(tc.ID, kgThread), true
} }
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input) result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil { if err != nil {
result = tool.ToolResult{Error: err.Error()} result = tool.ToolResult{Error: err.Error()}
} }
@@ -952,7 +969,7 @@ func (r *Runtime) dispatchTool(
} }
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil { if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
hook(ctx, tc.Name, tc.Input, result) callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
} }
return result, false return result, false
@@ -963,27 +980,27 @@ func (r *Runtime) dispatchTool(
// streaming kickoff goroutines. // streaming kickoff goroutines.
func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (result tool.ToolResult, aborted bool) { func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (result tool.ToolResult, aborted bool) {
if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil { if hook := r.AgentLoop.Hooks.BeforeToolUse; hook != nil {
d, err := hook(ctx, tc.Name, tc.Input) d, err := callBeforeToolHook(ctx, hook, tc.Name, tc.Input)
if err != nil { if err != nil {
res := tool.ToolResult{Error: err.Error()} res := tool.ToolResult{Error: err.Error()}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res) callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
} }
return res, false return res, false
} }
if !d.Allow { if !d.Allow {
res := tool.ToolResult{Error: d.Reason} res := tool.ToolResult{Error: d.Reason}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res) callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
} }
return res, false return res, false
} }
} }
if r.Permission != nil { if r.Permission != nil {
if d := r.Permission.Check(ctx, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny { if d := callPermissionCheck(ctx, r.Permission, r.AgentID, tc.Name, tc.Input); d.Behavior == tool.DecisionDeny {
res := tool.ToolResult{Error: d.Reason} res := tool.ToolResult{Error: d.Reason}
if after := r.AgentLoop.Hooks.AfterToolUse; after != nil { if after := r.AgentLoop.Hooks.AfterToolUse; after != nil {
after(ctx, tc.Name, tc.Input, res) callAfterToolHook(ctx, after, tc.Name, tc.Input, res)
} }
return res, false return res, false
} }
@@ -991,7 +1008,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
if ctx.Err() != nil { if ctx.Err() != nil {
return tool.ToolResult{Error: "aborted by user"}, true return tool.ToolResult{Error: "aborted by user"}, true
} }
result, err := r.Tools.Execute(ctx, tc.Name, tc.Input) result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
if err != nil { if err != nil {
result = tool.ToolResult{Error: err.Error()} result = tool.ToolResult{Error: err.Error()}
} }
@@ -1002,7 +1019,7 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
r.recordFileTouch(extractPathFromInput(tc.Input)) r.recordFileTouch(extractPathFromInput(tc.Input))
} }
if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil { if hook := r.AgentLoop.Hooks.AfterToolUse; hook != nil {
hook(ctx, tc.Name, tc.Input, result) callAfterToolHook(ctx, hook, tc.Name, tc.Input, result)
} }
return result, false return result, false
} }
+62
View File
@@ -0,0 +1,62 @@
package runtime
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"runtime/debug"
"github.com/sausheong/harness/tool"
)
func recoveredPanicError(component string, recovered any) error {
err := fmt.Errorf("%s panicked: %v", component, recovered)
slog.Error("recovered extension panic", "component", component, "error", err, "stack", string(debug.Stack()))
return err
}
func callToolExecute(ctx context.Context, ex tool.Executor, name string, input json.RawMessage) (result tool.ToolResult, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("tool "+name, recovered)
}
}()
return ex.Execute(ctx, name, input)
}
func callBeforeToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage) (HookDecision, error), name string, input json.RawMessage) (decision HookDecision, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = recoveredPanicError("BeforeToolUse hook", recovered)
}
}()
return hook(ctx, name, input)
}
func callAfterToolHook(ctx context.Context, hook func(context.Context, string, json.RawMessage, tool.ToolResult), name string, input json.RawMessage, result tool.ToolResult) {
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("AfterToolUse hook", recovered)
}
}()
hook(ctx, name, input, result)
}
func callOnStopHook(ctx context.Context, hook func(context.Context, string), reason string) {
defer func() {
if recovered := recover(); recovered != nil {
_ = recoveredPanicError("OnStop hook", recovered)
}
}()
hook(ctx, reason)
}
func callPermissionCheck(ctx context.Context, checker tool.PermissionChecker, agentID, name string, input json.RawMessage) (decision tool.Decision) {
defer func() {
if recovered := recover(); recovered != nil {
decision = tool.Decision{Behavior: tool.DecisionDeny, Reason: recoveredPanicError("permission checker", recovered).Error()}
}
}()
return checker.Check(ctx, agentID, name, input)
}
+111
View File
@@ -0,0 +1,111 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type panickingTool struct{}
func (*panickingTool) Name() string { return "panic_tool" }
func (*panickingTool) Description() string { return "panics for testing" }
func (*panickingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (*panickingTool) IsConcurrencySafe(json.RawMessage) bool { return false }
func (*panickingTool) Execute(context.Context, json.RawMessage) (tool.ToolResult, error) {
panic("boom")
}
type panickingPermission struct{}
func (panickingPermission) Check(context.Context, string, string, json.RawMessage) tool.Decision {
panic("permission boom")
}
func (panickingPermission) FilterToolDefs(defs []llm.ToolDef, _ string) []llm.ToolDef {
return defs
}
func TestDispatchToolRecoversExecutePanicAndPreservesPairing(t *testing.T) {
reg := tool.NewRegistry()
reg.Register(&panickingTool{})
rt := &Runtime{Tools: reg, Session: session.NewSession("agent", "key")}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
ID: "call-1", Name: "panic_tool", Input: json.RawMessage(`{}`),
}, nil)
assert.False(t, aborted)
assert.Contains(t, result.Error, "tool panic_tool panicked: boom")
entries := rt.Session.Entries()
require.Len(t, entries, 2)
assert.Equal(t, session.EntryTypeToolCall, entries[0].Type)
assert.Equal(t, session.EntryTypeToolResult, entries[1].Type)
}
func TestDispatchToolFailsClosedWhenPermissionPanics(t *testing.T) {
reg := tool.NewRegistry()
reg.Register(&mockTool{name: "safe", output: "must not execute"})
rt := &Runtime{
Tools: reg, Session: session.NewSession("agent", "key"),
Permission: panickingPermission{},
}
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{
ID: "call-1", Name: "safe", Input: json.RawMessage(`{}`),
}, nil)
assert.False(t, aborted)
assert.Contains(t, result.Error, "permission checker panicked")
assert.NotContains(t, result.Output, "must not execute")
require.Len(t, rt.Session.Entries(), 2)
}
func TestRunRecoversHookPanicAsEventError(t *testing.T) {
rt := hookFixture(t, LifecycleHooks{
OnUserPromptSubmit: func(context.Context, string, []llm.ImageContent) (string, []llm.ImageContent, error) {
panic("hook boom")
},
}, nil, nil)
events, err := rt.Run(context.Background(), "hello", nil)
require.NoError(t, err)
var got error
for event := range events {
if event.Type == EventError {
got = event.Error
}
}
require.Error(t, got)
assert.Contains(t, got.Error(), "runtime panicked: hook boom")
}
func TestRunRejectsConcurrentCall(t *testing.T) {
started := make(chan struct{})
provider := &llmtest.Stub{Text: "done", Delay: 50 * time.Millisecond, Started: started}
rt := &Runtime{
LLM: provider, Tools: tool.NewRegistry(),
Session: session.NewSession("agent", "key"), Model: "mock", MaxTurns: 1,
}
first, err := rt.Run(context.Background(), "first", nil)
require.NoError(t, err)
<-started
second, err := rt.Run(context.Background(), "second", nil)
require.ErrorContains(t, err, "already running")
assert.Nil(t, second)
for range first {
}
third, err := rt.Run(context.Background(), "third", nil)
require.NoError(t, err, "runtime must become available after the first run ends")
for range third {
}
}
+4 -3
View File
@@ -46,9 +46,10 @@ type AgentSpec struct {
// Reasoning maps to each provider's native reasoning knob. Use // Reasoning maps to each provider's native reasoning knob. Use
// llm.ReasoningOff (zero value), Low, Medium, or High. // llm.ReasoningOff (zero value), Low, Medium, or High.
Reasoning string Reasoning string
// Loop controls the runtime's tool-execution behavior (concurrency // Loop controls the runtime's per-agent tool-execution behavior
// cap, depth cap, streaming-tools toggle). Zero value ⇒ env-var // (concurrency cap, depth cap, streaming-tools toggle). Non-zero fields
// fallback then compiled-in defaults. // and non-nil hooks override RuntimeDeps.AgentLoop; remaining zero values
// inherit the shared setting, then its env/default fallback.
Loop LoopConfig Loop LoopConfig
// MCPServers, when non-empty, are connected by BuildRuntime: each // MCPServers, when non-empty, are connected by BuildRuntime: each
// server's tools are namespaced ("mcp__<Name>__<tool>") and added // server's tools are namespaced ("mcp__<Name>__<tool>") and added
+49
View File
@@ -53,8 +53,29 @@ func (s *Store) sessionPath(agentID, key string) string {
return filepath.Join(s.sessionDir(agentID), key+".jsonl") return filepath.Join(s.sessionDir(agentID), key+".jsonl")
} }
// validateStoreComponent keeps caller-provided identifiers as one filesystem
// path component. Empty values remain supported for backward compatibility,
// but separators, volume names, and dot traversal are rejected.
func validateStoreComponent(kind, value string) error {
if value == "." || value == ".." || filepath.VolumeName(value) != "" ||
strings.ContainsAny(value, `/\`) {
return fmt.Errorf("invalid %s %q: must be a single path component", kind, value)
}
return nil
}
func validateStoreIDs(agentID, key string) error {
if err := validateStoreComponent("agent ID", agentID); err != nil {
return err
}
return validateStoreComponent("session key", key)
}
// Load reads a session from its JSONL file. // Load reads a session from its JSONL file.
func (s *Store) Load(agentID, key string) (*Session, error) { func (s *Store) Load(agentID, key string) (*Session, error) {
if err := validateStoreIDs(agentID, key); err != nil {
return nil, err
}
path := s.sessionPath(agentID, key) path := s.sessionPath(agentID, key)
f, err := os.Open(path) f, err := os.Open(path)
@@ -103,6 +124,11 @@ func (s *Store) Load(agentID, key string) (*Session, error) {
func (s *Store) AppendEntry(sess *Session, entry SessionEntry) { func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
if err := validateStoreIDs(sess.AgentID, sess.Key); err != nil {
s.markDegraded("invalid session path", err)
slog.Error("refusing to persist session outside store", "error", err)
return
}
dir := s.sessionDir(sess.AgentID) dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil { if err := os.MkdirAll(dir, 0o755); err != nil {
@@ -135,6 +161,9 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
// Create creates an empty session file on disk so it shows up in List. // Create creates an empty session file on disk so it shows up in List.
func (s *Store) Create(agentID, key string) error { func (s *Store) Create(agentID, key string) error {
if err := validateStoreIDs(agentID, key); err != nil {
return err
}
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@@ -153,6 +182,9 @@ func (s *Store) Create(agentID, key string) error {
// List returns metadata for all sessions belonging to the given agent. // List returns metadata for all sessions belonging to the given agent.
func (s *Store) List(agentID string) ([]SessionInfo, error) { func (s *Store) List(agentID string) ([]SessionInfo, error) {
if err := validateStoreComponent("agent ID", agentID); err != nil {
return nil, err
}
dir := s.sessionDir(agentID) dir := s.sessionDir(agentID)
entries, err := os.ReadDir(dir) entries, err := os.ReadDir(dir)
if err != nil { if err != nil {
@@ -224,6 +256,9 @@ func (s *Store) List(agentID string) ([]SessionInfo, error) {
// Exists checks whether a session file exists for the given agent and key. // Exists checks whether a session file exists for the given agent and key.
func (s *Store) Exists(agentID, key string) bool { func (s *Store) Exists(agentID, key string) bool {
if validateStoreIDs(agentID, key) != nil {
return false
}
path := s.sessionPath(agentID, key) path := s.sessionPath(agentID, key)
_, err := os.Stat(path) _, err := os.Stat(path)
return err == nil return err == nil
@@ -231,6 +266,12 @@ func (s *Store) Exists(agentID, key string) bool {
// Rename renames a session file from oldKey to newKey. // Rename renames a session file from oldKey to newKey.
func (s *Store) Rename(agentID, oldKey, newKey string) error { func (s *Store) Rename(agentID, oldKey, newKey string) error {
if err := validateStoreIDs(agentID, oldKey); err != nil {
return err
}
if err := validateStoreComponent("session key", newKey); err != nil {
return err
}
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@@ -249,6 +290,9 @@ func (s *Store) Rename(agentID, oldKey, newKey string) error {
// Delete removes a session's JSONL file. // Delete removes a session's JSONL file.
func (s *Store) Delete(agentID, key string) error { func (s *Store) Delete(agentID, key string) error {
if err := validateStoreIDs(agentID, key); err != nil {
return err
}
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
@@ -264,6 +308,11 @@ func (s *Store) Delete(agentID, key string) error {
func (s *Store) Rewrite(sess *Session) { func (s *Store) Rewrite(sess *Session) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
if err := validateStoreIDs(sess.AgentID, sess.Key); err != nil {
s.markDegraded("invalid session path", err)
slog.Error("refusing to rewrite session outside store", "error", err)
return
}
dir := s.sessionDir(sess.AgentID) dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil { if err := os.MkdirAll(dir, 0o755); err != nil {
+13
View File
@@ -50,3 +50,16 @@ func TestStore_RewriteDegradedWarns(t *testing.T) {
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"), require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"Rewrite failure must emit the degraded warning") "Rewrite failure must emit the degraded warning")
} }
func TestStoreRejectsPathTraversalIdentifiers(t *testing.T) {
s := NewStore(t.TempDir())
_, err := s.Load("../outside", "key")
require.ErrorContains(t, err, "invalid agent ID")
require.ErrorContains(t, s.Create("agent", "../outside"), "invalid session key")
require.ErrorContains(t, s.Rename("agent", "../old", "new"), "invalid session key")
require.ErrorContains(t, s.Delete("agent", "../outside"), "invalid session key")
require.False(t, s.Exists("agent", "../outside"))
_, err = s.List("../outside")
require.ErrorContains(t, err, "invalid agent ID")
}
+12 -3
View File
@@ -291,14 +291,24 @@ func ValidatePathInWorkDir(path, workDir string) error {
realWork = absWork // workspace might not exist yet realWork = absWork // workspace might not exist yet
} }
// For the target path, resolve the parent directory (file may not exist yet) // Resolve an existing target itself so a final-component symlink cannot
// escape the workspace. For a path that does not exist yet, resolve its
// parent directory instead so callers can safely create a new file.
realPath, targetErr := filepath.EvalSymlinks(absPath)
if targetErr == nil {
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
return fmt.Errorf("path %q is outside workspace %q", path, workDir)
}
return nil
}
parentDir := filepath.Dir(absPath) parentDir := filepath.Dir(absPath)
realParent, err := filepath.EvalSymlinks(parentDir) realParent, err := filepath.EvalSymlinks(parentDir)
if err != nil { if err != nil {
// Parent doesn't exist — use the unresolved absolute path // Parent doesn't exist — use the unresolved absolute path
realParent = parentDir realParent = parentDir
} }
realPath := filepath.Join(realParent, filepath.Base(absPath)) realPath = filepath.Join(realParent, filepath.Base(absPath))
if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork { if !strings.HasPrefix(realPath, realWork+string(filepath.Separator)) && realPath != realWork {
return fmt.Errorf("path %q is outside workspace %q", path, workDir) return fmt.Errorf("path %q is outside workspace %q", path, workDir)
@@ -313,4 +323,3 @@ func ValidatePathInWorkDir(path, workDir string) error {
func RegisterCron(reg *Registry, agentID string, scheduler JobScheduler) { func RegisterCron(reg *Registry, agentID string, scheduler JobScheduler) {
reg.Register(&CronTool{AgentID: agentID, Scheduler: scheduler}) reg.Register(&CronTool{AgentID: agentID, Scheduler: scheduler})
} }
+7 -4
View File
@@ -11,6 +11,7 @@ import (
"runtime" "runtime"
"strings" "strings"
"time" "time"
"github.com/sausheong/harness/tool" "github.com/sausheong/harness/tool"
) )
@@ -57,8 +58,7 @@ func resolveBashCommandPaths(cmd string) (string, [][2]string) {
return out, subs return out, subs
} }
// shellSingleQuote wraps s in single quotes, escaping any embedded single // shellSingleQuote wraps s in single quotes, safely escaping embedded quotes.
// quotes via the standard '\'' dance.
func shellSingleQuote(s string) string { func shellSingleQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
} }
@@ -83,7 +83,7 @@ const defaultBashTimeout = 120 * time.Second
// ExecPolicy controls which commands the bash tool is allowed to execute. // ExecPolicy controls which commands the bash tool is allowed to execute.
type ExecPolicy struct { type ExecPolicy struct {
Level string // "deny", "allowlist", "full" Level string // "deny", "allowlist", "full"; any other value denies execution
Allowlist []string // command basenames allowed when Level is "allowlist" Allowlist []string // command basenames allowed when Level is "allowlist"
} }
@@ -214,8 +214,11 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
return tool.ToolResult{Error: fmt.Sprintf("command %q is not in the exec allowlist", cmd)}, nil return tool.ToolResult{Error: fmt.Sprintf("command %q is not in the exec allowlist", cmd)}, nil
} }
} }
case "full":
// Explicitly unrestricted.
default:
return tool.ToolResult{Error: fmt.Sprintf("invalid bash execution policy %q; execution denied", t.ExecPolicy.Level)}, nil
} }
// "full" or unrecognized: allow everything
} }
timeout := defaultBashTimeout timeout := defaultBashTimeout
+19 -4
View File
@@ -43,6 +43,21 @@ func TestExtractCommands_BackgroundAmpersand(t *testing.T) {
} }
} }
func TestUnknownExecPolicyFailsClosed(t *testing.T) {
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlits", Allowlist: []string{"echo"}}}
in, err := json.Marshal(bashInput{Command: "echo should-not-run"})
if err != nil {
t.Fatal(err)
}
res, err := bt.Execute(context.Background(), in)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(res.Error, "invalid bash execution policy") {
t.Fatalf("unknown policy must fail closed, got %q", res.Error)
}
}
func TestSanitizeLLMText(t *testing.T) { func TestSanitizeLLMText(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -86,10 +101,10 @@ func TestResolveBashCommandPaths(t *testing.T) {
} }
tests := []struct { tests := []struct {
name string name string
cmd string cmd string
wantCmd string wantCmd string
wantSubs int wantSubs int
}{ }{
{ {
name: "backslash-escaped path with ascii spaces resolves to nbsp file", name: "backslash-escaped path with ascii spaces resolves to nbsp file",
+5 -1
View File
@@ -289,6 +289,10 @@ func (t *BrowserTool) Execute(ctx context.Context, input json.RawMessage) (tool.
if in.Script == "" { if in.Script == "" {
return tool.ToolResult{Error: "script is required for evaluate action"}, nil return tool.ToolResult{Error: "script is required for evaluate action"}, nil
} }
case "navigate", "get_text", "screenshot":
// No additional required fields beyond the checks above.
default:
return tool.ToolResult{Error: fmt.Sprintf("unknown action: %q (valid: navigate, click, type, get_text, screenshot, evaluate, close)", in.Action)}, nil
} }
// Catch the about:blank trap: any post-navigation action (screenshot, // Catch the about:blank trap: any post-navigation action (screenshot,
@@ -390,7 +394,7 @@ func (t *BrowserTool) getOrCreateSession(name string) (*browserSession, error) {
// both — wrap it. // both — wrap it.
sess := &browserSession{ sess := &browserSession{
taskCtx: taskCtx, taskCtx: taskCtx,
taskCancel: cleanup, // cleanup tears down both task + alloc taskCancel: cleanup, // cleanup tears down both task + alloc
allocCancel: func() {}, // no-op; cleanup already covers alloc allocCancel: func() {}, // no-op; cleanup already covers alloc
lastUsed: time.Now(), lastUsed: time.Now(),
} }
+24
View File
@@ -48,6 +48,30 @@ func TestReadFileToolWorkDirClamps(t *testing.T) {
"reads outside the workspace must be rejected when WorkDir is set") "reads outside the workspace must be rejected when WorkDir is set")
} }
func TestReadFileToolWorkDirRejectsEscapingFileSymlink(t *testing.T) {
workspace := t.TempDir()
outside := filepath.Join(t.TempDir(), "secret.txt")
require.NoError(t, os.WriteFile(outside, []byte("nope"), 0o644))
link := filepath.Join(workspace, "secret-link")
require.NoError(t, os.Symlink(outside, link))
readTool := &ReadFileTool{WorkDir: workspace}
input, _ := json.Marshal(readFileInput{Path: link})
result, err := readTool.Execute(context.Background(), input)
require.NoError(t, err)
assert.Contains(t, result.Error, "outside workspace")
assert.Empty(t, result.Output)
writeTool := &WriteFileTool{WorkDir: workspace}
writeInput, _ := json.Marshal(writeFileInput{Path: link, Content: "overwritten"})
result, err = writeTool.Execute(context.Background(), writeInput)
require.NoError(t, err)
assert.Contains(t, result.Error, "outside workspace")
data, readErr := os.ReadFile(outside)
require.NoError(t, readErr)
assert.Equal(t, "nope", string(data))
}
func TestWriteFileTool(t *testing.T) { func TestWriteFileTool(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
path := filepath.Join(dir, "subdir", "output.txt") path := filepath.Join(dir, "subdir", "output.txt")