Harden Harness runtime, persistence and execution for Hand

This commit is contained in:
sausheong committed 2026-09-09 22:55:55 +08:00
1 parent 09c30fe2d5
commit 0972eed3ea
164 files changed
+15912 -506

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
package process
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Read verifies a completed artifact within this store. It never follows paths
// supplied by output prose. Missing/expired, active, corrupt or legacy unverified
// artifacts fail explicitly. Truncated describes capture completeness separately
// from integrity: the verified captured prefix may still be read.
func (s *ArtifactStore) Read(ctx context.Context, info ArtifactInfo) ([]byte, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
digest, err := hex.DecodeString(info.SHA256)
if err != nil || len(digest) != sha256.Size || info.Bytes < 0 || info.Bytes > ArtifactFileLimit || info.Error != "" {
return nil, errors.New("artifact has no valid completed integrity record")
}
rel, err := filepath.Rel(s.dir, info.Path)
if err != nil || filepath.Base(rel) != rel || !strings.HasPrefix(rel, "output-") || !strings.HasSuffix(rel, ".log") {
return nil, errors.New("artifact is outside this store")
}
root, err := os.OpenRoot(s.dir)
if err != nil {
return nil, err
}
defer root.Close()
before, err := root.Lstat(rel)
if err != nil {
return nil, err
}
if !before.Mode().IsRegular() {
return nil, errors.New("artifact is not a regular file")
}
f, err := root.OpenFile(rel, artifactReadFlags(), 0)
if err != nil {
return nil, err
}
defer f.Close()
if err := lockArtifact(f, true); err != nil {
return nil, fmt.Errorf("artifact is active or unavailable: %w", err)
}
stat, err := f.Stat()
if err != nil {
return nil, err
}
if !stat.Mode().IsRegular() || stat.Mode().Perm()&0077 != 0 || stat.Size() != info.Bytes {
return nil, errors.New("artifact size or permissions changed")
}
data := make([]byte, 0, int(info.Bytes))
buf := make([]byte, 32<<10)
for {
if err := ctx.Err(); err != nil {
return nil, err
}
n, readErr := f.Read(buf)
if int64(len(data)+n) > info.Bytes {
return nil, errors.New("artifact grew during read")
}
data = append(data, buf[:n]...)
if readErr == io.EOF {
break
}
if readErr != nil {
return nil, readErr
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
actual := sha256.Sum256(data)
if int64(len(data)) != info.Bytes || hex.EncodeToString(actual[:]) != strings.ToLower(info.SHA256) {
return nil, errors.New("artifact integrity mismatch")
}
return data, nil
}
+84
View File
@@ -0,0 +1,84 @@
//go:build unix
package process
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
)
func TestArtifactReadVerifiedAndTampered(t *testing.T) {
store := testStore(t)
capture := store.Capture(4)
data := bytes.Repeat([]byte("captured output\n"), 100)
capture.Write(data)
if _, err := store.Read(context.Background(), capture.Info()); err == nil {
t.Fatal("active unfinalised capture accepted")
}
if err := capture.Close(); err != nil {
t.Fatal(err)
}
info := capture.Info()
got, err := store.Read(context.Background(), info)
if err != nil || !bytes.Equal(got, data) || len(info.SHA256) != 64 {
t.Fatal("verified artifact unavailable", err)
}
tampered := bytes.Repeat([]byte("x"), len(data))
if err := os.WriteFile(info.Path, tampered, 0600); err != nil {
t.Fatal(err)
}
if _, err := store.Read(context.Background(), info); err == nil {
t.Fatal("same-size tampering accepted")
}
if err := os.Remove(info.Path); err != nil {
t.Fatal(err)
}
if _, err := store.Read(context.Background(), info); !os.IsNotExist(err) {
t.Fatal("missing artifact not reported", err)
}
}
func TestArtifactReadScopeLockAndCancellation(t *testing.T) {
store := testStore(t)
capture := store.Capture(1)
capture.Write([]byte("complete output"))
capture.Close()
info := capture.Info()
outside := info
outside.Path = filepath.Join(t.TempDir(), filepath.Base(info.Path))
if _, err := store.Read(context.Background(), outside); err == nil {
t.Fatal("outside path accepted")
}
link := filepath.Join(store.dir, "output-link.log")
if err := os.Symlink(info.Path, link); err != nil {
t.Fatal(err)
}
alias := info
alias.Path = link
if _, err := store.Read(context.Background(), alias); err == nil {
t.Fatal("symlink accepted")
}
file, err := os.OpenFile(info.Path, os.O_RDWR, 0)
if err != nil {
t.Fatal(err)
}
if err := lockArtifact(file, false); err != nil {
t.Fatal(err)
}
if _, err := store.Read(context.Background(), info); err == nil {
t.Fatal("locked artifact accepted")
}
file.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := store.Read(ctx, info); err != context.Canceled {
t.Fatal(err)
}
legacy := info
legacy.SHA256 = ""
if _, err := store.Read(context.Background(), legacy); err == nil {
t.Fatal("unverified legacy record accepted")
}
}
+216
View File
@@ -0,0 +1,216 @@
package process
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"hash"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
const ArtifactFileLimit int64 = 8 << 20
const ArtifactStoreLimit int64 = 64 << 20
const ArtifactRetention = 24 * time.Hour
// ArtifactStore owns a private directory used only for command output. Each
// active capture reserves one full file allowance. Advisory file locks protect
// active files across cooperating processes; old completed files are evicted
// oldest first. Retention is enforced when a new artifact is allocated.
type ArtifactStore struct{ dir string }
func NewArtifactStore(dir string) (*ArtifactStore, error) {
abs, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
if err = os.MkdirAll(abs, 0700); err != nil {
return nil, err
}
info, err := os.Lstat(abs)
if err != nil {
return nil, err
}
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
return nil, errors.New("artifact directory must be a private directory (0700)")
}
return &ArtifactStore{dir: abs}, nil
}
func (s *ArtifactStore) allocate() (*os.File, string, error) {
root, err := os.OpenRoot(s.dir)
if err != nil {
return nil, "", err
}
defer root.Close()
guard, err := root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return nil, "", err
}
defer guard.Close()
if err = lockArtifact(guard, false); err != nil {
return nil, "", err
}
names, err := fs.ReadDir(root.FS(), ".")
if err != nil {
return nil, "", err
}
type candidate struct {
name string
modified time.Time
}
var files []candidate
for _, e := range names {
if !strings.HasPrefix(e.Name(), "output-") {
continue
}
info, err := e.Info()
if err != nil {
return nil, "", err
}
if !info.Mode().IsRegular() || info.Size() > ArtifactFileLimit {
return nil, "", errors.New("invalid output artifact in store")
}
files = append(files, candidate{e.Name(), info.ModTime()})
}
sort.Slice(files, func(i, j int) bool { return files[i].modified.Before(files[j].modified) })
count := len(files)
for _, f := range files {
expired := time.Since(f.modified) > ArtifactRetention
if !expired && int64(count+1)*ArtifactFileLimit <= ArtifactStoreLimit {
continue
}
file, err := root.OpenFile(f.name, os.O_RDWR, 0)
if err != nil {
return nil, "", err
}
err = lockArtifact(file, true)
if artifactBusy(err) {
file.Close()
continue
}
if err != nil {
file.Close()
return nil, "", err
}
err = root.Remove(f.name)
file.Close()
if err != nil {
return nil, "", err
}
count--
}
if int64(count+1)*ArtifactFileLimit > ArtifactStoreLimit {
return nil, "", errors.New("output artifact quota occupied by active captures")
}
name := "output-" + rand.Text() + ".log"
file, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
if err != nil {
return nil, "", err
}
if err = lockArtifact(file, false); err != nil {
file.Close()
root.Remove(name)
return nil, "", err
}
return file, filepath.Join(s.dir, name), nil
}
// OutputCapture drains every byte, retains a bounded memory prefix, and spills
// output exceeding that prefix into an artifact with an independent disk cap.
// Call Close after the subprocess joins, before consuming Info. Write errors
// are recorded instead of stopping the drain and changing subprocess behaviour.
type OutputCapture struct {
mu sync.Mutex
prefix *Capture
store *ArtifactStore
file *os.File
info ArtifactInfo
closed bool
digest hash.Hash
}
type ArtifactInfo struct {
SHA256 string `json:"sha256,omitempty"`
Path string `json:"path,omitempty"`
Bytes int64 `json:"bytes"`
Truncated bool `json:"truncated"`
Error string `json:"error,omitempty"`
}
func (s *ArtifactStore) Capture(memoryLimit int) *OutputCapture {
return &OutputCapture{store: s, prefix: NewCapture(memoryLimit), digest: sha256.New()}
}
func (c *OutputCapture) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return 0, os.ErrClosed
}
var before string
if c.file == nil && c.info.Error == "" {
_, retained, limit := c.prefix.stats()
if len(p) > limit-retained {
before, _, _ = c.prefix.Snapshot()
}
}
c.prefix.Write(p)
total, retained, _ := c.prefix.stats()
truncated := total > int64(retained)
if truncated && c.file == nil && c.info.Error == "" {
f, path, err := c.store.allocate()
if err != nil {
c.info.Error = err.Error()
} else {
c.file = f
c.info.Path = path
c.writeDisk([]byte(before))
}
}
if c.file != nil {
c.writeDisk(p)
}
c.info.Truncated = truncated && (c.info.Bytes < total)
return len(p), nil
}
func (c *OutputCapture) writeDisk(p []byte) {
if c.info.Error != "" {
return
}
keep := min(int64(len(p)), ArtifactFileLimit-c.info.Bytes)
n, err := c.file.Write(p[:int(keep)])
c.info.Bytes += int64(n)
c.digest.Write(p[:n])
if err == nil && int64(n) != keep {
err = errors.New("short artifact write")
}
if err != nil {
c.info.Error = fmt.Sprintf("capture output: %v", err)
}
}
func (c *OutputCapture) Snapshot() (string, int64, bool) { return c.prefix.Snapshot() }
func (c *OutputCapture) Info() ArtifactInfo { c.mu.Lock(); defer c.mu.Unlock(); return c.info }
func (c *OutputCapture) Close() error {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return nil
}
c.closed = true
if c.file == nil {
return nil
}
err := errors.Join(c.file.Sync(), c.file.Close())
c.info.SHA256 = fmt.Sprintf("%x", c.digest.Sum(nil))
if err != nil {
c.info.Error = err.Error()
}
return err
}
+15
View File
@@ -0,0 +1,15 @@
//go:build !unix
package process
import (
"errors"
"os"
)
func lockArtifact(_ *os.File, _ bool) error {
return errors.New("output artifact locking is unsupported on this platform")
}
func artifactBusy(_ error) bool { return false }
func artifactReadFlags() int { return os.O_RDONLY }
+182
View File
@@ -0,0 +1,182 @@
//go:build unix
package process
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
"time"
)
func testStore(t *testing.T) *ArtifactStore {
t.Helper()
dir := filepath.Join(t.TempDir(), "output")
s, err := NewArtifactStore(dir)
if err != nil {
t.Fatal(err)
}
return s
}
func TestArtifactSpillExactAndCap(t *testing.T) {
s := testStore(t)
c := s.Capture(7)
for _, p := range []string{"abc", "def", "ghij", "klmnop"} {
c.Write([]byte(p))
}
c.Close()
info := c.Info()
raw, err := os.ReadFile(info.Path)
if err != nil || string(raw) != "abcdefghijklmnop" || info.Bytes != 16 || info.Truncated || info.Error != "" {
t.Fatalf("%q %+v %v", raw, info, err)
}
stat, _ := os.Stat(info.Path)
if stat.Mode().Perm() != 0600 {
t.Fatal(stat.Mode())
}
capped := s.Capture(4)
block := bytes.Repeat([]byte("z"), 1<<20)
for range 10 {
capped.Write(block)
}
capped.Close()
info = capped.Info()
stat, err = os.Stat(info.Path)
if err != nil || stat.Size() != ArtifactFileLimit || info.Bytes != ArtifactFileLimit || !info.Truncated {
t.Fatalf("%+v %v", info, err)
}
prefix, total, truncated := capped.Snapshot()
if prefix != "zzzz" || total != 10<<20 || !truncated {
t.Fatalf("%q %d %v", prefix, total, truncated)
}
}
func TestArtifactQuotaProtectsActiveAndEvictsCompleted(t *testing.T) {
s := testStore(t)
var active []*OutputCapture
for range 8 {
c := s.Capture(1)
c.Write([]byte("abc"))
if c.Info().Error != "" {
t.Fatal(c.Info())
}
active = append(active, c)
defer c.Close()
}
// A separate store instance must obey the same active-file reservations.
other, err := NewArtifactStore(s.dir)
if err != nil {
t.Fatal(err)
}
full := other.Capture(1)
full.Write([]byte("abc"))
full.Close()
if full.Info().Error == "" || !full.Info().Truncated || full.Info().Path != "" {
t.Fatal(full.Info())
}
old := active[0].Info().Path
active[0].Close()
next := other.Capture(1)
next.Write([]byte("abc"))
defer next.Close()
if next.Info().Error != "" {
t.Fatal(next.Info())
}
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Fatalf("completed artifact not evicted: %v", err)
}
for _, c := range active[1:] {
if _, err := os.Stat(c.Info().Path); err != nil {
t.Fatal("active artifact evicted", err)
}
}
}
func TestArtifactRetentionAndPrivateDirectory(t *testing.T) {
s := testStore(t)
c := s.Capture(1)
c.Write([]byte("abc"))
c.Close()
old := c.Info().Path
expired := time.Now().Add(-ArtifactRetention - time.Hour)
if err := os.Chtimes(old, expired, expired); err != nil {
t.Fatal(err)
}
next := s.Capture(1)
next.Write([]byte("abc"))
next.Close()
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Fatalf("expired artifact remains: %v", err)
}
small := s.Capture(10)
small.Write([]byte("abc"))
small.Close()
if small.Info().Path != "" || small.Info().Truncated {
t.Fatal(small.Info())
}
if _, err := small.Write([]byte("x")); err == nil {
t.Fatal("write after close succeeded")
}
if err := os.Chmod(s.dir, 0755); err != nil {
t.Fatal(err)
}
if _, err := NewArtifactStore(s.dir); err == nil {
t.Fatal("public directory accepted")
}
}
func TestArtifactCrossProcessReservation(t *testing.T) {
if dir := os.Getenv("HARNESS_ARTIFACT_QUOTA_FIXTURE"); dir != "" {
s, err := NewArtifactStore(dir)
if err != nil {
t.Fatal(err)
}
c := s.Capture(1)
c.Write([]byte("abc"))
c.Close()
if c.Info().Error == "" || c.Info().Path != "" {
t.Fatal("child bypassed active reservations", c.Info())
}
return
}
s := testStore(t)
for range 8 {
c := s.Capture(1)
c.Write([]byte("abc"))
defer c.Close()
if c.Info().Error != "" {
t.Fatal(c.Info())
}
}
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := Command(ctx, exe, "-test.run=^TestArtifactCrossProcessReservation$")
cmd.Env = append(os.Environ(), "HARNESS_ARTIFACT_QUOTA_FIXTURE="+s.dir, "GORACE=atexit_sleep_ms=0")
var output bytes.Buffer
cmd.Stdout = &output
cmd.Stderr = &output
if err := Run(cmd); err != nil {
t.Fatalf("child quota check: %v %s", err, output.String())
}
}
func TestArtifactAllocationFailureStillDrains(t *testing.T) {
s := testStore(t)
if err := os.Mkdir(filepath.Join(s.dir, ".lock"), 0700); err != nil {
t.Fatal(err)
}
c := s.Capture(2)
n, err := c.Write([]byte("abcdef"))
c.Close()
if n != 6 || err != nil {
t.Fatalf("drain: %d %v", n, err)
}
prefix, total, truncated := c.Snapshot()
if prefix != "ab" || total != 6 || !truncated || c.Info().Error == "" || !c.Info().Truncated {
t.Fatalf("%q %d %v %+v", prefix, total, truncated, c.Info())
}
}
+20
View File
@@ -0,0 +1,20 @@
//go:build unix
package process
import (
"errors"
"os"
"syscall"
)
func lockArtifact(f *os.File, nonblocking bool) error {
flags := syscall.LOCK_EX
if nonblocking {
flags |= syscall.LOCK_NB
}
return syscall.Flock(int(f.Fd()), flags)
}
func artifactBusy(err error) bool { return errors.Is(err, syscall.EWOULDBLOCK) }
func artifactReadFlags() int { return os.O_RDONLY | syscall.O_NONBLOCK | syscall.O_NOFOLLOW }
+44
View File
@@ -0,0 +1,44 @@
package process
import "sync"
// Capture retains a bounded prefix while draining all writes. It deliberately
// does not embed a buffer: io.Copy must not bypass Write through ReaderFrom.
// The zero value drains without retaining bytes.
type Capture struct {
mu sync.Mutex
limit int
data []byte
total int64
}
func NewCapture(limit int) *Capture {
if limit < 0 {
limit = 0
}
return &Capture{limit: limit}
}
func (c *Capture) Write(p []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
n := len(p)
c.total += int64(n)
keep := min(n, c.limit-len(c.data))
c.data = append(c.data, p[:keep]...)
return n, nil
}
// Snapshot returns an independent prefix, observed byte count and truncation.
func (c *Capture) Snapshot() (string, int64, bool) {
c.mu.Lock()
defer c.mu.Unlock()
return string(c.data), c.total, c.total > int64(len(c.data))
}
// stats inspects accounting without allocating a copy of the retained bytes.
func (c *Capture) stats() (total int64, retained, limit int) {
c.mu.Lock()
defer c.mu.Unlock()
return c.total, len(c.data), c.limit
}
+41
View File
@@ -0,0 +1,41 @@
package process
import (
"bytes"
"path/filepath"
"testing"
)
func TestOutputCaptureFloodAllocationsPlateau(t *testing.T) {
store, err := NewArtifactStore(filepath.Join(t.TempDir(), "output"))
if err != nil {
t.Fatal(err)
}
capture := store.Capture(64 << 10)
defer capture.Close()
block := bytes.Repeat([]byte("x"), 32<<10)
for i := 0; i < 300; i++ {
if _, err = capture.Write(block); err != nil {
t.Fatal(err)
}
}
if info := capture.Info(); info.Bytes != ArtifactFileLimit || !info.Truncated {
t.Fatalf("disk not saturated: %+v", info)
}
allocations := testing.AllocsPerRun(100, func() {
if _, err := capture.Write(block); err != nil {
panic(err)
}
})
if allocations != 0 {
t.Fatalf("saturated capture allocates per write: %f", allocations)
}
prefix, total, truncated := capture.Snapshot()
if len(prefix) != 64<<10 || total <= 300*int64(len(block)) || !truncated {
t.Fatal("capture accounting changed")
}
t.Logf("saturated_write_allocations=%f retained_prefix_bytes=%d backing_capacity_bytes=%d", allocations, len(prefix), cap(capture.prefix.data))
if cap(capture.prefix.data) > 2*(64<<10)+8192 {
t.Fatal("capture backing storage exceeded allowance")
}
}
+40
View File
@@ -0,0 +1,40 @@
package process
import (
"io"
"strings"
"sync"
"testing"
)
func TestCaptureCopyBound(t *testing.T) {
c := NewCapture(17)
n, err := io.Copy(c, strings.NewReader(strings.Repeat("x", 1<<20)))
prefix, total, truncated := c.Snapshot()
if err != nil || n != 1<<20 || total != n || prefix != strings.Repeat("x", 17) || !truncated {
t.Fatalf("copy=%d err=%v prefix=%q total=%d truncated=%v", n, err, prefix, total, truncated)
}
}
func TestCaptureConcurrentAndEmpty(t *testing.T) {
var c Capture
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
for range 100 {
_, _ = c.Write([]byte("abc"))
c.Snapshot()
}
})
}
wg.Wait()
prefix, total, truncated := c.Snapshot()
if prefix != "" || total != 3000 || !truncated {
t.Fatalf("%q %d %v", prefix, total, truncated)
}
empty := NewCapture(10)
_, total, truncated = empty.Snapshot()
if total != 0 || truncated {
t.Fatal("empty capture marked truncated")
}
}
+28
View File
@@ -0,0 +1,28 @@
// Package process owns bounded subprocess shutdown. On Unix each command has
// its own process group. This is lifecycle management, not a security sandbox.
package process
import (
"context"
"os/exec"
"time"
)
// Command creates a command whose cancellation kills its owned process group.
// Run joins it and removes descendants left after normal exit. Callers using
// Start/Wait directly must call KillGroup when their protocol closes.
func Command(ctx context.Context, name string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, args...)
configureGroup(cmd)
cmd.Cancel = func() error { return KillGroup(cmd) }
cmd.WaitDelay = 250 * time.Millisecond
return cmd
}
func Run(cmd *exec.Cmd) error {
err := cmd.Run()
cleanupErr := KillGroup(cmd)
if err != nil {
return err
}
return cleanupErr
}
+24
View File
@@ -0,0 +1,24 @@
//go:build !unix
package process
import (
"errors"
"os"
"os/exec"
)
func configureGroup(cmd *exec.Cmd) {}
// Other platforms stop the direct child only. Process-tree guarantees apply
// to the advertised Linux/macOS backends; isolation is a separate capability.
func KillGroup(cmd *exec.Cmd) error {
if cmd.Process == nil {
return nil
}
err := cmd.Process.Kill()
if errors.Is(err, os.ErrProcessDone) {
return nil
}
return err
}
+28
View File
@@ -0,0 +1,28 @@
//go:build unix
package process
import (
"errors"
"os/exec"
"syscall"
)
func configureGroup(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} }
// KillGroup only signals the group explicitly created for this command.
func KillGroup(cmd *exec.Cmd) error {
if cmd.Process == nil {
return nil
}
var err error
if cmd.SysProcAttr != nil && cmd.SysProcAttr.Setpgid {
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
} else {
err = cmd.Process.Kill()
}
if errors.Is(err, syscall.ESRCH) {
return nil
}
return err
}
+161
View File
@@ -0,0 +1,161 @@
package process
import (
"context"
"crypto/rand"
"errors"
"io"
"os/exec"
)
const HandleInputLimit = 64 << 10
type inputWrite struct {
data []byte
done chan error
}
// Handle owns one deliberately asynchronous process group. It does not survive
// its owner context or application shutdown; callers must Close or Wait.
type Handle struct {
ID string
ctx context.Context
cancel context.CancelFunc
command *exec.Cmd
stdin io.WriteCloser
stdout, stderr *OutputCapture
input chan inputWrite
inputDone, done chan struct{}
err error
}
type HandleSnapshot struct {
ID string
Running bool
ExitCode int
Error string
Stdout, Stderr string
StdoutBytes, StderrBytes int64
StdoutTruncated, StderrTruncated bool
StdoutArtifact, StderrArtifact ArtifactInfo
}
func StartHandle(parent context.Context, store *ArtifactStore, dir, name string, args ...string) (*Handle, error) {
return startHandle(parent, store, nil, dir, name, args...)
}
// StartHandleWithEnv uses only the supplied environment, without ambient inheritance.
func StartHandleWithEnv(parent context.Context, store *ArtifactStore, env []string, dir, name string, args ...string) (*Handle, error) {
return startHandle(parent, store, append([]string{}, env...), dir, name, args...)
}
func startHandle(parent context.Context, store *ArtifactStore, env []string, dir, name string, args ...string) (*Handle, error) {
if store == nil {
return nil, errors.New("background process requires an output store")
}
ctx, cancel := context.WithCancel(parent)
cmd := Command(ctx, name, args...)
cmd.Dir = dir
cmd.Env = env
stdin, err := cmd.StdinPipe()
if err != nil {
cancel()
return nil, err
}
h := &Handle{ID: rand.Text(), ctx: ctx, cancel: cancel, command: cmd, stdin: stdin, stdout: store.Capture(64 << 10), stderr: store.Capture(64 << 10), input: make(chan inputWrite, 1), inputDone: make(chan struct{}), done: make(chan struct{})}
cmd.Stdout = h.stdout
cmd.Stderr = h.stderr
if err := cmd.Start(); err != nil {
cancel()
stdin.Close()
h.stdout.Close()
h.stderr.Close()
return nil, err
}
go h.writeInput()
go func() {
defer close(h.done)
waitErr := cmd.Wait()
cleanupErr := KillGroup(cmd)
cancel()
stdin.Close()
<-h.inputDone
h.err = errors.Join(waitErr, cleanupErr, h.stdout.Close(), h.stderr.Close())
}()
return h, nil
}
func (h *Handle) writeInput() {
defer close(h.inputDone)
for {
select {
case <-h.ctx.Done():
return
case request := <-h.input:
if err := h.ctx.Err(); err != nil {
request.done <- err
continue
}
n, err := h.stdin.Write(request.data)
if err == nil && n != len(request.data) {
err = io.ErrShortWrite
}
request.done <- err
}
}
}
// Send waits for a bounded input write. If its context is cancelled after
// admission, the owned process is cancelled because a partial write cannot be
// withdrawn safely. Successful return means the pipe accepted all bytes.
func (h *Handle) Send(ctx context.Context, data []byte) error {
if err := ctx.Err(); err != nil {
return err
}
if len(data) > HandleInputLimit {
return errors.New("process input exceeds 64 KiB")
}
request := inputWrite{data: append([]byte(nil), data...), done: make(chan error, 1)}
select {
case <-ctx.Done():
return ctx.Err()
case <-h.done:
return errors.New("process already stopped")
case <-h.ctx.Done():
return h.ctx.Err()
case h.input <- request:
}
select {
case err := <-request.done:
return err
case <-h.done:
select {
case err := <-request.done:
return err
default:
return errors.New("process stopped before input delivery completed")
}
case <-ctx.Done():
h.cancel()
<-h.done
return ctx.Err()
}
}
func (h *Handle) Cancel() { h.cancel() }
func (h *Handle) Wait() error { <-h.done; return h.err }
func (h *Handle) Close() error { h.cancel(); return h.Wait() }
func (h *Handle) Snapshot() HandleSnapshot {
s := HandleSnapshot{ID: h.ID, Running: true, ExitCode: -1}
select {
case <-h.done:
s.Running = false
if h.command.ProcessState != nil {
s.ExitCode = h.command.ProcessState.ExitCode()
}
if h.err != nil {
s.Error = h.err.Error()
}
default:
}
s.Stdout, s.StdoutBytes, s.StdoutTruncated = h.stdout.Snapshot()
s.Stderr, s.StderrBytes, s.StderrTruncated = h.stderr.Snapshot()
s.StdoutArtifact, s.StderrArtifact = h.stdout.Info(), h.stderr.Info()
return s
}
+104
View File
@@ -0,0 +1,104 @@
//go:build unix
package process
import (
"context"
"strings"
"testing"
"time"
)
func TestHandleSendReadWait(t *testing.T) {
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "read line; printf 'received:%s' \"$line\"")
if err != nil {
t.Fatal(err)
}
defer h.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err := h.Send(ctx, []byte("hello\n")); err != nil {
t.Fatal(err)
}
if err := h.Wait(); err != nil {
t.Fatal(err)
}
result := h.Snapshot()
if result.Running || result.ExitCode != 0 || result.Stdout != "received:hello" {
t.Fatal(result)
}
if err := h.Send(ctx, []byte("late")); err == nil {
t.Fatal("input accepted after exit")
}
}
func TestHandleBoundedCaptureAndOwnerCancellation(t *testing.T) {
store := testStore(t)
h, err := StartHandle(context.Background(), store, t.TempDir(), "sh", "-c", "head -c 70000 /dev/zero")
if err != nil {
t.Fatal(err)
}
defer h.Close()
if err := h.Wait(); err != nil {
t.Fatal(err)
}
result := h.Snapshot()
if len(result.Stdout) != 64<<10 || result.StdoutBytes != 70000 || !result.StdoutTruncated {
t.Fatal("capture bound failed")
}
data, err := store.Read(context.Background(), result.StdoutArtifact)
if err != nil || len(data) != 70000 {
t.Fatal("full capture unavailable", err)
}
ctx, cancel := context.WithCancel(context.Background())
server, err := StartHandle(ctx, store, t.TempDir(), "sh", "-c", "sleep 30 & wait")
if err != nil {
t.Fatal(err)
}
defer server.Close()
cancel()
done := make(chan error, 1)
go func() { done <- server.Wait() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("owned process did not stop")
}
if server.Snapshot().Running {
t.Fatal("cancelled process still running")
}
}
func TestHandleRejectsOversizedInput(t *testing.T) {
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "sleep 30")
if err != nil {
t.Fatal(err)
}
defer h.Close()
if err := h.Send(context.Background(), []byte(strings.Repeat("x", HandleInputLimit+1))); err == nil {
t.Fatal("oversized input accepted")
}
}
func TestHandleCancelledInputStopsAndJoinsProcess(t *testing.T) {
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "sleep 30")
if err != nil {
t.Fatal(err)
}
defer h.Close()
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
payload := []byte(strings.Repeat("x", HandleInputLimit))
// A process that never reads eventually fills its pipe; delivery cancellation
// must stop it rather than leave a queued or partially delivered write alive.
for i := 0; i < 32; i++ {
err = h.Send(ctx, payload)
if err != nil {
break
}
}
if err != context.DeadlineExceeded {
t.Fatal("blocked input did not observe deadline", err)
}
if h.Snapshot().Running {
t.Fatal("cancelled input returned before process joined")
}
}