-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsecurefilepath_test.go
380 lines (327 loc) · 10.6 KB
/
securefilepath_test.go
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
/*
* Copyright 2016 ClusterHQ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package securefilepath_test
import (
"fmt"
"io/ioutil"
"os"
"os/user"
"sort"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/ScatterHQ/go-securefilepath"
)
// RunningAsRoot returns true if it is running as a super user
func runningAsRoot() bool {
//are we running as root
usr, err := user.Current()
if err != nil {
fmt.Println("Failed to get current user with the following error:", err)
return false
}
uid, err := strconv.Atoi(usr.Uid)
if err != nil {
fmt.Println("Failed to get uid with the following error:", err)
return false
}
gid, err := strconv.Atoi(usr.Gid)
if err != nil {
fmt.Println("Failed to get gid with the following error:", err)
return false
}
return uid == 0 && gid == 0
}
type ByPath []securefilepath.SecureFilePath
func (s ByPath) Len() int {
return len(s)
}
func (s ByPath) Less(i, j int) bool {
return strings.Compare(s[i].Path(), s[j].Path()) == -1
}
func (s ByPath) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// TestNew verifies that New rejects any potentially ambiguously formed or
// non-canonical paths and accepts only canonical, absolute paths.
func TestNew(t *testing.T) {
filepath, err := securefilepath.New("non-absolute")
assert.NotEqual(t, err, nil, "Non-absolute path should produce an error.")
filepath, err = securefilepath.New("/absolute/../with/dots")
assert.NotEqual(t, err, nil, "Path with .. should produce error.")
filepath, err = securefilepath.New("//weird/absolute")
assert.NotEqual(t, err, nil, "Path with duplicate / should produce error.")
filepath, err = securefilepath.New("/superfluous/./directory/reference")
assert.NotEqual(t, err, nil, "Path with . segment should produce error.")
filepath, err = securefilepath.New("/valid/absolute/path")
assert.Equal(t, err, nil, "Clean absolute path should not produce error.")
assert.Equal(t, filepath.Path(), "/valid/absolute/path")
}
// TestParent verifies that SecureFilePath.Parent returns a path representing
// the parent path of the given path.
func TestParent(t *testing.T) {
root, err := securefilepath.New("/")
require.NoError(t, err)
a, err := root.Child("a")
require.NoError(t, err)
b, err := a.Child("b")
require.NoError(t, err)
c, err := b.Child("c")
require.NoError(t, err)
assert.Equal(t, b, c.Parent())
assert.Equal(t, a, b.Parent())
assert.Equal(t, root, a.Parent())
assert.Equal(t, root, root.Parent())
}
// TestChild verifies that SecureFilePath.Child allows access only to any paths
// which are children of the parent path (disregarding effects of symbolic
// links).
func TestChild(t *testing.T) {
filepath, err := securefilepath.New("/parent")
if err != nil {
t.Errorf("%s", err)
return
}
child, err := filepath.Child("/not-child")
assert.NotEqual(
t, err, nil,
fmt.Sprintf(
"Absolute path for child segment should produce error, not '%s'.",
child))
child, err = filepath.Child("multiple/segments")
assert.NotEqual(t, err, nil, "Child argument with multiple segments should produce an error.")
child, err = filepath.Child("")
assert.NotEqual(t, err, nil, "Child argument with no segments should produce an error.")
child, err = filepath.Child("..")
assert.NotEqual(t, err, nil, "Special parent segment should produce an error.")
child, err = filepath.Child("valid-child")
assert.Equal(t, err, nil, "Valid child should return a new SecureFilePath.")
anotherChild, err := securefilepath.New("/parent/valid-child")
if err != nil {
t.Errorf("%s", err)
return
}
assert.Equal(t, child, anotherChild)
// Nul is not allowed in paths so a child segment containing a nul
// cannot result in a valid path.
notChild, err := filepath.Child("hello\000world")
assert.Nil(t, notChild)
assert.Error(t, err)
}
// TestPath verifies that SecureFilePath.Path returns a string representing the path.
func TestPath(t *testing.T) {
for _, path := range []string{"/parent", "/parent/child/grandchild"} {
filepath, _ := securefilepath.New(path)
assert.Equal(t, filepath.Path(), path, "Wrong path returned.")
}
}
// touch creates a file at the given path.
func touch(p securefilepath.SecureFilePath) error {
f, err := os.Create(p.Path())
if err != nil {
return err
}
return f.Close()
}
// setupChildren creates and returns a directory with a directory ("dirchild")
// and a normal file ("filechild") as children.
func setupChildren() (securefilepath.SecureFilePath, securefilepath.SecureFilePath, securefilepath.SecureFilePath, error) {
path, _ := ioutil.TempDir("", "")
root, _ := securefilepath.New(path)
os.Mkdir(root.Path(), os.ModePerm)
dirChild, _ := root.Child("dirchild")
os.Mkdir(dirChild.Path(), os.ModePerm)
fileChild, _ := root.Child("filechild")
err := touch(fileChild)
if err != nil {
return nil, nil, nil, err
}
return root, dirChild, fileChild, nil
}
// TestChildrenEmpty verifies that SecureFilePath.Children returns an empty
// slice when called on a path representing a directory with no children.
func TestChildrenEmpty(t *testing.T) {
_, dirChild, _, err := setupChildren()
if err != nil {
t.Errorf("%s", err)
return
}
childChildren, err := dirChild.Children()
if err != nil {
t.Errorf("%s", err)
return
}
assert.Equal(t, []securefilepath.SecureFilePath{}, childChildren, "Should be empty.")
}
// TestChildren verifies that SecureFilePath.Children returns a slice of
// SecureFilePath with one element for each child of the path represented.
func TestChildren(t *testing.T) {
root, dirChild, fileChild, err := setupChildren()
if err != nil {
t.Errorf("%s", err)
return
}
actualChildren, err := root.Children()
if err != nil {
t.Errorf("%s", err)
return
}
expectedChildren := ByPath{dirChild, fileChild}
sort.Sort(expectedChildren)
actualSorted := ByPath(actualChildren)
sort.Sort(actualSorted)
assert.Equal(t, expectedChildren, actualSorted, "Wrong children returned.")
}
// TestChildrenOfFile verifies that SecureFilePath.Children returns an error when
// used on a path which refers to a regular file.
func TestChildrenOfFile(t *testing.T) {
_, _, fileChild, err := setupChildren()
if err != nil {
t.Errorf("%s", err)
return
}
_, err = fileChild.Children()
assert.Error(t, err, "Shouldn't be able to list file.")
}
// TestChildrenOfNonExistant verifies that SecureFilePath.Children returns an
// error when used on a path which does not refer to a file which exists.
func TestChildrenOfNonExtant(t *testing.T) {
nonexistent, _ := securefilepath.New("/nosuchpathIreallyhopereallyreally")
_, err := nonexistent.Children()
assert.Error(t, err, "Shouldn't be able to list non-existent directory.")
}
// TestChildrenWithoutPermission verifies that SecureFilePath.Children returns
// an error when used on a path to which we do not have read permission.
func TestChildrenWithoutPermission(t *testing.T) {
if runningAsRoot() {
t.Skip("Skipped because test running as root.")
}
root, _, _, err := setupChildren()
if err != nil {
t.Errorf("%s", err)
return
}
err = os.Chmod(root.Path(), 0)
if err != nil {
t.Errorf("%s", err)
return
}
defer os.Chmod(root.Path(), os.ModePerm)
_, err = root.Children()
assert.Error(t, err, "Shouldn't be able to list unreadable dir.")
}
// setupExists creates a scratch space in the filesytem for a test of Exists to
// play with.
func setupExists() (securefilepath.SecureFilePath, error) {
parent, err := ioutil.TempDir("", "testexists")
if err != nil {
return nil, err
}
parentDir, err := securefilepath.New(parent)
if err != nil {
return nil, err
}
return parentDir, nil
}
// TestExists verifies that SecureFilePath.Exists returns false if no such file
// exists at the filesystem path it represents.
func TestExistsFalse(t *testing.T) {
parent, err := setupExists()
if err != nil {
t.Errorf("%s", err)
return
}
filepath, err := parent.Child("nonexistent")
if err != nil {
t.Errorf("%s", err)
return
}
exists, err := filepath.Exists()
if err != nil {
t.Errorf("%s", err)
return
}
require.False(t, exists, "%s does not exist but Exists() says it does.", filepath.Path())
}
// TestExists verifies that SecureFilePath.Exists return true if a file does
// exist at the filesystem path it represents.
func TestExistsTrue(t *testing.T) {
parent, err := setupExists()
if err != nil {
t.Errorf("%s", err)
return
}
filepath, err := parent.Child("extant")
if err != nil {
t.Errorf("%s", err)
return
}
err = touch(filepath)
if err != nil {
t.Errorf("%s", err)
return
}
exists, err := filepath.Exists()
if err != nil {
t.Errorf("%s", err)
return
}
require.True(t, exists, "%s does exist but Exists() says it does not.", filepath.Path())
}
// TestExists verifies that SecureFilePath.Exists returns an error if the
// underlying filesystem returns an error when checking for existance.
func TestExistsError(t *testing.T) {
if runningAsRoot() {
t.Skip("Skipped because test running as root.")
}
parent, err := setupExists()
if err != nil {
t.Errorf("%s", err)
return
}
// An error encountered trying to determine whether a path has a
// corresponding file is propagated to the caller.
defer os.Chmod(parent.Path(), os.FileMode(0700))
os.Chmod(parent.Path(), os.FileMode(0))
filepath, err := parent.Child("nonexistent")
if err != nil {
t.Errorf("%s", err)
return
}
exists, err := filepath.Exists()
require.Error(t, err, "Exists() should have failed with a permission denied error, instead succeeded with %v", exists)
require.True(t, os.IsPermission(err), "Exists() should have failed with a permission denied error, instead failed with %v", err)
}
// TestBase verifies that SecureFilePath.Base returns the "base name" (the last
// path segment; hierarchically, the most inferior path segment) of the path as
// a string.
func TestBase(t *testing.T) {
for _, testcase := range []struct{ input, expected string }{
{"/", ""},
{"/parent", "parent"},
{"/parent/foo", "foo"},
} {
path, err := securefilepath.New(testcase.input)
if err != nil {
t.Errorf("Failed to construct SecureFilePath %v: %v", testcase.input, err)
}
if path.Base() != testcase.expected {
t.Errorf("%v != %v", path.Base(), testcase.expected)
}
}
}