File: join_test.go

package info (click to toggle)
golang-github-cyphar-filepath-securejoin 0.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, experimental, sid
  • size: 104 kB
  • sloc: makefile: 2
file content (385 lines) | stat: -rw-r--r-- 12,438 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright (C) 2017 SUSE LLC. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package securejoin

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
	"syscall"
	"testing"
)

// TODO: These tests won't work on plan9 because it doesn't have symlinks, and
//       also we use '/' here explicitly which probably won't work on Windows.

func symlink(t *testing.T, oldname, newname string) {
	if err := os.Symlink(oldname, newname); err != nil {
		t.Fatal(err)
	}
}

// Test basic handling of symlink expansion.
func TestSymlink(t *testing.T) {
	dir, err := ioutil.TempDir("", "TestSymlink")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	symlink(t, "somepath", filepath.Join(dir, "etc"))
	symlink(t, "../../../../../../../../../../../../../etc", filepath.Join(dir, "etclink"))
	symlink(t, "/../../../../../../../../../../../../../etc/passwd", filepath.Join(dir, "passwd"))

	for _, test := range []struct {
		root, unsafe string
		expected     string
	}{
		// Make sure that expansion with a root of '/' proceeds in the expected fashion.
		{"/", filepath.Join(dir, "passwd"), "/etc/passwd"},
		{"/", filepath.Join(dir, "etclink"), "/etc"},
		{"/", filepath.Join(dir, "etc"), filepath.Join(dir, "somepath")},
		// Now test scoped expansion.
		{dir, "passwd", filepath.Join(dir, "somepath", "passwd")},
		{dir, "etclink", filepath.Join(dir, "somepath")},
		{dir, "etc", filepath.Join(dir, "somepath")},
		{dir, "etc/test", filepath.Join(dir, "somepath", "test")},
		{dir, "etc/test/..", filepath.Join(dir, "somepath")},
	} {
		got, err := SecureJoin(test.root, test.unsafe)
		if err != nil {
			t.Errorf("securejoin(%q, %q): unexpected error: %v", test.root, test.unsafe, err)
			continue
		}
		// This is only for OS X, where /etc is a symlink to /private/etc. In
		// principle, SecureJoin(/, pth) is the same as EvalSymlinks(pth) in
		// the case where the path exists.
		if test.root == "/" {
			if expected, err := filepath.EvalSymlinks(test.expected); err == nil {
				test.expected = expected
			}
		}
		if got != test.expected {
			t.Errorf("securejoin(%q, %q): expected %q, got %q", test.root, test.unsafe, test.expected, got)
			continue
		}
	}
}

// In a path without symlinks, SecureJoin is equivalent to Clean+Join.
func TestNoSymlink(t *testing.T) {
	dir, err := ioutil.TempDir("", "TestNoSymlink")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	for _, test := range []struct {
		root, unsafe string
	}{
		// TODO: Do we need to have some conditional FromSlash handling here?
		{dir, "somepath"},
		{dir, "even/more/path"},
		{dir, "/this/is/a/path"},
		{dir, "also/a/../path/././/with/some/./.././junk"},
		{dir, "yetanother/../path/././/with/some/./.././junk../../../../../../../../../../../../etc/passwd"},
		{dir, "/../../../../../../../../../../../../../../../../etc/passwd"},
		{dir, "../../../../../../../../../../../../../../../../somedir"},
		{dir, "../../../../../../../../../../../../../../../../"},
		{dir, "./../../.././././../../../../../../../../../../../../../../../../etc passwd"},
	} {
		expected := filepath.Join(test.root, filepath.Clean(string(filepath.Separator)+test.unsafe))
		got, err := SecureJoin(test.root, test.unsafe)
		if err != nil {
			t.Errorf("securejoin(%q, %q): unexpected error: %v", test.root, test.unsafe, err)
			continue
		}
		if got != expected {
			t.Errorf("securejoin(%q, %q): expected %q, got %q", test.root, test.unsafe, expected, got)
			continue
		}
	}
}

