81 lines
2.0 KiB
Go
81 lines
2.0 KiB
Go
//go:build !windows
|
|
|
|
package safeio
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
func TestReadCanonicalRegularRejectsNamedPipeWithoutBlocking(t *testing.T) {
|
|
temporaryRoot, err := filepath.EvalSymlinks(os.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
root, err := os.MkdirTemp(temporaryRoot, "thothctl-safeio-")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { _ = os.RemoveAll(root) })
|
|
pipe := filepath.Join(root, "secret-pipe")
|
|
if err := unix.Mkfifo(pipe, 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if _, err := ReadCanonicalRegular(pipe, 1024); !errors.Is(err, ErrUnsafeFile) {
|
|
t.Fatalf("named pipe error = %v, want ErrUnsafeFile", err)
|
|
}
|
|
}
|
|
|
|
func TestCanonicalDescriptorOwnershipDoesNotLeakAcrossNestedOperations(t *testing.T) {
|
|
root, err := filepath.EvalSymlinks(t.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
nested := filepath.Join(root, "one", "two")
|
|
if err := os.MkdirAll(nested, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
input := filepath.Join(nested, "input.sql")
|
|
if err := os.WriteFile(input, []byte("select 1"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fdCount := func() int {
|
|
f, err := os.Open("/dev/fd")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer f.Close()
|
|
names, err := f.Readdirnames(-1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return len(names)
|
|
}
|
|
baseline := fdCount()
|
|
for i := 0; i < 20; i++ {
|
|
if _, err := ReadCanonicalRegular(input, 1024); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := validateCanonicalOutputPath(filepath.Join(nested, "out-"+string(rune('a'+i))+".yaml")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if got := fdCount(); got > baseline+2 {
|
|
t.Fatalf("descriptor leak after read/validate: baseline=%d got=%d", baseline, got)
|
|
}
|
|
for i := 0; i < 20; i++ {
|
|
path := filepath.Join(nested, "write-"+string(rune('a'+i))+".yaml")
|
|
if err := writeCanonicalExclusive(path, []byte("ok"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if got := fdCount(); got > baseline+2 {
|
|
t.Fatalf("descriptor leak after writes: baseline=%d got=%d", baseline, got)
|
|
}
|
|
}
|