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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user