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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions internal/repository/mutation.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,15 +96,19 @@ type MutationReceipt struct {
// hardened environment. The closed argv templates make arbitrary git
// invocation impossible.
type MutationExecutor struct {
gitPath string
gitPath string
maxDuration time.Duration
commandContext func(context.Context, string, ...string) *exec.Cmd
}

func NewMutationExecutor() (*MutationExecutor, error) {
path, err := exec.LookPath("git")
if err != nil {
return nil, fmt.Errorf("git binary is unavailable: %w", err)
}
return &MutationExecutor{gitPath: path}, nil
return &MutationExecutor{
gitPath: path, maxDuration: MaxGitDuration, commandContext: exec.CommandContext,
}, nil
}

func (e *MutationExecutor) Available() bool { return e != nil && e.gitPath != "" }
Expand Down Expand Up @@ -205,6 +209,10 @@ func (e *MutationExecutor) Execute(ctx context.Context, root string, spec Mutati
return receipt, apperror.New(apperror.CodeFailedPrecondition,
"git mutation failed: "+strings.TrimSpace(boundedOutput(stderr)))
}
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
return receipt, apperror.New(apperror.CodeDeadlineExceeded,
"git mutation exceeded its duration bound")
}
if err != nil && ctx.Err() == nil {
return receipt, apperror.Wrap(apperror.CodeFailedPrecondition,
"git mutation failed: "+strings.TrimSpace(boundedOutput(stderr)), err)
Expand Down Expand Up @@ -234,17 +242,25 @@ func (e *MutationExecutor) runGit(ctx context.Context, root string, spec Mutatio
if err != nil {
return "", "", 0, err
}
command := exec.CommandContext(ctx, e.gitPath, args...)
duration := e.maxDuration
if duration <= 0 {
duration = MaxGitDuration
}
commandCtx, cancel := context.WithTimeout(ctx, duration)
defer cancel()
commandContext := e.commandContext
if commandContext == nil {
commandContext = exec.CommandContext
}
command := commandContext(commandCtx, e.gitPath, args...)
command.Dir = root
command.Env = hardenedGitEnvironment()
var stdout, stderr boundedBuffer
command.Stdout = &stdout
command.Stderr = &stderr
started := time.Now()
err = command.Run()
if time.Since(started) > MaxGitDuration && ctx.Err() == nil {
_ = command.Process.Kill()
return stdout.String(), stderr.String(), 0, errors.New("git mutation exceeded its duration bound")
if commandErr := commandCtx.Err(); commandErr != nil {
return stdout.String(), stderr.String(), 0, commandErr
}
if err != nil {
var exitErr *exec.ExitError
Expand Down
77 changes: 77 additions & 0 deletions internal/repository/mutation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ package repository

import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"

"cyberagent-workbench/internal/apperror"
)
Expand Down Expand Up @@ -226,3 +228,78 @@ func TestMutationCreateAndSwitchBranch(t *testing.T) {
t.Fatalf("branch did not switch: %q", current)
}
}

func TestMutationRunGitEnforcesDurationBound(t *testing.T) {
executor := blockingMutationExecutor(50 * time.Millisecond)
started := time.Now()
_, _, _, err := executor.runGit(t.Context(), t.TempDir(), MutationSpec{
ProtocolVersion: MutationProtocolVersion, Operation: MutationStage,
Paths: []string{"file.txt"},
})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("git mutation timeout was not enforced: %v", err)
}
if elapsed := time.Since(started); elapsed > 2*time.Second {
t.Fatalf("git mutation exceeded the injected duration bound: %s", elapsed)
}
}

func TestMutationRunGitPreservesCallerCancellation(t *testing.T) {
executor := blockingMutationExecutor(time.Minute)
ctx, cancel := context.WithCancel(t.Context())
timer := time.AfterFunc(50*time.Millisecond, cancel)
defer timer.Stop()
_, _, _, err := executor.runGit(ctx, t.TempDir(), MutationSpec{
ProtocolVersion: MutationProtocolVersion, Operation: MutationStage,
Paths: []string{"file.txt"},
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("caller cancellation was not preserved: %v", err)
}
}

func TestMutationExecuteReportsDurationDeadline(t *testing.T) {
root := newMutationRepo(t)
executor := newExecutor(t)
executor.maxDuration = 50 * time.Millisecond
executor.commandContext = blockingMutationCommand
if err := os.WriteFile(filepath.Join(root, "slow.txt"), []byte("slow\n"), 0o600); err != nil {
t.Fatal(err)
}
spec := MutationSpec{ProtocolVersion: MutationProtocolVersion,
Operation: MutationStage, Paths: []string{"slow.txt"}}
binding, err := executor.CaptureBinding(t.Context(), root)
if err != nil {
t.Fatal(err)
}
_, err = executor.Execute(t.Context(), root, spec, binding)
if apperror.CodeOf(err) != apperror.CodeDeadlineExceeded {
t.Fatalf("duration bound did not surface as deadline exceeded: %v", err)
}
}

func blockingMutationExecutor(duration time.Duration) *MutationExecutor {
return &MutationExecutor{
gitPath: os.Args[0], maxDuration: duration,
commandContext: blockingMutationCommand,
}
}

func blockingMutationCommand(ctx context.Context, _ string, _ ...string) *exec.Cmd {
return exec.CommandContext(ctx, os.Args[0],
"-test.run=^TestMutationGitHelperProcess$", "--", "mutation-git-helper")
}

func TestMutationGitHelperProcess(t *testing.T) {
helper := false
for _, argument := range os.Args {
if argument == "mutation-git-helper" {
helper = true
break
}
}
if !helper {
return
}
time.Sleep(10 * time.Second)
}