Harden Harness runtime, persistence and execution for Hand
This commit is contained in:
1 parent
09c30fe2d5
commit
0972eed3ea
164 files changed
+15912
-506
No files matched your search
@@ -0,0 +1,100 @@
|
||||
package bash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/execution"
|
||||
"github.com/sausheong/harness/process"
|
||||
)
|
||||
|
||||
type recordingBackend struct {
|
||||
requests []execution.Request
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (*recordingBackend) Boundary() string { return "fixture boundary" }
|
||||
func (b *recordingBackend) Run(_ context.Context, r execution.Request) (execution.Result, error) {
|
||||
b.requests = append(b.requests, r)
|
||||
if b.fail {
|
||||
return execution.Result{ExitCode: -1}, errors.New("backend unavailable")
|
||||
}
|
||||
return execution.Result{Stdout: "captured", ExitCode: 0}, nil
|
||||
}
|
||||
func TestBackendReceivesExactApprovedCommandAndNeverFallsBack(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
actual := filepath.Join(workspace, "narrow\u00a0space")
|
||||
if err := os.WriteFile(actual, []byte("fixture"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
command := "cat '" + filepath.Join(workspace, "narrow space") + "'"
|
||||
backend := &recordingBackend{}
|
||||
bt := &BashTool{WorkDir: workspace, Backend: backend}
|
||||
input, _ := json.Marshal(bashInput{Command: command})
|
||||
result, err := bt.Execute(context.Background(), input)
|
||||
if err != nil || result.Error != "" {
|
||||
t.Fatalf("%+v %v", result, err)
|
||||
}
|
||||
if len(backend.requests) != 1 || !reflect.DeepEqual(backend.requests[0].Argv, []string{"/bin/bash", "-c", command}) {
|
||||
t.Fatal("approved source was rewritten")
|
||||
}
|
||||
if backend.requests[0].OutputStore == nil || result.Metadata["execution_boundary"] != "fixture boundary" {
|
||||
t.Fatal("capture or boundary missing")
|
||||
}
|
||||
backend.fail = true
|
||||
marker := filepath.Join(workspace, "must-not-exist")
|
||||
input, _ = json.Marshal(bashInput{Command: "touch '" + marker + "'"})
|
||||
result, _ = bt.Execute(context.Background(), input)
|
||||
if !strings.Contains(result.Error, "backend unavailable") {
|
||||
t.Fatal(result)
|
||||
}
|
||||
if _, err = os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatal("fallback ran on host")
|
||||
}
|
||||
bt.ExecPolicy = &ExecPolicy{Level: "deny"}
|
||||
bt.Execute(context.Background(), input)
|
||||
if len(backend.requests) != 2 {
|
||||
t.Fatal("policy denial reached backend")
|
||||
}
|
||||
}
|
||||
func TestBashNativeContainerWithCapture(t *testing.T) {
|
||||
image, socket := os.Getenv("HARNESS_TEST_BASH_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
|
||||
if image == "" || socket == "" {
|
||||
t.Skip("native bash container fixture not configured")
|
||||
}
|
||||
workspace := t.TempDir()
|
||||
if err := os.Chmod(workspace, 0777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := process.NewArtifactStore(filepath.Join(t.TempDir(), "capture"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bt := &BashTool{OutputStore: store, Backend: execution.Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: workspace, Writable: true}}
|
||||
input, _ := json.Marshal(bashInput{Command: `set -eu; test ! -e /var/run/docker.sock; ! touch /etc/outside; printf allowed >/workspace/allowed; head -c 100000 /dev/zero`})
|
||||
result, err := bt.Execute(context.Background(), input)
|
||||
if err != nil || result.Error != "" {
|
||||
t.Fatalf("%+v %v", result, err)
|
||||
}
|
||||
if result.Metadata["stdout_bytes"] != int64(100000) || result.Metadata["output_truncated"] != true {
|
||||
t.Fatal("capture limits missing", result.Metadata)
|
||||
}
|
||||
info, ok := result.Metadata["stdout_artifact"].(process.ArtifactInfo)
|
||||
if !ok || info.Bytes != 100000 || info.Error != "" {
|
||||
t.Fatal("full artifact missing", info)
|
||||
}
|
||||
raw, err := store.Read(context.Background(), info)
|
||||
if err != nil || len(raw) != 100000 {
|
||||
t.Fatalf("artifact: %d %v", len(raw), err)
|
||||
}
|
||||
raw, err = os.ReadFile(filepath.Join(workspace, "allowed"))
|
||||
if err != nil || string(raw) != "allowed" {
|
||||
t.Fatal("workspace write absent")
|
||||
}
|
||||
}
|
||||
+109
-17
@@ -1,17 +1,20 @@
|
||||
package bash
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/execution"
|
||||
"github.com/sausheong/harness/process"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
@@ -89,8 +92,10 @@ type ExecPolicy struct {
|
||||
|
||||
// BashTool executes shell commands.
|
||||
type BashTool struct {
|
||||
WorkDir string
|
||||
ExecPolicy *ExecPolicy // nil means "full" (allow everything)
|
||||
Backend execution.Backend // optional explicit command boundary; configured before use
|
||||
WorkDir string
|
||||
OutputStore *process.ArtifactStore // nil uses the private per-user temporary store
|
||||
ExecPolicy *ExecPolicy // nil means "full" (allow everything)
|
||||
}
|
||||
|
||||
type bashInput struct {
|
||||
@@ -183,8 +188,10 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
|
||||
// (e.g. ASCII spaces in a filename that on disk uses NBSP). Substitution
|
||||
// only fires when the on-disk entry actually contains Unicode whitespace,
|
||||
// so create-style commands like `mkdir /tmp/newdir` are unaffected.
|
||||
resolvedCmd, pathSubs := resolveBashCommandPaths(in.Command)
|
||||
in.Command = resolvedCmd
|
||||
var pathSubs [][2]string
|
||||
if t.Backend == nil {
|
||||
in.Command, pathSubs = resolveBashCommandPaths(in.Command)
|
||||
}
|
||||
|
||||
// Enforce exec policy
|
||||
if t.ExecPolicy != nil {
|
||||
@@ -229,38 +236,83 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
if t.Backend != nil {
|
||||
return t.executeBackend(ctx, in.Command), nil
|
||||
}
|
||||
var cmd *exec.Cmd
|
||||
if runtime.GOOS == "windows" {
|
||||
cmd = exec.CommandContext(ctx, "cmd", "/c", in.Command)
|
||||
cmd = process.Command(ctx, "cmd", "/c", in.Command)
|
||||
} else {
|
||||
cmd = exec.CommandContext(ctx, "bash", "-c", in.Command)
|
||||
cmd = process.Command(ctx, "bash", "-c", in.Command)
|
||||
}
|
||||
if t.WorkDir != "" {
|
||||
cmd.Dir = t.WorkDir
|
||||
}
|
||||
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
store := t.OutputStore
|
||||
if store == nil {
|
||||
var err error
|
||||
store, err = process.NewArtifactStore(filepath.Join(os.TempDir(), "harness-output-"+strconv.Itoa(os.Getuid())))
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: "prepare output capture: " + err.Error()}, nil
|
||||
}
|
||||
}
|
||||
stdout, stderr := store.Capture(64<<10), store.Capture(64<<10)
|
||||
cmd.Stdout = stdout
|
||||
cmd.Stderr = stderr
|
||||
|
||||
err := cmd.Run()
|
||||
err := process.Run(cmd)
|
||||
stdout.Close()
|
||||
stderr.Close()
|
||||
|
||||
output := stdout.String()
|
||||
errOutput := stderr.String()
|
||||
output, stdoutBytes, stdoutTruncated := stdout.Snapshot()
|
||||
errOutput, stderrBytes, stderrTruncated := stderr.Snapshot()
|
||||
metadata := map[string]any{
|
||||
"stdout_bytes": stdoutBytes, "stderr_bytes": stderrBytes,
|
||||
"stdout_artifact": stdout.Info(), "stderr_artifact": stderr.Info(),
|
||||
"stdout_truncated": stdoutTruncated, "stderr_truncated": stderrTruncated,
|
||||
"cancelled": ctx.Err() == context.Canceled,
|
||||
"timed_out": ctx.Err() == context.DeadlineExceeded,
|
||||
}
|
||||
if cmd.ProcessState != nil {
|
||||
metadata["exit_code"] = cmd.ProcessState.ExitCode()
|
||||
}
|
||||
if stdoutTruncated {
|
||||
output += "\n[stdout truncated after 65536 bytes]"
|
||||
}
|
||||
if stderrTruncated {
|
||||
errOutput += "\n[stderr truncated after 65536 bytes]"
|
||||
}
|
||||
|
||||
notice := pathSubsNotice(pathSubs)
|
||||
for _, capture := range []struct {
|
||||
name string
|
||||
info process.ArtifactInfo
|
||||
}{
|
||||
{"stdout", stdout.Info()}, {"stderr", stderr.Info()},
|
||||
} {
|
||||
if capture.info.Path != "" {
|
||||
notice += fmt.Sprintf("[%s artifact: %s; %d bytes; truncated=%t]\n", capture.name, capture.info.Path, capture.info.Bytes, capture.info.Truncated)
|
||||
}
|
||||
if capture.info.Error != "" {
|
||||
notice += fmt.Sprintf("[%s artifact unavailable or incomplete: %s]\n", capture.name, capture.info.Error)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
msg := err.Error()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
msg = "command timed out"
|
||||
} else if ctx.Err() == context.Canceled {
|
||||
msg = "command cancelled"
|
||||
}
|
||||
if errOutput != "" {
|
||||
msg = errOutput
|
||||
msg += ": " + errOutput
|
||||
}
|
||||
return tool.ToolResult{
|
||||
Output: notice + output,
|
||||
Error: msg,
|
||||
Output: notice + output,
|
||||
Error: msg,
|
||||
Metadata: metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -268,7 +320,7 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
|
||||
output += "\nSTDERR:\n" + errOutput
|
||||
}
|
||||
|
||||
return tool.ToolResult{Output: notice + output}, nil
|
||||
return tool.ToolResult{Output: notice + output, Metadata: metadata}, nil
|
||||
}
|
||||
|
||||
// pathSubsNotice formats a one-block notice listing any path substitutions
|
||||
@@ -285,3 +337,43 @@ func pathSubsNotice(subs [][2]string) string {
|
||||
b.WriteString("---\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// Explicit backends receive the exact approved shell source. Do not reinterpret
|
||||
// paths on the host: the backend filesystem can contain different resources.
|
||||
func (t *BashTool) executeBackend(ctx context.Context, command string) tool.ToolResult {
|
||||
store := t.OutputStore
|
||||
if store == nil {
|
||||
var err error
|
||||
store, err = process.NewArtifactStore(filepath.Join(os.TempDir(), "harness-output-"+strconv.Itoa(os.Getuid())))
|
||||
if err != nil {
|
||||
return tool.ToolResult{Error: "prepare output capture: " + err.Error()}
|
||||
}
|
||||
}
|
||||
r, err := t.Backend.Run(ctx, execution.Request{Argv: []string{"/bin/bash", "-c", command}, OutputStore: store})
|
||||
meta := map[string]any{"execution_boundary": t.Backend.Boundary(), "exit_code": r.ExitCode, "stdout_bytes": r.StdoutBytes, "stderr_bytes": r.StderrBytes, "stdout_artifact": r.StdoutArtifact, "stderr_artifact": r.StderrArtifact, "output_truncated": r.Truncated, "stdout_truncated": r.StdoutTruncated, "stderr_truncated": r.StderrTruncated, "cancelled": ctx.Err() == context.Canceled, "timed_out": ctx.Err() == context.DeadlineExceeded}
|
||||
output := r.Stdout
|
||||
if r.Stderr != "" {
|
||||
output += "\nSTDERR:\n" + r.Stderr
|
||||
}
|
||||
if r.Truncated {
|
||||
output += "\n[inline output truncated; inspect capture artifacts]"
|
||||
}
|
||||
for _, capture := range []struct {
|
||||
name string
|
||||
info process.ArtifactInfo
|
||||
}{{"stdout", r.StdoutArtifact}, {"stderr", r.StderrArtifact}} {
|
||||
if capture.info.Error != "" {
|
||||
output += "\n[" + capture.name + " artifact unavailable or incomplete: " + capture.info.Error + "]"
|
||||
}
|
||||
}
|
||||
result := tool.ToolResult{Output: output, Metadata: meta}
|
||||
if err != nil {
|
||||
result.Error = err.Error()
|
||||
}
|
||||
if ctx.Err() == context.Canceled {
|
||||
result.Error = "command cancelled"
|
||||
} else if ctx.Err() == context.DeadlineExceeded {
|
||||
result.Error = "command timed out"
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package bash
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/sausheong/harness/process"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCancellationStopsShellDescendant(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "survived")
|
||||
input, _ := json.Marshal(bashInput{Command: "sh -c 'sleep 1; echo survived > \"$1\"' fixture " + shellSingleQuote(marker) + " & wait"})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||
defer cancel()
|
||||
result, err := (&BashTool{}).Execute(ctx, input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Error == "" {
|
||||
t.Fatal("cancelled command succeeded")
|
||||
}
|
||||
// Waiting beyond the descendant's scheduled write distinguishes stopping it
|
||||
// from merely returning while it continues to run in the background.
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
if _, err := os.Stat(marker); err == nil {
|
||||
t.Fatal("shell descendant survived cancellation and wrote its marker")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalExitStopsShellDescendant(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "survived")
|
||||
input, _ := json.Marshal(bashInput{Command: "sh -c 'sleep 1; echo survived > \"$1\"' fixture " + shellSingleQuote(marker) + " >/dev/null 2>&1 &"})
|
||||
result, err := (&BashTool{}).Execute(context.Background(), input)
|
||||
if err != nil || result.Error != "" {
|
||||
t.Fatalf("%+v %v", result, err)
|
||||
}
|
||||
time.Sleep(1100 * time.Millisecond)
|
||||
if _, err := os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatalf("descendant marker: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputCaptureBoundsBothStreams(t *testing.T) {
|
||||
input := json.RawMessage(`{"command":"head -c 1048576 /dev/zero; head -c 1048576 /dev/zero >&2"}`)
|
||||
store, storeErr := process.NewArtifactStore(filepath.Join(t.TempDir(), "artifacts"))
|
||||
if storeErr != nil {
|
||||
t.Fatal(storeErr)
|
||||
}
|
||||
result, err := (&BashTool{OutputStore: store}).Execute(context.Background(), input)
|
||||
if err != nil || result.Error != "" {
|
||||
t.Fatalf("error: %v %s", err, result.Error)
|
||||
}
|
||||
if len(result.Output) > 2*(64<<10)+1000 {
|
||||
t.Fatalf("unbounded output: %d", len(result.Output))
|
||||
}
|
||||
for _, stream := range []string{"stdout", "stderr"} {
|
||||
artifact := result.Metadata[stream+"_artifact"].(process.ArtifactInfo)
|
||||
raw, err := os.ReadFile(artifact.Path)
|
||||
if err != nil || len(raw) != 1048576 || artifact.Truncated || artifact.Error != "" {
|
||||
t.Fatalf("artifact %+v: len=%d err=%v", artifact, len(raw), err)
|
||||
}
|
||||
for _, b := range raw {
|
||||
if b != 0 {
|
||||
t.Fatal("artifact content corrupted")
|
||||
}
|
||||
}
|
||||
if result.Metadata[stream+"_bytes"] != int64(1048576) || result.Metadata[stream+"_truncated"] != true {
|
||||
t.Fatalf("incorrect capture metadata: %+v", result.Metadata)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,8 @@ import (
|
||||
|
||||
// EditFileTool performs a string-replace edit on a file.
|
||||
type EditFileTool struct {
|
||||
WorkDir string // if set, restricts edits to this directory
|
||||
ExactPath bool // preserve admitted path spelling; no home or Unicode recovery
|
||||
WorkDir string // if set, restricts edits to this directory
|
||||
}
|
||||
|
||||
type editFileInput struct {
|
||||
@@ -62,11 +63,15 @@ func (t *EditFileTool) Execute(ctx context.Context, input json.RawMessage) (tool
|
||||
return tool.ToolResult{Error: "path is required"}, nil
|
||||
}
|
||||
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
if !t.ExactPath {
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
}
|
||||
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
|
||||
in.Path = filepath.Join(t.WorkDir, in.Path)
|
||||
}
|
||||
in.Path = tool.ResolveExistingPath(in.Path)
|
||||
if !t.ExactPath {
|
||||
in.Path = tool.ResolveExistingPath(in.Path)
|
||||
}
|
||||
|
||||
if t.WorkDir != "" {
|
||||
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
|
||||
|
||||
@@ -15,7 +15,8 @@ import (
|
||||
|
||||
// ReadFileTool reads the contents of a file.
|
||||
type ReadFileTool struct {
|
||||
WorkDir string // if set, restricts reads to this directory
|
||||
ExactPath bool // preserve admitted path spelling; no home or Unicode recovery
|
||||
WorkDir string // if set, restricts reads to this directory
|
||||
}
|
||||
|
||||
type readFileInput struct {
|
||||
@@ -82,11 +83,15 @@ func (t *ReadFileTool) Execute(ctx context.Context, input json.RawMessage) (tool
|
||||
return tool.ToolResult{Error: "path is required"}, nil
|
||||
}
|
||||
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
if !t.ExactPath {
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
}
|
||||
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
|
||||
in.Path = filepath.Join(t.WorkDir, in.Path)
|
||||
}
|
||||
in.Path = tool.ResolveExistingPath(in.Path)
|
||||
if !t.ExactPath {
|
||||
in.Path = tool.ResolveExistingPath(in.Path)
|
||||
}
|
||||
|
||||
if t.WorkDir != "" {
|
||||
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
|
||||
|
||||
+20
-4
@@ -3,15 +3,17 @@ package file
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// WriteFileTool creates or overwrites a file.
|
||||
type WriteFileTool struct {
|
||||
WorkDir string // if set, restricts writes to this directory
|
||||
ExactPath bool // preserve admitted path spelling; no home or Unicode recovery
|
||||
WorkDir string // if set, restricts writes to this directory
|
||||
}
|
||||
|
||||
type writeFileInput struct {
|
||||
@@ -55,7 +57,9 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
|
||||
return tool.ToolResult{Error: "path is required"}, nil
|
||||
}
|
||||
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
if !t.ExactPath {
|
||||
in.Path = tool.ExpandHome(in.Path)
|
||||
}
|
||||
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
|
||||
in.Path = filepath.Join(t.WorkDir, in.Path)
|
||||
}
|
||||
@@ -72,7 +76,19 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to create directory: %v", err)}, nil
|
||||
}
|
||||
|
||||
if err := tool.WriteFileAtomic(in.Path, []byte(in.Content), 0o600); err != nil {
|
||||
// Retain existing ordinary permission bits, including executable scripts.
|
||||
// New files remain private. Inspection failures must not silently replace
|
||||
// a file with restrictive defaults and lose its original mode.
|
||||
mode := os.FileMode(0600)
|
||||
if info, err := os.Stat(in.Path); err == nil {
|
||||
if !info.Mode().IsRegular() {
|
||||
return tool.ToolResult{Error: "destination is not a regular file"}, nil
|
||||
}
|
||||
mode = info.Mode().Perm()
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("inspect destination: %v", err)}, nil
|
||||
}
|
||||
if err := tool.WriteFileAtomic(in.Path, []byte(in.Content), mode); err != nil {
|
||||
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -24,3 +24,44 @@ func TestWriteFileIsRestrictive(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
|
||||
}
|
||||
|
||||
func TestWriteFilePreservesExecutableMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "script.sh")
|
||||
require.NoError(t, os.WriteFile(path, []byte("old"), 0751))
|
||||
require.NoError(t, os.Chmod(path, 0751))
|
||||
writer := &WriteFileTool{WorkDir: dir}
|
||||
input, _ := json.Marshal(map[string]string{"path": path, "content": "#!/bin/sh\nexit 0\n"})
|
||||
result, err := writer.Execute(context.Background(), input)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, result.Error)
|
||||
info, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0751), info.Mode().Perm())
|
||||
}
|
||||
|
||||
func TestFailedWritePreservesExistingContentAndMode(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Fatal("permission failure fixture requires an unprivileged user")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "script.sh")
|
||||
require.NoError(t, os.WriteFile(path, []byte("original"), 0751))
|
||||
require.NoError(t, os.Chmod(path, 0751))
|
||||
require.NoError(t, os.Chmod(dir, 0500))
|
||||
defer os.Chmod(dir, 0700)
|
||||
writer := &WriteFileTool{WorkDir: dir}
|
||||
input, _ := json.Marshal(map[string]string{"path": path, "content": "replacement"})
|
||||
result, err := writer.Execute(context.Background(), input)
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, result.Error)
|
||||
data, err := os.ReadFile(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "original", string(data))
|
||||
info, err := os.Stat(path)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0751), info.Mode().Perm())
|
||||
entries, err := os.ReadDir(dir)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, entries, 1)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCancelledHandshakeReapsChildPromptly(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "pid")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
cli, err := Connect(ctx, ServerConfig{Name: "hung", Command: "sh", Args: []string{"-c", `echo $$ > "$1"; exec sleep 30`, "fixture", path}})
|
||||
elapsed := time.Since(start)
|
||||
if cli != nil {
|
||||
cli.Close()
|
||||
t.Fatal("hung handshake connected")
|
||||
}
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("connect error %v", err)
|
||||
}
|
||||
data, readErr := os.ReadFile(path)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
pid, parseErr := strconv.Atoi(strings.TrimSpace(string(data)))
|
||||
if parseErr != nil {
|
||||
t.Fatal(parseErr)
|
||||
}
|
||||
aliveErr := syscall.Kill(pid, 0)
|
||||
if aliveErr == nil {
|
||||
syscall.Kill(pid, syscall.SIGKILL)
|
||||
t.Fatal("connection returned with child still alive")
|
||||
}
|
||||
if !errors.Is(aliveErr, syscall.ESRCH) {
|
||||
t.Fatalf("child status %v", aliveErr)
|
||||
}
|
||||
if elapsed > 2*time.Second {
|
||||
t.Fatalf("cancelled handshake took %s", elapsed)
|
||||
}
|
||||
}
|
||||
+19
-12
@@ -24,9 +24,11 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/sausheong/harness/process"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
@@ -34,6 +36,10 @@ import (
|
||||
// transport must be specified: Command (stdio, the most common) or URL
|
||||
// (Streamable HTTP via the SDK's StreamableClientTransport).
|
||||
type ServerConfig struct {
|
||||
// Optional permits construction to continue when this server fails.
|
||||
Optional bool
|
||||
// ConnectTimeout bounds this server; optional servers default to five seconds.
|
||||
ConnectTimeout time.Duration
|
||||
// Name namespaces the server's tools. Adapter tool names become
|
||||
// "mcp__<Name>__<tool>" — the conventional double-underscore
|
||||
// scheme that prevents collisions with built-in tools.
|
||||
@@ -71,16 +77,20 @@ type ServerConfig struct {
|
||||
// Client is a connected MCP server with its discovered tools adapted as
|
||||
// harness tool.Tool implementations.
|
||||
type Client struct {
|
||||
name string
|
||||
session *sdk.ClientSession
|
||||
tools []tool.Tool
|
||||
closed bool
|
||||
name string
|
||||
session *sdk.ClientSession
|
||||
tools []tool.Tool
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// Connect opens a session to the MCP server in cfg, lists its tools,
|
||||
// and adapts each into a tool.Tool. Returned Client owns the session;
|
||||
// call Close to release it.
|
||||
func Connect(ctx context.Context, cfg ServerConfig) (*Client, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Name == "" {
|
||||
return nil, fmt.Errorf("mcp: ServerConfig.Name is required")
|
||||
}
|
||||
@@ -135,11 +145,8 @@ func (c *Client) Ping(ctx context.Context) error {
|
||||
// Close releases the underlying MCP session. Safe to call multiple
|
||||
// times — subsequent calls are no-ops.
|
||||
func (c *Client) Close() error {
|
||||
if c.closed {
|
||||
return nil
|
||||
}
|
||||
c.closed = true
|
||||
return c.session.Close()
|
||||
c.closeOnce.Do(func() { c.closeErr = c.session.Close() })
|
||||
return c.closeErr
|
||||
}
|
||||
|
||||
// buildTransport selects a transport based on cfg. stdio uses
|
||||
@@ -149,9 +156,9 @@ func (c *Client) Close() error {
|
||||
// applied via wrapHTTPClient.
|
||||
func buildTransport(cfg ServerConfig) (sdk.Transport, error) {
|
||||
if cfg.Command != "" {
|
||||
cmd := exec.Command(cfg.Command, cfg.Args...)
|
||||
cmd := process.Command(context.Background(), cfg.Command, cfg.Args...)
|
||||
cmd.Env = mergeEnv(os.Environ(), cfg.Env)
|
||||
return &sdk.CommandTransport{Command: cmd}, nil
|
||||
return &managedCommandTransport{CommandTransport: sdk.CommandTransport{Command: cmd, TerminateDuration: 250 * time.Millisecond}}, nil
|
||||
}
|
||||
return &sdk.StreamableClientTransport{
|
||||
Endpoint: cfg.URL,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"sync"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/sausheong/harness/process"
|
||||
)
|
||||
|
||||
type managedCommandTransport struct{ sdk.CommandTransport }
|
||||
|
||||
func (t *managedCommandTransport) Connect(ctx context.Context) (sdk.Connection, error) {
|
||||
conn, err := t.CommandTransport.Connect(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &managedCommandConnection{Connection: conn, command: t.Command}, nil
|
||||
}
|
||||
|
||||
type managedCommandConnection struct {
|
||||
sdk.Connection
|
||||
command *exec.Cmd
|
||||
once sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
func (c *managedCommandConnection) Close() error {
|
||||
c.once.Do(func() {
|
||||
// Let the SDK close stdin and join the server first, then remove any
|
||||
// descendants it left behind. WaitDelay bounds inherited-pipe draining.
|
||||
c.closeErr = c.Connection.Close()
|
||||
if err := process.KillGroup(c.command); c.closeErr == nil {
|
||||
c.closeErr = err
|
||||
}
|
||||
})
|
||||
return c.closeErr
|
||||
}
|
||||
Reference in new issue
Block a user