// Make sure that .. is **not** expanded lexically.
func TestNonLexical(t *testing.T) {
	dir, err := ioutil.TempDir("", "TestNonLexical")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	os.MkdirAll(filepath.Join(dir, "subdir"), 0755)
	os.MkdirAll(filepath.Join(dir, "cousinparent", "cousin"), 0755)
	symlink(t, "../cousinparent/cousin", filepath.Join(dir, "subdir", "link"))
	symlink(t, "/../cousinparent/cousin", filepath.Join(dir, "subdir", "link2"))
	symlink(t, "/../../../../../../../../../../../../../../../../cousinparent/cousin", filepath.Join(dir, "subdir", "link3"))

	for _, test := range []struct {
		root, unsafe string
		expected     string
	}{
		{dir, "subdir", filepath.Join(dir, "subdir")},
		{dir, "subdir/link/test", filepath.Join(dir, "cousinparent", "cousin", "test")},
		{dir, "subdir/link2/test", filepath.Join(dir, "cousinparent", "cousin", "test")},
		{dir, "subdir/link3/test", filepath.Join(dir, "cousinparent", "cousin", "test")},
		{dir, "subdir/../test", filepath.Join(dir, "test")},
		// This is the divergence from a simple filepath.Clean implementation.
		{dir, "subdir/link/../test", filepath.Join(dir, "cousinparent", "test")},
		{dir, "subdir/link2/../test", filepath.Join(dir, "cousinparent", "test")},
		{dir, "subdir/link3/../test", filepath.Join(dir, "cousinparent", "test")},
	} {
		got, err := SecureJoin(test.root, test.unsafe)
		if err != nil {
			t.Errorf("securejoin(%q, %q): unexpected error: %v", test.root, test.unsafe, err)
			continue
		}
		if got != test.expected {
			t.Errorf("securejoin(%q, %q): expected %q, got %q", test.root, test.unsafe, test.expected, got)
			continue
		}
	}
}

// Make sure that symlink loops result in errors.
func TestSymlinkLoop(t *testing.T) {
	dir, err := ioutil.TempDir("", "TestSymlinkLoop")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	os.MkdirAll(filepath.Join(dir, "subdir"), 0755)
	symlink(t, "../../../../../../../../../../../../../../../../path", filepath.Join(dir, "subdir", "link"))
	symlink(t, "/subdir/link", filepath.Join(dir, "path"))
	symlink(t, "/../../../../../../../../../../../../../../../../self", filepath.Join(dir, "self"))

	for _, test := range []struct {
		root, unsafe string
	}{
		{dir, "subdir/link"},
		{dir, "path"},
		{dir, "../../path"},
		{dir, "subdir/link/../.."},
		{dir, "../../../../../../../../../../../../../../../../subdir/link/../../../../../../../../../../../../../../../.."},
		{dir, "self"},
		{dir, "self/.."},
		{dir, "/../../../../../../../../../../../../../../../../self/.."},
		{dir, "/self/././.."},
	} {
		got, err := SecureJoin(test.root, test.unsafe)
		if err != ErrSymlinkLoop {
			t.Errorf("securejoin(%q, %q): expected ELOOP, got %v & %q", test.root, test.unsafe, err, got)
			continue
		}
	}
}

// Make sure that ENOTDIR is correctly handled.
func TestEnotdir(t *testing.T) {
	dir, err := ioutil.TempDir("", "TestEnotdir")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	os.MkdirAll(filepath.Join(dir, "subdir"), 0755)
	ioutil.WriteFile(filepath.Join(dir, "notdir"), []byte("I am not a directory!"), 0755)
	symlink(t, "/../../../notdir/somechild", filepath.Join(dir, "subdir", "link"))

	for _, test := range []struct {
		root, unsafe string
	}{
		{dir, "subdir/link"},
		{dir, "notdir"},
		{dir, "notdir/child"},
	} {
		_, err := SecureJoin(test.root, test.unsafe)
		if err != nil {
			t.Errorf("securejoin(%q, %q): unexpected error: %v", test.root, test.unsafe, err)
			continue
		}
	}
}

// Some silly tests to make sure that all error types are correctly handled.
func TestIsNotExist(t *testing.T) {
	for _, test := range []struct {
		err      error
		expected bool
	}{
		{&os.PathError{Op: "test1", Err: syscall.ENOENT}, true},
		{&os.LinkError{Op: "test1", Err: syscall.ENOENT}, true},
		{&os.SyscallError{Syscall: "test1", Err: syscall.ENOENT}, true},
		{&os.PathError{Op: "test2", Err: syscall.ENOTDIR}, true},
		{&os.LinkError{Op: "test2", Err: syscall.ENOTDIR}, true},
		{&os.SyscallError{Syscall: "test2", Err: syscall.ENOTDIR}, true},
		{&os.PathError{Op: "test3", Err: syscall.EACCES}, false},
		{&os.LinkError{Op: "test3", Err: syscall.EACCES}, false},
		{&os.SyscallError{Syscall: "test3", Err: syscall.EACCES}, false},
		{errors.New("not a proper error"), false},
	} {
		got := IsNotExist(test.err)
		if got != test.expected {
			t.Errorf("IsNotExist(%#v): expected %v, got %v", test.err, test.expected, got)
		}
	}
}

