Debian Codegraph @

content/file/utils_test.go

raw
1 /*
2 Copyright The ORAS Authors.
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 */
15
16 package file
17
18 import (
19 "archive/tar"
20 "bytes"
21 "compress/gzip"
22 "context"
23 "errors"
24 "os"
25 "path/filepath"
26 "testing"
27 )
28
29 func Test_tarDirectory(t *testing.T) {
30 setup := func(t *testing.T) (tmpdir string, gz *os.File, gw *gzip.Writer) {
31 tmpdir = t.TempDir()
32
33 paths := []string{
34 filepath.Join(tmpdir, "file1.txt"),
35 filepath.Join(tmpdir, "file2.txt"),
36 }
37
38 for _, p := range paths {
39 err := os.WriteFile(p, []byte("test content"), 0644)
40 if err != nil {
41 t.Fatal(err)
42 }
43 }
44
45 gz, err := os.CreateTemp(tmpdir, "tarDirectory-*")
46 if err != nil {
47 t.Fatal(err)
48 }
49
50 return tmpdir, gz, gzip.NewWriter(gz)
51 }
52
53 t.Run("success", func(t *testing.T) {
54 tmpdir, gz, gw := setup(t)
55 defer func() {
56 if err := gw.Close(); err != nil {
57 t.Fatal(err)
58 }
59 if err := gz.Close(); err != nil {
60 t.Fatal(err)
61 }
62 }()
63
64 err := tarDirectory(context.Background(), tmpdir, "prefix", gw, false, nil)
65 if err != nil {
66 t.Fatal(err)
67 }
68
69 _, err = gz.Stat()
70 if err != nil {
71 t.Fatal(err)
72 }
73 })
74
75 t.Run("context cancellation", func(t *testing.T) {
76 tmpdir, gz, gw := setup(t)
77 defer func() {
78 if err := gw.Close(); err != nil {
79 t.Fatal(err)
80 }
81 if err := gz.Close(); err != nil {
82 t.Fatal(err)
83 }
84 }()
85
86 ctx, cancel := context.WithCancel(context.Background())
87 cancel()
88
89 err := tarDirectory(ctx, tmpdir, "prefix", gw, false, nil)
90 if err == nil {
91 t.Fatal("expected context cancellation error, got nil")
92 }
93 if !errors.Is(err, context.Canceled) {
94 t.Fatalf("expected context.Canceled error, got %v", err)
95 }
96
97 _, err = gz.Stat()
98 if err != nil {
99 t.Fatal(err)
100 }
101 })
102 }
103
104 func Test_ensureBasePath(t *testing.T) {
105 root := t.TempDir()
106 if err := os.MkdirAll(filepath.Join(root, "hello world", "foo", "bar"), 0700); err != nil {
107 t.Fatal("failed to create temp folders:", err)
108 }
109 baseRel := "hello world/foo"
110 baseAbs := filepath.Join(root, baseRel)
111
112 tests := []struct {
113 name string
114 target string
115 want string
116 wantErr bool
117 }{
118 {
119 name: "valid case (depth 0)",
120 target: "hello world/foo",
121 want: ".",
122 },
123 {
124 name: "valid case (depth 1)",
125 target: "hello world/foo/bar",
126 want: "bar",
127 },
128 {
129 name: "valid case (depth 2)",
130 target: "hello world/foo/bar/fun",
131 want: filepath.Join("bar", "fun"),
132 },
133 {
134 name: "invalid prefix",
135 target: "hello world/fun",
136 wantErr: true,
137 },
138 {
139 name: "invalid prefix",
140 target: "hello/foo",
141 wantErr: true,
142 },
143 {
144 name: "bad traversal",
145 target: "hello world/foo/..",
146 wantErr: true,
147 },
148 {
149 name: "valid traversal",
150 target: "hello world/foo/../foo/bar/../bar",
151 want: "bar",
152 },
153 {
154 name: "complex traversal",
155 target: "hello world/foo/../foo/bar/../..",
156 wantErr: true,
157 },
158 }
159 for _, tt := range tests {
160 t.Run(tt.name, func(t *testing.T) {
161 got, err := resolveRelToBase(baseAbs, baseRel, tt.target)
162 if (err != nil) != tt.wantErr {
163 t.Errorf("ensureBasePath() error = %v, wantErr %v", err, tt.wantErr)
164 return
165 }
166 if got != tt.want {
167 t.Errorf("ensureBasePath() = %v, want %v", got, tt.want)
168 }
169 })
170 }
171 }
172
173 func Test_ensureLinkPath(t *testing.T) {
174 root := t.TempDir()
175 if err := os.MkdirAll(filepath.Join(root, "hello world", "foo", "bar"), 0700); err != nil {
176 t.Fatal("failed to create temp folders:", err)
177 }
178 baseRel := "hello world/foo"
179 baseAbs := filepath.Join(root, baseRel)
180
181 tests := []struct {
182 name string
183 link string
184 target string
185 want string
186 wantErr bool
187 }{
188 {
189 name: "valid case (depth 1)",
190 link: "hello world/foo/bar",
191 target: "fun",
192 want: "fun",
193 },
194 {
195 name: "valid case (depth 2)",
196 link: "hello world/foo/bar/fun",
197 target: "../fun",
198 want: "../fun",
199 },
200 {
201 name: "invalid prefix",
202 link: "hello world/foo",
203 target: "fun",
204 wantErr: true,
205 },
206 {
207 name: "bad traversal",
208 link: "hello world/foo/bar",
209 target: "../fun",
210 wantErr: true,
211 },
212 {
213 name: "valid traversal",
214 link: "hello world/foo/../foo/bar/../bar", // hello world/foo/bar
215 target: "../foo/../foo/fun",
216 want: "../foo/../foo/fun",
217 },
218 {
219 name: "complex traversal",
220 link: "hello world/foo/bar",
221 target: "../foo/../../fun",
222 wantErr: true,
223 },
224 }
225 for _, tt := range tests {
226 t.Run(tt.name, func(t *testing.T) {
227 got, err := ensureLinkPath(baseAbs, baseRel, tt.link, tt.target)
228 if (err != nil) != tt.wantErr {
229 t.Errorf("ensureLinkPath() error = %v, wantErr %v", err, tt.wantErr)
230 return
231 }
232 if got != tt.want {
233 t.Errorf("ensureLinkPath() = %v, want %v", got, tt.want)
234 }
235 })
236 }
237 }
238
239 func Test_extractTarGzip_Error(t *testing.T) {
240 t.Run("Non-existing file", func(t *testing.T) {
241 err := extractTarGzip("", "", "non-existing-file", "", nil, false)
242 if err == nil {
243 t.Fatal("expected error, got nil")
244 }
245 })
246 }
247
248 func Test_extractTarDirectory(t *testing.T) {
249 tests := []struct {
250 name string
251 tarData []byte
252 wantFiles map[string]string // map of file paths to their expected contents
253 wantErr bool
254 }{
255 {
256 name: "valid files should be exracted",
257 tarData: createTar(t, []tarEntry{
258 {name: "base/", mode: os.ModeDir | 0777},
259 {name: "base/test.txt", content: "hello world", mode: 0666},
260 {name: "base/file_symlink", linkname: "test.txt", mode: os.ModeSymlink | 0666},
261 }),
262 wantFiles: map[string]string{
263 "base/test.txt": "hello world",
264 "base/file_symlink": "hello world",
265 },
266 wantErr: false,
267 },
268 {
269 name: "non-regular files",
270 tarData: createTar(t, []tarEntry{
271 {name: "base/something", isNonRegular: true},
272 }),
273 wantErr: false,
274 },
275 {
276 name: "filepath outside of working dir should fail",
277 tarData: createTar(t, []tarEntry{
278 {name: "test.txt", content: "hello world", mode: 0666},
279 }),
280 wantErr: true,
281 },
282 {
283 name: "symlink to a bad target should fail",
284 tarData: createTar(t, []tarEntry{
285 {name: "base/file_symlink", linkname: "base/test.txt", mode: os.ModeSymlink | 0666},
286 }),
287 wantErr: true,
288 },
289 {
290 name: "invalid tar header",
291 tarData: []byte("random data"),
292 wantErr: true,
293 },
294 }
295
296 for _, tt := range tests {
297 t.Run(tt.name, func(t *testing.T) {
298 tempDir := t.TempDir()
299 dirName := "base"
300 dirPath := filepath.Join(tempDir, dirName)
301 buf := make([]byte, 1024)
302
303 if err := extractTarDirectory(dirPath, dirName, bytes.NewReader(tt.tarData), buf, false); (err != nil) != tt.wantErr {
304 t.Fatalf("extractTarDirectory() error = %v, wantErr %v", err, tt.wantErr)
305 }
306 if !tt.wantErr {
307 for path, wantContent := range tt.wantFiles {
308 filePath := filepath.Join(tempDir, path)
309 fi, err := os.Lstat(filePath)
310 if err != nil {
311 t.Fatalf("failed to stat file %s: %v", filePath, err)
312 }
313
314 if fi.Mode()&os.ModeSymlink != 0 {
315 filePath, err = os.Readlink(filePath)
316 if err != nil {
317 t.Fatalf("failed to read link %s: %v", filePath, err)
318 }
319 if !filepath.IsAbs(filePath) {
320 filePath = filepath.Join(dirPath, filePath)
321 }
322 }
323 gotContent, err := os.ReadFile(filePath)
324 if err != nil {
325 t.Fatalf("failed to read file %s: %v", filePath, err)
326 }
327 if string(gotContent) != wantContent {
328 t.Errorf("file content = %s, want %s", gotContent, wantContent)
329 }
330 }
331 }
332 })
333 }
334 }
335
336 func Test_extractTarDirectory_HardLink(t *testing.T) {
337 t.Run("hard link with a good path should be extracted", func(t *testing.T) {
338 tempDir := t.TempDir()
339 dirName := "base"
340 dirPath := filepath.Join(tempDir, dirName)
341 linkPath := filepath.Join(dirPath, "test.txt")
342 fileContent := "hello world"
343 buf := make([]byte, 1024)
344
345 tarData := createTar(t, []tarEntry{
346 {name: "base/", mode: os.ModeDir | 0777},
347 {name: "base/test.txt", content: fileContent, mode: 0666},
348 {name: "base/test_hardlink", linkname: linkPath, mode: 0666, isHardLink: true},
349 })
350
351 if err := extractTarDirectory(dirPath, dirName, bytes.NewReader(tarData), buf, false); err != nil {
352 t.Fatalf("extractTarDirectory() error = %v", err)
353 }
354
355 // verify extracted hard link file
356 gotContent, err := os.ReadFile(linkPath)
357 if err != nil {
358 t.Fatalf("failed to read file %s: %v", linkPath, err)
359 }
360 if string(gotContent) != fileContent {
361 t.Errorf("file content = %s, want %s", gotContent, fileContent)
362 }
363 })
364
365 t.Run("hard link with a bad path should fail", func(t *testing.T) {
366 tempDir := t.TempDir()
367 dirName := "base"
368 dirPath := filepath.Join(tempDir, dirName)
369 buf := make([]byte, 1024)
370
371 tarData := createTar(t, []tarEntry{
372 {name: "base/test_hardlink", linkname: "whatever", mode: 0666, isHardLink: true},
373 })
374
375 if err := extractTarDirectory(dirPath, dirName, bytes.NewReader(tarData), buf, false); err == nil {
376 t.Error("extractTarDirectory() error = nil, wantErr = true")
377 }
378 })
379
380 t.Run("hard link with relative linkname must not escape extract dir via process CWD", func(t *testing.T) {
381 // GHSA-fxhp-mv3v-67qp: a tarball TypeLink entry with a relative Linkname
382 // was passed verbatim to os.Link, which resolves relative paths against the
383 // process CWD rather than the link file's directory. An attacker-controlled
384 // registry could use this to hardlink a CWD file into the extract tree.
385 cwdDir := t.TempDir()
386 sentinelPath := filepath.Join(cwdDir, "sentinel.txt")
387 if err := os.WriteFile(sentinelPath, []byte("secret"), 0600); err != nil {
388 t.Fatal(err)
389 }
390
391 origDir, err := os.Getwd()
392 if err != nil {
393 t.Fatal(err)
394 }
395 if err := os.Chdir(cwdDir); err != nil {
396 t.Fatal(err)
397 }
398 defer os.Chdir(origDir) //nolint:errcheck
399
400 extractDir := t.TempDir()
401 dirName := "base"
402 dirPath := filepath.Join(extractDir, dirName)
403 buf := make([]byte, 1024)
404
405 // The relative Linkname "sentinel.txt" would resolve against the process
406 // CWD (cwdDir) via link(2) if not explicitly resolved first.
407 tarData := createTar(t, []tarEntry{
408 {name: "base/", mode: os.ModeDir | 0777},
409 {name: "base/evil_link", linkname: "sentinel.txt", mode: 0666, isHardLink: true},
410 })
411
412 err = extractTarDirectory(dirPath, dirName, bytes.NewReader(tarData), buf, false)
413 if err != nil {
414 // Expected: target resolves to <extractDir>/base/sentinel.txt which
415 // doesn't exist, so os.Link returns an error. No escape occurred.
416 return
417 }
418
419 // If extraction succeeded, verify the hardlink does not share an inode
420 // with the CWD sentinel file (i.e., it did not escape the extract dir).
421 evilLinkPath := filepath.Join(dirPath, "evil_link")
422 evilInfo, statErr := os.Lstat(evilLinkPath)
423 if statErr != nil {
424 return // link was not created; no escape
425 }
426 sentinelInfo, statErr := os.Lstat(sentinelPath)
427 if statErr != nil {
428 t.Fatal(statErr)
429 }
430 if os.SameFile(evilInfo, sentinelInfo) {
431 t.Error("hardlink escaped extract dir: evil_link shares inode with CWD sentinel file")
432 }
433 })
434 }
435
436 type tarEntry struct {
437 name string
438 content string
439 linkname string
440 mode os.FileMode
441 isNonRegular bool
442 isHardLink bool
443 }
444
445 func createTar(t *testing.T, entries []tarEntry) []byte {
446 var buf bytes.Buffer
447 tw := tar.NewWriter(&buf)
448
449 for _, entry := range entries {
450 hdr := &tar.Header{
451 Name: entry.name,
452 Mode: int64(entry.mode.Perm()),
453 Size: int64(len(entry.content)),
454 }
455 if entry.isNonRegular {
456 hdr.Typeflag = tar.TypeBlock
457 } else if entry.isHardLink {
458 hdr.Typeflag = tar.TypeLink
459 hdr.Linkname = entry.linkname
460 } else if entry.mode&os.ModeSymlink != 0 {
461 hdr.Typeflag = tar.TypeSymlink
462 hdr.Linkname = entry.linkname
463 }
464
465 if err := tw.WriteHeader(hdr); err != nil {
466 t.Fatalf("failed to write tar header: %v", err)
467 }
468 if _, err := tw.Write([]byte(entry.content)); err != nil {
469 t.Fatalf("failed to write tar content: %v", err)
470 }
471 }
472
473 if err := tw.Close(); err != nil {
474 t.Fatalf("failed to close tar writer: %v", err)
475 }
476 return buf.Bytes()
477 }