| 291 | } |
| 292 | |
| 293 | func TestOpenFileAllowsTrustedParentSymlinks(t *testing.T) { |
| 294 | tests := []struct { |
| 295 | name string |
| 296 | path func(sandbox string) string |
| 297 | }{ |
| 298 | { |
| 299 | name: "relative", |
| 300 | path: func(string) string { |
| 301 | return filepath.Join("link", "file.txt") |
| 302 | }, |
| 303 | }, |
| 304 | { |
| 305 | name: "absolute", |
| 306 | path: func(sandbox string) string { |
| 307 | return filepath.Join(sandbox, "link", "file.txt") |
| 308 | }, |
| 309 | }, |
| 310 | { |
| 311 | name: "parent relative", |
| 312 | path: func(string) string { |
| 313 | return filepath.Join("..", "link", "file.txt") |
| 314 | }, |
| 315 | }, |
| 316 | } |
| 317 | |
| 318 | for _, tt := range tests { |
| 319 | t.Run(tt.name, func(t *testing.T) { |
| 320 | sandbox := t.TempDir() |
| 321 | target := filepath.Join(sandbox, "target") |
| 322 | require.NoError(t, os.Mkdir(target, 0o755)) |
| 323 | require.NoError(t, os.Symlink(target, filepath.Join(sandbox, "link"))) |
| 324 | if tt.name == "parent relative" { |
| 325 | work := filepath.Join(sandbox, "work") |
| 326 | require.NoError(t, os.Mkdir(work, 0o755)) |
| 327 | t.Chdir(work) |
| 328 | } else { |
| 329 | t.Chdir(sandbox) |
| 330 | } |
| 331 | |
| 332 | file, err := safepaths.OpenFile(tt.path(sandbox), 0o644, 0o755, false) |
| 333 | require.NoError(t, err) |
| 334 | _, err = file.Write([]byte("content")) |
| 335 | require.NoError(t, err) |
| 336 | require.NoError(t, file.Close()) |
| 337 | content, err := os.ReadFile(filepath.Join(target, "file.txt")) |
| 338 | require.NoError(t, err) |
| 339 | assert.Equal(t, "content", string(content)) |
| 340 | }) |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | func TestOpenRootDirAllowsTrustedPathSymlinks(t *testing.T) { |
| 345 | tests := []struct { |