diff --git a/internal/tools/file_commit.go b/internal/tools/file_commit.go index 157b9f61b..b44cf5aa3 100644 --- a/internal/tools/file_commit.go +++ b/internal/tools/file_commit.go @@ -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. @@ -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 } @@ -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 } @@ -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 @@ -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() diff --git a/internal/tools/file_commit_attributes_other.go b/internal/tools/file_commit_attributes_other.go new file mode 100644 index 000000000..b3e116a4e --- /dev/null +++ b/internal/tools/file_commit_attributes_other.go @@ -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 } diff --git a/internal/tools/file_commit_attributes_test.go b/internal/tools/file_commit_attributes_test.go new file mode 100644 index 000000000..8057fdadd --- /dev/null +++ b/internal/tools/file_commit_attributes_test.go @@ -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)) + } +} diff --git a/internal/tools/file_commit_attributes_windows.go b/internal/tools/file_commit_attributes_windows.go new file mode 100644 index 000000000..a663f3ef2 --- /dev/null +++ b/internal/tools/file_commit_attributes_windows.go @@ -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), ¤t); 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 +} diff --git a/internal/tools/file_commit_attributes_windows_test.go b/internal/tools/file_commit_attributes_windows_test.go new file mode 100644 index 000000000..9bcd8ba11 --- /dev/null +++ b/internal/tools/file_commit_attributes_windows_test.go @@ -0,0 +1,246 @@ +//go:build windows + +package tools + +import ( + "context" + "os" + "path/filepath" + "testing" + + "golang.org/x/sys/windows" +) + +// testedAttributeBits are the attributes these tests make claims about. A +// directory can hand a new file others, compression above all, and whether the +// machine's temporary directory does that is not what is being tested. +const testedAttributeBits = windows.FILE_ATTRIBUTE_HIDDEN | windows.FILE_ATTRIBUTE_SYSTEM | + windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | windows.FILE_ATTRIBUTE_READONLY | + windows.FILE_ATTRIBUTE_TEMPORARY | windows.FILE_ATTRIBUTE_ARCHIVE + +// testFileAttributes returns the attributes under test that the file has. +func testFileAttributes(t *testing.T, path string) uint32 { + t.Helper() + name, err := windows.UTF16PtrFromString(path) + if err != nil { + t.Fatal(err) + } + attributes, err := windows.GetFileAttributes(name) + if err != nil { + t.Fatalf("read the attributes of %s: %v", path, err) + } + return attributes & testedAttributeBits +} + +// newPlainTestFile writes the file an overwrite will replace and clears the +// attributes under test on it. A new file takes the not-content-indexed +// attribute from its directory, and the temporary directory of the machine +// running this may have it, so the starting state is set and not assumed. +func newPlainTestFile(t *testing.T, path string) { + t.Helper() + if err := os.WriteFile(path, []byte("observed\n"), 0o644); err != nil { + t.Fatal(err) + } + setTestFileAttributes(t, path, windows.FILE_ATTRIBUTE_ARCHIVE) + if got := testFileAttributes(t, path); got != windows.FILE_ATTRIBUTE_ARCHIVE { + t.Fatalf("SETUP INVALID: attributes = %#x after they were cleared", got) + } +} + +func setTestFileAttributes(t *testing.T, path string, attributes uint32) { + t.Helper() + name, err := windows.UTF16PtrFromString(path) + if err != nil { + t.Fatal(err) + } + if err := windows.SetFileAttributes(name, attributes); err != nil { + t.Fatalf("set the attributes of %s: %v", path, err) + } +} + +// AN OVERWRITE KEEPS THE ATTRIBUTES OF THE FILE IT REPLACES. +// +// Publishing an overwrite by rename replaced the file with a new one that had +// no attributes beyond the archive bit, so a hidden file came back visible and +// a system file lost its mark. Both tools that publish through the rename are +// checked, on both ways a side file is created: with the replaced file's +// access control, and on a volume that keeps none. +func TestOverwriteKeepsTheReplacedFilesAttributes(t *testing.T) { + for _, layout := range []struct { + name string + attributes uint32 + }{ + {name: "hidden", attributes: windows.FILE_ATTRIBUTE_HIDDEN}, + {name: "system", attributes: windows.FILE_ATTRIBUTE_SYSTEM}, + {name: "hidden and system", attributes: windows.FILE_ATTRIBUTE_HIDDEN | windows.FILE_ATTRIBUTE_SYSTEM}, + {name: "not content indexed", attributes: windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED}, + } { + for _, volume := range []struct { + name string + keepsACL bool + }{ + {name: "a volume with access control lists", keepsACL: true}, + {name: "a volume without them", keepsACL: false}, + } { + for _, tool := range []struct { + name string + run func(root string) Result + }{ + {name: "write_file", run: func(root string) Result { + return NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "kept.txt", "content": "replacement\n", "overwrite": true, + }) + }}, + {name: "edit_file", run: func(root string) Result { + return NewScopedEditFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "kept.txt", "old_string": "observed", "new_string": "replacement", + }) + }}, + } { + t.Run(layout.name+"/"+volume.name+"/"+tool.name, func(t *testing.T) { + if !volume.keepsACL { + prior := fileVolumeKeepsACLs + fileVolumeKeepsACLs = func(windows.Handle) (bool, error) { return false, nil } + t.Cleanup(func() { fileVolumeKeepsACLs = prior }) + } + root := t.TempDir() + path := filepath.Join(root, "kept.txt") + newPlainTestFile(t, path) + setTestFileAttributes(t, path, layout.attributes) + before := testFileAttributes(t, path) + if before&layout.attributes != layout.attributes { + t.Fatalf("SETUP INVALID: attributes = %#x after setting %#x", before, layout.attributes) + } + + result := tool.run(root) + if result.Status != StatusOK { + t.Fatalf("%s = %s: %s", tool.name, result.Status, result.Output) + } + content, err := os.ReadFile(path) + if err != nil || string(content) != "replacement\n" { + t.Fatalf("content = %q, err=%v; the overwrite did not land", content, err) + } + // A modified file has the archive bit; nothing else may differ. + want := before | windows.FILE_ATTRIBUTE_ARCHIVE + if after := testFileAttributes(t, path); after != want { + t.Fatalf("attributes across the overwrite: %#x before, %#x after, want %#x", before, after, want) + } + }) + } + } + } +} + +// ONLY THE PRESENTATION ATTRIBUTES ARE CARRIED. +// +// The carry adds to what the new file has. It must not copy bits that describe +// how the old file object was stored, which cannot be set as attributes and +// would make the call fail or lie, and a file with nothing to carry must come +// out as an ordinary new file. +func TestOverwriteCarriesNothingBeyondThePresentationAttributes(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "plain.txt") + newPlainTestFile(t, path) + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + carried := carriedFileAttributes(info) + if carried == nil { + t.Fatal("an existing file carries nil; it must carry the fact that none of the attributes is set") + } + if *carried != 0 { + t.Fatalf("an ordinary file carries %#x, want none of the attributes", *carried) + } + var handed []uint32 + installFileWriteAttributes(t, func(file *os.File, attributes *uint32) error { + if attributes == nil { + t.Error("an overwrite handed its side file nil in place of the replaced file's attributes") + return nil + } + handed = append(handed, *attributes) + return applyFileAttributes(file, attributes) + }) + setTestFileAttributes(t, path, windows.FILE_ATTRIBUTE_HIDDEN|windows.FILE_ATTRIBUTE_ARCHIVE|windows.FILE_ATTRIBUTE_TEMPORARY) + if before := testFileAttributes(t, path); before&windows.FILE_ATTRIBUTE_TEMPORARY == 0 { + t.Fatalf("SETUP INVALID: attributes = %#x, the temporary bit did not take", before) + } + + result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "plain.txt", "content": "replacement\n", "overwrite": true, + }) + if result.Status != StatusOK { + t.Fatalf("overwrite = %s: %s", result.Status, result.Output) + } + if len(handed) != 1 || handed[0] != windows.FILE_ATTRIBUTE_HIDDEN { + t.Fatalf("the side file was handed %#x, want the hidden bit alone", handed) + } + if after := testFileAttributes(t, path); after != windows.FILE_ATTRIBUTE_HIDDEN|windows.FILE_ATTRIBUTE_ARCHIVE { + t.Fatalf("attributes after the overwrite = %#x, want hidden and archive", after) + } +} + +// AN OVERWRITE DOES NOT PICK UP THE DIRECTORY'S ATTRIBUTES. +// +// A new file inherits the not-content-indexed attribute from its directory. +// The side file is a new file, so in a directory that has the attribute it is +// born with it, and the file it replaces may not have had it. The carry sets +// the presentation attributes to exactly what the replaced file had, which +// means clearing what the directory handed the side file as well as adding +// what the original had. +func TestOverwriteDoesNotPickUpTheDirectorysAttributes(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "kept.txt") + newPlainTestFile(t, path) + setTestFileAttributes(t, root, windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED) + probe := filepath.Join(root, "probe.txt") + if err := os.WriteFile(probe, nil, 0o644); err != nil { + t.Fatal(err) + } + if testFileAttributes(t, probe)&windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED == 0 { + t.Skip("this volume does not hand the directory's not-content-indexed attribute to a new file") + } + before := testFileAttributes(t, path) + if before&windows.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED != 0 { + t.Fatalf("SETUP INVALID: the existing file already has the attribute: %#x", before) + } + + result := NewScopedWriteFileTool(root, nil).Run(context.Background(), map[string]any{ + "path": "kept.txt", "content": "replacement\n", "overwrite": true, + }) + if result.Status != StatusOK { + t.Fatalf("overwrite = %s: %s", result.Status, result.Output) + } + want := before | windows.FILE_ATTRIBUTE_ARCHIVE + if after := testFileAttributes(t, path); after != want { + t.Fatalf("attributes across the overwrite: %#x before, %#x after, want %#x; the directory's attribute leaked onto the file", before, after, want) + } +} + +// THE LAYER THAT WRITES ATTRIBUTES ENFORCES THE MASK ITSELF. +// +// What the commit path hands it is already masked, so an overwrite cannot show +// whether this layer would pass other bits through. It is called directly here +// with bits it must not set. +func TestApplyFileAttributesSetsOnlyThePresentationAttributes(t *testing.T) { + path := filepath.Join(t.TempDir(), "staged.txt") + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + t.Fatal(err) + } + bits := uint32(windows.FILE_ATTRIBUTE_HIDDEN | windows.FILE_ATTRIBUTE_TEMPORARY | windows.FILE_ATTRIBUTE_READONLY) + applyErr := applyFileAttributes(file, &bits) + if err := file.Close(); err != nil { + t.Fatal(err) + } + if applyErr != nil { + t.Fatalf("applyFileAttributes: %v", applyErr) + } + after := testFileAttributes(t, path) + if after&windows.FILE_ATTRIBUTE_HIDDEN == 0 { + t.Fatalf("SETUP INVALID: attributes = %#x, the hidden bit was not applied", after) + } + if after&(windows.FILE_ATTRIBUTE_TEMPORARY|windows.FILE_ATTRIBUTE_READONLY) != 0 { + t.Fatalf("attributes = %#x; only the presentation attributes may be set from the carried value", after) + } +}