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
18 changes: 14 additions & 4 deletions internal/tools/file_commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ var (
fileWriteApplySecurity = applyFileSecurity
)

// fileWriteApplyAttributes carries the replaced file's attributes to the file
// that takes its name. Tests replace it to exercise a failure.
var fileWriteApplyAttributes = applyFileAttributes

// 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 @@ -186,7 +190,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, nil, content)
tempName, err := writeRootedSideFile(root, relativePath, 0o644, true, nil, nil, content)
if err != nil {
return err
}
Expand Down Expand Up @@ -263,7 +267,7 @@ func renameNoReplaceUnsupported(err error) bool {
// 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, security *fileSecurity, content string) error {
tempName, err := writeRootedSideFile(root, publishPath, mode, false, security, content)
tempName, err := writeRootedSideFile(root, publishPath, mode, false, security, carriedFileAttributes(openedInfo), content)
if err != nil {
return err
}
Expand Down Expand Up @@ -332,8 +336,9 @@ func resolveRootedFinalPath(root *os.Root, relativePath string) (string, error)
// An overwrite stages 0o600 and finally carries the observed file's permission
// 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) {
// create passes nil and keeps what the directory gives a new file. attributes
// are the replaced file's, and a create passes nil for the same reason.
func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, umaskDerived bool, security *fileSecurity, attributes *uint32, content string) (string, error) {
createMode := mode.Perm()
if !umaskDerived {
createMode = 0o600
Expand Down Expand Up @@ -368,6 +373,11 @@ func writeRootedSideFile(root *os.Root, relativePath string, mode os.FileMode, u
if err := fileWriteTempWrite(temp, content); err != nil {
return err
}
// The attributes go on before the permission bits, which on Windows
// are the read-only attribute and are changed without touching the rest.
if err := fileWriteApplyAttributes(temp, attributes); err != nil {
return err
}
return temp.Chmod(granted.Perm())
}()
closeErr := temp.Close()
Expand Down
12 changes: 12 additions & 0 deletions internal/tools/file_commit_attributes_other.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//go:build !windows

package tools

import "os"

// Only Windows keeps the presentation of a file in attributes that a rename
// leaves behind. Elsewhere there is nothing here to carry.

func carriedFileAttributes(os.FileInfo) *uint32 { return nil }

func applyFileAttributes(*os.File, *uint32) error { return nil }
103 changes: 103 additions & 0 deletions internal/tools/file_commit_attributes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package tools

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

func installFileWriteAttributes(t *testing.T, apply func(*os.File, *uint32) error) {
t.Helper()
prior := fileWriteApplyAttributes
fileWriteApplyAttributes = apply
t.Cleanup(func() { fileWriteApplyAttributes = prior })
}

// AN OVERWRITE THAT CANNOT CARRY THE FILE'S ATTRIBUTES DOES NOT HAPPEN.
//
// The staged file is a new one and starts with no attributes. If the replaced
// file's cannot be put on it, publishing anyway would change how the file is
// presented behind the user's back, so the write is refused, the observed
// bytes stay, and the side file is removed. This runs on every platform: the
// seam is the same everywhere, and only what sits behind it differs.
func TestOverwriteRefusesWhenAttributesCannotBeCarried(t *testing.T) {
failure := errors.New("injected attribute failure")
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 func() { _ = workspace.Close() }()
info, err := os.Stat(target)
if err != nil {
t.Fatal(err)
}
preimage := "observed\n"
calls := 0
installFileWriteAttributes(t, func(*os.File, *uint32) error {
calls++
return failure
})

err = commitRootedFileContents(workspace, target, "existing.txt", info, &preimage, "replacement\n")
if !errors.Is(err, failure) {
t.Fatalf("commit error = %v, want the injected attribute failure", err)
}
if calls != 1 {
t.Fatalf("SETUP INVALID: the attribute seam ran %d times, want once", calls)
}
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, ", "))
}
}

