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
45 changes: 37 additions & 8 deletions internal/transfer/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,45 @@ type ExportSummary struct {
Errors []string `json:"errors,omitempty"`
}

// canonicalizePathForOverlap returns a cleaned absolute path whose deepest
// existing ancestor has been resolved via filepath.EvalSymlinks (expanding
// symlinks as well as Windows 8.3 short names) with any non-existent trailing
// path segments rejoined cleanly.
func canonicalizePathForOverlap(p string) string {
if p == "" {
return ""
}
if abs, err := filepath.Abs(p); err == nil {
p = abs
} else {
p = filepath.Clean(p)
}
cur := p
var missing []string
for {
if resolved, err := filepath.EvalSymlinks(cur); err == nil {
res := filepath.Clean(resolved)
for i := len(missing) - 1; i >= 0; i-- {
res = filepath.Join(res, missing[i])
}
return filepath.Clean(res)
}
parent := filepath.Dir(cur)
if parent == cur {
return filepath.Clean(p)
}
missing = append(missing, filepath.Base(cur))
cur = parent
}
}

func pathsOverlap(a, b string) bool {
ca, cb := filepath.Clean(a), filepath.Clean(b)
if ea, err := filepath.EvalSymlinks(ca); err == nil {
ca = filepath.Clean(ea)
if a == "" || b == "" {
return false
}
if eb, err := filepath.EvalSymlinks(cb); err == nil {
cb = filepath.Clean(eb)
ca, cb := canonicalizePathForOverlap(a), canonicalizePathForOverlap(b)
if runtime.GOOS == "windows" {
ca, cb = strings.ToLower(ca), strings.ToLower(cb)
}
within := func(base, target string) bool {
rel, err := filepath.Rel(base, target)
Expand All @@ -50,9 +82,6 @@ func pathsOverlap(a, b string) bool {
}
return rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator)) && !filepath.IsAbs(rel)
}
if runtime.GOOS == "windows" {
ca, cb = strings.ToLower(ca), strings.ToLower(cb)
}
return within(ca, cb) || within(cb, ca)
}

Expand Down
50 changes: 50 additions & 0 deletions internal/transfer/transfer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,13 @@ func TestExportRejectsLibraryOverlapAndFiltersMissingFiles(t *testing.T) {
if _, err := Export(ctx, []library.ItemMetadata{it}, lib, filepath.Join(lib.CacheDir(), "nested"), nil); err == nil {
t.Fatal("Export accepted subdirectory of CacheDir as destination")
}
deepNested := filepath.Join(lib.CacheDir(), "a", "b", "c")
if _, err := Export(ctx, []library.ItemMetadata{it}, lib, deepNested, nil); err == nil {
t.Fatal("Export accepted deeply nested non-existent subdirectory of CacheDir as destination")
}
if _, err := os.Stat(filepath.Join(lib.CacheDir(), "a")); !os.IsNotExist(err) {
t.Fatalf("Export created directory under CacheDir despite overlap rejection: %v", err)
}

// Remove P02.mp4 locally: exported item.json must not claim P02.mp4 exists.
_ = os.Remove(filepath.Join(it.ItemDir, "P02.mp4"))
Expand Down Expand Up @@ -749,3 +756,46 @@ func TestTransferWeiboRetweetPreservesOriginAndFromOrigin(t *testing.T) {
t.Fatalf("imported Via mismatch: %+v", got.Via)
}
}

func TestPathsOverlapNonExistentSubdirsAndSymlinkAncestor(t *testing.T) {
ctx := context.Background()
lib := newLib(t)
it := localItem(t, lib, "bilibili/1001_UP/videos/BVovlp", video("BVovlp", "重叠校验"),
file{path: "P01.mp4", role: "video", data: []byte("p1")})

cacheDir := lib.CacheDir()
deepNested := filepath.Join(cacheDir, "a", "b", "c")
if !pathsOverlap(deepNested, cacheDir) || !pathsOverlap(cacheDir, deepNested) {
t.Fatalf("pathsOverlap failed for deeply nested non-existent subdir %q vs %q", deepNested, cacheDir)
}
if !pathsOverlap(filepath.Dir(cacheDir), cacheDir) {
t.Fatalf("pathsOverlap failed for parent of CacheDir")
}
if _, err := Export(ctx, []library.ItemMetadata{it}, lib, filepath.Dir(cacheDir), nil); err == nil {
t.Fatal("Export accepted parent of CacheDir as destination")
}

// Non-overlapping sibling sharing a string prefix must not be rejected.
sibling := cacheDir + "-export"
if pathsOverlap(sibling, cacheDir) || pathsOverlap(filepath.Join(sibling, "a", "b"), cacheDir) {
t.Fatalf("pathsOverlap falsely reported overlap for sibling %q vs %q", sibling, cacheDir)
}
if pathsOverlap("", cacheDir) || pathsOverlap(cacheDir, "") {
t.Fatal("pathsOverlap falsely reported overlap with empty path")
}

// Symlinked ancestor pointing to CacheDir with a non-existent nested suffix.
t.Run("symlink_ancestor", func(t *testing.T) {
link := filepath.Join(t.TempDir(), "cache-link")
if err := os.Symlink(cacheDir, link); err != nil {
t.Skipf("symlinks unavailable in this environment: %v", err)
}
viaLink := filepath.Join(link, "a", "b", "c")
if !pathsOverlap(viaLink, cacheDir) || !pathsOverlap(cacheDir, viaLink) {
t.Fatalf("pathsOverlap failed for symlinked ancestor %q vs %q", viaLink, cacheDir)
}
if _, err := Export(ctx, []library.ItemMetadata{it}, lib, viaLink, nil); err == nil {
t.Fatal("Export accepted non-existent subdir under symlinked CacheDir")
}
})
}
117 changes: 117 additions & 0 deletions internal/transfer/transfer_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//go:build windows

