53 lines
1.4 KiB
Go
53 lines
1.4 KiB
Go
package safeio
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"testing"
|
|
)
|
|
|
|
func TestReadCanonicalRegularRejectsFinalAndParentSymlinks(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) })
|
|
|
|
realDirectory := filepath.Join(root, "real")
|
|
if err := os.Mkdir(realDirectory, 0o700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
realFile := filepath.Join(realDirectory, "secret")
|
|
if err := os.WriteFile(realFile, []byte("secret"), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
parentLink := filepath.Join(root, "parent-link")
|
|
symlinkOrSkip(t, realDirectory, parentLink)
|
|
if _, err := ReadCanonicalRegular(filepath.Join(parentLink, "secret"), 1024); !errors.Is(err, ErrUnsafeFile) {
|
|
t.Fatalf("parent symlink error = %v, want ErrUnsafeFile", err)
|
|
}
|
|
|
|
finalLink := filepath.Join(root, "final-link")
|
|
symlinkOrSkip(t, realFile, finalLink)
|
|
if _, err := ReadCanonicalRegular(finalLink, 1024); !errors.Is(err, ErrUnsafeFile) {
|
|
t.Fatalf("final symlink error = %v, want ErrUnsafeFile", err)
|
|
}
|
|
}
|
|
|
|
func symlinkOrSkip(t *testing.T, target, link string) {
|
|
t.Helper()
|
|
if err := os.Symlink(target, link); err != nil {
|
|
if runtime.GOOS == "windows" && errors.Is(err, os.ErrPermission) {
|
|
t.Skip("Windows symlink privilege is unavailable")
|
|
}
|
|
t.Fatal(err)
|
|
}
|
|
}
|