| 342 | } |
| 343 | |
| 344 | func TestOpenRootDirAllowsTrustedPathSymlinks(t *testing.T) { |
| 345 | tests := []struct { |
| 346 | name string |
| 347 | path func(sandbox string) string |
| 348 | }{ |
| 349 | { |
| 350 | name: "relative", |
| 351 | path: func(string) string { |
| 352 | return filepath.Join("link", "selected") |
| 353 | }, |
| 354 | }, |
| 355 | { |
| 356 | name: "absolute", |
| 357 | path: func(sandbox string) string { |
| 358 | return filepath.Join(sandbox, "link", "selected") |
| 359 | }, |
| 360 | }, |
| 361 | { |
| 362 | name: "parent relative", |
| 363 | path: func(string) string { |
| 364 | return filepath.Join("..", "link", "selected") |
| 365 | }, |
| 366 | }, |
| 367 | } |
| 368 | |
| 369 | for _, tt := range tests { |
| 370 | t.Run(tt.name, func(t *testing.T) { |
| 371 | sandbox := t.TempDir() |
| 372 | target := filepath.Join(sandbox, "target") |
| 373 | require.NoError(t, os.Mkdir(target, 0o755)) |
| 374 | require.NoError(t, os.Symlink(target, filepath.Join(sandbox, "link"))) |
| 375 | if tt.name == "parent relative" { |
| 376 | work := filepath.Join(sandbox, "work") |
| 377 | require.NoError(t, os.Mkdir(work, 0o755)) |
| 378 | t.Chdir(work) |
| 379 | } else { |
| 380 | t.Chdir(sandbox) |
| 381 | } |
| 382 | |
| 383 | root, err := safepaths.OpenRootDir(tt.path(sandbox), 0o755) |
| 384 | require.NoError(t, err) |
| 385 | require.NoError(t, root.WriteFile("file.txt", []byte("content"), 0o644, 0o755, false)) |
| 386 | require.NoError(t, root.Close()) |
| 387 | content, err := os.ReadFile(filepath.Join(target, "selected", "file.txt")) |
| 388 | require.NoError(t, err) |
| 389 | assert.Equal(t, "content", string(content)) |
| 390 | }) |
| 391 | } |
| 392 | } |