package transfer

import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"

"github.com/chialecode/trace/internal/library"
"github.com/chialecode/trace/internal/storage"
"golang.org/x/sys/windows"
)

func TestPathsOverlapWindowsCaseShortPathAndJunction(t *testing.T) {
ctx := context.Background()
lib := newLib(t)
it := localItem(t, lib, "bilibili/1001_UP/videos/BVwinovlp", video("BVwinovlp", "Windows重叠校验"),
file{path: "P01.mp4", role: "video", data: []byte("p1")})
cacheDir := lib.CacheDir()

t.Run("case_variation", func(t *testing.T) {
upperNested := filepath.Join(strings.ToUpper(cacheDir), "A", "B", "C")
lowerNested := filepath.Join(strings.ToLower(cacheDir), "a", "b", "c")
for _, cand := range []string{upperNested, lowerNested} {
if !pathsOverlap(cand, cacheDir) || !pathsOverlap(cacheDir, cand) {
t.Fatalf("pathsOverlap failed for case-varied path %q vs %q", cand, cacheDir)
}
if _, err := Export(ctx, []library.ItemMetadata{it}, lib, cand, nil); err == nil {
t.Fatalf("Export accepted case-varied overlapping destination %q", cand)
}
}

// Both sides non-existent below an existing ancestor, differing in case.
tmp := t.TempDir()
a := filepath.Join(strings.ToUpper(tmp), "NonExist", "Sub")
b := filepath.Join(strings.ToLower(tmp), "nonexist", "sub", "deep")
if !pathsOverlap(a, b) || !pathsOverlap(b, a) {
t.Fatalf("pathsOverlap failed for non-existent case-varied paths %q vs %q", a, b)
}
})

t.Run("short_path", func(t *testing.T) {
tmp := t.TempDir()
longBase := filepath.Join(tmp, "a long directory name for short path overlap")
longCache := filepath.Join(longBase, "cache")
if err := os.MkdirAll(longCache, 0o700); err != nil {
t.Fatal(err)
}
in, err := windows.UTF16PtrFromString(longCache)
if err != nil {
t.Fatal(err)
}
buf := make([]uint16, windows.MAX_LONG_PATH)
n, err := windows.GetShortPathName(in, &buf[0], uint32(len(buf)))
if err != nil || n == 0 {
t.Skipf("no short path: %v", err)
}
shortCache := windows.UTF16ToString(buf[:n])
if strings.EqualFold(shortCache, longCache) {
t.Skip("8.3 names are disabled on this volume")
}

// Reproduce the exact Windows CI failure: CacheDir uses a short path
// (e.g. RUNNER~1) and dest is a non-existent subdir under that short path.
shortNested := filepath.Join(shortCache, "a", "b", "c")
longNested := filepath.Join(longCache, "a", "b", "c")
if !pathsOverlap(shortNested, shortCache) || !pathsOverlap(shortCache, shortNested) {
t.Fatalf("pathsOverlap failed for short-path non-existent subdir %q vs %q", shortNested, shortCache)
}
if !pathsOverlap(shortNested, longCache) || !pathsOverlap(longNested, shortCache) {
t.Fatalf("pathsOverlap failed for mixed short/long non-existent subdirs")
}
sibling := filepath.Join(filepath.Dir(shortCache), "cache-export")
if pathsOverlap(sibling, longCache) || pathsOverlap(sibling, shortCache) {
t.Fatalf("pathsOverlap falsely matched sibling %q against %q", sibling, longCache)
}

db, _, _, err := storage.OpenSQLite(filepath.Join(tmp, "short-library.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Close() })
shortLib, err := library.OpenWithDataDir(db, shortCache, tmp)
if err != nil {
t.Fatal(err)
}
shortItem := localItem(t, shortLib, "bilibili/1001_UP/videos/BVshort", video("BVshort", "短路径"),
file{path: "P01.mp4", role: "video", data: []byte("p1")})
if _, err := Export(ctx, []library.ItemMetadata{shortItem}, shortLib, shortNested, nil); err == nil {
t.Fatalf("Export accepted non-existent subdir %q of short-path CacheDir %q", shortNested, shortCache)
}
if _, err := os.Stat(filepath.Join(shortCache, "a")); !os.IsNotExist(err) {
t.Fatalf("Export created directory under short-path CacheDir despite overlap rejection: %v", err)
}
})

t.Run("junction_ancestor", func(t *testing.T) {
junction := filepath.Join(t.TempDir(), "cache-junction")
cmd := exec.Command("cmd", "/c", "mklink", "/J", junction, cacheDir)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000}
if out, err := cmd.CombinedOutput(); err != nil {
t.Skipf("cannot create junction: %v %s", err, out)
}
viaJunction := filepath.Join(junction, "a", "b", "c")
if _, err := Export(ctx, []library.ItemMetadata{it}, lib, viaJunction, nil); err == nil {
t.Fatalf("Export accepted non-existent subdir %q under junction to CacheDir", viaJunction)
}
if _, err := os.Stat(filepath.Join(cacheDir, "a")); !os.IsNotExist(err) {
t.Fatalf("Export created directory under CacheDir via junction: %v", err)
}
})
}