Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(execd): truncate command output files before unlink (#2295)
epha17f60df98f78
diff --git a/components/execd/pkg/runtime/command_cleanup_test.go b/components/execd/pkg/runtime/command_cleanup_test.goindex 9dac5e8fa..242b8feba 100644--- a/components/execd/pkg/runtime/command_cleanup_test.go+++ b/components/execd/pkg/runtime/command_cleanup_test.go@@ -191,3 +191,50 @@ func TestCleanupFinishedCommandsRetainsRunningAndRecentCommands(t *testing.T) {require.NotNil(t, c.getCommandKernel("recent"))require.NotNil(t, c.getCommandKernel("running"))}++// TestRemoveCommandOutputFilesTruncatesBeforeUnlink verifies that removal+// releases the data blocks even when a forked child still holds the fd: the+// unlinked inode survives via the held fd, and its size must be zero after+// cleanup instead of staying allocated until the holder exits (#2291).+func TestRemoveCommandOutputFilesTruncatesBeforeUnlink(t *testing.T) {+ if goruntime.GOOS == "windows" {+ t.Skip("Windows refuses to remove a file held open without FILE_SHARE_DELETE")+ }++ tempDir := t.TempDir()+ path := filepath.Join(tempDir, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.stderr")+ require.NoError(t, os.WriteFile(path, []byte("payload the child keeps writing to"), 0o600))++ held, err := os.Open(path)+ require.NoError(t, err)+ defer held.Close()++ removeCommandOutputFiles(path)++ require.NoFileExists(t, path)+ info, err := held.Stat()+ require.NoError(t, err)+ require.Zero(t, info.Size(), "data blocks must be released while another fd still holds the file")+}++// TestRemoveCommandOutputFilesDoesNotFollowSymlink verifies the cleanup-time+// truncation cannot be redirected at an arbitrary file by swapping the entry+// for a symlink: the link is unlinked, the target's content is untouched.+func TestRemoveCommandOutputFilesDoesNotFollowSymlink(t *testing.T) {+ if goruntime.GOOS == "windows" {+ t.Skip("symlink creation requires additional privileges on Windows")+ }++ tempDir := t.TempDir()+ victim := filepath.Join(tempDir, "victim")+ require.NoError(t, os.WriteFile(victim, []byte("must-not-be-truncated"), 0o600))+ link := filepath.Join(tempDir, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.output")+ require.NoError(t, os.Symlink(victim, link))++ removeCommandOutputFiles(link)++ require.NoFileExists(t, link)+ content, err := os.ReadFile(victim)+ require.NoError(t, err)+ require.Equal(t, "must-not-be-truncated", string(content))+}diff --git a/components/execd/pkg/runtime/command_common.go b/components/execd/pkg/runtime/command_common.goindex 4c15f2921..ed2344397 100644--- a/components/execd/pkg/runtime/command_common.go+++ b/components/execd/pkg/runtime/command_common.go@@ -124,6 +124,18 @@ func removeCommandOutputFiles(paths ...string) {continue}seen[path] = struct{}{}+ // Truncate before unlinking: forked children may outlive the command+ // while still holding the output fd, so the unlinked inode's data+ // blocks would stay allocated (invisible "(deleted)" growth) until the+ // last holder exits. Truncation releases them immediately, without+ // needing to track or kill grandchildren. The helper never follows+ // symlinks: a workload can swap the entry between a directory scan and+ // this call, and a following truncate would zero an arbitrary file+ // where the remove below would only unlink the link.+ // See opensandbox-group/OpenSandbox#2291.+ if err := truncateCommandOutputFile(path); err != nil && !os.IsNotExist(err) {+ log.Warn("command output: truncate %s: %v", path, err)+ }if err := os.Remove(path); err != nil && !os.IsNotExist(err) {log.Warn("command output: remove %s: %v", path, err)}diff --git a/components/execd/pkg/runtime/command_output_unix.go b/components/execd/pkg/runtime/command_output_unix.goindex c86e01fb4..7dfa6c75e 100644--- a/components/execd/pkg/runtime/command_output_unix.go+++ b/components/execd/pkg/runtime/command_output_unix.go@@ -17,6 +17,7 @@package runtimeimport (+ "errors""fmt""os""path/filepath"@@ -62,6 +63,41 @@ func openNewCommandOutput(path string) (*os.File, error) {return file, nil}+// truncateCommandOutputFile releases the file's data blocks through a+// descriptor opened without following symlinks: cleanup runs on paths a+// sandbox workload can race with, and a truncate that follows a symlink swap+// would zero an arbitrary file where os.Remove alone would only remove the+// link. O_NONBLOCK keeps a FIFO swap from blocking the open, and the+// descriptor is verified to be a regular file before truncating; anything+// else (symlink, FIFO, socket) is skipped, leaving the entry to the unlink.+// Hard links are skipped for the same reason: with Nlink > 1 the inode's+// content is still visible through other names, and truncating would clear+// data this name's deletion was never meant to touch. An fd held open by a+// forked child does not raise Nlink, so the reclaim behavior for ordinary+// command output files is unaffected.+func truncateCommandOutputFile(path string) error {+ fd, err := unix.Open(path, unix.O_WRONLY|unix.O_NONBLOCK|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)+ if err != nil {+ if errors.Is(err, unix.ELOOP) || errors.Is(err, unix.ENXIO) {+ return nil+ }+ return err+ }+ defer unix.Close(fd) //nolint:errcheck++ var stat unix.Stat_t+ if err := unix.Fstat(fd, &stat); err != nil {+ return err+ }+ if stat.Mode&unix.S_IFMT != unix.S_IFREG {+ return nil+ }+ if stat.Nlink > 1 {+ return nil+ }+ return unix.Ftruncate(fd, 0)+}+func openCommandOutputForRead(path string) (*os.File, error) {fd, err := unix.Open(path, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)if err != nil {diff --git a/components/execd/pkg/runtime/command_output_unix_test.go b/components/execd/pkg/runtime/command_output_unix_test.gonew file mode 100644index 000000000..66ae2e27d--- /dev/null+++ b/components/execd/pkg/runtime/command_output_unix_test.go@@ -0,0 +1,67 @@+// Copyright 2026 The OpenSandbox Authors+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++//go:build !windows++package runtime++import (+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+ "golang.org/x/sys/unix"+)++// TestRemoveCommandOutputFilesSkipsFifo verifies a FIFO swap cannot stall the+// janitor: the open must not wait for a reader, the non-regular entry is not+// truncated, and the unlink still proceeds.+func TestRemoveCommandOutputFilesSkipsFifo(t *testing.T) {+ tempDir := t.TempDir()+ fifo := filepath.Join(tempDir, "cccccccccccccccccccccccccccccccc.output")+ require.NoError(t, unix.Mkfifo(fifo, 0o600))++ done := make(chan struct{})+ go func() {+ removeCommandOutputFiles(fifo)+ close(done)+ }()+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("removeCommandOutputFiles blocked on a FIFO entry")+ }+ require.NoFileExists(t, fifo)+}++// TestRemoveCommandOutputFilesKeepsHardLinkContent verifies a hard-linked+// entry is only unlinked: with Nlink > 1 the inode's content must stay+// reachable through the other name instead of being truncated through the+// shared inode.+func TestRemoveCommandOutputFilesKeepsHardLinkContent(t *testing.T) {+ tempDir := t.TempDir()+ kept := filepath.Join(tempDir, "kept")+ entry := filepath.Join(tempDir, "dddddddddddddddddddddddddddddddd.output")+ require.NoError(t, os.WriteFile(entry, []byte("shared-inode-content"), 0o600))+ require.NoError(t, os.Link(entry, kept))++ removeCommandOutputFiles(entry)++ require.NoFileExists(t, entry)+ content, err := os.ReadFile(kept)+ require.NoError(t, err)+ require.Equal(t, "shared-inode-content", string(content))+}diff --git a/components/execd/pkg/runtime/command_output_windows.go b/components/execd/pkg/runtime/command_output_windows.goindex 74d3afd81..776b1e14e 100644--- a/components/execd/pkg/runtime/command_output_windows.go+++ b/components/execd/pkg/runtime/command_output_windows.go@@ -19,6 +19,8 @@ package runtimeimport ("fmt""os"++ "golang.org/x/sys/windows")func ensurePrivateCommandOutputDir(path string) error {@@ -43,6 +45,45 @@ func openNewCommandOutput(path string) (*os.File, error) {return file, nil}+// truncateCommandOutputFile releases the file's data blocks through a write+// handle instead of a path-based truncate, so a path swapped mid-cleanup is+// never truncated after being re-resolved. The handle is opened with+// FILE_FLAG_OPEN_REPARSE_POINT so it stays on the entry itself instead of+// resolving a symlink swap to its target; an entry carrying a reparse point+// (name surrogate or otherwise) is skipped and left to the unlink, as is any+// other non-regular file.+func truncateCommandOutputFile(path string) error {+ pathp, err := windows.UTF16PtrFromString(path)+ if err != nil {+ return err+ }+ handle, err := windows.CreateFile(pathp,+ windows.GENERIC_WRITE,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,+ nil,+ windows.OPEN_EXISTING,+ windows.FILE_FLAG_OPEN_REPARSE_POINT,+ 0)+ if err != nil {+ return err+ }++ var info windows.ByHandleFileInformation+ if err := windows.GetFileInformationByHandle(handle, &info); err != nil {+ _ = windows.CloseHandle(handle)+ return err+ }+ if info.FileAttributes&windows.FILE_ATTRIBUTE_REPARSE_POINT != 0 ||+ info.FileAttributes&windows.FILE_ATTRIBUTE_DIRECTORY != 0 {+ _ = windows.CloseHandle(handle)+ return nil+ }++ file := os.NewFile(uintptr(handle), path)+ defer file.Close() //nolint:errcheck+ return file.Truncate(0)+}+func openCommandOutputForRead(path string) (*os.File, error) {file, err := os.Open(path)if err != nil {