// A CREATE CARRIES NO ATTRIBUTES.
//
// It has no original to take them from. The overwrite that follows proves the
// seam is reached at all, so the create half cannot pass by never calling it.
func TestACreateCarriesNoAttributes(t *testing.T) {
root := t.TempDir()
var applied []*uint32
installFileWriteAttributes(t, func(_ *os.File, attributes *uint32) error {
applied = append(applied, attributes)
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 {
t.Fatalf("SETUP INVALID: the attribute seam ran %d times for a create, want once", len(applied))
}
if applied[0] != nil {
t.Fatalf("a create handed its side file the attributes %#x; it has no original to carry any from", *applied[0])
}
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 {
t.Fatalf("the attribute seam ran %d times across a create and an overwrite, want twice", len(applied))
}
}
93 changes: 93 additions & 0 deletions internal/tools/file_commit_attributes_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
//go:build windows

package tools

import (
"fmt"
"os"
"syscall"
"unsafe"

"golang.org/x/sys/windows"
)

// carriedAttributeMask selects the attributes an overwrite takes from the file
// it replaces: the ones a person or a tool sets on a file to say how it is
// presented. The side file is a new file. It has none of the replaced file's,
// so a hidden file would reappear in listings once it had been edited, and it
// has whatever its directory hands a new file, which the replaced file may
// never have had.
//
// The rest are left alone on purpose. Read-only travels with the permission
// bits. Archive is set by the system on any new file, which is also what a
// write in place does. Compressed, encrypted, sparse, offline and the cloud
// placement bits describe how one file object is stored, and cannot be set as
// attributes on another.
const carriedAttributeMask = windows.FILE_ATTRIBUTE_HIDDEN |
windows.FILE_ATTRIBUTE_SYSTEM |
windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED

// fileBasicInfo is FILE_BASIC_INFO. A zero time leaves that time as it is, and
// zero attributes leave the attributes as they are.
type fileBasicInfo struct {
CreationTime int64
LastAccessTime int64
LastWriteTime int64
ChangeTime int64
FileAttributes uint32
_ uint32
}

// carriedFileAttributes returns the presentation attributes of the file an
// overwrite is about to replace, out of what was read through the handle whose
// identity the caller has already validated. The result is never nil for a
// file: a file with none of them set carries that fact, so the side file is
// cleared of anything its directory gave it.
func carriedFileAttributes(info os.FileInfo) *uint32 {
data, ok := info.Sys().(*syscall.Win32FileAttributeData)
if !ok {
return nil
}
carried := data.FileAttributes & carriedAttributeMask
return &carried
}

// applyFileAttributes sets the staged file's presentation attributes to
// exactly the carried ones, through its own handle, and keeps every other
// attribute it has. Nil means there is no original, and nothing is changed.
func applyFileAttributes(staged *os.File, attributes *uint32) error {
if attributes == nil {
return nil
}
raw, err := staged.SyscallConn()
if err != nil {
return err
}
var applyErr error
if err := raw.Control(func(handle uintptr) {
var current windows.ByHandleFileInformation
if applyErr = windows.GetFileInformationByHandle(windows.Handle(handle), &current); applyErr != nil {
return
}
wanted := current.FileAttributes&^carriedAttributeMask | *attributes&carriedAttributeMask
if wanted == current.FileAttributes {
return
}
if wanted == 0 {
wanted = windows.FILE_ATTRIBUTE_NORMAL
}
basic := fileBasicInfo{FileAttributes: wanted}
applyErr = windows.SetFileInformationByHandle(
windows.Handle(handle),
windows.FileBasicInfo,
(*byte)(unsafe.Pointer(&basic)),
uint32(unsafe.Sizeof(basic)),
)
}); err != nil {
return err
}
if applyErr != nil {
return fmt.Errorf("carry the existing file's attributes: %w", applyErr)
}
return nil
}
Loading
Loading