type mockVFS struct {
	lstat    func(path string) (os.FileInfo, error)
	readlink func(path string) (string, error)
}

func (m mockVFS) Lstat(path string) (os.FileInfo, error) { return m.lstat(path) }
func (m mockVFS) Readlink(path string) (string, error)   { return m.readlink(path) }

// Make sure that SecureJoinVFS actually does use the given VFS interface.
func TestSecureJoinVFS(t *testing.T) {
	dir, err := ioutil.TempDir("", "TestNonLexical")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	os.MkdirAll(filepath.Join(dir, "subdir"), 0755)
	os.MkdirAll(filepath.Join(dir, "cousinparent", "cousin"), 0755)
	symlink(t, "../cousinparent/cousin", filepath.Join(dir, "subdir", "link"))
	symlink(t, "/../cousinparent/cousin", filepath.Join(dir, "subdir", "link2"))
	symlink(t, "/../../../../../../../../../../../../../../../../cousinparent/cousin", filepath.Join(dir, "subdir", "link3"))

	for _, test := range []struct {
		root, unsafe string
		expected     string
	}{
		{dir, "subdir", filepath.Join(dir, "subdir")},
		{dir, "subdir/link/test", filepath.Join(dir, "cousinparent", "cousin", "test")},
		{dir, "subdir/link2/test", filepath.Join(dir, "cousinparent", "cousin", "test")},
		{dir, "subdir/link3/test", filepath.Join(dir, "cousinparent", "cousin", "test")},
		{dir, "subdir/../test", filepath.Join(dir, "test")},
		// This is the divergence from a simple filepath.Clean implementation.
		{dir, "subdir/link/../test", filepath.Join(dir, "cousinparent", "test")},
		{dir, "subdir/link2/../test", filepath.Join(dir, "cousinparent", "test")},
		{dir, "subdir/link3/../test", filepath.Join(dir, "cousinparent", "test")},
	} {
		var nLstat, nReadlink int
		mock := mockVFS{
			lstat:    func(path string) (os.FileInfo, error) { nLstat++; return os.Lstat(path) },
			readlink: func(path string) (string, error) { nReadlink++; return os.Readlink(path) },
		}

		got, err := SecureJoinVFS(test.root, test.unsafe, mock)
		if err != nil {
			t.Errorf("securejoin(%q, %q): unexpected error: %v", test.root, test.unsafe, err)
			continue
		}
		if got != test.expected {
			t.Errorf("securejoin(%q, %q): expected %q, got %q", test.root, test.unsafe, test.expected, got)
			continue
		}
		if nLstat == 0 && nReadlink == 0 {
			t.Errorf("securejoin(%q, %q): expected to use either lstat or readlink, neither were used", test.root, test.unsafe)
		}
	}
}

// Make sure that SecureJoinVFS actually does use the given VFS interface, and
// that errors are correctly propagated.
func TestSecureJoinVFSErrors(t *testing.T) {
	var (
		lstatErr    = errors.New("lstat error")
		readlinkErr = errors.New("readlink err")
	)

	// Set up directory.
	dir, err := ioutil.TempDir("", "TestSecureJoinVFSErrors")
	if err != nil {
		t.Fatal(err)
	}
	dir, err = filepath.EvalSymlinks(dir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir)

	// Make a link.
	symlink(t, "../../../../../../../../../../../../../../../../path", filepath.Join(dir, "link"))

	// Define some fake mock functions.
	lstatFailFn := func(path string) (os.FileInfo, error) { return nil, lstatErr }
	readlinkFailFn := func(path string) (string, error) { return "", readlinkErr }

	// Make sure that the set of {lstat, readlink} failures do propagate.
	for idx, test := range []struct {
		vfs      VFS
		expected []error
	}{
		{
			expected: []error{nil},
			vfs: mockVFS{
				lstat:    os.Lstat,
				readlink: os.Readlink,
			},
		},
		{
			expected: []error{lstatErr},
			vfs: mockVFS{
				lstat:    lstatFailFn,
				readlink: os.Readlink,
			},
		},
		{
			expected: []error{readlinkErr},
			vfs: mockVFS{
				lstat:    os.Lstat,
				readlink: readlinkFailFn,
			},
		},
		{
			expected: []error{lstatErr, readlinkErr},
			vfs: mockVFS{
				lstat:    lstatFailFn,
				readlink: readlinkFailFn,
			},
		},
	} {
		_, err := SecureJoinVFS(dir, "link", test.vfs)

		success := false
		for _, exp := range test.expected {
			if err == exp {
				success = true
			}
		}
		if !success {
			t.Errorf("SecureJoinVFS.mock%d: expected to get lstatError, got %v", idx, err)
		}
	}
}