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
41 changes: 34 additions & 7 deletions internal/tools/file_commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ var fileWriteRename = func(root *os.Root, oldName, newName string) error {
return root.Rename(oldName, newName)
}

// fileWriteCaptureSecurity and fileWriteApplySecurity carry the replaced file's
// access control to the file that takes its name. Tests replace them to
// exercise a failure at either step.
var (
fileWriteCaptureSecurity = captureFileSecurity
fileWriteApplySecurity = applyFileSecurity
)

// fileWriteNoReplaceRename publishes a create without replacing an existing
// name. Tests replace it to exercise the hard-link fallback that filesystems
// without a no-replace rename use.
Expand Down Expand Up @@ -156,10 +164,20 @@ func commitRootedFileContents(root *os.Root, absolutePath, relativePath string,
return fmt.Errorf("%w: link target changed", errFileChangedDuringWrite)
}
}
// The side file is created fresh and would publish with the directory's
// inherited access control. Read what the observed file carries while its
// validated handle is still open, so the file that takes its name keeps
// it. A list that cannot be read cannot be carried, and replacing the file
// anyway would reset it, so that refuses the write.
security, securityErr := fileWriteCaptureSecurity(file)
if securityErr != nil {
_ = file.Close()
return fmt.Errorf("writing %s: %w", relativePath, securityErr)
}
if err := file.Close(); err != nil {
return err
}
return commitRootedFileOverwrite(root, absolutePath, relativePath, publishPath, openedInfo, mode, content)
return commitRootedFileOverwrite(root, absolutePath, relativePath, publishPath, openedInfo, mode, security, content)
}

// commitRootedFileCreate publishes a brand-new file whose absence the caller
Expand All @@ -168,7 +186,7 @@ func commitRootedFileContents(root *os.Root, absolutePath, relativePath string,
// either absent or the whole file, a concurrent create is refused rather than
// replaced, and a write that cannot complete leaves no file at all.
func commitRootedFileCreate(root *os.Root, relativePath, content string) error {
tempName, err := writeRootedSideFile(root, relativePath, 0o644, true, content)
tempName, err := writeRootedSideFile(root, relativePath, 0o644, true, nil, content)
if err != nil {
return err
}
Expand Down Expand Up @@ -244,8 +262,8 @@ func renameNoReplaceUnsupported(err error) bool {
// Refused renames fail without mutating the observed inode. Writing in place
// here would expose partial content and rewrite hard-link siblings, defeating
// the guarantees that staging provides.
func commitRootedFileOverwrite(root *os.Root, absolutePath, relativePath, publishPath string, openedInfo os.FileInfo, mode os.FileMode, content string) error {
tempName, err := writeRootedSideFile(root, publishPath, mode, false, content)
func commitRootedFileOverwrite(root *os.Root, absolutePath, relativePath, publishPath string, openedInfo os.FileInfo, mode os.FileMode, security *fileSecurity, content string) error {
tempName, err := writeRootedSideFile(root, publishPath, mode, false, security, content)
if err != nil {
return err
}
Expand Down Expand Up @@ -312,13 +330,15 @@ func resolveRootedFinalPath(root *os.Root, relativePath string) (string, error)
// 0o644 and remembers what the process umask actually granted; the bytes are
// made owner-only while they are staged, then the granted bits are restored.
// An overwrite stages 0o600 and finally carries the observed file's permission
// bits over, so the published file looks like the one it replaced.
func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, umaskDerived bool, content string) (string, error) {
// bits over, so the published file looks like the one it replaced. It also
// carries security, the replaced file's access control, when there is any: a
// create passes nil and keeps what the directory gives a new file.
func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, umaskDerived bool, security *fileSecurity, content string) (string, error) {
createMode := mode.Perm()
if !umaskDerived {
createMode = 0o600
}
temp, tempName, err := pathjail.CreateTempMode(root, filepath.Dir(relativePath), "zero-write", ".tmp", createMode)
temp, tempName, err := createSideFile(root, relativePath, createMode, security)
if err != nil {
return "", fmt.Errorf("writing %s: %w", relativePath, err)
}
Expand All @@ -338,6 +358,13 @@ func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, u
}
}
writeErr := func() error {
// The side file was created with the directory's access control. It is
// given the replaced file's before any byte is written, while it is still
// empty: applied afterwards, the replacement would sit readable by
// everyone the directory admits until the list landed.
if err := fileWriteApplySecurity(temp, security); err != nil {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return err
}
if err := fileWriteTempWrite(temp, content); err != nil {
return err
}
Expand Down
27 changes: 27 additions & 0 deletions internal/tools/file_commit_security_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//go:build !windows

package tools

import (
"os"
"path/filepath"

"github.com/Twigpine/zero/internal/pathjail"
)

// fileSecurity is the access control an overwrite carries from the file it
// replaces. Only Windows has anything to carry here: elsewhere the permission
// bits are the access control this package preserves, and the staged file is
// given them directly.
type fileSecurity struct{}

func captureFileSecurity(*os.File) (*fileSecurity, error) { return nil, nil }

func applyFileSecurity(*os.File, *fileSecurity) error { return nil }

// createSideFile creates the side file an overwrite or a create stages its
// bytes in. The mode is the kernel's exclusive-create mode, so an overwrite's
// side file is owner-only from the moment it exists.
func createSideFile(root *os.Root, relativePath string, mode os.FileMode, _ *fileSecurity) (*os.File, string, error) {
return pathjail.CreateTempMode(root, filepath.Dir(relativePath), "zero-write", ".tmp", mode)
}
119 changes: 119 additions & 0 deletions internal/tools/file_commit_security_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package tools

import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
)

func installFileWriteSecurity(t *testing.T, capture func(*os.File) (*fileSecurity, error), apply func(*os.File, *fileSecurity) error) {
t.Helper()
priorCapture, priorApply := fileWriteCaptureSecurity, fileWriteApplySecurity
if capture != nil {
fileWriteCaptureSecurity = capture
}
if apply != nil {
fileWriteApplySecurity = apply
}
t.Cleanup(func() { fileWriteCaptureSecurity, fileWriteApplySecurity = priorCapture, priorApply })
}

// AN OVERWRITE THAT CANNOT CARRY THE FILE'S ACCESS CONTROL DOES NOT HAPPEN.
//
// The overwrite replaces the file with a freshly created one, and a fresh file
// has whatever the directory gives it. If the original's access control cannot
// be read, or cannot be put on the staged file, publishing anyway would quietly
// widen who can read a file its owner had locked down. Both failures therefore
// refuse the write, leave the observed bytes standing, and remove the side
// file. These run on every platform: the seams are the same everywhere, and
// only what the production functions do behind them differs.
func TestOverwriteRefusesWhenAccessControlCannotBeCarried(t *testing.T) {
failure := errors.New("injected access control failure")
for _, testCase := range []struct {
name string
capture func(*os.File) (*fileSecurity, error)
apply func(*os.File, *fileSecurity) error
}{
{name: "reading it fails", capture: func(*os.File) (*fileSecurity, error) { return nil, failure }},
{name: "applying it fails", apply: func(*os.File, *fileSecurity) error { return failure }},
} {
t.Run(testCase.name, func(t *testing.T) {
root := t.TempDir()
target := filepath.Join(root, "existing.txt")
if err := os.WriteFile(target, []byte("observed\n"), 0o644); err != nil {
t.Fatal(err)
}
workspace, err := os.OpenRoot(root)
if err != nil {
t.Fatal(err)
}
defer workspace.Close()
info, err := os.Stat(target)
if err != nil {
t.Fatal(err)
}
preimage := "observed\n"
installFileWriteSecurity(t, testCase.capture, testCase.apply)

err = commitRootedFileContents(workspace, target, "existing.txt", info, &preimage, "replacement\n")
if !errors.Is(err, failure) {
t.Fatalf("commit error = %v, want the injected access control failure", err)
}
got, readErr := os.ReadFile(target)
if readErr != nil || string(got) != "observed\n" {
t.Fatalf("file = %q, err=%v; the observed bytes must outlive a refused overwrite", got, readErr)
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 {
names := make([]string, 0, len(entries))
for _, entry := range entries {
names = append(names, entry.Name())
}
t.Fatalf("directory holds %s; a refused overwrite must remove its side file", strings.Join(names, ", "))
}
})
}
}

// THE CARRY IS FOR THE FILE THAT IS REPLACED, AND ONLY THAT ONE.
//
// A create has no original to take access control from and keeps what the
// directory gives a new file, so it must hand the side file nothing. An
// overwrite hands it exactly what was read from the observed file. The
// assertion on the overwrite also proves the seam was reached, so the create
// half cannot pass by the seam never being called.
func TestOnlyAnOverwriteCarriesAccessControl(t *testing.T) {
root := t.TempDir()
read := &fileSecurity{}
var applied []*fileSecurity
installFileWriteSecurity(t,
func(*os.File) (*fileSecurity, error) { return read, nil },
func(_ *os.File, security *fileSecurity) error {
applied = append(applied, security)
return nil
},
)
tool := NewScopedWriteFileTool(root, nil)

created := tool.Run(context.Background(), map[string]any{"path": "note.txt", "content": "first\n"})
if created.Status != StatusOK {
t.Fatalf("create = %s: %s", created.Status, created.Output)
}
if len(applied) != 1 || applied[0] != nil {
t.Fatalf("a create handed its side file %v; it has no original to carry access control from", applied)
}

overwrote := tool.Run(context.Background(), map[string]any{"path": "note.txt", "content": "second\n", "overwrite": true})
if overwrote.Status != StatusOK {
t.Fatalf("overwrite = %s: %s", overwrote.Status, overwrote.Output)
}
if len(applied) != 2 || applied[1] != read {
t.Fatalf("an overwrite handed its side file %v, want what was read from the file it replaces", applied)
}
}
Loading
Loading